#include <proto/exec.h>
#include <exec/memory.h>
#include <proto/dos.h>
#include <proto/xpk.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "printXpkFib.c"

struct Library *XpkBase = NULL;

char errbuf[XPKERRMSGSIZE + 1], *buf = NULL;
long bufsize;
BPTR fh = 0;

void 
end (char *text)
{
  if (fh)
    Close (fh);
  if (buf)
    FreeMem (buf, bufsize);
  if (text)
    printf ("%s %s\n", text, errbuf);
  if (XpkBase)
    CloseLibrary (XpkBase);
  exit (text ? 10 : 0);
}

void 
main (int argc, char *argv[])
{
  struct XpkFib xfib;
  struct FileInfoBlock fib;
  ULONG ulen;

  errbuf[0] = 0;

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

  if (argc != 2)
    end ("Usage: testMemExamine filename\n");

  if (XpkExamineTags( &xfib,
		      XPK_InName, argv[1],
                      XPK_GetError, errbuf,
		      TAG_DONE
		    ))
    end ("Can't XpkExamine;");

  printXpkFib(&xfib);

  errbuf[0] = 0;

  if (!(fh = Open (argv[1], MODE_OLDFILE)))
    end ("Cannot open input file");

  if (!(ExamineFH (fh, &fib)))
    end ("Failed to ExamineFH input file");

  bufsize = fib.fib_Size;

  if (!(buf = AllocMem (bufsize, MEMF_ANY)))
    end ("Out of memory!");

  ulen = Read (fh, buf, bufsize);

  if (ulen != bufsize)
    end ("Could not read whole file with one Read()");

  Close (fh);
  fh = 0;

  if (XpkExamineTags( &xfib,
		      XPK_InBuf, buf,
		      XPK_InLen, bufsize,
                      XPK_GetError, errbuf,
		      TAG_DONE
		    ))
    end ("Can't XpkExamine:");
    
  printXpkFib(&xfib);

  end (NULL);
}
