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

package org.bouncycastle.mime;

import java.io.IOException;
import org.bouncycastle.util.Strings;
import java.io.InputStream;

public class BoundaryLimitedInputStream extends InputStream
{
    private final InputStream src;
    private final byte[] boundary;
    private final byte[] buf;
    private int bufOff;
    private int index;
    private boolean ended;
    private int lastI;
    
    public BoundaryLimitedInputStream(final InputStream src, final String s) {
        this.bufOff = 0;
        this.index = 0;
        this.ended = false;
        this.src = src;
        this.boundary = Strings.toByteArray(s);
        this.buf = new byte[s.length() + 3];
        this.bufOff = 0;
    }
    
    @Override
    public int read() throws IOException {
        if (this.ended) {
            return -1;
        }
        int read;
        if (this.index < this.bufOff) {
            read = (this.buf[this.index++] & 0xFF);
            if (this.index < this.bufOff) {
                return read;
            }
            final int n = 0;
            this.bufOff = n;
            this.index = n;
        }
        else {
            read = this.src.read();
        }
        this.lastI = read;
        if (read < 0) {
            return -1;
        }
        if (read == 13 || read == 10) {
            this.index = 0;
            int n2;
            if (read == 13) {
                n2 = this.src.read();
                if (n2 == 10) {
                    this.buf[this.bufOff++] = 10;
                    n2 = this.src.read();
                }
            }
            else {
                n2 = this.src.read();
            }
            if (n2 == 45) {
                this.buf[this.bufOff++] = 45;
                n2 = this.src.read();
            }
            if (n2 == 45) {
                this.buf[this.bufOff++] = 45;
                final int bufOff = this.bufOff;
                int read2;
                while (this.bufOff - bufOff != this.boundary.length && (read2 = this.src.read()) >= 0) {
                    this.buf[this.bufOff] = (byte)read2;
                    if (this.buf[this.bufOff] != this.boundary[this.bufOff - bufOff]) {
                        ++this.bufOff;
                        break;
                    }
                    ++this.bufOff;
                }
                if (this.bufOff - bufOff == this.boundary.length) {
                    this.ended = true;
                    return -1;
                }
            }
            else if (n2 >= 0) {
                this.buf[this.bufOff++] = (byte)n2;
            }
        }
        return read;
    }
}
