#include <ME218_C32.h>
#include <timers12.h>
#include <stdio.h>
#include "ADS12.h"
#include "target.h"
#include "shooter.h"
#include "CoinSensor.h" 
#include "motors.h"
#include "LCD.h"

#define ADPINS        "IAAAOOOO"
#define GAME_LENGTH   60 //In seconds
#define GAME_TIMER    5
#define COIN_SENSOR   0x80
#define DIFFICULTY_IN 6
#define ONE_SECOND    1000
#define FIVE_SECONDS  5000
#define IND_SCORE_TO_WIN_PRIZE  1

void main(void){
   TMRS12_Init(TMRS12_RATE_1MS);
   ADS12_Init(ADPINS);
   InitMotors();
   InitCoinSensor(COIN_SENSOR); 
   initShooter();
   initTargets();
   LCDInit();

   while(1) {															
     unsigned char secondsPlayed = 0;
     //Wait for coin
     printf("Waiting for a coin...\r\n");
     
     LCDResetGame();
     while(!CheckCoinEvent()) {}
          
     //Wait for trigger press to begin game
     printf("Waiting for trigger press...\r\n");
     LCDWaitTrigger();
     while(!checkTrigger1() && !checkTrigger2()) {}
     LCDGameSetUp();
     initShooter();
     initTargets();
     ChangeMotorSpeed(DIFFICULTY_IN);

     WriteTime(GAME_LENGTH);
     TMRS12_InitTimer(GAME_TIMER,ONE_SECOND);

     while(secondsPlayed < GAME_LENGTH) {
       if(checkTrigger1())
         fireShooter1();
       if(checkTarget1()) {
         registerHit1();
         WriteScore(score1(), score2());
       }
       if(checkShooter1())
         turnOffShooter1();

       if(checkTrigger2())
         fireShooter2();
       if(checkTarget2()) {
         registerHit2();
         WriteScore(score1(), score2());
       }
       if(checkShooter2())
         turnOffShooter2();
 
       if(checkActivateTarget())
         activateTarget();
       
       if(checkVibrate1())
         turnOffVibrate1();
       if(checkVibrate2())
         turnOffVibrate2();

       if(TMRS12_IsTimerExpired(GAME_TIMER)) {
         secondsPlayed++;
         TMRS12_InitTimer(GAME_TIMER,ONE_SECOND);
         WriteTime(GAME_LENGTH - secondsPlayed);
       }             
     }
     endShooter();
     endTarget();
     EndMotors();

     LCDGameEnd(score1(),score2(), IND_SCORE_TO_WIN_PRIZE);
     printf("Final Score\r\n");
     printf("Player 1: %d, Player 2: %d\r\n",score1(),score2());
     
     if( (score1() >= IND_SCORE_TO_WIN_PRIZE ) || (score2() >= IND_SCORE_TO_WIN_PRIZE) ) 
     {
        DispenseSWAG(GAME_TIMER);
     }
     
     
     //Reset LCD to read "Insert Coin"		
     TMRS12_InitTimer(GAME_TIMER,FIVE_SECONDS);
     while (TMRS12_IsTimerExpired(GAME_TIMER) ==0 ) {
     }
     LCDResetGame();
     printf("Resetting LCD");
   }
}

