/*
 * $Id: VKCInputStream.java,v 1.3 2003/12/10 14:46:19 koppy Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 *
 * $Log: VKCInputStream.java,v $
 * Revision 1.3  2003/12/10 14:46:19  koppy
 * robuster gemacht
 *
 * Revision 1.2  2003/12/02 23:55:22  koppy
 * vervollständigt
 *
 * Revision 1.1  2003/11/28 17:13:58  koppy
 * Initiale Version
 *
 *
 */
package vkc.util;

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

/**
 * This class represents an inputstream
 * which provides the total size of the stream.
 * <p>
 * <b>IMPORANT NOTE</b>: It only reads the specified size of bytes
 * then returns -1, even if there are still bytes available
 * from the underlying inputstream!!
 * </p>
 * 
 * @author koppy
 */
public class VKCInputStream extends FilterInputStream {

	private long length;
	private long remainingBytes;
	
	/**
	 * Creates a VKCInputStream that uses the specified
	 * underlying InputStream.
	 *
	 * @param  in   the specified input stream
	 * @param length the length of the stream
	 */
	public VKCInputStream(InputStream in, long length) {
		super(in);
		this.length = length;
		this.remainingBytes = length;
	}
		

	/**
	 * @return
	 */
	public long getLength() {
		return length;
	}

	/** 
	 * (non-Javadoc)
	 * @see java.io.InputStream#read(byte[], int, int)
	 */
	public int read(byte[] b, int off, int len) throws IOException {
		
		if( remainingBytes == 0 )
			return -1;
					
		int bytesToRead = (remainingBytes > len )? (int)len: (int)remainingBytes;
		int bytesRead = super.read(b, off, bytesToRead);
		
		remainingBytes-= bytesRead;				
		return bytesRead;
	}

	/** 
	 * (non-Javadoc)
	 * @see java.io.InputStream#skip(long)
	 */
	public long skip(long n) throws IOException {
		
		long skipped = super.skip(n); 
		remainingBytes-=skipped;
		
		return skipped;
	}

	/** 
	 * (non-Javadoc)
	 * @see java.io.InputStream#read(byte[])
	 */
	public int read(byte[] b) throws IOException {
		
		return this.read(b, 0, b.length );
	}

	/**
	 *  (non-Javadoc)
	 * @see java.io.InputStream#read()
	 */
	public int read() throws IOException {
		
		int read = super.read();
		if( read > -1 ) 
			remainingBytes--;
			
		return read; 
	}

}
