package net.argius.filetool;

import java.io.*;

import org.apache.tools.bzip2.*;

/**
 * BZIP2解凍処理。
 * AntAPIを使用してBZIP2形式の解凍を行う。
 */
public final class Bzip2Decompressor extends InputStream implements Decompressor {

    private CBZip2InputStream bis;

    /**
     * Bzip2Decompressorの生成。
     * @param is 入力ストリーム
     * @throws IOException 入出力エラーが発生した場合 
     */
    public Bzip2Decompressor(InputStream is) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        IOUtilities.transfer(is, bos, 2);
        String id = new String(bos.toByteArray(), "ISO8859-1");
        if (!id.equals("BZ")) {
            throw new IOException("bad file identifier: " + id);
        }
        this.bis = new CBZip2InputStream(is);
    }

    /* (overridden)
     * @see net.argius.filetool.compress.Decompressor#decompress(java.io.InputStream)
     */
    public void decompress(OutputStream os) throws IOException {
        IOUtilities.transferAll(bis, os);
    }

    /* (overridden)
     * @see java.io.InputStream#available()
     */
    public int available() throws IOException {
        return bis.available();
    }

    /* (overridden)
     * @see java.io.InputStream#read()
     */
    public int read() throws IOException {
        return bis.read();
    }

    /* (overridden)
     * @see java.io.InputStream#read(byte[])
     */
    public int read(byte[] b) throws IOException {
        return bis.read(b);
    }

    /* (overridden)
     * @see java.io.InputStream#read(byte[], int, int)
     */
    public int read(byte[] buf, int off, int len) throws IOException {
        return bis.read(buf, off, len);
    }

    /* (overridden)
     * @see java.io.InputStream#mark(int)
     */
    public void mark(int readlimit) {
        bis.mark(readlimit);
    }

    /* (overridden)
     * @see java.io.InputStream#markSupported()
     */
    public boolean markSupported() {
        return bis.markSupported();
    }

    /* (overridden)
     * @see java.io.InputStream#reset()
     */
    public void reset() throws IOException {
        bis.reset();
    }

    /* (overridden)
     * @see java.io.InputStream#skip(long)
     */
    public long skip(long n) throws IOException {
        return bis.skip(n);
    }

    /* (overridden)
     * @see java.io.InputStream#close()
     */
    public void close() throws IOException {
        try {
            bis.close();
        } finally {
            super.close();
        }
    }

}
