#

/*
 *	main.c: main loop of ksosdb
 *
 *
 *	Build by get(I)'ing all the source files into
 *		a directory. Then execute:
 *
 *			cc *.c -lS -lpw -lPW
 */

#include "globals.h"
#include <stdio.h>

char	*_S_main	"@(#)main.c	1.11";

PROCESS main( argc, argv )

VAR	char	**argv;
	integer	argc;

BEGIN	initialize( argc, argv );

	WHILE command != QUIT
	DO	printf("> ");
		command = getcmd();

		CASE command OF
		case NOCMD	: BEGIN printf("?\n");
				  ENDCASE;
		case HELP	: BEGIN help();
				  ENDCASE;
		case QUIT	: BEGIN cleanup();
				  ENDCASE;
		case DOT	: BEGIN display( addr-dsplysz, addr );
				  ENDCASE;
		case NL		: BEGIN addr = addr + step;
					display( addr, addr );
				  ENDCASE;
		case DISPLAY	: BEGIN addr = addr+step;
					display( addr, addr+dsplysz );
					addr = addr+dsplysz;
				  ENDCASE;
		case BACK	: BEGIN addr = addr - step;
				  ENDCASE;
		case EQUAL	: BEGIN prtdot();
				  ENDCASE;
		case LOOK	: BEGIN look();
				  ENDCASE;
		case TEXT	: BEGIN text();
				  ENDCASE;
		case DATA	: BEGIN data();
				  ENDCASE;
		case LABEL	: BEGIN label();
				  ENDCASE;
		case NAME	: BEGIN	fndlab();
				  ENDCASE;
		case STACK	: BEGIN stack();
				  ENDCASE;
		case REG	: BEGIN reg();
				  ENDCASE;
		case PPT	: BEGIN ppt();
				  ENDCASE;
		case SIGNAL	: BEGIN sgnal();
				  ENDCASE;
		case SHELL	: BEGIN shell();
				  ENDCASE;
		case PREV	: BEGIN	prev();
				  ENDCASE;
		case NEXT	: BEGIN next();
				  ENDCASE;
		case TABLE	: BEGIN table();
				  ENDCASE;
		case MODE	: BEGIN setmode();
				  END;
		END
	END
END


#define	MAXARGS	20

char	pathstr[128];
char	shellnam[16];

/*
 *	shell: fork off inferior shell(I)
 */

PROCEDURE shell()

BEGIN	VAR	integer	childid;
		integer	status;
		integer pid;
		integer	oldsig;
		integer	index;
		integer i;
		char	args[MAXARGS][MAXLINELENGTH];
		char	*argv[MAXARGS];
		char	name[MAXLINELENGTH];
		boolean command;


	pathstr[0] = eos;
	shellnam[0] = eos;

	pexinit();

	index = 0;

	LOOP	getword( args[index] );

		WHEN ( args[index][0] == eos ) DO EXIT;

		WHEN index == MAXARGS
		DO	printf("Too many arguments\n");
		EXIT;

		inc( index );
	END;

	i = 0;
	LOOP	WHEN i == index 
		DO	argv[i] = 0;
		EXIT;
	
		argv[i] = &args[i];

		inc(i);
	END;

	IF index == 0
	THEN	command = false;
	ELSE	move( args[0], name, size(args[0]) );
		command = true;
	END;

	oldsig = signal( 2, 1 );

	IF childid = fork()
	THEN	/* parent process */

		LOOP	pid = wait( &status );

			WHEN ( pid == -1 ) OR ( pid == childid ) DO EXIT;
		END;

		signal( 2, oldsig );

	ELSE	/* child process */

		signal( 2, oldsig );

		IF command
		THEN	pexec( name, argv );
		ELSE	execl( shellnam, shellnam, 0 );
		END;

		exit(0);
	END
END
