/**********************************************************************
 
	Copyright (C) 2003 Tomohito Nakajima<nakajima@zeta.co.jp>
 
	This program is free software; you can redistribute it 
	and/or modify it under the terms of the GLOBALBASE 
	Library General Public License (G-LGPL) as published by 

	http://www.globalbase.org/
 
	This program is distributed in the hope that it will be 
	useful, but WITHOUT ANY WARRANTY; without even the 
	implied warranty of MERCHANTABILITY or FITNESS FOR A 
	PARTICULAR PURPOSE.

**********************************************************************/
#include <windows.h>
#include <stdio.h>

/*
	gbs proccess observer.
	communicate with stabilizer (arch/win/std/utils/stabilizer.c)
*/

#define ARG_MAX 256

static void chop(char *str){
	if(str==NULL)
		return;
	while(strlen(str)>=1 && 
		(str[strlen(str)-1] == '\r'||
		str[strlen(str)-1] == '\n')
		){

		str[strlen(str)-1] = '\0';
	}
}

static void execute(int argc, char *argv[], char *stabilizer_param){
char argstr[1024];
int i;
	argstr[0]=0;
	if(stabilizer_param){
		sprintf(argstr, "-stab %s ", stabilizer_param);
	}
	for(i=1;i<argc;++i){
		sprintf(argstr+strlen(argstr), "\"%s\" ", argv[i]);
	}
	
	ShellExecute(
		NULL,
		"open",
		argv[0],
		argstr,
		NULL,
		SW_SHOWDEFAULT
	);
}

int main(int argc, char* argv[])
{
char buf[512];
char *pbuf;
char c;
int _argc;
char *_argv[ARG_MAX];
	
	pbuf = buf;
	for(_argc=0;;++_argc){
		if(_argc>=ARG_MAX){
			printf("gbpo: too many args");
			return 1;
		}
		if(fgets(pbuf, sizeof(buf)-(pbuf-buf), stdin) == NULL){
			printf("gbpo: error read args");
			return 1;
		}
		chop(pbuf);
		if(strlen(pbuf) == 0){
			_argv[_argc] = 0;
			break;
		}
		else{
			_argv[_argc] = pbuf;
			pbuf += strlen(pbuf)+1;
			
			printf("gbpo.main(): _argv[%d]=%s\n", _argc, _argv[_argc]);
		}
	}
	
	c=getc(stdin);
	switch(c){
		case EOF:
			/* tarminated with error */
			printf("unexpected shutdown \"%s\" , so start %s again \n",_argv[0],_argv[0]);
			execute( _argc, _argv, "a");
			break;
		case 'e':
			/* exit normaly */
			break;
		default:
			{
			/* want reboot ? */
				char tmp[] = {c,0};
				execute( _argc, _argv, tmp);
			}
	}
	
	return 0;
}
