/* play.c - play a sound file on the speaker
**
** 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 <fcntl.h>
#include <sys/file.h>
#include <sys/signal.h>
#include "libsst.h"

#define MYBUF 256

int sst_fd;

main( argc, argv )
int argc;
char *argv[];
    {
    int rrtn, wrtn;
    unsigned char buf[MYBUF];
    int file_fd;
    int argn, loop;
    int sighandler();
    char *usage = "usage:  %s [-l] [<file>]\n";

    sst_fd = sst_open( );
    (void) signal( SIGHUP, sighandler );
    (void) signal( SIGINT, sighandler );

    argn = 1;
    loop = 0;

    if ( argn < argc && argv[argn][0] == '-' )
	{
	if ( argv[argn][1] == 'l' && argv[argn][2] == '\0' )
	    loop = 1;
	else
	    {
	    fprintf( stderr, usage, argv[0] );
	    exit( 1 );
	    }
	argn++;
	}
    if ( argn == argc )
	{
	if ( loop )
	    {
	    fprintf( stderr, "can't loop stdin, aye!\n" );
	    exit( 1 );
	    }
	file_fd = 0;
	}
    else
	{
	file_fd = open( argv[argn], O_RDONLY );
	if ( file_fd < 0 )
	    {
	    perror( argv[argn] );
	    exit( 1 );
	    }
	argn++;
	}
    if ( argn != argc )
	{
	fprintf( stderr, usage, argv[0] );
	exit( 1 );
	}

#if 0	/* fast write, no crap */
    while ( (rrtn = read(file_fd, buf, MYBUF)) > 0) {
	wrtn = write(sst_fd, buf, rrtn);
	if (wrtn < 0) {
		perror("write fails");
		exit(0);
	}
	if (wrtn != rrtn) {
		fprintf(stderr, "read %d, wrote %d\n", rrtn, wrtn);
	}
    }
#else		/* old crap */
    for ( ; ; )
	{
	rrtn = read( file_fd, buf, MYBUF );
	if ( rrtn < 0 )
	    {
	    perror( "read" );
	    exit( 1 );
	    }
	if ( rrtn == 0 )
	    {
	    if ( loop )
		{
		if ( lseek( file_fd, 0, L_SET ) == -1 )
		    {
		    perror( "lseek" );
		    exit( 1 );
		    }
		continue;
		}
	    else
		break;
	    }

	for ( ; ; )
	    {
	    wrtn = write( sst_fd, buf, rrtn );
	    if ( wrtn < 0 )
		{
		perror( "write" );
		exit( 1 );
		}
	    if ( wrtn != 0 )
		break;
	    usleep( 1000 );
	    }
	if ( wrtn != rrtn )
	    {
	    fprintf( stderr, "play: rrtn = %d, wrtn = %d\n", rrtn, wrtn );
	    exit( 1 );
	    }
	}
#endif

    sst_close( sst_fd );
    exit( 0 );
    }

int
sighandler( )
    {
    sst_close( sst_fd );
    exit( 1 );
    }
