//
// Bunch crossing signal generation
//
// v1.0 jb/march/2019
//
//
//***************************************************************************
//
//  BC control register definition:
//
//  BC_cntrl    [0] BCRST enable
//  BC_cntrl [13:1] BCRST period
//  BC_cntrl[15:14] reserved
//
//***************************************************************************
//

module BC_control
    (  
          //module state machine inputs
          input clk,
          input rst,
          input op_start,
          input wire[15:0] BC_cntrl,
		  
          //Bunch crossing signal 
          output reg BCRST
    );
		


//variables			
reg        op_starts, op_start_reg, rst_reg, rst_flg; 
reg [12:0] BCRST_period, BCRST_cnt;

//main body
always @(posedge clk)	
 begin	
//operation starts
        op_start_reg <= op_start;
        op_starts    <= ~op_start_reg & op_start;
//reset flag
        rst_reg <= rst;
        rst_flg <= ~rst_reg & rst;
 end
 
 
// 
//Bunch crossing signal runs continuosly 
//
always @(posedge clk or posedge rst_flg)	
begin	
 if (rst_flg)        BCRST_period  <= 13'b0000000000000; 
 else if (op_starts) BCRST_period  <= BC_cntrl [13:1];
end


//BCRST counter 
always @(posedge clk )
begin
  if      (op_starts)          BCRST_cnt <= 13'h007;
  else if (BCRST_cnt==13'h000) BCRST_cnt <= BCRST_period;  
  else if (BC_cntrl[0])        BCRST_cnt <= BCRST_cnt - 13'b0000000000001;
end

//BCRST
always @(posedge clk)
begin
 BCRST <= BC_cntrl[0] & (BCRST_cnt==13'b0000000000000);
end 
 
endmodule				