module analyser
	(
		input	wire			clock, frame, reset,
		input	wire	[15:0]	cfg_data,
		input	wire	[1:0]	uwt_flag,
		input	wire	[11:0]	uwt_data,
		output	wire			ana_good,
		output	wire	[11:0]	ana_data
	);

	reg				state_reg, state_next;
	reg		[3:0]	counter_reg, counter_next;
	reg		[11:0]	minimum_reg, minimum_next;
	reg				good_reg, good_next;
	reg		[11:0]	data_reg, data_next;

	always @(posedge clock)
	begin
		if (reset)
		begin
			state_reg <= 1'b0;
			counter_reg <= 4'd0;
			minimum_reg <= 12'd0;
			good_reg <= 1'b0;
			data_reg <= 12'd0;
		end
		else
		begin
			state_reg <= state_next;
			counter_reg <= counter_next;
			minimum_reg <= minimum_next;
			good_reg <= good_next;
			data_reg <= data_next;
		end
	end
	
	always @*
	begin
		state_next = state_reg;
		counter_next = counter_reg;
		minimum_next = minimum_reg;
		good_next = good_reg;
		data_next = data_reg;
		
		case (state_reg)
			0:
			begin
				if (frame)
				begin
					// minimum
					if (uwt_flag[0])
					begin
						counter_next = cfg_data[3:0];
						minimum_next = uwt_data;
					end
					// counter is not zero
					else if (|counter_reg)
					begin
						counter_next = counter_reg - 4'd1;
					end
					// maximum
					else if ((uwt_flag[1]) & (uwt_data > minimum_reg))
					begin
						data_next = uwt_data - minimum_reg;
						state_next = 1'b1;
					end
                end
 			end
			
			1:
			begin
				good_next = (data_reg >= cfg_data[15:4]);
				state_next = 1'b0;
 			end

		endcase
	end

	assign ana_good = good_reg;
	assign ana_data = data_reg;

endmodule
