/* 
 *  cleaned variables
 *  added factory reset
 *  added potentiometer trimming
 */


 
#include <EEPROM.h>
#include <MIDI.h>
#include <LiquidCrystal.h>#
MIDI_CREATE_DEFAULT_INSTANCE();
LiquidCrystal lcd(2,3,4,5,6,7);

// Define inputs and outputs
const int button1Pin=8;   //PLAY
const int button2Pin=9;   //STOP
const int button3Pin=12;  //WRITE
const int button4Pin=11;  //F1
const int button5Pin=10;  //F2
const int clockInPin=13;  //CLOCK-IN

const int TempoCVPin = A0; // =Tempo potentiometer
const int CV1Pin = A1; // (5V or CV1-In) via CV1 potentiometer
const int CV2Pin = A2; // (5V or CV2-In) via CV2 potentiometer
const int clockOutPin = A5; //->sent via the clock-socket-switch to clockInPin


unsigned long CV1raw;
unsigned long CV2raw;
unsigned long TempoCVraw;


//Offset variables for the CV ins, for adopting to potentiometer variations
unsigned long maxOffTempoCV;
unsigned long maxOffCV1;
unsigned long maxOffCV2;

// Variables to handle the potentiometers
unsigned long CV1;
unsigned long CV2;
unsigned long TempoCV;

// Variables to handle the buttons and digital inputs
int button1State=0; 
int button2State=0; 
int button3State=0;
int button4State=0;
int button5State=0;
int clockInState=0;
int button1StatePrev=0;
int button2StatePrev=0;
int button3StatePrev=0;
int button4StatePrev=0;
int button5StatePrev=0;
int clockInStatePrev=0;

// Variable required for the clock generator
float BPMf=120;
int BPMi=0;
unsigned long tempo=0;
unsigned long tempoX=0;
unsigned long clocktime=1;
int clockOn=0;
int clockOff=1;

unsigned long thistime;
unsigned long triggertime;
unsigned long lasttriggertime;
int midiclockcounter=0; 
int clockfactor=1;


// Variables to handle the generic status of the software
int menu=0;
int edit=0;
int runmode=0; // 0=Stop, 1=Play
int writemode=0; // 1=Record Trigger, 2=Record Velocity
int writemodevalue=0;
int writeselect=0;
int maxmenu;
int adjuststep=0; //used for the poti adjustment procedure

// Variables for setup parameters

int triggersource=0;
int velocitymode=0;
int notethrumode=1;
int outchannel=1;
int inchannelvalue=0;
int inchannel=1;
int controlthrumode=1;
int programthrumode=0;
int bendthrumode=1;
int otherthrumode=0;
int chordtriggermode=1;
int clockmode=0;

// Variables for handling MIDI data
const int maxSteps=64;
const int maxNotes=12;
uint8_t note[maxNotes+1];
uint8_t outNote[maxNotes+1];
uint8_t t_step[maxSteps+1];
uint8_t v_step[maxSteps+1];
uint8_t velocity;
uint8_t chdata;

// Variables for sequence handling
int stepNumber=0; // Stepnumber while writing
int t_lastStep=0;
int t_stepNumber=0; // Trigger stepnumber while playing
int v_lastStep=0;
int v_stepNumber=0; // Velocity stepnumber while playing
int stepBack=0;
int stepLCDposition;
int noteInChord=0;
int keysPressed=0;
int keysPressedPrev;
int pause=0; // 0=normal play, 1=steps are counted, but no midi is sent
int waitEndOfPause=0;
int transpose=0;
int ontrigger=0;
int offtrigger=0;
int stepdisplay=0; // 0=triggersteps, 1=velocitysteps
uint8_t i=0;
uint8_t j=0;

void setup() {
  lcd.begin(16, 2);
  MIDI.begin();
  MIDI.setThruFilterMode(0);
  MIDI.turnThruOff();

  if (EEPROM.read(1) == 255) factoryreset(); 

  maxOffTempoCV=1;
  maxOffCV1=1;
  maxOffCV2=1;
  outchannel=1;
  inchannelvalue=1;

  triggersource=EEPROM.read(9);
  velocitymode=EEPROM.read(10);
  notethrumode=EEPROM.read(11);
  controlthrumode=EEPROM.read(12);
  programthrumode=EEPROM.read(13);
  bendthrumode=EEPROM.read(14);
  otherthrumode=EEPROM.read(15);
  chordtriggermode=EEPROM.read(16);
   
  pinMode(button1Pin, INPUT);
  pinMode(button2Pin, INPUT);
  pinMode(button3Pin, INPUT);
  pinMode(button4Pin, INPUT);
  pinMode(button5Pin, INPUT);
  pinMode(clockInPin, INPUT);
  pinMode(TempoCVPin, INPUT);
  pinMode(CV1Pin, INPUT);
  pinMode(CV2Pin, INPUT);
  pinMode(clockOutPin, OUTPUT);

  velocity=96;

  /* FIRMWARE VERSION */
  lcd.setCursor(0, 0); 
  lcd.print(F("ChordTrigger V7"));
  delay(1000);
  lcd.setCursor(0, 0);
  lcd.print(F("           "));  

  loadsequence();
  for( i=0 ; i <= maxNotes ; i++ ) {
    note[i]=128;
  }
  clearscreen();
        
}

void printstep (int step, char type) {
  if (menu == 0) {
   if (step == 0) {
      lcd.setCursor(step,1);
      lcd.print(F("                "));
   }
   lcd.setCursor(step,1);
   lcd.print(type);
  }
}


void midireset() {
   int i=0;
   for (i=0; i <= 126 ; i++) {
      MIDI.sendNoteOff(i,0,outchannel);
      delay(1);
   }
   MIDI.sendControlChange(123,0,outchannel);
}

void resetchord() {
  clockInStatePrev=0;
  for( i=0 ; i <= maxNotes ; i++ ) {
    MIDI.sendNoteOff(outNote[i],velocity,outchannel);
  } 
  for( i=0 ; i <= maxNotes ; i++ ) {
    note[i]=128;
  }
}

void clearscreen(){
   lcd.setCursor(0,0);
   lcd.print(F("                "));
   lcd.setCursor(0,1);
   lcd.print(F("                "));
}



void adjustpotis() {
   CV1raw=analogRead(CV1Pin) ;
   CV2raw=analogRead(CV2Pin) ;
   TempoCVraw=analogRead(TempoCVPin) ;

  if (adjuststep == 0) {
    while ((TempoCVraw + maxOffTempoCV) != 1023) {
      TempoCVraw=analogRead(TempoCVPin)+0.5 ;
      if ((TempoCVraw + maxOffTempoCV) < 1023) maxOffTempoCV++;
      if ((TempoCVraw + maxOffTempoCV) > 1023) maxOffTempoCV--;
      lcd.setCursor(0, 0);
      lcd.print("Tempo: ");
      lcd.print(TempoCVraw);
      lcd.print(" ");
      lcd.setCursor(0, 1);
      lcd.print("1023=");
      lcd.print(TempoCVraw + maxOffTempoCV);
      lcd.print(" ");
      lcd.print(maxOffTempoCV);
    }
    if ((TempoCVraw + maxOffTempoCV) == 1023 ) {
      clearscreen();
      lcd.setCursor(0, 0);
      lcd.print(F("Tempo is good!"));
      EEPROM.write(1,maxOffTempoCV);
      delay(1000);
      clearscreen();
      adjuststep=1;
    }
  }
         
  if (adjuststep == 1) {
    while ((CV1raw + maxOffCV1) != 1023) {
      CV1raw=analogRead(CV1Pin)+0.5 ;
      if ((CV1raw + maxOffCV1) < 1023) maxOffCV1++;
      if ((CV1raw + maxOffCV1) > 1023) maxOffCV1--;
      lcd.setCursor(0, 0);
      lcd.print("CV1: ");
      lcd.print(CV1raw);
      lcd.print(" ");
      lcd.setCursor(0, 1);
      lcd.print("1023=");
      lcd.print(CV1raw + maxOffCV1);
      lcd.print(" ");
      lcd.print(maxOffCV1);
    }
    if ((CV1raw + maxOffCV1) == 1023 ) {
      clearscreen();
      lcd.setCursor(0, 0);
      lcd.print(F("CV1 is good!"));
      EEPROM.write(2,maxOffCV1);
      delay(1000);
      clearscreen();
      adjuststep=2;
      }
    } 

  if (adjuststep == 2) {
    while ((CV2raw + maxOffCV2) != 1023) {
      CV2raw=analogRead(CV2Pin)+0.5 ;
      if ((CV2raw + maxOffCV2) < 1023) maxOffCV2++;
      if ((CV2raw + maxOffCV2) > 1023) maxOffCV2--;
      lcd.setCursor(0, 0);
      lcd.print("CV2: ");
      lcd.print(CV2raw);
      lcd.print(" ");
      lcd.setCursor(0, 1);
      lcd.print("1023=");
      lcd.print(CV2raw + maxOffCV2);
      lcd.print(" ");
      lcd.print(maxOffCV2);
    }
    if ((CV2raw + maxOffCV2) == 1023 ) {
      clearscreen();
      lcd.setCursor(0, 0);
      lcd.print(F("CV2 is good!"));
      EEPROM.write(3,maxOffCV2);
      delay(1000);
      clearscreen();
      adjuststep=0;
      edit=0;
    }
  } 
}

void factoryreset() {
   clearscreen();
   lcd.setCursor(0, 0); 
   lcd.print(F("Reset EEprom"));
   int i=0;
   for (i=0;i<31;i++) {
       EEPROM.write(i,255);
   } 
   i=0;
   for (i=31;i<255;i++) {
       EEPROM.write(i,0);
   }
   EEPROM.write(33,60);  //+
   EEPROM.write(34,60);  //+
   EEPROM.write(35,60);  //+
   EEPROM.write(36,60);  //+
   EEPROM.write(37,60);  //+
   EEPROM.write(38,129); //.
   EEPROM.write(39,70);  //+
   EEPROM.write(40,128); //-
   EEPROM.write(30,8); // t_laststep

   EEPROM.write(97,60);   //+
   EEPROM.write(98,129);  //.
   EEPROM.write(99,128);  //-
   EEPROM.write(31,3); // v_laststep


   EEPROM.write(1,90); //maxOffTempoCV
   EEPROM.write(2,100); //maxOffCV1
   EEPROM.write(3,100); //maxOffCV2   
   EEPROM.write(4,1); //outchannel
   EEPROM.write(5,1); //inchannelvalue
   
   EEPROM.write(9,0); //triggersource: 0=Sequence / 1=Clock
   EEPROM.write(10,0); //velocitymode: 0=Random(Clock) / 1=Sequenced
   EEPROM.write(11,1); //notethrumode: 0=Off / 1=Thru while stop
   EEPROM.write(12,1); //controlthrumode
   EEPROM.write(13,0); //programthrumode
   EEPROM.write(14,1); //bendthrumode
   EEPROM.write(15,0); //otherthrumode
   EEPROM.write(16,1); //chordtriggermode: 0=Played /1=Held

   maxOffTempoCV=EEPROM.read(1);
   maxOffCV1=EEPROM.read(2);
   maxOffCV2=EEPROM.read(3);
   outchannel=EEPROM.read(4);
   inchannelvalue=EEPROM.read(5);

   triggersource=EEPROM.read(9);
   velocitymode=EEPROM.read(10);
   notethrumode=EEPROM.read(11);
   controlthrumode=EEPROM.read(12);
   programthrumode=EEPROM.read(13);
   bendthrumode=EEPROM.read(14);
   otherthrumode=EEPROM.read(15);
   chordtriggermode=EEPROM.read(16);
   
   clearscreen();
   loadsequence();
}

void savesequence() {
   lcd.setCursor(1,1);
   lcd.print(F("               "));
   EEPROM.write(30,t_lastStep);
   EEPROM.write(31,v_lastStep);
   for (t_stepNumber=0; t_stepNumber < maxSteps; t_stepNumber++) {
     int address=(t_stepNumber + 32);
     EEPROM.write(address,t_step[t_stepNumber]);
     lcd.setCursor(1,1);
     lcd.print(address);
   }
   for (v_stepNumber=0; v_stepNumber < maxSteps; v_stepNumber++) {
     int address=(v_stepNumber + maxSteps + 1 + 32);
     EEPROM.write(address,v_step[v_stepNumber]);
     lcd.setCursor(1,1);
     lcd.print(address);
   }
   lcd.setCursor(1,1);
   lcd.print(F("DONE     "));  
}

void loadsequence() {
   lcd.setCursor(0,0);
   lcd.print(F("LOAD PATTERN"));
   t_lastStep=EEPROM.read(30);
   v_lastStep=EEPROM.read(31);

   for (t_stepNumber=0; t_stepNumber < maxSteps; t_stepNumber++) {
     int address=(t_stepNumber + 32);
     t_step[t_stepNumber]=EEPROM.read(address);
     lcd.setCursor(1,1);
     lcd.print(address);
   }
   for (v_stepNumber=0; v_stepNumber < maxSteps; v_stepNumber++) {
     int address=(v_stepNumber + maxSteps + 1 + 32);
     v_step[v_stepNumber]=EEPROM.read(address);
     lcd.setCursor(1,1);
     lcd.print(address);
   }


   lcd.setCursor(1, 1); 
   lcd.print(F("LOAD DONE      "));
   delay(1000);
   clearscreen();
}



void loop() {
  if (1==1) { //clockstuff
  /* READ BUTTONS */ 
  button1State=!digitalRead(button1Pin);
  button2State=!digitalRead(button2Pin);
  button3State=!digitalRead(button3Pin);
  button4State=!digitalRead(button4Pin);
  button5State=!digitalRead(button5Pin);

//ANZEIG
  
  CV1raw=analogRead(CV1Pin) ;
  CV2raw=analogRead(CV2Pin) ;
  TempoCVraw=analogRead(TempoCVPin) ;
  CV1=CV1raw - 1 + ((CV1raw + 1.0) / (1023.0 - maxOffCV1) * maxOffCV1 );
  CV2=CV2raw - 1 + ((CV2raw + 1.0) / (1023.0 - maxOffCV2) * maxOffCV2 );
  TempoCV=TempoCVraw + ((TempoCVraw + 1.0) / (1023.0 - maxOffTempoCV) * maxOffTempoCV );

   if (inchannelvalue == 0) {
     inchannel = outchannel;
   } else {
    inchannel = inchannelvalue;
   }


  
  /* GENERAT THE INTERNAL CLOCK */
  thistime=millis();
  BPMf=analogRead(TempoCVPin);
  BPMf=round(BPMf*0.24);
  BPMi=BPMf+1;
  tempoX=round(7500/BPMi);  
  //tempoX=round(110/BPMi);  
   
  if (clocktime + tempoX <= thistime && clockOn == 0) {
    clockOn=1;
    clocktime=thistime;
    digitalWrite(clockOutPin, HIGH);
      lcd.setCursor(15, 0);
      lcd.print(F("^"));
    
    clockOff=0;
  }
  if (clocktime + tempoX <= thistime && clockOff == 0) {
    clockOff=1;
    clocktime=thistime;
    digitalWrite(clockOutPin, LOW);
      lcd.setCursor(15, 0);
      lcd.print(F("v"));
    clockOn=0;
  }
  }
  
  /* TIE plus REST will switch to setup*/
  if (button4State == 1 && button4StatePrev == 0 && button5State == 1 && button5StatePrev == 0 && menu == 0) {
     button4StatePrev=1;
     button5StatePrev=1;
     clearscreen();
     menu=1;
  }
  if (button4State == 0 && button4StatePrev == 1 && button5State == 0 && button5StatePrev == 1) {
     button4StatePrev=0;
     button5StatePrev=0;
  }
   

  if (menu == 0) { //STOP-PLAY-WRITE

    /*BUTTONS IN STOP MODE*/  

    /* PLAY BUTTON IN STOP MODE*/
    if (button1State == 1 && button1StatePrev == 0 && runmode==0 && writemode == 0 && writeselect==0) { //PLAY
      button1StatePrev=1;
      runmode=1;
      t_stepNumber=0;
      v_stepNumber=0;
      writemode=0; 
      clearscreen();
      if (button2State == 0) t_stepNumber=0; // DO NOT RESET THE SEQUENCE IF LEAVING THE SETUP
      //lcd.setCursor(0, 0);
      //lcd.print(F("PLAY"));
    }
    if (button1State == 0 && button1StatePrev == 1)  button1StatePrev=0;
    
    /* WRITE BUTTON IN STOP MODE */
    if (button3State == 1 && button3StatePrev == 0 && runmode == 0 && writeselect==0 && writemode == 0) { //WRITE
      button3StatePrev=1;
      writeselect=1;
      stepNumber=0;
      clearscreen();
    }
    if (button3State == 0 && button3StatePrev == 1)  button3StatePrev=0;

    if (writeselect==1) {
      lcd.setCursor(0,0);
      lcd.print(F("F1=Trig F2=Vel"));
      
      if (button4State == 1 && button4StatePrev == 0) {
        button4StatePrev = 1;
      }
      if (button5State == 1 && button5StatePrev == 0) {
        button5StatePrev = 1;
      }
      
      if (button4State == 0 && button4StatePrev == 1)  {
        button4StatePrev=0;
        writeselect=0;
        writemode=1;
      }
      if (button5State == 0 && button5StatePrev == 1)  {
        button5StatePrev=0;
        writeselect=0;
        writemode=2;
      }    
    }
    

    /* BUTTONS IN PLAYMODE

    /* STOP BUTTON NOT IN WRITE MODE*/
    if (button2State == 1 && button2StatePrev == 0 && writemode == 0  && writeselect==0) { //STOP
      button2StatePrev=1;
      runmode=0;
      clockInStatePrev=1;
      clockInState=0;
      ontrigger=0;
      offtrigger=0;
      noteInChord=0;
      resetchord();
      midireset();
      keysPressed=0;
    }
    if (button2State == 0 && button2StatePrev == 1) button2StatePrev=0;

      
      
    /* F2 BUTTON IN PLAY MODE RESETS KEYSPRESSED TO REMOVE HANGING NOTES */
    if (button5State == 1 && button5StatePrev == 0 && runmode > 0 && writemode == 0  && writeselect==0) { 
      button5StatePrev=1;
      int chordtriggermodePrev=chordtriggermode;
      if (chordtriggermode == 0) chordtriggermode=1;
      if (chordtriggermode == 1 && chordtriggermodePrev == 1 ) chordtriggermode=0;
    }
    if (button5State == 0 && button5StatePrev == 1)  button5StatePrev=0;

    /* F1 BUTTON IN PLAY MODE TOGGLES STEPDISPLAY BETWEEN TRIGGER AND VELOCITY */
    if (button4State == 1 && button4StatePrev == 0 && runmode > 0 && writemode == 0  && writeselect==0) { 
      button4StatePrev=1;
      int stepdisplayPrev=stepdisplay;
      if (stepdisplay == 0) stepdisplay=1;
      if (stepdisplay == 1 && stepdisplayPrev == 1 ) stepdisplay=0;
    }
    if (button4State == 0 && button4StatePrev == 1)  button4StatePrev=0;
       
        
    /*STOP MODE*/
    if (runmode == 0 && writemode == 0  && writeselect==0) { 
      lcd.setCursor(0, 0);
      lcd.print(F("STOP "));
      
      /* MIDITHRU IN STOP MODE*/
      if (MIDI.read()) {
        byte type=MIDI.getType();
        switch (type) {
          case midi::NoteOn:
            MIDI.sendNoteOn(MIDI.getData1(),MIDI.getData2(),outchannel);
          break;
          case midi::NoteOff:
            MIDI.sendNoteOff(MIDI.getData1(),MIDI.getData2(),outchannel);
          break;
        }      
      }    /* END OF MIDITHRU IN STOP MODE */
    } //END OF STOP MODE


   /* WRITE */
  if (runmode == 0 && writemode > 0) { //WRITE
    if ( menu == 0 ) {
      lcd.setCursor(0, 0);
      if (writemode==1) lcd.print(F("WRITE T         "));  
      if (writemode==2) lcd.print(F("WRITE V         "));  
    }
    stepLCDposition=stepNumber % 16;
    /* WRITE NoteOn and NoteOff */
    if (MIDI.read()) { 
      byte type=MIDI.getType()  ;                  
      if ((type == midi::NoteOn) && (MIDI.getChannel() == inchannel)) {
        if (writemode == 1) t_step[stepNumber]=MIDI.getData1();
        if (writemode > 1) v_step[stepNumber]=MIDI.getData1();
        lcd.setCursor(13,0);
        lcd.print(stepNumber+1);
        lcd.print(F(" "));
        printstep(stepLCDposition,43); // Print a dot "+"
        stepNumber++;
      }
    }
    
    /* Write a TIE */
    if (button4State == 1 && noteInChord == 0 && button4StatePrev == 0 && button3State == 0) {
      if (writemode == 1) t_step[stepNumber]=128;
      if (writemode > 1) v_step[stepNumber]=128;
      button4StatePrev=1;
      lcd.setCursor(13,0);
      lcd.print(stepNumber+1);
      lcd.print(F(" "));
      printstep(stepLCDposition, 45); //print a "-"
      stepNumber++;
    }
    if (button4State == 0 && button4StatePrev == 1) button4StatePrev=0;

    /* Write a REST */
    if (button5State == 1 && noteInChord == 0 && button5StatePrev == 0) {
      if (writemode == 1) t_step[stepNumber]=129;
      if (writemode > 1) v_step[stepNumber]=129;
      button5StatePrev=1;
      //delay(2)
      lcd.setCursor(13,0);
      lcd.print(stepNumber+1);
      lcd.print(F(" "));
      printstep(stepLCDposition,46); // Print a "."
      stepNumber++;
    }
    if (button5State == 0 && button5StatePrev == 1) button5StatePrev=0;

    /* One Step Backward with WRITE */
    if (button3State == 1 && noteInChord == 0 && button3StatePrev == 0 && writemode == 1 && t_stepNumber > 0) {
      button3StatePrev=1;
      stepBack=1;
    }
    if (button3State == 0 && button3StatePrev == 1) button3StatePrev=0;

    if (stepBack == 1 ) {
      t_stepNumber--;
      printstep(stepLCDposition - 1, 32); //print a " "
      lcd.setCursor(13,0);
      lcd.print(stepNumber);
      lcd.print(F(" "));
      stepBack=0;
    }
    
    /* STOP or PLAY ends WRITE */
    if (button1State == 1 || button2State == 1 || stepNumber == maxSteps) { // end-write-condition
      if (stepNumber > 0 ) { 
        if (writemode == 1) t_lastStep=stepNumber;
        if (writemode > 1) v_lastStep=stepNumber;
      }
      writemode=0;
      clearscreen();
    } // end-write-condition
    
    if (stepNumber == maxSteps && writemode == 1) t_lastStep=stepNumber - 1;
    if (stepNumber == maxSteps && writemode > 1) v_lastStep=stepNumber - 1;
  } //if (runmode == 0 && writemode == 1)




    /* PLAY MODE */
    if (runmode == 1 && writemode == 0) {
      lcd.setCursor(0, 0);
      lcd.print(F("PLAY"));
      lcd.setCursor(5, 0);
      lcd.print(noteInChord);
      lcd.print(F(" "));
      lcd.print(keysPressed);
      lcd.print(F(" "));
       
      /* READ INCOMING MIDI */
      if (MIDI.read()) {
        byte type= MIDI.getType();
        switch (type) { 
          case midi::NoteOn:
            if (keysPressed == 0) {
              for( i=0 ; i <= maxNotes ; i++ ) {
                note[i]=128;
              }
              noteInChord=0;
            }
            note[noteInChord]=MIDI.getData1();
            if (noteInChord < maxNotes) {
              noteInChord++;
              keysPressed++;
            }
          break;
          
          case midi::NoteOff:
            if (noteInChord > 0) keysPressed--;
            if (keysPressed < 0) keysPressed=0; //it can happen by unlucky timing that we miss a noteOn, but get the noteOff
          break;
          /* UNTIL HERE WE READ THE CHORD, NOW SOME THRU THINGS AND MIDI CLOCK*/

          case midi::ControlChange: 
            if ( controlthrumode == 1) {
              MIDI.sendControlChange(MIDI.getData1(),MIDI.getData2(),outchannel); 
            }
          break;
          
          case midi::ProgramChange: 
            if ( programthrumode == 1) {
              MIDI.sendProgramChange(MIDI.getData1(),outchannel);
            }
          break; 
            
          case midi::PitchBend: 
            if ( bendthrumode == 1) {
              MIDI.sendPitchBend( (((MIDI.getData2() * 128) + MIDI.getData1() ) + 8192),outchannel);
            }
          break;
          
          case midi::Clock:
            if (midiclockcounter == 0) {
              if ((clockmode > 0) && (clockmode < 6)) digitalWrite(clockOutPin, HIGH);
            }
            if (midiclockcounter == ( 3 * clockfactor)) {
              if ((clockmode > 0) && (clockmode < 6)) digitalWrite(clockOutPin, LOW);
            }
            midiclockcounter++;          
            if (midiclockcounter == (6 * clockfactor)) {
              midiclockcounter=0;
            }
          break;
                        
          case midi::Stop:
            midiclockcounter=0;
            runmode=0;
          break;
        }
      } //END OF MIDI-READ




     /*  
      *   Read external trigger or clock respectively
      */
      //int triggermode=0; //0=chord 1=velocity
      
      clockInState=!digitalRead(clockInPin);
      if (clockInState == 1 && clockInStatePrev == 0) {
         // If this step-value is a note then ontrigger
         if ((t_step[t_stepNumber] < 128) && (triggersource==0)) ontrigger=1;
         if (triggersource==1) ontrigger=1;
         clockInStatePrev=1;
      }
      
      if (stepdisplay==0) { /* THIS "IF" IS TO DISABLE THE SECTION EASILY*/
        stepLCDposition=t_stepNumber % 16;
        if (t_step[t_stepNumber] < 128) {
          printstep(stepLCDposition,43); //print a "+"
        }
        if (t_step[t_stepNumber] == 128) {
          printstep(stepLCDposition,45); //print a "."
        }
        if (t_step[t_stepNumber] == 129) {
          printstep(stepLCDposition,46); //print a "-" 
        } 
        /*   
        lcd.setCursor(13,0);
        lcd.print(t_stepNumber+1);
        lcd.print(F(" "));
        */
      }
      
      if (stepdisplay==1) { /* THIS "IF" IS TO DISABLE THE SECTION EASILY*/
        stepLCDposition=v_stepNumber % 16;
        if (v_step[v_stepNumber] < 128) {
         printstep(stepLCDposition,43); //print a "+"
        }
        if (v_step[v_stepNumber] == 128) {
         printstep(stepLCDposition,45); //print a "."
        }
        if (v_step[v_stepNumber] == 129) {
         printstep(stepLCDposition,46); //print a "-" 
        } 
        /*  
        lcd.setCursor(13,0);         
        lcd.print(v_stepNumber+1);
        lcd.print(F(" "));
        */
      }
      
      if (clockInState == 0 && clockInStatePrev == 1) {
        // If the next step is a tie then do not send an offtrigger
        // If the next step is a pause or a new note then send an offtrigger
        if ((t_step[t_stepNumber + 1] != 128) && (triggersource==0)) offtrigger=1;
        if ((triggersource==1)) offtrigger=1;
        clockInStatePrev=0;
        t_stepNumber++;
        if (t_stepNumber == t_lastStep) t_stepNumber=0;
        v_stepNumber++;
        if (v_stepNumber == v_lastStep) v_stepNumber=0;
      }


      
      int center=(CV1 / 8);
      int range=(CV2 / 8);


      if ( ((chordtriggermode == 0) && (keysPressed >= 1)) || (chordtriggermode == 1)) {
        if (ontrigger == 1) {
          for ( i=0 ; i <= maxNotes ; i++ ) {
            if ( (note[i] < 127) && (note[i] > 12) ) {
              outNote[i]=note[i];
              if (velocitymode==0){
                velocity=((CV1 / 8) + (CV2 / 8));
              }
              if (velocitymode==1){
                velocity=(center - ( random(1,126) *  ((range+1)/128.0) ) / 2) + ((random(1,126) *  ((range+1)/128) ));
              }
              if (velocitymode==2){
                if (v_step[v_stepNumber] <  128) velocity=((CV1 / 8) + ((CV2 / 8)) / 1); // +
                if (v_step[v_stepNumber] == 129) velocity=(CV1 / 8); // .
                if (v_step[v_stepNumber] == 128) velocity=((CV1 / 8) + ((CV2 / 8) / 2)); // -
              }
              if (velocitymode==3){
                if (v_step[v_stepNumber] <  128) velocity=((CV1 / 8) + ((CV2 / 8)) / 1); // +
                if (v_step[v_stepNumber] == 129) velocity=((CV1 / 8) - ((CV2 / 8) / 2)); // .
                if (v_step[v_stepNumber] == 128) velocity=(CV1 / 8); // -
              }
              if (velocity < 1) velocity=1;
              if (velocity > 127) velocity=127;
              MIDI.sendNoteOn(note[i],velocity,outchannel);
              keysPressedPrev=1;
            }
          }
          ontrigger=0; 
        }
        if (offtrigger == 1) {
          for( i=0 ; i <= maxNotes ; i++ ) {
            MIDI.sendNoteOff(outNote[i],velocity,outchannel);
          }
          offtrigger=0; 
        }
      }
      if ((chordtriggermode == 0) && (keysPressed == 0) && (keysPressedPrev == 1)) {
          for( i=0 ; i <= maxNotes ; i++ ) {
            MIDI.sendNoteOff(outNote[i],velocity,outchannel);
          }
          keysPressedPrev=0;
      }

    /* WRITE BUTTON IN PLAY MODE - TOGGLES chord mode*/
    if (button3State == 1 && button3StatePrev == 0 && chordtriggermode == 0) { 
      button3StatePrev=1;
      chordtriggermode=1;
    }
    if (button3State == 1 && button3StatePrev == 0 && chordtriggermode == 1) { 
      button3StatePrev=1;
      chordtriggermode=0;
    }
    if (button3State == 0 && button3StatePrev == 1)  {
      button3StatePrev=0;
    }

      
    } //END OF RUNMODE
  }// END OF MENU==0




  /*========HERE BEGINS THE SETUP SECTION========*/
  if (menu > 0 ) { //SETUP
      lcd.setCursor(0,1);
      if (edit == 0) lcd.print(F(" ")); 
      if (edit == 1) lcd.print(F("!")); 

      /* STOP+PLAY exits the setup */
      if ( button1State == 1 && button1StatePrev == 0 && button2State == 1 && button2StatePrev == 0 && menu > 0 && edit == 0) { 
         button1StatePrev = 1;
         button2StatePrev = 1;
         clearscreen();
         lcd.setCursor(0, 0); 
         if (runmode == 0) lcd.print(F("STOP "));
         if (runmode == 1) lcd.print(F("PLAY"));
         menu=0;
      }

      
       /*
       * Stepping thru the setup menu
       */ 
      
      maxmenu=15; // MAXMENU DETERMINES HOW MANY MENU PAGES ARE AVAILABLE 
         
      if (edit == 0) {
         if (button4State == 1 && button4StatePrev == 0) { // SCROLL THRU MENU DOWN
            button4StatePrev=1; 
            clearscreen();
            menu--;
            if (menu < 1) menu=maxmenu;
         }

         if (button4State == 0 && button4StatePrev == 1) {
            button4StatePrev=0;
         }
         
         if (button5State == 1 && button5StatePrev == 0) { // SCROLL THRU MENU UP
            button5StatePrev=1;
            clearscreen();
            menu++;
            if (menu > maxmenu) menu = 1;
         }
         if (button5State == 0 && button5StatePrev == 1) {
            button5StatePrev=0;
         }
         
         if (button3State == 1 && button3StatePrev == 0) { // ENTER EDIT MODE
            button3StatePrev=1;
            if (menu == 15 && runmode == 1) {
              lcd.setCursor(1, 1); 
              lcd.print(F("Not while Play"));              
            } else {
              edit=1;           
            }
         }
         if (button3State == 0 && button3StatePrev == 1) {
            button3StatePrev=0;
         }
      }
        /*PLAYMODE,ChordPlayMode,TriggerMode,VelocityMode,OutChannel,InChannel,NoteThru,ControlThru,ProgrammThru,BendTHru,OtherChannelThru,TrimmPotis,FactoryReset,LoadSequence,SaveSequence,ClockSelect};
         *0        1         2           3            4          5         6        7           8            9        10               11         12           13          ,14          ,15
        */
      switch (menu) {
        case 1: //CHORDPLAYMODE
           lcd.setCursor(0, 0); 
           lcd.print(F("CHORDPLAY-MODE"));
           lcd.setCursor(1, 1); 
           if (chordtriggermode==0) lcd.print(F("Keyed       "));
           if (chordtriggermode==1) lcd.print(F("Held        "));
           if (edit == 1) {
              if (button4State == 1 && button4StatePrev == 0) { //DECREASE TRANSPOSE MODE
                 button4StatePrev=1;
                 if (chordtriggermode > 0) chordtriggermode--;
              }
              if (button4State == 0 && button4StatePrev == 1) {
                 button4StatePrev=0;
              }
      
              if (button5State == 1 && button5StatePrev == 0) { //INCREASE TRANSPOSE MODE
                 button5StatePrev=1;
                 if (chordtriggermode < 1) chordtriggermode++;
              }
              if (button5State == 0 && button5StatePrev == 1) {
                 button5StatePrev=0;
              }
              
              if (button3State == 1 && button3StatePrev == 0) { 
                 button3StatePrev=1;
                 EEPROM.write(16,chordtriggermode);
                 //delay(10);
                 edit=0;
              }
              if (button3State == 0 && button3StatePrev == 1) {
                 button3StatePrev=0;
              }
           }                      
        break;

        case 2: //TRIGGERMODE
           lcd.setCursor(0, 0); 
           lcd.print(F("TRIGGER-SOURCE"));
           lcd.setCursor(1, 1); 
           if (triggersource==1) lcd.print(F("Clock   "));
           if (triggersource==0) lcd.print(F("Pattern"));
           if (edit == 1) {
              if (button4State == 1 && button4StatePrev == 0) { //DECREASE NOTEOFFMODE
                 button4StatePrev=1;
                 if (triggersource > 0) triggersource--;
              }
              if (button4State == 0 && button4StatePrev == 1) {
                 button4StatePrev=0;
              }
      
              if (button5State == 1 && button5StatePrev == 0) { //INCREASE NOTEOFFMODE
                 button5StatePrev=1;
                 if (triggersource < 1) triggersource++;
              }
              if (button5State == 0 && button5StatePrev == 1) {
                 button5StatePrev=0;
              }
              if (button3State == 1 && button3StatePrev == 0) { 
                 button3StatePrev=1;
                 EEPROM.write(9,triggersource);
                 //delay(10);
                 edit=0;
              }
              if (button3State == 0 && button3StatePrev == 1) {
                 button3StatePrev=0;
              }
           }                      
        break;

        case 3://VELOCITYMODE
           lcd.setCursor(0, 0); 
           lcd.print(F("VELOCITY-MODE"));
           lcd.setCursor(1, 1);
           if (velocitymode==0) lcd.print(F("Constant   "));
           if (velocitymode==1) lcd.print(F("Random     "));
           if (velocitymode==2) lcd.print(F("Pattern 0/+"));
           if (velocitymode==3) lcd.print(F("Pattern -/+"));
           if (edit == 1) {
              if (button4State == 1 && button4StatePrev == 0) { //DECREASE NOTEOFFMODE
                 button4StatePrev=1;
                 if (velocitymode > 0) velocitymode--;
              }
              if (button4State == 0 && button4StatePrev == 1) {
                 button4StatePrev=0;
              }
      
              if (button5State == 1 && button5StatePrev == 0) { //INCREASE NOTEOFFMODE
                 button5StatePrev=1;
                 if (velocitymode < 4) velocitymode++;
              }
              if (button5State == 0 && button5StatePrev == 1) {
                 button5StatePrev=0;
              }
              if (button3State == 1 && button3StatePrev == 0) { 
                 button3StatePrev=1;
                 EEPROM.write(10,velocitymode);
                 //delay(10);
                 edit=0;
              }
              if (button3State == 0 && button3StatePrev == 1) {
                 button3StatePrev=0;
              }
           }                      
        break;
            
        case 4://OUTCHANNEL
           lcd.setCursor(0, 0); 
           lcd.print(F("OUTPUT CHANNEL"));
           lcd.setCursor(1, 1);
           //String stringChannel=String(outchannel);
           //stringChannel=stringChannel + "           ";
           lcd.print(outchannel);
           if (edit == 1) {
              if (button4State == 1 && button4StatePrev == 0) { //DECREASE CHANNEL
                 button4StatePrev=1;
                 if (outchannel > 1) outchannel--;
                 lcd.setCursor(1, 1); 
                 lcd.print(F("      "));
                 lcd.setCursor(1, 1); 
                 lcd.print(outchannel);                 

              }
              if (button4State == 0 && button4StatePrev == 1) {
                 button4StatePrev=0;
              }
      
              if (button5State == 1 && button5StatePrev == 0) { //INCREASE CHANNEL
                 button5StatePrev=1;
                 if (outchannel < 16) outchannel++;
                 lcd.setCursor(1, 1); 
                 lcd.print(F("      "));
                 lcd.setCursor(1, 1); 
                 lcd.print(outchannel);              }
              if (button5State == 0 && button5StatePrev == 1) {
                 button5StatePrev=0;
              }
              if (button3State == 1 && button3StatePrev == 0) { 
                 button3StatePrev=1;
                 EEPROM.write(4,outchannel);
                 delay(10);
                 edit=0;
              }
              if (button3State == 0 && button3StatePrev == 1) {
                 button3StatePrev=0;
              }
           }                      
        break;

        case 5://INCHANNEL
           lcd.setCursor(0, 0); 
           lcd.print(F("INPUT CHANNEL"));
           lcd.setCursor(1, 1);
           lcd.print(inchannelvalue);
           if (edit == 1) {
              if (button4State == 1 && button4StatePrev == 0) { //DECREASE CHANNEL
                 button4StatePrev=1;
                 if (inchannelvalue > 0) inchannelvalue--;
                 lcd.setCursor(1, 1); 
                 lcd.print(F("      "));
                 lcd.setCursor(1, 1); 
                 lcd.print(inchannelvalue);              }
              if (button4State == 0 && button4StatePrev == 1) {
                 button4StatePrev=0;
              }
      
              if (button5State == 1 && button5StatePrev == 0) { //INCREASE CHANNEL
                 button5StatePrev=1;
                 if (inchannelvalue < 16) inchannelvalue++;
                 lcd.setCursor(1, 1); 
                 lcd.print(F("      "));
                 lcd.setCursor(1, 1); 
                 lcd.print(inchannelvalue);              }
              if (button5State == 0 && button5StatePrev == 1) {
                 button5StatePrev=0;
              }
              if (button3State == 1 && button3StatePrev == 0) { 
                 button3StatePrev=1;
                 EEPROM.write(5,inchannelvalue);
                 delay(10);
                 edit=0;
              }
              if (button3State == 0 && button3StatePrev == 1) {
                 button3StatePrev=0;
              }
           }                      
        break;

        case 6: //NOTETHRU
           lcd.setCursor(0, 0); 
           lcd.print(F("NOTE-THRU-MODE"));
           lcd.setCursor(1, 1);
           if (notethrumode == 0) lcd.print(F("Off           ")); 
           if (notethrumode == 1) lcd.print(F("Thru while Stop")); 
           if (edit == 1) {
              if (button4State == 1 && button4StatePrev == 0) { //DECREASE MIDI-THRU-MODE
                 button4StatePrev=1;
                 if (notethrumode > 0) notethrumode--;
              }
              if (button4State == 0 && button4StatePrev == 1) {
                 button4StatePrev=0;
              }
              if (button5State == 1 && button5StatePrev == 0) { //INCREASE MIDI-THRU-MODE
                 button5StatePrev=1;
                 if (notethrumode < 1) notethrumode++;
              }
              if (button5State == 0 && button5StatePrev == 1) {
                 button5StatePrev=0;
              }
              
              if (button3State == 1 && button3StatePrev == 0) { 
                 button3StatePrev=1;
                 EEPROM.write(11,notethrumode);
                 delay(10);
                 edit=0;
              }
              if (button3State == 0 && button3StatePrev == 1) {
                 button3StatePrev=0;
              }
           }                      
        break;

        case 7: //CONTROLTHRU
           lcd.setCursor(0, 0); 
           lcd.print(F("CTRL-THRU-MODE"));
           lcd.setCursor(1, 1);
           if (controlthrumode == 0) lcd.print(F("Off")); 
           if (controlthrumode == 1) lcd.print(F("On ")); 
           if (edit == 1) {
              if (button4State == 1 && button4StatePrev == 0) { //DECREASE MIDI-THRU-MODE
                 button4StatePrev=1;
                 if (controlthrumode > 0) controlthrumode--;
              }
              if (button4State == 0 && button4StatePrev == 1) {
                 button4StatePrev=0;
              }
              if (button5State == 1 && button5StatePrev == 0) { //INCREASE MIDI-THRU-MODE
                 button5StatePrev=1;
                 if (controlthrumode < 1) controlthrumode++;
              }
              if (button5State == 0 && button5StatePrev == 1) {
                 button5StatePrev=0;
              }
              
              if (button3State == 1 && button3StatePrev == 0) { 
                 button3StatePrev=1;
                 EEPROM.write(12,controlthrumode);
                 delay(10);
                 edit=0;
              }
              if (button3State == 0 && button3StatePrev == 1) {
                 button3StatePrev=0;
              }
           }                      
        break;

        case 8: //PROGRAM
           lcd.setCursor(0, 0); 
           lcd.print(F("PRG-THRU-MODE"));
           lcd.setCursor(1, 1); 
           //lcd.print(onoffmodename[programthrumode]);          
           if (programthrumode == 0) lcd.print(F("Off")); 
           if (programthrumode == 1) lcd.print(F("On ")); 
           if (edit == 1) {
              if (button4State == 1 && button4StatePrev == 0) { //DECREASE MIDI-THRU-MODE
                 button4StatePrev=1;
                 if (programthrumode > 0) programthrumode--;
              }
              if (button4State == 0 && button4StatePrev == 1) {
                 button4StatePrev=0;
              }
              if (button5State == 1 && button5StatePrev == 0) { //INCREASE MIDI-THRU-MODE
                 button5StatePrev=1;
                 if (programthrumode < 1) programthrumode++;
              }
              if (button5State == 0 && button5StatePrev == 1) {
                 button5StatePrev=0;
              }
              
              if (button3State == 1 && button3StatePrev == 0) { 
                 button3StatePrev=1;
                 EEPROM.write(13,programthrumode);
                 delay(10);
                 edit=0;
              }
              if (button3State == 0 && button3StatePrev == 1) {
                 button3StatePrev=0;
              }
           }                      
        break;

        case 9: //BENDER
           lcd.setCursor(0, 0); 
           lcd.print(F("BEND-THRU-MODE"));
           lcd.setCursor(1, 1); 
           if (bendthrumode == 0) lcd.print(F("Off")); 
           if (bendthrumode == 1) lcd.print(F("On ")); 
           if (edit == 1) {
              if (button4State == 1 && button4StatePrev == 0) { //DECREASE MIDI-THRU-MODE
                 button4StatePrev=1;
                 if (bendthrumode > 0) bendthrumode--;
              }
              if (button4State == 0 && button4StatePrev == 1) {
                 button4StatePrev=0;
              }
              if (button5State == 1 && button5StatePrev == 0) { //INCREASE MIDI-THRU-MODE
                 button5StatePrev=1;
                 if (bendthrumode < 1) bendthrumode++;
              }
              if (button5State == 0 && button5StatePrev == 1) {
                 button5StatePrev=0;
              }
              
              if (button3State == 1 && button3StatePrev == 0) { 
                 button3StatePrev=1;
                 EEPROM.write(14,bendthrumode);
                 delay(10);
                 edit=0;
              }
              if (button3State == 0 && button3StatePrev == 1) {
                 button3StatePrev=0;
              }
           }                      
        break;

        case 10: //OTHER-CHANNELS-THRU
           lcd.setCursor(0, 0); 
           lcd.print(F("OTHER-CH-THRU"));
           lcd.setCursor(1, 1);
           if (otherthrumode == 0) lcd.print(F("Off")); 
           if (otherthrumode == 1) lcd.print(F("On ")); 
           if (edit == 1) {
              if (button4State == 1 && button4StatePrev == 0) { //DECREASE MIDI-THRU-MODE
                 button4StatePrev=1;
                 if (otherthrumode > 0) otherthrumode--;
              }
              if (button4State == 0 && button4StatePrev == 1) {
                 button4StatePrev=0;
              }
              if (button5State == 1 && button5StatePrev == 0) { //INCREASE MIDI-THRU-MODE
                 button5StatePrev=1;
                 if (otherthrumode < 4) otherthrumode++;
              }
              if (button5State == 0 && button5StatePrev == 1) {
                 button5StatePrev=0;
              }
              
              if (button3State == 1 && button3StatePrev == 0) { 
                 button3StatePrev=1;
                 EEPROM.write(15,otherthrumode); 
                 edit=0;
              }
              if (button3State == 0 && button3StatePrev == 1) {
                 button3StatePrev=0;
              }
           }                      
        break;

        case 11: //POTENTIOMETER ADJUSTMENT
           if (edit == 0) {
              lcd.setCursor(0, 0); 
              lcd.print(F("ADJUST POTI-CVs"));
              lcd.setCursor(1, 1); 
              lcd.print(F("PRESS WRITE")); 
           }          
         
           if (edit == 1) {
             lcd.setCursor(0, 0); 
             lcd.print(F("SET POTIS TO MAX"));
             lcd.setCursor(1, 1); 
             lcd.print(F("THEN PRESS WRITE")); 
             if (button3State == 1 && button3StatePrev == 0) {
               button3StatePrev=1;
               clearscreen();
               adjuststep=0;
               adjustpotis();
               edit=0;
               clearscreen();
             }
             if (button3State == 0 && button3StatePrev == 1) {
              button3StatePrev=0;
             }
        }

        break;
        
        case 12: //FACTORY RESET
           if (edit == 0) {
              lcd.setCursor(0, 0); 
              lcd.print(F("FACTORY RESET"));
              lcd.setCursor(1, 1); 
              lcd.print(F("PRESS 2xWRITE"));          
           }
           if (edit == 1) {
              lcd.setCursor(0, 0); 
              lcd.print(F("RESET:PRESS WRITE"));
              lcd.setCursor(1, 1); 
              lcd.print(F("STOP TO CANCEL"));          
              if (button3State == 1 && button3StatePrev == 0) {
                 runmode = 0;
                 button3StatePrev=1;
                 factoryreset();
                 delay(10);
                 edit=0;
                 clearscreen();
                 menu=0;          
              }
              if (button3State == 0 && button3StatePrev == 1) {
                 button3StatePrev=0;
              }
              if (button2State == 1 && button2StatePrev == 0 && menu > 0) { 
                  button2StatePrev=1;
              }
              if (button2State == 0 && button2StatePrev == 1 && menu > 0) {
                 button2StatePrev=0;
                 clearscreen();
                 edit=0;
              }
           }                      
        break;


        case 13: //LOAD
           if (edit == 0) {
              lcd.setCursor(0, 0); 
              lcd.print(F("LOAD PATTERN"));
              lcd.setCursor(1, 1); 
              lcd.print(F("PRESS 2xWRITE"));
           }
           if (edit == 1) {
              lcd.setCursor(0, 0); 
              lcd.print(F("LOAD PRESS WRITE"));
              lcd.setCursor(1, 1); 
              lcd.print(F("STOP FOR CANCEL"));          
              if (button3State == 1 && button3StatePrev == 0) {
                 runmode = 0;
                 button3StatePrev=1;
                 loadsequence();
                 delay(10);
                 edit=0;
                 clearscreen();
                 menu=0;          
              }
              if (button3State == 0 && button3StatePrev == 1) {
                 button3StatePrev=0;
              }
              if (button2State == 1 && button2StatePrev == 0 && menu > 0) { 
                  button2StatePrev=1;
              }
              if (button2State == 0 && button2StatePrev == 1 && menu > 0) {
                 button2StatePrev=0;
                 clearscreen();
                 edit=0;
              }
           }                      
        break;

        case 14: //SAVE SEQUENCE
           if (edit == 0) {        
              lcd.setCursor(0, 0); 
              lcd.print(F("SAVE PATTERN"));
              lcd.setCursor(1, 1); 
              lcd.print(F("PRESS 2xWRITE"));
           }          
           if (edit == 1) {
              lcd.setCursor(0, 0); 
              lcd.print(F("SAVE PRESS WRITE"));
              lcd.setCursor(1, 1); 
              lcd.print(F("STOP FOR CANCEL"));          
              if (button3State == 1 && button3StatePrev == 0) { 
                 button3StatePrev=1;
                 savesequence();
                 edit=0;
                 lcd.setCursor(1, 1); 
                 lcd.print(F("SAVE DONE    "));
                 if (runmode == 0) delay(500);
                 clearscreen();
                 menu=0;          
              }
              if (button3State == 0 && button3StatePrev == 1) {
                 button3StatePrev=0;
              }
              if (button2State == 1 && button2StatePrev == 0 && menu > 0) { 
                  button2StatePrev=1;
              }
              if (button2State == 0 && button2StatePrev == 1 && menu > 0) {
                 button2StatePrev=0;
                 clearscreen();
                 edit=0;
              }
           }                      
        break;
        
        case 15: //CLOCK SELECT
           lcd.setCursor(0, 0); 
           lcd.print(F("CLOCK"));
           lcd.setCursor(1, 1); 
           if (clockmode == 0) lcd.print(F("Internal       ")); 
           if (clockmode == 1) {
            lcd.print(F("MIDI-Clock 1/16"));
            clockfactor=1;
           }
           if (clockmode == 2) {
            lcd.print(F("MIDI-Clock  1/8"));
            clockfactor=2;
           }
           if (clockmode == 3) {
            lcd.print(F("MIDI-Clock  1/4"));
            clockfactor=4;
           }
           if (clockmode == 4) {
            lcd.print(F("MIDI-Clock  1/1"));                      
            clockfactor=16;
           }
           if (clockmode == 5) {
            lcd.print(F("MIDI-Clock  2/1"));                      
            clockfactor=32;
           }
           if (clockmode == 6) lcd.print(F("MIDI Start/Stop")); 
           if (edit == 1) {
              if (button4State == 1 && button4StatePrev == 0) { //DECREASE MIDI-THRU-MODE
                 if (clockmode > 0) clockmode--;
                 button4StatePrev=1;              }
              if (button4State == 0 && button4StatePrev == 1) {
                 button4StatePrev=0;
              }
              if (button5State == 1 && button5StatePrev == 0) { //INCREASE MIDI-THRU-MODE
                 if (clockmode < 6) clockmode++;
                 button5StatePrev=1;
              }
              if (button5State == 0 && button5StatePrev == 1) {
                 button5StatePrev=0;
              }
              
              if (button3State == 1 && button3StatePrev == 0) { 
                 button3StatePrev=1;
                 edit=0;
              }
              if (button3State == 0 && button3StatePrev == 1) {
                 button3StatePrev=0;
              }
           }                      
        break;

     } // END OF SWITCH:CASE
  }  // END OF SETUP  
    
} // EndOfLoop
