/* hilo - print highest and lowest sample values */

#include <stdio.h>
#include <fcntl.h>
#include <functions.h>
#include <hackercorp/iff.h>
#include <hackercorp/8svx.h>

#include "prototypes.h"

Voice8Header v8head;

short buffer[512];

char *program_name = "fziff";

long nsamples;
UBYTE *bodyp;

void freebody(void)
{
	if (bodyp)
		FreeMem(bodyp,nsamples);
}

main(int argc, char *argv[])
{
	int fzfd, svxfd;
	UBYTE *outp;
	int i;

	if (argc != 3)
	{
		fprintf(stderr,"usage: fziff fz1dumpfilename new8svxfilename\n");
		exit(1);
	}

	init_libs();

	/* open the sample file read from the casio fz-1 by karl's fz-1 read stuff */
	if ((fzfd = open(argv[1],O_RDONLY)) == -1)
	{
		perror(argv[1]);
		exit(2);
	}

	/* eventually get the real number from the voice parameters */
	nsamples = (lseek(fzfd,0L,2) - 1024) / 2;

	/* initialize the VHDR chunk */
	v8head.oneShotHiSamples = nsamples;
	v8head.repeatHiSamples = 0;
	v8head.samplesPerHiCycle = 0;
	v8head.samplesPerSec = 17987;	/* get it out of the header eventually */
	v8head.ctOctave = 0;
	v8head.sCompression = 0;
	v8head.volume = 65535;

	/* skip the voice parameters for now - this assumes, as the casio dumper
	 * does, only one voice and no banks */
	if (lseek(fzfd, 1024L,0) == -1)
	{
		perror(argv[1]);
		exit(3);
	}

	/* get that IFF file open, we have to cleanup from now on */
	if ((svxfd = CreateIFF(argv[2],ID_FORM,ID_8SVX)) == -1)
		panic("unable to create IFF 8SVX file\n");

	if (!WriteChunk(svxfd,ID_VHDR,&v8head,sizeof(v8head)))
		panic("unable to write VHDR chunk");

	if (!WriteTextChunk(svxfd,ID_NAME,argv[2]))
		panic("unable to write NAME chunk");

/*
	if (!WriteTextChunk(svxfd,ID_Copyright,"Copyright (C) 1989 Hackercorp.  All Rights Reserved."))
		panic("unable to write Copyright chunk");

	if (!WriteTextChunk(svxfd,ID_ANNO,"sampled on a 16-bit synth and converted for the Amiga by Karl Lehenbauer/Hackercorp"));

*/

	if ((bodyp = AllocMem(nsamples,0)) == NULL)
		panic("unable to alloc sample memory");

	add_cleanup(freebody);
	outp = bodyp;
	while (read(fzfd,&buffer[0],1024) == 1024)
	{
		for (i = 0; i < 512; i++)
			*outp++ = buffer[i] & 0xff;
	}
	WriteChunk(svxfd,ID_BODY,bodyp,nsamples);

	Rewrite_IFF_header(svxfd);
	exit(0);
}

