/*  agxfile.c-- functions to read and write AGX files     */
/*                                                        */
/* Copyright 1996,97    Robert Masenten                   */
/*                                                        */
/* This is part of the source for both AGiliTy: the (Mostly) Universal */
/*       AGT Interpreter and for the Magx adventure game compiler.    */

/* #define DEBUG_AGX */

/* NOTES ON CHANGING THE AGX FILE FORMAT 

     First of all, don't.  

     One of the benifits of adventure creation systems like this is
   that the same game files can be played on a variety of different
   platforms without any extra effort on the part of the game
   author.  If you change the file format, this is no longer true:  games
   created under the new format won't run on the old interpreters. 

     Even if you distribute a new interpreter with your game, there are two 
   problems:
     i) People on other platforms won't be able to play your game unless
    and until your modified interpreter is ported to their machine. Since
    I-F players as a group tend to be more diverse in terms of platform 
    than the population at large, this is bad.
     ii) Even for machines that you port your modified interpreter to,
    people will now need to maintain two interpreters: the original one
     (for most of the games) and your modified one (for your new game).
    This is not only a nuisance but it wastes disk space.


    If you *do* decide to change the file format anyhow, please adhere to 
  the following guidelines, to minimize confusion.
   
GUIDLINES FOR NEW FILE FORMAT VERSIONS
  File format version are labled by a series of four bytes near the
beginning of the file. (They are actually the fifth, sixth, seventh,
and eight bytes-- the first four bytes are the file format signature
that indicate the file is an AGX file and not, say, a PCX file)
  In order, they are the version owner id and number, and the extension
owner id and number.  In "vanilla" AGX, both owner id's are 'r', the
version number is 1, and the extension number is 0. (There are AGX
files with version number 0 and extension number 0 or 1, created by 
earlier releases of agt2agx.)
  I will discuss the difference between "versions" and "extensions"
further below, but briefly: extensions are minor changes whereas versions
represent vast reoganizations of the file format.  The routines below
will still try to read in a file with an unrecognized extension, but
they will give up on an unrecognized version.
  If you create a new extension, then you should first change the
extension owner id to something else; the owner id is intended to
indicate who is responsible for defining this extension; 'r' indicates
Robert Masenten (the author of this file) and so shouldn't be used by anyone
else. The id isn't required to be a printable character; I just chose
mine that way.
  You can then define extension number however you want. The extension
number is intended to differentiate between different extensions
defined by the same source (e.g. two extensions both defined by me
would have the same owner id but different extension numbers). The
extensions that I define are numbered sequentially starting at 0, but
you don't have to follow this convention if you don't want. 
  Finally, send me an e-mail note telling me what you've done so I can
keep track of the different extensions and prevent conflicts between
owner-ids. 
  Creating a new version works the same way: change the version owner-id to
something no one is using and set the version number however you want.
If you're defining a new version, you can do whatever you want with
the two extension bytes.

  This whole scheme is probably overkill, but I'm trying to prevent a
return to the Tower of Babel that AGT was caught in before the creation
of AGiliTy.


EXTENSIONS AND VERSIONS
  For purposes of the file format, an 'extension' is a change to the
format that follows certain restrictions given below; a 'version' is one that
violates one or more of these restrictions. 
  If at all possible you should try to fit your changes to the format
within the limitations of an 'extension': it is more likely that other
programs will work with your new file format and it is also more
likely that your modified interpreter will still be able to understand
the original file format.
  An extension shouldn't change any of the existing data fields; nor
should it insert new data fields into the middle of records.  An
extension *may* add new fields onto the end of one or more of the
records and it can define new blocks.

  Examples of things that would be extensions (create a new extension
id and number, but keep the version the same):
--Adding a new field onto the end of the creature record, containing
	the code for a sound file that should be played whenever
	the creature is in thie room.
--Adding a new block to the file containing debugging information for
	the new AGT compiler you've just written, numbered 28.

  Things that would *not* be extensions (create a new version id and
number; do what you want with the extension id and number) 
  --Going to 32-bit object numbers for everything. (Although there *are*
sneaky ways you could make this an extension; but not if you just do this
by converting all the int16 fields in the file to int32)
  --Changeing metacommands to accept an arbitrary string of tokens
instead of just  ACTOR,VERB NOUN PREP OBJECT. 


A FEW NOTES ON BACKWARD COMPATIBILITY
  (These notes only apply if you are creating an extension; if you are
creating a new version, then anything goes)
  If you add a new field onto an existing record (like the creature
soundtrack example above) and read in an old-format file, then the new
data fields will be automatically initialized to zero so long as none
of them are individually longer than 81 bytes (if any *are* longer than
81 bytes then the file routines may break). (There is nothing magic
about 81 bytes; it just happens to be the length of the largest data
structure that shows up in 'vanilla' AGX files).
  If you add a new block, then you should check the extension number
of the file and if the block doesn't exists be prepared to either
initialize the data to something sensible or to exit cleanly with an
error message.

 */

/* AGX File format versions and corresponding versions of AGiliTy
   and Magx: (versions given as 'Version-Extension') 

 AGX  AGiliTy    Magx
 0-0    0.5
 0-1    0.7       0.1
 1-0    0.7.2     <not yet released>

 */

#include <ctype.h>
#include <stddef.h>
#include "agtread.h"

#define AGX_NUMBLOCK 28
#define AGT_FILE_SIG 0x51C1C758L

/* AGX File format:
  (This tends to lag a little behind the code below;
  you should double check against the actual file_info definitions
  below) 
All integer values stored little-endian.
desc_ptrs: int32 ofs, int32 leng (both in lines)
dictionary word: int16
slist ptr: int16
tline: char[81]
filename: char[10]
bool values are packed into bytes, 1 bit per value, from lsb to msb.
cfgopt: 0=false, 1=true, 2=leave alone

Mandatory blocks are marked with astericks. 

*File header: 16  bytes
   uint 32 File ID ['....' 4 bytes]
   byte Version owner: 'R'
   byte Version 0
   byte Extension owner 'R'
   byte Extension 0
   char[2]: '\n\r'  -- to catch download errors
   char[6] Reserved for future use (should be 0 right now)
*0-File index: 
   For each block (including itself): [16 bytes]
        uint32 starting offset
        uint32 block size
	uint32 number of records
	uint32 size of a record  (recsize*numrec == blocksize)	
11-Description strings (block of tline)
12-Command text (block of int16)
*1-Game header 
   uint16 AGT_version_code;  +1 for "big/soggy" games
   uint32 game_sig  (game signature, used to check save files and debug info)
   bool debug_mode, freeze_mode, milltime_mode, bold_mode, 
         have_meta, mars_fix, intro_first;
   uchar score_mode, statusmode;
   uint16 max_lives
   uint32 max_score;
   uint16 start_time, delta_time;
   descr_ptr intro_ptr, title_ptr, ins_ptr;
   int16 start_room, treas_room, ressurect_room
   int16 first_room, first_noun, first_creat
   int16 FLAG_NUM, CNT_NUM, VAR_NUM
   int16 BASE_VERB
   cfgopt PURE_ANSWER, PURE_TIME, PURE_ROOMTITLE;
   cfgopt PURE_AND, PURE_METAVERB;
   cfgopt PURE_SYN, PURE_NOUN, PURE_ADJ;
   cfgopt PURE_DUMMY, PURE_SUBNAME, PURE_PROSUB;
   cfgopt PURE_HOSTILE, PURE_GETHOSTILE;
   cfgopt PURE_DISAMBIG, PURE_ALL;
   cfgopt irun_mode, verboseflag;
2-Room data (room_rec format, pointers->int ref into static string)
   include help, desc, special ptrs
3-Noun data (noun_rec format)
   include noun, text, turn, push, pull, play ptrs
4-Creature data (creat_rec format)
   include creature, talk, ask ptrs
5-Command headers (cmd_rec format), pointers into command text
     must be in increasing order.
6-Standard error message ptrs (array of descptr
7-Message ptrs   (array of descptr)
8-Question pointers (array of descptr)
9-Answer pointers (array of descptr)
10-User strings  (array of tline)
*13-Static string block (block of chars)
14-Subroutine dictionary ids (array of word:int16)
*15-Synlist (for verbs) (array of slist:int16)
16-Pix names (array of word:int16 -- pointers into dictionary)
17-Global nouns (array of word:int16 -- ptrs into dictionary)
18-Flag nouns (array of word:int16)
*19-Syntbl (block of word:int16)
*20-Dictionary text (block of char)
*21-Dictionary 'index' (array of uint32)
22-OPT block (14 bytes)
23-Picture filename ptrs
24-Pix filename ptrs
25-Font filename ptrs
26-Sound filename ptrs
27-VOC block, an array of verbinfo_rec 
*/

/* AGT Version IDs; +1 for LARGE/SOGGY 
        00000=v1.0
	01800=v1.18
	01900=v1.19
	02000=v1.20
	03200=v1.32/COS
	03500=v1.35
	05000=v1.5/H
	05050=v1.5/F (MDT)
        05070=v1.5/P (PORK)
	08200=v1.82
	08300=v1.83
       	10000=ME/1.0
	15000=ME/1.5
	15500=ME/1.55
	16000=ME/1.6
	20000=Magx/0.0
	etc.
*/



static integer old_base_verb;

/* AGX file info blocks */

#define g(ft,dt,var) {ft,dt,&var,0}
#define r(ft,dt,str,f) {ft,dt,NULL,offsetof(str,f)}
#define dptype {FT_DESCPTR,DT_DESCPTR,NULL,0}
#define xx DT_DEFAULT
#define u16 FT_UINT16
#define u32 FT_UINT32
#define bb  FT_BOOL
#define i16 FT_INT16

static file_info fi_gameinfo[]={
  g(FT_VERSION,xx,aver), /* FT_VERSION converter also sets ver */
  g(u32,DT_LONG,game_sig),
  g(bb,xx,debug_mode), g(bb,xx,freeze_mode), g(bb,xx,milltime_mode),
  g(bb,xx,bold_mode), g(bb,xx,have_meta), g(bb,xx,mars_fix),
  g(bb,xx,intro_first),g(bb,xx,box_title),
  g(FT_BYTE,xx,score_mode), g(FT_BYTE,xx,statusmode),
  g(i16,xx,max_lives), g(u32,DT_LONG,max_score),
  g(i16,xx,start_time),g(i16,xx,delta_time),
  g(FT_DESCPTR,xx,intro_ptr), g(FT_DESCPTR,xx,title_ptr),
  g(FT_DESCPTR,xx,ins_ptr),
  g(i16,xx,treas_room),
  g(i16,xx,start_room),g(i16,xx,ressurect_room),
  g(i16,xx,first_room),  g(i16,xx,first_noun),
  g(i16,xx,first_creat), g(i16,xx,FLAG_NUM),
  g(i16,xx,CNT_NUM), g(i16,xx,VAR_NUM),
  g(i16,xx,old_base_verb),
  g(FT_CFG,xx,PURE_ANSWER), g(FT_CFG,xx,PURE_ROOMTITLE),
  g(FT_CFG,xx,PURE_AND), g(FT_CFG,xx,PURE_METAVERB),
  g(FT_CFG,xx,PURE_SYN), g(FT_CFG,xx,PURE_NOUN), g(FT_CFG,xx,PURE_ADJ),
  g(FT_CFG,xx,PURE_DUMMY), g(FT_CFG,xx,PURE_SUBNAME), 
  g(FT_CFG,xx,PURE_PROSUB), g(FT_CFG,xx,PURE_HOSTILE), 
  g(FT_CFG,xx,PURE_GETHOSTILE), g(FT_CFG,xx,PURE_DISAMBIG), 
  g(FT_CFG,xx,PURE_ALL),
  g(FT_CFG,xx,irun_mode),g(FT_CFG,xx,verboseflag),
  g(FT_CFG,xx,PURE_TIME),      /* Ext R0-1 */
  g(FT_CFG,xx,PURE_OBJ_DESC), /* Ext R0-1 */
  g(i16,xx,exitmsg_base),           /* Ext R0-1 */
  endrec
};

static file_info fi_room[]={
  dptype, /* help */
  dptype, /* desc */
  dptype, /* special */
  r(FT_STR,xx,room_rec,name),
  r(FT_INT32,xx,room_rec,flag_noun_bits),
  r(FT_INT32,xx,room_rec,PIX_bits),
  r(FT_SLIST,xx,room_rec,replacing_word),
  r(FT_WORD,xx,room_rec,replace_word),
  r(FT_WORD,xx,room_rec,autoverb),
  r(FT_PATHARRAY,xx,room_rec,path),
  r(FT_INT16,xx,room_rec,key),
  r(FT_INT16,xx,room_rec,points),
  r(FT_INT16,xx,room_rec,light),
  r(FT_INT16,xx,room_rec,pict),
  r(FT_INT16,xx,room_rec,initdesc),
  r(bb,xx,room_rec,seen), r(bb,xx,room_rec,locked_door),
  r(bb,xx,room_rec,end),r(bb,xx,room_rec,win),r(bb,xx,room_rec,killplayer),
  endrec
};

static file_info fi_noun[]={
  dptype, /* Noun */
  dptype, /* Text */
  dptype, dptype, dptype, dptype, /* Turn, push, pull, play */
  r(FT_STR,xx,noun_rec,shortdesc),
  r(FT_STR,xx,noun_rec,position),
  r(FT_SLIST,xx,noun_rec,syns),
  r(FT_WORD,xx,noun_rec,name),  r(FT_WORD,xx,noun_rec,adj),
  /* r(FT_WORD,xx,noun_rec,pos_prep),  r(FT_WORD,xx,noun_rec,pos_name),*/
  r(FT_INT16,xx,noun_rec,nearby_noun),
  r(FT_INT16,xx,noun_rec,num_shots), r(FT_INT16,xx,noun_rec,points),
  r(FT_INT16,xx,noun_rec,weight), r(FT_INT16,xx,noun_rec,size),
  r(FT_INT16,xx,noun_rec,key),
  r(FT_INT16,xx,noun_rec,initdesc), r(FT_INT16,xx,noun_rec,pict),
  r(FT_INT16,xx,noun_rec,location),
  r(bb,xx,noun_rec,sing_plur),
  r(bb,xx,noun_rec,something_pos_near_noun),
  r(bb,xx,noun_rec,has_syns),
  r(bb,xx,noun_rec,pushable),  r(bb,xx,noun_rec,pullable),  
  r(bb,xx,noun_rec,turnable),  r(bb,xx,noun_rec,playable),
  r(bb,xx,noun_rec,readable),  r(bb,xx,noun_rec,on),
  r(bb,xx,noun_rec,closable),  r(bb,xx,noun_rec,open),
  r(bb,xx,noun_rec,lockable),  r(bb,xx,noun_rec,locked),
  r(bb,xx,noun_rec,edible),  r(bb,xx,noun_rec,wearable),
  r(bb,xx,noun_rec,drinkable),  r(bb,xx,noun_rec,poisonous),
  r(bb,xx,noun_rec,movable),  r(bb,xx,noun_rec,light),
  r(bb,xx,noun_rec,shootable),  r(bb,xx,noun_rec,win),
  r(FT_WORD,xx,noun_rec,related_name),  /* Ext R0-1 */
  endrec
};

static file_info fi_creat[]={
  dptype,  /* Creature */
  dptype, dptype,  /* Talk, ask */
  r(FT_STR,xx,creat_rec,shortdesc),
  r(FT_SLIST,xx,creat_rec,syns),
  r(FT_WORD,xx,creat_rec,name),r(FT_WORD,xx,creat_rec,adj),
  r(FT_INT16,xx,creat_rec,location),
  r(FT_INT16,xx,creat_rec,weapon), r(FT_INT16,xx,creat_rec,points),
  r(FT_INT16,xx,creat_rec,counter), r(FT_INT16,xx,creat_rec,threshold), 
  r(FT_INT16,xx,creat_rec,timethresh), r(FT_INT16,xx,creat_rec,timecounter),
  r(FT_INT16,xx,creat_rec,pict), r(FT_INT16,xx,creat_rec,initdesc),
  r(bb,xx,creat_rec,has_syns), r(bb,xx,creat_rec,groupmemb),
  r(bb,xx,creat_rec,hostile), r(FT_BYTE,xx,creat_rec,gender),
  endrec
};

static file_info fi_cmdhead[]={
  {FT_CMDPTR,DT_CMDPTR,NULL,0},  
  r(FT_INT16,xx,cmd_rec,actor),
  r(FT_WORD,xx,cmd_rec,verbcmd), r(FT_WORD,xx,cmd_rec,nouncmd),  
  r(FT_WORD,xx,cmd_rec,objcmd), r(FT_WORD,xx,cmd_rec,prep),
  r(FT_INT16,xx,cmd_rec,cmdsize),
  r(FT_WORD,xx,cmd_rec,noun_adj), r(FT_WORD,xx,cmd_rec,obj_adj), /* Ext R0-1*/
  endrec
};

static file_info fi_verbentry[]={
  r(FT_WORD,xx,verbentry_rec,verb),
  r(FT_WORD,xx,verbentry_rec,prep),
  r(FT_INT16,xx,verbentry_rec,objnum),
  endrec
};


static file_info fi_descptr[]={
  r(FT_INT32,xx,descr_ptr,start),
  r(FT_INT32,xx,descr_ptr,size),
  endrec
};

static file_info fi_tline[]={
  {FT_TLINE,xx,NULL,0},
  endrec
};

#undef g
#undef r
#undef xx
#undef u16
#undef u32
#undef bb
#undef i16
#undef dptype

static long descr_ofs;

void agx_close_descr(void)
{
  buffclose(); /* This closes the whole AGX file */
}

descr_line *agx_read_descr(long start,long size)
{
  int i, line, len;
  descr_line *txt;
  char *buff;

  if (size<=0) return NULL;
  buff=read_recblock(NULL,FT_CHAR,size,
		     descr_ofs+start, size*ft_leng[FT_CHAR]);

  len=0;
  for(i=0;i<size;i++)   /* Count the number of lines */
    if (buff[i]==0) len++;
  txt=rmalloc(sizeof(descr_line)*(len+1));
  txt[0]=buff;
  i=0;
  for(line=1;line<len;)  /* Determine where each of the lines is */ 
    if (buff[i++]==0)  
      txt[line++]=buff+i;
  txt[len]=NULL;  /* Mark the end of the array */
  return txt;
}


/* We need to read in command text and use cmd_rec[] values to
   rebuild command[].data. We are guaranteed that cmd_rec[] is in
   increasing order */

static void read_command(long cmdcnt, long cmdofs, bool diag)
{  
  int i;

  for(i=0;i<last_cmd;i++) {
    command[i].data=rmalloc(sizeof(integer)*command[i].cmdsize);
    read_recblock(command[i].data,FT_INT16,command[i].cmdsize,
		  cmdofs+2*cmd_ptr[i],2*command[i].cmdsize);
  }
  if (!diag) rfree(cmd_ptr);
}


/* Correct for differences between old_base_verb and BASE_VERB.
   This means that the interpreter's set of built-inv verbs has changed
   since the file was created. */
static void correct_synlist(void)
{
  int i;
  if (BASE_VERB==old_base_verb) return; /* Nothing needs to be done */

  /* Need to move everything >= old_base_verb to BASE_VERB */
  memmove(synlist+BASE_VERB,synlist+old_base_verb,
	  sizeof(slist)*(DVERB+MAX_SUB) );

  if (BASE_VERB<old_base_verb) /* We've _lost_ verbs */
    agtwarn("Missing built-in verbs.",0);

  /* Now we need to give the "new" verbs empty synonym lists */
  for(i=old_base_verb;i<BASE_VERB;i++)
    synlist[i]=synptr;
  addsyn(-1);
}



static void set_roomdesc(file_info fi[])
{
  fi[0].ptr=help_ptr=rmalloc(sizeof(descr_ptr)*(maxroom-first_room+1));
  fi[1].ptr=room_ptr=rmalloc(sizeof(descr_ptr)*(maxroom-first_room+1));
  fi[2].ptr=special_ptr=rmalloc(sizeof(descr_ptr)*(maxroom-first_room+1));
}

static void wset_roomdesc(file_info fi[])
{
  fi[0].ptr=help_ptr;
  fi[1].ptr=room_ptr;
  fi[2].ptr=special_ptr;
}

static void set_noundesc(file_info *fi)
{
  fi[0].ptr=noun_ptr=rmalloc(sizeof(descr_ptr)*(maxnoun-first_noun+1));
  fi[1].ptr=text_ptr=rmalloc(sizeof(descr_ptr)*(maxnoun-first_noun+1));
  fi[2].ptr=turn_ptr=rmalloc(sizeof(descr_ptr)*(maxnoun-first_noun+1));
  fi[3].ptr=push_ptr=rmalloc(sizeof(descr_ptr)*(maxnoun-first_noun+1));
  fi[4].ptr=pull_ptr=rmalloc(sizeof(descr_ptr)*(maxnoun-first_noun+1));
  fi[5].ptr=play_ptr=rmalloc(sizeof(descr_ptr)*(maxnoun-first_noun+1));
}

static void wset_noundesc(file_info *fi)
{
  fi[0].ptr=noun_ptr;
  fi[1].ptr=text_ptr;
  fi[2].ptr=turn_ptr;
  fi[3].ptr=push_ptr;
  fi[4].ptr=pull_ptr;
  fi[5].ptr=play_ptr;
}

static void set_creatdesc(file_info *fi)
{
  fi[0].ptr=creat_ptr=rmalloc(sizeof(descr_ptr)*(maxcreat-first_creat+1));  
  fi[1].ptr=talk_ptr=rmalloc(sizeof(descr_ptr)*(maxcreat-first_creat+1));  
  fi[2].ptr=ask_ptr=rmalloc(sizeof(descr_ptr)*(maxcreat-first_creat+1));   
}

static void wset_creatdesc(file_info *fi)
{
  fi[0].ptr=creat_ptr;
  fi[1].ptr=talk_ptr;
  fi[2].ptr=ask_ptr;
}

static void set_cmdptr(file_info *fi)
{
  fi[0].ptr=cmd_ptr=rmalloc(sizeof(long)*last_cmd);
}

static void wset_cmdptr(file_info *fi)
{
  fi[0].ptr=cmd_ptr;
}


typedef struct {  /* Entries in the index header of the AGX file */
  uint32 file_offset;
  uint32 blocksize;
  uint32 numrec; 
  uint32 recsize;
} index_rec;

static file_info fi_index[]={
  {FT_UINT32, DT_DEFAULT, NULL, offsetof(index_rec,file_offset)},
  {FT_UINT32, DT_DEFAULT, NULL, offsetof(index_rec,blocksize)},
  {FT_UINT32, DT_DEFAULT, NULL, offsetof(index_rec,numrec)},
  {FT_UINT32, DT_DEFAULT, NULL, offsetof(index_rec,recsize)},
  endrec
};


/*
   uint32 File ID ['....' 4 bytes]
   byte Version owner: 'R'
   byte Version 0
   byte Extension owner 'R'
   byte Extension 0
   */

typedef struct {
  unsigned long fileid;
  unsigned long res1; /* Reserved for future use */
  unsigned short res2;
  uchar eol_chk1;  /* Catch non-binary upload errors */
  uchar eol_chk2;
  uchar ver_own;
  uchar version;
  uchar ext_own;
  uchar extnum;
} file_head_rec;

static file_info fi_header[]={
  {FT_UINT32, DT_LONG, NULL, offsetof(file_head_rec,fileid)}, /* File ID */
  {FT_BYTE, DT_DEFAULT, NULL, offsetof(file_head_rec,ver_own)},  /* Owner */
  {FT_BYTE, DT_DEFAULT, NULL, offsetof(file_head_rec,version)},  /* Version */
  {FT_BYTE, DT_DEFAULT, NULL, offsetof(file_head_rec,ext_own)},  /*Ext owner*/
  {FT_BYTE, DT_DEFAULT, NULL, offsetof(file_head_rec,extnum)},  /* Ext vers */
  {FT_BYTE, DT_DEFAULT, NULL, offsetof(file_head_rec,eol_chk1)},
  {FT_BYTE, DT_DEFAULT, NULL, offsetof(file_head_rec,eol_chk2)},
  {FT_INT16, DT_DEFAULT, NULL, offsetof(file_head_rec,res2)},
  {FT_UINT32, DT_DEFAULT, NULL, offsetof(file_head_rec,res1)},
  endrec
};

/* Return 0 on failure, 1 on success */
int read_agx(char *gamename, bool diag)
{
  file_head_rec filehead;
  unsigned long fsize;
  index_rec *index;
  int i;
  int index_recsize;
  int index_start;
  
  agx_file=1;
  fsize=buffopen(gamename,pAGX,16,NULL,1);
  if (fsize==0) 
    fsize=buffopen(gamename,"",16,NULL,1);
  if (fsize==0) {
    agx_file=0;
    return 0;
  }

  /* Read header */
  read_recarray(&filehead,sizeof(file_head_rec),1,fi_header,
		"File Header",0,compute_recsize(fi_header));
  if (filehead.fileid!=AGT_FILE_SIG)
    fatal("Not an AGX file.");
  if (DIAG) {
    rprintf("AGX file format");
    rprintf("   Version:%c%d\tExtension:%c%d\n",
	    filehead.ver_own,filehead.version,
	    filehead.ext_own,filehead.extnum);
  }
  if (filehead.ver_own!='R' || filehead.version>1)
    fatal("Unsupported AGX file version.");

  index_recsize=compute_recsize(fi_index);
  if (filehead.version==0) {
    if (debug_da1)
      rprintf("[AGX version 0: obsolete.]\n");
    index_recsize+=8; /* Extra junk block in version 0. */
    index_start=8;
  } else {
    index_start=16;
    if (filehead.eol_chk1!='\n' || filehead.eol_chk2!='\r') 
      fatal("File apparently downloaded as non-binary file.");
  }
  if (filehead.ext_own!='R' 
      || (filehead.version==0 && filehead.extnum>1)
      || (filehead.version==1 && filehead.extnum>0) )
    agtwarn("Unrecognized extension to AGX file format.",0);
  if (filehead.ext_own!='R') filehead.extnum=0;
  /* Assume lowest common denomenator */

  /* Now read master index */
  index=read_recarray(NULL,sizeof(index_rec),AGX_NUMBLOCK,
		      fi_index, "File Index",index_start, 
		      index_recsize*AGX_NUMBLOCK);
  if (DIAG) {
    rprintf("\n");
    rprintf("File Index:\n");
    rprintf("    Offset   Size   NumRec  RecSz\n");
    rprintf("    ------  ------  ------  ------\n");
    for(i=0;i<AGX_NUMBLOCK;i++)
      rprintf("%2d: %6d  %6d  %6d  %6d\n", i,
	      index[i].file_offset, index[i].blocksize,
	      index[i].numrec, index[i].recsize);
  }
  if (index[0].file_offset!=index_start)
    fatal("File header corrupted.");

  for(i=0;i<AGX_NUMBLOCK;i++) { /* Error checking */
#ifdef DEBUG_AGX
    rprintf("  Verifying block %d...\n",i);
#endif
    if (index[i].recsize*index[i].numrec!=index[i].blocksize)
      fatal("File header corrupted.");
    if (index[i].file_offset+index[i].blocksize>fsize)
      fatal("File index points past end of file.");
  }
 
  /* Check for mandatory fields */
  if (!index[0].numrec    /* File index */
      || !index[1].numrec /* Game header */
      || !index[13].numrec /* Static string block */
      || !index[15].numrec /* Synonym list */
      || !index[19].numrec /* Syntbl */
      || !index[20].numrec /* Dictionary text */
      || !index[21].numrec /* Dictionary index */
      ) 
    fatal("AGX file missing mandatory block.");
      
 
  read_globalrec(fi_gameinfo,"Game Info",index[1].file_offset,
		 index[1].blocksize);
  if (filehead.version==0 && filehead.extnum==0) {
    exitmsg_base=1000;
    if (aver>=AGT15) 
      box_title=1;
  }

  /* Need to read in ss_array before rooms/nouns/creatures */
  ss_size=strptr=index[13].numrec;
  static_str=read_recblock(NULL,FT_CHAR,
			   index[13].numrec,index[13].file_offset,
			   index[13].blocksize);

  synptr=syntbl_size=index[19].numrec;
  syntbl=read_recblock(NULL,FT_WORD,index[19].numrec,index[19].file_offset,
		       index[19].blocksize);  

  maxroom=first_room+index[2].numrec-1;
  set_roomdesc(fi_room);
  room=read_recarray(NULL,sizeof(room_rec),index[2].numrec,
		     fi_room,"Room",index[2].file_offset,index[2].blocksize);
  
  maxnoun=first_noun+index[3].numrec-1;
  set_noundesc(fi_noun);
  noun=read_recarray(NULL,sizeof(noun_rec),index[3].numrec,
		     fi_noun,"Noun",index[3].file_offset,index[3].blocksize);

  last_obj=maxcreat=first_creat+index[4].numrec-1;  
  set_creatdesc(fi_creat);
  creature=read_recarray(NULL,sizeof(creat_rec),index[4].numrec,
			 fi_creat,"Creature",index[4].file_offset,
			 index[4].blocksize);

  last_cmd=index[5].numrec;  
  set_cmdptr(fi_cmdhead);
  command=read_recarray(NULL,sizeof(cmd_rec),index[5].numrec,
		       fi_cmdhead,"Metacommand",index[5].file_offset,
		       index[5].blocksize);

  NUM_ERR=index[6].numrec;  
  err_ptr=read_recarray(NULL,sizeof(descr_ptr),index[6].numrec,
		fi_descptr,"Error Message",index[6].file_offset,
		index[6].blocksize);

  last_message=index[7].numrec;
  msg_ptr=read_recarray(NULL,sizeof(descr_ptr),index[7].numrec,
			fi_descptr,"Message",index[7].file_offset,
			index[7].blocksize);

  MaxQuestion=index[8].numrec;
  question=answer=NULL;
  quest_ptr=read_recarray(NULL,sizeof(descr_ptr),index[8].numrec,
			  fi_descptr,"Question",index[8].file_offset,
			  index[8].blocksize);
  if (index[9].numrec!=index[8].numrec)
    fatal("File corrputed: questions and answers don't match.");
  ans_ptr=read_recarray(NULL,sizeof(descr_ptr),index[9].numrec,
			fi_descptr,"Answer",index[9].file_offset,
			index[9].blocksize);

  MAX_USTR=index[10].numrec;
  userstr=read_recarray(NULL,sizeof(tline),index[10].numrec,
			fi_tline,"User String",index[10].file_offset,
			index[10].blocksize);

  MAX_SUB=index[14].numrec;
  sub_name=read_recblock(NULL,FT_WORD,index[14].numrec,index[14].file_offset,
		index[14].blocksize);

  if (index[16].numrec>MAX_PIX) {
    index[16].numrec=MAX_PIX;
    index[16].blocksize=index[16].recsize*index[16].numrec;
  }
  maxpix=index[16].numrec;
  for(i=0;i<MAX_PIX;i++) pix_name[i]=0; /* In case there are less than 
					   MAX_PIX names */
  read_recblock(pix_name,FT_WORD,index[16].numrec,index[16].file_offset,
		index[16].blocksize);

  numglobal=index[17].numrec;
  globalnoun=read_recblock(NULL,FT_WORD,
			   index[17].numrec,index[17].file_offset,
			   index[17].blocksize);

  if (index[18].numrec>MAX_FLAG_NOUN) {
    index[18].numrec=MAX_FLAG_NOUN;
    index[18].blocksize=index[18].recsize*index[18].numrec;
  }
  
  for(i=0;i<MAX_FLAG_NOUN;i++) flag_noun[i]=0;
  read_recblock(flag_noun,FT_WORD,index[18].numrec,index[18].file_offset,
		index[18].blocksize);



  DVERB=index[15].numrec-old_base_verb-MAX_SUB;
  synlist=read_recblock(NULL,FT_SLIST,index[15].numrec,index[15].file_offset,
		index[15].blocksize);
  correct_synlist(); 

  /* dicstr must be read in before dict */
  dictstrsize=dictstrptr=index[20].numrec;
  dictstr=read_recblock(NULL,FT_CHAR,index[20].numrec,index[20].file_offset,
			index[20].blocksize);

  dp=index[21].numrec;
  dict=read_recblock(NULL,FT_DICTPTR,
		     index[21].numrec,index[21].file_offset,
		     index[21].blocksize);

  have_opt=(index[22].numrec!=0);
  for(i=0;i<14;i++) opt_data[i]=0;
  if (have_opt) {
    if (index[22].numrec>14) index[22].numrec=14;
    read_recblock(opt_data,FT_BYTE,index[22].numrec,index[22].file_offset,
		  index[22].blocksize); 
  }

  maxpict=index[23].numrec;
  pictlist=read_recblock(NULL,FT_STR,index[23].numrec,index[23].file_offset,
		     index[23].blocksize);
  maxpix=index[24].numrec;
  pixlist=read_recblock(NULL,FT_STR,index[24].numrec,index[24].file_offset,
		     index[24].blocksize);
  maxfont=index[25].numrec;
  fontlist=read_recblock(NULL,FT_STR,index[25].numrec,index[25].file_offset,
		     index[25].blocksize);
  maxsong=index[26].numrec;
  songlist=read_recblock(NULL,FT_STR,index[26].numrec,index[26].file_offset,
		     index[26].blocksize);

  vm_size=index[27].numrec;
  verbinfo=read_recarray(NULL,sizeof(verbentry_rec),index[27].numrec,
		       fi_verbentry,"Menu Vocabulary",index[27].file_offset,
		       index[27].blocksize);

  /* Block 12: Command text */
  read_command(index[12].numrec,index[12].file_offset, diag);       

  /* Block 11 is description block; it doesn't get read in by
     agxread() but during play */
  descr_ofs=index[11].file_offset;

  reinit_dict();
  return 1;
}      




static index_rec *index;

static void agx_compute_index(void)
     /* This computes the blocksize and offset values for all blocks */
{
  int i;

  for(i=0;i<AGX_NUMBLOCK;i++) 
      index[i].blocksize=index[i].recsize*index[i].numrec;
  index[0].file_offset=16;
  index[11].file_offset=index[0].file_offset+index[0].blocksize;
  index[12].file_offset=index[11].file_offset+index[11].blocksize;
  index[1].file_offset=index[12].file_offset+index[12].blocksize;
  for(i=2;i<=AGX_NUMBLOCK-1;i++)
    if (i==13)
      index[13].file_offset=index[10].file_offset+index[10].blocksize;
    else if (i!=11 && i!=12)
      index[i].file_offset=index[i-1].file_offset+index[i-1].blocksize;
}


/* Create the preliminary index for the new file and set it up so we can
 write descriptions to the new file */
void agx_create(char *gamename)
{
  int i;
  file_head_rec filehead;


  bw_open(gamename,pAGX);
  index=rmalloc(sizeof(index_rec)*AGX_NUMBLOCK);

  filehead.fileid=AGT_FILE_SIG;
  filehead.ver_own=filehead.ext_own='R';
  filehead.version=1;
  filehead.extnum=0;
  filehead.eol_chk1='\n';
  filehead.eol_chk2='\r';
  filehead.res1=0;
  filehead.res2=0;
  write_recarray(&filehead,sizeof(file_head_rec),1,fi_header,0);

  index[0].numrec=AGX_NUMBLOCK;
  for(i=1;i<AGX_NUMBLOCK;i++)  /* Initialize the rest to 0 */
    index[i].numrec=0;

  /* This writes random data to the file; their only purpose
     is to prevent problems with seeking beyond the end of file */
  write_recarray(NULL,sizeof(index_rec),AGX_NUMBLOCK,fi_index,16);

  old_base_verb=BASE_VERB; /* This will be constant for any given version
			      of the interpreter, but may change across
			      versions of the interpreter */
  /* Set record sizes */
  index[0].recsize=compute_recsize(fi_index);
  index[1].recsize=compute_recsize(fi_gameinfo);
  index[2].recsize=compute_recsize(fi_room);
  index[3].recsize=compute_recsize(fi_noun);
  index[4].recsize=compute_recsize(fi_creat);
  index[5].recsize=compute_recsize(fi_cmdhead);
  index[6].recsize=index[7].recsize=index[8].recsize=
    index[9].recsize=compute_recsize(fi_descptr);
  index[10].recsize=ft_leng[FT_TLINE];
  index[11].recsize=ft_leng[FT_CHAR]; 
  index[12].recsize=ft_leng[FT_INT16];
  index[13].recsize=index[20].recsize=ft_leng[FT_CHAR];  
  index[14].recsize=index[16].recsize=index[17].recsize=
    index[18].recsize=ft_leng[FT_WORD];
  index[15].recsize=ft_leng[FT_SLIST];
  index[19].recsize=ft_leng[FT_WORD];
  index[21].recsize=ft_leng[FT_DICTPTR];
  index[22].recsize=ft_leng[FT_BYTE];
  index[23].recsize=index[24].recsize=index[25].recsize=
    index[26].recsize=ft_leng[FT_STR];
  index[27].recsize=compute_recsize(fi_verbentry);

  agx_compute_index(); /* Only the first 10 blocks will be correct */
  /* The important thing is to get the offset of block 11, the desciption
     text block, so we can write to it. */
  /* Block 11 is description block; it doesn't get written by agxwrite()
     but by its own routines. */
}


static void agx_finish_index(void)
{
  /* Still have 11, 27-29 */
  /* Block 12 is taken care of elsewhere (in write_command) */

  index[1].numrec=1; 
  index[2].numrec=rangefix(maxroom-first_room+1);
  index[3].numrec=rangefix(maxnoun-first_noun+1);
  index[4].numrec=rangefix(maxcreat-first_creat+1);
  index[5].numrec=last_cmd;
  index[6].numrec=NUM_ERR;
  index[7].numrec=last_message;
  index[8].numrec=index[9].numrec=MaxQuestion;
  if (userstr!=NULL) 
    index[10].numrec=MAX_USTR;
  else index[10].numrec=0;
  index[13].numrec=strptr;
  index[15].numrec=TOTAL_VERB;  
  index[16].numrec=maxpix;
  index[17].numrec=numglobal;
  index[19].numrec=synptr;
  index[20].numrec=dictstrptr;
  index[21].numrec=dp;
  index[23].numrec=maxpict;
  index[24].numrec=maxpix;
  index[25].numrec=maxfont;
  index[26].numrec=maxsong;
  index[14].numrec=MAX_SUB;
  index[27].numrec=vm_size;

  /* These may also be zero (?) */
  index[22].numrec= have_opt ? 14 : 0;
  index[18].numrec=MAX_FLAG_NOUN;

  agx_compute_index(); /* This time it will be complete except for
			the VOC-TTL-INS blocks at the end */
}
 


/* The following routine writes a description to disk,
   and stores the size and length in dp */
void write_descr(descr_ptr *dp,descr_line *txt)
{
  int i;
  long size;
  char *buff, *buffptr, *src;

  size=0;
  if (txt==NULL) {
    dp->start=0;
    dp->size=0;
    return;
  } 

  for(i=0;txt[i]!=NULL;i++) /* Compute size */
    size+=strlen(txt[i])+1;  /* Remember trailing \0 */
  buff=rmalloc(sizeof(char)*size);

  buffptr=buff;
  for(i=0;txt[i]!=NULL;i++) {
    for(src=txt[i];*src!=0;src++,buffptr++)
      *buffptr=*src;
    *buffptr++=0;
  }
  dp->start=index[11].numrec;
  dp->size=size;
  index[11].numrec+=
    write_recblock(buff,FT_CHAR,size,
		   index[11].file_offset+index[11].numrec);
  rfree(buff);
}

/* Write command text to file and return number of bytes written. */
static long write_command(long cmdofs)
{
  int i, cnt;

  cmd_ptr=rmalloc(sizeof(long)*last_cmd);
  cnt=0;
  for(i=0;i<last_cmd;i++) {
    cmd_ptr[i]=cnt;
    write_recblock(command[i].data,FT_INT16,command[i].cmdsize,
		   cmdofs+2*cnt);
    cnt+=command[i].cmdsize;
  }
  return cnt;
}




/* Write the bulk of the AGX file. This requires that the descriptions,
   etc. have already been written */
void agx_write(void) 
{
  index[11].blocksize=index[11].numrec*index[11].recsize;
  index[12].file_offset=index[11].file_offset+index[11].blocksize;

  index[12].numrec=write_command(index[12].file_offset);  

  agx_finish_index();

  /* Need to write these blocks in order */

  write_globalrec(fi_gameinfo,index[1].file_offset);

  wset_roomdesc(fi_room);
  write_recarray(room,sizeof(room_rec),index[2].numrec,
		     fi_room,index[2].file_offset);

  wset_noundesc(fi_noun);
  write_recarray(noun,sizeof(noun_rec),index[3].numrec,
		     fi_noun,index[3].file_offset);

  wset_creatdesc(fi_creat);
  write_recarray(creature,sizeof(creat_rec),index[4].numrec,
			 fi_creat,index[4].file_offset);

  wset_cmdptr(fi_cmdhead);
  write_recarray(command,sizeof(cmd_rec),index[5].numrec,
		 fi_cmdhead,index[5].file_offset);

  write_recarray(err_ptr,sizeof(descr_ptr),index[6].numrec,
		fi_descptr,index[6].file_offset);
  write_recarray(msg_ptr,sizeof(descr_ptr),index[7].numrec,
		 fi_descptr,index[7].file_offset);
  write_recarray(quest_ptr,sizeof(descr_ptr),index[8].numrec,
		 fi_descptr,index[8].file_offset);
  write_recarray(ans_ptr,sizeof(descr_ptr),index[9].numrec,
		 fi_descptr,index[9].file_offset);

  if (userstr!=NULL)
    write_recarray(userstr,sizeof(tline),index[10].numrec,
		   fi_tline,index[10].file_offset);

  write_recblock(static_str,FT_CHAR,
		 index[13].numrec,index[13].file_offset);

  write_recblock(sub_name,FT_WORD,index[14].numrec,index[14].file_offset);
  write_recblock(synlist,FT_SLIST,index[15].numrec,index[15].file_offset);
  write_recblock(pix_name,FT_WORD,index[16].numrec,index[16].file_offset);
  write_recblock(globalnoun,FT_WORD,index[17].numrec,index[17].file_offset);
  write_recblock(flag_noun,FT_WORD,index[18].numrec,index[18].file_offset);
  write_recblock(syntbl,FT_WORD,index[19].numrec,index[19].file_offset);
  write_recblock(dictstr,FT_CHAR,index[20].numrec,index[20].file_offset);
  write_recblock(dict,FT_DICTPTR,index[21].numrec,index[21].file_offset);
  if (have_opt)
    write_recblock(opt_data,FT_BYTE,index[22].numrec,index[22].file_offset);

  write_recblock(pictlist,FT_STR,index[23].numrec,index[23].file_offset);
  write_recblock(pixlist,FT_STR,index[24].numrec,index[24].file_offset);
  write_recblock(fontlist,FT_STR,index[25].numrec,index[25].file_offset);
  write_recblock(songlist,FT_STR,index[26].numrec,index[26].file_offset);

  write_recarray(verbinfo,sizeof(verbentry_rec),index[27].numrec,
		 fi_verbentry,index[27].file_offset);
}


/* Write master index and close AGX file */
void agx_wclose(void)   
{
  write_recarray(index,sizeof(index_rec),AGX_NUMBLOCK,fi_index,16);
  bw_close();
  rfree(index);
}


void agx_wabort(void)
{
  bw_abort();
  rfree(index);
}
