//internal PAK functions (.dat, .edq)

#include <stdio.h>
#include "svgacc.h"
#include "input.h"
#include "pak.h"
#include "grfx.h"
#include "intpak.h"

pak_t      dat;
pakentry_t datentry;
config_t   config;

void opendat()
{
   dat.p = fopen("edquake.dat","rb+");
   if (!dat.p)
   {
      datnew();
      dat.p = fopen("edquake.dat","rb+");
      if (!dat.p) return;
   }
   fseek(dat.p,4,0);
   dat.tableloc = fgetl(dat.p);
   fseek(dat.p,0,2);
   dat.tablelen = (ftell(dat.p) - dat.tableloc) / 64;
   fseek(dat.p,0,0);
}

void datnew()
{
   FILE *out;
   long t;
   out = fopen("edquake.dat","wb");
   if (!out) return; //no disk space?
   fwrite("PACK",4,1,out);
   t = 12;
   fwrite(&t,4,1,out);
   t = 0;
   fwrite(&t,4,1,out);
   fclose(out);
}

void datadd(char *filename)
{
   FILE *in, *temp;
   char *tempname;
   long size, pos;
   in = fopen(filename, "rb");
   if (!in) return;
   size = getfilesize(in);
   tempname = mktemp("TXXXXXX");
   temp = fopen(tempname,"wb+");
   inputbox(299,100,501,160,"Saving...");
     drwstring(SET,BLACK,LTGRAY,"Moving Directory...",308,123);
   fseek(dat.p,dat.tableloc,0);
   for (pos = 0; pos < dat.tablelen * 64; pos++)
   {
      fputc(fgetc(dat.p),temp);
      statusbar(305,140,495,155,pos,size);
   }
   fclose(in);
   fclose(temp);
   remove(tempname);
}
