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

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

long chunkfunc (struct XpkProgress *prog);
#pragma regcall(chunkfunc(a1))

struct Library *XpkBase, *OpenLibrary (UBYTE * libName, ULONG version);

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

long chunkfunc (struct XpkProgress *prog)
{
  long abort = (long) SetSignal (0, SIGBREAKF_CTRL_C) & SIGBREAKF_CTRL_C;

  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);
  fflush (stdout);
  if (prog->xp_Type == XPKPROG_END)
    printf ("\n");

  return abort;
}
struct Hook chunkhook =
{ {0}, (void *) chunkfunc};

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

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

extern int Enable_Abort;

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

  Enable_Abort = 0;

  if (!(XpkBase = OpenLibrary ((STRPTR) 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];
  tags[2].ti_Data = (long) errbuf;
  tags[3].ti_Data = (long) &chunkhook;

  if (argc == 3)
    res = XpkUnpack (tags);
  else {
    tags[4].ti_Tag = XPK_PackMethod;
    tags[4].ti_Data = (long) argv[1];
    res = XpkPack (tags);
  }
  if (res)
    end (strcat (errbuf, "\n"));

  end (NULL);
}
