/*
 * This program is to take two .wav files at the same rate, and adds them
 * sample by sample.
 * the output is a wav file.

 * cleaner version

 * This may only work with the "basic" wav format, to which there are extensions.

 * Usage: mixer foo.wav bar.wav output.wav
 */

import java.lang.*;
import java.io.*;
import javax.sound.sampled.*;

class mixer {

    public static void main(String[] args) {
		if (args.length != 3) {
			System.err.println("usage: mixer input1.wav input2.wav output.wav");
			return;
		}

		WavReader wr1, wr2;

		// first file

		String filename1 = args[0];
		// check that it has .wav extension
		if (! (filename1.toLowerCase().endsWith(".wav"))) {
			System.err.println("must use a .wav file!");
			return;
		}
		FileInputStream fis1;
		try {
			fis1 = new FileInputStream(filename1);
		} catch (IOException ioe) {
			System.err.println("file \"" + filename1 + "\" not found??");
			return;
		}
		wr1 = new WavReader(fis1);

		// second file must match:

		int samplerate = wr1.getSampleRate();
		int samplesize = wr1.getSampleSize();
		int samplecount = wr1.getNumSamples();

		if (wr1.getChannels() != 1) {
			System.err.println("this version works with mono only; file "
				+ filename1 + " has " + wr1.getChannels() + " channels.");
			return;
		}


		String filename2 = args[1];
		// check that it has .wav extension
		if (! (filename2.toLowerCase().endsWith(".wav"))) {
			System.err.println("must use a .wav file!");
			return;
		}
		FileInputStream fis2;
		try {
			fis2 = new FileInputStream(filename2);
		} catch (IOException ioe) {
			System.err.println("file \"" + filename2 + "\" not found??");
			return;
		}
		wr2 = new WavReader(fis2);

		// YOU MUST DO:
		// check that wr2 has the same samplerate/samplesize/etc
		// it's ok if one file has fewer samples than the other,
		// but if so the mixed file will only be as long as the shorter input
		// set samplecount to the SHORTER length!!!

		// output file

		String outfileName = args[2];
		// check that it has .wav extension
		if (! (outfileName.toLowerCase().endsWith(".wav"))) {
			System.err.println("must use a .wav file!");
			return;
		}
		File outfile = new File(outfileName);

		int valuesize = samplesize;

		//-------------------------------------------------


		short[] samples = new short[samplecount];

		for (int i = 0; i<samplecount; i++) {
			// get the next sample from wr1, wr2
			// put their average into samples[i]
		}
		
        	WavReader.writeWav(samples, samplerate, outfile);
	}
}
