// This is the user file inclued in parse_tb.v
// You have access to clk, rst, hlt as well as all output states and input variables

integer file, count, outfile,result;
reg [7:0] data_in [0:65535];
reg [7:0] data_out [0:65535];
reg [15:0] data_in_address;
reg [15:0] data_out_address;

reg [7:0] dataout;

initial begin
result = 0;
data_in_address = 0;
data_out_address = 0;
file = $fopen("text.txt","r");
outfile = $fopen("parse.out","w");
for (count = 0; count < 65536;count = count+1) begin 
    data_in[count] = $fgetc(file);
    data_out[count] <= 0;
end

end
assign valid = 1;
reg next_data_r;

always @(posedge clk) result = result + 1;

always @(posedge clk) begin
if (ready == 0 || rst == 1) begin  
count <= 0;
next_data_r <= 0; 
data_in_address <= 0;
data_out_address <= 0;
dataout <= 0;
end
else if (read_data == 1 && next_data == 0) begin
     data_in_address <= data_in_address + 1;
     if (write_data == 1) begin 
          data_out[data_out_address] <= data_in[data_in_address];
          $fwrite(outfile,"%c",data_in[data_in_address]);
          data_out_address <= data_out_address + 1;
     end
end
else if (next_data == 1 && next_data_r == 0 && read_data == 0) begin
   data_out[data_out_address] <= 8'ha;
   $fwrite(outfile,"%c",8'h0a);
   data_out_address <= data_out_address + 1;
end
else if (next_data == 1 && read_data == 1) data_in_address <= data_in_address + 1;

next_data_r <= next_data;
if (data_out_address > 1)
dataout <= data_out[data_out_address-1];

//if (data_in_address > 65530) begin 
if (data_in_address > 2000) begin 
   $fclose(outfile);
   $finish();
end

end



assign din7 = data_in[data_in_address][7];
assign din6 = data_in[data_in_address][6];
assign din5 = data_in[data_in_address][5];
assign din4 = data_in[data_in_address][4];
assign din3 = data_in[data_in_address][3];
assign din2 = data_in[data_in_address][2];
assign din1 = data_in[data_in_address][1];
assign din0 = data_in[data_in_address][0];
assign next_wrap_around = next_data;
