/*---------------------------------------------------------------------------*\

    This program can build and burn bridges between two ports

         Voicetronix Voice Processing Board (VPB) Software

         Copyright (C) 1999-2008 Voicetronix www.voicetronix.com.au

         This library is free software; you can redistribute it and/or
         modify it under the terms of the GNU Lesser General Public
         License version 2.1 as published by the Free Software Foundation.

         This library is distributed in the hope that it will be useful,
         but WITHOUT ANY WARRANTY; without even the implied warranty of
         MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
         Lesser General Public License for more details.

         You should have received a copy of the GNU Lesser General Public
         License along with this library; if not, write to the Free Software
         Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
         MA  02110-1301  USA

\*---------------------------------------------------------------------------*/

#include "vpbapi.h"
#include "kbhit.h"

#include <string>
#include <cstdio>
#include <cstdlib>
#include <cstring>

using std::string;


static int arg_exists(int argc, char *argv[], const char *arg)
{ //{{{
	for(int i = 0; i < argc; ++i)
		if(strcmp(argv[i],arg) == 0) return i;

	return 0;
} //}}}

static void usage(const char *argv0)
{ //{{{
	printf("usage: %s [options] board1 port1 board2 port2\n\n", argv0);
	printf("  --noreset        Do not reset the ports upon start up\n");
	printf("  --listen         Create a half duplex bridge\n");
	printf("  --persist        Don't unbridge again at exit\n");
	printf("  --recgain db     Set the record gain to db.\n");
	printf("  --rec outfile    Record (half-duplex) to outfile.\n");
	printf("  --tap board port Monitor the bridge from another port\n");
	printf("  --log file       Record (full-duplex) to file.\n\n");
} //}}}

int main(int argc, char * argv[])
{ //{{{
	if(argc < 5) {
		usage(argv[0]);
		exit(EXIT_FAILURE);
	}

	string      recfile;
	int         arg;
	VPBOpenMode flags = VPB_OPEN_DEFAULTS;

	if( arg_exists(argc, argv, "--noreset") ) flags &= ~VPB_OPEN_RESET;

	int card1 = atoi(argv[argc - 4]);
	int port1 = atoi(argv[argc - 3]);
	int card2 = atoi(argv[argc - 2]);
	int port2 = atoi(argv[argc - 1]);
	int h1    = vpb_open(card1, port1, flags);
	int h2    = vpb_open(card2, port2, flags);
	int taph  = VPB_PORTHANDLE_NULL;

	if((arg = arg_exists(argc, argv, "--rec")) != 0) recfile = argv[arg+1];
	sleep(1);

	if((arg = arg_exists(argc, argv, "--recgain")) != 0) {
		float recgain = atof(argv[arg+1]);
		vpb_record_set_gain(h1, recgain);
		vpb_record_set_gain(h2, recgain);
	}

	string file1 = recfile + "-" + vpb_get_driver_version() + "-"
		     + argv[argc - 4] + "~" + argv[argc - 3] + ".wav";
	string file2 = recfile + "-" + vpb_get_driver_version() + "-"
		     + argv[argc - 2] + "~" + argv[argc - 1] + ".wav";

	if( ! recfile.empty() ) {
		vpb_record_file_async(h1, file1, VPB_LINEAR);
		vpb_record_file_async(h2, file2, VPB_LINEAR);

		printf("recording to %s and %s\n", file1.c_str(), file2.c_str());
	}

	if(arg_exists(argc, argv, "--listen")) {
		printf("Listen %d:%d to %d:%d ...\n", card1, port1, card2, port2);
		vpb_listen( h1, h2, VPB_BRIDGE_ON );
	} else {
		printf("Bridging %d:%d to %d:%d ...\n", card1, port1, card2, port2);
		vpb_bridge( h1, h2, VPB_BRIDGE_ON );
	}

	if((arg = arg_exists(argc, argv, "--tap")) != 0) {
		int tapcard = atoi(argv[arg+1]);
		int tapport = atoi(argv[arg+2]);
		taph        = vpb_open(tapcard, tapport, flags);

		vpb_monitor_audio(taph, h1);
	}

	if((arg = arg_exists(argc, argv, "--log")) != 0)
		vpb_log_to_file( h1, argv[arg+1] );

	for(;;) {
		switch( kbhit() )
		{
		    case 0: break;

		    case 'r':
			vpb_record_terminate_sync(h1);
			vpb_record_terminate_sync(h2);
			printf("\nRecording stopped.\n");
			break;

		    case 'R':
			printf("\nRecording ...\n");
			vpb_record_file_async(h1, file1, VPB_LINEAR);
			vpb_record_file_async(h2, file2, VPB_LINEAR);
			break;

		    default:
			goto done;
		}


		VPB_EVENT  e;
		char       s[VPB_MAX_STR];

		// Time out occasionally here to check if the user hit a key.
		if( vpb_get_event_sync(&e,250) != VPB_OK )
			continue;

		vpb_translate_event(&e, s);
		printf("%s",s);
	}

    done:

	if( ! arg_exists(argc, argv, "--persist") ) {
		printf("UN-Bridging %d:%d from %d:%d ...\n", card1, port1, card2, port2);
		vpb_bridge( h1, h2, VPB_BRIDGE_OFF );
		sleep(1);
	}

	if( taph != VPB_PORTHANDLE_NULL )
		vpb_monitor_terminate( taph );

	if(arg_exists(argc, argv, "--log"))
		vpb_log_terminate( h1 );

	//printf("stopping recording...\n");
	//if( ! recfile.empty() ) {
	//	vpb_record_terminate_sync(h1);
	//	vpb_record_terminate_sync(h2); }

	vpb_close();

	return EXIT_SUCCESS;
} //}}}

