 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");
-    }
+  float execTime = 0;
+  float initRead = 0;
+  float resetTime = 0;
+  int n=0;                                // Count loops around print routine
+  int i=0;
+  int transStat = 0;
+  int prevStat = 0;
+  boolean downloadBegin = false;
+  boolean transBegin = false;
+  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;
+  
+  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;
+    }
+    
+    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~SD Download Routine~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+                                  //  If a download is requested, no further data needs
+                                  //  to be read/generated/logged to SD. If information
+                                  //  was still being logged/transmitted, data will be 
+                                  //  jumbled and SD writing happening simultaneously to
+                                  //  reading.
+    
+    if(downloadBegin && myFile)
+    {
+      downloadSD();
+      downloadBegin = false;
+      Serial2.print("#\r");
+    }
+      
+    
+    //~~~~~~~~~~~~~~~~~~~~~~~~~Check for signals from plotter~~~~~~~~~~~~~~~~~~~~~~~~~
+    if(xbeeMode)
+    {
+      if(Serial2.available() > 2)
+      {
+        char start_buf[10] = "";
+        Serial2.readBytes(start_buf, Serial2.available());
+        Serial.print("Received string was: ");
+        Serial.println(String(start_buf));
         
-    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 
+        if(String(start_buf) == "!!!")  
+        {
+          Serial.println("----------Start Transmission Signal Received----------");
+          transBegin = true;
+        }
+        if(String(start_buf) == "~~~")  
+        {
+          Serial.println("----------Stop Transmission Signal Received----------");
+          transBegin = false;
+        }
+        if(String(start_buf) == "---")
+        {
+          Serial.println("----------Timer Reset Signal Received----------");
+          Serial2.println("$");
+          Serial.println("Returned reset acknowledgement.");
+          while(Serial2.available() < 2);
+          memset(&start_buf, 0, sizeof(start_buf));
+          Serial2.readBytes(start_buf, Serial2.available());
+          Serial.print("Confirmation received: ");;
+          Serial.println(start_buf);
+           
+          n=0;
+          initRead = 0;
+          resetTime = execTime;
+          createNewSDFile();
+        }
+        if(String(start_buf) == "===")
+        {
+          Serial.println("Initiating SD Download");
+          downloadBegin = true;
+          Serial.println(downloadBegin);
+        }
+        char error_buf[1] = "";
+        while(Serial2.available() > 0)
+        {
+          Serial.print(".");
+          Serial2.readBytes(error_buf, 1);
+        }
+        Serial.println("Buffer Flushed.\n"); 
+        
+      }
+      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(String(start_buf) == "===")
+        {
+          Serial.println("Initiating SD Download");
+          downloadBegin = true;
+          Serial.println(downloadBegin);
+        }
+        
+      }
+      if(!transBegin) continue;
+    }
+    
+    if(mockMode)
+    {
+      if(n >= 500) continue;
+      //~~~~~~~~~~~~~~~Print mock data string to serial port~~~~~~~~~~~~~~~~~~~~~~~~                                          
+         Serial2.print(execTime);                // 'T' data stream 
+         Serial2.print(" ");
+         if(myFile) {
+          myFile.print(execTime);           // Print dataset to SD Card
+          myFile.print(" ");                         // Formatting
+         }
+         int i=1;
+         for(i; i < sigNum; i++)
+         {
+           float mockSig = random(0,1000);
+           Serial2.print(mockSig);               // 'A' 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(" ");
+                                                 //  SD Card Implementation
+          if(myFile) {
+            myFile.print(mockSig);           // Print dataset to SD Card
+            myFile.print(" ");                         // Formatting
            }
-           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;
-      }
-      
+         }
+         myFile.print("\r");
+         Serial2.print(" \r");
+         delay(dataRateDelay);
+         n++; 
+         
+    }
+    else
+    {
       //~~~~~~~~~~~~~~~~~~~~~~~~~Generate Data for transmission~~~~~~~~~~~~~~~~~~~~~~~~~~
+                                                //  Creates realistic string of variables as 
+                                                //  to those that would be expected.
+      
+      
       execTime = execTime - resetTime;
       
       i++;

          }
        }
      }
      delay(100);
      n++;                                   //  Increment loop counter
    }                                        
  }                                          
  
  // each while loop has a wait 1000 milliseconds before the loop
  // repeats for the output to be constant and not

                                           //  sets the maximum time elapsed before
                                           //  program should send an config update.
                                           
boolean xbeeMode = true;                  //  This condition determines whether Xbees
                                           //  are being used. Usually this would be
                                           //  true, except for testing without the
                                           //  Xbee.
                                           
boolean SDMode = true;                    //  Condition to execute optional SD
                                           //  functionality. This is provided for
                                           //  testing purposes where the SD might
                                           //  not be used.
