/* XPK - General XPK file-to-file packer/unpacker   */
/* This is the version to be compiled with DICE     */
/* Watch the special handing of the progress report */

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

extern hookstub();

struct Library *XpkBase, *OpenLibrary(UBYTE *libName, ULONG version);
char errbuf[XPKERRMSGSIZE + 1];      /* +1 to make room for '\n'        */

__stkargs long chunkfunc(struct Hook *myhook, 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);
  fflush(stdout);
  if(prog->xp_Type==XPKPROG_END)
    printf("\n");

  return (long)SetSignal(0, SIGBREAKF_CTRL_C) & SIGBREAKF_CTRL_C;
}

struct Hook chunkhook = {{0},(void*)hookstub,(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);
}

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];
  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(0);
}
