/* 
   Copyright 1994-2003 Free Software Foundation, Inc.

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   This library 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.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 
   USA

   You may contact the author at:

   mailto::camille@bluegrass.net

   or by snail mail at:

   David Lindauer
   850 Washburn Ave Apt 99
   Louisville, KY 40222
*/
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <process.h>
#include <wchar.h>
#include <locale.h>
#include "libp.h"

extern char _RTL_DATA **_environ ;

static char *createenviron(char **env)
{
   int len = 0 ;
   char **dummy,*rv=0 ;
   if (!env)
      env = _environ ;
   dummy = env ;
   while (*dummy) {
      len += strlen(*dummy) + 1 ;
      dummy++ ;
   }
   if (len) {
      len += 1 ;
      rv = malloc (len) ;
      if (rv) {
         char *p = rv ;
         while(*env) {
            strcpy(p,*env) ;
            p+= strlen(p)+ 1 ;
            env++ ;
         }
         *p = 0 ;
      }
   }
   return rv ;
}
int __ll_spawn(char *file, char *parms, char **env , int mode)
{
	PROCESS_INFORMATION pi;
   STARTUPINFO si ;
   DWORD rv = -1;
   char buf[1000],*block = createenviron(env) ;
	memset(&si,0,sizeof(si)) ;
	si.cb = sizeof(STARTUPINFO) ;
	si.dwFlags = STARTF_USESTDHANDLES ;
	si.hStdInput = (HANDLE)__uiohandle(fileno(stdin)) ;
	si.hStdOutput = (HANDLE)__uiohandle(fileno(stdout)) ;
	si.hStdError = (HANDLE)__uiohandle(fileno(stderr)) ;
   sprintf(buf,"\"%s\" %s",file,parms) ;
   if (CreateProcess(file,buf,0,0,TRUE,
						NORMAL_PRIORITY_CLASS,
                  (LPVOID)block,0,&si,&pi)) {
      if (mode == P_WAIT) {
         WaitForInputIdle(pi.hProcess,INFINITE) ;
         WaitForSingleObject(pi.hProcess,INFINITE);
         GetExitCodeProcess(pi.hProcess,&rv) ;
      }
		CloseHandle(pi.hProcess);
		CloseHandle(pi.hThread) ;
      free(block) ;
      return rv ;
   } else {
      free(block) ;
      return -1 ;
   }
}
