// 
// Decompiled by Procyon v0.6.0
// 

package org.bouncycastle.mime;

import java.io.IOException;
import java.io.OutputStream;
import org.bouncycastle.mime.smime.SMimeParserContext;
import java.io.FilterOutputStream;

public class CanonicalOutputStream extends FilterOutputStream
{
    protected int lastb;
    protected static byte[] newline;
    private final boolean is7Bit;
    
    public CanonicalOutputStream(final SMimeParserContext sMimeParserContext, final Headers headers, final OutputStream out) {
        super(out);
        this.lastb = -1;
        if (headers.getContentType() != null) {
            this.is7Bit = (headers.getContentType() != null && !headers.getContentType().equals("binary"));
        }
        else {
            this.is7Bit = sMimeParserContext.getDefaultContentTransferEncoding().equals("7bit");
        }
    }
    
    @Override
    public void write(final int lastb) throws IOException {
        if (this.is7Bit) {
            if (lastb == 13) {
                this.out.write(CanonicalOutputStream.newline);
            }
            else if (lastb == 10) {
                if (this.lastb != 13) {
                    this.out.write(CanonicalOutputStream.newline);
                }
            }
            else {
                this.out.write(lastb);
            }
        }
        else {
            this.out.write(lastb);
        }
        this.lastb = lastb;
    }
    
    @Override
    public void write(final byte[] array) throws IOException {
        this.write(array, 0, array.length);
    }
    
    @Override
    public void write(final byte[] array, final int n, final int n2) throws IOException {
        for (int i = n; i != n + n2; ++i) {
            this.write(array[i]);
        }
    }
    
    public void writeln() throws IOException {
        super.out.write(CanonicalOutputStream.newline);
    }
    
    static {
        (CanonicalOutputStream.newline = new byte[2])[0] = 13;
        CanonicalOutputStream.newline[1] = 10;
    }
}
