/* Copyright (C) 1986,1987 by Manx Software Systems, Inc. */

/* Hacked up for SnipIt 1.2 use - Scott Evernden */

#include <exec/memory.h>
#include <libraries/dosextens.h>
#include <functions.h>

struct Process *_FindTask();
void *_AllocMem();
long _Open();

#define STACK_SIZE	3000L

extern BPTR output;
extern long running;

extern char *_procname;
extern char *_detach_name;
static long _alen = 0;
static char *_aptr = 0;

#asm
	dseg
	public	__savsp
	cseg
#endasm

do_detach(alen, aptr)
long *alen;
char **aptr;
{
	register struct CommandLineInterface *cli;
	register struct Process *pp;
	register unsigned short c;
	register char *cp;
	register long l;
	long *lp, *sav;
	struct MemList *mm;

	pp = _FindTask(0L);

	/* first time through!! */
	if (pp->pr_CLI) {

		cli = (struct CommandLineInterface *) ((long)pp->pr_CLI << 2);
		l = cli->cli_Module;

		output = (BPTR) _Open("*", MODE_OLDFILE);

		_alen = *alen;
		_aptr = _AllocMem(_alen, 0L);
		movmem(*aptr, _aptr, (int)_alen);

		cp = (char *)((long)cli->cli_CommandName << 2);
		_detach_name = AllocMem((long)cp[0]+1, 0L);
		movmem(cp, _detach_name, cp[0]+1);
#asm
		move.l	__savsp,-(sp)
#endasm
		cli->cli_Module = 0;
		CreateProc(_procname, 0L, l, STACK_SIZE);
		while (running == 0)
			Delay(5L);
#asm
		move.l	(sp)+,sp
		move.l	#0,d0
		rts
#endasm
	}

	/* second time through */
	else if (strcmp(pp->pr_Task.tc_Node.ln_Name, _procname) == 0) {

		lp = (long *)((long)pp->pr_SegList << 2);
		lp = (long *)(lp[3] << 2);
		sav = lp;
		c = 2;
		while (lp) {
			lp = (long *)(*lp << 2);
			c++;
		}
		mm = _AllocMem((long)sizeof(struct MemList)+
							(c-1)*sizeof(struct MemEntry), 0L);
		lp = sav;
		mm->ml_NumEntries = c;
		c = 0;
		while (lp) {
			mm->ml_me[c].me_Addr = (APTR)lp - 1;
			mm->ml_me[c].me_Length = lp[-1];
			lp = (long *)(*lp << 2);
			c++;
		}
		mm->ml_me[c].me_Addr = (APTR)_aptr;
		mm->ml_me[c++].me_Length = _alen;
		mm->ml_me[c].me_Addr = (APTR)_detach_name;
		mm->ml_me[c++].me_Length = _detach_name[0] + 1;

		AddTail(&((struct Task *)pp)->tc_MemEntry, mm);

		*alen = _alen;
		*aptr = _aptr;
	}
}

