#ifndef FILEINPUTSTREAM_H
#define FILEINPUTSTREAM_H

/*
 * @(#)FileInputStream.h
 *
 * This file is part of webCDwriter - Network CD Writing.
 *
 * Copyright (C) 2003 Jörg P. M. Haeger
 *
 * webCDwriter is free software. See CDWserver.cpp for details.
 *
 * Jörg Haeger, 02.05.2002
 */

#include <stdio.h>
#include "Exception.h"
#include "File.h"

class FileInputStream {
	FILE *in;

public:
	FileInputStream() {
		in = NULL;
	}

	FileInputStream(File &file) {
		in = fopen(file.getPath().getBytes(), "r");
		if (in == NULL)
			throw new Exception(S.e + "Cannot open "
				+ file.getPath().getBytes());
	}

	FileInputStream(FileInputStream *stream) {
		in = stream->in;
		stream->in = NULL;
		delete stream;
	}

	~FileInputStream() {
		if (in != NULL)
			fclose(in);
	}

	FileInputStream &operator=(FileInputStream *stream) {
		if (in != NULL)
			fclose(in);

		in = stream->in;
		stream->in = NULL;
		delete stream;
	}

	int read() {
		if (in == NULL)
			return -1;

		int b = fgetc(in);
		if (b == EOF)
			return -1;
		return b;
	}

	int read(char *b, int off, int len) {
		if (in == NULL)
			return -1;

		return fread(&b[off], 1, len, in);
	}

	public: long skip(long n) {
		if (in == NULL)
			return 0;

		long pos0 = ftell(in);
		if (pos0 < 0)
			return 0;

		fseek(in, n, SEEK_CUR);

		long pos = ftell(in);
		if (pos < 0)
			return 0;

		return pos - pos0;
	}
};

#endif
