/*
 * recordchaintest.c - this test shows how to chain small recordings
 * and append them to a soundfile.
 */ 
#import	<stdio.h>
#import	<sound/sound.h>

#define	NUM_BUFFERS	2
#define	BUF_SIZE	8192
#define	SECONDS		10000.0

static SNDSoundStruct *buffers[NUM_BUFFERS];
static FILE *sfp;
static int requestedDataSize, recordedDataSize = 0;
static int lastBufNum;

static void record(int tag);

static int recordDone(SNDSoundStruct *s, int tag, int err)
/*
 * Called when a buffer has been recorded.
 * Appends the buffer to the soundfile and initiates recording into it again.
 */
{
    if (recordedDataSize >= requestedDataSize)
	return 0;
    if (err)
        fprintf(stderr, "recordDone: %s\n", SNDSoundError(err));
    if (fwrite((void*)((char*)s + s->dataLocation), 1, s->dataSize, stdout) !=
	s->dataSize)
	fprintf(stderr, "recordDone: could not write data to soundfile\n");

    recordedDataSize += s->dataSize;
    record((lastBufNum + 1) % NUM_BUFFERS);
    return 0;
}

static void record(int bufNum)
/*
 * Initiates recording into a buffers[bufNum].
 */
{
    int err;
    static int tag = 1;
    
    lastBufNum = bufNum;
    if (err = SNDStartRecording(buffers[bufNum], tag++, 0, 0, SND_NULL_FUN,
				recordDone))
        fprintf(stderr, "record: %s\n", SNDSoundError(err));
}

static void init(int n, int size)
/*
 * Allocate n sound buffers.
 * Creates the soundfile.
 */
{
    int i, err;
    SNDSoundStruct s;

    for (i = 0; i < n; i++)
        if (err = SNDAlloc(&buffers[i], size, SND_FORMAT_MULAW_8,
			   SND_RATE_CODEC, 1, 4))
	    fprintf(stderr, "init: %s\n", SNDSoundError(err));
    if (fwrite((void *)&s, sizeof(SNDSoundStruct), 1, stdout) != 1)
	fprintf(stderr, "init: could not write dummy header to soundfile\n");
}

static void cleanup(void)
/*
 * Write the soundfile header.
 */
{
    SNDSoundStruct s;

    s.magic = SND_MAGIC;
    s.dataLocation = sizeof(SNDSoundStruct);
    s.dataSize = recordedDataSize;
    s.dataFormat = SND_FORMAT_MULAW_8;
    s.samplingRate = SND_RATE_CODEC;
    s.channelCount = 1;

    if (fwrite((void *)&s, sizeof(SNDSoundStruct), 1, stdout) != 1)
	fprintf(stderr, "cleanup: could not write header to soundfile\n");
}

main(int argc, char *argv[])
{
    int i;

    requestedDataSize = SECONDS * SND_RATE_CODEC;
    cleanup();
    init(NUM_BUFFERS, BUF_SIZE);
    for (i=0; i<NUM_BUFFERS; i++)
		record(i);
    SNDWait(0);
}
