/*  monstertable.c: (c) 2002 sibn

    This file is part of Gwiz.

    GWiz is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    GWiz is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with GWiz; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

#include <SDL/SDL.h>
#include <SDL/SDL_image.h>
#include <SDL/SDL_ttf.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <getopt.h>
#include <string.h>
#include <time.h>
#include <netinet/in.h>  /* important.  monsters are network-endian */
#include "gwiz.h"
#include "uiloop.h"
#include "prefsdat.h"
#include "text.h"
#include "maploader.h"
#include "menus.h"
#include "playerpawn.h"
#include "castle.h"
#include "playergen.h"
#include "monstertable.h"

extern GwizApp gwiz;

void LoadMonsterPawn (int monsterno, MonsterPawn *mon)
{
    FILE *stock;
    int i;
    char *freeme;
    char fname[8]; /* /monXYZ */
    
    /* set the filename by the monster number */
    /* note monster numbers >999 are not allowed */
    if (monsterno < 1000)
	snprintf (fname, sizeof(char)*7, "/mon%d", monsterno);
    else
	BailCall ("monstertable.c: asked to load invalid monster: ",
		  "monster number was greater than 999");
    
    freeme = MakePath(gwiz.udata.monsters, fname);
    
    if ((stock = fopen (freeme, "rb")) == NULL)
	BailCall ("monstertable.c: unable to open monster data: ",
		  freeme);
    Sfree (freeme);
    
    if ((i = FindNextOpenNPC()) != -1)
	fread (&gwiz.mpawn[i], sizeof(MonsterPawn), 1,
	       stock);
    else
	{
	    fprintf(stderr, "monster chart full; pawn desired not loaded");
	    fclose (stock);
	    return;
	}
    
    /* about done.  be sure to flip the bytes back to host-endian */
    gwiz.mpawn[i].minphys = ntohl(gwiz.mpawn[i].minphys);
    gwiz.mpawn[i].maxphys = ntohl(gwiz.mpawn[i].maxphys);
    gwiz.mpawn[i].mspells = ntohl(gwiz.mpawn[i].mspells);
    gwiz.mpawn[i].cspells = ntohl(gwiz.mpawn[i].cspells);
    gwiz.mpawn[i].hp      = ntohl(gwiz.mpawn[i].hp);
    gwiz.mpawn[i].epval   = ntohl(gwiz.mpawn[i].epval);
    gwiz.mpawn[i].gpval   = ntohl(gwiz.mpawn[i].gpval);
    gwiz.mpawn[i].susceptibility = ntohl(gwiz.mpawn[i].susceptibility);
    
    fclose (stock);
}

int FindNextOpenNPC (void)
{
    int i;
    for (i = 0; i < 64; i++)
	if (gwiz.mpawn[i].hp == 0)
	    return (i);
    return (-1);
}

