/**********************************************************************
 
	Copyright (C) 2003 Hirohisa MORI <joshua@nichibun.ac.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	<stdlib.h>
#include	"memory_debug.h"
#include	"utils.h"
#include	"fcntl.h"
#include "init.h"
#include <windows.h>

extern int max_fid;
extern int s_task_flag;
/*
void
launch_devnull(char * proc)
{
char * buf;
int id;
int i;
	buf = d_alloc(1000);
#ifndef WIN32
	id = fork1();
#endif
	if ( id == 0 ) {
		id = open("/dev/null",O_WRONLY);
		for ( i = 1 ; i <= max_fid ; i ++  )
			close(i);
		dup(id);
		dup(id);
		close(id);
		sprintf(buf,"%s &",proc);
		system(buf);
		exit(0);
	}
	d_f_ree(buf);
}
*/
void
launch_devnull(char * proc)
{
    STARTUPINFO  si;
    PROCESS_INFORMATION  pi;
    SECURITY_ATTRIBUTES sa;

	char * ApplicationName;
	char * FullPath;
	int len,i,j;
	int IsSuccess = 0;
	len = strlen(proc);

    sa.nLength = sizeof(SECURITY_ATTRIBUTES);
    sa.lpSecurityDescriptor = NULL;
    sa.bInheritHandle = TRUE;

    memset(&si, 0, sizeof(STARTUPINFO));
    si.cb = sizeof(STARTUPINFO);

    si.dwFlags = STARTF_USESTDHANDLES;
    si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
	si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
    si.hStdError = NULL;

	ApplicationName = calloc(len+1,sizeof(char));
	FullPath = calloc(1024,sizeof(char));
	for(i = 0 ; (proc[i] != ' ') && i < (int)strlen(proc) ; i++)
		ApplicationName[i] = proc[i];
	if(!SearchPath(NULL,ApplicationName,".exe",1024,FullPath,NULL))
	{
		GetModuleFileName(NULL,FullPath,1024);
		/* strcpy(strstr(FullPath,"cosmos.exe"),proc); */
		strcpy(strrchr(FullPath, '\\')+1,proc);
	}
	else 
		for(j = strlen(FullPath) ; i < (int)strlen(proc) ; i++,j++)
			FullPath[j] = proc[i];

	IsSuccess = CreateProcess(NULL,FullPath,NULL, NULL, TRUE, DETACHED_PROCESS, NULL, NULL, &si, &pi);
    free(ApplicationName);
	free(FullPath);

	if(IsSuccess)
    {
		if(s_task_flag & INI_WAITCHI)
			WaitForSingleObject( pi.hProcess, INFINITE );
    }
}
