#include <io.h>
#include <system.h>
#include <stdio.h>

#include <sys/alt_irq.h> // the irq functions
#include <alt_types.h>
#include <keyboard_ctrl.h>

#define IOWR_LED_DATA(base, offset, data) \
  IOWR_16DIRECT(base, (offset) * 2, data) 
#define IORD_LED_DATA(base, offset) \
  IORD_16DIRECT(base, (offset) * 2)
#define IOWR_LED_SPEED(base, data) \
  IOWR_16DIRECT(base + 32, 0, data)

KB_CODE_TYPE decode_mode;
alt_u8 key = 0;

static void irqhandler (void * context, alt_u32 id)
{
    printf ("interrupt occurred\n");
    IOWR_16DIRECT(DE2_PS2_INST_IRQ, 0, 0); // reset request

    //unsigned char code;
    //alt_u8 code;
    //while (!IORD_8DIRECT(DE2_PS2_INST_BASE, 0));/* Poll the status */
    //code = IORD_8DIRECT(DE2_PS2_INST_BASE, 4);

    //printf("%x ",code);
    //int i;
    //for(i=0;i<1000000;i++){}
    read_make_code (&decode_mode, &key);
    printf("code is %c \n",key);
}

/*
static void irqprint(){
    IOWR_16DIRECT(DE2_PS2_INST_IRQ, 0, 0);
    unsigned char code;
    code = IORD_8DIRECT(DE2_PS2_INST_BASE, 4);

    printf("%x ",code);
    printf ("interrupt occurred\n");
}
*/

int main()
{
  //int i;
  printf("Hello Michael\n");
  
  alt_irq_register( DE2_PS2_INST_IRQ, NULL,( void*)irqhandler ); // register the irq
  //alt_irq_register( DE2_PS2_INST_IRQ, NULL,( void*)irqprint );
  
  while(1){  
  
  }
  /* Get received byte */

  printf("Goodbye!\n");
    
  return 0;
}
