module EM2_32bit
#(
	parameter ENDMEMBER			=21,
	parameter WIDTH_MEMORY		=32,
	parameter NUMBER_OF_PIXEL	=350*350,
	parameter LOG_DIM				=13
)
(
	input clk,rst,
	input req,
	input [WIDTH_MEMORY-1:0] memory_data,												//Para la memoria
	
	output [clog2(NUMBER_OF_PIXEL*(ENDMEMBER-1)-1)-1:0] 	address_memory, 	//Para la memoria
	output [(clog2(NUMBER_OF_PIXEL-1))*ENDMEMBER-1:0]	position_endmember, //Salida
	output ack
);
//DMA
wire req_DMA,ack_DMA;
wire [clog2(NUMBER_OF_PIXEL-1)-1:0] id_pixel_DMA;
wire [(ENDMEMBER-1)*WIDTH_MEMORY-1:0] pixel_memory;
//N-FINDR
wire ack_NFNDR,new_pixel,init_NFINDR;
//Control
wire [16:0] position;
wire [(ENDMEMBER-1)*WIDTH_MEMORY-1:0] pixel;

NFINDR2_32bit #(.WIDTH(WIDTH_MEMORY),.ENDMEMBER(ENDMEMBER),.PIXEL_NUMBER(NUMBER_OF_PIXEL),.LOG_DIM(LOG_DIM)) stage_N_FINDR
(
	.clk(clk),
	.rst(rst),
	.init(init_NFINDR),
	.new_data(new_pixel),
	.pixel(pixel),
	.position(position),
	.position_endmember(position_endmember),
	.ack_pixel(ack_NFNDR)
);

control #(.top(NUMBER_OF_PIXEL),.endmember(ENDMEMBER),.WIDTH(WIDTH_MEMORY)) stage_control
(
	.clk(clk),
	.rst(rst),
	.req(req),
	.ack_mem(ack_DMA),
	.ack_NFNDR(ack_NFNDR),
	.data(pixel_memory),
	.req_mem(req_DMA),
	.new_pixel(new_pixel),
	.init_NFINDR(init_NFINDR),
	.position(position),
	.memory_position(id_pixel_DMA),
	.pixel(pixel),
	.ack(ack)
);

DMA #(.ENDMEMBER(ENDMEMBER),.WIDTH_MEMORY(WIDTH_MEMORY),.NUMBER_OF_PIXEL(NUMBER_OF_PIXEL)) stage_DMA
(
	.clk(clk),
	.rst(rst),
	.req(req_DMA),
	.ack(ack_DMA),
	.id_pixel(id_pixel_DMA),
	.address(address_memory),
	.pixel(pixel_memory),
	.memory_data(memory_data)
);

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

endmodule
