/*EdQuake v0.50 source code
  (c) Copyright 1996 Scott Mitting
  email:smitting@netusa1.net
  ----------------------------------
  PAK.C  -  .PAK file control

  __variables:
  char *quakepath;          -- path to current editing .PAK file
  pak_t      pak;	    -- pointer to pak file
  pakentry_t pakentry;	    -- pointer to current entry

  __functions:
  void getname()		     -- low level function
  void getentry(int e)		     -- selects new current entry
  void export(int e, char*filename)  -- saves an entry to disk
  void openpak()		     -- opens a pak file
  void showmenu(int showE, int curE) -- low level function for selectpak
  int findfile(char *filename)       -- text search for file
  ----------------------------------
*/
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include "pak.h"
#include "svgacc.h"
#include "grfx.h"
#include "disk.h"

char *quakepath;
pak_t      pak;
pakentry_t pakentry;
config_t config;
char *mapfile;
char *wadname;
char *pakname;


int loadconfig()
{
   FILE *p;
   p = fopen("edquake.cfg","rb");
   if (!p) return 0;
   fread(mapfile,64,1,p);
   fread(wadname,64,1,p);
   fread(pakname,64,1,p);
   fread(&config,64,1,p);
   fclose(p);
   return 1;
}

void saveconfig()
{
   FILE *p;
   p = fopen("edquake.cfg","wb");
   if (!p) return;
   fwrite(mapfile,64,1,p);
   fwrite(wadname,64,1,p);
   fwrite(pakname,64,1,p);
   fwrite(&config,64,1,p);
   fclose(p);
}

void openpak()
{
   pak.p = fopen(pakname,"rb");
   if (!pak.p) return;
   fseek(pak.p,4,0);
   pak.tableloc = fgetl(pak.p);
   fseek(pak.p,0,2);
   pak.tablelen = (ftell(pak.p) - pak.tableloc) / 64;
   fseek(pak.p,0,0);
}

void getname()
{
   int t;
   for (t = 0; t < 56; t++)
       pakentry.name[t] = fgetc(pak.p);
}

void getentry(int e)
{
   fseek(pak.p, pak.tableloc + ((e-1) * 64),0);
   getname();
   pakentry.loc = fgetl(pak.p);
   pakentry.len = fgetl(pak.p);
}

void export(int e, char*filename)
{
   FILE *out;
   long byte;
   int  t;

   getentry(e);
   out = fopen(filename, "wb");
   if (!out) return;
   fseek(pak.p, pakentry.loc, 0);
   for (byte = 1; byte <= pakentry.len; byte++)
       fputc(fgetc(pak.p),out);
   fclose(out);
}

void showmenu(int showE, int curE)
{
   int t,qt;
   char buf[80];
   qt = 40;
   mousehide();
   for (t = 1; t < 20; t++)
   {
     getentry(t + showE);
     if (t != curE)
     {
	drwfillbox(SET, BLACK,6,qt,300,qt+14);
	sprintf(buf, "%s",       pakentry.name);
	drwstring(SET, WHITE,BLACK,buf,11,qt);
     }
     else
     {
	drwfillbox(SET,RED,6,qt,300,qt+14);
	sprintf(buf, "%s",       pakentry.name);
	drwstring(SET, YELLOW,RED,buf,11,qt);
     }
     qt+=14;
   }
   mouseshow();
}

int findfile(char *filename)
{
   int t;
   if (!pak.p) return -1;
   for (t = 0; t < pak.tablelen; t++)
   {
      getentry(t);
      if (strcmpi(filename, pakentry.name) == 0) t += 1000;
   }
   if (t < 1000) return -1;
   t-=1001;
   return t;
}
