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

package org.bouncycastle.mime.encoding;

import java.io.IOException;
import java.io.OutputStream;
import org.bouncycastle.util.encoders.Base64Encoder;
import java.io.FilterOutputStream;

public class Base64OutputStream extends FilterOutputStream
{
    private static final Base64Encoder ENCODER;
    private static final int INBUF_SIZE = 54;
    private static final int OUTBUF_SIZE = 74;
    private final byte[] inBuf;
    private final byte[] outBuf;
    private int inPos;
    
    public Base64OutputStream(final OutputStream out) {
        super(out);
        this.inBuf = new byte[54];
        this.outBuf = new byte[74];
        this.inPos = 0;
        this.outBuf[72] = 13;
        this.outBuf[73] = 10;
    }
    
    @Override
    public void write(final int n) throws IOException {
        this.inBuf[this.inPos++] = (byte)n;
        if (this.inPos == 54) {
            this.encodeBlock(this.inBuf, 0);
            this.inPos = 0;
        }
    }
    
    @Override
    public void write(final byte[] array, final int n, final int n2) throws IOException {
        final int n3 = 54 - this.inPos;
        if (n2 < n3) {
            System.arraycopy(array, n, this.inBuf, this.inPos, n2);
            this.inPos += n2;
            return;
        }
        int n4 = 0;
        if (this.inPos > 0) {
            System.arraycopy(array, n, this.inBuf, this.inPos, n3);
            n4 += n3;
            this.encodeBlock(this.inBuf, 0);
        }
        int inPos;
        while ((inPos = n2 - n4) >= 54) {
            this.encodeBlock(array, n + n4);
            n4 += 54;
        }
        System.arraycopy(array, n + n4, this.inBuf, 0, inPos);
        this.inPos = inPos;
    }
    
    @Override
    public void write(final byte[] array) throws IOException {
        this.write(array, 0, array.length);
    }
    
    @Override
    public void close() throws IOException {
        if (this.inPos > 0) {
            int encode = Base64OutputStream.ENCODER.encode(this.inBuf, 0, this.inPos, this.outBuf, 0);
            this.inPos = 0;
            this.outBuf[encode++] = 13;
            this.outBuf[encode++] = 10;
            this.out.write(this.outBuf, 0, encode);
        }
        this.out.close();
    }
    
    private void encodeBlock(final byte[] array, final int n) throws IOException {
        Base64OutputStream.ENCODER.encode(array, n, 54, this.outBuf, 0);
        this.out.write(this.outBuf, 0, 74);
    }
    
    static {
        ENCODER = new Base64Encoder();
    }
}
