EGwhaven Code Reference
-----------------------
This document is intended to give a reference guide to the structure of the
game's code.  Some things may not be fully documented yet.

NOT DONE: CDROM.C

=============================================================================
MISC NOTES
=============================================================================
To change the name of the EXE produced, alterations should be done to both
WHAVEN.MAK and WHAVEN.LNK.  The names in both files should match, though
only the .MAK file will include the .EXE extension on the file name.
=============================================================================


=============================================================================
WHAVEN.C
=============================================================================
Overarching purpose:
Entry point of execution, set up and shut down the game, including BUILD
 init, load needed data and configurations, perform the core game loop,
 handle errors.
=============================================================================
 void faketimerhandler(void)
   Does nothing?
   See also WHMSC.C which has a version with functioning code.

 int getvmode(void)
   Low-level function, judging by name, probably finds out what video mode
   is set.

 void cls80x25(int top, int mid, int bot)
   Directly adjust text mode screen memory, using "top" to set the colors
   for the top row, "bot" for the bottom row and "mid" for the rest.

 void tprintf(int x, int y, char *fmt,...)
   Directly access text mode screen memory to print a formatted string at
   position x, y.

 void showadditionalinfo(void)
   Appears to be for outputting an average framerate.

 void shutdown(void)
   Handles closing the game, saving options set during play to file.  Calls
   various shutdown routines, terminates the program unless crashflag was
   set.

 void crash(char *fmt)
   Set crashflag, call shutdown(), display an error message, call longjmp

 void doanimations(long numtics)
   Presumably to handle animating something.

 long getanimationgoal(long *animptr)
   Presumably also animation related.

 long setanimation(long *animptr, long thegoal, long thevel)
   Presumably also animation related.

 void setdelayfunc(void (*func) (), int item, int delay)
   Timer related?

 void dodelayitems(int tics)
   Timer related?

 void setup3dscreen(void)
   Initialization for graphics, sets things differently depending on whether
   or not SVGA mode was chosen.

 void setupboard(char *fname)
   fname - name of a map file to load.  If not loadable, calls
     crash("Board not found")
   Initializes a level for play.  This includes automatically scaling certain
   sprites, creating effects in sectors based on special texture or sprite
   placement, setting up monsters' attributes, etc.
   Called by startnewgame (WHMENU.C) (and others?)

 void drawscreen(struct player * plr)
   Called from playloop (later in WHAVEN.C)
   Contains various calls to render the game scene, including calls to the
   BUILD engine components as well as other Witchaven modules such as those
   to draw HUD weapons.

 void setOptions(void)
   Appears to be related to configurable options including keyboard mapping.
   Called by main.

 void main(int argc, char *argv[])
   The program entry point, performs various setup functions.
   Proceeds as follows:
   - Call installcrerrhndlr
   - Call netcheckargs (from WHNET.C, processes command line arguments)
   - Does CD check
   - Loads STUFF.DAT if present
   - Saves old video mode, changes to text mode to display initialization info
   - Reads settings files - readControlConfigs (READCFG.C)
   - Call setOptions (earlier this file)
   - Set up mouse and joystick if appropriate
   - Start the engine
   - Start sound, if appropriate
   - Load graphics
   - Setup VR devices, if appropriate
   - Init player variables
   - Call setup3dscreen (earlier in this file)
   - Call initpaletteshifts (later in this file)
   - Call readpalettetable (later in this file)
   - Do some additional palette stuff.
   - Play the intro sequence unless there's some reason not to (smkinit and smkplayseq from WHSMK.C)
   - Call SND_MenuMusic
   - Call playloop (later in this file)

 void playloop(void)
   Called from main.
   The core loop of the game.  Checks whether or not the menu has been called
   up, and otherwise serves mainly to repeatedly call other important
   functions in the game, including:
   - menuscreen (WHMENU.C - Menu screens)
   - updatestatusbar (WHINP.C)
   - drawscreen (earlier in WHAVEN.C - Graphics)
   - processinput (WHINP.C - Controls)
   - If in multiplayer, netgetmove and netsendmove
   - processobjs (WHOBJ.C - Player collision with sprites)
   - animateobjs (WHANI.C - Behavior of sprite entities)
   - animatetags (WHTAG.C)
   - doanimations (earlier in WHAVEN.C)
   - dodelayitems
   Loops if the exit variable hasn't been set via the menuscreen function (See WHMENU.C).

 void drawoverheadmap(struct player * plr)
   Called from drawscreen (earlier in this file)
   Displays the automap.

 void readpalettetable(void)
   Reads LOOKUP.DAT.  Calls makepallookup based on the file contents.

 int adjusthp(int hp)
   Called by setupboard (WHAVEN.C) and a few other locations.
   This is used to set up HP values for monsters.
   Takes the value given in the variable hp, increases or decreases it by a
   random amount (From about 0 to 20 percent of the hp variable), multiplies
   it by the difficulty level and returns.

 void initkeys(void)
   Presumably to set up keyboard input.

 void uninitkeys(void)
   Presumably to clean up keyboard handling afterwards.

 void __interrupt __far keyhandler(void)
   Presumably for accepting keyboard input.

 void permanentwritesprite(long thex, long they, short tilenum,
                           signed char shade, long cx1, long cy1,
                           long cx2, long cy2, char dapalnum)
   A wrapper for the BUILD function rotatesprite, with an adjustment for
   SVGA mode which sets the "all pages" bit.

 void overwritesprite(long thex, long they, short tilenum, signed char shade,
                      char stat, char dapalnum)
   Another wrapper for rotatesprite.  Removed from EGwhaven in favor of
   calling rotatesprite directly.

 void searchmap(short startsector)
   Unsure, possibly automapping related

END WHAVEN.C
=============================================================================


=============================================================================
READCFG.C
Overarching purpose:
Load configuration files.
Note:
The functions in this file rely on hmiINI* functions defined in PROFILE.H
 and compiled into NETNOWR.LIB.
=============================================================================

 BOOL readHMICFGFile(PSTR szName,PSTR szDIGIName,PSTR szMIDIName)
   Appears to read the sound card settings.
   Called by readControlConfigs (later this file)

 void readKeyboardConfig(_INI_INSTANCE *sInstance)
   Presumably reads the keyboard controls out of the config file.

 void writeKeyboardConfig(_INI_INSTANCE *sInstance)
   Presumably writes keyboard settings into the config file.

 void readMouseConfig(_INI_INSTANCE *sInstance)
   Presumably reads mouse settings from config.

 void writeMouseConfig(_INI_INSTANCE *sInstance)
   Presumably writes mouse settings to config.
   
 void readJoystickConfig(_INI_INSTANCE *sInstance)
   Presumably reads joystick settings from config.
   
 void writeJoystickConfig(_INI_INSTANCE *sInstance)
   Presumably writes joystick settings to config.
   
 void readAvengerConfig(_INI_INSTANCE *sInstance)
 
 void writeAvengerConfig(_INI_INSTANCE *sInstance)
 
 void readGamepadConfig(_INI_INSTANCE *sInstance)
 
 void writeGamepadConfig(_INI_INSTANCE *sInstance)
 
 void readWingmanConfig(_INI_INSTANCE *sInstance)
 
 void writeWingmanConfig(_INI_INSTANCE *sInstance)
 
 void readVFX1Config(_INI_INSTANCE *sInstance)
 
 void writeVFX1Config(_INI_INSTANCE *sInstance)
 
 void readVideoMode(_INI_INSTANCE *sInstance)
 
 void writeVideoMode(_INI_INSTANCE *sInstance)
   
 void readControlConfigs(int readhmi)
   Call individual config-reading modules.
   Called by main.
   
 void writeControlConfigs(void)

 end READCONFIG.C
=============================================================================


=============================================================================
WHPLR.C
=============================================================================
Overarching purpose:
Functions that are tied to the player, including death, attacks, and status
 bar display, hp, armor and score gain, leveling up.
=============================================================================
 void playerdead(struct player * plr)
   Handling of player death.  If player hasn't had their heart ripped out by
   a spike, and has a health potion, handles automatic drinking to restore
   health and returns instead of actually making the player dead.
   For dead players, cleans up powerups, motion, etc.

 void spikeheart(struct player * plr)
   Animate spike tearing the player's heart out.
   
 void updateloadedplayer(int i)
   Presumably sets up the player after loading a saved game.
 
 void initplayersprite(void)
   Initializes the player's position, powerups, etc.
   
 void autoweaponchange(int dagun)
   Weapon switching (presumably for automatic cases)
   
 void weaponchange(void)
   Weapon switching (for non-automatic cases)
   
 void potiontext(void)
   Display name of currently selected potion.
   
 void swingdacrunch(int daweapon)
   Makes sounds for hitting monsters in melee.
   
 void swingdasound(int daweapon)
   Makes sounds for attacking with weapons.
   
 void lockon(struct player *plr,short numshots,short shootguntype)
   Handle autoaiming on enemies.
   
 void swingdaweapon(struct player * plr)
   Initiate weapon attacks, calls shootgun (later in this file)

 void plrfireweapon(struct player * plr)
   Weapon code, handles weapon degradation and destruction, randomizes
   swing animations.
   
 void activatedaorb(struct player * plr)
   Part of the spell casting code.  Checks and decrements "orb" (scroll) ammo
   and in the cases of freeze, magic arrow, open doors, fireball and nuke
   sets plr->orbactive[currentorb] = -1.  Also adjusts currweaponfired and
   currweapontics (spellcast animation, presumably)
   
 void plruse(struct player * plr)
   Handles activation of things via the player's "use" key (doors, chains,
   etc.) (EGwhaven fixes/enhancements to triggering sprite activation)
   
 void loadnewlevel(int mapon)
   Makes file name level*.map where * is filled in by the mapon variable,
   calls setupboard (WHAVEN.C) with the resulting file name, calls
   initplayersprite and updatepics.
   
 void victory(int demoflag)
   demoflag is 1 to enable demo version handling, 0 for full version victory
   If demoflag = 0, calls smkplayseq (WHSMK.C) three times to play the outro
   cutscenes, then calls shutdown.
   If demoflag = 1, displays image THEORDER or STTHEORDER (depending on
   resolution) and calls shutdown.  Possibly a relic of the demo version?
   EGwhaven removes demoflag and its associated code.

 void drawweapons(struct player * plr)
   Handling for HUD weapon & shield drawing, animation and enchanted sound
   loops, as well as helmettime weapon speedup and dual wielding.
   Also appears to animate spell switching on the statbar.
   
 void castaorb(struct player * plr)
   Handles spellcasting (sounds and actual function of spell)
   Magic arrow and fireball call lockon()
   Freeze calls shootgun(plr, daang, 6);
   Open Doors calls shootgun(plr, daang, 7);
   Nuke calls shootgun(plr, daang, 4);
   
 void chunksofmeat(struct player * plr, short hitsprite, long hitx, long hity, long hitz, short hitsect, short daang)
   If goreon variable is nonzero and the hit enemy is not a shade, spawns
   gore splatters.
   
 void swingdapunch(int daweapon)
   Makes sounds if the player hits a wall with certain weapons, also handles
   the "hurt yourself if you punch a wall with your fist" stuff.
   
 void shootgun(struct player * plr, short daang, char guntype)
   Handles attacks and some other functions that work somewhat like attacks.
   This is a huge function with several cases depending on what guntype
   value it is passed.
   guntype 0 = melee weapon
     A case with extensive code owing to its prevalance in this game.
     If hitting a wall, calls swingdapunch (earlier in this file), and also
	 explosion() if the weapon is an enchanted morning star.
     If hitting a hittable sprite, handles damage randomization, strength,
	 helmet, and level damage boosts, calls swingdacrunch, chunksofmeat,
	 icecubes, and possibly other functions depending on what was hit and
	 with what.
   guntype 1 = bow
     Handling for firing the bow.
   guntype 2 = magic arrow
   guntype 3 = shoot firebals
   guntype 4 = nuke spell
   guntype 5 = EGwhaven fireball spell, not in vanilla, only sets flag and
               falls through to guntype 3.
   guntype 6 = freeze spell ("medusa")
     Walks through sprites using variable i for iterations, checking if
	 they are a freezeable enemy.  If so, calls
	 checkmedusadist(i, plr->x, plr->y, plr->z, plr->lvl) and if it returns
	 true, calls medusa(i) (which freezes the monster).
   guntype 7 = open doors ("knockspell")
     Calls hitscan to check if the player is in front of a door, operates it
	 if so.
   guntype 10 = throw pike axes
     Calls insertsprite to create the thrown axe(s).  Checks and handling for
	 the enchanted pike axe.

 void singleshot(short bstatus)
   Appears to unset the fire button status and the hasshot variable.
   Called from WHINP.C processinput.
   
 void potionpic(int currentpotion)
   Draws potion display on the status bar.
   
 void usapotion(struct player * plr)
   Handles drinking of potions.
   
 void orbpic(int currentorb)
   Status bar display for spells ("orbs").
   
 void healthpic(int hp)
   Increases player's health by the hp variable (with adjustment for
   difficulty), displays on status bar.
   
 void armorpic(int arm)
   Increases player's armor by the arm variable and displays on status bar.
   
 void levelpic(void)
   Displays arrow count, pike count, or XP level in the left side slot of
   the status bar.
   
 void score(int score)
   Increases player's score and expgained by the value of score, updates
   status bar and calls goasupalevel(plr) (later in this file).
   
 void goesupalevel(struct player * plr)
   Checks player's XP level and XP points, raises level when appropriate,
   displaying the level up message and calling levelpic (earlier in this
   file.)
   
 int checkweapondist(short i, long x, long y, long z, char guntype)
   Handles reach of melee attacks, returning 1 if an enemy is in reach, 0
   otherwise.
   
 void updatepics(void)
   Calls all status bar updating functions (score, levelpic, healthpic,
   armorpic, orbpic, keyspic; and depending on game mode captureflagpic,
   fragspic, or potionpic).  Functions that could alter the player's stats
   are called with a 0 parameter (i.e. no change).
   
 void captureflagpic(void)
   Display flag score on status bar for capture-the-flag netgames.
   
 void fragspic(void)
   Display frag score on status bar for deathmatch netgames.
   
 void keyspic(void)
   Display keys collected on status bar.
   
 int adjustscore(int score)
   Tweaks score plus or minus a random amount up to approximately 20%, and
   returns the tweaked value.  A seemingly unused function.
   
 int lvlspellcheck(struct player * plr)
   Check if the player is high enough level to cast the currently selected
   spell, return 1 if yes or 0 otherwise.  In Witchaven II, always returns
   1. (This function is to be retained in EGwhaven for future modding
   options).
   
 void gronmissile(int s)
   Seemingly unused but would seemingly shoot a PLASMA at target s.
   
 void displayspelltext(void)
   Show the name of the selected spell.
   
 void painsound(long xplc, long yplc)
   Play a randomized player pain spell.

 int inView(struct player *plr,int i)
   Seemingly unused, an alternative to BUILD's cansee?

END WHPLR.C
=============================================================================


=============================================================================
WHOBJ.C
=============================================================================
Overarching purpose:
Handle behavior of special sprites (treasures, monsters, projectiles, etc.)
 Allow player to touch treasures/traps, keep track of powerups and poison
 status, make sure monsters display the proper viewing angle, and handle
 monster movement, attack and death behaviors.
 As a rule of thumb, it could be said that code for an actor *deciding* what
 to do is in WHANI.C, while the code for actually *doing* it is here.  The
 two files are closely related.
=============================================================================

 void monitor(void)
   Handle powerup timers, poison timer and damage, and powerup display.

 void processobjs(struct player * plr)
   Handle the player touching special objects. This usually means treasure,
   but the instant kill spikes are also handled here. The meat of this
   function is a large switch block based on spr->picnum.  Of special note:
   case GIFTBOX is the code which handles random treasure chest contents.

 int potionspace(int vial)
   Check if the player is at max of the potion type indicated by vial.
   Return 0 if maxed out, 1 if not.

 void updatepotion(int vial)
   Add one potion of type indicated by vial to the player's inventory.

 void transformactors(struct player * plr)
   Handle rotation of sprites that have multiple viewing angles
   (Monsters for instance).

 void newstatus(short sn, int seq)
   Handle switching an actor to a different status/action.  Plays sounds in
   some cases, increases kill count for monster DIE states and XP score for
   monster DEAD/RESURRECT states.  Sometimes the code for an actor is only
   handled if netgame is not set.

 void firebreath(short i, int a, int b, int c)
   A seemingly unused function to shoot fireballs.  Possibly a leftover from
   the WH1 dragon.

 void castspell(short i)
   Shoot fireballs.

 void skullycastspell(short i)
   Shoot PLASMA (magic bolt that can't be fire resisted).

 int checkheat(short i)
   Unsure, appears never to be called.

 int checkfacing(short i, long x, long y)
   Appears to check if the sprite indicated by i is looking towards
   point x,y.

 int checkmedusadist(short i, long x, long y, long z, int lvl)
   Appears to check if a target is within a range that becomes greater with
   a higher lvl value.

 int checkdist(short i, long x, long y, long z)
   Appears to be for checking if a monster is close enough to attack the
   player.

 int checksight(short i, short *daang)
   Appears to be for checking if a monster can see the player.

 void checkmove(short i, short *movestat)
   Appears to attempt moving a monster and changing its angle if it hits the
   wall.

 void shieldhit(int hp)
   Subtracts hp from the player's shield points and displays a message if the
   shield is destroyed.

 void attack(short i)
   Handles monsters attacking the player in melee.  Armor, shield, and the
   Adamantine Ring are all considered in this function.  Sounds are played,
   base damage is chosen based on monster type, and poison may be inflicted.

 void fireballblast(short i)
   Shoot a FATSPANK (Grey Witch flesh blob). Possibly an unused leftover
   from WH1.

 void makeafire(short i, int firetype)
   Creates a sprite with pic FIRE (nuke spell effect?)

 void explosion(short i, long x, long y, long z, short owner)
   Presumably explodes things (like chests?)

 void explosion2(short i, long x, long y, long z, short owner)
   Presumably explodes things (like chests?)

 void trailingsmoke(short i, short ball)
   Make smoke puffs (for fireball trails?)

 void icecubes(short i, long x, long y, long z, short owner)
   Spawn a chunk of ice (for frozen monsters getting smashed, called
   repeatedly to spawn many).

 int damageactor(short hitobject, short i)
   Handles projectiles hitting things they can hurt.

 void nukespell(short j)
   Nuke the enemy indicated by j.  Don't nuke shades.

 void medusa(short j)
   Freeze the enemy indicated by j.

 int movesprite(short spritenum, long dx, long dy, long dz, long ceildist, long flordist, char cliptype)
   Handle movement of sprites.
   Calls clipmove (BUILD).

 int actormovesprite(short spritenum)
   Dead function, superceded by movesprite.  Removed from EGwhaven.

 void guardianfire(short i, int k, struct player * plr)
   Shoot PLASMA.  (Possibly unused??)

 void gonzopike(short s)
   Throw a pike axe, for monsters (Argothonian's ranged attack.)

 void newguyarrow(short s)
   Shoot an arrow, for monsters (Ciraean archer)

 void trowajavlin(int s)
   Shoot projectiles (wall traps)

 void throwhalberd(int s)
   Throw a halberd (Midians)

 void spawnhornskull(short i)
   Drop the Horned Skull.

 void monsterweapon(short i)
   Spawn dropped items (not necessarily weapons) from monsters.

 void madenoise(int val, long x, long y, long z)
   Presumably related to waking up monsters by sound.

 void monsternoise(short i)
   Makes ogres growl, does nothing for other monsters.

 void randompotion(short i)
   Spawn a random potion.

 void spawnabaddy(short i, short monster)
   Appears to be for Cirae-Argoth to summon Midians.

 void spawnapentagram(short sn)
   Spawns a pentagram.

 int isvalidactor(short i)
   Returns 1 if the sprite indicated by i has a picnum matching SKELETON,
   KOBOLD, IMP, GRONHAL, GRONMU or GRONSW.  Otherwise returns 0.

 int actoruse(short i)
   Presumably for performing the player's "use" action on sprites?

 void deaddude(short sn)
   Need to check, possibly shade related.

 int isActor(int spritenum)
   Return 1 if the sprite indicated by spritenum has a picnum matching a
   monster type, otherwise returns 0.

END WHOBJ.C
=============================================================================


=============================================================================
WHANI.C
=============================================================================
Overarching purpose:
Handling the states of sprites and transitioning between them.  Enemy AI.
=============================================================================

 void animateobjs(struct player * plr)
   Called by playloop (WHAVEN.C)
   Handles various states for sprite actors: this ranges from simple
   animation for things like pull chains to more elaborate actions, notably
   enemy AI.  The meat of this function is a HUGE switch/case block.
   Possible states include:
    CHILL - Hanging skeleton animates before going to state FACE
    SHARDOFGLASS - Appears to make sprite fall based on its extra variable.
    LAND - Appears to be for jumping GONZO (Giryon), sends him to FACE
    AMBUSH - For jumping, transitions to LAND state
    SPARKSUP
    SPARKSDN
    SPARKS
    STONETOFLESH - A statue comes to life, transitions to FACE
    SHADE - Preparation to spawn a shade (Giryon ghost)
    EVILSPIRIT - Spawn a shade (Giryon ghost) and put it in FACE state
    PATROL - Seems to be patrol point related, can branch to CHASE or FINDME
    PULLTHECHAIN - Animate a pulled chain (chain-triggered activation is
                   handled elsewhere)
    ANIMLEVERDN - Possibly unused?
    ANIMLEVERUP - Ditto
    WARPFX - Teleport visual effect
    NUKED - Blown up with a nuke spell, spawns fire effect and splatters
            gore, then goes to DIE state
    FROZEN - Hit with freeze spell.  lotag is used as a counter for thawing
             out again.
    PAIN - Enemy recovers from pain flinch, branches to FLEE.  Also handles
           being burnt by an explosion (and going to DIE if appropriate)
    FLOCKSPAWN - Spawn bats randomly.
    FLOCK - Handle spawned bats.
    SKIRMISH
    FINDME
    TORCHFRONT
    TORCHLIGHT
    GLOWLIGHT
    BOB - Appears to move a sprite vertically upwards
    RESURRECT - Monster waits a bit, then comes back to life
    LIFTUP - Sprite lift moves up
    LIFTDN - Sprite lift moves down
    WITCHSIT
    FACE - Enemy aware of the player.  Can see player?  Then change to FLEE
           if a rat or if player has scare spell, CHASE otherwise.  Can't see?
           Then change to FINDME. Close to player? FLEE again if rat,
           otherwise ATTACK.
    MASPLASH
    ATTACK2
    ATTACK - Enemy hits in melee.  Calls startsong (WHSNDMOD.C) to set the
             music to a battle track if it's not already playing one.
    SHATTER
    FIRE
    FALL
    SHOVE
    PUSH
    FLEE - Run from the player
    CHASE - Enemy AI
    DRAIN
    CAST - Enemy ranged attack (not limited to spells per se)
    DIE - Enemy dies. State changes to RESURRECT if skill 4, DEAD otherwise.
    STAND - Wait for player
    ACTIVE
    DORMANT
    MISSILE - A projectile in motion.
    JAVLIN - A projectile in motion.  Difference as far as I know is that a
              JAVLIN can stick in the wall when it hits.
    FIRECHUNK
    CHUNKOWALL
    CHUNKOMEAT
    BLOOD
    DEVILFIRE - Shoot fireballs.
    DRIP
    SMOKE
    EXPLO
    BROKENVASE - Destroyable scenery breaks, not just vases but stained
                  glass as well.
    FX

 int findapatrolpoint(short i)
   Meant to work with patrol points, a feature that seems to be bugged or
   incomplete.

 void checkhit(short i, short j)
   Calls hitscan (a BUILD function) to check something.
   i and j are indices to sprites. From what I can gather, it casts a ray
   from sprite j along its facing angle, then adjusts sprite i's angle
   based on that.
   Need to check what calls this to understand more.

END WHANI.C
=============================================================================


=============================================================================
WHSMK.C
=============================================================================
Overarching purpose:
Connect with SMACK.LIB to play Smacker videos, handle intro, outro, and
  intermission between levels, including end-of-level score calculations.
  Also contains level titles that are displayed on the intermission screen.
=============================================================================
 RCFUNC void PTR4 *RADLINK radmalloc(u32 numbytes)
   Presumably for video memory allocation.

 RCFUNC void RADLINK radfree(void PTR4 * ptr)
   Presumably to free what was allocated by radmalloc.

 void smkinit(unsigned int digifh)
   Called by main (WHAVEN.C)
   Looks like it initializes sound and time for SMK playback.

 void texttobuf(char *buffer,short x,short y,short fontstart,char *text,short pal)
   Called from smkplayseq (WHSMK.C), to display intermission text.
   Used to graphically display text using a font from the .ART tiles.  A comment
   in the code notes that it assumes a 320x200 display.

 void smkplayseq(int s)
   Called by main (WHAVEN.C)
   Plays an SMK file.  Depending on the number passed to it, plays:
   0 - intro.smk
   1 - ending1.smk
   2 - stairs.smk  (intermission)
   3 - ending2.smk
   4 - ending3.smk
   If passed a value of 2 for s, also handles the calculation of end of level
   stats and granting bonus XP for good performance.

END WHSMK.C
=============================================================================


=============================================================================
WHTAG.C
Overarching purpose:
Activation of tagged effects on sectors and sprites. Traps, doors, moving
 floors, and the like.
=============================================================================

 void operatesprite(int s)
   Causes certain sprites to go into a special state: activatable traps,
   statues that come to life, jumping enemies, breaking glass.
   Also responsible for the sprite elevator seen in level 1 of Witchaven I.

 void operatesector(int s)
   Handles various forms of moving sector: doors, including locked ones,
   split doors, moving floors, moving ceilings.

 void animatetags(struct player * plr)
   Called from playloop (WHAVEN.C)
   Appears to have code related to swinging doors.

END WHTAG.C
=============================================================================


=============================================================================
WHFX.C
=============================================================================
Overarching purpose:
Miscellaneous "special effects", including some special sectors and some
 purely cosmetic features.
=============================================================================

 void panningfx(void)
   Called from dofx (WHFX.C)
   Appears to be responsible for animating scrolling walls and floors.

 void revolvefx(void)
   Responsible for revolving sectors?

 void bobbingsector(void)
   Called from dofx (WHFX.C)
   Makes a sector's floor bob up and down (buggy)

 void teleporter(void)
   Called from dofx (WHFX.C)
   Handles both intra-level teleportation and also level exits. For exits,
   checks for pentagram, and removes keys etc. from the player when exiting.
   Also displays a message if the exit is tried without having the pentagram.

 void warp(long *x, long *y, long *z, short *daang, short *dasector)
   Performs actions on a sector whose effects I am not certain of.

 void warpsprite(short spritenum)
   Performs actions on a sprite whose effects I am not certain of.

 void ironbars(void)
   Called from dofx (WHFX.C)
   Appears to be for sprite doors.

 void sectorsounds(void)
   Appears to be related to ambient sound.

 void scary(void)
   Called from dofx (WHFX.C)
   Handles the random timing, graphics and sound for the blue jumpscare skull.

 void dofx(void)
   Called from drawscreen (WHAVEN.C)
   Calls several other WHFX.C functions.

 void weaponpowerup(void)
   Called from dofx (WHFX.C)
   Handles the player visiting a weapon enchantment sector, giving the
   enchanted weapons, and if the shrine is used up, removing the graphical
   effects.

 void thunder(void)
   Called from dofx (WHFX.C)
   Thunder and lightning for areas with certain sky textures.

 void thesplash(void)
   Called from dofx (WHFX.C)
   Checks if the player is on a liquid floor, and calls makeasplash if so.

 void makeasplash(int picnum, struct player * plr)
   Called from thesplash (WHFX.C)
   Creates splash sprites and sounds for players.

 void makemonstersplash(int picnum, int i)
   Like makeasplash, but for monsters.

 void bats(short k)
   Called from animateobjs FLOCKSPAWN state (WHANI.C)
   Creates a bat sprite.

 void warpfxsprite(int s)
   Appears to be for displaying a teleport flash sprite.

 void makesparks(short i, int type)
   Called from setupboard (WHAVEN.C)
   Create glitter sprites for weapon enchant zones.

 void shards(short i, short type)
   Appears to be for creating a breaking glass effect, not sure if used?

END WHFX.C
=============================================================================


=============================================================================
WHINP.C
=============================================================================
Overarching purpose:
Receive player's input and handle motion.
=============================================================================

 void initjstick(void)
   Presumably initializes the joystick.

 void keytimerstuff(void)
   Keyboard input and player movement: Strafing, turning, moving back and forth

 void dophysics(struct player * plr, long goalz, short flyupdn, int v)
   Called from processinput (WHINP.C)
   Player movement: flight, jumping, falling.

 void processinput(struct player * plr)
   Input: joystick, mouse, some keyboard (not that handled in keytimerstuff),
   game timer, lower view when wading, stomping on sprites (kills rats, makes
   creaky noises on bridges, etc.)

 void autothehoriz(struct player * plr)
   Probably centering player's view.

 void nettypeletter(void)
   Probably for communicating in net games.

 void typeletter(void)
   Perhaps for entering savegame names?

 void checkcheat(void)
   Looks at what's been typed in the cheat console, and does cheats if it's
   a valid code.

 void typecheat(char ch)
   Presumably to take cheat input.

 void dosoundthing(void)
   Appears to be for handling the sound volume options.

 void updatestatusbar(void)
   Draws status bar background, calls updatepics

 void debugchain(void)
   Presumably debug related.

END WHINP.C
=============================================================================


=============================================================================
WHMENU.C
=============================================================================
Overarching purpose:
Menu screens, initiate/save/load games, palette functions.
=============================================================================

 void loadsavetoscreen(void)
   Appears to be for displaying load/save option on screen.
   Called by loadsave.

 void menutoscreen(void)
   Display main menu background.
   Called by menuscreen.

 void menutoscreenblank(void)
   Possibly for clearing menu display?

 void itemtoscreen(long x, long y, short dapic, signed char dashade, char dapal)
   Put a graphic on the screen using permanentwritesprite.
   Called from fancyfont (and others?)

 void fancyfont(long x, long y, short tilenum, char *string, char pal)
   For displaying a string on screen using the "fancy font".
   Calls itemtoscreen.

 void fancyfontscreen(long x, long y, short tilenum, char *string)
   Like fancyfont, not sure of difference in purpose.
   Calls overwritesprite.

 int menuscreen(struct player * plr)
   Central handler for the main menu screen, calls menu display functions,
   gets input and calls the submenu functions.

 void help(void)
   Display help screens and receive input.
   Called by menuscreen.

 void loadsave(struct player * plr)
   Load & save menu.
   Called by menuscreen.

 void quit(void)
   Checks if player really wants to quit, calls shutdown (WHAVEN.C) if so.
   Called by menuscreen.

 void thedifficulty(void)
   Handles gore & difficulty settings submenu.

 void startnewgame(struct player * plr)
   Starts a new game or loads a saved game; loads map (calls setupboard)
   Also calls initplayersprite, cleanup, dolevelmusic, etc.

 void loadgame(struct player * plr)
   Handles game loading submenu.

 void savegame(struct player * plr)
   Handles game saving submenu.

 void savegametext(int select)
   Presumably to handle displaying saved game names.

 int savedgamename(int gn)
   Output a saved game.

 int savedgamedat(int gn)
   Not sure, perhaps verify that the file is a saved game?

 void loadplayerstuff(void)
   Load from a saved game.

 void optionspage(void)
   Handle options menu.

 void thesound(void)
   Handle sound setting/jukebox screen (including dancing Cirae-Argoth)

 void thecontrols(void)
   Handle control preference menu.

 int __far cehndlr(unsigned deverr, unsigned errcode, unsigned far * devhdr)
   Presumably an error handler.

 void installcrerrhndlr(void)
   Presumably sets up the error handler.

 void screenfx(struct player * plr)
   Calls updatepaletteshifts.

 void clearpal(void)
   Appears to set the palette to entirely black.

 void getpalette(char *palette)
   Appears to be for reading palette data.

 void fillpalette(int red, int green, int blue)
   Appears to fill the entire palette with a single color defined by the
   function's parameters.
   
 void fadeout(int start, int end, int red, int green, int blue, int steps)
   Appears to fade the palette to a specified color in the specified
   number of steps.

 void fadein(int start, int end, int steps)
   Appears to return the palette to its normal colors in the specified
   number of steps.

 void fog1(void)
   Unsure, calls fadeout or fadein.

 void fog2(void)
   Unsure, palette related.

 void makefxlookups(void)
   Unsure, palette related.

 void initpaletteshifts(void)
   Creates various palette effects.

 void startgreenflash(int greentime)
   Presumably flashes the palette green.

 void startblueflash(int bluetime)
   Presumably flashes the palette blue.

 void startredflash(int damage)
   Presumably flashes the palette red (damage flash?)

 void startwhiteflash(int bonus)
   Presumably flashes the palette white (bonus flash?)

 void updatepaletteshifts(void)
   Presumbably handles fading the palette from a flash back to normal.

 void finishpaletteshifts(void)
   Presumably sets palette back to normal after a flash.

 void TEMPSND(void)
   Call SND_Sound with a random value.

 void cleanup(void)
   Resets various player attributes (powerups, selected weapon, potion and spell).

END WHMENU.C
=============================================================================


=============================================================================
WHNET.C
=============================================================================
Overarching purpose:
Netgames, command line parameters.
=============================================================================

 void interrupt far newGPhandler(union INTPACK r)

 void interrupt far newPGhandler(union INTPACK r)

 void far * dpmi_getexception(int no)

 void dpmi_setexception(int no, void far * func)

 void installGPhandler(void)

 void debugout(char *fmt,...)

 void netcheckargs(int argc, char *argv[])
   Parse command line parameters.
   Called from main (WHAVEN.C)

 int netattacking(short p)

 void netsendpck(struct netpck * p, WORD dnode)

 short netchecktouchflag(struct player * plr)
   Appears to be related to grabbing the flag in CTF multiplayer.

 void netmarkflag(short i)

 void moveflag(long x, long y, long z, long teamno)

 void sendmyinfo(WORD dnode, short forcesend)

 void netjoingame(void)
   Appears to handle joining a netgame.

 void netsendmove(void)

 void netshootgun(short s, char guntype)

 void netdamageactor(short s, short o)

 void nethitsprite(short p, char guntype, char taghit)

 void spawnflag(long x, long y, long z, long teamno)

 void dropflagstart(short teamno)

 void netdropflag(void)

 void wongamescreen(short p)
   Appears to display the "Victory for the knights in ***" screens.

 char * IPXadrstr(_IPX_INTERNET_ADDR * p)

 void netgetmove(void)

 void netpickmonster(void)

 void initmulti(int numplayers)

 void dropDTR(void)

 void netshutdown(void)

 void whnetmon(void)

 void netrestartplayer(struct player * plr)

 void netkillme(void)

 void netreviveme(void)

End WHNET.C
=============================================================================


=============================================================================
WHSNDMOD.C
=============================================================================
Overarching purpose:
Sound and music.
=============================================================================

 BOOL loadlevelsongs(int which)

 VOID _far sosMIDISongCallback(WORD hSong)

 BOOL startsong(WORD which)
   Play one of four tracks (indicated by which)
   Called from sosMIDISongCallback to set regular music (which is randomly 0 or 1).
   Called from dolevelmusic to set regular music (which is always 0)
   Called from animateobjs (WHANI.C) ATTACK state, to set battle music (which is randomly 2 or 3).
   Called from playerdead (WHPLR.C) to set regular music (which is randomly 0 or 1).

 void dolevelmusic(int which)
   Play a track, if music is enabled.
   Calls startsong, always with a parameter of 0.
   Called from startnewgame (WHMENU.C) if (musicoverride == -1).
   Called from thesound (WHMENU.C) with varying values (jukebox screen)

 VOID SND_MenuMusic(void)
   Call dolevelmusic with NUMLEVELS - 1 as the value.

 VOID SND_InitSOSTimer(VOID)

 VOID _far _loadds timerevent(VOID)

 VOID _far cdecl sosDIGISampleCallback(WORD wDriverHandle, WORD wCallSource, WORD hSample)

 VOID SND_SetupTables(VOID)
   Load JOESND and F_SONGS or W_SONGS.

 void SND_LoadMidiIns(void)
   Apparently to set up instrument settings for music.

 VOID SND_DoBuffers(void)

 VOID SND_UnDoBuffers(void)

 VOID SND_Startup(VOID)
   "Initialize all SOS Drivers and start timer service."

 VOID SND_Shutdown(VOID)
   "Un-Initialize all SOS Drivers and releases timer service(s)."

 void SND_StopMusic(void)

 VOID SND_Mixer(WORD wSource, WORD wVolume)
   Sound and music volume adjustment.

 int SND_PlaySound(WORD sound, long x, long y, WORD Pan, WORD loopcount)
   Play a sound effect, taking into account position in the world for volume
   attenuation.  If passed 0, 0 for x, y then it is treated as a global
   sound (max volume).  Also handles sound priority.

 WORD SND_Sound(WORD sound)
   If sound is on, pass "sound" to SND_PlaySound as a global non-looping
   sound.

 VOID SND_CheckLoops(void)
   Appears to halt all looping sounds.

 VOID SND_StopLoop(WORD which)
   Halt a looping sound.

 VOID SND_DIGIFlush(void)

 VOID SND_UpdateSoundLoc(WORD which, WORD Volume, WORD Pan)
   Appears to be unused, change position of a positioned sound?

 void playsound_loc(int soundnum, long xplc, long yplc)
   Play a sound at a specified location (Why this and not direct to
   SND_PlaySound? Seems to have unused variables? Wrapper function?)

 void updatesound_loc(void)
   Appears to be unused, change positions of a positioned sounds?

End WHSNDMOD.C
=============================================================================


=============================================================================
WHCTM.C
=============================================================================
Overarching purpose:
CyberMAXX support.
=============================================================================

 void ctm_deinit(void)

 int ctm_init(int port)

 void vio_deinit(void)

 void vio_reset(void)

 void vio_setup(void)

 int vio_init(int port)

 void vio_read(short *yaw,short *pitch,short *roll)

End WHCTM.C
=============================================================================


=============================================================================
WHMSC.C
=============================================================================
Overarching purpose:
Low-level functions to call DOS interrupts, text mode screen, exception
 handlers, networking(?)
=============================================================================

 void faketimerhandler(void)
   Unlike the WHAVEN.C one, has actual code in it (is the WHAVEN.C one a
   prototype?)  However it is only compiled if MULTIPLAYER is #defined.

 void setvmode(int m)
   Calls video mode interrupt (0x10 AH=0x00) to set mode indicated by m.
   Called by main (WHAVEN.C) with m = 0x03 (80x25 text mode)
   Called by shutdown (WHAVEN.C) with m = variable "oldvmode" (video cleanup)
 
 void setatr(int fore, int back)
   Unsure -- fore and back colors for textmode??

 void setcsize(int t, int b)
   Calls video interrupt for setting cursor shape (0x10 AH=0x01)
   CH = t and CL = b

 void gotoxy(int x, int y)
   Calls video interrupt for setting cursor position (0x10 AH=0x02)
   DH = y and DL = x

 void getcurs(void)
   Calls video interrupt for checking cursor position & size (0x10 AH=0x03)
   Retrieves cursor position to the variables cursx and cursy.

 void setregion(int x1, int y1, int x2, int y2)
   Transfers the parameter variables to other variables (why do it
   this way?)

 void scrollup(void)
   Calls video interrupt to scroll window up (0x10 AH=0x06)

 void scrolldn(void)
   Calls video interrupt to scroll window down (0x10 AH=0x07)

 void clrregion(int fore, int back)
   Calls setatr(fore, back) (Earlier in this file) and then
   behaves similarly to scrollup, but with AL set to 0x00 (clear
   whole window)

 void far * dpmi_getexception(int no)
   Calls DPMI interrupt to get processor exception handler vector (0x31 AX=0x0202)
   Returns far pointer based on the INT's response.

 void dpmi_setexception(int no, void far * func)
   Calls DPMI interrupt to set processor exception handler vector (0x31 AX=0x0203)
   Sets it based on func (ECX:EDX) and no (EBX).

 int dpmi_callrealint(int no, struct rmreg * r)
   Only present if MULTIPLAYER is #defined.
   Calls DPMI interrupt to "simulate real mode interrupt" (0x31 AX=0x0300)

 int isipx(void)
   Only present if MULTIPLAYER is #defined.
   Appears to be for setting ipxflag based on some low level checks.

End WHMSC.C
=============================================================================

=============================================================================
WHASM.ASM
=============================================================================
Overarching purpose:
Assembly language functions for use when changing the palette.
 This uses the DAC I/O method.
 A reference that may help you to understand some of what's going on here:
 http://asm.inightmare.org/index.php?tutorial=2&location=11
=============================================================================
 
 asmwaitvrt_
   Called from fadeout             (WHMENU.C),
               fadein              (WHMENU.C),
			   updatepaletteshifts (WHMENU.C),
			   finishpaletteshifts (WHMENU.C)
   
 
 asmsetpalette_
   Called from fadeout             (WHMENU.C),
               fadein              (WHMENU.C),
			   updatepaletteshifts (WHMENU.C),
			   finishpaletteshifts (WHMENU.C)

END WHASM.ASM 
=============================================================================


=============================================================================
JSTICK.ASM
=============================================================================
Overarching purpose:
Low level joystick/gamepad handler.  Decently commented as to how it works.
=============================================================================

 jstick_
   Find out status of joystick position and buttons.
   Called from processinput (WHINP.C), both to get controller input and to
    calibrate.

END JSTICK.ASM
=============================================================================


=============================================================================
Definition files
=============================================================================
NAMES.H   - Associates names with the numbers of tiles in the .ART files that
            are meant to have special properties or otherwise be identified by
            name.
PROFILE.H - Header to HMI library, used in READCFG.C
SNDMOD.H  - In addition to definitions for the sound code, it also associates
            names with the sound effects contained in JOESND.
			
others?
=============================================================================
