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

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

static VOID HostIn ();
static VOID HostOut ();

/*
 *	Connect  establishes a virtual terminal connection
 *	with the remote machine, over a tty line.
 *
 */

VOID Connect ()
{
#ifndef AMIGA
    register int child_pid;
    register FILE *fp;
#endif

    DBUG_ENTER ("Connect");
#ifdef AMIGA
    Error (NOCONNECT);
#else
    fp = NULL;
    if (!host) {
	Error (CONNECT);
    } else {
	if (photo != NULL) {
	    fp = fopen (photo, "w");
	    if (fp == NULL) {
		Error (PHOTO, photo);
	    }
	}
	child_pid = fork ();
	if (child_pid) {
	    HostOut ();
	    (VOID) kill (child_pid, 9);
	    if (fp != NULL) {
		(VOID) fclose (fp);
	    }
	} else {
	    HostIn (fp);
	}
    }
#endif	/* AMIGA */
    DBUG_VOID_RETURN;
}


/*
 *	We are the child process, so read from remote and send
 *	to user until killed by parent when disconnecting.
 *	Note infinite loop.
 *
 */

static VOID HostIn (fp)
FILE *fp;
{
    auto char c;

    c = NULL;
    while (TRUE) {
	(VOID) read (remfd, &c, 1);
	c &= 0177;		/* No 8 bit */
	if (c != '\000') {
	    (VOID) write (1, &c, 1);
	}
	if (fp != NULL) {
	    (VOID) putc (c, fp);
	    (VOID) fflush (fp);
	}
    }
}


/*
 *	We are the parent process, so read from user and
 *	send to remote, until disconnect character recieved.
 */
 
static VOID HostOut ()
{
    auto char c;
    
    DBUG_ENTER ("HostOut");
    c = NULL;
    (VOID) printf ("Connected.\r\n");
    HostRaw ();
    (VOID) read (0, &c, 1);
    while (c != escchr) {
	(VOID) write (remfd, &c, 1);
	c = NULL;
	(VOID) read (0, &c, 1);
    }
    HostCooked ();
    (VOID) printf ("\nDisconnected.\n");
    DBUG_VOID_RETURN;
}
