/* mix.c - mix multiple sound files
**
** Copyright (C) 1989 by Jef Poskanzer.
**
** Permission to use, copy, modify, and distribute this software and its
** documentation for any purpose and without fee is hereby granted, provided
** that the above copyright notice appear in all copies and that both that
** copyright notice and this permission notice appear in supporting
** documentation.  This software is provided "as is" without express or
** implied warranty.
*/

#include <stdio.h>
#include <strings.h>
#include "libst.h"

#define MAXFILES 64	/* the kernel's got a limit, why shouldn't I? */
#define MYBUFSIZ 256

main( argc, argv )
int argc;
char *argv[];
    {
    FILE *files[MAXFILES];
    char mybuf[MYBUFSIZ];
    int nfiles, i, c, sum, gotone;

    nfiles = argc - 1;
    if ( nfiles < 2 )
	{
	fprintf( stderr, "usage:  %s <file1> <file2> [<fileN> ...]\n", argv[0] );
	exit( 1 );
	}

    for ( i = 0; i < nfiles; ++i )
	{
	if ( strcmp( argv[i + 1], "-" ) == 0 )
	    files[i] = stdin;
	else
	    {
	    files[i] = fopen( argv[i + 1], "r" );
	    if ( files[i] == NULL )
		{
		perror( argv[i + 1] );
		exit( 1 );
		}
	    }
	}
    setbuffer( stdout, mybuf, MYBUFSIZ );
    
    for ( ; ; )
	{
	sum = 0;
	gotone = 0;
	for ( i = 0; i < nfiles; ++i )
	    {
	    if ( files[i] != NULL )
		{
		c = getc( files[i] );
		if ( c == EOF )
		    {
		    fclose( files[i] );
		    files[i] = NULL;
		    }
		else
		    {
		    gotone = 1;
		    sum += st_ulaw_to_linear( (unsigned char) c );
		    }
		}
	    }
	if ( gotone == 0 )
	    break;
	LINCLIP( sum );
	putchar( st_linear_to_ulaw( sum ) );
	}

    exit( 0 );
    }
