//
// Programmer:    Craig Stuart Sapp <craig@ccrma.stanford.edu>
// Creation Date: Mon Nov 20 16:12:43 PST 2000
// Last Modified: Mon Nov 20 16:12:46 PST 2000
// Filename:      ...sig/examples/all/tertian.cpp
// Web Address:   http://sig.sapp.org/examples/museinfo/humdrum/tertian.cpp
// Syntax:        C++; museinfo
//
// Description:   determination of tertian sonority through rules given
//                by John Maxwell in:
//
// Reference:     "An Expert System for Harmonizing Analysis of Tonal
//                Music." pp 335-353 in: "Understanding Music with AI: 
//                Perspectives on Music Cognition." Ed. by Mira Balaban, 
//                Kemal Ebcioglu, and Otto Laske.  MIT Press; 1992.
//                [ISBN 0-262-52170-9]
//
// 

#include "humdrum.h"

#include <string.h>
#include <ctype.h>


// function declarations
void   checkOptions(Options& opts, int argc, char* argv[]);
void   example(void);
void   generateAnalysis(HumdrumFile& infile, Array<int>& tertian);
int    measureTertian(HumdrumFile& infile, int line);
void   printAnalysis(HumdrumFile& infile, Array<int>& tertian);
void   rotateNotes(Array<int>& notes);
void   usage(const char* command);


// global variables
Options      options;            // database for command-line arguments
int          debugQ     = 0;     // used with the --debug option
int          appendQ    = 0;     // used with the -a option


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

int main(int argc, char* argv[]) {
   HumdrumFile infile;
   Array<int>  tertian;

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

   // figure out the number of input files to process
   int numinputs = options.getArgCount();

   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) {
         infile.read(cin);
      } else {
         infile.read(options.getArg(i+1));
      }

      generateAnalysis(infile, tertian);
      printAnalysis(infile, tertian);
   }

   return 0;
}


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


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

void checkOptions(Options& opts, int argc, char* argv[]) {
   opts.define("a|append=b",        "append analysis to data in output");   

   opts.define("debug=b",  "trace input parsing");   
   opts.define("author=b",  "author of the program");   
   opts.define("version=b", "compilation information"); 
   opts.define("example=b", "example usage"); 
   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, Nov 2000" << endl;
      exit(0);
   } else if (opts.getBoolean("version")) {
      cout << argv[0] << ", version: Nov 2000" << 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);
   }

   debugQ = opts.getBoolean("debug");
   appendQ = opts.getBoolean("append");

}



//////////////////////////////
//
// example -- example usage of the tertian program
//

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



//////////////////////////////
//
// generateAnalysis -- 
//

void generateAnalysis(HumdrumFile& infile, Array& tertian) {
   tertian.setSize(infile.getNumLines());

   for (int i=0; i<infile.getNumLines(); i++) {
      if (options.getBoolean("debug")) {
         cout << "processing line " << (i+1) << " of input ..." << endl;
      }

      if (infile[i].getType() != E_humrec_data) {
         tertian[i] = -1;
         continue;
      }

      tertian[i] = measureTertian(infile, i);
   }
}


//////////////////////////////
//
// measureTertian -- apply the rule 5 on page 337:
//
// Rule 5: IF the pitch classes of a vertical sonority can be arranged
// so that each note is separated from its neighbor(s) by a third or fifth,
// and the pitches all lie within a single octave, THEN it is tertian.
//

#define TERTIAN_YES       0
#define TERTIAN_NO        1
#define TERTIAN_UNKNOWN  -1

int measureTertian(HumdrumFile& infile, int line) {
   Array<int> notes;

   if (infile[line].getType() != E_humrec_data) {
      return TERTIAN_UNKNOWN;
   }

   infile.getNoteList(notes, line, NL_PC | NL_FILL | NL_SORT | NL_UNIQ | 
         NL_NORESTS);
   
   // if there is one or fewer notes, then cannot be tertian
   if (notes.getSize() <= 1) {
      return TERTIAN_NO;
   }

   int i, j;
   int foundTertianQ = 0;
   int interval;
   for (i=0; i<notes.getSize(); i++) {
      foundTertianQ = 1;
      for (j=1; j<notes.getSize(); j++) {
         interval = notes[j] - notes[j-1];
         if (interval == E_base40_maj3 ||
             interval == E_base40_min3 ||
             interval == E_base40_dim3 ||
             interval == E_base40_aug3 ||
             interval == E_base40_per5 ||
             interval == E_base40_dim5 ||
             interval == E_base40_aug5) {
            // do nothing
         } else {
            // invalid interval
            foundTertianQ = 0;
            break;
         }
      }
      if (foundTertianQ == 1) {
         return TERTIAN_YES;
      }
      rotateNotes(notes);
   }

   return TERTIAN_NO;
}



//////////////////////////////
//
// rotateNotes -- 
// 

void rotateNotes(Array& notes) {
   if (notes.getSize() < 2) {
      return;
   }

   int note = notes[0];
   int i;
   for (i=0; i<notes.getSize() - 1; i++) {
      notes[i] = notes[i+1];
   }
   notes[notes.getSize()-1] = note + 40;
}



//////////////////////////////
//
// printAnalysis -- 
//

void printAnalysis(HumdrumFile& infile, Array& tertian) {
   int i;
   if (appendQ) {
      for (i=0; i<infile.getNumLines(); i++) {
         switch (infile[i].getType()) {
         case E_humrec_global_comment:
         case E_humrec_bibliography:
         case E_humrec_none:
         case E_humrec_empty:
            cout << infile[i].getLine() << "\n";
            break;
         case E_humrec_data:
            cout << infile[i].getLine() << "\t";
            if (tertian[i] == TERTIAN_YES) {
               cout << "y";
            } else {
               cout << "n";
            }
            cout << "\n";
            break;
         case E_humrec_data_comment:
            if (infile[i].equalFieldsQ("**kern")) {
               cout << infile[i].getLine() << "\t"
                    << infile[i][0] << "\n";
            } else {
               cout << infile[i].getLine() << "\t!\n";
            }
            break;
         case E_humrec_data_measure:
            if (infile[i].equalFieldsQ("**kern")) {
               cout << infile[i].getLine() << "\t"
                    << infile[i][0] << "\n";
            } else {
               cout << infile[i].getLine() << "\t=\n";
            }
            break;
         case E_humrec_data_interpretation:
            if (strncmp(infile[i][0], "**", 2) == 0) {
               cout << infile[i].getLine() << "\t";
               cout << "**tertian" << "\n";
            } else if (infile[i].equalFieldsQ("**kern")) {
               cout << infile[i].getLine() << "\t"
                    << infile[i][0] << "\n";
            } else {
               cout << infile[i].getLine() << "\t*\n";
            }
            break;
         }
      }

   } else {

      for (i=0; i<infile.getNumLines(); i++) {
         switch (infile[i].getType()) {
         case E_humrec_global_comment:
         case E_humrec_bibliography:
         case E_humrec_none:
         case E_humrec_empty:
            cout << infile[i].getLine() << "\n";
            break;
         case E_humrec_data:
            if (tertian[i] == TERTIAN_YES) {
               cout << "y";
            } else {
               cout << "n";
            }
            cout << "\n";
            break;
         case E_humrec_data_comment:
            if (infile[i].equalFieldsQ("**kern")) {
               cout << infile[i][0] << "\n";
            } else {
               // do nothing
            }
            break;
         case E_humrec_data_measure:
            if (infile[i].equalFieldsQ("**kern")) {
               cout << infile[i][0] << "\n";
            } else {
               cout << "\t=\n";
            }
            break;
         case E_humrec_data_interpretation:
            if (strncmp(infile[i][0], "**", 2) == 0) {
               cout << "**tertian" << "\n";
            } else if (infile[i].equalFieldsQ("**kern")) {
               cout << infile[i][0] << "\n";
            } else {
               // do nothing
            }
            break;
         }
      }
   }
}



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

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


// md5sum: 1ace18f54220ee423d194f17c0c61c4a tertian.cpp [20050403]