/*****************************************************************************\
 * $VER: SplitQ.c 1.1                 DICE/LATTICE C/SAS C/AZTEC C + AmigaOS *
 *                 _                                                         *
 *            _   // (c)1992 by "Quarky" Dieter Temme                        *
 *            \\ //                                                          *
 * .ts=4       \X/ --- Freeware --- ONLY AMIGA MAKES IT POSSIBLE             *
 *                                                                           *
 * SplitQ splits a file at requested byte offset (like BASIC MID$ function). *
\*****************************************************************************/

#define PRGNAME "SplitQ"
#define VERSION "1.1"
#define PRGDATE "27.8.92"

#include "amigacompq.h"

#include <stdlib.h>
#include <clib/dos_protos.h>
#include <clib/exec_protos.h>
#include <dos/dos.h>
#include <exec/memory.h>

#ifdef PRAGMAS_
 #include <pragmas/dos_lib.h>
 #include <pragmas/exec_lib.h>
#endif

#ifdef LATTICE
 int CXBRK(void) { return 0; }  /* Disable Lattice CTRL-C handling */
 int chkabort(void) { return 0; }
#endif

#ifdef AZTEC_C
 void _wb_parse(void) {}
 void _abort(void) {}
#endif

TEXT VersionString[]= "\0$VER: " PRGNAME " " VERSION " (" PRGDATE ")";

#define ARG_SRC 1
#define ARG_DST 2
#define ARG_OFS 3
#define ARG_LEN 4

int main(int argc, TEXT *argv[])
{	struct FileInfoBlock fib;
	BPTR file= NULL, lock;
	UBYTE *buffer= NULL;
	LONG offset, length= 0;
	UBYTE rc= RETURN_FAIL;

	if ((argc == 2) && (argv[1][0] == '?') && !argv[1][1])
	{	Write(Output(), "Usage: SplitQ src/A dest/A offset/N/A length/N\n"
						"       splits file at offset into two files\n", 91);
		return RETURN_OK;
	}

	switch(TRUE)
	{	default:
			if ((argc < 4) || (argc > 5))
			{	Write(Output(), "SplitQ: too few/many arguments\n", 31);
				break;
			}
			if ((offset= atol(argv[ARG_OFS])) < 0) break;
			if (argc == 5) if ((length= atol(argv[ARG_LEN])) < 0) break;
			if (!(lock= Lock(argv[ARG_SRC], ACCESS_READ))) break;
			if (!Examine(lock, &fib))
			{	UnLock(lock);
				break;
			}
			UnLock(lock);
			if (fib.fib_DirEntryType > 0) break;
			if (argc == 4) if ((length= fib.fib_Size-offset) < 0) break;
			printf("%d\n", length);
			if (!(buffer= AllocMem(length, MEMF_PUBLIC))) break;
			if (!(file= Open(argv[1], MODE_OLDFILE))) break;
			Seek(file, offset, OFFSET_BEGINNING);
			if (Read(file, buffer, length) < length) break;
			Close(file);
			if (!(file= Open(argv[ARG_DST], MODE_NEWFILE))) break;
			if (Write(file, buffer, length) < length) break;
			rc= RETURN_OK;
	}
	if (buffer) FreeMem(buffer, length);
	if (file) Close(file);

	return (int)rc;
}
