/*
 *   This program will start executables and batch script in the background.
 *   Written by Rouslan Placella, rouslan [at] placella [dot] com, 10-Oct-2009.
 */

/*
 *   This file is part of bg_start.
 *
 *   bg_start is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   bg_start 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 General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with bg_start.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include <stdio.h>
#include <string.h>
#include <windows.h>

int main (int argc, char* argv[]) {
	// required variables
	int			i, arg_len = 1;
	
	// Exit if no arguments were passed to the program.
	if ( argc == 1 ) {
		MessageBox(NULL, "ERROR: No arguments found.\nThis program will launch executables and batch scripts in the background.\n\nUsage: bg_start [command] [argument 1] [argument 2] ...\n", "ERROR", MB_ICONERROR);
		return 1;
	}
	for ( i = 2; i < argc; i++ ) {
		arg_len = arg_len + strlen(argv[i]) + 1;
	}

	char			arguments[arg_len], command[arg_len];
	for ( i = 0; i < arg_len; i++ ) {
		command[i]=0;
		arguments[i]=0;
	}
	for ( i = 0; i < argc; i++ ) {
		strcat(arguments, argv[i]);
		strcat(arguments, " ");
	}

	STARTUPINFO		siStartupInfo;
	PROCESS_INFORMATION	piProcessInfo;

	memset(&siStartupInfo, 0, sizeof(siStartupInfo));
	memset(&piProcessInfo, 0, sizeof(piProcessInfo));

	// Set flags to run process in the backround.
	siStartupInfo.cb = sizeof(siStartupInfo);
	siStartupInfo.dwFlags = STARTF_USESHOWWINDOW;
	siStartupInfo.wShowWindow = SW_HIDE;

	// Test if a background process can be created and show an error pop-up message if it can't.
	if (CreateProcess(argv[1], arguments, 0, 0, FALSE, CREATE_NO_WINDOW, 0, 0, &siStartupInfo, &piProcessInfo) == FALSE) {
		MessageBox(NULL, "ERROR: Could not create new process.\n", "ERROR", MB_ICONERROR);
		return 1;
	}
	return 0;
}

