#include <string.h>
#include "exec/types.h"
#include "exec/memory.h"
#include "workbench/workbench.h"
#include "workbench/startup.h"
#include "workbench/icon.h"
#include "libraries/dosextens.h"
extern struct WBStartup *WBenchMsg;
extern struct FileHandle *Open();
extern struct DiskObject *GetDiskObject();
extern struct Library *OpenLibrary();
LONG IconBase;

void type(string)
char *string;
{
	Write(Output(),string,strlen(string));
}

void main(argc,argv)
int argc;
char **argv;

{
	int fileLength;
	char **tools;
	char *inputBuffer;
	struct FileHandle *execFile, *users_Dir, *ixWindow, *tempFile=0;
	struct WBArg *whoCalled;
	struct DiskObject *do_ptr;

	if (argc) /* the idiot ran me from CLI! */
	{
	type("Usage:\n");
	type("Make this program the default tool for a project-type icon.\n");
	type("Make the file associated with the icon a CLI script.\n");
	type("The CLI script will be executed when the icon is launched.\n");
	type("\nPublic domain software by Benson the Dog.\n");	
	}
	else
	{
	whoCalled = WBenchMsg->sm_ArgList;
	users_Dir = (struct FileHandle *) CurrentDir(whoCalled[1].wa_Lock);
	ixWindow = Open("CON:10/10/500/150/Ixecute",MODE_OLDFILE);
	execFile = Open(whoCalled[1].wa_Name,MODE_OLDFILE);
	if (execFile)
	{
		if (!(IconBase = (LONG) OpenLibrary("icon.library",0)))
		{
			Write(ixWindow,"Can't open icon library.",24);
			goto earlyEnd;
		}
		do_ptr = GetDiskObject(whoCalled[1].wa_Name);
		tools = do_ptr->do_ToolTypes;
		if (!(strnicmp(*tools,"expert",6)))
			Write(ixWindow,"Expert\n",7);
		else
		{
			tempFile = Open("SYS:t/Ixec.temp",MODE_NEWFILE);
			if (tempFile)
			{
				Seek(execFile,0,OFFSET_END);
				fileLength = Seek(execFile,0,OFFSET_BEGINNING);
				if (inputBuffer = (char *) AllocMem(fileLength,MEMF_FAST))
				{
					Read(execFile,inputBuffer,fileLength);
					Write(tempFile,"cd SYS:\n",8);
					Write(tempFile,inputBuffer,fileLength);
					Write(tempFile,"endcli\n",7);
					Close(execFile);
					Close(tempFile);
					execFile = Open("SYS:t/Ixec.temp",MODE_OLDFILE);
					FreeMem(inputBuffer,fileLength);
				}
				else
				{
					FreeDiskObject(do_ptr);
					Write(ixWindow,"Not enough memory. Use expert mode.",35);
					goto earlyEnd;
				}				
			}
			else
			{
				FreeDiskObject(do_ptr);
				Write(ixWindow,"Can't open temp file.",21);
				goto earlyEnd;
			}
		}
		CloseLibrary(IconBase);
		FreeDiskObject(do_ptr);
		Execute("",execFile,ixWindow);
		Close(execFile);
		if (tempFile)
			DeleteFile("SYS:t/Ixec.temp");
	}
	else
	{	
		Write(ixWindow,"\n\n\n\n",4);
		Write(ixWindow,whoCalled[1].wa_Name,strlen(whoCalled[1].wa_Name));
		Write(ixWindow," not found.",11);
}
earlyEnd:
	Delay(250);
	Close(ixWindow);
	} 		
}

