#include <exec/types.h>
#include <exec/exec.h>
#include <libraries/dos.h>
#include <string.h>

char fname[255];
char workfname[255];
int method;

void MemCleanup() {}
void chkabort(void) {}

#define METHODS 4

struct arclist 
	{
	char filext[6];
	char cmd[20]; 
	} arcs[] = 
	{ 
	{".Zoo","Zoo xO// "},
	{".Arc","Arc xw "},
	{".Lzh","lharc -a -x -m x "},
	{".Zip","Unzip "} 
	};
	
/* NOTE: the xw (for Arc) and the xO (for Zoo) are VERY important */
/*  they keep the progs from asking "Overwrite existing?"         */

void
verify_fname(void)
{
int x;
int len;
BPTR FP;

len=strlen(fname);

FP = Lock(fname, ACCESS_READ);
if (FP!=0)
	{
	UnLock(FP);
	for (x=0; x<METHODS; x++)
		{
		if (stricmp(&fname[len-4], arcs[x].filext) == 0)
			{
			method=x;
			return;
			};
		};

	printf("Unknown archive type.\n");
	exit(0);
	};

len=strlen(fname);

for (x=0; x<METHODS; x++)
	{
	strcpy(workfname, fname);
	strcat(workfname, arcs[x].filext);
	FP=Lock(workfname, ACCESS_READ);
	if (FP != 0)
		{
		UnLock(FP);
		method=x;
		strcpy(fname, workfname);
		return;
		};
	};

printf("Error: Cannot find archive name.\n");
exit(0);
}


void
verify_compression(void)
{
BPTR FP;
char buffer[512];
int realmethod=1;
int len;

FP = Open(fname, MODE_OLDFILE);
if (FP==0) 
	return;

Read(FP, buffer, 512);
Close(FP);

if (strncmp(buffer, "ZOO", 3)==0)
	realmethod=0;

if (strncmp(buffer, "PK", 2)==0)
	realmethod=3;

if (strncmp(&buffer[2], "-lh", 3)==0)
	realmethod=2;

if (realmethod != method)
	{
	strcpy(buffer, "It looks like a ");
	strcat(buffer, arcs[realmethod].filext);
	strcat(buffer, ", but is named like a ");
	strcat(buffer, arcs[method].filext);
	strcat(buffer, "\n");
	printf("Can I rename it (Y/n): ");
	buffer[0]='Y';
	buffer[1]=0;
	gets(buffer);
	if (toupper(buffer[0])!='N')
		{
		strcpy(workfname, fname);
		len = strlen(workfname);
		workfname[len-4]=0;
		strcat(workfname, arcs[realmethod].filext);
		if (Rename(fname, workfname)==FALSE)
			{
			printf("Error:  Rename failed.\n");
			exit(0);
			};
		strcpy(fname, workfname);
		method=realmethod;
		} else
		{
		printf("Aborting.\n");
		exit(0);
		};	
	};
}




main(int argc, char **argv)
{
char command[255];
int len;

if (argc!=2)
	{
	printf("Usage: Undo ArchiveName\n");
	return(10);
	};

/* First we get the right filename */
strcpy(fname, argv[1]);

verify_fname();

/* now we know filename is right */

verify_compression();

/* And we know the compression is right. */
	
len = strlen(fname);
fname[len-4]=0;
strcpy(command, arcs[method].cmd);
strcat(command, fname);

printf("%s\n", command);
Execute(command,0L,Output());
return(0);
}
