/* mte.c - MCONV Text Editor
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <errno.h>
#include <sys/stat.h>
#include <unistd.h>
#include "getopt.h"
#include "terminal.h"

int rf_redraw = 0;
int menuview_rescan_now = 0;
int menuview_last_resize = 0;
int menuview_exitup = 0;

int ed_main(char *, long, char *, char *);
void display_version(void);


/* Display command-line help for mgid.
 */
void display_help(void)
{
	printf("\
Usage: mte FILE\n\
Edit FILE.\n\
\n\
      --help            show this help and exit\n\
  -V, --version         show version information and exit\n\
\n\
Report bugs to <mconv@ivarch.com>.\n\
");
}


/* Handle SIGCONT by reinitialising the terminal.
 */
void sh_cont(int s)
{
	t_init(getenv("TERM"));
	t_echo_off();
	t_canon_off();
	t_clearscreen = 1;
	signal(SIGCONT, sh_cont);
}


/* Process command-line arguments, and edit the given file.
 */
int main(int argc, char *argv[])
{
	struct option long_options[] = {
		{"help", 0, 0, '!'},
		{"version", 0, 0, 'V'},
		{0, 0, 0, 0}
	};
	char *short_options = "V";
	int option_index = 0;
	int read_something = 0;
	struct stat sb;
	FILE *fptr;
	char *file;
	char *pn;
	int c, r, e;

	pn = strrchr(argv[0], '/');
	if (pn)
		pn++;
	else
		pn = argv[0];

	do {				    /* read options */
		c = getopt_long(argc, argv, short_options, long_options,
				&option_index);
		if (c < 0)
			continue;
		switch (c) {
		case 'V':
			display_version();
			return (0);
			break;
		case '!':
			display_help();
			return (0);
			break;
		default:
			fprintf(stderr,
				"Try `%s --help' for more information.\n\r",
				pn);
			return (1);
			break;
		}
	} while (c != -1);

	c = 0;				    /* exit status */

	signal(SIGINT, SIG_IGN);	    /* ignore ^C */
#ifdef DEBUG
	/* don't trap SIGQUIT */
#else				/* !DEBUG */
	signal(SIGQUIT, SIG_IGN);	    /* ignore ^\ */
#endif				/* DEBUG */
	signal(SIGCONT, sh_cont);

	while (optind < argc) {		    /* edit each file in turn */

		file = argv[optind];
		r = 0;

		if (stat(file, &sb)) {	    /* create file if nonexistent */
			fptr = fopen(file, "w");
			if (fptr) {
				r = 1;
				fclose(fptr);
			}
		}

		t_init(getenv("TERM"));
		t_echo_off();
		t_canon_off();

		e = ed_main(file, 0, file, 0);

		if (e < 0) {
			t_echo_on();
			t_canon_on();
			fprintf(stderr, "%s: %s: %s\n\r", pn, file,
				strerror(errno));
			c = 1;
		} else {
			t_echo_on();
			t_canon_on();
		}

		if ((e != 0) && (r))
			remove(file);

		read_something = 1;
		optind++;
	}

	if (!read_something) {		    /* no valid files specified */
		fprintf(stderr, "%s: no valid files specified\n\r", pn);
		c = 1;
	}

	return (c);
}

/* EOF */
