/***************************************************************************
    mmuwave_file_header.h  -  A class for the .wav file header

    begin                : July 2, 2001
    copyright            : (C) 2001 by Michael Minn
    email                : michael@michaelminn.com

    This program is free software; you can redistribute it and/or modify
    it under the terms of version 2 of the GNU General Public License as 
    published by the Free Software Foundation (see COPYING or www.gnu.org).

***************************************************************************/

#ifndef MMUWAVE_FILE_HEADER
#define MMUWAVE_FILE_HEADER

#include <string.h>
#include <unistd.h>

class mmuwave_file_header
{
	public:
	char riff_title[4];
	unsigned int header_chunk_length;
	char wave_title[4];

	char format_chunk_title[4];
	unsigned int format_chunk_length;
	unsigned short format_type;
	unsigned short channel_numbers;
	unsigned int sample_rate;
	unsigned int bytes_per_second;
	unsigned short bytes_per_sample;
	unsigned short bits_per_sample;

	char data_chunk_title[4];
	unsigned int data_chunk_length;

	mmuwave_file_header()
	{
		set_44khz_stereo();
	}

	void set_44khz_stereo()
	{
		memset(this, 0, sizeof(*this));
		memcpy(riff_title, "RIFF", 4);
		memcpy(wave_title, "WAVE", 4);

		memcpy(format_chunk_title, "fmt ", 4);
		format_chunk_length = 16;
		format_type = 1;
		channel_numbers = 2;
		sample_rate = 44100;
		bytes_per_second = 44100 * 4;
		bytes_per_sample = 4;
		bits_per_sample = 16;
		memcpy(data_chunk_title, "data", 4);
	}

	int is_valid_header()
	{
		return (strncmp(riff_title, "RIFF", 4) == 0) 
			&& (strncmp(wave_title, "WAVE", 4) == 0) 
			&& (channel_numbers > 0) 
			&& (channel_numbers <= 4)
			&& (bits_per_sample >= 8)
			&& (bits_per_sample <= 32);
	}

	int write_header(int file_descriptor)
	{
		struct stat file_status;

		if (fstat(file_descriptor, &file_status) < 0)
		{
			perror("Failure finding length of output file for header write");
			return -errno;
		}

		else if (lseek(file_descriptor, 0, SEEK_SET) == -1)
		{
			perror("Failure seeking start of output file for header write");
			return -errno;
		}

		data_chunk_length = file_status.st_size - sizeof(mmuwave_file_header);
		if (data_chunk_length < 0)
			data_chunk_length = 0;
		header_chunk_length = data_chunk_length + 36;

		if (write(file_descriptor, (void*) this, sizeof(mmuwave_file_header)) < 0)
		{
			perror("Failure writing output file header");
			return -errno;
		}

        return sizeof(mmuwave_file_header);
	}
};

#endif









