`timescale 1ns / 1ps

// VGA Pong v1.0     Chris Fallin <cfallin@nd.edu>

module kbd(clk, reset,
				ps2_clk, ps2_data,
				paddle1_down, paddle1_up, paddle2_down, paddle2_up);
	input clk;
	input reset;
	input ps2_clk;
	input ps2_data;
	output paddle1_down;
	output paddle1_up;
	output paddle2_down;
	output paddle2_up;
	 
	wire ps2_clk;
	wire ps2_data;
	
	reg paddle1_down;
	reg paddle1_up;
	reg paddle2_down;
	reg paddle2_up;
	initial paddle1_down = 0;
	initial paddle1_up = 0;
	initial paddle2_down = 0;
	initial paddle2_up = 0;
	
	reg [10:0] shiftreg;
	reg [3:0] bitcount;
	initial bitcount = 0;
	initial shiftreg = 0;
	
	wire [7:0] kbd_data;
	assign kbd_data = shiftreg[8:1];
	
	reg keyup_prefix;
	initial keyup_prefix = 0;

  reg byte_complete;
  initial byte_complete = 0;

  reg last_ps2_clk;
	initial last_ps2_clk = 1;

	always @(posedge clk or posedge reset) begin
		if(reset) begin
			shiftreg <= 0;
			bitcount <= 0;
			keyup_prefix <= 0;
			byte_complete <= 0;
			paddle1_up <= 0;
			paddle1_down <= 0;
			paddle2_up <= 0;
			paddle2_down <= 0;
			last_ps2_clk <= 1;
		end
		else begin

      last_ps2_clk <= ps2_clk;
      if(last_ps2_clk == 1 && ps2_clk == 0) begin
			  shiftreg <= (shiftreg >> 1) | (ps2_data << 10);
        if(bitcount == 10) byte_complete <= 1;
        if(bitcount == 11)
          bitcount <= 1;
        else
          bitcount <= bitcount + 1;
      end


      if(byte_complete) begin
        byte_complete <= 0;
			  
        // process keycode
				if(kbd_data == 8'hF0)
					keyup_prefix <= 1;
				else begin
					keyup_prefix <= 0;
					if(kbd_data == 8'h1D) // W: paddle 1 up
						paddle1_up <= ~keyup_prefix;
					if(kbd_data == 8'h1B) // S: paddle 1 down
            paddle1_down <= ~keyup_prefix;
					if(kbd_data == 8'h44) // O: paddle 2 up
						paddle2_up <= ~keyup_prefix;
					if(kbd_data == 8'h4B) // L: paddle 2 down
						paddle2_down <= ~keyup_prefix;	
				end

			end // byte_complete

		end // posedge clk

	end

endmodule
