module endmembers_reg
#(
	parameter WIDTH=16,
	parameter ENDMEMBER=21
)
(
	input 												clk,rst,
	input		[(ENDMEMBER-1)*WIDTH-1:0]			fila_de_prueba, /////////////endmember -2
	input													move,
	input 												save,
	output	[ENDMEMBER*ENDMEMBER*WIDTH-1:0]	matrix,
	output	[4:0]				id
);

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

//Declaración de señales
reg [ENDMEMBER*(ENDMEMBER-1)*WIDTH-1:0] fila_reg,fila_next;
reg [4:0] i_reg,i_next;
//Registro de filas
genvar i;
generate
for (i=0;i<=ENDMEMBER-1;i=i+1) begin :generate_fila
	always@(posedge rst, posedge clk)
	if (rst)
		fila_reg[(ENDMEMBER-1)*WIDTH*(i+1)-1:(ENDMEMBER-1)*WIDTH*(i)] <= 3'b000;
	else
		fila_reg[(ENDMEMBER-1)*WIDTH*(i+1)-1:(ENDMEMBER-1)*WIDTH*(i)] <= fila_next[(ENDMEMBER-1)*WIDTH*(i+1)-1:(ENDMEMBER-1)*WIDTH*(i)];
	end
endgenerate

generate
for (i=1;i<=ENDMEMBER-1;i=i+1) begin :generate_fila_next
	always@(*)
	begin
	if (move)
		fila_next[(ENDMEMBER-1)*WIDTH*(i+1)-1:(ENDMEMBER-1)*WIDTH*(i)]= fila_reg[(ENDMEMBER-1)*WIDTH*i-1:(ENDMEMBER-1)*WIDTH*(i-1)];
	else
		fila_next[(ENDMEMBER-1)*WIDTH*(i+1)-1:(ENDMEMBER-1)*WIDTH*(i)]=fila_reg[(ENDMEMBER-1)*WIDTH*(i+1)-1:(ENDMEMBER-1)*WIDTH*(i)];
	end
end
endgenerate

always@(*)
begin
if	(save)
begin
	fila_next[(ENDMEMBER-1)*WIDTH-1:0]=fila_de_prueba;
end
else 
begin
	if (move)
	begin
		fila_next[(ENDMEMBER-1)*WIDTH-1:0]=fila_reg[(ENDMEMBER-1)*WIDTH*ENDMEMBER-1:(ENDMEMBER-1)*WIDTH*(ENDMEMBER-1)];
	end
	else
	begin
		fila_next[(ENDMEMBER-1)*WIDTH-1:0]=fila_reg[(ENDMEMBER-1)*WIDTH-1:0];
	end
end
end

generate
for (i=1;i<=ENDMEMBER-1;i=i+1) begin :matrix_generate
	assign matrix[ENDMEMBER*WIDTH*(i+1)-1:ENDMEMBER*WIDTH*i]={16'h0001,fila_reg[(ENDMEMBER-1)*WIDTH*(i+1)-1:(ENDMEMBER-1)*WIDTH*(i)]};
end
endgenerate

assign matrix[ENDMEMBER*WIDTH-1:0]={16'h0001,fila_de_prueba};

always@(posedge rst,posedge clk)
begin
if (rst)
	i_reg=5'h00;
else
	i_reg=i_next;
end

always@(*)
begin
i_next=i_reg;
if (move)
begin
	if (i_reg==ENDMEMBER-1)
	begin
		i_next=5'h00;
	end
	else
	begin
		i_next=i_reg+1'b1;
	end
end
else
begin
	i_next=i_reg;
end
end

assign id = i_reg;

endmodule
