/*****************************************************************************/
/*** IMPORTANT - This file is the work of the fine folks at GOFF Concepts. ***/
/*****************************************************************************/


int ExecuteProcess(string &FullPathToExe, string &Parameters, int SecondsToWait)
{
  int iMyCounter = 0, iReturnVal = 0;
  DWORD dwExitCode;

  /* - NOTE - You could check here to see if the exe even exists */

  /* Add a space to the beginning of the Parameters */
  if (Parameters.size() != 0 )
  {
    Parameters.insert(0," ");
  }

  /* When using CreateProcess the first parameter needs to be the exe
     itself */
  Parameters = getExeName(FullPathToExe).append(Parameters);

  /* The second parameter to CreateProcess can not be anything but a
     char !!
        Since we are wrapping this C function with strings, we will
     create
     the needed memory to hold the parameters  */

  /* Dynamic Char */
  char * pszParam = new char[Parameters.size() + 1];

  /* Verify memory availability */
  if (pszParam == 0)
  {
    /* Unable to obtain (allocate) memory */
    return 1;
  }
  const char* pchrTemp = Parameters.c_str();
  strcpy(pszParam, pchrTemp);

  /* CreateProcess API initialization */
  STARTUPINFO siStartupInfo;
  PROCESS_INFORMATION piProcessInfo;
  memset(&siStartupInfo, 0, sizeof(siStartupInfo));
  memset(&piProcessInfo, 0, sizeof(piProcessInfo));
  siStartupInfo.cb = sizeof(siStartupInfo);

  /* Execute */
  if (CreateProcess(FullPathToExe.c_str(), pszParam, 0, 0, false,
                    CREATE_DEFAULT_ERROR_MODE, 0, 0, &siStartupInfo,
                    &piProcessInfo) != false)
  {
    /* A loop to watch the process. Dismissed with SecondsToWait set
       to 0 */
    GetExitCodeProcess(piProcessInfo.hProcess, &dwExitCode);

    while (dwExitCode == STILL_ACTIVE && SecondsToWait != 0)
    {
      GetExitCodeProcess(piProcessInfo.hProcess, &dwExitCode);
      Sleep(500);
      iMyCounter += 500;

      if (iMyCounter > (SecondsToWait * 1000))
      {
        dwExitCode = 0;
      }
    }
  }
    else
    {
      /* CreateProcess failed. You could also set the return to
         GetLastError() */
      iReturnVal = 2;
    }

  /* Release handles */
  CloseHandle(piProcessInfo.hProcess);
  CloseHandle(piProcessInfo.hThread);

  /* Free memory */
  delete[]pszParam;
  pszParam = 0;

  return iReturnVal;
}

/*------------------| getExeName |--------------------------------*
| Description:
| ~~~~~~~~~
| Returns the string after the last "\"
\*-----------------------------------------------------------------*/
string getExeName(string strFullPathToExe)
{
  int Position = strFullPathToExe.find_last_of("\\");
  strFullPathToExe = strFullPathToExe.erase(0, Position +1);

  return strFullPathToExe;
}