/*  maploader.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 <dlfcn.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "gwiz.h"
#include "prefsdat.h"
#include "text.h"
#include "uiloop.h"
#include "maploader.h"
#include "menus.h"
#include "castle.h"
#include "monstertable.h"

extern GwizApp gwiz;

void MapLoad (int floorno)
{
    char *freeme;
    FILE *map;
    int i = 0;
    
    /* FIXME: set up a switch (floorno) here to set freeme to the "correct"
       path and level */
    freeme = MakePath (PKGDATADIR, "/demo.map");
    if ((map = fopen (freeme, "rb")) == NULL)
	BailCall ("maploader.c: unable to load map from file: ",
		  freeme);
    
    /* destroy all monsters before creating new ones */
    InitMonsterPawns();
    
    fread (&gwiz.map, sizeof(GwizMap), 1, map);
    fclose (map);

    gwiz.z = floorno;
    
    /* FIXME: this should be saved with the map. */
    for (i = 3; i < 64; i++)
	gwiz.map.npc[i] = 0;
    
    gwiz.map.npc[0] = 1;
    gwiz.map.npc[1] = 2;
    gwiz.map.npc[2] = 3;
    gwiz.map.npc[3] = 4;
    
    LoadMapPawns();
    
    if (gwiz.map.version != 0)
	BailCall ("maploader.c: wrong map version: ",
		  freeme);
    Sfree (freeme);
}

void OnTileChanged (void)
{
    char *opts[] = { "Continue in Maze", "Enter Castle", NULL};
    if ((gwiz.x == 128) && (gwiz.y == 128))
	if (NewGwizMenu(gwiz.canvas, opts, -1, gwiz.canvas->w/3, 0) == 1)
	    {
		WipeCanvas();
		EnterCastle();
	    }
}

void InitMonsterPawns(void)
{
    /* This function should disappear when the demo map features saved
       monster lists. */
    int i = 0;
    for (i = 0; i < 64; i++)
	{
	    strncpy (gwiz.mpawn[i].name, "               ", 16);
	    gwiz.mpawn[i].minphys = 0;
	    gwiz.mpawn[i].maxphys = 0;
	    gwiz.mpawn[i].mspells = 0;
	    gwiz.mpawn[i].cspells = 0;
	    gwiz.mpawn[i].hp      = 0;
	    gwiz.mpawn[i].epval   = 0;
	    gwiz.mpawn[i].gpval   = 0;
	    gwiz.mpawn[i].susceptibility = 0;
	}
}

void LoadMapPawns (void)
{
    int i = 0;
    for (i = 0; i < 64; i++)
	if (gwiz.map.npc[i] != 0)
	    LoadMonsterPawn (gwiz.map.npc[i], &gwiz.mpawn[i]);
}


