#include <hidef.h> /* for EnableInterrupts macro */
#include <stdio.h>
#include <stdlib.h>
#include "derivative.h" /* include peripheral declarations */
#include "demo9S08QG8.h" /*include demo board declarations */
#include "serial.h"

   
state_type state = SLEEP; // Start up in this mode
unsigned char ScrollSpeed = 3; // scroll speed (1 = slowest, 5 = fastest)
unsigned char MsgChar; // currently selected character for user-customizable scrolling text message

unsigned char scroll_flag = 0; // if set, scroll the display, else remain static
unsigned char state_change_flag = 1; // if set, we need to change state/mode
 
unsigned char fb[MSG_LENGTH]; // frame buffer
unsigned char shiftreg[NUMBER_OF_74595];
unsigned char row_count = 0; // current row of message buffer that we'll copy to fb (for scrolling)
 
void main(void) 
{
  signed char i;
  unsigned char str_tmp[CHAR_LENGTH + 1]; // buffer for user-generated text message + null
  
  disable_scrolling();
  MCU_init(); // call Device Initialization from MCUInit.c
  
  memset(fb, 0x1F, NUM_ROWS);  // turn on all LEDs in the entire matrix (for testing)
  delay_ms(250);
  
  clear_matrix();     
  memset(str_tmp, 0x00, CHAR_LENGTH + 1); 

  //(void)printf ("\n\n\rLet's get this party started!\n\n\r");
  
  // sorry for this spaghetti-like state machine - i'm just a lowly electrical engineer :)
  while(1)
  {  
    if (state_change_flag) // if there has been a change in state
  	{
  	  state_change_flag = 0;
MAINLOOP:  	  	  
  		switch (state) // ...then enter the new state
    	{
    	  case SCROLL:
    	    if (str_tmp[0] == '\0') // if no user-programmed message exists...
    	      LedStr((char*)str_default); // ...scroll the default programmed text message
    	    else // otherwise display the user-programmed message
    	    {
    	      if (strcmp(str_tmp, MAGIC_PASSWORD) == 0)
    	        LedStr((char*)str_easteregg); // ssshhh!
    	      else
    	        LedStr(str_tmp);
    	    }
    	      	    
    	    // set scroll speed based on user selection
    	    switch (ScrollSpeed)
    	    {
    	      case 1:
    	        MTIMMOD = 24; // 205ms
    	        break;
    	      case 2:
    	        MTIMMOD = 17; // 147ms
    	        break;
    	      case 4:
    	        MTIMMOD = 6; // 57ms
    	        break;
    	      case 5:
    	        MTIMMOD = 2; // 24ms
    	        break;
    	      case 3:
    	      default:
    	        MTIMMOD = 10; // 90ms
    	        break;
    	    }
    	    
    	    enable_scrolling();    	    
MOREWAIT:
    	    while (SW1 || SW2) asm ("wait"); // wait until no more buttons are pressed
          while (!SW1) asm ("wait");       // just hang out here until it's time to change modes
    	    while (SW1)         // wait until button is released
    	    {
    	      asm ("wait");
    	      if (SW1 && SW2) // if both buttons pressed, don't do anything
    	        goto MOREWAIT;
    	    }
    	    MTIMMOD = 10; // set scroll speed back to default (90ms)
    	    change_state();
    	    break;
    	  case SET_MSG:
    	    LedStr("TEXT");
     	    enable_scrolling();
MOREWAIT2:
    	    while (SW1 || SW2) asm ("wait");   // wait until no more buttons are pressed
     	    while (!SW1 && !SW2) asm ("wait"); // wait until a button is pressed
     	    if (SW1)
     	    {
     	      while (SW1) // wait until button is released
     	      { 
     	        asm ("wait");
     	        if (SW1 && SW2) // if both buttons are pressed, don't do anything
     	          goto MOREWAIT2;
     	      }
     	      change_state();
            break;
     	    }
     	    else if (SW2)
     	    {
     	      while (SW2) // wait until button is released
     	      {
     	        asm ("wait");
     	        if (SW1 && SW2) // if both buttons are pressed, don't do anything
     	          goto MOREWAIT2;
     	      }
     	      disable_scrolling();
     	      i = 0; // pointer into array
     	      MsgChar = 'A'; // default character
     	      while (1)
     	      {
     	        asm ("wait")
     	        if (SW1)
     	        {
     	          while (SW1) // wait until button is released
     	          { 
     	            asm ("wait");
     	            if (SW1 && SW2) // if both buttons pressed...
     	            {
     	              while (SW1 || SW2) asm ("wait");   // wait until no more buttons are pressed
     	              switch (MsgChar)
     	              {
     	                case '}': // arrow selected, erase previous character 
     	                  i--;
     	                  if (i < 0) i = 0;     	                  
     	                  goto DISPTEXT;
     	                  break;
     	                case '~': // checkered flag selected, end mode and return to scrolling message 
     	                  str_tmp[i] = '\0'; // remove end-of-message character     	                  
     	                  state = SCROLL;
     	                  goto MAINLOOP; // get out of this mess of nested loops     	                
     	                  break;
     	                default: // add selected character to scrolling message array/fb
     	                  if (i < CHAR_LENGTH) // if we haven't exceeded the maximum message size...
     	                    i++; 
     	                  else // force end-of-message character to notify user that they can't enter any more text
     	       	            MsgChar = '~'; 
                        goto DISPTEXT;
                        break;
     	              }
     	            }
     	          }
                MsgChar++; // increment character
                if (MsgChar > 0x7E) MsgChar = 0x20; 
     	        }
     	        else if (SW2)
     	        {
     	          while (SW2) // wait until button is released
     	          {
     	            asm ("wait");
     	            if (SW1 && SW2) // if both buttons pressed...
     	            {
     	              while (SW1 || SW2) asm ("wait");   // wait until no more buttons are pressed
     	              switch (MsgChar)
     	              {
     	                case '}': // arrow selected, erase previous character 
     	                  i--;
     	                  if (i < 0) i = 0;
     	                  goto DISPTEXT;
     	                  break;
     	                case '~': // checkered flag selected, end mode and return to scrolling message 
     	                  str_tmp[i] = '\0'; // remove end-of-message character
     	                  state = SCROLL;
     	                  goto MAINLOOP; // get out of this mess of nested loops     	                
     	                  break;
     	                default: // add selected character to scrolling message array/fb
     	                  if (i < CHAR_LENGTH) // if we haven't exceeded the maximum message size...
     	                    i++;
     	                  else // force end-of-message character to notify user that they can't enter any more text
     	                    MsgChar = '~'; 
     	                  goto DISPTEXT;                              	                  
                        break;
     	              }
     	            }
     	          }
                MsgChar--; // increment character
                if (MsgChar < 0x20) MsgChar = 0x7E;
     	        }
DISPTEXT:
     	        str_tmp[i] = MsgChar; // append currently selected character to array
     	        str_tmp[i + 1] = '\0';
     	        row_count = 6 + (i * 6); // skip the blank spaces in fb
              LedStr(str_tmp); 
     	      }
     	      break;
     	    }
     	    break;
    	  case SET_SPEED:
    	    LedStr("SPEED");
     	    enable_scrolling();
MOREWAIT3:
    	    while (SW1 || SW2) asm ("wait");   // wait until no more buttons are pressed
     	    while (!SW1 && !SW2) asm ("wait"); // wait until a button is pressed
     	    if (SW1)
     	    {
     	      while (SW1) // wait until button is released
     	      {
     	        asm ("wait");
     	        if (SW1 && SW2) // if both buttons are pressed, don't do anything
     	          goto MOREWAIT3;
     	      }
     	      change_state();
     	      break;
     	    }
     	    else if (SW2)
     	    {
     	      while (SW2) // wait until button is released
     	      {
     	        asm ("wait");
     	        if (SW1 && SW2) // if both buttons are pressed, don't do anything
     	          goto MOREWAIT3;
     	      }
     	      disable_scrolling();
     	      while (1)
     	      {
     	        asm ("wait");
     	        if (SW1)
     	        {
     	          while (SW1) // wait until button is released
     	          {
     	            asm ("wait");
     	            if (SW1 && SW2) // if both buttons pressed, return to scrolling message
     	            {
     	              state = SCROLL;
     	              goto MAINLOOP; // get out of this mess of nested loops
     	            }
     	          }
     	          ScrollSpeed++;
                if (ScrollSpeed > 5) ScrollSpeed = 1;     	          
     	        }
     	        else if (SW2)
     	        {
     	          while (SW2) // wait until button is released
     	          {
     	            asm ("wait");
     	            if (SW1 && SW2) // if both buttons pressed, return to scrolling message
     	            {
     	              state = SCROLL;
                    goto MAINLOOP; // get out of this mess of nested loops
     	            }
     	          }
     	          ScrollSpeed--;
     	          if (ScrollSpeed < 1) ScrollSpeed = 5;
     	        }
     	        row_count = 6; // skip the blank spaces in fb
              LedStr(num2asc(ScrollSpeed) + 1); // in serial.c. ignore the first byte, which will be 0 for a single-digit input
     	      }
     	      break;
     	    }
     	    break;
    	  case POV:
          LedStr("POV"); 
     	    enable_scrolling();
MOREWAIT4:
    	    while (SW1 || SW2) asm ("wait");   // wait until no more buttons are pressed
     	    while (!SW1 && !SW2) asm ("wait"); // wait until a button is pressed
     	    if (SW1)
     	    {
     	      while (SW1) // wait until button is released
     	      {
     	        asm ("wait");
     	        if (SW1 && SW2) // if both buttons are pressed, don't do anything
     	          goto MOREWAIT4;
     	      }     	      
     	      change_state();
     	      break;
     	    }
     	    else if (SW2)
     	    {
     	      while (SW2) // wait until button is released
     	      {
     	        asm ("wait");
     	        if (SW1 && SW2) // if both buttons are pressed, don't do anything
     	          goto MOREWAIT4;
     	      }     	      
     	      disable_scrolling();
     	      SRTISC_RTIE = 0; // disable RTI - too slow for our purposes
     	      while (!SW1 || !SW2) // do this state until both buttons are pressed
     	      {
     	        // remember that you have to spin the badge in the proper direction in order to display the correct, non-mirrored image
              // the badge has no sense of where it is located, so it just displays the graphics over and over again until it's time to change modes
              // you could do some cool tweaks with the accelerometer here, like reverse the drawing direction when the badge is going in the other direction
              for (i = 0; i < POV_MAX_FRAME; ++i) 
      	      {
      	        memcpy(fb, &POV_buffer[i], NUM_ROWS);
      	        draw_buffer(fb);      	     
      	        //delay(1); // frame rate speed - determines how fast the image is "drawn" into the air
      	      }
     	      }
     	      SRTISC_RTIE = 1; // re-enable RTI
     	      change_state();
            break;
     	    }
    	    break;
    	  case SLEEP:
    	  default:
    	    disable_scrolling();
    	    clear_matrix();
    	    while (SW1 || SW2) asm ("wait"); // wait until no more buttons are pressed
    	    SRTISC_RTIE = 0;    // disable RTI, since that could wake us up
BACKTOSLEEP:
          asm ("stop");  // go to sleep (we're configured for STOP3 standby mode in Device Initialization) until keypress (only STOP3 wakes on KBI)         

          // we will wake on a KBI from SW1 or SW2, but we're only interested in SW1
          if (SW1)
          {
            delay_ms(100);  // poor man's debounce added to prevent spurious interrupts from QT100 touch sensors
            if (SW1)
            {
              while (SW1)
              {
                asm ("wait");
                if (SW1 && SW2) // if both buttons are pressed, don't do anything
                  goto BACKTOSLEEP;
              }
              SRTISC_RTIE = 1;    // re-enable RTI
    	        change_state();     // when we're awakened, time to change state              
              break;
            }
            else
              goto BACKTOSLEEP; 
          }
          else
            goto BACKTOSLEEP;
    	}
  	}
  } /* loop forever */
  /* please make sure that you never leave main */
}


void clear_matrix(void)
{
  memset(fb, 0x00, MSG_LENGTH); 
}


// this function will draw the entire matrix (all 19 rows)
// it needs to be refreshed as often as possible, since we're using multiplexing
void draw_buffer(unsigned char* buf) // pass pointer to frame buffer
{
  unsigned char i;
  
  // the first 3 rows are a special case since we have to shift in row control along with column data
  shiftreg[U4] = REVERSEBITS(buf[0]) | 0b011;  
  shiftreg[U5] = 0xFF;
  shiftreg[U6] = 0xFF;    
  write_expanded_outputs(shiftreg);  
   
  shiftreg[U4] = REVERSEBITS(buf[1]) | 0b101;
  shiftreg[U5] = 0xFF;
  shiftreg[U6] = 0xFF;    
  write_expanded_outputs(shiftreg);  
  
  shiftreg[U4] = REVERSEBITS(buf[2]) | 0b110;
  shiftreg[U5] = 0xFF;
  shiftreg[U6] = 0xFF;    
  write_expanded_outputs(shiftreg);  

  for (i = 3; i <= 10; ++i)
  {
    shiftreg[U4] = REVERSEBITS(buf[i]) | 0b111;
    shiftreg[U5] = (0x80 >> (unsigned char)(i-3)) ^ 0xFF; // select the row to enable
    shiftreg[U6] = 0xFF;    
    write_expanded_outputs(shiftreg);  
  }

  for (i = 11; i <= 18; ++i)
  {
    shiftreg[U4] = REVERSEBITS(buf[i]) | 0b111;
    shiftreg[U5] = 0xFF;
    shiftreg[U6] = (0x80 >> (unsigned char)(i-11)) ^ 0xFF;   
    write_expanded_outputs(shiftreg);  
  }
  
  shiftreg[U4] = 0xFF;
  shiftreg[U5] = 0xFF;
  shiftreg[U6] = 0xFF;    
  write_expanded_outputs(shiftreg);      
}  


/*--------------------------------------------------------------------------------------------------

  Name         :  LedStr
  Description  :  Loads a string into the frame buffer
  Argument(s)  :  dataPtr -> Pointer to null terminated ASCII string to display.
  Return value :  None.
  
  NOTE : Be sure the passed string is not longer than the frame buffer

--------------------------------------------------------------------------------------------------*/

void LedStr (char *dataPtr)
{
  unsigned char i, j;

  // we waste a lot of RAM here with 40 bytes of blanks...
  for (i = 0; i < 20; i++) // add enough space as header to start text from bottom of matrix
       fb[i] = 0x00; 
    
  while ( *dataPtr )
  {
    if ( (*dataPtr < 0x20) || (*dataPtr > 0x7E) ) // If non-printable character,
        *dataPtr = 32;  //  Convert to a blank.
    
    for (j = 0; j < 5; j++)
    {
         fb[i] = FontLookup[*dataPtr - 32][j];
         i++;
    }
    
    if (*dataPtr != 32)  // if we're not printing a space
    {
      fb[i] = 0x00; // add a single blank line in between characters
      i++;
    }
    else
      i--; // remove a blank line to keep words closer together
    
    dataPtr++;
  }
  
  for (j = 0; j < 20; j++, i++) // add enough space to completely scroll through the matrix
       fb[i] = 0x00; 
     
  fb[i] = 0x80; // add end-of-message flag
}


// interrupt service routines

void KBI_ISR (void) 
{ 
  KBISC_KBACK = 1;  // Clear pending keyboard interrupts
}


void RTI_ISR (void) // 8ms
{
  // set corner LEDs as indicators if buttons are pressed (only if not scrolling)
  /*if (!scroll_flag)
  {
    if (SW1)
     fb[row_count] |= 0x10; // turn on upper left LED   
    else
     fb[row_count] &= 0x0F; // turn it off
    
    if (SW2)
     fb[row_count] |= 0x01; // turn on upper right LED
    else
     fb[row_count] &= 0x17; // turn it off
  }*/
  
  draw_buffer(fb + row_count); // draw the buffer every interrupt         
          
  SRTISC |= 0x40;  // clear RTIF
}


void MTIM_ISR (void)  // note: to change the scroll speed, change the MTIM period (default = 90ms)
{
  if (scroll_flag) // if we want to scroll...
  {
    if (fb[row_count + 20] != 0x80)  // if we haven't reached the end of the message, keep on truckin'!
      row_count++;   // increment the row counter for scrolling purposes
    else
      row_count = 0;
  }

  MTIMSC_TOF = 0;   // Clear interrupt flag
}
     

void enable_scrolling (void)
{
  scroll_flag = 1;
  row_count = 0;
}

void disable_scrolling (void)
{
  scroll_flag = 0;
  row_count = 0;
}


void change_state (void)
{
  disable_scrolling();
  clear_matrix();

  switch (state) 
  {
    case SLEEP:
  	  state = SCROLL;
  		break;
    case SCROLL:
     	state = SET_MSG;
     	break;
    case SET_MSG:
     	state = SET_SPEED;
     	break;
    case SET_SPEED:
     	state = POV;
     	break;     	
    case POV:
  		state = SLEEP;
  	break;
  }
   
	state_change_flag = 1;
}


////   Library for a 74595 Expanded Output Chip                        ////
////   from CCS PIC-C 74595.C driver and modified to not erase input   ////
////   byte when shifting out data.                                    ////
////                                                                   ////
////   write_expanded_outputs(eo);  Writes the array eo to the chips   ////
////                                                                   ////
void write_expanded_outputs (unsigned char eo[NUMBER_OF_74595]) 
{
    unsigned char i, j;

    REG_CLK = LOW;
    REG_STROBE = LOW;

    for (i = 0; i < NUMBER_OF_74595; ++i)  // start with LSB
    {
      for(j = 1; j <= 8; ++j) 
      {  
        // Clock out bits from the eo array (start with LSB)
        if ((eo[i] & 0x01) == 0)
            REG_DATA = LOW;
        else
            REG_DATA = HIGH;
   
        eo[i] >>= 1;
         
        REG_CLK = HIGH;
        REG_CLK = LOW;
      }
    }
    
    REG_STROBE = HIGH;
    REG_STROBE = LOW;
}

/**************************************************************
*	Function: 	delay
*	Parameters: 16-bit delay value
*	Return:		none
*
*	Simple delay loop.
**************************************************************/
 
void delay(unsigned int count) 
{
	unsigned int i;
	for (i = 0; i < count; i++);
}

// delay the specified number of milliseconds
// not really very accurate because it could get interrupted
void delay_ms(unsigned int ms)  
{
  unsigned int timer;

  while (ms != 0) {
    // this number is dependent on the clock frequency (currently at 16MHz)
    for (timer=0; timer <= 376; timer++);
    ms--;
  }
}


/*-------------------------- UNUSED BITS & PIECES --------------------------*/

// Freescale MMA7260QT 3-axis Accelerometer code 
/*  
    #define TRIAXSLEEP    PTBD_PTBD7    // Output
    #define THRESH        300

    // set ideal 0g and 1g calibration values
    #define X0g 512
    #define Y0g 512
    #define Z0g 512
      
    #define X1g 758
    #define Y1g 758
    #define Z1g 758
      
    // A/D channels
    #define X_AXIS        0x02
    #define Y_AXIS        0x01
    #define Z_AXIS        0x00
  
    ADCSC1 = X_AXIS;//read X channel
    while(!ADCSC1_COCO);
    xx = ADCR;

    delay(10);

    ADCSC1 = Y_AXIS;//read Y channel
    while(!ADCSC1_COCO);
    yy = ADCR;

    delay(10);
      
    ADCSC1 = Z_AXIS;//read Z channel
    while(!ADCSC1_COCO);
    zz = ADCR;
             
    TRIAXSLEEP = 0;   // go to sleep for TRIAX
      
    xx = xx - xx_cal;
    yy = yy - yy_cal;
    zz = zz - zz_cal;
    (void)printf ("X: %d  Y: %d  Z: %d\n\r", xx, yy, zz);
*/

