/* Copyright (C) 1981,1982, 1983 by Manx Software Systems */
#include "errno.h"
#include "fcntl.h"
#include "io.h"

int badfd(), noper();

/*
 * channel table: relates fd's to devices
 */
struct channel  chantab[] = {
	{ 2, 0, 1, 0, noper, 2 },
	{ 0, 2, 1, 0, noper, 2 },
	{ 0, 2, 1, 0, noper, 2 },
	{ 0, 0, 0, 0, badfd, 0 },
	{ 0, 0, 0, 0, badfd, 0 },
	{ 0, 0, 0, 0, badfd, 0 },
	{ 0, 0, 0, 0, badfd, 0 },
	{ 0, 0, 0, 0, badfd, 0 },
	{ 0, 0, 0, 0, badfd, 0 },
	{ 0, 0, 0, 0, badfd, 0 },
	{ 0, 0, 0, 0, badfd, 0 },
};

#define MAXARGS 30
static char *Argv[MAXARGS];
static int Argc;
int fd_clsall();
int (*_closall)() = fd_clsall;

Croot(cp)
register char *cp;
{
	register char *fname;
	register int k;

	Argv[0] = "";
	Argc = 1;
	while (Argc < MAXARGS) {
		while (*cp == ' ' || *cp == '\t')
			++cp;
		if (*cp == 0)
			break;
		if (*cp == '>') {		/* redirect output */
			k = 1;
			goto redirect;
		} else if (*cp == '<') {	/* redirect input */
			k = 0;
redirect:
			while (*++cp == ' ' || *cp == '\t')
				;
			fname = cp;
			while (*++cp)
				if (*cp == ' ' || *cp == '\t') {
					*cp++ = 0;
					break;
				}
			close(k);
			if (k)
				k = creat(fname, 0666);
			else
				k = open(fname, O_RDONLY);
			if (k == -1)
				redir_err(fname);
		} else {
			Argv[Argc++] = cp;
			while (*++cp)
				if (*cp == ' ' || *cp == '\t') {
					*cp++ = 0;
					break;
				}
		}
	}
	main(Argc,Argv);
	exit(0);
}

static redir_err(name)
char *name;
{
	char buff[200];

	strcpy(buff, "Can't open file for redirection: ");
	strcat(buff, name);
	strcat(buff, "\n");
	write(2, buff, strlen(buff));
	exit(10);
}

exit(code)
{
	(*_closall)();
	boot_(code);
}

badfd()
{
	errno = EBADF;
	return -1;
}

noper()
{
	return 0;
}

