/** Fictitious audio format based on .wav and MP3.
  * An instance of DaveWaveFile represents an audio recording.
  * (Perhaps "file" is a poor choice of words, since this code
  * doesn't have anything to do with real files.)
  * Used as example of abstract class with method compareTo, etc.
  * For classroom convenience, there are multiple classes in this java file. 
  */
public abstract class DaveWaveFile {
   protected final int SAMPLES_PER_SEC= 44100;
   protected String fileName; // class invar: fileName!=null
   
   /** duration, in seconds */
   abstract public int duration();
   
   /** = -1 if duration of this is less than duration of other,
     *    0 if durations are the same
     *    1 if duration of this is greater than other's. */
   public int compareTo(DaveWaveFile other) {
     if (this.duration() < other.duration())
       return -1;
     else if (this.duration() == other.duration())
       return 0;
     else return 1;    
   }

   /** = a wave file in db with duration = t, if one exists; otherwise null;
       Precondition: db!=null  */
   public DaveWaveFile findToFitTime(int t, DaveWaveFile[] db) {
      int i= 0;

      // set i to index with duration t, or to db.length if there is none
        // invar: 0<=i<=db.length 
        //        &&  db[0..i-1] has no file with duration t
        while ( i != db.length && db[i].duration() != t )
          { i++; }

      // { db[0..i-1] has no file with duration t
      //    && ( i=db.length || i<db.length && db[i].duration()==t ) }
  
      // return db[i] if it has duration t, otherwise return null
         if (i == db.length) 
           // { db[0..] has no file with duration n }
            return null;
         else                
           // { 0<=i<db.length && db[i].duration()==t }
            return db[i];
   }
}

class SimpleWaveFile extends DaveWaveFile {
   private short[] samples; 
   // class invar: samples!=null && samples.length % SAMPLES_PER_SEC == 0
   
   /** An instance with given data, assuming nam!=null and samp!=null 
     * and samp.length % SAMPLES_PER_SEC == 0 */
   SimpleWaveFile(String nam, short[] samp) {
     fileName= nam; samples= samp;
   }
   
   /** = duration, in seconds */
   public int duration() {
     return samples.length / SAMPLES_PER_SEC;
   }
} // end SimpleWaveFile
  
class WaveSegment {
  public short[] samples;
}

class SegmentedWaveFile extends DaveWaveFile {
  private WaveSegment[] segs;
  /* class invar: segs!=null and for each i in 0..segs.length-1, segs[i]!=null
   * and segs[i].samples.length % SAMPLES_PER_SEC == 0 */
  
  /** = duration, in seconds */
  public int duration() {
    int d= 0; int i= 0;
    // invar: d = sum of lengths of segs[0..i-1] 
    while (i!=segs.length) {
      d += segs[i].samples.length;
      i++;
    }
    return d / SAMPLES_PER_SEC;
  }
}



   
   
     



