//
// Programmer:    Craig Stuart Sapp <craig@ccrma.stanford.edu>
// Creation Date: Mon Nov 20 09:00:52 PST 2000
// Last Modified: Mon Nov 20 09:00:55 PST 2000
// Filename:      ...sig/examples/all/vertdis.cpp
// Web Address:   http://sig.sapp.org/examples/museinfo/humdrum/vertdis.cpp
// Syntax:        C++ 
//
// Description:   Implementation of rules for tertian dissonance 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   generateAnalysis1(HumdrumFile& infile, Array<int>& soncondis);
int    measureVerticalConsonance(HumdrumFile& infile, int line);
void   printAnalysis(HumdrumFile& infile, Array<int>& soncondis);
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>  soncondis;

   // 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));
      }

      generateAnalysis1(infile, soncondis);
      printAnalysis(infile, soncondis);
   }

   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 quality program
//

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



//////////////////////////////
//
// generateAnalysis1 -- 
//

void generateAnalysis1(HumdrumFile& infile, Array& soncondis) {
   soncondis.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) {
         soncondis[i] = -1;
         continue;
      }

      soncondis[i] = measureVerticalConsonance(infile, i);
   }
}


//////////////////////////////
//
// measureVerticalConsonance -- apply the rules 1 & 2 from page 337:
//
// Rule 1 & Rule 2.  IF a sonority consists of only one note, OR it
// consists of two notes that form a consonant interval other than a
// perfect fourth, OR it consists of three of more notes forming only
// consonant intervals, THEN it is a consonant vertical, OTHERWISE,
// it is a dissonant vertical.
//

#define CONSONANT_VERTICAL 0
#define DISSONANT_VERTICAL 1
#define UNDEFINED_VERTICAL  -1

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

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

   infile.getNoteList(notes, line, NL_FILL | NL_SORT | NL_UNIQ | NL_NORESTS);
   
   // IF a sonority consists of only one note, THEN it is a consonant vertical.
   if (notes.getSize() <= 1) {
      return CONSONANT_VERTICAL;
   }

   // IF a sonority consists of two notes that form a consonant interval
   // other than a perfect fourth, THEN it is a consonant vertical.
   if (notes.getSize() == 2) {
      int interval = notes[1] - notes[0];
      if (interval < 0) {
         cout << "Error on line " << line+1 << " of file: " 
              << "problem determing interval" << endl;
         exit(1);
      }

      interval = interval % 40;
      if (interval == E_base40_per4) {
         return DISSONANT_VERTICAL;
      } else if (interval == E_base40_per1 ||
                 interval == E_base40_maj3 ||
                 interval == E_base40_min3 ||
                 interval == E_base40_min6 ||
                 interval == E_base40_maj6 ||
                 interval == E_base40_per5) {
         return CONSONANT_VERTICAL;
      } else {
         return DISSONANT_VERTICAL;
      }
   }

   // IF a sonority consists of three or more notes forming only 
   // consonant intervals, THEN it is a consonant vertical.
   int i, j;
   int interval;
   for (i=0; i<notes.getSize()-1; i++) {
      for (j=i+1; j<notes.getSize(); j++) {
         interval = notes[j] - notes[i];
         interval = interval % 40;
         if (interval == E_base40_per1 ||
             interval == E_base40_maj3 ||
             interval == E_base40_min3 ||
             interval == E_base40_min6 ||
             interval == E_base40_maj6 ||
             interval == E_base40_per4 ||
             interval == E_base40_per5) {
            // do nothing
         } else {
            return DISSONANT_VERTICAL;
         }
      }
   }

   // the chord notes contain only consonant intervals.
   return CONSONANT_VERTICAL;
}



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

void printAnalysis(HumdrumFile& infile, Array& soncondis) {
   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 (soncondis[i] == CONSONANT_VERTICAL) {
               cout << "c";
            } else if (soncondis[i] == DISSONANT_VERTICAL) {
               cout << "d";
            } else {
               cout << "X";
            }
            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 << "**vertdis" << "\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 (soncondis[i] == CONSONANT_VERTICAL) {
               cout << "c";
            } else if (soncondis[i] == DISSONANT_VERTICAL) {
               cout << "d";
            } else {
               cout << "X";
            }
            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 << "**vertdis" << "\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: 616359e9c313fc329ddfeb79958c9a56 vertdis.cpp [20050403]