#include <stdio.h>

long fgetl(FILE *f)
{
   long t,
	l;
   l  = fgetc(f);
   t  = fgetc(f);
   l += t << 8;
   t  = fgetc(f);
   l += t << 16;
   t  = fgetc(f);
   l += t << 24;
   return l;
}

int fgeti(FILE *f)
{
   long t,
	l;
   l  = fgetc(f);
   t  = fgetc(f);
   l += t << 8;
   return l;
}

int main()
{
   char file1[101], file2[50];
   char finalname[56];
   FILE *fin, *fout, *ftemp;
   long filesize, t, filesize2, diroffset;
   long entry, fileoff;
   int def;
   for (t = 0; t < 101; t++)
     file1[t] = 0;
   printf("addpak for EdQuake [.map beta test file]\n");
   printf("by Scott Mitting (smitting@netusa1.net)\n");
   printf("free for public use. enjoy Quake\n");
   printf("bsp file: ");
   gets(file1);
   printf("pak file: ");
   gets(file2);
   printf("%s+=%s\n",file2,file1);
   fin = fopen(file1, "rb");
   fout = fopen(file2, "rb+");
   ftemp = fopen("bs23s232.123","wb+");
   if (!fin) return 0;
   if (!fout) return 0;
   if (!ftemp) return 0;
   //get filesize
   fseek(fin,0,2);
   filesize = ftell(fin);
   fseek(fin,0,0);
   fseek(fout,0,2);
   filesize2 = ftell(fout);
   fseek(fout,4,0);
   fseek(ftemp,0,0);
   printf("moving table data\n");
   //move table data
   fileoff = diroffset = fgetl(fout);
   entry = fgetl(fout);
   fseek(fout,diroffset,0);
   for (t = 0; t < entry; t++)
      fputc(fgetc(fout),ftemp);
   fseek(fout,diroffset,0);
   for (t = 0; t < filesize; t++)
	fputc(fgetc(fin),fout);
   printf("move old entries\n");
   //move old entries back
   fseek(ftemp,0,0);
   diroffset = ftell(fout);
   fseek(fout,4,0);
   fwrite(&diroffset,4,1,fout);
   entry+=64;
   fwrite(&entry,4,1,fout);
   fseek(fout,diroffset,0);
   for (t = 0; t < entry - 64; t++)
      fputc(fgetc(ftemp),fout);
   printf("create entry\n");
   //create entry
   def = 50;
   while (def > 0)
   {
      if (file1[def] == '\\') def=-def;
	 else def--;
   }
   def=-def;
   def++;
   finalname[0] = 'm';
   finalname[1] = 'a';
   finalname[2] = 'p';
   finalname[3] = 's';
   finalname[4] = '/';
   for (t = 0; t < 51; t++)
     finalname[t+5] = file1[t + def -1];
   fwrite(finalname,56,1,fout);
   fwrite(&fileoff,4,1,fout);
   fwrite(&filesize,4,1,fout);
   printf("ok\n");
   fclose(fin);
   fclose(fout);
   return 0;
}
