 //1: serial logging,
 //2: SD card logging
 
-#define LOGFILE "stabilize_log.txt"
-#define NAMEFILE "stabilize_last.txt"
+//Filenames for logging
+#define LOGFILE "slog.txt"
+#define NAMEFILE "slast.txt"
+#define DATAFILESTEM "sdat"//##.txt
+String fileName = DATAFILESTEM;
+int fileNumber = 0;
+const int chipSelect = BUILTIN_SDCARD;
 
 //use this function to log a line to the computer
 void logln(String msg) {
   if(LOGGING == 1) {
     Serial.println(msg);
   } else if(LOGGING == 2) {
-    //TODO
+    File logfile = SD.open(LOGFILE, FILE_WRITE);
+    if(logfile){
+      logfile.println(String(fileNumber) + String("|") + msg);
+      logfile.close();
+    } else {
+      return;
+    }
   }
 }
 
 
-String fileName = "stabilize_data_";
-int fileNumber = 0;
-
 //Setup for data loggin to SD card
 void dataLoggingSetup() {
-  while(!SD.begin(BUILTIN_SDCARD)) {
+  logln("Initializing SD card...");
+  
+  if(!SD.begin(chipSelect)) {
     logln("Card failed, or not present");
+    return;
   }
+
+  logln(String("Looking for ") + String(NAMEFILE) + String("..."));
+  
   if(SD.exists(NAMEFILE)) {
+    logln("Previous namefile exists");
 
     //read existing namefile and parse new file number
-    File namefile = SD.open(NAMEFILE);
+    File namefile = SD.open(NAMEFILE, FILE_READ);
     String fileNumberS = "";
     while(namefile.available()){
-      fileNumberS += namefile.read();
+      char next = namefile.read();
+      fileNumberS += next;
     }
+    logln(String("Previous file number:") + fileNumberS);
     fileNumber = fileNumberS.toInt() + 1;
     
     //erase previous namefile

}



void setup() {
  dataLoggingSetup();
}

void loop() {
  // put your main code here, to run repeatedly:

}

    SD.remove(NAMEFILE);
    
    //write a new namefile
    namefile = SD.open(NAMEFILE, FILE_WRITE);
    if(namefile) {
      fileName += String(fileNumber) + ".txt";
      namefile.print(String(fileNumber));
      namefile.close();
    } else {
      logln(String("Error opening ") + String(NAMEFILE) + String("!"));
      return;
    }
    
    
  } else {
    logln("No previous namefile exists. Creating new namefile.");
    
    fileName += "0.txt"; 

    //make a namefile
    File namefile = SD.open(NAMEFILE, FILE_WRITE);
    if(namefile) {
      namefile.print(String("0"));
      namefile.close();
    } else {
      logln(String("Error opening ") + String(NAMEFILE) + String("!"));
      return;
    }
    
  }

  //Done!
