/**
 * Interrupts used to read buttons and increment / decrement the counter on the display.
*/

#include <main.h>

/**
 * Set the length of the list to loop up till.
*/
#define LIST_LEN 10
unsigned int SSD_Chars[] = {0x40, 0x79, 0x24, 0x30, 0x19, 0x12, 0x02, 0x78, 0x00, 0x10, 0x08, 0x03, 0x46, 0x21, 0x06, 0x0e};

unsigned int count = 0;
unsigned int list_index = 0;
unsigned int dir;

#INT_RTCC
void RTCC_isr(void) {
   count++;
   
   if ((count > (31 * 1)) & (dir != STOP)) { // 31 interrupts corresponds to ~1 second on the PIC 
      if (dir == UP) {list_index++;}
      else {list_index--;}
      if ((list_index > LIST_LEN) | (list_index < 0))
      {
      list_index = 0;
      }
      count = 0;
      }
   else {
      if (input(button_1) == 1) {
         dir = UP;
      }
      else if (input(button_2) == 1) {
         dir = DOWN;
      }
      else {
         dir = STOP;
      }
      ssd_update(dir);
   }
   clear_interrupt(int_rtcc);
}

void main()
{
   setup_timer_0(RTCC_INTERNAL | RTCC_DIV_256 | RTCC_8_BIT);
   /**
    * Enable the use of interrupts so the execution
    * of the program is non-blocking.
   */
   enable_interrupts(INT_RTCC);
   enable_interrupts(GLOBAL);

   while (TRUE)
   {
   }
}

void ssd_update(unsigned int direction)
{
   switch (direction)
   {
   case STOP:
      output_b(0x7f); // "Turn off" the SSD
      break;
   case UP: // If button one is pressed, display the character
      output_b(SSD_CHARS[list_index]);
      break;
   case DOWN: // If button two is pressed, display the character
      output_b(SSD_CHARS[list_index]);
      break;
   default:
      break;
   }
}