`timescale 1ns / 1ps

module enco(clk, enable,quadA, quadB, out,buffer_addr);
input clk, quadA, quadB;
input enable;
input [10:0]buffer_addr;
output [7:0] out;

wire [7:0] vel_dir;
//Registros para implementar retardos, con la idea de syncronizar las seales
reg [2:0] quadA_delayed, quadB_delayed=0;
always @(posedge clk) quadA_delayed <= {quadA_delayed[1:0], quadA};
always @(posedge clk) quadB_delayed <= {quadB_delayed[1:0], quadB};

//Valores internos para habilitar el conteo, y determinar la direccin del mismo
wire count_enable = quadA_delayed[1] ^ quadA_delayed[2] ^ quadB_delayed[1] ^ quadB_delayed[2];
wire count_direction = quadA_delayed[1] ^ quadB_delayed[2];

//Registro para almacenar el contador
reg [7:0] count=0;	//Pendiente cambiar este, no sabemos que dato saldr al final
always @(posedge clk)
begin
  if(count_enable)
  begin
    if(count_direction) count<=count+1; else count<=count-1;
  end
end

//Falta definir como vamos a comunicar esta info, es ms facil como posicin

/*reg [1:0] pos_reg0=0;	//Registro temporal 1
reg [1:0] pos_reg1=0;	//Registro temporal
reg dir=0;	//Direccin, 1=adelante? 0=atras?
always @(posedge clk)	
begin
pos_reg0<={quadB, quadA};
pos_reg1<=pos_reg0;
	
	if(pos_reg1==pos_reg0) dir<=dir;
	else if(pos_reg0==1)
  begin
    if(pos_reg1<pos_reg0) dir<=0; else dir<=1;
  end
  else if(pos_reg1==1)
  begin
    if(pos_reg1<pos_reg0) dir<=0; else dir<=1;
  end
  else	
  begin
    if(pos_reg1<pos_reg0) dir<=1; else dir<=0;
  end
  
  
end*/
//Fue cambiado!
assign vel_dir={count[7:0]};

    // Dual-port RAM instatiation
    RAMB16_S9_S9 ba0(
            .DOA(out),         // Port A 8-bit Data Output
            .DOB(),     // Port B 8-bit Data Output
            .DOPA(),              // Port A 1-bit Parity Output
            .DOPB(),              // Port B 1-bit Parity Output
            .ADDRA(buffer_addr[10:0]),   // Port A 11-bit Address Input
            .ADDRB(1'b0),  // Port B 11-bit Address Input
            .CLKA(~clk),          // Port A Clock
            .CLKB(~clk),          // Port B Clock
            .DIA(),     // Port A 8-bit Data Input
            .DIB(vel_dir),    // Port B 8-bit Data Input
            .DIPA(1'b0),          // Port A 1-bit parity Input
            .DIPB(1'b0),          // Port-B 1-bit parity Input
            .ENA(1'b1),           // Port A RAM Enable Input
            .ENB(1'b1),           // Port B RAM Enable Input
            .SSRA(1'b0),          // Port A Synchronous Set/Reset Input
            .SSRB(1'b0),          // Port B Synchronous Set/Reset Input
            .WEA(1'b0),            // Port A Write Enable Input
            .WEB(enable) );          // Port B Write Enable Input 
				
endmodule
