     SD.remove(NAMEFILE);
     
     //write a new namefile
-    namefile = SD.open(NAMEFILE);
-    fileName += String(fileNumber) + ".txt";
-    char charbuf[50];
-    String(fileNumber).toCharArray(charbuf, 50);
-    namefile.write(charbuf, 50);
-    namefile.close();
+    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 {
-    fileName += "0.txt";
+    logln("No previous namefile exists. Creating new namefile.");
+    
+    fileName += "0.txt"; 
 
     //make a namefile
-    File namefile = SD.open(NAMEFILE);
-    namefile.write('0');
-    namefile.close();
+    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!

//1: serial logging,
//2: SD card logging

#define LOGFILE "stabilize_log.txt"
#define NAMEFILE "stabilize_last.txt"

//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
  }
}


String fileName = "stabilize_data_";
int fileNumber = 0;

//Setup for data loggin to SD card
void dataLoggingSetup() {
  while(!SD.begin(BUILTIN_SDCARD)) {
    logln("Card failed, or not present");
  }
  if(SD.exists(NAMEFILE)) {

    //read existing namefile and parse new file number
    File namefile = SD.open(NAMEFILE);
    String fileNumberS = "";
    while(namefile.available()){
      fileNumberS += namefile.read();
    }
    fileNumber = fileNumberS.toInt() + 1;
    
    //erase previous namefile

}


void dataln(String dat) {
  char fileNameC[fileName.length()+1];
  fileName.toCharArray(fileNameC, fileName.length()+1);
  File datafile = SD.open(fileNameC, FILE_WRITE);
  if(datafile) {
    datafile.println(dat);
    datafile.close();
  } else {
    logln(String("Failed to open ") + fileName + String(" for data logging. data: ") + dat);
  }
}


void setup() {
  if(LOGGING == 1) {
    //wait for USB
    Serial.begin(115200);
    while (!Serial) {
      ; // wait for serial port to connect. Needed for Leonardo only
    }
  }
  dataLoggingSetup();
}

void loop() {
  static unsigned long t1 = millis();
  static unsigned long t2 = millis();
  
  String string = String("time elapsed (milliseconds): ");
  t2 = millis();
  string += String(t2 - t1);
  t1 = t2;
  dataln(string);
  
}
