#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <tos.h>
#include <aes.h>
#include <mint\mintbind.h>


long	*cookies;



long get_cookiejar(void)
{
	long	**_cookiejar = (long **)0x5A0;
	int		  used;
	
	if (*_cookiejar == NULL)
	  return(0L);

	cookies = *_cookiejar;
	for (used = 0; cookies[2*used] != 0L; used++) {
		if (cookies[2*used] == 'MiNT')
			break;
		if (cookies[2*used] == 'MagX')
			break;
	}
	return(cookies[2*used]);
}



main(int argc, char *argv[])
{
	char	buff[BUFSIZ], *s;
	int		used, appl,
			msg[208];
	long    cookie;
	
	if (argc > 1)
	{
		strcpy(buff, "");
		for (used = 1; used < argc; used++)
		{
			strcat(buff, " ");
			strcat(buff, argv[used]);
		}
	}
	else
	{
		shel_read((char*)msg, &buff[1]);
	}
	buff[0] = (char)strlen(buff+1);

	if ((cookie = Supexec(get_cookiejar)) == 0L)
	{
		appl = appl_init();
		used = appl_find("GEMVIEW ");
		if (used >= 0)
		{
		    strcpy((char*)&msg[8], buff+1);
			msg[0] = 0xDF00;
			msg[1] = appl;
			msg[2] = (int)strlen(buff+1);
			msg[3] = 0x0000;
			appl_write(used, 16+msg[2], msg);
		}
		appl_exit();
	}
	else
	{
		appl = appl_init();
		used = appl_find("GEMVIEW ");
		if (used >= 0)
		{
		    strcpy((char*)&msg[8], buff+1);
			msg[0] = 0xDF00;
			msg[1] = appl;
			msg[2] = (int)strlen(buff+1);
			msg[3] = 0x0000;
			appl_write(used, 16+msg[2], msg);
		}
		else
		{
			appl_exit();
			if ((s = getenv("GEMVIEW")) == NULL)
			  s = "C:\\GEMVIEW.APP";
			if (cookie == 'MiNT') {
				if((int)Pexec(100, s, buff, NULL) < 0)
					return(-1);
			} else {
				if(shel_write(100, 1, 1, s, buff) < 0)
					return(-1);
			}
		}
		appl_exit();
	}
	return(0);
}
