package daruma.util;

import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Write out to original output stream and another stream.
 */
public class TeeOutputStream extends FilterOutputStream
{
	private	OutputStream	teeout;
	private	boolean		closeTee = true;

	/**
	 * @param ostream original output stream
	 * @param tee original output is duplicate to this stream.
	 */
	public	TeeOutputStream(OutputStream ostream, OutputStream tee)
	{
		super(ostream);
		teeout = tee;
	}

	/**
	 * @param ostream original output stream
	 * @param tee original output is duplicate to this stream.
	 * @param closeTeeFlag close "tee" stream when close the
	 * original stream
	 */
	public	TeeOutputStream(OutputStream ostream, OutputStream tee,
				boolean closeTeeFlag)
	{
		super(ostream);
		teeout = tee;
		closeTee = closeTeeFlag;
	}

	public	void	write( int  b ) throws IOException
	{
		out.write(b);

		if ( teeout != null ) {
			teeout.write( b );
		}
	}

	public	void	write( byte[]  b ) throws IOException
	{
		out.write( b );

		if ( teeout != null ) {
			teeout.write( b );
		}
	}

	public	void	write( byte[]  b ,  int  off ,  int  len )
		throws IOException
	{
		out.write( b , off , len );

		if ( teeout != null ) {
			teeout.write( b , off , len );
		}
	}

	public	void	flush() throws IOException
	{
		out.flush();

		if ( teeout != null ) {
			teeout.flush();
		}
	}

	public	void	close() throws IOException
	{
		out.close();

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