//
// Programmer:    Craig Stuart Sapp <craig@ccrma.stanford.edu>
// Creation Date: Thu Apr 12 18:50:21 PDT 2001
// Last Modified: Thu Apr 12 18:50:25 PDT 2001
// Filename:      ...sig/examples/all/kern2notelist.cpp
// Web Address:   http://sig.sapp.org/examples/museinfo/humdrum/kern2notelist.cpp
// Syntax:        C++; museinfo
//
// Description:   Generates a list of notes from the input along with their
//		  absolute position in the music, their duration and
//		  the metric level
// 

#include "humdrum.h"

#include <string.h>
#include <math.h>
#include <stdlib.h>

// function declarations
void   checkOptions(Options& opts, int argc, char* argv[]);
void   example(void);
void   usage(const char* command);
void   fillDataArrays(HumdrumFile& infile, 
                                 Array<double>& absbeat, Array<int>& pitch, 
                                 Array<double>& duration, Array<double>& level);

// user interface variables
Options      options;            // database for command-line arguments
int          quietQ = 0;         // display only data table or not
int          verboseQ = 1;       // display only data table or not
int          compoundQ  = 1;     // used with the -c option


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

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
   int numinputs = options.getArgCount();

   Array<double> absbeat;
   Array<int> pitch;
   Array<int> testset;
   Array<double> duration;
   Array<double> level;
   Array<double> coef;

   int i, j;
   for (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));
      }

      fillDataArrays(infile, absbeat, pitch, duration, level);
      cout<<"**absbeat\t**base40\t**duration\t**level\n";
      for (j=0; j<pitch.getSize(); j++) {
         cout << absbeat[j]  << "\t"
              << pitch[j]    << "\t"
              << duration[j] << "\t"
              << level[j]    << "\n";
      }
      cout << "*-\t*-\t*-\t*-\n";
   }

   return 0;
}


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


//////////////////////////////
//
// fillDataArrays -- 
//

void fillDataArrays(HumdrumFile& infile, Array<double>& absbeat, 
      Array<int>& pitches, Array<double>& durations, Array<double>& levels) {
   absbeat.setSize(infile.getNumLines() * 100);
   pitches.setSize(infile.getNumLines() * 100);
   durations.setSize(infile.getNumLines() * 100);
   levels.setSize(infile.getNumLines() * 100);
   absbeat.setSize(0);
   pitches.setSize(0);
   durations.setSize(0);
   levels.setSize(0);
   absbeat.allowGrowth(1);
   pitches.allowGrowth(1);
   durations.allowGrowth(1);
   levels.allowGrowth(1);

   Array<int> scorelevels;
   infile.analyzeMetricLevel(scorelevels);
   
   int firsttime = 1;
   int i, j, k;
   int ii, jj;
   int ccount;
   static char buffer[1024] = {0};
   int pitch;
   double beatvalue;
   double duration;
   double level;
   for (i=0; i<infile.getNumLines(); i++) {
      if (infile[i].getType() != E_humrec_data) {
         // ignore non-note data lines
         continue;
      }
      beatvalue = infile.getAbsBeat(i);
      ii = i;
      for (j=0; j<infile[i].getFieldCount(); j++) {
         if (infile[i].getExInterpNum(j) != E_KERN_EXINT) {
            // ignore non-kern data spines
            continue;
         }
         if (firsttime && strcmp(infile[i][j], ".") == 0) {
            // extract the held over note from a previous point in the infile
            ii = infile[i].getDotLine(j);
            jj = infile[i].getDotSpine(j);
         } else {
            ii = i;
            jj = j;
         }
 
         if (strcmp(infile[ii][jj], ".") != 0) {
            // extract all notes in the region of interest, ignoring
            // tied notes.
            ccount = infile[ii].getTokenCount(jj);
            for (k=0; k<ccount; k++) {
               infile[ii].getToken(buffer, jj, k, 128);
               if (strchr(buffer, 'r') != NULL) {
                  // skip over rests
                  continue;
               }
               if (strchr(buffer, '_') != NULL) {
                  // skip over doubly tied notes
                  continue;                

               }
               if (!firsttime && strchr(buffer, ']') != NULL) {
                  // skip over tied notes at the ends of ties.
                  continue;
               }
               // have a note so now extract the metric level and the duration
               pitch = Convert::kernToBase40(buffer);
               if (pitch < 0) {
                  // ignore rests
                  continue;
               }
               // pitch = ((int)pitch - 2 + 40) % 40;
               duration = infile.getTiedDuration(ii, jj, k);
               if (duration == 0.0) {
                  // ignore grace notes and other zero-dur ornaments
                  continue;
               }
               level = 1.0/pow(2.0, scorelevels[ii]);
               durations.append(duration);
               levels.append(level);
               pitches.append(pitch);
               absbeat.append(beatvalue);
 
            } // end of a chord
         }
      }  // end of a line
      firsttime = 0;
 
   } // end of the music selection   


   absbeat.allowGrowth(0);
   pitches.allowGrowth(0);
   durations.allowGrowth(0);
   levels.allowGrowth(0);

   for (i=0; i<pitches.getSize(); i++) {
      pitches[i] = (pitches[i] - 2 + 40) % 40;
   }
}



//////////////////////////////
//
// 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("q|quiet=b",         "suppress extra information");   
   opts.define("v|noverbose=b",     "suppress extra information");   
   opts.define("C|compound=b",      "don't try to use compound meters");   

   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, April 2001" << endl;
      exit(0);
   } else if (opts.getBoolean("version")) {
      cout << argv[0] << ", version: 13 April 2001" << 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);
   }

   // compound diabled for now
   if (opts.getBoolean("compound")) {
      compoundQ = 0;
   } else {
      compoundQ = 0;
   }

   quietQ   = opts.getBoolean("quiet");
   verboseQ = !opts.getBoolean("noverbose");
}



//////////////////////////////
//
// example -- example usage of the maxent program
//

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



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

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


// md5sum: cf2cb0f3697dc966a643dcadde4ab270 kern2notelist.cpp [20050403]