
/*
 * Copyright (C) 1990 by Jay Konigsberg. mail: jak@sactoh0
 *
 * Permission to use, copy, modify, and distribute this  software  and  its
 * documentation is hereby  granted,  provided  that  the  above  copyright
 * notice appear in all copies  and that  both  the  copyright  notice  and
 * this permission notice appear in supporting documentation. This software
 * is provided "as is" without express or implied  warranty.  However,  the
 * author retains all Copyright priviliges and rights  to  renumeration  if
 * this software is sold.
 */

/*
 * main - general setup and signal functions. Its life's work is to make
 * the bed for commands().
 */

#include "simped.h"

/*
Global for interrupt routine: cleanup()
*/
struct		termio	ttyset;		/* terminal settings */
unsigned	short	c_lflag_hold;	/* hold original values for reset */
unsigned	char	VEOF_hold;	/* hold original value for reset */

/* global to replace \b in input */
unsigned char bs_char;

void main(argc, argv)
int	argc;
char	**argv;
{
int	fprintf(),
	ioctl();

void	commands(),
	exit();

extern	int	cleanup();

char	*options();		/* command line options - returns filename */

char	*editfile=NULL;		/* The file being edited */

int	newfile=FALSE,		/* new or existing file */
	postnews=FALSE,		/* flag for postnews compatability */
	append=FALSE;		/* flag to always come up in append mode */

FILE	*fopen(),
	*fd=stdin;		/* file descriptor for command line */

/*
 * was a filename was entered on the command line?
 */

editfile = options(argc, argv, &postnews, &append, editfile);
if (editfile)
    {
    if ((fd = fopen(editfile, "r+")) == NULL)
	{
	newfile = TRUE;
	if ((fd = fopen(editfile, "a")) == NULL)
	    {
	    fprintf(stderr,"fopen failed: error=%d\n", errno);
	    exit(2);
	    }
	}
    }
else
    {
    newfile = TRUE;
    editfile = NULL;
    fd = stdin;
    }

/*
enter raw mode
*/
if ( ioctl(0, TCGETA, &ttyset) == -1 )
    {
    fprintf(stderr, "ioctl: error=%d\n", errno);
    exit(2);
    }
c_lflag_hold=ttyset.c_lflag;
VEOF_hold = ttyset.c_cc[4];
bs_char = ttyset.c_cc[2];
ttyset.c_cc[4] = (unsigned char)1;
ttyset.c_lflag &= ~(ICANON | ECHO);

if ( ioctl(0, TCSETAW, &ttyset) == -1 )
    {
    fprintf(stderr, "ioctl: error=%d\n",errno);
    }
signal(SIGINT, cleanup);

commands(editfile, &newfile, fd, postnews, append);
/*NOTREACHED*/
}
