//*****************************************************
bool newCommand = false;
String command;
char c;
//*****************************************************
const int maxEntries = 10;
const int lastRecord = maxEntries - 1;
bool memFull = 0;
unsigned int numberOfEntries;
char record[maxEntries] = {'a', 'b', 'c', 'd'};
unsigned int recordIndex;
unsigned int orderIndex;
unsigned int recordOrder[2 * maxEntries];
//*****************************************************

void setup() {
  Serial.begin(115200);
  Serial.println("Starting");
  numberOfEntries = 0;
  recordIndex = 0;
  orderIndex = maxEntries - recordIndex;
  initOrder();
  printOrder();
  printRecords();

}

//********************************************************
void loop() {



  checkSerialCommand();
  delay(50);
}


//*******************************************************
void initOrder() {
  int j = lastRecord;
  for (int i = 0; i < lastRecord ; i++) {
    recordOrder[i] = j;
    j--;
  }
  for (int i = 0; i < maxEntries; i++) {
    recordOrder[i + maxEntries] = recordOrder[i];
  }
}
//--------------------------------------------
void printOrder() {
  Serial.println("Record Order");
  for (int i = 0; i < 2 * maxEntries; i++) {
    Serial.print(recordOrder[i]);
    if (i < ( 2 * maxEntries - 1)) Serial.print("-");
  }
  Serial.println();
}
//--------------------------------------------
void printRecords() {
  Serial.println("Record Data");
  for (int i = 0; i < numberOfEntries; i++) {
    Serial.print(record[recordOrder[i + orderIndex]]);
    if (i < (numberOfEntries - 1)) Serial.print("-");
  }
  Serial.println();
}
//--------------------------------------------
void saveRecord() {
  if (memFull == false) {
    numberOfEntries++;
    if (numberOfEntries >= maxEntries) memFull = true;
  }
  record[recordIndex] = c;
  if (recordIndex >= lastRecord)
    recordIndex = 0;
  else
    recordIndex++;

  orderIndex = maxEntries - recordIndex;

  printRecords();

}
//********************************************************
// ************* Routines for checking and ***************
// *************  reading Serial commands   **************
//********************************************************
void checkSerialCommand() {
  serialEvent();  // must be called to handle serial1 commands
  if (newCommand) {
    Serial.print("New Command: "); Serial.println(command);
    newCommand = 0;
    executeCommand();
    command = "";
  }
}
void executeCommand() {
  c = command.charAt(0);
  saveRecord();
}

void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read();
    Serial.print(inChar);
    // if the incoming character is a newline, set a flag so the main loop can
    // do something about it:
    if (inChar == '\n') {
      newCommand = true;
      break;
    }
    command += inChar;
  }
}