-/*                                                                   25th SEPTEMBER 2014
+/*                                                                    14th NOVEMBER 2014
 ========================================================================================
 ========================= Engineering Design 3A - FSAE TEAM 52 =========================
 ========================================================================================

void loop() {
  float timeElapsed = 0;
  float addedTime = 0;
  int n = 0;
  File myFile;
  
  //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~SD Card Implementation~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  if(SDMode)                              //  SD only needs to be initialized if SD is being
  {                                       //  used. Otherwise, initialization will fail.
    pinMode(10, OUTPUT);
    
    if (!SD.begin(4)) {
      Serial.println("initialization failed!");
      return;
    }
    
    if(SD.exists("data.txt")){
      SD.remove("data.txt");
    }
        
    myFile = SD.open("data.txt", FILE_WRITE);
  }
  
  //~~~~~~~~~~~~~~~~~~~~~~~~~~~Generate and Transmit Mock Data~~~~~~~~~~~~~~~~~~~~~~~~~~~
  if(mockMode)                              //  Enters mock data transmission mode
  {
    int ramp = 0; 
    for(;;)                                 //  Loops in this mode forever
    {
           //~~~~~~~~~~~~~~~Print mock data string to serial port~~~~~~~~~~~~~~~~~~~~~~~~
           float exectime = float(millis())/1000; //  millis command is a long int that 
                                                  //  contains program execute time in ms.
                                                 
           Serial2.print(exectime);                // 'T' data stream 
           Serial2.print(" ");
           Serial2.print(ramp);
           Serial2.print(" ");
           ramp += 1;
           
           int i=2;
           for(i; i < sigNum; i++)
           {
             Serial2.print(random(0,1000));          // 'A' data stream
             Serial2.print(" ");
           }
           Serial2.print(" \r");
           
           delay(25);//delay in ms 250 = 4 times a second
           
           timeElapsed = exectime - addedTime;     //  Checks how much time has elapsed,
                                                   //  if it has been more than 5 seconds
                                                   /*
           if((timeElapsed > configUpdateLimit) && sendConfigInfo) 
           {                                       //  since last config update, sends a 
             sendConfigString();                   //  config string.
             addedTime = exectime;
           }
           */
           
  
      }
  }
  else                                      //  Enters data acquisition mode  
  {
                                            //  Creates realistic string of variables as 
                                            //  to those that would be expected.
    float execTime = 0;
    float batteryLevel = 100;               //  100% battery by default
    float vehicleSpeed = 0;                 //  Speed starts at 0ms
    float vehicleAccel = 0;                 //  Acceleration starts at 0ms^2
    float engineTemp = 20;                   //  Engine temperature starts at 20 degrees
    int vehicleIndicators = 0;
    float initRead = 0;
    float resetTime = 0;
    int n=0;                                // Count loops around print routine
    int i=0;
    boolean transBegin = false;
    boolean downloadBegin = false;
    
    for(;;)
    {
      //~~~~~~~~~~~~~~~~~~~~~~~Create simulation data for now~~~~~~~~~~~~~~~~~~~~~~~~~~~
      execTime = float(millis())/1000;     //  millis command is a long int that 
      
      timeElapsed = execTime - addedTime;     //  Checks how much time has elapsed,
                                              //  if it has been more than 5 seconds
      if((timeElapsed > configUpdateLimit) && sendConfigInfo) 
      {                                       //  since last config update, sends a 
         sendConfigString();                  //  config string.
         addedTime = execTime;
      }
      
      //~~~~~~~~~~~~~~~~~~~~~~~~~Check for signals from plotter~~~~~~~~~~~~~~~~~~~~~~~~~
     if(xbeeMode)
      {
        if(Serial2.available() > 2)
        {
          char start_buf[10] = "";
          Serial2.readBytes(start_buf, Serial2.available());
          Serial.print("Plotter string received was: ");
          Serial.println(String(start_buf));
          if(String(start_buf) == "!!!")  
          {
            transBegin = true;
          }
          if(String(start_buf) == "~~~")  transBegin = false;
          if(String(start_buf) == "---")
          {
            n=0;
            initRead = 0;
            resetTime = execTime;
          }
        }
        if(!transBegin) continue;
      }
      else
      {
        if(Serial.available() > 2)
        {
          char start_buf[10] = "";
          Serial.readBytes(start_buf, Serial.available());
          
          
          Serial.print("Plotter string received was: ");
          Serial.println(String(start_buf));
          if(String(start_buf) == "!!!")  
          {
            transBegin = true;
          }
          if(String(start_buf) == "~~~")  transBegin = false;
          if(String(start_buf) == "---")
          {
            n=0;
            initRead = 0;
            resetTime = execTime;
          }
        }
        if(!transBegin) continue;
      }
      
      //~~~~~~~~~~~~~~~~~~~~~~~~~Generate Data for transmission~~~~~~~~~~~~~~~~~~~~~~~~~~
      execTime = execTime - resetTime;
      
      i++;

    }
    return;
}

void downloadSD()
{
  String dataSet;
  int bytesStored = 0;
  int byteCount = 0;
          
                      //  Close and save current SD file
  Serial.println("SD File Saved.");
  myFile.close();
  
                      //  Determine how many files exist on SD card
  boolean fileFlag = true;
  int m=0;
  char fileName[15];
  while(fileFlag)
  {
     sprintf(fileName, "data%d.txt", m);
     if(SD.exists(fileName))  
     {
       Serial.print(fileName);
       Serial.println(" exists.");
     }
     else  
     {
       Serial.print(fileName);
       Serial.println(" does not exist.");
       fileFlag = false;
     }
     m++;
  }
  
                    //  Issue prompt to GUI on which file should be read
  Serial.println("Prompting user to select file");
  Serial2.print("%");
  for(int u=0; u<(m-1); u++)  Serial2.print(u);
  Serial2.print("\r");
                    //  Wait for response from GUI
  while(Serial2.available() < 3);
                    //  Read in response
  char start_buf[10] = "";
  Serial2.readBytes(start_buf, Serial2.available());
  Serial.println(start_buf);
  sprintf(fileName, "data%c.txt", start_buf[2]);
  Serial.println(fileName);
  
                    //  Open selected file
  if(SD.exists(fileName))  myFile = SD.open(fileName, FILE_READ);
  else  
  {
    Serial.println("File selected does not exist. Download cancelled");
    return;
  }
  
  bytesStored = myFile.available();
  Serial.print(bytesStored);
  Serial.println(" bytes available on SD card.");
  while(byteCount <= bytesStored)
  {
    dataSet = "";
    for(int r=0; r<sigNum; r++)
    {
      String sampBuffer = "";
      int s=0;
      char sampChar;
      do
      {
        sampChar = myFile.read();
        byteCount++;
        sampBuffer += String(sampChar);
        s++;
      }  while((!String(sampChar).equals(" ")) && (byteCount <= bytesStored));
      dataSet += sampBuffer;
      if(byteCount > bytesStored) break;
    }
    if(byteCount >  bytesStored) break;
    
    Serial.print("Data Set was: ");
    Serial.println(dataSet);
    Serial2.print(dataSet);
    delay(100);
  }
  Serial2.print("\r\n");
  Serial2.print("#\r");
  Serial.println("Download complete.");
  
  createNewSDFile();
  return;
}

void createNewSDFile()
{
                            //  Close current SD file and create a new one
    Serial.println("Creating new SD File...");
    myFile.close();
                            //  Check existing files to determine next file name
    boolean fileFlag = true;
    int m=0;
    char fileName[15];
    while(fileFlag)
    {
       sprintf(fileName, "data%d.txt", m);
       if(SD.exists(fileName))   m++;  
       else                      fileFlag = false;
    }
    Serial.print("New file name is: ");
    Serial.println(fileName);
    myFile = SD.open(fileName, FILE_WRITE);
    
    return;
}
