//
// Programmer:    Craig Stuart Sapp <craig@ccrma.stanford.edu>
// Creation Date: Wed Apr 20 20:47:40 PDT 2011
// Last Modified: Sun Jan  8 18:58:40 PST 2012 (added -s option)
// Filename:      ...sig/examples/all/noficta.cpp
// Web Address:   http://sig.sapp.org/examples/museinfo/humdrum/noficta.cpp
// Syntax:        C++; museinfo
//
// Description:   Remove ficta marks from **kern data
//

#include "humdrum.h"
#include "PerlRegularExpression.h"

#include <string.h>

#ifndef OLDCPP
   #include <iostream>
   using namespace std;
#else
   #include <iostream.h>
#endif


// function declarations
void      checkOptions(Options& opts, int argc, char* argv[]);
void      example(void);
void      usage(const char* command);
void      getFictaChar(char* ficta, HumdrumFile& infile);
void      processFile(HumdrumFile& infile);
void      processFileSuppress(HumdrumFile& infile);
void      processFileSwitch(HumdrumFile& infile);
void      removeFicta(HumdrumFile& infile, int line, int spine, 
                              const char* ficta);
void      removeFictaSuppress(HumdrumFile& infile, int line, int spine, 
                              const char* ficta);
void      processNote(HumdrumFile& infile, int i, int j, 
                              Array<int>& diatonicstate);
void      processTrack(int ttrack, HumdrumFile& infile);
void      parseKeySignature(Array<int>& keysig, const char* keyinfo);

// global variables:
Options   options;            // database for command-line arguments
int       numinputs;          // the total number of input files
int       debugQ    = 0;      // used with --debug option
int       suppressQ = 0;      // used with -S option
int       switchQ   = 0;      // used with -s option
char      FICTA[1024] = {0};  // used with getFictaChar().
const char* Tiehead = "";     // used for keeping track musica ficta on
                              // tied notes
int       Notecounter = 0; 

//////////////////////////////////////////////////////////////////////////

int main(int argc, char** argv) {
   HumdrumFile infile;

   // process the command-line options
   checkOptions(options, argc, argv);

   // figure out the number of input files to process
   numinputs = options.getArgCount();
 
   const char* filename = "";

   for (int i=0; i<numinputs || i==0; i++) {
      infile.clear();

      // if no command-line arguments read data file from standard input
      if (numinputs < 1) {
         filename = "";
         infile.read(cin);
      } else {
         filename = options.getArg(i+1);
         infile.read(filename);
      }
      if (strcmp(FICTA, "") == 0) {
         getFictaChar(FICTA, infile);
      }
      if (suppressQ) {
         processFileSuppress(infile);
      } else if (switchQ) {
         processFileSwitch(infile);
      } else {
         processFile(infile);
      }
     
   }

   return 0;
}

//////////////////////////////////////////////////////////////////////////



//////////////////////////////
//
// processFileSuppress --
//

void processFileSuppress(HumdrumFile& infile) {
   int i, j;
   if (strcmp(FICTA, "") == 0) {
      getFictaChar(FICTA, infile);
   }
   PerlRegularExpression pre;
   
   for (i=0; i<infile.getNumLines(); i++) {
      if (!infile[i].isData()) {
         continue;
      }
      for (j=0; j<infile[i].getFieldCount(); j++) {
         if (!infile[i].isExInterp(j, "**kern")) {
            continue;
         }
         if (strstr(infile[i][j], FICTA) == NULL) {
            continue;
         }
         removeFictaSuppress(infile, i, j, FICTA);
      }
   }
   cout << infile;
}



//////////////////////////////
//
// processFileNotationHide --
//

void processFileSwitch(HumdrumFile& infile) {
   int i;
   char ficta[1024] = {0};
   getFictaChar(ficta, infile);
   PerlRegularExpression pre;

   Array<int> ktracks;
   infile.getTracksByExInterp(ktracks, "**kern");

   for (i=0; i<ktracks.getSize(); i++) {
      if (debugQ) {
         cout << "!!PROCESSING TRACK " << ktracks[i] << endl;
      }
      processTrack(ktracks[i], infile);
   }

   cout << infile;
}



//////////////////////////////
//
// processTrack --  currently assuming that editorial accidentals
//     are not found in chords.  
//

void processTrack(int ttrack, HumdrumFile& infile) {
   int i, j;
   int ptrack;
   PerlRegularExpression pre;
   Array<int> diatonicstate;
   diatonicstate.setSize(7);
   diatonicstate.setAll(0);
   Tiehead = "";
   Notecounter = 0;

   Array<int> keysignature;
   keysignature.setSize(7);
   keysignature.setAll(0);
   
   for (i=0; i<infile.getNumLines(); i++) {
      if (debugQ) {
         cout << "!!Processing line " << i+1 << " : " << infile[i] << endl;
      }
      if (infile[i].isMeasure()) {
         diatonicstate = keysignature;
         Notecounter = 0;
         continue;
      }
      if (!(infile[i].isData() || infile[i].isInterpretation())) {
         continue;
      }
      if (infile[i].isInterpretation()) {
         for (j=0; j<infile[i].getFieldCount(); j++) {
            ptrack = infile[i].getPrimaryTrack(j);
            if (ptrack != ttrack) {
               continue;
            }
            if (pre.search(infile[i][j], "^\\*k\\[(.*?)\\]")) {
               parseKeySignature(keysignature, pre.getSubmatch(1));
               if (debugQ) {
                  cout << "!! Found keysignature on line " << i+1 
                       << ": " << keysignature << endl;
               }
            }
            
         }
      } else if (infile[i].isData()) {
         for (j=0; j<infile[i].getFieldCount(); j++) {
            ptrack = infile[i].getPrimaryTrack(j);
            if (ptrack != ttrack) {
               continue;
            }
            processNote(infile, i, j, diatonicstate);
         }
      }
   }
}



//////////////////////////////
//
// processNote -- presumes not in a chord!  Also presuming octave 
// equivalence for accidental states.
//

void processNote(HumdrumFile& infile, int i, int j, Array& diatonicstate) {
   if (strcmp(infile[i][j], ".") == 0) {
      // ignore null tokens
      return;
   }
   if (strchr(infile[i][j], 'r') != NULL) {
      // ignore rests
      return;
   }

   int diatonic   = Convert::kernToDiatonicPitchClassNumeric(infile[i][j]);
   int accidental = Convert::kernToDiatonicAlteration(infile[i][j]);

   //if ((strcmp(Tiehead, "") != 0) && ((strchr(infile[i][j], ']') != NULL) ||
   //      (strchr(infile[i][j], '_') != NULL))) {
   if ((Notecounter == 0) && ((strchr(infile[i][j], ']') != NULL) ||
         (strchr(infile[i][j], '_') != NULL))) {

      // Have a tied note which started with a pitch which used to have
      // and editorial accidental.  Match the chromatic pitch of the 
      // prevailing diatonic state.
      
      // int accidentalT = Convert::kernToDiatonicAlteration(Tiehead);
      // int diatonicT   = Convert::kernToDiatonicPitchClassNumeric(Tiehead);

      PerlRegularExpression preT;
      Array<char> dataT;
      dataT.setSize(strlen(infile[i][j])+1);
      strcpy(dataT.getBase(), infile[i][j]);

      int differenceT = diatonicstate[diatonic] - accidental;
      int base40T = Convert::kernToBase40(dataT.getBase());
      base40T += differenceT; 

      char pitchbuffer[64] = {0};
      Convert::base40ToKern(pitchbuffer, base40T);
   
      PerlRegularExpression preZ;
      preZ.sar(dataT, "[A-G]+[n#-]*", pitchbuffer, "i");
      preZ.sar(dataT, "n", "", ""); // don't need/want natural sign
      preZ.sar(dataT, FICTA, "", ""); // don't keep editorial accidental

      infile[i].changeField(j, dataT.getBase());

      // diatonicstate[diatonicT] = accidentalT;

      if (strchr(infile[i][j], ']') != NULL) {
         Tiehead = "";
      }

      return;
   }

   // Tiehead should no longer be needed, so set it to empty
   Tiehead = "";
   Notecounter++;

   if (debugQ) {
      cout << "!!Diatonicstate: " << diatonicstate << endl;
   }

   if (debugQ) {
      cout << "!!kern = " << infile[i][j] << " DIATONIC : " << diatonic 
           << "\taccidental: " << accidental << endl;
   }

   if (strstr(infile[i][j], FICTA) == NULL) {
      // update the diatonic state if no editorial accidental
      diatonicstate[diatonic] = accidental;
      if (debugQ) {
         cout << "!!UPDATING DIATONIC STATE for " << diatonic
              << " to " << diatonicstate[diatonic] << endl;
         cout << "!!\t" << diatonicstate << endl;
      } 
      return;
   }

   // at this point there is an editorial accidental.  The accidental
   // must be changed so that it is not printed in the score (with a 
   // score writing program which uses modern accidental syles).

   Array<char> data;
   data.setSize(strlen(infile[i][j])+1);
   strcpy(data.getBase(), infile[i][j]);

   PerlRegularExpression pre;

   if (accidental == diatonicstate[diatonic]) {
      // the editorial accidental matches the current diatonic
      // state.  This is desirable for hiding in printed music,
      // since an accidental will not be printed into the notation, 
      // so just get rid of the editorial accidental marker.
      pre.sar(data, FICTA, "", "");
   } else {
      // the editorial accidental does not match the current
      // diatonic state.  This is undesirable, since the notation
      // program will print a correcting accididental.  So insert the
      // current accidental for that diatonic pitch class and then
      // remove the editorial accidental marker.
      int difference = diatonicstate[diatonic] - accidental;
      int base40 = Convert::kernToBase40(data.getBase());
      base40 += difference; 
      char outbuffer[64] = {0};
      Convert::base40ToKern(outbuffer, base40);

      if (debugQ) {
         cout << "!!ACCIDENTAL = " << accidental << endl;
         cout << "!!DIATONIC = " << diatonic << endl;
         cout << "!!DIATONIC STATE = " << diatonicstate[diatonic] << endl;
         cout << "!!DIFFERENCE = " << difference << endl;
         cout << "!!GOING to convert " << data.getBase() 
              << " TO " << outbuffer << endl;
      }
      pre.sar(data, "[A-G]+[n#-]*", outbuffer, "i");
   }

   pre.sar(data, "n", "", ""); // don't need/want natural sign
   pre.sar(data, FICTA, "", ""); // match diatonic state:

   // insert the token back into the data file.
   infile[i].changeField(j, data.getBase());

   // store the tie head string
   if (strchr(infile[i][j], '[') != NULL) {
      Tiehead = infile[i][j];
   }

}



//////////////////////////////
//
// parseKeySignature --
//    b-e-a-d- => C=0, D=-1, E=-1, F=0, etc.
//

void parseKeySignature(Array& keysig, const char* keyinfo) {
   keysig.setAll(0);
   PerlRegularExpression pre;

   if (pre.search(keyinfo, "c-", "i")) { keysig[0] = -1; }
   if (pre.search(keyinfo, "d-", "i")) { keysig[1] = -1; }
   if (pre.search(keyinfo, "e-", "i")) { keysig[2] = -1; }
   if (pre.search(keyinfo, "f-", "i")) { keysig[3] = -1; }
   if (pre.search(keyinfo, "g-", "i")) { keysig[4] = -1; }
   if (pre.search(keyinfo, "a-", "i")) { keysig[5] = -1; }
   if (pre.search(keyinfo, "b-", "i")) { keysig[6] = -1; }

   if (pre.search(keyinfo, "c#", "i")) { keysig[0] = +1; }
   if (pre.search(keyinfo, "d#", "i")) { keysig[1] = +1; }
   if (pre.search(keyinfo, "e#", "i")) { keysig[2] = +1; }
   if (pre.search(keyinfo, "f#", "i")) { keysig[3] = +1; }
   if (pre.search(keyinfo, "g#", "i")) { keysig[4] = +1; }
   if (pre.search(keyinfo, "a#", "i")) { keysig[5] = +1; }
   if (pre.search(keyinfo, "b#", "i")) { keysig[6] = +1; }
}




//////////////////////////////
//
// processFile --
//

void processFile(HumdrumFile& infile) {
   int i, j;
   char ficta[1024] = {0};
   getFictaChar(ficta, infile);
   PerlRegularExpression pre;
   
   for (i=0; i<infile.getNumLines(); i++) {
      if (!infile[i].isData()) {
         continue;
      }
      for (j=0; j<infile[i].getFieldCount(); j++) {
         if (!infile[i].isExInterp(j, "**kern")) {
            continue;
         }
         if (strstr(infile[i][j], ficta) == NULL) {
            continue;
         }
         removeFicta(infile, i, j, ficta);
      }
   }

   for (i=0; i<infile.getNumLines(); i++) {
      if (!infile[i].isBibliographic()) {
         cout << infile[i] << "\n";
         continue;
      }
      if (!(pre.search(infile[i][0], "^!!!RDF\\*\\*kern\\s*:.*ficta", "i") ||
              pre.search(infile[i][0], "^!!!RDF\\*\\*kern\\s*:.*editorial", 
             "i"))) {
         cout << infile[i] << "\n";
      }
   }

}



//////////////////////////////
//
// removeFicta --
//

void removeFicta(HumdrumFile& infile, int line, int spine, const char* ficta) {
   Array<char> temp;
   temp.setSize(strlen(infile[line][spine])+1);
   strcpy(temp.getBase(), infile[line][spine]);

   PerlRegularExpression pre;
   int hasflat    = pre.search(temp, "-", "");
   int hassharp   = pre.search(temp, "#", "");
   int hasnatural = pre.search(temp, "n", "");

   pre.sar(temp, ficta, "", "g");
 
   if (hasflat) {
      pre.sar(temp, "-", "", "g");
   } else if (hassharp) {
      pre.sar(temp, "#", "", "g");
   } else {
      if (hasnatural) {
         pre.sar(temp, "n", "", "g");
      }
      char buffer[1024] = {0};
      pre.search(temp, "^(.*)([a-g]+)(.*)$", "i");
      strcpy(buffer, pre.getSubmatch(1));
      strcat(buffer, pre.getSubmatch(2));
      PerlRegularExpression pre2;
      if (pre2.search(pre.getSubmatch(), "[bead]+", "")) {
         strcat(buffer, "-");
      } else if (pre2.search(pre.getSubmatch(), "[fcg]+", "")) {
         strcat(buffer, "#");
      }
      strcat(buffer, pre.getSubmatch(3));
      temp.setSize(strlen(buffer)+1);
      strcpy(temp.getBase(), buffer);
   }

   infile[line].changeField(spine, temp.getBase());
}



//////////////////////////////
//
// removeFictaSuppress -- change 4c#i to 4c#yi
//

void removeFictaSuppress(HumdrumFile& infile, int line, int spine, 
       const char* ficta) {
   Array<char> temp;
   temp.setSize(strlen(infile[line][spine])+1);
   strcpy(temp.getBase(), infile[line][spine]);

   PerlRegularExpression pre;
 
   char searchbuffer[1024] = {0};
   strcpy(searchbuffer, ficta);
   strcat(searchbuffer, "(?!y)");

   char replacebuffer[1024] = {0};
   strcpy(replacebuffer, "y");
   strcat(replacebuffer, ficta);

   pre.sar(temp, searchbuffer, replacebuffer, "g");

   infile[line].changeField(spine, temp.getBase());
}



//////////////////////////////
//
// getFictaChar --
//

void getFictaChar(char* ficta, HumdrumFile& infile) {
   int i;
   PerlRegularExpression pre;
   for (i=infile.getNumLines()-1; i>=0; i--) {
      if (!infile[i].isBibliographic()) {
         continue;
      }

      if (pre.search(infile[i][0], 
            "^!!!RDF\\*\\*kern\\s*:\\s*([^\\s=]+)\\s*=.*ficta", "")) {
         strcpy(ficta, pre.getSubmatch(1));
         return;
      }
   }

   // presume "i" as ficta if no RDF marker
   strcpy(ficta, "i");
}



//////////////////////////////
//
// checkOptions -- validate and process command-line options.
//

void checkOptions(Options& opts, int argc, char* argv[]) {
   opts.define("s|switch=b", "switch editorial accidentals");
   opts.define("S|suppress=b", "suppress display of editorial accidentals");

   opts.define("debug=b");                // debugging mode
   opts.define("author=b");               // author of program
   opts.define("version=b");              // compilation info
   opts.define("example=b");              // example usages
   opts.define("h|help=b");               // short description
   opts.process(argc, argv);
   
   // handle basic options:
   if (opts.getBoolean("author")) {
      cout << "Written by Craig Stuart Sapp, "
           << "craig@ccrma.stanford.edu, April 2011" << endl;
      exit(0);
   } else if (opts.getBoolean("version")) {
      cout << argv[0] << ", version: 20 April 2011" << endl;
      cout << "compiled: " << __DATE__ << endl;
      cout << MUSEINFO_VERSION << endl;
      exit(0);
   } else if (opts.getBoolean("help")) {
      usage(opts.getCommand());
      exit(0);
   } else if (opts.getBoolean("example")) {
      example();
      exit(0);
   }

   suppressQ = opts.getBoolean("suppress");
   switchQ   = opts.getBoolean("switch");
   debugQ    = opts.getBoolean("debug");
}



//////////////////////////////
//
// example -- example usage of the quality program
//

void example(void) {
   cout <<
   "                                                                         \n"
   << endl;
}



//////////////////////////////
//
// usage -- gives the usage statement for the meter program
//

void usage(const char* command) {
   cout <<
   "                                                                         \n"
   << endl;
}



// md5sum: 8adb836d21af91ff993cf116753ed824 noficta.cpp [20120404]