`timescale 1ns / 500ps

`include "src/rmii/rmii_transmit_controller.v"

module rmii_transmit_controller_test;

	// Inputs
	reg clk;
	reg rst;
	reg clear;
	reg [7:0] data_in;
	reg wrt;

	// Outputs
	wire not_full;
	wire TXEN;
	wire [1:0] TXD;

	// Instantiate the Unit Under Test (UUT)
	rmii_transmit_controller uut (
		.clk(clk), 
		.rst(rst), 
		.clear(clear), 
		.data_in(data_in), 
		.wrt(wrt), 
		.not_full(not_full), 
		.TXEN(TXEN), 
		.TXD(TXD),
		.busy()
	);

	always #10 clk = ~clk;

	integer ifile = 0, ofile = 0;
	reg run;
	reg read_input;
	integer c;

	always @(posedge clk)
	begin
		if (read_input)
		begin
			if (not_full)
			begin
				c = $fgetc(ifile);
				if (c != -1)
				begin
					data_in <= c[7:0];
					wrt <= 1;
				end
				else
				begin
					read_input <= 0;
					wrt <= 0;
				end
			end
		end
	end
	
	integer wrt_cntr;
	reg [7:0] deser;
	always @(posedge clk)
	begin
		if (TXEN && run)
		begin
			deser = {TXD, deser[7:2]};
			wrt_cntr = wrt_cntr + 1;
			if ((wrt_cntr & 32'b11) == 0)
			begin
				$fwrite(ofile, "%c", deser);
			end
		end
	end

	initial begin
		// Initialize Inputs
		clk <= 0;
		rst <= 1;
		clear <= 0;
		data_in <= 0;
		wrt <= 0;

		run <= 0;
		c = 0;
		wrt_cntr = 0;
		deser = 0;
		wrt <= 0;
		read_input <= 0;

		// Wait 20 ns for global reset to finish
		#20;
		rst <= 0;
        
		// Add stimulus here
		
		// open file holding the test input
		ifile = $fopen("src/sim/lorem_ipsum.txt", "r");
		ofile = $fopen("src/sim/rmii_TXD.txt", "w");
		if ((ifile == 0) || (ofile == 0))
		begin
			$display("Error on opening at least one of the files!\n");
			$finish;
		end
		
		@(posedge clk);
		@(posedge clk);
		
		// start simulation
		run <= 1;
		read_input <= 1;
		
		@(posedge clk);

		// wait for the deassertion of run
		@(TXEN == 1);
		@(TXEN == 0);
		run <= 0;
		
		@(posedge clk);
		@(posedge clk);

		$fclose(ifile);
		$fclose(ofile);
		$finish;
	end
      
endmodule

