/*  agtdata.c-- Miscellaneous utilities and data structures */
/* 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.    */

/*
  This is a mishmash of utilities and preinitialized arrays,
  including the verblist, the metacommand token list, 
  and the dictionary routines.
*/

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

#ifdef PROFILE_SUPPORT
#include <sys/times.h>
#endif


/* ------------------------------------------------------------------- */
/*  Preinitialized data structures                                     */
/*    Most of the preinitialized data structures used by all of the    */
/*    AGT-related programs go here .                                   */
/* ------------------------------------------------------------------- */


/* ------------------------------------------------------------ */
/* The PC --> Ascii conversion table. This converts the 8th-bit */
/*   PC charcters to their nearest ASCII equivalent.            */
/* ------------------------------------------------------------ */ 

const char trans_ibm[]=
"CueaaaaceeeiiiAA"   /* 80 */
"E@@ooouuyOUc$$pf"   /* 90 */
"aiounNao?....!<>"   /* A0 */
"###|++|+++|\\/++\\"   /* B0 */
"\\+++-+||\\/+++=+="   /* C0 */
"+=+++++++//@@@@@"   /* D0 */
"abGpSsmtFTOd.fe^"   /* E0 */
"=+><fj/=***/n2# ";  /* F0 */

 
/* ------------------------------------------------------------- */
/*  Tables of Opcodes                                            */
/*   These gives the names and argument types of all of the AGT  */
/*   opcodes.                                                    */
/* ------------------------------------------------------------- */

/* All of the following are undefined again just after the table */

#define n AGT_NUM
#define v AGT_VAR
#define r AGT_ROOM
#define i AGT_ITEM

#define o (AGT_ITEM|AGT_CREAT)  /* "object" */
#define l (r|o|AGT_NONE|AGT_SELF|AGT_WORN)   /* "location" */



/* opcode, argnum, arg1, arg2 */
#ifdef LOWMEM
#define a(s)  {"",0,0,0}  
#define b(s,a1) {"",1,(a1),0}
#define c(s,a1,a2) {"",2,(a1),(a2)}
#else 
#define a(s)  {#s,0,0,0}  
#define b(s,a1) {#s,1,(a1),0}
#define c(s,a1,a2) {#s,2,(a1),(a2)}
#endif

const opdef cond_def[]=
{
  b(AtLocation,r),b(AtLocationGT,n), b(AtLocationLT,n),  
    a(SongPlaying),a(SoundIsOn),a(DirectionOK),b(DirectionIs,AGT_DIR),
  c(BetweenRooms,n,n),b(HasVisitedRoom,r),
    a(EnteredObject),b(TimeGT,n),b(TimeLT,n),
  a(FirstVisitToRoom),
  a(NewLife),
  a(IsCarryingSomething),a(IsCarryingNothing),
  a(IsWearingSomething),
  b(IsCarryingTreasure,n),
  a(IsWearingNothing),  
  b(LoadWeightEquals,n),b(LoadWeightGT,n),b(LoadWeightLT,n),
  b(Present,o),b(IsWearing,o),b(IsCarrying,o),
  b(IsNowhere,o),b(IsSomewhere,o),
  b(InRoom,o),c(IsLocated,o,l),c(Together,o,o), 
  b(IsON,o),b(IsOFF,o),
  b(IsGroupMember,AGT_CREAT),
  b(IsOpen,o),b(IsClosed,o),b(IsLocked,o),b(IsUnLocked,o),
  b(IsEdible,o),b(IsDrinkable,o),b(IsPoisonous,o),
  b(IsMovable,o),
  a(NOUNPresent),a(NOUNIsWearing),a(NOUNIsCarrying),
  a(NOUNIsNowhere),a(NOUNIsSomewhere),
  a(NOUNInRoom),b(NOUNIsLocated,l), 
  a(NOUNIsOn),a(NOUNIsOff),
  a(NOUNIsOpen),a(NOUNIsClosed),a(NOUNIsLocked),a(NOUNIsUnLocked),
  a(NOUNIsEdible),a(NOUNIsDrinkable),a(NOUNIsPoisonous),
  a(NOUNIsMovable), 
  b(NOUNpointsEquals,n),b(NOUNpointsGT,n),b(NOUNpointsLT,n),
  b(NOUNweightEquals,n),b(NOUNweightGT,n),b(NOUNweightLT,n),
  a(LightPresent),a(RoomNeedsLight),
  b(FlagON,AGT_FLAG),b(FlagOFF,AGT_FLAG),
  b(RoomFlagOn,AGT_ROOMFLAG),b(Room_PixHere,AGT_PIX),
  b(RoomFlagOff,AGT_ROOMFLAG),
  b(ScoreEquals,n),b(ScoreGT,n),b(ScoreLT,n),
  b(NumberEquals,n),b(NumberGT,n),b(NumberLT,n),
  a(AnswerIsCorrect),a(AnswerIsWrong),
  b(TurnsEquals,n),b(TurnsGT,n),b(TurnsLT,n),
  c(CounterEquals,AGT_CNT,n),c(CounterGT,AGT_CNT,n),c(CounterLT,AGT_CNT,n),
  c(VariableEquals,v|n,n),c(VariableGT,v|n,n),c(VariableLT,v|n,n),
  c(CompareVariables,v,v),c(VariableChance,v|n,n),
  a(NamePresent),b(NameIsNumber,o|AGT_NONE),      /* QQ:Not sure about these */
  b(NOUNIsNumber,o|AGT_NONE),b(ObjectIsNumber,o|AGT_NONE),
  b(SomethingInside,r|o|AGT_SELF),
  b(Chance,n),
  a(PromptForYES),a(PromptForNO),
  a(VerbIsDirection),
  a(NOUNIsCreature),
  a(NOUNIsMan),a(NOUNIsWoman),a(NOUNIsThing),
  a(OBJECTIsMan),a(OBJECTIsWoman),a(OBJECTIsThing),
  a(ObjectIsCreature),
  a(ObjectPresent),
  a(NOT),a(OR),
  a(BeforeCommand),a(AfterCommand),     /* 110,111 */
  b(HourEquals,n),b(HourGT,n),b(HourLT,n),
  b(MinuteEq,n),b(MinuteGT,n),b(MinuteLT,n),
  a(IsAM), 
  
  a(OnDisambig),
  b(IsHostile,o), a(HostilePresent), 
  a(NameWasPresent), a(OncePerTurn)
};


const opdef act_def[]=
{
  b(GoToRoom,r),c(GoToRandomRoom,r,r),
  b(MakeVarRoomNum,v),b(MakeVarNounNum,v),b(MakeVarObjectNum,v),
  b(GoToVariableRoom,v|r),c(SendToVariableRoom,o,v|l),
  b(GetVariableIt,v|o),b(PrintVariableMessage,v|AGT_MSG),
  b(GetIt,o),b(WearIt,o),b(DropIt,o),b(RemoveIt,o),
  b(LoadFont,AGT_FONT),b(ShowPicture,AGT_PIC),c(ChangePicture,AGT_PIC,AGT_PIC),
  b(IfYShowPicture,AGT_PIC),
  b(ShowRoom_Pix,AGT_PIX),b(IfYShowRoom_Pix,AGT_PIX),
  b(PlaySong,AGT_SONG),c(PlayRandom,n,n),b(RepeatSong,AGT_SONG),
  a(EndRepeatSong),a(StopSong),a(SuspendSong),a(ResumeSong),
  a(ToggleMovable),c(ChangeDescr,r|o,AGT_MSG),c(ChangePoints,r|o,n),
  a(DestroyOBJECT),b(GetString,AGT_STR),
  b(GetVariable,v),b(SetVariableToTime,v),b(SetTimeToVariable,v|n),
  b(SetTime,n),b(AddToTime,n),b(SetDeltaTime,n),  
  b(DoSubroutine,AGT_SUB),a(Return),
  a(GetNOUN),a(WearNOUN),a(DropNOUN),a(RemoveNOUN),
  a(DropEverything),a(RemoveEverything),a(KillPlayer),
  b(PutInCurrentRoom,o),c(SendToRoom,o,l),
  c(RePosition,o,l),  
  a(PutNOUNInCurrentRoom),b(SendNOUNToRoom,l),
  b(SendAllToRoom,l),c(SendTreasuresToRoom,l,n),
  c(RelocateAll,l,l),
  b(Destroy,o),a(DestroyNOUN),
  c(SwapLocations,o,o),c(SendToItem,o,o),b(SendNOUNtoItem,o),
  b(AddToGroup,AGT_CREAT),b(RemoveFromGroup,AGT_CREAT),b(MoveTheGroup,l),
  a(RedirectTo),          
  c(RandomMessage,AGT_MSG,AGT_MSG), b(ShowContents,r|o|AGT_SELF|AGT_WORN),
  b(OpenIt,i),b(CloseIt,i),b(LockIt,i),b(UnlockIt,i),
  a(OpenNOUN),a(CloseNOUN),a(LockNOUN),a(UnlockNOUN),
  a(ShowScore),b(PlusScore,n),b(MinusScore,n),
  a(ShowInventory),a(WaitForReturn),a(TimePasses),
  b(Delay,n),
  a(ClearScreen),
  b(DescribeThing,r|o),a(LookAtRoom),
  b(PrintMessage,AGT_MSG),a(BlankLine),c(Tone,n,n),
  c(GetNumberInput,n,n),b(AskQuestion,AGT_QUEST),
  c(ChangePassageway,AGT_DIR,AGT_EXIT),
  b(TurnFlagOn,AGT_FLAG),b(TurnFlagOff,AGT_FLAG),b(ToggleFlag,AGT_FLAG),
  b(TurnRoomFlagOn,AGT_ROOMFLAG),b(TurnRoomFlagOff,AGT_ROOMFLAG),
  b(ToggleRoomFlag,AGT_ROOMFLAG),
  b(TurnCounterOn,AGT_CNT),b(TurnCounterOff,AGT_CNT),
  c(SetVariableTo,v,n),c(AddToVariable,v|n,n),c(SubtractFromVariable,v|n,n),
  c(AddVariables,v,v),c(SubtractVariables,v,v),
  c(RandomVariable,v,n),
  b(NounToVariable,v),b(ObjectToVariable,v),
  b(Quote,AGT_MSG),
  b(TimePlus,n),b(TimeMinus,n),b(SetHour,n),b(SetMinute,n),
  b(TimePlusVariable,v|n),b(TimeMinusVariable,v|n),
  b(SetHourToVariable,v|n),b(SetMinutesToVariable,v|n),

  b(SubtractFromTime,n), b(SetDisambigPriority,n),
  b(SetVariableToDeltaTime,v),b(ChangeStatus,n),
  c(MultiplyVariable,v|n,n),c(DivideVariable,v|n,n),
  c(ComputeRemainder,v|n,n),
  a(WaitForKey),
  b(SetHE,o),b(SetSHE,o),b(SetIT,o),b(SetTHEY,o),
  b(PrintMessageNoNL,AGT_MSG),
  b(StandardMessage,AGT_ERR), 
  b(FailMessage,AGT_MSG), b(FailStdMessage,AGT_ERR),
  c(ErrMessage,n,AGT_MSG),  c(ErrStdMessage,n,AGT_ERR),
  a(AND)
};

const opdef end_def[]={ 
  a(WinGame),a(EndGame),
  a(QuitThisCMD),a(QuitAllCMDs),a(DoneWithTurn)
};

const opdef illegal_def=a(ILLEGAL);

#undef a
#undef b
#undef c

#undef n 
#undef v
#undef r
#undef i
#undef o
#undef l




/* ------------------------------------------------------------- */
/*  Opcode Translation Tables                                    */
/*    These convert opcode numbers from the various AGT versions */
/*    to a uniform coding.                                       */
/* ------------------------------------------------------------- */

/*NOTE this is being changed so that rather than the second term
  is an absolute offset of the first term. Still applies to ranges
  up until next one. Also incorporates the +1000 correction
  into the correction set itself. (to avoid further problems
  when including more opcodes, e.g. AGT 1.83).
   The last table entry is now marked by a new value of -1.*/

/* Versions of the command set:
    v1.21 apparantly has a compatible command set w/ 1.7 (!)
      [except that their maxcmd is apparantly 22, not 30]
    1.0 doesn't; it seems to have an EOC code of 154, as opposed to
    165 or so.
    1.18 seems to be slightly different from 1.7, but seemingly only
       by one opcode.
    [And of course both ME and 1.8 have their own extended command sets]
*/

static const cmd_fix_rec FIX_ME[]=   /* No longer using this as baseline */
{ {0,0},
    {110,1000},  /* i.e. commands moved to start at opcode 1000 */
    {215,WIN_ACT},
    {220,-1}}; 

static const cmd_fix_rec FIX_ME0[]= /* This *seems* to work */
/* 169 */
{ {0,0},
    {110,1000},
    {136,1028},  /* Skip ToggleMoveable and ChangeDescr */
    {156,1049},  /* Skip RePosition */
    {212,WIN_ACT},
    {217,-1}};

static const cmd_fix_rec FIX_ME15[]= 
{ {0,0},
    {110,1000},  /* i.e. commands moved to start at opcode 1000 */
    {158,1049},   /* Skip the one opcode added in 1.56: RePosition */  
    {214,WIN_ACT},
    {219,-1}}; 

static const cmd_fix_rec FIX_135[]=    
{ {0,0},
    {3,12},
    {59,71},
    {88,106},
    {92,1000},
    {105,1039}, /* 149 */
    {114,1049}, /* 159 */
    {157,1095}, /* 205 */
    {167,WIN_ACT},
    {172,-1}};

static const cmd_fix_rec FIX_118[]=    
{ {0,0},
    {3,12},
    {59,71},
    {88,106},
    {92,1000},
    {105,1039}, /* 149 */
    {114,1049}, /* 159 */
    {118,1054}, /* Skip SendTreasuresToRoom */
    {156,1095}, /* 205 */
    {166,WIN_ACT},
    {171,-1}};


static const cmd_fix_rec FIX_182[]=
{ {0,0},
    {3,12},
    {53,110},  /* Shift BeforeCmd and AfterCmd */
    {55,62},
    {61,71},
    {90,106},
    {94,1000},
    {107,1039}, /* 149 */
    {116,1049}, /* 159 */
    {143,1105},   /* QUOTE-- need to move somewhere else */
    {144,1076},
    {160,1095}, /* 205 */
    {170,WIN_ACT},
    {175,-1}};

static const cmd_fix_rec FIX_183[]=
{ {0,0},
    {3,12},
    {55,110},  /* Shift BeforeCmd and AfterCmd */
    {57,64},
    {61,71},
    {90,106},
    {94,112},   /* Time condition tokens */
    {102,1000},          
    {115,1039}, 
    {124,1049}, 
    {159,1105},   /* QUOTE-- need to move somewhere else */
    {160,1084}, 
    {168,1095},  
    {170,1106},     /* Time Action Tokens */  
    {178,1095},
    {186,WIN_ACT},
    {191,-1}};

static const cmd_fix_rec FIX_183A[]=
{ {0,0},
    {3,12},
    {55,110},  /* Shift BeforeCmd and AfterCmd */
    {57,64},
    {61,71},
    {90,106},
    {94,112},   /* Time condition tokens */
         /* In early 1.83, there seems to be no IsAM conditional ?? */
    {101,1000},          
    {114,1039}, 
    {123,1049}, 
    {158,1105},   /* QUOTE-- need to move somewhere else */
    {159,1084}, 
    {167,1095},  
    {169,1106},     /* Time Action Tokens */  
    {177,1095},
    {185,WIN_ACT},
    {190,-1}};

static const cmd_fix_rec FIX_10[]=  /* This doesn't work yet */  
{ {0,0},
    {3,12},
    {59,71},
    {80,95},
    {84,108},
    {86,1000},
    {88,1009},
    {92,1039},
    {101,1049},
    {105,1054},
    {115,1065},
    {142,1095},
    {152,WIN_ACT},
    {157,-1}};

static const cmd_fix_rec FIX_15[]=    /* This works */
{ {0,0},
    {3,12},     /* Skip 3-11 */
    {60,70},    /* Skip 69 */
    /* {61,72}, */   /* Skip 71 -- WRONG! */
    {90,106},   /* Skip 101-105 */
    {94,1000},   
    {107,1039},  /* skip 1013-1038 */
    {116,1049},  /* Skip 1048  */
    {172,WIN_ACT},
    {177,-1}};

const fix_array FIX_LIST[]= /* An array of arrays, indexed by aver */
{FIX_135, /* Aver=0: unknown format, might as well assume Classic */
   FIX_10, FIX_118, FIX_135, FIX_135, FIX_135, FIX_182, FIX_183A, FIX_183, 
   FIX_15, FIX_15, FIX_15, FIX_ME0, FIX_ME15, FIX_ME15, FIX_ME};


/* ------------------------------------------------------------- */
/* Miscellaneous collections of strings                          */
/* ------------------------------------------------------------- */

const char* verstr[]={"????","SMALL","BIG","MASTER","SOGGY"};
const char* averstr[]={"????","1.0","1.18","1.2","1.32/COS","Classic",
		       "1.82","1.83a","1.83",
		       "1.5","1.5/F","1.5/P",
		       "ME/1.0","ME/1.5","ME/1.55","ME/1.6",
		       "Magx"};

const char *portstr=PORTSTR;
const char *version_str="version 0.7.2 (beta)";

/* Names of exits */
const char* exitname[13]=
        {"N","S","E","W","NE","NW","SE","SW","U","D","IN","OUT","SPC"};




/* ------------------------------------------------------------- */
/* Verblist is the  array of canonical forms of all the verbs    */
/* ------------------------------------------------------------- */
/* The following long string defines all the built in AGT verbs, in the 
   following format:  
  verb syn syn syn , prep prep ; next_verb ....
  except that if a verb takes no objects at all, it should be period
  terminated and if it is a metaverb it should be terminated by '!'. */
static const char verbdef[]= 
"north n. south s. east e. west w." 
"northeast ne. northwest nw. southeast se. southwest sw."
"up u. down d. enter in inside. exit leave out. special."
"throw cast dump, at to in into across inside;"
"open , with; close shut; lock, with; unlock, with;"
"look l. examine x ex check inspect; change_locations change_location;"
"read; eat; drink; score! attack kill fight hit, with;"
"wait z. yell shout scream."
"put place, in with inside into near behind over under on;"
"quit q! tell talk, to about; inventory inv i. get take pick; ask, about for;"
"turn, on off; push touch press, with; pull; play; list. show, to; drop;"
"listexit listexits list_exits. brief! verbose! save! restore!"
"light; extinguish ext; fire shoot, at with;"
"help h. wear; remove; script! unscript! magic_word. view; after."
"instructions ins!"   /* INSTRUCTIONS is "1.83 only" */
/* The following are not defined in the original AGT */
"again g. restart! oops; undo. notify! listexit_on! listexit_off!"
"agildebug agtdebug! log! logoff! replay! replay_step! menu! UNUSED."
"sound sound_on! sound_off! introduction intro! dir_addr.";

/* 1.83: Removes listexit; adds instructions after remove. */

/* Then come the dummy verbs */
/* Dummy verb n ==> n-55     105,122
    Dummy_verb1...Dummy_Verb50        */	      
 	 
/* Possible extension to verb definitons (not implemented): 
   If it _requires_ a prep, use : ? 
   If it takes a prep and no dobj, use | ? 
*/

	      


/* ------------------------------------------------------------------- */
/* Dictionary primitives: the basic functions for manipulating the     */
/* dictionary data structures.                                         */
/* ------------------------------------------------------------------- */
#define HASHSIZE (1<<HASHBITS)
#define HASHMASK (HASHSIZE-1)

#ifdef DOHASH
static word hash[HASHSIZE];
#endif

static int hashfunc(const char *s)
{
  unsigned long n, i;

  n=0;
  for(;*s!=0;s++) {
    n+=(n<<2)+(uchar)*s;
    i=n & ~HASHMASK;
    if (i)
      n=(n^(i>>HASHBITS))&HASHMASK; 
  }
  return (n & HASHMASK);
}

static word search0_dict(const char *s)
{
  int i;

#ifdef DOHASH
  for(i=hashfunc(s);
      hash[i]!=-1 && strcmp(s,dict[hash[i]])!=0;
      i=(i+1)&HASHMASK);
  return hash[i];
#else
  for(i=0; strcmp(s,dict[i])!=0 && i<dp; i++);
  if (i<dp) return i;
  return -1;
#endif
}

word search_dict(const char *s)	    
/* This does a case-insensitive search */
{
  word w;
  char *t,*p;

  t=rstrdup(s);
  for(p=t;*p;p++) *p=tolower(*p);
  w=search0_dict(t);
  rfree(t);
  return w;
}
  
/* The basic routine to add s to the dictionary; this does no preprocessing
  of s; use add_dict for that */
static word add0_dict(const char *s)
{
  int i;
  long newptr;
  char *newstr;

  i=search0_dict(s);
  if (i!=-1) return i; 
  /* Okay, it's not in the dictionary; need to add it. */
  /*  rprintf("Adding %s\n",s);*/

  dict=rrealloc(dict,sizeof(char*)*(dp+1));
  newptr=dictstrptr+strlen(s)+1;
  if (newptr>dictstrsize) {  /* Enlarge dictstr */
    while(newptr>dictstrsize)
      dictstrsize+=DICT_GRAN;
    newstr=rrealloc(dictstr,dictstrsize);
    for(i=0;i<dp;i++)
      dict[i]=(dict[i]-dictstr)+newstr;
    dictstr=newstr;
    /* Now need to update all of our pointers */
  }
  strcpy(dictstr+dictstrptr,s); /* Copy word into memory */
  dict[dp]=dictstr+dictstrptr;
  dictstrptr=newptr;

#ifdef DOHASH  /* Need to update the hash table */
  if (dp>HASHSIZE) fatal("Hash table overflow");
  for(i=hashfunc(s);hash[i]!=-1;i=(i+1)&HASHMASK);
  hash[i]=dp;
#endif
  return dp++;
}

#ifdef DOHASH

static void init_hash(void)
{
  int i;

  for(i=0;i<HASHSIZE;i++) hash[i]=-1;
}


/* This routine rebuilds the hash table from the dictionary. */
/* It's used by the AGX reading routines, since they save */
/* the dictionary but not the hash table */
static void rebuild_hash(void)  
{
  int i,j;

  if (dp>HASHSIZE) fatal("Hash table overflow");
  init_hash();

  for(i=0;i<dp;i++) {
    for(j=hashfunc(dict[i]);hash[j]!=-1;j=(j+1)&HASHMASK);
    hash[j]=i;    
  }
}
#endif


static void init0_dict(void)
/* This sets up the basic data structures associated with the dictionary */
/* (It's called by init_dict, which also adds the basic verbs) */
{
#ifdef DOHASH
  init_hash();
  hash[hashfunc("any")]=0;
#endif

  dict=rmalloc(sizeof(char*));
  dictstr=rmalloc(DICT_GRAN);
  strcpy(dictstr,"any");
  dict[0]=dictstr;
  
  dictstrptr=4; /* Point just after 'any' */
  dictstrsize=DICT_GRAN;
  dp=1;
  syntbl=NULL;synptr=0;syntbl_size=0; /* Clear synonym table */
} 




/* ------------------------------------------------------------------- */
/* Higher level dictionary routines: Things that load initial vocab,   */
/* and massage strings into the correct form for the dictionary        */
/* ------------------------------------------------------------------- */

static void enter_verbs(int vp, const char *s)
/* Read definition string s, starting to make entries at verb # vp */
/* WARNING: This doesn't do any sort of checking; it assumes the input
   string is correctly formed. */
{
  const char *p; /* Points along string. */
  words curr;  /* word currently being read. */
  int n; /* length of curr */

  n=0;
  auxsyn[vp]=synptr;
  for(p=s;*p!=0;p++) 
    if (*p==';' || *p==',' || *p=='.' || *p=='!' || isspace(*p)) {
      if (n>0) { /* word just ended: need to add it to dictionary etc */
	curr[n]=0;n=0;
	addsyn(add0_dict(curr)); /* Add to syn list or prep list, depending */
      }
      if (!isspace(*p))  
	addsyn(-1); /* Mark the end of the list */
      if (*p==';' || *p=='.' || *p=='!') {
	if (*p==';') verbflag[vp]|=VERB_TAKEOBJ; 
	if (*p=='!') verbflag[vp]|=VERB_META;
	vp++;
	if (vp>=TOTAL_VERB) break;
	auxsyn[vp]=synptr;  /* The following words will be the syn list */
      }
      else if (*p==',') 
	preplist[vp]=synptr; /* The following words will be the prep list */
    }    
    else curr[n++]=*p;  
}


static bool no_syn;


void init_dict(void)
{
  dict=NULL;verblist=NULL;syntbl=NULL;no_syn=0;
  auxsyn=NULL;preplist=NULL;verbflag=NULL;
}

/* This is called by agttest.c */
void build_verblist(void)
{
  int i;

  verblist=rmalloc(sizeof(words)*TOTAL_VERB);
  for(i=0;i<TOTAL_VERB;i++)
    strncpy(verblist[i],dict[syntbl[auxsyn[i]]],sizeof(words));
#ifdef DUMP_VLIST
  { 
    int j;
    rprintf("VERB LIST:\n");
    for(i=0;i<TOTAL_VERB;i++) {
      rprintf("%2d %s:",i,verblist[i]);
      for(j=auxsyn[i];syntbl[j]!=0;j++)
	rprintf(" %s",dict[syntbl[auxsyn[i]]]);
      rprintf(" ==> ");
      for(j=preplist[i];syntbl[j]!=0;j++)
	rprintf(" %s",dict[ syntbl[preplist[i]]] );
      writeln("");
    }
  }
#endif
}



void set_verbflag(void)
{
  verbflag[14]|=VERB_MULTI;  /* throw */
  verbflag[29]|=VERB_MULTI;  /* put */
  verbflag[33]|=VERB_MULTI;  /* get */
  verbflag[41]|=VERB_MULTI;  /* drop */
  verbflag[51]|=VERB_MULTI;  /* wear */
  verbflag[52]|=VERB_MULTI;  /* remove */
}


void reinit_dict(void)
/* reinit_dict initializes verblist and sets up aux_syn as well
   as loading the initial vocabulary into the dictionary. */
{ 
  char buff[16]; /* Needs to be big enough to hold dummy_verbNNN\0
		    or subroutineNNN\0 */
  int i;

  no_syn=no_auxsyn;

  auxsyn=rmalloc(sizeof(slist)*TOTAL_VERB);
  preplist=rmalloc(sizeof(slist)*TOTAL_VERB);
  verbflag=rmalloc(sizeof(uchar)*TOTAL_VERB);

  if (!agx_file) 
    init0_dict();
#ifdef DOHASH
  else 
    rebuild_hash();
#endif

  for(i=0;i<TOTAL_VERB;i++)
    verbflag[i]=0;

  auxsyn[0]=synptr;
  addsyn(-1);
  
  enter_verbs(1,verbdef); 
  set_verbflag(); /* Do additional verbflag initialization */

  for(i=0;i<DVERB;i++)
    {
      sprintf(buff,"dummy_verb%d",i+1);
      auxsyn[i+BASE_VERB]=synptr;
      addsyn(add0_dict(buff));
      addsyn(-1);
    }
  for(i=0;i<MAX_SUB;i++)
    {
      sprintf(buff,"subroutine%d",i+1);
      auxsyn[i+BASE_VERB+DVERB]=synptr;
      addsyn( sub_name[i]=add0_dict(buff) ); 
      addsyn(-1);
    }
  no_syn=0;  /* Return to usual state */
  verblist=NULL;
}




void free_dict(void)
{
  rfree(dict);rfree(verblist);rfree(syntbl);
  rfree(auxsyn);rfree(preplist);rfree(verbflag);
}

word add_dict(const char *str)
{
  int i, j;
  char s[50];
  
  strncpy(s,str,48);
  for(i=0;s[i]!=0 && isspace(s[i]);i++); 
  if (s[i]==0) return 0; /* If it's all whitespace, ignore. */
 /* i now points at first non-whitespace character */
 /* Eliminate leading whitespace and lowercase the string. */
  for(j=0;s[j+i]!=0;j++) s[j]=tolower(s[j+i]);
  s[j]=0; 
 /* Now eliminate trailing whitespace (j points to end of string) */
  for(j--;isspace(s[j]) && j>0; j--);
  s[j+1]=0;
 /* Okay, now make sure it isn't 'none' */
  if (strcmp(s,"none")==0) return 0;
 /* Finally, add it to the dictionary if it isn't already there */
  return add0_dict(s);
}

/* Adds w to dynamically grown synonym list */
/* If no_syn is set, then *don't* add a synonym: return immediatly */
/*  (This is done by agt2agx to avoid creating the auxsyn lists,  */
/*   since those should be created when the interpreter loads the */
/*   game file and not before) */
void addsyn(word w)
{
  if (no_syn) return;
  if (w==0) return;
  if (w==-1) w=0;
  if (synptr>=syntbl_size) {
    syntbl_size+=SYN_GRAIN;
    if (syntbl_size>0x7FFF) 
      fatal("Too many synonyms.");
    syntbl=rrealloc(syntbl,((long)syntbl_size)*sizeof(word)); }
  syntbl[synptr++]=w;
}





/* ------------------------------------------------------------------- */
/* General utilities linking objects to their names                   */
/* ------------------------------------------------------------------- */

int verb_code(word w)
/* Given a word w, searches auxsyn and returns the verb id */
{
  int i,j;

  /* Check game-specific synonyms first */
  /* Scan in reverse so later synonyms will override earlier ones */
  for(i=TOTAL_VERB-1;i>0;i--)  
    for(j=synlist[i];syntbl[j]!=0;j++)
      if (w==syntbl[j]) return i;

/* Then check built in verbs */
  /* (Do this second so as to allow the game files to override this) */    
  for(i=1;i<TOTAL_VERB;i++)
    for(j=auxsyn[i];syntbl[j]!=0;j++)
      if (syntbl[j]==w) return i;

 /* Failed to find a match */
  return 0;
}

/* This is a faster version of the above  for use in the special case of 
   command headers where the verb word is much more restricted; it should
   be the first auxsyn entry and it should never by a synlist entry. */
static int cmdverb_code(word w)
{
  int i,j;

  for(i=0;i<TOTAL_VERB;i++)
    if (syntbl[auxsyn[i]]==w) return i;
  /* Hmm... that failed. Search the rest of the auxsyns in case the
     order of auxsyns has changed or something */
  agtwarn("Header verb not in canonical form.",1);
  for(i=1;i<TOTAL_VERB;i++)
    for(j=auxsyn[i];syntbl[j]!=0;j++)
      if (syntbl[j]==w) return i;
  agtwarn("Header verb not in internal list.",1);
  return verb_code(w);
}

char *objname(int i)  /* returns malloc'd name string of object i */
{
  char *s;

  if (i<0) 
    return rstrdup(dict[-i]);
  if (i==0)
    return rstrdup("....");
  if (i==1) return rstrdup("*Self*");
  if (i==1000) return rstrdup("*Worn*");
  if (i>=first_room && i<=maxroom)
    return rstrdup(room[i-first_room].name);
  if (i>=first_noun && i<=maxnoun) {
    if (strcmp(dict[noun[i-first_noun].adj],"no_adjective")==0)
	       return rstrdup(dict[noun[i-first_noun].name]);
    return concdup(dict[noun[i-first_noun].adj],
		  dict[noun[i-first_noun].name]);
  }
  if (i>=first_creat && i<=maxcreat)
    return concdup(dict[creature[i-first_creat].adj],
		   dict[creature[i-first_creat].name]);    
 /* At this point we can't get a name: return ILLn. */
  s=rmalloc(3+1+(5*sizeof(int))/2+1);    
         /* Make sure we have enough space in case i is big */
  sprintf(s,"ILL%d",i);
  return s;
}



/* ------------------------------------------------------------------- */
/*  Routines to sort the command array and construct verbptr           */ 
/* ------------------------------------------------------------------- */

#define SORT_META

#ifdef SORT_META

#define ch1 ((const cmd_rec*)cmd1)
#define ch2 ((const cmd_rec*)cmd2)

/* See notes below before trying to decipher this routine;
   during the sort, many of the fields are being used for nonstandard
   purposes */



#define s_verb(cmd) ( (cmd)->actor<0 ? (cmd)->data[0] : (cmd)->verbcmd)

static int cmp_cmd(const void *cmd1, const void *cmd2)
{
  word v1,v2;

  /* We are sorting on command[].verbcmd, but if one of the headers
     is really the object of a redirect command then we need to use
     its parent's verbcmd */
  /* For commands with actors, we need to avoid sorting them at all. */
  v1=s_verb(ch1);
  v2=s_verb(ch2);

  if (v1<v2) return -1;
  if (v1>v2) return +1;
  
 /* v1==v2, so leave them in the same order as before */
 /* We have to take absolute values here because we are using negatives
    to indicate redirection objects */
  if ( abs(ch1->actor) < abs(ch2->actor) )
    return -1;
  else return 1;
  /* Equality should be impossible */
}

#undef ch1
#undef ch2

/* This sets things up for qsort */
/* We need a sort that is 
   i) Stable and
   ii) Keeps "redirection headers" attached to the correct command */
/* We steal the field actor for this purpose */
/*   actor will equal the index of the header in the original list. */
/*   (or negative the header if the command is a redirection) */
/* For redirected commands, we steal the data pointer since it shouldn't
    be being used anyhow. */
/* In a field pointed to by data we store the verb word */
/* NOTE: this routine requires that the data type of *data (namely
  integer) is big enough to hold a value of type word. */

static void rsort(void)
{
  long i;
  integer *save_actor;
  word *save_verb;

  save_actor=rmalloc(last_cmd*sizeof(integer));
  save_verb=rmalloc(last_cmd*sizeof(word));

  /* The following loop does three things:
     i) Copies command[].actor to save_actor[] 
     ii) Sets command[].actor to the commands index in the array 
     iii) For actor commands, sets the verb to .... after saving it
            in save_verb.
     iv) For redirection commands, stores the verb of the owning 
       header in a block pointed to by data */

  for(i=0;i<last_cmd;i++) {  /* Copy actor to save_actor */
    save_verb[i]=command[i].verbcmd;
    if (command[i].actor>1)  /* i.e. there _is_ an actor */
      command[i].verbcmd=syntbl[auxsyn[DIR_ADDR_CODE]];
    save_actor[i]=command[i].actor;
    command[i].actor=i;  
    if (save_actor[i]<0) { /* Redirected command */
      command[i].actor=-i;
      rfree(command[i].data); /* data may be NULL, anyhow */
      command[i].data=rmalloc(sizeof(integer)); 
      if (i>0) 
	command[i].data[0]=command[i-1].verbcmd; 
      else {
	command[i].data[0]=0;
	agtwarn("First command header is REDIRECT object!",0);
      }
    }
  }

  /* Now do the sort... */
  qsort(command,last_cmd,sizeof(cmd_rec),cmp_cmd);

#if 0  /* This is code to test the integrity of the sort */
  for(i=0;i<last_command;i++)
    if (command[i].actor<0)
      assert(i==0 || command[i].data[0]==command[i-1].verbcmd);
#endif

  /* Finally, restore everything to normal */
  for(i=0;i<last_cmd;i++) {  /* Restore actor */
    command[i].verbcmd=save_verb[abs(command[i].actor)];
    command[i].actor=save_actor[abs(command[i].actor)];
    if (command[i].actor<0) {
      rfree(command[i].data);  /* Sets it to NULL automatically */
      command[i].cmdsize=0;
    }
  }
  rfree(save_actor);
  rfree(save_verb);
}

#endif

void sort_cmd(void)
{
  int i;
  word curr_vb;
  word all_word, global_word;

  verbptr=rmalloc(sizeof(short)*TOTAL_VERB);
  verbend=rmalloc(sizeof(short)*TOTAL_VERB);

  if (mars_fix) {  /* Don't bother if mars scanning is active */
    for(i=0;i<TOTAL_VERB;i++) {
      verbptr[i]=0;         /* That is, scan the whole space for all verbs */
      verbend[i]=last_cmd;}
    return;
  }

#ifdef SORT_META
  if (!agx_file) rsort();
#endif


  if (no_auxsyn) return; /* Used by agt2agx */

  for(i=0;i<TOTAL_VERB;i++) {
    verbptr[i]=last_cmd; 
    verbend[i]=0;
  }

  all_word=search_dict("all");
  if (all_word==0) all_word=-1; /* This means none of the metacommands
				   used ALL, so prevent ANY matches */
  global_word=search_dict("global_scope");
  if (global_word==0) global_word=-1;  /* Ditto */


  for(i=0;i<last_cmd;i++) {
    if (command[i].actor<0) continue; /* Redirection */
    if (command[i].nouncmd==all_word)  
      /* Detect multinoun accepting verbs by ALL */
      verbflag[cmdverb_code(command[i].verbcmd)]|=VERB_MULTI;
    if (command[i].actor>1) 
      curr_vb=DIR_ADDR_CODE;
    else 
      curr_vb=cmdverb_code(command[i].verbcmd);
    if (i<verbptr[curr_vb]) verbptr[curr_vb]=i;
    if (i>verbend[curr_vb]) verbend[curr_vb]=i;
  }

  for(i=0;i<TOTAL_VERB;i++) 
    if (verbptr[i]==last_cmd)  /* No occurences of this verb */
      verbend[i]=last_cmd;
    else verbend[i]++; /* Point *after* last occurance */

  for(i=0;i<TOTAL_VERB;i++) {
    int j;

    j=synlist[i];
    if (syntbl[j]==0) continue;
    while(syntbl[j]!=0) j++;
    j--;
    if (syntbl[j]==global_word) { /* Ends with global_scope */
      verbflag[i]|=VERB_GLOBAL;
      syntbl[j]=0;
    }
  }
}




/* ------------------------------------------------------------------- */
/*  Functions for getting opcode information                           */
/* ------------------------------------------------------------------- */


/* Returns the opdef structure associated with an opcode */
const opdef *get_opdef(integer op)
{
  if (op<0 || (op>MAX_COND && op<START_ACT) || (op>PREWIN_ACT && op<WIN_ACT)
      || (op>MAX_ACT) ) {
    agtwarn("Illegal opcode found.",1);
    return &illegal_def;
  }
  if (op>=2000) 
    return &end_def[op-2000];
  if (op>=1000)
    return &act_def[op-1000];
  return &cond_def[op];
}




/* ------------------------------------------------------------------- */
/* Functions for reading in descriptions                               */
/* ------------------------------------------------------------------- */

descr_line *read_descr(long start,long size)
{
  if (agx_file)
    return agx_read_descr(start,size);
  else 
    return agt_read_descr(start,size);
}

void free_descr(descr_line *txt)
{
  if (txt==NULL) return;
  rfree(txt[0]);  /* First free the string block containing the text...*/
  rfree(txt);    /* ... then the array of pointers to it */
}





/* ------------------------------------------------------------------- */
/* Warning and error functions                                         */
/* ------------------------------------------------------------------- */

void agtwarn(const char *s,int elev)
{
  if (ERR_LEVEL>=elev) 
    rprintf("Warning: %s\n",s);
}

void agtnwarn(const char *s,int n,int elev)
{
  if (ERR_LEVEL>=elev) 
    rprintf("Warning: %s%d.\n",s,n);
}

void fatal(const char *s)
{
  /* We don't use rprintf in this case since we may be in too much trouble 
   for it to work */
  rprintf("Fatal error: %s\n",s);
  close_interface();
  exit(EXIT_FAILURE);
}

