#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <process.h>

#ifdef __USAGE
%C - translate arguments and start pterm
%C [options] [-e program arguments...]

Options:
-e shell            Program to run (/bin/sh)
-tty fd             Write pty name on this fd at startup (for wvideo).
-lo(gin)            Start shell as login shell.
-8859               Fonts are not 'PC' fonts
                    (changes terminal type to qnx8859m)
-t(itle)    string              Use 'string' as window title.
-geo(metry) N[xM]   (80x25)     Start terminal in N columns by M rows.
-mingeo     N[xM]   (10x10)     Min size of window in rows and cols
-maxgeo     N[xM]   (1000x1000) Max size of window in rows and cols
-font       name                Add 'name' to font list to load.
-initfont   name    (pcterm14)  Use 'name' as initial font.
#endif

#define N 100

char
	pterm[] = "/usr/photon/bin/pterm",
	*args[ N ];

int argn = 0;

void addarg( char *s ) {
	args[ argn ] = s;
/*	printf( "argv[ %d ] = '%s'\n", argn, s ); */
	if ( ++argn == N ) {
		fputs( "Too many arguments\n", stderr );
		exit( 2 );
	}	}

long multichar( const char *arg ) {
	unsigned char c;
	long val = 0;
	while	(	( c = *arg++ ) != '\0'
			&&	val <= 0xFFFFFF
				)
		val = val << 8 | tolower( c );
	return val;
	}

char *sh=0;

char **aptr, *opt, *arg;

char *getopt( void ) {
	if ( ( opt = *++aptr ) == NULL )
		--aptr;
	return opt;
	}

char *getarg( void ) {
	if ( ( arg = *++aptr ) == 0 ) {
		fprintf( stderr, "No argument for the '%s' option\n", opt );
		exit( 2 );
		}
	return arg;
	}

void cpyarg( char *op ) {
	addarg( op );
	addarg( getarg() );
	}

const char *digits( char *string ) {
	char *s = string;
	while ( isdigit( (unsigned char) *s ) )
		++s;
	*s = '\0';
	return string;
	}

void cpysize( char *op ) {
	char *h, *t;
	addarg( op );
	if ( ( t = strchr( h = getarg(), 'x' ) ) != NULL ) {
		if ( ( arg = malloc(strlen(arg)+1) ) == NULL ) {
			fputs( "No memory\n", stderr );
			exit( 2 );
			}
		*t++ = '\0';
		sprintf( arg, "%sx%s", digits(t), digits(h) );
		}
	addarg( arg );
	}

int main( int argc, char **argv ) {
	char *s;
	addarg( argv[0] );
	addarg( "-Q" );
	aptr = argv;
	while ( getopt() != NULL )
		switch ( multichar( opt ) ) {
			case '-e' :
				addarg( getarg() );
				while ( getopt() )
					addarg( opt );
				break;
			case '-885'	: addarg( "-8" ); break;
			case '-tty'	: cpyarg( "-N" ); break;
			case '-ini'	: cpyarg( "-f" ); break;
			case '-fon'	: cpyarg( "-a" ); break;
			case '-min'	: cpysize( "-m" ); break;
			case '-max'	: cpysize( "-M" ); break;
			case '-t'	:
			case '-tit'	: cpyarg( "-t" ); break;
			case '-lo'	:
			case '-log'	: addarg( "-l" ); break;
			case '-nob'	: addarg( "-b" ); break;
			case '-pcf'	: break;
			case '-geo'	: cpysize( "-g" ); break;
			default		: fprintf( stderr, "Argument ignored: '%s'\n", opt );
			}
	execv( pterm, args );
	return 2;
	}

