import java.io.*;

/**
 * TitleOutputStream converts the first letter of every word written
 * to it into titlecase.  A given words begins at its first letter,
 * and ends at the next whitespace.
 */
class TitleOutputStream extends FilterOutputStream {

    public TitleOutputStream(OutputStream out) {
	super(out);
    }

    /*
     * Note that this streams expects to be written with two byte
     * characters as done by the DataOutputStream.writeChar method.
     * Thus, it stores every first byte in a temporary variable until
     * the second byte is received to process the character.
     */

    // true if we have only the high byte of the last character written
    private boolean haveHighByte = false;

    // high byte of character partially received
    private int partial;

    // true if in the middle of a writing a word
    private boolean inWord = false;

    public void write(int b) throws IOException {
	b &= 0xFF;			// force argument to a byte

	if (!haveHighByte) {
	    partial = b;
	    haveHighByte = true;

	} else {
	    // construct full character from high and low bytes
	    char ch = (char)((partial << 8) | b);

	    if (!inWord) {
		if (Character.isLetter(ch)) { // convert first letter in word
		    ch = Character.toTitleCase(ch);
		    inWord = true;
		}
	    } else {
		if (Character.isSpace(ch)) // copy rest through to next space
		    inWord = false;
	    }

	    out.write(((int)ch >> 8) & 0xFF);
	    out.write((int)ch & 0xFF);
	    haveHighByte = false;
	}
    }

    public void write(byte b[], int off, int len) throws IOException {
	/*
	 * This is quite an inefficient implementation, because it has to
	 * call the other write method for every byte in the array.  It
         * could be optimized for performance by doing all the processing
	 * in this method.
	 */
	for (int i = 0; i < len; i++)
	    write(b[off + i]);
    }
}
