`include	"defines.v"

// Stable simulation startup:
// RAM load completes before stimulus.
// Simulation terminates with explicit $finish.

module blk_ram16kx12(clk, wea, addra, dina, douta);
	input clk;
	input wea;
	input [14:0]addra;
	input [11:0]dina;
	output [11:0]douta;
`ifndef init_ram
	RAM U4 (
   .clka(clk),
   .wea(wea),
   .addra(addra),
   .dina (dina),
   .douta(douta));
`else
	reg clkS;
	reg weaS;
	reg [14:0] addraS;
	reg [11:0] dinaS;

	wire clkR;
	wire weaR;
	wire [14:0] addraR;
	wire [11:0] dinaR;

	reg simul;

	assign clkR 	= simul ? clkS 	: clk;
	assign addraR 	= simul ? addraS 	: addra;
	assign dinaR 	= simul ? dinaS 	: dina;
	assign weaR 	= simul ? weaS 	: wea;

	RAM U4 (
   .clka(clkR), 	// input clka
   .wea(weaR), 	// input [0 : 0] wea
   .addra(addraR),// input [11 : 0] addra
   .dina (dinaR), // input [11 : 0] dinai
   .douta(douta));// output [11 : 0] douta

	// usate per la simulazione
	reg [8*11-1:0] testfilename;   // "default.mem" = 11 caratteri
	reg [30*8:1]    str;
   integer fd, file, code, dummy;

	initial
		begin
		simul=1;
		testfilename = "default.mem";

		$display("BKram: code filename: <%s>", testfilename);

		file = $fopen(testfilename, "r");

		if (file == 0) begin
			$display("BKram: ERROR - cannot open file: <%s>", testfilename);
			$finish;
		end else begin
			$display("BKram: opened file: <%s>", testfilename);
		end

code = 1;
while (code) begin
	code = $fgets(str, file);

	if (code) begin
		dummy = $sscanf(str, "%o %o", addraS, dinaS);

		if (dummy == 2) begin
			weaS = 1'b1;
			#1 clkS = 1'b1;
			#1 clkS = 1'b0;
			weaS = 1'b0;
		end
	end
end
	/*	code=1;
      while (code)
		begin
         code = $fgets(str, file);
         dummy = $sscanf(str, "%o %o", addraS,dinaS);
			//$display("BKram[%o] <- %o", addraS, dinaS);
			//ram[i] = v;
			weaS = 1'b1;
			#1 clkS = 1'b1;
			#1 clkS = 1'b0;
			weaS = 1'b1;
			// rileggi per controllo
//			#10 clkS = 1'b1;
//			#10 clkS = 1'b0;
//			$display ("mem= %o", dinaS);
      end*/
	   $fclose(file);
		$display("BKram: done reading at %d", $time);
		simul=0;
    end
`endif
endmodule
