/*
 * Program: XPK Cut
 * Author : LeMUr/Fire & blabla
 * Version: 0.1 ßeta
 * Date   : 01.03.1996
 *
 * See doc for more!
 *
 * Informations about changes:
 * - 01.03.1996 - 1st version, CLI use only
 *
 */


#include <exec/memory.h>

#include <proto/exec.h>
#include <proto/dos.h>

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


#define VER_STR "$VER: XPK-Cut v0.1ß by LeMUr/Fire & blabla"


// memory
UBYTE *Bufor = NULL;
UBYTE *OldBufor = NULL;
ULONG Size = NULL;


void out(int code);


void main(int argc, char *argv[])
{
	// files locks
	BPTR lock = NULL;
	BPTR file = NULL;

	// indicators
	ULONG i;
	ULONG ind = 1;
	ULONG len;

	// file name
	UBYTE name[50];

	struct FileInfoBlock __aligned fib;


	if(argc != 2)
	{
		printf("I need a file name!\n");
		out(20);
	}

	if(!(lock = Lock(argv[1], ACCESS_READ)))
	{
		printf("Unable to lock \"%s\"\n", argv[1]);
		out(25);
	}

	if(!Examine(lock, &fib))
	{
		printf("Unable to examine \"%s\"\n", argv[1]);
		UnLock(lock);
		out(30);
	}

	if(!(Size = fib.fib_Size))
	{
		printf("File couldn't be 0 bytes long!\n");
		UnLock(lock);
		out(32);
	}

	if(!(Bufor = AllocMem(Size, MEMF_ANY | MEMF_CLEAR)))
	{
		printf("Unable to allocate needed memory!\n");
		UnLock(lock);
		out(35);
	}

	if(!(file = Open(argv[1], MODE_OLDFILE)))
	{
		printf("Unable to open file \"%s\"\n", argv[1]);
		UnLock(lock);
		out(40);
	}

	Read(file, Bufor, Size);
	Close(file);
	UnLock(lock);


	OldBufor = Bufor;

	// searching with saving (if found 'coz)
	for(i=0; i != Size; i++)
	{
		if(*Bufor == 'X' && *(++Bufor) == 'P' && *(++Bufor) == 'K' && *(++Bufor) == 'F')
		{
			sprintf(name, "File_%d", ind++);
			if(!(file = Open(name, MODE_NEWFILE)))
			{
				printf("Unable to open file \"%s\"\n", name);
				out(40);
			}
			len = *((ULONG *)++Bufor) + 4;	/* lenght of packed file
					('+1' because of ULONG type); '+4' - security margin
					ignored by decrunchers */

			printf("File: %s  Len: %ld (0x%X)\n", name, len, len);
			Write(file, "XPKF", 4);
			Write(file, Bufor, len);
			Close(file);
		}
		Bufor++;
	}

	out(0);
}	// of main()



void out(int code)
{
	if(Size && OldBufor)
		FreeMem(OldBufor, Size);

	exit(code);
}
