module comparador
#(
	parameter WIDTH=16,
	parameter NUMBER=21
)
(
	input									clk,rst,
	input		[WIDTH-1:0]				data,
	input		[WIDTH-1:0]				actual,
	input									new_data,
	input									rst_mayor,
	input		[4:0]	id_in,
	output 								ack_data,
	output								change,
	output	[WIDTH-1:0]				mayor,
	output	[4:0]						id_out
);

function integer clog2;
input integer value;
begin 
value = value-1;
for (clog2=0; value>0; clog2=clog2+1)
value = value>>1;
end 
endfunction

reg [WIDTH-1:0] mayor_reg,mayor_next;
reg [4:0] i_reg,i_next;
reg change_reg,change_next;
reg en_mayor;
reg ack_reg;
wire ack_next;

always@(posedge rst,posedge clk)
begin
	if (rst)
		begin
		mayor_reg  <= 3'b000;
		i_reg		  <= 3'b000;
		change_reg <= 1'b0;
		ack_reg	  <= 1'b0;
		end
	else
		begin
		mayor_reg  <= mayor_next;
		i_reg		  <= i_next;
		change_reg <= change_next;
		ack_reg	  <= ack_next;
		end
end

always@(*)
begin
if (change)
	begin
	if (mayor_reg<data)
		en_mayor = 1'b1;
	else
		en_mayor =1'b0;
	end
else
	begin
	if (actual < data)
		en_mayor = 1'b1;
	else
		en_mayor =1'b0;
	end
end

always@(*)
begin
	if (rst_mayor)
		begin
			mayor_next  <= 3'b000;
			i_next		<= 3'b000;
			change_next <= 1'b0;
		end
	else if (en_mayor & new_data)
		begin
			mayor_next 	<= data;
			i_next		<= id_in;
			change_next <= 1'b1;
		end
	else
		begin
			mayor_next 	<= mayor_reg;
			i_next		<= i_reg;
			change_next <= change_reg;
		end
end

assign ack_next = new_data; 
assign change = change_reg;
assign id_out=i_reg;
assign mayor = mayor_reg;
assign ack_data=ack_reg;

endmodule
