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

package org.bouncycastle.asn1;

import java.io.IOException;
import java.io.InputStream;

class ConstructedOctetStream extends InputStream
{
    private final ASN1StreamParser _parser;
    private boolean _first;
    private InputStream _currentStream;
    
    ConstructedOctetStream(final ASN1StreamParser parser) {
        this._first = true;
        this._parser = parser;
    }
    
    @Override
    public int read(final byte[] b, final int n, final int n2) throws IOException {
        if (this._currentStream == null) {
            if (!this._first) {
                return -1;
            }
            final ASN1OctetStringParser nextParser = this.getNextParser();
            if (nextParser == null) {
                return -1;
            }
            this._first = false;
            this._currentStream = nextParser.getOctetStream();
        }
        int n3 = 0;
        while (true) {
            final int read = this._currentStream.read(b, n + n3, n2 - n3);
            if (read >= 0) {
                n3 += read;
                if (n3 == n2) {
                    return n3;
                }
                continue;
            }
            else {
                final ASN1OctetStringParser nextParser2 = this.getNextParser();
                if (nextParser2 == null) {
                    this._currentStream = null;
                    return (n3 < 1) ? -1 : n3;
                }
                this._currentStream = nextParser2.getOctetStream();
            }
        }
    }
    
    @Override
    public int read() throws IOException {
        if (this._currentStream == null) {
            if (!this._first) {
                return -1;
            }
            final ASN1OctetStringParser nextParser = this.getNextParser();
            if (nextParser == null) {
                return -1;
            }
            this._first = false;
            this._currentStream = nextParser.getOctetStream();
        }
        while (true) {
            final int read = this._currentStream.read();
            if (read >= 0) {
                return read;
            }
            final ASN1OctetStringParser nextParser2 = this.getNextParser();
            if (nextParser2 == null) {
                this._currentStream = null;
                return -1;
            }
            this._currentStream = nextParser2.getOctetStream();
        }
    }
    
    private ASN1OctetStringParser getNextParser() throws IOException {
        final ASN1Encodable object = this._parser.readObject();
        if (object == null) {
            return null;
        }
        if (object instanceof ASN1OctetStringParser) {
            return (ASN1OctetStringParser)object;
        }
        throw new IOException("unknown object encountered: " + ((ASN1OctetStringParser)object).getClass());
    }
}
