#include <cstdlib>
#include <allegro.h>
#include "CDisplay.hpp"
#include "CMap.hpp"
#include "CPlayer.hpp"
#include "CNpc.hpp"
#include "Interaction.hpp"
#include "CMenu.hpp"
#include "CBattle.hpp"
#include "CCine.hpp"
#include "Quests.hpp"

// Globals 
CApp App;
CMap map;
BITMAP *text_box;
BITMAP *game_objects;

int key_space = 0;
int key_rctrl = 0;
int key_lctrl = 0;

void HandleEvents(int i)
{
   if( CHECK_BIT(map.event[i].flags, EVENT_SIGN) )
   {
    	Talk(map.event[i].name, map.event[i].text);
    	/*
    	// The sign can also spontanously produce items!
    	if(map.event[i].id != 0 && !map.event[i].seen)
    	{
           SET_BIT(map.tile[1][player[App.selected_pc].y/map.sizeh][player[App.selected_pc].x/map.sizew].flags, FLAG_EVENT);
           map.tile[1][player[App.selected_pc].y/map.sizeh][player[App.selected_pc].x/map.sizew].gfx = TILE_ITEM;
           event.x = player[App.selected_pc].x/map.sizew;
           event.y = player[App.selected_pc].y/map.sizeh;
           event.flags = EVENT_ITEM;
           event.id = map.event[i].id;
           map.event.push_back(event);
           map.max_event++;
           map.event[i].seen = true;
        }
        */
   }
   
   if(CHECK_BIT(map.event[i].flags, EVENT_SHOP_WEAPON) )
   {
        Talk(map.event[i].name, map.event[i].text);
        player[App.selected_pc].shop.Shop(map.event[i].id, player[App.selected_pc]); // the id holds the specific Shop ID (which in turn returns what the shop carries!)
   }

   if(CHECK_BIT(map.event[i].flags, EVENT_INN) )
   {
        if(menu.Choice(Talk(map.event[i].name, map.event[i].text, 1)) )
        {
          if(player[0].gold >= 5)
          {
                 Talk("", "After a good nights sleep, your wounds have been healed.");
                 player[0].gold-=5;
                 player[0].hp=player[0].max_hp;
                 player[1].hp=player[1].max_hp;
          }
          else
              Talk("", "You don't have enough money to stay here!");
        }

        else
        {
             Talk(map.event[i].name, "Piss off then!");
        }

   }
   
   if(CHECK_BIT(map.event[i].flags, EVENT_CLERIC) )
   {
        if(menu.ClericChoice(Talk(map.event[i].name, map.event[i].text, 1)) )
        {
           // Cancel -- do nothing
        }
        else
        {
           SaveGame();
           Talk("", "You successfully saved!");
        }
   }
   
   // The event.id holds the QUEST_*** to check if the goal is done
   if(CHECK_BIT(map.event[i].flags, EVENT_SWITCH) )
   {
      // TODO: Uh should we be storing this so the player doesn't have to restart when the map is reloaded???
      if(map.event[i].read == false)
      {
         map.event[i].read = true;
         Talk("", "You turn the switch off.");
         map.tile[0][map.event[i].y][map.event[i].x].gfx++;
         quest.ProcessQuest(map.event[i].id);

      }

      else if(map.event[i].read == true)
      {
         map.event[i].read = false;
         Talk("", "You turn the switch on.");
         map.tile[0][map.event[i].y][map.event[i].x].gfx--;
         quest.ProcessQuest(map.event[i].id);
      }
   }
   
   
   if(CHECK_BIT(map.event[i].flags, EVENT_TRAINER) )
   {
     menu.TrainerChoice(Talk(map.event[i].name, map.event[i].text, 1));
   }

}

/*
bool CheckPlayer(CPlayer player, CMap map, int i)
{
       if( (player.x+16+1 > map.npc[i].x &&
      		player.y + 16-1 > map.npc[i].y  && 
			player.x < map.npc[i].x + 16+2  && 
			player.y+1 < map.npc[i].y+16+1))
						return true;

	return false;
}
*/

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//             Timing Routines
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
volatile int speed_counter = 0;

void increment_speed_counter()
{
    speed_counter++;
}
END_OF_FUNCTION(increment_speed_counter);

volatile int frame_count, fps  = 0;

void fps_proc(void)
{
   fps = frame_count;
   frame_count = 0;
}
END_OF_FUNCTION(fps_proc);

void SetTimers(void)
{
        LOCK_VARIABLE(speed_counter);
        LOCK_FUNCTION(increment_speed_counter);
        install_int_ex(increment_speed_counter, BPS_TO_TIMER(60));

        LOCK_VARIABLE (frame_count);
        LOCK_VARIABLE (fps);        // Lock FPS
        LOCK_FUNCTION (fps_proc);  // Lock FPScounter
        install_int(fps_proc, 1000);
        frame_count = fps = 0;
}

void SetTimers(int speed)
{
        LOCK_VARIABLE(speed_counter);
        LOCK_FUNCTION(increment_speed_counter);
        install_int_ex(increment_speed_counter, BPS_TO_TIMER(speed));

        LOCK_VARIABLE (frame_count);
        LOCK_VARIABLE (fps);        // Lock FPS
        LOCK_FUNCTION (fps_proc);  // Lock FPScounter
        install_int(fps_proc, 1000);
        frame_count = fps = 0;
}

void ResetTimers()
{
     App.timer = 0;
     speed_counter = 0;
}

/////////////////////////
//CApp
/////////////////////////
CApp::CApp()
{
        done = FALSE;
        selected_pc = 0;
        timer = 0;
}

CApp::~CApp()
{
}

//Callback to exit
void exit_callback()
{
App.done = true;
}


 class CWaypoint
  {
	public:
	int x;
	int y;
  };
  CWaypoint waypoint[6];

  static int ex = 64;
  static int ey = 64;
  int count = 0;



int main(int argc, char *argv[])
{
	  //CNPC npc;
	/*
  CNPC npc;		
  npc.waypoint[0].x = 80;
  npc.waypoint[0].y = 64;
  npc.waypoint[1].x = 96;
  npc.waypoint[1].y = 64;
  npc.waypoint[2].x = 112;
  npc.waypoint[2].y = 64;
  npc.waypoint[3].x = 128;
  npc.waypoint[3].y = 64;
  npc.waypoint[4].x = 144;
  npc.waypoint[4].y = 64;
   */

	//npc.x = 16*4;
	//npc.y = 16*4;
	
  srand(time(NULL));
  int key_space = 0;
  
  Display.CreateWindow(640, 480, 16, true);
  SetTimers();

  menu.Init();


  text_box = load_bitmap("./data/text.bmp", NULL);
  
  
  player[0].gfx = load_bitmap("./data/character.bmp", NULL); // TODO put this somewhere else
  player[1].gfx = load_bitmap("./data/character2.bmp", NULL); // "
  

/*
  // EvenTS MUST BE PLACED ON LAYER 1 (2nd layer)
  SET_BIT(map.tile[1][4][4].flags, FLAG_EVENT);
  
  CNpc npc;
  npc.x = 64;
  npc.gfx = 1;
  npc.y = 64;
  npc.frame = 0;
  npc.id = 1;
  map.npc.push_back(npc);
  map.max_npc++;
   SET_BIT(map.tile[1][4][4].flags, FLAG_EVENT);
  CEvent event;
  event.x = 4;
  event.y = 4;
  event.name = "Sign";
  event.text = "fucka";
  event.flags = EVENT_MSG;
  map.event.push_back(event);
  map.max_event++;
  

  
  SET_BIT(map.tile[0][4][4].flags, FLAG_WAYPOINT);
  
  SET_BIT(map.tile[0][4][5].flags, FLAG_WAYPOINT);
  SET_BIT(map.tile[0][4][6].flags, FLAG_WAYPOINT);
  SET_BIT(map.tile[0][4][7].flags, FLAG_WAYPOINT);
  SET_BIT(map.tile[0][5][7].flags, FLAG_WAYPOINT);
  SET_BIT(map.tile[0][6][7].flags, FLAG_WAYPOINT);
  
  SET_BIT(map.tile[0][4][4].flags, FLAG_WAYPOINT);
  SET_BIT(map.tile[0][5][4].flags, FLAG_WAYPOINT);
  SET_BIT(map.tile[0][6][4].flags, FLAG_WAYPOINT);
  
  */
//  game_objects = load_bitmap("./data/game_objects.bmp", NULL);
  
  
  
  

  
  // TODO: PUT THIS SOMEWhere useful!
    player[1].x = player[0].x;
    player[1].y = player[0].y;
    
player[0].GetInfo();
player[0].shop.Init();
player[1].name = "Teliana";
player[1].GetInfo();
player[1].shop.Init();


/*
CPortal portal;
portal.destx = 100;
portal.desty = 100;
portal.name="./data/test.map";
portal.srcx=10;
portal.srcy=10;
map.portal.push_back(portal);
map.max_portal++;
*/
//        allegro_message("SaVED %d %d %d %d %s", map.portal[0].srcx, map.portal[0].srcy, map.portal[0].destx, map.portal[0].desty, map.portal[0].name.c_str());

//player.inv[3].id = 3;

/*
player[0].GetInfo();
player[0].shop.Init();
player[0].inv[0].id = 4;
player[0].inv[1].id = 4;
player[0].inv[2].id = 4;
player[0].inv[4].id = 4;
player[0].inv[5].id = 4;
player[0].inv[6].id = 4;
player[0].inv[7].id = 4;
player[0].inv[8].id = 4;
player[0].inv[3].id = 2;
allegro_message("max npc %d, max_portal %d", map.max_npc, map.max_portal);

player[1].name = "Omg I'm a rockstarz";
player[1].GetInfo();
player[1].shop.Init();
player[1].inv[0].id = 3;
player[1].inv[1].id = 3;
player[1].inv[2].id = 3;
*/



MIDI *space_mid = load_midi("./data/music/space.mid");
MIDI *spacewalk_mid = load_midi("./data/music/spacewalkbiatch.mid");
MIDI *dark = load_midi("./data/music/dark.mid");
MIDI *dark2 = load_midi("./data/music/dark2.mid");
MIDI *knightsrevenge = load_midi("./data/music/knightsrevenge.mid");
MIDI *inprog = load_midi("./data/music/inprog.mid");
MIDI *stringscool = load_midi("./data/music/stringscool.mid");
MIDI *tribalbeat = load_midi("./data/music/tribalbeat.mid");
play_midi(knightsrevenge, NULL);


// If App.Intro() == 1 then begin a new game, else load a game!
if(App.Intro() == 1)
{

// KEEP THIS
player[0].InitStats();
player[1].InitStats();

// UNCOMMENT THIS ONCE YOU are DONE
map.LoadMap("./data/blackhawk.map");
map.LoadNpcs();
for(int i = 0; i<map.max_npc; ++i)
{
        //TODO: THIS IS TEMPORARY UNTIL THE EDITOR does this auto
         //   map.npc[i].id = 1;
   map.npc[i].UpdateTargets();
   map.npc[i].LoadStats();
}

map.SetPositions();
map.CheckCine();
map.SetPositions();
player[0].UpdateMovement();
}

else
{
   LoadGame();
}

//SET_BIT(quest.quest_bit, QUEST_TALKED_ABOUT_HERB);
//SET_BIT(quest.quest_bit, QUEST_PLANTED_HERB);

/*
map.LoadMap("./data/worldmap.map");
//map.LoadMap("./data/blackhawk.map");
map.LoadNpcs();
player[0].exp = 0;
map.CheckCine();
if(map.CheckBattle()) battle.Battle(false);
*/

//map.LoadMap("./data/castle.map");
//map.LoadNpcs();
//map.CheckCine();
//if(map.CheckBattle()) battle.Battle(false);

//map.LoadMap("./data/cave.map");
//map.LoadNpcs();
//map.SetPositions();
//player[0].UpdateMovement();

//if(map.CheckBattle()) battle.Battle(false);


while (!App.done)
{
  while (speed_counter > 0)
  {

	if( midi_pos < 0 )
	{
	    int randmusic = rand()%9;
		switch(randmusic)
        {
		case 1:
			play_midi(space_mid, NULL);
		    break;
		case 2:
	    	play_midi(spacewalk_mid, NULL);
		    break;
		case 3:
			play_midi(dark, NULL);
			break;
		case 4:
			play_midi(dark2, NULL);
			break;
		case 5:
			play_midi(knightsrevenge, NULL);
			break;
		case 6:
			play_midi(inprog, NULL);
			break;
		case 7:
			play_midi(stringscool, NULL);
			break;
		case 8:
			play_midi(tribalbeat, NULL);
			break;
		}
   }


    // Logic:
    if(key[KEY_ESC]) Display.Shutdown();

	if(key[KEY_RIGHT]) 
	{
        map.CheckPortals(player[0]);
		player[0].Move(map, EAST);
		player[1].x=player[0].x;
        map.CheckEvents(player[0]);
	}

	if(key[KEY_LEFT]) 
	{
        map.CheckPortals(player[0]);
		player[0].Move(map, WEST);
        player[1].x=player[0].x;
		map.CheckEvents(player[0]);
	}
	
	if(key[KEY_UP]) 
	{
        map.CheckPortals(player[0]);
		player[0].Move(map, NORTH);
    	player[1].y=player[0].y;
		map.CheckEvents(player[0]);
	}
	
	
	if(key[KEY_DOWN]) 
	{
        map.CheckPortals(player[0]);
		player[0].Move(map, SOUTH);
    	player[1].y=player[0].y;
		map.CheckEvents(player[0]);
	}

/* TODO: Only for debug use!
	if(key[KEY_V])
	{
     SaveGame();
     while(key[KEY_V]) {}
    }
    
    if(key[KEY_B])
	{
     LoadGame();
     while(key[KEY_B]) {}
    }
*/
	
	update_key(KEY_SPACE, &key_space);
	update_key(KEY_LCONTROL, &key_lctrl);
	update_key(KEY_RCONTROL, &key_rctrl);
	
    if(key_space == 1)
 	{
       // If the PC is on top of the object...
    	if( CHECK_BIT(map.tile[1][player[0].y/16][(player[0].x)/16].flags, FLAG_EVENT) ||
	        CHECK_BIT(map.tile[1][player[0].y/16][(player[0].x+15)/16].flags, FLAG_EVENT) ||
            CHECK_BIT(map.tile[1][(player[0].y+15)/16][(player[0].x)/16].flags, FLAG_EVENT) ||
            CHECK_BIT(map.tile[1][(player[0].y+15)/16][(player[0].x+15)/16].flags, FLAG_EVENT) )
        {
            	for(int i = 0; i<map.max_event; ++i)
				{
					if( (player[0].x/16 == map.event[i].x && player[0].y/16 == map.event[i].y) ||
						((player[0].x+15)/16 == map.event[i].x && (player[0].y)/16 == map.event[i].y) ||
						 ( player[0].x/16 == map.event[i].x && (player[0].y+15)/16 == map.event[i].y) ||
						 ((player[0].x+15)/16 == map.event[i].x && (player[0].y+15)/16 == map.event[i].y) )
					{
                        if(CHECK_BIT(map.event[i].flags, EVENT_ITEM) )
                        {

                            player[App.selected_pc].PickupObject(i);
                            break;
                        }
                        

                        if( CHECK_BIT(map.event[i].flags, EVENT_SIGN) )
						{
							Talk(map.event[i].name, map.event[i].text);
						}
						
						  // Ignores player 1 only deals with the main player [0]
                          bool already_given = false;
                           if(CHECK_BIT(map.event[i].flags, EVENT_CHEST) )
                           {
                             for(int j = 0; j<player[0].event_check.size(); ++j)
                             {
                              if( player[0].event_check[j].name != map.name && map.event[i].x != player[0].event_check[j].x &&
                                  map.event[i].y != player[0].event_check[j].y)
                                  {
                                     // do nothing
                                  }
                              else already_given=true;
                             }
                             

                           for(int j = 0; j< player[0].event_check.size(); ++j)
                           {
                             if(already_given == false)
                             {
                              if(player[0].event_check[j].x == 0)
                              {
                                for(int v = 0; v<MAX_ITEMS; ++v)
                                {
                                  if(map.event[i].id == player[0].list[v].id)
                                  {
                                     Talkf("", "You find %s!", player[0].list[v].name.c_str());
                                     break;
                                  }
                                }
                                       SET_BIT(map.tile[1][player[0].y/map.sizeh][player[0].x/map.sizew].flags, FLAG_EVENT);
                                       map.tile[1][player[0].y/map.sizeh][player[0].x/map.sizew].gfx = TILE_ITEM;
                                       CEvent event;
                                       event.x = player[0].x/map.sizew;
                                       event.y = player[0].y/map.sizeh;
                                       event.flags = EVENT_ITEM;
                                       event.id = map.event[i].id;
                                       map.event.push_back(event);
                                       map.max_event++;
                                     
                        	    	 player[0].event_check[j].name = map.name;
                         			 player[0].event_check[j].x = player[0].x/map.sizew;
                        			 player[0].event_check[j].y = player[0].y/map.sizeh;
                        			 player[0].event_check.resize(player[0].event_check.size()+1);
                        			 SaveGame(); // force a SaveGame so the player can't get the prize more than once
                        			 break;
                              }
                             }
                           }
                           }
						
					}
				}

        }

		if(player[0].facing == NORTH)
		{
			if( CHECK_BIT(map.tile[1][player[0].y/16-1][(player[0].x)/16].flags, FLAG_EVENT) ||
				CHECK_BIT(map.tile[1][player[0].y/16-1][(player[0].x+15)/16].flags, FLAG_EVENT))
			{
				for(int i = 0; i<map.max_event; ++i)
				{
					if( (player[0].x/16 == map.event[i].x && player[0].y/16-1 == map.event[i].y) ||
						((player[0].x+15)/16 == map.event[i].x && (player[0].y)/16-1 == map.event[i].y) )
					{
                        if(CHECK_BIT(map.event[i].flags, EVENT_ITEM) )
                        {
                            player[App.selected_pc].PickupObject(i);
                            break;
                        }

                        HandleEvents(i);
					}
				}
			}
				
//			if( map.CheckNpcs(player[0].x, player[0].y-16) ) Talk("HI", "HI");
            map.InteractNpcs(player[0].x, player[0].y-16);
		}

		else if(player[0].facing == SOUTH)
		{

			if( CHECK_BIT(map.tile[1][(player[0].y+15)/16+1][(player[0].x)/16].flags, FLAG_EVENT) ||
				CHECK_BIT(map.tile[1][(player[0].y+15)/16+1][(player[0].x+15)/16].flags, FLAG_EVENT) )
			{
				for(int i = 0; i<map.max_event; ++i)
				{
					if( (player[0].x/16 == map.event[i].x && (player[0].y+15)/16+1 == map.event[i].y) ||
						((player[0].x+15)/16 == map.event[i].x && (player[0].y+15)/16+1 == map.event[i].y) )
					{
					    if(CHECK_BIT(map.event[i].flags, EVENT_ITEM) )
                        {
                            player[App.selected_pc].PickupObject(i);
                            break;
                        }
                        
                        HandleEvents(i);
					}
				}
			}
				
		//	if( map.CheckNpcs(player[0].x, player[0].y+16) )    Talk("HI", "HI");
		  map.InteractNpcs(player[0].x, player[0].y+16);
		}
		
		else if(player[0].facing == WEST)
		{
			//allegro_message("prim");
			if( CHECK_BIT(map.tile[1][player[0].y/16][(player[0].x)/16-1].flags, FLAG_EVENT) ||
				CHECK_BIT(map.tile[1][(player[0].y+15)/16][(player[0].x)/16-1].flags, FLAG_EVENT) )
			{
				for(int i = 0; i<map.max_event; ++i)
				{
					if( (player[0].x/16-1 == map.event[i].x && player[0].y/16 == map.event[i].y) ||
						( (player[0].x)/16-1 == map.event[i].x && (player[0].y+15)/16 == map.event[i].y))
					{
					    if(CHECK_BIT(map.event[i].flags, EVENT_ITEM) )
                        {
                            player[App.selected_pc].PickupObject(i);
                            break;
                        }
                        
                        HandleEvents(i);
					}
				}
			}
				
		//	if( map.CheckNpcs(player[0].x-16, player[0].y) ) Talk("HI", "HI");
		  map.InteractNpcs(player[0].x-16, player[0].y);
		}
		
		else if(player[0].facing == EAST)
		{
			//allegro_message("prim");
			if( CHECK_BIT(map.tile[1][player[0].y/16][(player[0].x+15)/16+1].flags, FLAG_EVENT)  ||
				CHECK_BIT(map.tile[1][(player[0].y+15)/16][(player[0].x+15)/16+1].flags, FLAG_EVENT) )
			{
				for(int i = 0; i<map.max_event; ++i)
				{
					if( ((player[0].x+15)/16+1 == map.event[i].x && player[0].y/16 == map.event[i].y) ||
						((player[0].x+15)/16+1 == map.event[i].x && (player[0].y+15)/16 == map.event[i].y)  )
					{
						if(CHECK_BIT(map.event[i].flags, EVENT_ITEM) )
                        {
                            player[App.selected_pc].PickupObject(i);
                            break;
                        }
                        
                        HandleEvents(i);
   					}
				}
			}
				
//			if( map.CheckNpcs(player[0].x+16, player[0].y) ) Talk("HI", "HI");
            map.InteractNpcs(player[0].x+16, player[0].y);
		}
	}
	
	
	if(key_lctrl == 1 || key_rctrl == 1)
	{
        menu.DisplayStatus();
	}

   if(key[KEY_M])
   {
     for(int i = 0; i<map.max_event; ++i)
     {
        allegro_message(" num  %d ::: %d %d %d (Imax %d)", i,  map.event[i].x, map.event[i].y, map.event[i].flags, map.max_event);
     }
   }
   
	
	//if(key[KEY_Z])
	//{
		
	//	Talk("Sammy Davis Jr:", "I don't mean to stare -- we don't have to breed... I don't even care we don't have to breed!  ... .SHE SHE SHE SAID!"
                          //"The world is a vampyre!ddddddddddd sdfsd fdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddf dfffffffffffffffffffffazzzzzzzzzzzzzzdffdfsdfasdfdsafadsfadsfadsfdsaf dsfsdfadsfdsa fadfadsfsdaf dfadsfasdfadfadf adfadfasdfasdfdsfadsfdadff sdfsdfsd fsdfsdfs dfsdfsd THIS IS THE LAST LINE");
//						  "Post apa! CYBERPUNK 2005 slkfjdslkfj sdlkjf slkdj we can plant a house we can build a tree homgomgsdlkfjsdfsdoomigso");
  
		//int dir = 0;
		//int dir = 0;
		//if(count 
		//if( ex - waypoint[count].x > 0) dir = EAST;
		//else if( ex - waypoint[count].x < 0) dir = WEST;
		//Move(ex, ey, dir);
	//	while(key[KEY_Z]) {}
	//}
	
//	if(speed_counter == 1)
	//{

if(speed_counter == 1 && App.timer >= 30)
{
 if(player[0].frame%2 == 0) player[0].frame++;
 else if(player[0].frame%2 != 0) player[0].frame--;
}

if(speed_counter == 1)
{
for(int i = 0; i<map.max_npc; ++i)
{
    App.timer ++;
    if(App.timer > 30)
    {
       if(map.npc[i].frame == 1)
       map.npc[i].frame = 0;
       else map.npc[i].frame = 1;
       App.timer = 0;
    }

    if( CHECK_BIT(map.tile[0][map.npc[i].y/16][(map.npc[i].x)/16+1].flags, FLAG_WAYPOINT) && map.npc[i].dir == EAST )
	{
		if(!map.CheckNpcs(player[0].x-1, player[0].y)) map.npc[i].x+=1;
	}
	//else dir = WEST;
	
	else if( CHECK_BIT(map.tile[0][(map.npc[i].y)/16][(map.npc[i].x+15)/16-1].flags, FLAG_WAYPOINT) && map.npc[i].dir == WEST )
	{
		//if(map.npc[i].x != player[0].x) map.npc[i].x-=1;
		if(!map.CheckNpcs(player[0].x+1, player[0].y)) map.npc[i].x--;
	}
	//else dir = EAST;
	
	else if( CHECK_BIT(map.tile[0][(map.npc[i].y+15)/16-1][(map.npc[i].x)/16].flags, FLAG_WAYPOINT) && map.npc[i].dir == NORTH )
	{
		if(!map.CheckNpcs(player[0].x, player[0].y+1)) map.npc[i].y-=1;
	}
	//else dir = SOUTH;
	
	
	else if( CHECK_BIT(map.tile[0][(map.npc[i].y)/16+1][(map.npc[i].x)/16].flags, FLAG_WAYPOINT) && map.npc[i].dir == SOUTH )
	{
		if(!map.CheckNpcs(player[0].x-1, player[0].y-1)) map.npc[i].y+=1;
	}
	//else dir = NORTH;

	else
	{
       map.npc[i].dir = rand()%(50-1+1)+1;
    }
}


}






    speed_counter--;
  }

  // Rendering:
 // map.DrawMap(0, player[0].cam.x, player[0].cam.y);
  
  // Walls, Objects
  /*
  if(map.config == 1)
  {
		map.DrawMap(0, player[0].cam.x, player[0].cam.y); // Walls
		//DrawObjects
  }
  */
  //if(map.config == 2)
  {
		map.DrawMap(0, player[0].cam.x, player[0].cam.y); // Walls
		// drawobjects (not really a layer)
  }
 

  //rect(Display.GetSurface(), npc.x, npc.y, npc.x+16, npc.y+16, makecol(255,255,255));
//  for(int i = 0; i<map.max_npc; ++i)
//	  rect(Display.GetSurface(), map.npc[i].x, map.npc[i].y, map.npc[i].x+16-1, map.npc[i].y+16-1, makecol(255,255,255));
  map.DrawObjects( NULL, player[0].cam.x, player[0].cam.y);

 // rect(Display.GetSurface(), player[0].x-player[0].cam.x, player[0].y-player[0].cam.y, player[0].x+16-player[0].cam.x-1, player[0].y+16-player[0].cam.y-1, makecol(255,0,0));
//  draw_sprite(Display.GetSurface(), player[0].gfx, player[0].x-player[0].cam.x, player[0].y-player[0].cam.y);

 masked_blit( player[App.selected_pc].gfx, Display.GetSurface(), player[0].frame*16, player[0].facing*16, player[0].x-player[0].cam.x, player[0].y-player[0].cam.y, 16, 16);

  
 // map.DrawMapTrans(1, player[0].cam.x, player[0].cam.y); // Overlap
  
//  textprintf(Display.GetSurface(), font, 0, 0, makecol(255,0,0), "FPS: %d 1 x %d y %d 2 x %d y %d timer %d speedcounter %d ", fps, player[0].x, player[0].y, map.portal[5].srcx, map.portal[5].srcy, App.timer, speed_counter );
  textprintf(Display.GetSurface(), font, 0, 0, makecol(255,0,0), "%d fps %d", map.max_portal, fps );
  //textprintf(Display.GetSurface(), font, 0, 10, makecol(255,0,0), "x %d y %d",npc.x , npc.y );
  frame_count++;
 
  blit(Display.GetSurface(), screen, 0, 0, 0, 0, screen->w, screen->h);
  clear_bitmap(Display.GetSurface());


// show_video_bitmap(Display.GetSurface());
// Display.cur_page ^= 0x01;

if(Display.GetSurface() == Display.vscreen[0])
 Display.vscreen[2] = Display.vscreen[1];
else
 Display.vscreen[2] = Display.vscreen[0];

/*
   show_video_bitmap(active_page);
    if (active_page == page1)
      active_page = page2;
    else
      active_page = page1;
      */


};//end while(!App.done)


  Display.Shutdown();
  return 0;
}
END_OF_MAIN();


int CApp::Intro()
{
     bool intro_done = false;
     int choice = 0;
     
     BITMAP *title_bmp = load_bitmap("./data/title.tga", NULL);
     BITMAP *selector = load_bitmap("./data/selector.bmp", NULL);
     BITMAP *banner = load_bitmap("./data/banner.tga", NULL);

     BITMAP *newgame = load_bitmap("./data/newgame.tga", NULL);
     BITMAP *loadgame = load_bitmap("./data/loadgame.tga", NULL);
     BITMAP *options = load_bitmap("./data/options.tga", NULL);
     BITMAP *exit_bmp = load_bitmap("./data/exit.tga", NULL);
     
     // TODO: cue music
     blit(title_bmp, screen, 0, 0, screen->w/2-title_bmp->w/2, screen->h/2-title_bmp->h/2, title_bmp->w, title_bmp->h);
     rest(2000);
     
     int key_up = 0;
     int key_down = 0;
     key_space = 0;
     
     clear_keybuf();
     
     
     
     
     while (!intro_done)
     {
          while (speed_counter > 0)
         {
             update_key(KEY_UP, &key_up);
             update_key(KEY_DOWN, &key_down);
             update_key(KEY_SPACE, &key_space);
             
             if(key_up == 1)
             {
                if(choice-1 >= 0) choice--;
             }
             
             if(key_down == 1)
             {
                if(choice+1 < 4) choice++;
             }
             
             if(choice == 0 && key_space == 1)
             {
                       // Start new journey
                       intro_done = true;
                       return 1;
             }
             
             if(choice == 1 && key_space == 1)
             {
                       // Load Game!
                       intro_done = true;
                       return 0;
             }
             
             if(choice == 2 && key_space == 1)
             {
                       // Options!
                       //
                       alert("Hey man, I'm working on it!", "", "", "Okay", "Ja", NULL, NULL);
             }

             
             if(choice == 3 && key_space == 1)
             {
                       // Quit!
                       allegro_exit();
                       exit(0);
             }
             
             // TODO: Should probably add an ESC escape code for convenience

             speed_counter--;
         }

           textprintf_ex(Display.GetSurface(), font, 0, 470, makecol(255,255,255), 0, "v1.1");
           blit(banner, Display.GetSurface(), 0, 0, screen->w/2-banner->w/2, 0, banner->w, banner->h);


           blit(newgame, Display.GetSurface(), 0, 0, 100, 75, newgame->w, newgame->h);
           blit(loadgame, Display.GetSurface(), 0, 0, 75, 125, loadgame->w, loadgame->h);
           blit(options, Display.GetSurface(), 0, 0, 85, 175, options->w, options->h);
           blit(exit_bmp, Display.GetSurface(), 0, 0, 70, 225, exit_bmp->w, exit_bmp->h);
           /*
           textprintf_ex(Display.GetSurface(), font, 100, 75, makecol(255,255,255), 0, "1. Start New Journey");
           textprintf_ex(Display.GetSurface(), font, 100, 85, makecol(255,255,255), 0, "2. Load Previous Journey");
           textprintf_ex(Display.GetSurface(), font, 100, 95, makecol(255,255,255), 0, "3. Extinguish...");
           */
           masked_stretch_blit( selector, Display.GetSurface(), 0, 0, selector->w, selector->h, 87, 95+choice*50, 9,9);


           blit(Display.GetSurface(), screen, 0, 0, 0, 0, screen->w, screen->h);
        //   stretch_blit( Display.GetSurface(), screen, 0, 0, 320, 240, 0, 0, screen->w, screen->h);
           clear_bitmap(Display.GetSurface());
         
     }
     
}


