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

package org.bouncycastle.util.io.pem;

import java.util.List;
import org.bouncycastle.util.encoders.Base64;
import java.util.logging.Level;
import java.util.ArrayList;
import java.io.IOException;
import java.io.Reader;
import java.util.logging.Logger;
import java.io.BufferedReader;

public class PemReader extends BufferedReader
{
    public static final String LAX_PEM_PARSING_SYSTEM_PROPERTY_NAME = "org.bouncycastle.pemreader.lax";
    private static final String BEGIN = "-----BEGIN ";
    private static final String END = "-----END ";
    private static final Logger LOG;
    
    public PemReader(final Reader in) {
        super(in);
    }
    
    public PemObject readPemObject() throws IOException {
        String s;
        for (s = this.readLine(); s != null && !s.startsWith("-----BEGIN "); s = this.readLine()) {}
        if (s != null) {
            final String trim = s.substring("-----BEGIN ".length()).trim();
            final int index = trim.indexOf(45);
            if (index > 0 && trim.endsWith("-----") && trim.length() - index == 5) {
                return this.loadObject(trim.substring(0, index));
            }
        }
        return null;
    }
    
    private PemObject loadObject(final String str) throws IOException {
        final String string = "-----END " + str + "-----";
        final StringBuffer sb = new StringBuffer();
        final ArrayList list = new ArrayList();
        String line;
        while ((line = this.readLine()) != null) {
            final int index = line.indexOf(58);
            if (index >= 0) {
                list.add(new PemHeader(line.substring(0, index), line.substring(index + 1).trim()));
            }
            else {
                if (System.getProperty("org.bouncycastle.pemreader.lax", "false").equalsIgnoreCase("true")) {
                    final String trim = line.trim();
                    if (!trim.equals(line) && PemReader.LOG.isLoggable(Level.WARNING)) {
                        PemReader.LOG.log(Level.WARNING, "PEM object contains whitespaces on -----END line", new Exception("trace"));
                    }
                    line = trim;
                }
                if (line.indexOf(string) == 0) {
                    break;
                }
                sb.append(line.trim());
            }
        }
        if (line == null) {
            throw new IOException(string + " not found");
        }
        return new PemObject(str, list, Base64.decode(sb.toString()));
    }
    
    static {
        LOG = Logger.getLogger(PemReader.class.getName());
    }
}
