/*
 * rplay.c
 *
 * Copyright (c) 1992 by Mark Boyns
 *
 * 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 "version.h"
#include "rplay.h"

char	*usage = "usage: rplay host[:host...] [option] sound ...\n\
	Where option can be only one of the following:\n\
	-s	stop\n\
	-p	pause\n\
	-c	continue\n\
	-v n	play at volume n (0 <= n <= 255)\n\
	or no option which will play at the default volume (128)\n\
";

main(argc, argv)
int	argc;
char	**argv;
{
	int		rplay_fd, c, attr, append_attr, volume, val; 
	char		*hosts, *p, *q;
	RPLAY		*rp;  
	extern char	*optarg; 
	extern int	optind;

	if (argc < 3) {
		fprintf(stderr, usage);
		exit(1);
	}

	hosts = argv[1];

	argc--;
	argv++; 

	attr = RPLAY_VOLUME_PLAY;
	append_attr = RPLAY_APPEND_VOLUME_PLAY;
	volume = RPLAY_DEFAULT_VOLUME;

	while((c = getopt(argc, argv, "v:spch")) != -1) {
		switch(c) {
		case 'v':
			volume = atoi(optarg);
			break;

		case 's':   
			attr = RPLAY_STOP;
			append_attr = RPLAY_APPEND_STOP;
			break;

		case 'p': 
			attr = RPLAY_PAUSE;
			append_attr = RPLAY_APPEND_PAUSE;
			break;

		case 'c':  
			attr = RPLAY_CONTINUE;
			append_attr = RPLAY_APPEND_CONTINUE;
			break;
		
		case 'h':
		case '?':
			fprintf(stderr, usage);
			exit(1);
		} 
	}
		     
	if (optind == argc) {
		fprintf(stderr, usage);
		exit(1);
	} 
	
	rp = rplay_create();  
	if (rp == NULL) {
		rplay_perror("rplay_create");
		exit(1);
	}
	  
	val = rplay_set(rp, attr,
		argv[optind++], attr == RPLAY_VOLUME_PLAY ? volume : NULL,
		NULL);
	if (val < 0) {
		rplay_perror("rplay_set");
		exit(1);
	}

	while(argv[optind] != NULL) {
		val = rplay_set(rp, append_attr,
			argv[optind++], append_attr == RPLAY_APPEND_VOLUME_PLAY ? volume : NULL,
			NULL);
		if (val < 0) {
			rplay_perror("rplay_set");
			exit(1);
		}
	}

	q = hosts;
	do {
		p = q;
		q = index(p, ':');
		if (q != NULL) {
			*q++ = '\0';
		}
		rplay_fd = rplay_open(p);
		if (rplay_fd < 0) {
			rplay_perror(p);
			exit(1);
		}
		if (rplay(rplay_fd, rp) < 0) {
			rplay_perror(p);
			exit(1);
		}
		rplay_close(rplay_fd);
	} while(q != NULL);

	exit(0);
}
