/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ipmreader;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;

/**
 *
 * @author Lisewski
 */
public class IPMInputStream {
    FileInputStream fis;
    ByteArrayInputStream bais;
    int blockSize = 1012;
    char blockChar = 0x40;
    byte[] ba = new byte[blockSize];
    int bytesLeft = 0;
    boolean lastBlock = false;
    
    public IPMInputStream(String fileName) throws Exception{
        fis = new FileInputStream(fileName);
    }
    public byte[] readNBytes(int bytes) throws Exception{
        byte[] tmp = new byte[bytes];
        int bytesRead = 0;
        if (bytesLeft < bytes) {
            // Read part of the bytes then get a new block
            if (bytesLeft > 0) {
                bais.readNBytes(tmp, 0, bytesLeft);
                bytesRead = bytesLeft;
            }
            readBlock();
        }
        if (bytesRead < bytes) {
            bais.readNBytes(tmp, bytesRead, bytes - bytesRead);
            bytesLeft -= bytes - bytesRead;
        }
        return tmp;
    }
    public boolean lastBlock() {
        return lastBlock;
    }
    private void readBlock() throws Exception {
        bytesLeft = fis.readNBytes(ba, 0, blockSize);
//        System.out.println("bytesLeft : " + bytesLeft);
//        bytesLeft = ba.length;
        bais = new ByteArrayInputStream(ba);
        if (bytesLeft == blockSize) {
            // Read Padding
            byte[] padding = fis.readNBytes(2);
            if (padding[0] != blockChar || padding[1] != blockChar)
                System.out.println(String.format("Padding contains wrong characters %H%H. Expected %H%H",blockChar, blockChar, padding[0], padding[1]));
        } else {
            lastBlock = true;
        }
    }
    
}
