public class Nov03 {

  static int maxValue(Sound soundObj) {
    int numSamples = soundObj.getNumSamples() ;
    int maxSample  = Math.abs(soundObj.getSample(0).getValue()) ;
    for (int i=1; i<numSamples; ++i) {
      int nxtSample = Math.abs(soundObj.getSample(i).getValue()) ;
      if (nxtSample > maxSample) {
        maxSample = nxtSample ;
      }
    }
    return maxSample ;
  }

  static void clipSound(Sound soundObj, int clipSample) {
    int numSamples = soundObj.getNumSamples() ;
    for (int i=0; i<numSamples; ++i) {
      SoundSample nxtSample = soundObj.getSample(i) ;
      if (Math.abs(nxtSample.getValue())>clipSample) {
        if (nxtSample.getValue() >= 0) {
          nxtSample.setValue(clipSample) ;
        } else {
          nxtSample.setValue(clipSample) ;
        }
      }
    }
  }

  static void positiveSound(Sound soundObj) {
    int numSamples = soundObj.getNumSamples() ;
    for (int i=0; i<numSamples; ++i) {
      SoundSample nxtSample = soundObj.getSample(i) ;
      if (nxtSample.getValue()<0) {
          nxtSample.setValue(0) ;
      }
    }
  }
  
  static void multiplySound(Sound soundObj, double freq) {
    int numSamples = soundObj.getNumSamples() ;
    double soundFreq  = soundObj.getSamplingRate() ;
    double perMult = 2*Math.PI*freq/soundFreq ;
    for (int i=0; i<numSamples; ++i) {
      SoundSample nxtSample = soundObj.getSample(i) ;
      double sineMult  = Math.sin(perMult*i) ;
      int oldValue = nxtSample.getValue() ;
      int newValue = (int)Math.round(sineMult*oldValue) ;
      nxtSample.setValue(newValue) ;
    }
  }
  
  public static void main(String[] args) {
    String fileName = "G:\\Examples\\braes.wav" ;
    Sound  braesSnd = new Sound(fileName) ;
    // braesSnd.blockingPlay() ;
    // braesSnd.explore() ;
    System.out.println("Number of samples: " + braesSnd.getNumSamples()) ;
    System.out.println("Sampling rate: " + braesSnd.getSamplingRate()) ;
    System.out.println("Length: "
                         + (double)braesSnd.getNumSamples()/braesSnd.getSamplingRate()) ;
    SoundSample[] braesSamples = braesSnd.getSamples() ;
    System.out.println("Value at 100000: " + braesSamples[100000].getValue()) ;
    System.out.println("Max sample: " + maxValue(braesSnd)) ;
    
    Sound  clipSnd  = new Sound(braesSnd) ;
    clipSound(clipSnd, maxValue(braesSnd)*99/100) ;
    
    Sound  posSnd   = new Sound(braesSnd) ;
    positiveSound(posSnd) ;
    
    Sound  wowSnd   = new Sound(braesSnd) ;
    multiplySound(wowSnd, 2.0) ;
    
    braesSnd.blockingPlay() ;
    clipSnd.blockingPlay() ;
    posSnd.blockingPlay() ;
    wowSnd.blockingPlay() ;
                       
  }
}
