
package org.apache.tools.ant.taskdefs.optional;

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

public class ProcessLineOutputStream extends FilterOutputStream {

    private boolean skipLF = false;
    protected ByteArrayOutputStream buffer = new ByteArrayOutputStream();

    public ProcessLineOutputStream(OutputStream os) {
        super(os);
    }

    public void write(int b) throws IOException {
        ensureOpen();
        if (skipLF) {
            skipLF = false;
            if (b == '\n') {
                orphantLF(b);
                return;
            }
        }
        if (b == '\r' || b == '\n') {
            skipLF = (b == '\r');
            endOfLine(b);
        } else {
            buffer.write(b);
        }
    }


    public void close() throws IOException {
        try {
            endOfFile();
        } finally {
            super.close();
        }
    }


    protected void endOfFile() throws IOException {
        processLine();
    }


    protected void endOfLine(int b) throws IOException {
        buffer.write(b);
        processLine();
    }

    protected void processLine() throws IOException {
        try {
            buffer.writeTo(out);
        } finally {
            buffer.reset();
        }
    }


    protected void orphantLF(int b) throws IOException {
        out.write(b);
    }


    protected void ensureOpen() throws IOException {
    }
}
