#ifndef WAVE_H
#define WAVE_H

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

#include "File.h"
#include "FileInputStream.h"

/**
 * A class to handle WAV files.
 *
 * @version 20021019
 * @author Jörg P. M. Haeger
 */
class Wave {
private:
	int format;
	int channels;
	long frequency;
	long bytesPerSecond;
	int bytesPerSample;
	long dataLength;

public:
	Wave(File &file) {
		FileInputStream inStream = new FileInputStream(file);
		char bs[44];
		if (inStream.read(bs, 0, 44) < 44
			|| bs[0] != 'R' || bs[1] != 'I'
			|| bs[2] != 'F' || bs[3] != 'F'
			|| bs[8] != 'W' || bs[9] != 'A'
			|| bs[10] != 'V' || bs[11] != 'E')
			throw new Exception("is not a WAV");

//		inStream.close();
		format = uint16(bs, 20);
		if (format != 1)
			throw new Exception("has an invalid format");

		channels = uint16(bs, 22);
		frequency = uint32(bs, 24);
		bytesPerSecond = uint32(bs, 28);
		bytesPerSample = uint16(bs, 32);
		dataLength = uint32(bs, 40);
	}

	long getSeconds() {
		return dataLength / bytesPerSecond;
	}

	int uint16(char *bs, int offset) {
		return
			((bs[offset + 1] & 0xff) << 8)
			| (bs[offset] & 0xff);
	}

	long uint32(char *bs, int offset) {
		return
			((bs[offset + 3] & 0xff) << 24)
			| ((bs[offset + 2] & 0xff) << 16)
			| ((bs[offset + 1] & 0xff) << 8)
			| (bs[offset] & 0xff);
	}
};

#endif
