/*	@(#)main.c	1.1	1/26/85	*/

#include "kermit.h"
#include "errors.h"

static int rflg = 0;
static int Rflg = 0;
static int sflg = 0;

static VOID OpenRemote ();
static VOID Options ();
static VOID CleanUp ();


/*
 *      K e r m i t
 *
 *      Main routine - parse command and option, set up the
 *      tty lines and dispatch to the appropriate routine.
 */

main (argc, argv)
int argc;
char *argv[];
{
    DBUG_ENTER ("main");
    DBUG_PROCESS (argv[0]);
    Options (argc, argv);
    OpenRemote ();
    SetSpeed ();
    GetModes ();
    SetUp ();
    if (cflg) {
	Connect ();
    } else if (sflg) {
	Send (argv);
    } else if (rflg) {
	Receive ();
    }
    CleanUp ();
    DBUG_RETURN (0);
}


/*
 *	Note that if we are a remote kermit then file with
 *	descriptor 0 is used to read/write packets.
 */
 
static VOID OpenRemote ()
{
    DBUG_ENTER ("OpenRemote");
    if (!Rflg) {
	host = TRUE;
	DBUG_2 ("host", "we are a host kermit");
    } else {
	remtty = TERMINAL;
	host = FALSE;
	DBUG_2 ("host", "we are a remote kermit");
    }
    DBUG_3 ("tty", "open '%s' as communications port", remtty);
    remfd = open (remtty, 2, 0777);
    if (remfd < 0) {
	Error (REMTTY, remtty);
	WrapUp (1);
    }
    DBUG_VOID_RETURN;
}


static VOID Options (argc, argv)
int argc;
char *argv[];
{
    register int fchar;
    extern char *optarg;
    extern int getopt ();

    DBUG_ENTER ("options");
    if (argc < 2) {
	Usage ();
    }
    while ((fchar = getopt (argc, argv, "#:hcstrRme:l:b:p:")) != EOF) {
	switch (fchar) {
	    case '#': 
		DBUG_PUSH (optarg);
		break;
	    case 'h': 
		Help ();
		exit (0);
	    case 'c': 
		cflg++;
		break;
	    case 'm':
	        mflg++;
		break;
	    case 's': 
		sflg++;
		break;
	    case 't':
	        tflg++;
		break;
	    case 'r': 
		rflg++;
		break;
	    case 'R':
	        Rflg++;
		break;
	    case 'e': 
		escchr = atoi (optarg);
		DBUG_3 ("args", "esc char is %o", escchr);
		break;
	    case 'l': 
		remtty = optarg;
		DBUG_3 ("args", "remote tty line is %s", remtty);
		break;
	    case 'p': 
		photo = optarg;
		DBUG_3 ("args", "photo file is %s", photo);
		break;
	    case 'b': 
		NewSpeed (atoi (optarg));
		DBUG_3 ("args", "speed is %d baud", optarg);
		break;
	}
    }
    if ((cflg + sflg + rflg) != 1) {
	Error (MODE);
	WrapUp (1);
    }
    DBUG_VOID_RETURN;
}

