package phunky;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Reads in a sample file and lets the caller read bytes
 * from it ad nauseam: after the last byte is returned it
 * will loop back and return the first one again.
 * 
 * @author finsprings
 *
 */
public class Sample extends InputStream {
	/**
	 * sample data as read from the InputStream we're given at construction.
	 */
	private final byte [] data;
	
	/**
	 * index into data from which the next byte will be returned.
	 */
	private int index = 0;
	
	/**
	 * Read in our sample data so we're ready to return it from read().
	 * 
	 * @param in the stream from which to obtain our sample data
	 * @throws IOException may return this if we can't read in our sample data
	 */
	Sample(final InputStream in) throws IOException {
		final BufferedInputStream bin = new BufferedInputStream(in);
		final ByteArrayOutputStream out = new ByteArrayOutputStream();
		
		int c;
		while ((c = bin.read()) != -1) {
			out.write(c);
		}
		
		bin.close();
		data = out.toByteArray();
		
		System.out.println("Read in one sample, byte count=" + data.length);
	}
	
	public int read() throws IOException {
		final byte b = data[index];
		index = ++index % data.length;
		
		// We have to bitmask the returned value to avoid sign extension 
		// when the value is expanded into an integer. This problem arises
		// because the actual samples are 16-bit but we have to return them
		// a byte at a time.
		return ((int) b) & 0xFF;
	}
}