/* XPK - General XPK file-to-file packer/unpacker */
/* This is the version to be compiled with SAS/C  */

#include <proto/exec.h>
#include <proto/dos.h>
#include <pragma/xpkmaster_lib.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Library *XpkBase;
char errbuf[XPKERRMSGSIZE + 1];	/* +1 to make room for '\n'        */

/* disable lattice CTRL-C handling */
int chkabort (void)
{
  return 0;
}

long __asm __saveds chunkfunc(register __a1 struct XpkProgress *prog)
{
  printf ("\r%4s: %-9s %-12s (%6d bytes, %3d%% done, %2d%% CF, %6d cps) ",
    prog->xp_PackerName, prog->xp_Activity, prog->xp_FileName,
    prog->xp_ULen, prog->xp_Done, prog->xp_CF, prog->xp_Speed);
  if (prog->xp_Type == XPKPROG_END)
    printf ("\n");

  return (long) SetSignal (0, SIGBREAKF_CTRL_C) & SIGBREAKF_CTRL_C;
}
struct Hook chunkhook =
{ {0}, chunkfunc};

struct TagItem tags[]=
{
  XPK_InName, (long) NULL,
  XPK_OutName, (long) NULL,
  XPK_Ignore, (long) 0,
  XPK_NoClobber, (long) TRUE,
  XPK_GetError, (long) errbuf,
  XPK_ChunkHook, (long) &chunkhook,
  TAG_DONE};

void end (char *text)
{
  if (text)
    Write (Output (), text, strlen (text));
  if (XpkBase)
    CloseLibrary (XpkBase);
  exit (text ? 10 : 0);
}

void main (int argc, char *argv[])
{
  int res;

  if (!(XpkBase = OpenLibrary (XPKNAME, 0)))
    end ("Cannot open " XPKNAME "\n");

  if ((argc < 3) || (argc > 4))
    end ("Usage: XPK [<method>] <infile> <outfile>\n");

  tags[0].ti_Data = (long) argv[argc - 2];	/* First try to decompress... */
  tags[1].ti_Data = (long) argv[argc - 1];
  if (argc == 3)
    res = XpkUnpack (tags);
  else {
    tags[2].ti_Tag = XPK_PackMethod;
    tags[2].ti_Data = (long) argv[1];
    res = XpkPack (tags);
  }
  if (res)
    end (strcat (errbuf, "\n"));

  end (NULL);
}
