// Nevis12 ADC filter for radiation testing
// jb/2013/ v0.0
// The module sets bit "pipe_move_enable" if
// dataa  

module ADC_data_filter
(
	input [15:0] data,
	input [15:0] pedestal,
	input [15:0] window,
	input        clk,
	output       pipe_move_enable
);

//variables
reg [15:0]	data_r, res_a, res_ped, off_int;
wire			a_ge_ped, w_ge_int;
reg			a_ge_ped_reg;

reg [10:0]  wr_en_pipe;

//main body

compare	c1 ( .dataa ( data_r ), .datab ( pedestal ), .ageb ( a_ge_ped ));
compare	c2 ( .dataa ( window ), .datab ( off_int ),  .ageb ( w_ge_int ));

	always @ (posedge clk)
	begin

// delay 1
			data_r       <= data;
// delay 2
			res_a        <= data_r   - pedestal;
			res_ped      <= pedestal - data_r;
// delay 3 			
			a_ge_ped_reg <= a_ge_ped;
//	delay 4		
			if (a_ge_ped_reg) off_int <= res_a;
			else              off_int <= res_ped;
// delay 5
			if (w_ge_int) wr_en_pipe[0] <= 1'b0;
			else          wr_en_pipe[0] <= 1'b1;
//		
			wr_en_pipe[9:1]  <= wr_en_pipe[8:0];

	end

		assign pipe_move_enable = wr_en_pipe[3];	//to be adjusted
	
endmodule
