/*
 * Worldvisions Weaver Software:
 *   Copyright (C) 1998 Worldvisions Computer Technology, Inc.
 * 
 * simpleconn is a very simple program that forwards data between an
 * arbitrary given files (which are usually devices, named pipes, etc).  If
 * a file is named '-', it refers to stdin/stdout.
 */
#include "wvstream.h"


static int bouncer(WvStream &s, void *userdata)
{
    WvStreamList &l = *(WvStreamList *)userdata;
    WvStreamList::Iter i(l);
    char buf[1024];
    size_t len;
    
    len = s.read(buf, sizeof(buf));
    if (!len) return 0;
    
    for (i.rewind(); i.next(); )
    {
	WvStream &out = *i.data();
	
	if (&s != &out  &&  out.isok()  &&  out.select(0, false, true))
	    out.write(buf, len);
    }
    
    return 0;
}


int main(int argc, char **argv)
{
    WvStreamList l;
    int count;
    
    if (argc < 2)
    {
	fprintf(stderr, "Usage: %s file [file...]\n"
		"     Passes data between the given files/devices/etc.  "
		"If a filename is\n"
		"     '-', it refers to stdin/stdout.\n",
		argv[0]);
	return 1;
    }
    
    for (count = 1; count < argc; count++)
    {
	WvStream *f;
	
	if (!strcmp(argv[count], "-"))
	{
	    f = wvcon;
	    l.append(f, false);
	}
	else
	{
	    f = new WvFile(argv[count], O_RDWR);
	    
	    if (!f->isok())
	    {
		delete f;
		f = new WvFile(argv[count], O_RDONLY);
		if (!f->isok())
		{
		    fprintf(stderr, "%s: %s\n", argv[count], f->errstr());
		    return 1;
		}
	    }
	    
	    l.append(f, true);
	}
	
	f->setcallback(bouncer, &l);
    }
    
    for (;;)
    {
	if (l.select(-1))
	    l.callback();
    }
    
    return 0;
}
