/*
**	$RCSfile: Freeze.c,v $
**	$Filename: Freeze.c $
**	$Revision: 0.2 $
**	$Date: 1995/02/18 17:33:51 $
**
**	sysmon.library support command Freeze (version 0.3) 
**	
**	(C) Copyright 1995 by Etienne Vogt
*/

#include <exec/alerts.h>
#include <dos/dos.h>
#include <workbench/startup.h>
#define __USE_SYSBASE
#include <proto/exec.h>
#include <proto/dos.h>
#include <string.h>
#include <stdlib.h>
#include "sysmon_protos.h"
#include "sysmon_pragmas.h"

struct ExecBase *SysBase;
struct DosLibrary *DOSBase;
struct Library *SysmonBase;
static struct WBStartup *wbmsg;
static struct RDArgs *myrda;

ULONG __saveds main(void);
static void cleanexit(ULONG rc);

static UBYTE version[] = "$VER: Freeze 0.3 (5.8.95)";
static UBYTE template[] = "TASK,ADDR=ADDRESS/K";

#define	OPT_TASK	0
#define OPT_ADDRESS	1
#define OPTMAX		2

ULONG __saveds main(void)	/* No startup code */
{
  struct Process *myproc;
  struct Task *task = NULL;
  LONG opts[OPTMAX];

  SysBase = *(struct ExecBase **)4;
  DOSBase = NULL;
  SysmonBase = NULL;
  wbmsg = NULL;
  myrda = NULL;

  myproc = (struct Process *)FindTask(NULL);
  if ((DOSBase = (struct DosLibrary *)OpenLibrary("dos.library",36)) == NULL)
  { Alert(AT_Recovery|AG_OpenLib|AO_DOSLib);
    return 100;
  }

  if (!(myproc->pr_CLI))		/* If started from WB, exit cleanly */
  { WaitPort(&(myproc->pr_MsgPort));
    wbmsg = (struct WBStartup *)GetMsg(&(myproc->pr_MsgPort));
    cleanexit(20);
  }
  else
  { memset((char *)opts, 0, sizeof(opts));
    if ((SysmonBase = OpenLibrary("sysmon.library",0)) == NULL)
    { Printf("Freeze : Couldn't open sysmon.library\n");
      cleanexit(20);
    }
    if ((myrda = ReadArgs(template, opts, NULL)) == NULL)
    { PrintFault(IoErr(),NULL);
      cleanexit(20);
    }
    if (opts[OPT_TASK])
    { if ((task = FindTask((STRPTR)opts[OPT_TASK])) == NULL)
      { Printf("Freeze : Unable to find task %s\n",opts[OPT_TASK]);
	cleanexit(20);
      }
    }
    else if (opts[OPT_ADDRESS])
    { task = (struct Task *)strtoul((const char *)opts[OPT_ADDRESS], NULL, 16);
      if (task == NULL) task = FindTask(0);
      if (TypeOfMem(task) == NULL || (task->tc_Node.ln_Type != NT_TASK && task->tc_Node.ln_Type != NT_PROCESS))
      { Printf("Freeze : Address %08lx is not a valid Task structure\n", task);
	cleanexit(20);
      }
    }
    else
    { Printf("Freeze : Required Argument missing\n");
      cleanexit(20);
    }
    if (!smFreeze(task))
    { Printf("Freeze : Task %08lx couldn't be frozen.\n", task);
      cleanexit(10);
    }
  }
  cleanexit(0);
}

static void cleanexit(ULONG rc)
{
  if (myrda) FreeArgs(myrda);
  if (DOSBase) CloseLibrary((struct Library *)DOSBase);
  if (SysmonBase) CloseLibrary(SysmonBase);
  if (wbmsg)
  { Forbid();
    ReplyMsg((struct Message *)wbmsg);
  }
  Exit(rc);
}
