(--    
      WB (Write Back) stage of MIPS pipeline
      'WB.balsa'
--)

import [type]

procedure WB (input WBCtrl:WB;
                         input MEMRd:Rd;
                         input MEMRes :word;
                         output RegWrite: RegWrite;
                         output CP0W1: CP0Write;
                         output FMEMRes:word) 
is local
     variable WBCtrl_R : WB
     variable MEMRes_R: word
     variable Rd_R: Rd
     variable RegWrite_R: RegWrite
     channel RegWrite1: RegWrite
begin
  loop
     select WBCtrl then WBCtrl_R := WBCtrl end;

     if #(WBCtrl_R.wNe)[1] then MEMRd -> Rd_R 
                           else Rd_R := 12 end ||
     MEMRes -> MEMRes_R;


     if (#(WBCtrl_R.wNe)[1] and ((WBCtrl_R as 3 bits) /= 2)) then 
           RegWrite1 <-{((not #(WBCtrl_R.wNe)[0]) as rNw), Rd_R, MEMRes_R} ||
           FMEMRes <- MEMRes_R
     end ||

     if not (WBCtrl_R.cNp as bit) then 
       if #(WBCtrl_R.wNe)[0] then 
            CP0W1 <- {w, 14, MEMRes_R} 
       else 
            CP0W1 <- {(#(WBCtrl_R.wNe)[1] as rNw), Rd_R, MEMRes_R}
       end
     end
  end ||
  loop
     RegWrite1 -> RegWrite_R ;
     RegWrite <- RegWrite_R
  end
end
