//
// Programmer:    Craig Stuart Sapp <craig@ccrma.stanford.edu>
// Creation Date: Mon Nov 20 17:56:26 PST 2000
// Last Modified: Mon Nov 20 17:56:29 PST 2000
// Filename:      ...sig/examples/all/terdis.cpp
// Web Address:   http://sig.sapp.org/examples/museinfo/humdrum/terdis.cpp
// Syntax:        C++; museinfo
//
// Description:   measurements of tertian dissonances 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]
//
// Table 1: Levels of Tertian Dissonance, page 338
// 
// Dissonance Level	Chord Quality
// ==============================================
// 	   1		consonant intervals
//      		major triads
//			minor triads
//	   2 		tritone
//			diminished triad
//			minor-minor seventh
//			major-minor seventh
//	   3		augmented fifth
//	   		augmented triad
//	   4		half-diminished seventh
//			fully-diminished sevenths
//			augmented-sixth sonorities
//	   5 		verticals with major sevenths
//			anything else
// 
// 

#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<double>& terdis);
double measureTertianDissonance(HumdrumFile& infile, int line);
void   printAnalysis(HumdrumFile& infile, Array<double>& terdis);
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<double>  terdis;

   // 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, terdis);
      printAnalysis(infile, terdis);
   }

   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& terdis) {
   terdis.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) {
         terdis[i] = -1.0;
         continue;
      }

      terdis[i] = measureTertianDissonance(infile, i);
   }
}


//////////////////////////////
//
// measureTertianDissonance -- based on the table on page 338.
//

#define TERTIAN_UNKNOWN  -1
#define TERTIAN_0         0   /* i.e., all rests or single notes */
#define TERTIAN_1         1
#define TERTIAN_1_5       1.5   /* Mm seventh chords */
#define TERTIAN_2         2
#define TERTIAN_3         3
#define TERTIAN_4         4
#define TERTIAN_5         5

double measureTertianDissonance(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 (notes.getSize() == 0) {
      return TERTIAN_0;
   }

   if (notes.getSize() == 1) {
      return TERTIAN_0;
   }

   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) {
         break;
      }
      rotateNotes(notes);
   }

   // filter augmented sixth chords:
   for (i=1; i<notes.getSize(); i++) {
      interval = notes[i] - notes[i-1];
      if (interval == E_base40_aug6 || interval == E_base40_dim3) {
         return TERTIAN_4;
      }
   }

   // filter out non tertian sonorities:
   if (!foundTertianQ) {
      return TERTIAN_5;
   }

   // filter tertian chords with major sevenths:
   interval = notes[notes.getSize() - 1] - notes[0];
   if (interval == E_base40_maj7) {
      return TERTIAN_5;
   }

   // filter out augmented fifth chords:
   if (notes[notes.getSize() - 1] - notes[0] < E_base40_min6) {
      for (i=0; i<notes.getSize() - 1; i++) {
         for (j=i+1; j<notes.getSize(); j++) {
            interval = notes[j] - notes[j-1];
            if (interval == E_base40_aug5) {
               return TERTIAN_3;
            }
         }
      }
   }

   if (notes.getSize() == 2) {
      if (notes[1] - notes[0] == E_base40_dim5) {
         return TERTIAN_2;
      } else {
         return TERTIAN_1;
      }
   }

   int interval1;
   int interval2;
   interval1 = notes[1] - notes[0];
   interval2 = notes[2] - notes[0];
   if (notes.getSize() == 3) {
      if (interval2 == E_base40_per5) {
         if (interval1 == E_base40_maj3 || interval1 == E_base40_min3) {
            return TERTIAN_1;
         } else {
            return TERTIAN_5;
         }
      } else if (interval2 == E_base40_dim5) {
         if (interval1 == E_base40_min3) {
            return TERTIAN_2;
         } else {
            return TERTIAN_5;
         }
      } else if (interval2 == E_base40_min7) {
         if (interval1 == E_base40_min3 ||
             interval1 == E_base40_maj3 ||
             interval1 == E_base40_per5) {
            return TERTIAN_2;
         } else {
            return TERTIAN_5;
         }
      } else if (interval2 == E_base40_dim7) {
         if (interval1 == E_base40_min3 ||
             interval1 == E_base40_dim5 ||
             interval1 == E_base40_per5) {
            return TERTIAN_4;
         } else {
            return TERTIAN_5;
         }
      } else {
         return TERTIAN_5;
      }
   }

   int interval3;
   interval1 = notes[1] - notes[0];
   interval2 = notes[2] - notes[0];
   interval3 = notes[3] - notes[0];
   if (notes.getSize() == 4) {
      if (interval3 == E_base40_maj7) {
         return TERTIAN_5;
      } else if (interval3 == E_base40_min7) {
         if (interval2 == E_base40_per5) {
            if (interval1 == E_base40_min3 || interval1 == E_base40_maj3) {
               return TERTIAN_2;
            } 
         }
      } else if (interval3 == E_base40_dim7) {
         if (interval2 == E_base40_per5) {
            if (interval1 == E_base40_min3) {
               return TERTIAN_4;
            } 
         } else if (interval2 == E_base40_dim5) {
            if (interval1 == E_base40_min3) {
               return TERTIAN_4;
            } 
         } 
      } 
   }

   // couldn't identify tertian chord
   return TERTIAN_5;
}



//////////////////////////////
//
// 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& terdis) {
   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";
            cout << terdis[i] << "\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 << "**terdis" << "\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:
            cout << terdis[i] << "\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 << "**terdis" << "\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: ce3f1462b889a917d52c46983b707795 terdis.cpp [20050403]