/****************************************************************************
 Module
   CommMasterHSM.c

 Revision
   2.0.1

 Description
   This is a template for the top level Hierarchical state machine

 Notes

 History
 When           Who     What/Why
 -------------- ---     --------
 02/20/17 14:30 jec      updated to remove sample of consuming an event. We 
                         always want to return ES_NO_EVENT at the top level 
                         unless there is a non-recoverable error at the 
                         framework level
 02/03/16 15:27 jec      updated comments to reflect small changes made in '14 & '15
                         converted unsigned char to bool where appropriate
                         spelling changes on true (was True) to match standard
                         removed local var used for debugger visibility in 'C32
                         removed Microwave specific code and replaced with generic
 02/08/12 01:39 jec      converted from MW_MasterMachine.c
 02/06/12 22:02 jec      converted to Gen 2 Events and Services Framework
 02/13/10 11:54 jec      converted During functions to return Event_t
                         so that they match the template
 02/21/07 17:04 jec      converted to pass Event_t to Start...()
 02/20/07 21:37 jec      converted to use enumerated type for events
 02/21/05 15:03 jec      Began Coding
****************************************************************************/
/*----------------------------- Include Files -----------------------------*/
/* include header files for this state machine as well as any machines at the
   next lower level in the hierarchy that are sub-machines to this machine
*/
#include "ES_Configure.h"
#include "ES_Framework.h"
#include "CommMasterHSM.h"
#include "GameChatHSM.h"
#include "Hardware.h"
#include "Constants.h" 
#include "inc/hw_ssi.h"
#include "MasterSM.h"

// Clock defines
#define SYSTEM_CLOCK_FREQ 40000000
#define PWM_CLOCK_DIV SYSCTL_RCC_PWMDIV_4
#define DEFAULT_FREQ 1000
#define DEFAULT_DUTY 50
#define SCR 0x2700							//39 to scr which is bits 8-15
#define CPSDVSR 0x00000064 			//100 to cpsdvsr which is bits 0-7
#define NumResponseBytes	4
#define ALL_BITS_LO 0x00
#define StartQueryInterval 250 		//tryna turn on first BUT don't make this too fast don't you dare. 
//#define GameStatusCMD 0xC0
//#define QueryResponseCMD 0x70
//#define SendReportCMD 0x80
#define CommandMask 0xF0

//getter shifts and masks
#define CSG_S 7
#define CSR_S 3
#define GreenActiveArea_M 0x07
#define GreenActiveArea_S 4
#define CSR_M BIT0HI
#define Score_M 0x3F
#define RedActiveArea_M 0x07
#define GameStatus_S 7
#define GameStatus_M 0x80
#define Acknowledge_S 6
#define Acknowledge_M 0x03 
#define NextLocation_M 0x0F
#define Report50msValue 50

#define PrintGameStartQuery

//#define TestCommGameStatusCMD
//#define CommLoopBackTest

/*----------------------------- Module Defines ----------------------------*/

/*---------------------------- Module Functions ---------------------------*/
static ES_Event DuringQueryingGameStart( ES_Event Event);
static ES_Event DuringGameChat( ES_Event Event);
void SPI_EOT_Init (void);
void SPI_EOT_ISR (void);
void GameStartQuery_Init (void);
void SPI_Init(void);

/*---------------------------- Module Variables ---------------------------*/
// everybody needs a state variable, though if the top level state machine
// is just a single state container for orthogonal regions, you could get
// away without it
static CommMasterState_t CurrentState;
// with the introduction of Gen2, we need a module level Priority var as well
static uint8_t MyPriority;

static uint8_t LOC_Response [NumResponseBytes] = {0}; //array for bytes coming in from spi module and initialize them all to 0 
static uint8_t EatGarbageByte = 0; 	// variable to assign to value we read from DR when we don't care what it says  
static uint8_t CurrentCommand = 0;  // variable for the command that we are sending to LOC. either passed in as a param or set by us for query response 

//response bytes from loc
static uint8_t StatusByte1;
static uint8_t StatusByte2;
static uint8_t StatusByte3;
static uint8_t ResponseReadyByte;
static uint8_t ReportStatusByte;
static uint8_t FreqReportCMD;

/*------------------------------ Module Code ------------------------------*/
/****************************************************************************
 Function
     InitMasterSM

 Parameters
     uint8_t : the priorty of this service

 Returns
     boolean, False if error in initialization, True otherwise

 Description
     Saves away the priority,  and starts
     the top level state machine
 Notes

 Author
     J. Edward Carryer, 02/06/12, 22:06
****************************************************************************/
bool InitCommMasterSM ( uint8_t Priority )
{
  ES_Event ThisEvent;

  MyPriority = Priority;  // save our priority
	
	//init SPI transmission interrupt and game start query periodic timer-based interrupt
	SPI_Init();

  ThisEvent.EventType = ES_ENTRY;
  // Start the Master State machine

  StartCommMasterSM( ThisEvent );

  return true;
}

/****************************************************************************
 Function
     PostMasterSM

 Parameters
     ES_Event ThisEvent , the event to post to the queue

 Returns
     boolean False if the post operation failed, True otherwise

 Description
     Posts an event to this state machine's queue
 Notes

 Author
     J. Edward Carryer, 10/23/11, 19:25
****************************************************************************/
bool PostCommMasterSM( ES_Event ThisEvent )
{
  return ES_PostToService( MyPriority, ThisEvent);
}

/****************************************************************************
 Function
    RunMasterSM

 Parameters
   ES_Event: the event to process

 Returns
   ES_Event: an event to return

 Description
   the run function for the top level state machine 
 Notes
   uses nested switch/case to implement the machine.
 Author
   J. Edward Carryer, 02/06/12, 22:09
****************************************************************************/
ES_Event RunCommMasterSM( ES_Event CurrentEvent )
{
   bool MakeTransition = false;/* are we making a state transition? */
   CommMasterState_t NextState = CurrentState;
   ES_Event EntryEventKind = { ES_ENTRY, 0 };// default to normal entry to new state
   ES_Event ReturnEvent = { ES_NO_EVENT, 0 }; // assume no error

    switch ( CurrentState )
   {
       case QueryingGameStart :       // If current state is state one
         // Execute During function for state one. ES_ENTRY & ES_EXIT are
         // processed here allow the lowere level state machines to re-map
         // or consume the event
         CurrentEvent = DuringQueryingGameStart(CurrentEvent);
         //process any events
         if ( CurrentEvent.EventType != ES_NO_EVENT ) //If an event is active
         {
            switch (CurrentEvent.EventType)
            {
               case ES_GAME_START : //If event is event one
                  // Execute action function for state one : event one
                  NextState = GameChat;//Decide what the next state will be
                  // for internal transitions, skip changing MakeTransition
                  MakeTransition = true; //mark that we are taking a transition
                  // if transitioning to a state with history change kind of entry
                  EntryEventKind.EventType = ES_ENTRY;
                  break;
               case ES_RESPONSE_READY : //If event is event one
                  // Execute action function for state one : event one
                  NextState = CurrentState;//Decide what the next state will be
                  // for internal transitions, skip changing MakeTransition
                  MakeTransition = false; //mark that we are taking a transition
                  // if transitioning to a state with history change kind of entry
                  EntryEventKind.EventType = ES_ENTRY;
                  break;
                // repeat cases as required for relevant events
            }
         }
         break;
     
				case GameChat :       // If current state is state one
         // Execute During function for state one. ES_ENTRY & ES_EXIT are
         // processed here allow the lowere level state machines to re-map
         // or consume the event
         CurrentEvent = DuringGameChat(CurrentEvent);
         //process any events
         if ( CurrentEvent.EventType != ES_NO_EVENT ) //If an event is active
         {
            switch (CurrentEvent.EventType)
            {
               case ES_2MS_TIMEOUT : //If event is event one
                  // Execute action function for state one : event one
                  NextState = CurrentState;//Decide what the next state will be
                  // for internal transitions, skip changing MakeTransition
                  MakeTransition = false; //mark that we are taking a transition
                  // if transitioning to a state with history change kind of entry
                  EntryEventKind.EventType = ES_ENTRY;
                  break;
               case ES_RESPONSE_READY : //If event is event one
                  // Execute action function for state one : event one
                  NextState = CurrentState;//Decide what the next state will be
                  // for internal transitions, skip changing MakeTransition
                  MakeTransition = false; //mark that we are taking a transition
                  // if transitioning to a state with history change kind of entry
                  EntryEventKind.EventType = ES_ENTRY;
                  break;
                // repeat cases as required for relevant events
							 case ES_GAME_OVER : //If event is event one
                  // Execute action function for state one : event one
                  NextState = QueryingGameStart;//Decide what the next state will be
                  // for internal transitions, skip changing MakeTransition
                  MakeTransition = true; //mark that we are taking a transition
                  // if transitioning to a state with history change kind of entry
                  EntryEventKind.EventType = ES_ENTRY;
                  break;
            }
         }
         break; 
				 
    }
    //   If we are making a state transition
    if (MakeTransition == true)
    {
       //   Execute exit function for current state
       CurrentEvent.EventType = ES_EXIT;
       RunCommMasterSM(CurrentEvent);

       CurrentState = NextState; //Modify state variable

       // Execute entry function for new state
       // this defaults to ES_ENTRY
       RunCommMasterSM(EntryEventKind);
     }
   // in the absence of an error the top level state machine should
   // always return ES_NO_EVENT, which we initialized at the top of func
   return(ReturnEvent);
}
/****************************************************************************
 Function
     StartMasterSM

 Parameters
     ES_Event CurrentEvent

 Returns
     nothing

 Description
     Does any required initialization for this state machine
 Notes

 Author
     J. Edward Carryer, 02/06/12, 22:15
****************************************************************************/
void StartCommMasterSM ( ES_Event CurrentEvent )
{
  // if there is more than 1 state to the top level machine you will need 
  // to initialize the state variable
  CurrentState = QueryingGameStart;
  // now we need to let the Run function init the lower level state machines
  // use LocalEvent to keep the compiler from complaining about unused var
  RunCommMasterSM(CurrentEvent);
  return;
}

/***************************************************************************
 private functions
 ***************************************************************************/

static ES_Event DuringQueryingGameStart( ES_Event Event)
{
    ES_Event ReturnEvent = Event; // assme no re-mapping or comsumption

    // process ES_ENTRY, ES_ENTRY_HISTORY & ES_EXIT events
    if ( (Event.EventType == ES_ENTRY) ||
         (Event.EventType == ES_ENTRY_HISTORY) )
    {
        // implement any entry actions required for this state machine
			
			//enable the periodic interrupt for game start query
        HWREG(WTIMER0_BASE+TIMER_O_CTL) |= TIMER_CTL_TBEN;
      printf("entering querying game start case. enabled periodic timer 0B interrupt \n\r");

        // after that start any lower level machines that run in this state
        //StartLowerLevelSM( Event );
        // repeat the StartxxxSM() functions for concurrent state machines
        // on the lower level
    }
    else if ( Event.EventType == ES_EXIT )
    {
        // on exit, give the lower levels a chance to clean up first
        //RunLowerLevelSM(Event);
        // repeat for any concurrently running state machines
        // now do any local exit functionality
			
				//disenable the periodic interrupt for game start query
        HWREG(WTIMER0_BASE+TIMER_O_CTL) &= ~TIMER_CTL_TBEN;
      printf("exiting querying game start case. disabled periodic timer 0B interrupt \n\r");
    }else
    // do the 'during' function for this state
    {
        // run any lower level state machine
        // ReturnEvent = RunLowerLevelSM(Event);
      
        // repeat for any concurrent lower level machines
			//we could put in more safety code here to make sure that we changed game status states AND the game status is currently construction active 
			//but we don't need to do that because we are NEVER going to query too fast. do not query too fast friends. 
			//query to see if game has started by enabling the periodic timer interrupt 
			
			//asks if the game status bit is high 
      if (StatusByte3 & GameStatus_M){
				//if it is, post an event to both services 
				ES_Event ThisEvent;
				ThisEvent.EventType = ES_GAME_START;
				//PostCommMasterSM(ThisEvent);
				//commented out for testing so we can keep reading game status forever 
				ES_PostList00(ThisEvent);
			}
			#ifdef PrintGameStartQuery
			printf("LOC_COM: %02X | LOC_Response:	%02X	%02X	%02X	%02X \n\r", CurrentCommand, LOC_Response[0], LOC_Response[1], LOC_Response[2], LOC_Response[3] );
			#endif
        // do any activity that is repeated as long as we are in this state
    }
    // return either Event, if you don't want to allow the lower level machine
    // to remap the current event, or ReturnEvent if you do want to allow it.
    return(ReturnEvent);
}

static ES_Event DuringGameChat( ES_Event Event)
{
    ES_Event ReturnEvent = Event; // assme no re-mapping or comsumption

    // process ES_ENTRY, ES_ENTRY_HISTORY & ES_EXIT events
    if ( (Event.EventType == ES_ENTRY) ||
         (Event.EventType == ES_ENTRY_HISTORY) )
    {
        // implement any entry actions required for this state machine
              printf("entering game chat \n\r");

        // after that start any lower level machines that run in this state
        //StartLowerLevelSM( Event );
        // repeat the StartxxxSM() functions for concurrent state machines
        // on the lower level
			StartGameChatSM(Event);
    }
    else if ( Event.EventType == ES_EXIT )
    {
			   printf("exiting game chat \n\r");
        // on exit, give the lower levels a chance to clean up first
        //RunLowerLevelSM(Event);
        // repeat for any concurrently running state machines
        // now do any local exit functionality
      
    }else
    // do the 'during' function for this state
    {
			if (Event.EventType == ES_TIMEOUT && Event.EventParam == Report50msTimer){
			SPI_Transmit(QueryResponseCMD);
			}
        // run any lower level state machine
        // ReturnEvent = RunLowerLevelSM(Event);
      		ReturnEvent =	RunGameChatSM(Event);

        // repeat for any concurrent lower level machines
      
        // do any activity that is repeated as long as we are in this state
    }
    // return either Event, if you don't want to allow the lower level machine
    // to remap the current event, or ReturnEvent if you do want to allow it.
    return(ReturnEvent);
}

void SPI_Init(void){
	SPI_EOT_Init();
	GameStartQuery_Init();
	SafetyTimerInit();
}

void SPI_EOT_Init (void) {
	//printf("initing eot");
	// Check if clock is enabled to port A - if not, enable it
if ( (HWREG( SYSCTL_PRGPIO ) & SYSCTL_PRGPIO_R0) != SYSCTL_PRGPIO_R0 ){
		// Enable port A clock
			//printf("in that if statement ");
		HWREG( SYSCTL_RCGCGPIO ) |= SYSCTL_RCGCGPIO_R0;
		
}
	// enable the clock to ssi module 0 
	HWREG(SYSCTL_RCGCSSI) |= SYSCTL_RCGCSSI_R0;
	
	//Wait until port clock is ready
	while( (HWREG( SYSCTL_PRGPIO ) & SYSCTL_PRGPIO_R0) != SYSCTL_PRGPIO_R0 ){
	 }
		
  //Program the GPIO to use the alternate functions on the SSI pins
	HWREG( SPI_PORT+GPIO_O_AFSEL ) |= (MOSI | MISO | SCLK | FSS);
  //Set mux position in GPIOPCTL to select the SSI use of the pins
	HWREG(SPI_PORT+GPIO_O_PCTL) = (HWREG(SPI_PORT+GPIO_O_PCTL) & 0xff0000ff) + 
	     (2<<(5*BITS_IN_NIBBLE)) + (2<<(4*BITS_IN_NIBBLE)) + (2<<(3*BITS_IN_NIBBLE)) + (2<<(2*BITS_IN_NIBBLE));
	//Enable Digital IO for ssi Lines
	HWREG( SPI_PORT+GPIO_O_DEN ) |= (MOSI | MISO | SCLK | FSS);
	 //Program the required data directions on the port lines; mosi, sclock, and slave select are outputs 
	HWREG( SPI_PORT+GPIO_O_DIR ) |= (MOSI | SCLK | FSS);
	//Program the required data directions on the port lines; miso is input for the tiva
	HWREG( SPI_PORT+GPIO_O_DIR ) &= ~MISO; 
	 
	//set FSS line low to enable Slave
	//HWREG(GPIO_PORTA_BASE + (GPIO_O_DATA + ALL_BITS)) &= ~(FSS); 

	//we are using SPI mode 3, so program the pull-up on the clock line
	HWREG(SPI_PORT+GPIO_O_PUR) |= ENABLE_PULLUP; 
  //Wait for the SSI0 to be ready
	while( (HWREG( SYSCTL_PRSSI ) & SYSCTL_PRSSI_R0) != SYSCTL_PRSSI_R0 );
  //Make sure that the SSI is disabled before programming mode bits
	HWREG(SSI0_BASE+SSI_O_CR1) &= ~SSI_CR1_SSE;
	
	#ifdef CommLoopBackTest
	//if we are testing in loopback mode, set that bit in the control register 1
	HWREG(SSI0_BASE+SSI_O_CR1) |= SSI_CR1_LBM;
	#endif 
	
	//Select master mode (MS) 
	HWREG(SSI0_BASE+SSI_O_CR1) &= ~SSI_CR1_MS;
  //Configure the SSI clock source to the system clock
	HWREG(SSI0_BASE+SSI_O_CC) |= SSI_CC_CS_SYSPLL; 
  //Configure the clock pre-scaler
	HWREG(SSI0_BASE+SSI_O_CPSR) |= CPSDVSR;
  //Configure clock rate (SCR), phase & polarity (SPH, SPO), mode (FRF), data size (DSS) (mode 3)
	HWREG(SSI0_BASE+SSI_O_CR0) |= (SCR + SSI_CR0_SPO + SSI_CR0_SPH + SSI_CR0_DSS_8);
  //Setting the interrupt to fire when the FIFO is empty (assuming SSICR1 is set hi)
	HWREG(SSI0_BASE+SSI_O_RIS) |= SSI_RIS_TXRIS;
	//select TXRIS indicating End of Transmit (EOT)
	HWREG(SSI0_BASE+SSI_O_CR1) |= SSI_CR1_EOT;
	
	//try to first mask the interrupt until we use the spi_transmit
	HWREG(SSI0_BASE + SSI_O_IM) &= ~SSI_RIS_TXRIS;

  //Make sure that the SSI is enabled for operation
	HWREG(SSI0_BASE+SSI_O_CR1) |= SSI_CR1_SSE;
  //Enable the NVIC interrupt for the SSI when starting to transmit
	HWREG(NVIC_EN0) |= BIT7HI;
	//edit interrupt priority register to make the eot interrupt priority 2
  HWREG(NVIC_PRI1) = (HWREG(NVIC_PRI1) & ~NVIC_PRI1_INT7_M) + (PRIORITY_2<<(NVIC_PRI1_INT7_S)); 
	//printf("bottom of eot init");
}	

//Init spi eot Interrupt 
void SPI_EOT_ISR (void){
	
	//	Locally disable EOT interrupt (TXIM in SSIIM)
	HWREG(SSI0_BASE + SSI_O_IM) &= ~SSI_RIS_TXRIS;
		
	//we're going to clear locally so don't do this
					//disable the NVIC interrupt for the SSI because we are at the end of transmission 
					//HWREG(NVIC_EN0) &= ~BIT7HI;
	
  //read data from SSI data register and set equal to current command 
	//pull off first 8 bit garbage byte to discard it because that is what it sent while we wrote to it 
	EatGarbageByte = HWREG(SSI0_BASE+SSI_O_DR);
		
	//for all 4 response bytes, pull off into LOC_Response array
	for ( uint8_t i = 0 ; i < NumResponseBytes; i++){

		#ifndef TestCommGameStatusCMD
		LOC_Response[i] = HWREG(SSI0_BASE+SSI_O_DR);
		#endif
		
		#ifdef TestCommGameStatusCMD
		LOC_Response[1] = 0x11;
		#endif
	}
	
	//get the first four bits of the command and 0000 
	switch(CurrentCommand & CommandMask){
		//save the values from the data register to our module level variables
		case GameStatusCMD:
				//SB1 = data_register
				StatusByte1 = LOC_Response[1];
				//SB2 = data_register
				StatusByte2 = LOC_Response[2];
				//SB3 = data register
				StatusByte3 = LOC_Response[3];		
				break;
		//no case for send report because we read the FIFO when we populated LOC response array and we don't care about the values it gives us when we send the report in
		case QueryResponseCMD:
				//RR = data_register
		    ResponseReadyByte = LOC_Response[1];
				//RS  = data_register
				ReportStatusByte = LOC_Response[2];		
				break;
	}
	
	//printf("Above \n\r");
	//check if the response is actually ready or if we are still waiting on the results from the report 
	FreqReportCMD = GetFreqReportCMD();
	if((CurrentCommand == FreqReportCMD) || 
		((CurrentCommand == QueryResponseCMD) && (ResponseReadyByte == ReportResponseNOTReady))){
			ES_Timer_InitTimer(Report50msTimer,Report50msValue);
		}else{
			
			ES_Event ThisEvent;
      ThisEvent.EventType = ES_RESPONSE_READY;
			//PostCommMasterSM(ThisEvent); 
 //post new event because we have a command 
	   //printf("In else statement \n\r");
			//we only want to post response ready when we do game status because it messes up check in 
		  	if (CurrentCommand == GameStatusCMD){
					//printf("Going to post ES_RESPONSE_READY \n\r");
						//post to distribution list of master and comm 
					ES_PostList00(ThisEvent);
			}
				else{
					//otherwise, it would be a query command and the report response should be ready, so post it to comm master 
					PostCommMasterSM(ThisEvent);
			}
			
		}
}
	
void SPI_Transmit (uint8_t Command){

	//	Byte2Transmit equals passed in value
	CurrentCommand = Command;
	//	Write Byte2Transmit to the SSI data register
	HWREG(SSI0_BASE+SSI_O_DR) = CurrentCommand;

	for (uint8_t inc = 0; inc < NumResponseBytes ; inc++){
		HWREG(SSI0_BASE+SSI_O_DR) = ALL_BITS_LO;
	}
	
		//	Locally enable EOT interrupt (TXIM in SSIIM)
	HWREG(SSI0_BASE + SSI_O_IM) |= SSI_RIS_TXRIS;
	
	return;
}

//******************** GAME START PERIODIC QUERY INIT AND ISR*************************************************//
//init spi periodic timer query for game start 
void GameStartQuery_Init (void){
		//printf("initing query");
	// start by enabling the clock to the timer (Wide Timer 0)
HWREG(SYSCTL_RCGCWTIMER) |= SYSCTL_RCGCWTIMER_R0; // kill a few cycles to let the clock get going
while((HWREG(SYSCTL_PRWTIMER) & SYSCTL_PRWTIMER_R0) != SYSCTL_PRWTIMER_R0)
{
}
// make sure that timer (Timer B) is disabled before configuring
HWREG(WTIMER0_BASE+TIMER_O_CTL) &= ~TIMER_CTL_TBEN;

// set it up in 32bit wide (individual, not concatenated) mode
HWREG(WTIMER0_BASE+TIMER_O_CFG) = TIMER_CFG_16_BIT;
// set up timer B in periodic mode so that it repeats the time-outs
HWREG(WTIMER0_BASE+TIMER_O_TBMR) =
(HWREG(WTIMER0_BASE+TIMER_O_TBMR)& ~TIMER_TBMR_TBMR_M)| TIMER_TBMR_TBMR_PERIOD;
// set timeout to 250mS
HWREG(WTIMER0_BASE+TIMER_O_TBILR) = TicksPerMS * StartQueryInterval;
// enable a local timeout interrupt
HWREG(WTIMER0_BASE+TIMER_O_IMR) |= TIMER_IMR_TBTOIM;
// enable the Timer B in Wide Timer 0 interrupt in the NVIC
// it is interrupt number 95 so appears in EN2 at bit 31
HWREG(NVIC_EN2) = BIT31HI;
// make sure interrupts are enabled globally
__enable_irq();
// now kick the timer off by enabling it and enabling the timer to stall while stopped by the debugger
HWREG(WTIMER0_BASE+TIMER_O_CTL) |= (TIMER_CTL_TBEN | TIMER_CTL_TBSTALL);
//edit interrupt priority register to make the periodic timer interrupt priority 3
HWREG(NVIC_PRI23) = (HWREG(NVIC_PRI23) & ~NVIC_PRI23_INTD_M) + (PRIORITY_3<<(NVIC_PRI23_INTD_S));  
//printf("bottom of query init");
	}
	
	void GameStartQuery_ISR (void){
		// start by clearing the source of the interrupt
		HWREG(WTIMER0_BASE+TIMER_O_ICR) = TIMER_ICR_TBTOCINT;
		//set current command to game status 
		CurrentCommand = GameStatusCMD;
		//query command from the slave by sending the construction cycle status command 
		SPI_Transmit(CurrentCommand);
		//	HWREG(SSI0_BASE+SSI_O_DR) = CurrentCommand;
		//printf("every 250 ms ISR \n\r");
	}
//******************** END GAME START PERIODIC QUERY INIT AND ISR*************************************************//

//**************************************Getters*********************************************************************//
uint8_t GetCSG (void){
//Return bit 7 of Status Byte 1
	return (StatusByte1>>CSG_S);
}

//GetGreenActiveArea
uint8_t GetGreenActiveArea (void){
//Return bits 4-6 of Status Byte 1
	uint8_t GreenActiveArea = ((StatusByte1>>GreenActiveArea_S) & GreenActiveArea_M);
	return GreenActiveArea;
}
//GetRedCheckInShoot
	uint8_t GetCSR (void){
//Return bit 3 of Status Byte 1
		uint8_t CSR = ((StatusByte1>>CSR_S) & CSR_M);
	return CSR;	
	}
	
//GetRedActiveArea
	uint8_t GetRedActiveArea( void ){
//Return bit 0-2 of Status Byte 1
		uint8_t RedActiveArea = (StatusByte1 & RedActiveArea_M);
		return RedActiveArea;
	}		
//GetGreenScore
uint8_t GetGreenScore (void){
//Return bits 0-5 of Status Byte 2
	uint8_t GreenScore = (StatusByte2 & Score_M);
  return GreenScore;
}

//GetRedScore
uint8_t GetRedScore (void){
//Return Bits 0-5 of Status Byte 3
	uint8_t RedScore = (StatusByte3 & Score_M);
  return RedScore;
}

//GetGameStatus
uint8_t GetGameStatus (void){
//Return by 7 of Status Byte 3
		return (StatusByte3>>GameStatus_S);
}

//GetResponseReady
uint8_t GetResponseReadyByte (void){
//Return bits 0-7 of Response Ready Byte
	return ResponseReadyByte;
}

//GetReportResponse
uint8_t GetAcknowledge(void){
//Return bits 6-7 of Report Status Byte
		uint8_t Acknowledge = ((ReportStatusByte>>Acknowledge_S) & Acknowledge_M);
	return Acknowledge;
}

//GetNextLocation
uint8_t GetNextLocation (void){
//Return bits 0-3 of Report Status Byte
	uint8_t NextLocation = (ReportStatusByte & NextLocation_M);
	return NextLocation;
}

//GetCurrentCommand
uint8_t GetCurrentCommand (void){
	//return current command, called by game chat lower level sm 
	return CurrentCommand;
}

	#ifdef TEST_HARNESS
	//test harness main #jank 
	int main ( void ){
	// Set the clock to run at 40MhZ using the PLL and 16MHz external crystal
	SysCtlClockSet(SYSCTL_SYSDIV_5 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN
			| SYSCTL_XTAL_16MHZ);
	TERMIO_Init();
	//clrScrn();
	
	// Print test harness information
	puts("\rStarting jank Test Harness for SPI_Module\r\n");
	printf("%s %s\n",__TIME__, __DATE__);
	printf("\n\r\n");
		
	  SPI_EOT_Init();
		SPI_Query_Init();
		
	// Loop forever
	while ( true );
}
#endif