#include <SPI.h>
#include <SD.h>
#define SizeRegisterModules 300

int IDarg = 0;
String ParsedCommand[SizeRegisterModules];
File myFile;

char getCharCommand(){
  if (Serial.available() > 0) {
    char cmdraw = Serial.read();
    if (cmdraw > 0) return cmdraw;
  }
  return '?';
}

char getCharCommand2(){
  if (myFile.available() > 0) {
    char cmdraw = myFile.read();
    if (cmdraw > 0) return cmdraw;
  }
  return '?';
}

void play(String *args) {
  for(int i = 0;i<=1000;i++) {
    if(args[i*3] == "tone") {
      //tone(2,args[i*3+2],args[i*3+3]);
      Serial.print("tone(2,");
      Serial.print(args[i*3+2]);
      Serial.print(",");
      Serial.print(args[i*3+3]);
      Serial.println(");");
    } else if(args[i*3] == "delay") {
      Serial.print("delay(");
      Serial.print(args[i*3+3]);
      Serial.println(");");  
    }
  }
}

void mainL(String *args){
  if(args[0] == "play")
  {
    Serial.println("initialization done.");
    myFile = SD.open(args[1]);
    if (myFile) {
      Serial.print(args[1]);
      Serial.println(":");

      // read from the file until there's nothing else in it:
      while (myFile.available()) {
        char CharCommand = getCharCommand();
        if (CharCommand != '}' && CharCommand != '?'){
          Serial.print(CharCommand);
          if (CharCommand == ' ' && CharCommand == '(' && CharCommand == ',' && CharCommand == ')'){
            if(CharCommand == ')') { IDarg++; }
            IDarg++;
          }else{
            ParsedCommand[IDarg] += CharCommand;
          }
        } else {
        Serial.println(" ");
        play(ParsedCommand);
        IDarg = 0;
        for (int i = 0;i<=3000;i++) {ParsedCommand[i]="";}
        Serial.print(">");
      }
      }
      // close the file:
      myFile.close();
    } else {
      // if the file didn't open, print an error:
      Serial.print("error opening ");
      Serial.println(args[1]);
    }
  }
}

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  SD.begin(4);
  Serial.print("\n \n \n \n>");
}

void loop() {
 char CharCommand = getCharCommand();
 if (CharCommand != ';' && CharCommand != '?'){
    Serial.print(CharCommand);
  if (CharCommand == ' '){
    IDarg++;
  }else{
    ParsedCommand[IDarg] += CharCommand;
  }
 }else if(CharCommand == ';'){
  Serial.println(" ");
  mainL(ParsedCommand);
  IDarg = 0;
  for (int i = 0;i<=3000;i++) {ParsedCommand[i]="";}
  Serial.print(">");
 }
}
