package daruma.util;

import java.io.FilterInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Read in from stream and duplicate it to specified output stream
 */
public class TeeInputStream extends FilterInputStream
{
	private	OutputStream	tee;
	private boolean		closeTee = true;

	public	TeeInputStream(InputStream istream, OutputStream teeStream)
	{
		super(istream);

		tee = teeStream;
	}

	public	TeeInputStream(InputStream istream, OutputStream teeStream,
			       boolean  closeTeeFlag)
	{
		super(istream);

		tee = teeStream;

		closeTee = closeTeeFlag;
	}

	public	int	read() throws IOException
	{
		int ret = in.read();

		if (tee != null && ret != -1) {
			tee.write(ret);
		}

		return ret;
	}

	public	int	read(byte[] b) throws IOException
	{
		int ret = in.read(b);

		if (tee != null && ret != -1) {
			tee.write(b, 0, ret);
		}

		return ret;
	}

	public	int	read( byte[]  b ,  int  off ,  int  len )
		throws IOException
	{
		int ret = in.read(b, off, len);

		if (tee != null && ret != -1) {
			tee.write(b, off, ret);
		}

		return ret;
	}

	/**
	 * Flush tee output stream.
	 */
	public	void	flush() throws IOException
	{
		if (tee != null) {
			tee.flush();
		}
	}

	/**
	 * Close both input stream and tee output stream.
	 */
	public	void	close() throws IOException
	{
		in.close();

		if ( tee != null && closeTee ) {
			tee.close();
		}
	}

}
