/* perlwrap.c
 *
 * Run Perl script with same name as .EXE file.
 *
 * If this program is named \bin\foo.exe, then execute:
 *
 *     perl /bin/foo.pl
 *
 * The environment variable "PERL_EXE" can be used
 * to set the full path to the Perl executable used by this
 * program. 
 * 
 */

#include <windows.h>

#include <stdio.h>
#include <conio.h>
#include <process.h>
#include <string.h>

#define MAX_ARGS 1024

Err(char *why)
{
	LPVOID lpMsgBuf;

	FormatMessage(
		FORMAT_MESSAGE_ALLOCATE_BUFFER | 
    		FORMAT_MESSAGE_FROM_SYSTEM | 
		FORMAT_MESSAGE_IGNORE_INSERTS,
		NULL,
		GetLastError(),
		MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
		(LPTSTR) &lpMsgBuf,
		0,
		NULL );
	fprintf(stderr, "%s: %s", why, lpMsgBuf);
	LocalFree( lpMsgBuf );
}

void main(int argc, char **argv)
{
	int i;
	int status;
	static char *args[MAX_ARGS];
	static char perl[1024];
	static char path[1024];
	static char script[1024];
	static char buf[1024];
	char *p, *program, *getenv();

	// find full path to our executable (WinNT needs SearchPath() help!)
	program = *argv;
	if (SearchPath(NULL, *argv, ".EXE", sizeof(buf) - 1, buf, &p)) {
		program = buf;
	} else {
		Err(*argv);
	}
	//printf("*argv='%s', p='%s'\n", *argv, p);

	// isolate directory part
	p = strrchr(program, '\\');
	if (!p) p = strrchr(program, '/');
	if (!p) {
		strcpy(path, "");
		p = program;
	} else {
		++p;
		strncpy(path, program, p - program);
	}

	// construct Perl script name
	strcpy(script, path);
	strcat(script, p);
	p = strrchr(script, '.');
	if (p) *p = '\0';
	strcat(script, ".pl");

	// convert all \'s to /'s in Perl script name
	p = script;
	while (*p) {
		if (*p == '\\') *p = '/';
		++p;
	}

	// construct name of Perl executable
	p = getenv("PERL_EXE");
	if (p) {
		strncpy(perl, p, sizeof(perl)-1);
	} else {
		//strcpy(perl, path);
		strcat(perl, "perl");
		//strcat(perl, ".exe");
	}
	///printf("path='%s perl='%s' script='%s'\n", path, perl, script);

	// load up the passed parameters
	args[0] = perl;
	args[1] = script;
	for (i = 1; (i < argc) && (i < MAX_ARGS); ++i) {
		args[i+1] = argv[i];
	}

	///for (i = 0; args[i]; ++i) printf(" %s", args[i]); printf("\n");

	// start up Perl with our script and the passed parameters
	status = _spawnvp(_P_WAIT, perl, args);
	if (status == -1) {
		fprintf(stderr, "Can't _spawnvp: %s %s\n", perl, script);
		exit(255); // This point is reached only if exec fails.
	} else {
		return status;
	}
}
