//Deinterleaver for UMTS "300 x 2"
//Created by: Warrior Group
//
module second_deinter (clk, data, out_data, next_en, reset);

//Input and Output declarations
input clk , data, reset ;
output out_data ;
output next_en ;

//Deinterleaver Arrays and registers
reg [299:0] tmp_even,tmp_odd ;//Deinterleaver Array
reg tmp_out_fin ;//Deinterleaver seria output buffer
reg [9:0]count ; //Row counter
reg busy ; //Pipelining tmp register for next_en output
reg sh ; //Memory shifter for parallel to serial process

integer i,j; //Used in Parallel to serial Process

//Serial to Parallel Converting and Deinterleaver Memory writing
always @ ( posedge clk )
begin
  if (!reset)//reset all vectors as follow
    begin
      count = 10'b0 ;
      busy = 1'b0 ;
      i = -1 ;
      j = -1 ;
      sh = 1'b1 ;
    end
//Writing in the Deinterleaver Memory column by column
  else
    if(!busy)
    begin
      count = count + 10'd1 ;
//Writing in even Array
      if (count < 10'd301)
          tmp_even = {data, tmp_even[299:1]};
//Writing in odd Array
      else if (count < 10'd601)
          tmp_odd = {data, tmp_odd[299:1]};
    end
//Check if the 600 locations of Array full or not     
    if (count == 10'd601)
      busy = 1'b1 ;//if they are busy 
//Check if Interleaver busy about sending data or not     
    if (busy)
      begin
        sh = sh + 1'b1 ;
        count = 10'b0 ;//reset Row counter
//data parallel to serial process
        if(!sh)
          begin
            i = i + 1 ;
            if (i < 301)
              tmp_out_fin = tmp_even[i] ;
          end
        else if(sh)
          begin
            j = j + 1 ;
            if (j < 301)
              tmp_out_fin = tmp_odd[j] ;
            else 
              busy = 1'b0 ; //Deinterleaver now is not busy
              i = -1 ; j = -1 ;//reset parallel to serial counter
          end
     end
end
//Dinterleaver reading 
assign out_data = tmp_out_fin ;
//This pin "next_en" tell the previous units that the deinterleaver is busy
//And it tell the next units that the deinterleaver is sending its data now
assign next_en = busy ;
endmodule
