
package turgen.tapeimage;

import java.io.InputStream;
import java.io.OutputStream;
import turgen.FileFormatException;

/** baud tape image chunk*/
public class BaudChunk implements TapeImageChunk {

    /**Chunk type*/
    private static final String type="baud";
    /**Chunk length*/
    private int length;
    /**Baud rate*/
    private int baudRate;
    /**Data*/
    private int[] data;

    public BaudChunk() {
        
    }

    public BaudChunk(int baudRate) {
        length=0;
        this.baudRate=baudRate;
        data = new int[0];
    }

    public String getType() {
        return type;
    }

    public int getLength() {
       return length;
    }

    public int[] getData() {
        return data;
    }

    public boolean isGeneretedUsingParent() {
        return false;
    }


    public int getBaudRate() {
        return baudRate;
    }

    public void readFromStream(InputStream s) throws Exception {
        
        /*Read length and baud rate*/
        int lengthLo = s.read();
        int lengthHi = s.read();
        int baudLo=s.read();
        int baudHi=s.read();

        if (lengthLo==-1 || lengthHi==-1 || baudLo==-1 || baudHi==-1) {
            throw new FileFormatException("Truncated baud chunk header");
        }

        length = lengthLo + (256*lengthHi);
        baudRate = baudLo + (256*baudHi);
        
        /*Read data*/
        data = new int[length];
        for(int i=0;i<length;i++) {
            int b = s.read();
            if (b==-1) throw new FileFormatException("Truncated baud chunk data");
            data[i]=b;
        }
    }

    public void writeToStream(OutputStream s) throws Exception {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public String toString() {
        return "baud: ["+Integer.toString(baudRate)+" bd] ("+Integer.toString(length)+")";
    }

    public TapeImageChunk getParent() {
        return null;
    }


}
