/******************************************************************************/
// Given a .mid file as an argument, this program will provide the amount of 
// tracks, number of events, and the number of ticks in a MIDI file.
//
// Roy Vanegas: rvanegas@hunter.cuny.edu
/******************************************************************************/

import java.io.*;
import javax.sound.midi.*;

public class ShowTracksEventsAndTicksInMIDIFile
{
   private static Sequence sequence;

   public static void main( String[] args )
   {
      if( args.length == 0 )
      {
         System.out.println( "No MIDI file name specified.\n" + usage() );
         System.exit( 1 );
      }
      else
         if( args.length > 1 )
         {
            System.out.println( "Too many arguments.\n" + usage() );
            System.exit( 1 );
         }

      try
      {
         /**
          * Line 1: Get the MIDI filename
          * Line 2: Assign the MIDI file's tracks to sequence; throws
          *         IOException
          * Line 3: Obtain all the tracks, as an array, in this sequence.
          * Line 4: Method size will return, as an integer, the number of 
          *         events for each track.
          * Line 5: Method ticks will return, as a long integer, the length of 
          *         the current track in MIDI ticks.  There are two factors to 
          *         consider when dealing with MIDI ticks: the sequence's 
          *         timing resolution and BPM, or tempo.  
          */

/* 1 */  File midiFile = new File ( args[ 0 ] );
/* 2 */  sequence = MidiSystem.getSequence( midiFile );
/* 3 */  Track midiTracks[] = sequence.getTracks();
       
         System.out.println( "\nTotal tracks in " + args[ 0 ] + " is " + 
            midiTracks.length + "\n" );
       
         for( int track = 0; track < midiTracks.length; track++ )
            System.out.println( "The number of events in track " + 
               track + " is " + 
/* 4 */        midiTracks[ track ].size() + " and the number of ticks is " + 
/* 5 */        midiTracks[ track ].ticks() );

         System.out.println();      
         System.exit( 0 );
      }
      catch( InvalidMidiDataException badMIDI ) { badMIDI.printStackTrace(); }
      catch( IOException ioe ) { ioe.printStackTrace(); }
   }

   /**
    * Print proper usage of this program.
    *
    * @return String returns error message as a String
    */
   public static String usage()
   {
      return "\tUsage\n\tjava PlayMIDIFile <midifile.mid>";
   }
}

