#include "empire.h"

_button start[8];
_button back;
_button ok;
_button opt[10];

_ingameoptions gameoptions;

extern void create_sidebars();
extern void load_saved_characters(const char *savefilename);
extern void draw_minimap(int x, int y, string file);
extern void refresh_maplist();
//extern int ingame_options();
extern int do_gameoptions(bool ingame = false);

void assign_tintcolor(int p, int *colors, int searchdir);
void description(int c, int x, int y);
void description(_character *c, int x, int y);
void list_players(int numplayers);
void display_powers(_character *c, int x, int y, int iconsperrow);
void get_connected_beaches();
void add_surrounding_beaches(int bnum, int x, int y);
void get_teleports();
int is_beach(int x, int y);
int beach_already_listed(int x, int y);
int do_first();
int do_load();
//int do_options();
int do_gameload();
//int do_transition(int target);
string describe_strength(int num);
string describe_weakness(int num);

vector<_connectedlocs> beaches;
vector<_loc> teleports;

int menu()
{
	static int menunum = MENU_FIRST;
	static int startsongin = 2;
	int t;

	if (startsongin == 0)
	{  //delay the song by 2 logic loops (so it isn't triggered early by transition)
		play_song(TITLE_THEME);
		startsongin--;
	}
	else if (startsongin > 0)
	{
		startsongin--;
	}

	switch (menunum)
	{
		case MENU_FIRST:
			menunum = do_first();
			break;
		case MENU_LOAD:
			menunum = do_load();
			break;
		case MENU_GAME_OPTIONS:
			menunum = do_gameoptions();
			break;
		case MENU_GAME_LOAD:
			menunum = do_gameload();
			break;
		case QUIT:
			return QUIT;
			break;
		default:        //default cases would lead out of the menu, so
			t = menunum;  //the menu has to open in FIRST next time
			menunum = MENU_FIRST;
			return t;
			break;
	}
	return MENU;
}





int do_first()
{
	static bool first = true, firstloop;
	static short icondelay;
	int x, y;

	const int xadjust = (global.screen_width - 800) / 2;  //make sure the menu is always centered, no matter the resolution
	const int yadjust = (global.screen_height - 600) / 2;

	if (first)
	{
		empdebug("  init main menu...");
		firstloop = true;
		player[0].number = 0;
		player[1].number = 1;
		player[2].number = 2;
		player[3].number = 0;
		player[0].tintcolor = player_color(0, 0);
		player[1].tintcolor = player_color(1, 0);
		player[2].tintcolor = player_color(2, 0);
		player[3].tintcolor = player_color(0, 2);

		start[0].init(381 + xadjust, 96 + yadjust, 0, 0, "Hotseat", 3);
		start[1].init(583 + xadjust, 81 + yadjust, 0, 0, "Load Game", 4);
		start[2].init(581 + xadjust, 402 + yadjust, 0, 0, "Quit", 4);  //quit
		start[3].init(556 + xadjust, 199 + yadjust, 0, 0, "Options", 3);
		start[4].init(305 + xadjust, 240 + yadjust, 0, 0, "Map Editor", 4);
		start[5].init(10, global.screen_height - 30, 100, 20, "Credits", 5);
		start[6].init(global.screen_width - 110, global.screen_height - 30, 100, 20, "How to Play", 5);
		start[7].init(380 + xadjust, 299 + yadjust, 0, 0, "Network Game", 3);

		icondelay = 0;
		first = false;
		clear_particles();
		empdebug("  ...finished init main menu");
	}

	if (icondelay <= 0)
	{
		x = rand()%(global.screen_width - 100) + 50;
		y = rand()%(global.screen_height - 100) + 50;

		create_particle(x, y, P_LOGO);
		icondelay = 25;
	}
	else icondelay--;

	if (firstloop) empdebug("---First loop through main menu---");
	glb.draw_fullscreen(32);
	do_particles();
	if (firstloop) empdebug("   Successfully drew particles");
	glb.draw(39, xadjust, yadjust);

	start[0].check();
	start[1].check();
	start[2].check();
	start[3].check();
	start[4].check();
	start[5].check();
	start[6].check();

	buffer_textout_ex(normal, TRICHROMIC_VERSION, 5, 5, WHITE, 0.7);

	if (global.networking) start[7].check();

	if (start[0].clicked())
	{
		global.netgame = false;
		first = true;
		return MENU_LOAD;
	}
	if (start[1].clicked())
	{
		global.netgame = false;
		first = true;
		return MENU_GAME_LOAD;
	}
	if ((start[2].clicked()) || (key[KEY_ESC]))
	{
		first = true;
		return QUIT;
	}
	if (start[3].clicked())
	{
		first = true;
		return MENU_GAME_OPTIONS;
	}
	if (start[4].clicked())
	{
		first = true;
		return MAPEDIT;
	}
	if (start[5].clicked())
	{
		first = true;
		return CREDITS;
	}
	if (start[6].clicked())
	{
		first = true;
		return HELPSCREEN;
	}
	if ((global.networking) && (start[7].clicked()))
	{
		global.netgame = true;
		first = true;
		return NETWORK;
	}

	draw_mouse();

	if (firstloop)
	{
		empdebug("---Successfully finished first loop of main menu---");
		firstloop = false;
	}

	return MENU_FIRST;
}

int do_load()
{
	const float xratio = float(global.screen_width) / 800.0;
	const float yratio = float(global.screen_height) / 600.0;
	const float minratio=  (xratio < yratio) ? xratio : yratio;

	const int players_x = 38;
	const int players_y = 36;
	const int players_size = 90;
	const int players_spacing = 116;

	const int help_x = int(339 * xratio);
	const int help_y = int(29 * yratio);
	const int minimap_x = int(619 * xratio);  //where the minimap background image begins
	const int minimap_y = int(412 * yratio);
	const int minimap_realx = minimap_x + int(150.0 * (xratio - minratio) / 2.0);  //where the minimap is actually drawn
	const int minimap_realy = minimap_y + int(150.0 * (yratio - minratio) / 2.0);  //(to center the minimap)

	static bool first = true, changemap = false;
	static int oldsel, prevmap, colors[4];
	static _button team, plyrcycle[4], teamcycle[4], colorcycle[4], fundsperbuilding, showdamage,
	timelimit, back, mapchange, mapok, mapcancel, start, techlevel, startingcash,cashturns;
	static _listbox mapbox;
	static bool aremaps = false;
	int i, j, k, l;
	char c[150];
	string s;

	if (first)
	{
		const int startw = 100;
		const int starth = 25;
		const int startx = global.screen_width - startw - 10;
		const int starty = global.screen_height - starth - 10;

		const int button_width = int(170 * (xratio + 1.0) / 2.0);  //as the screen width increases, make the buttons' widths increase by a smaller factor

		const int options_x = minimap_x - button_width - 20;
		const int options_y = int(390 * yratio);

		play_song(MENU_THEME);

		empdebug("Loading the list of maps...");
		refresh_maplist();
		empdebug("  ...done");

		mapchange.init(options_x, int(555 * yratio), button_width, int(40 * yratio), "Change map");
		mapbox.init(options_x, int(410 * yratio), button_width, int(160 * yratio));
		mapbox.setsel(0);
		prevmap = 0;
		mapok.init(options_x, int(575 * yratio), button_width / 2 - 5, int(21 * yratio), "OK");
		mapcancel.init(options_x + (button_width / 2) + 5, int(575 * yratio), button_width / 2 - 5, int(21 * yratio), "Cancel");
		changemap = false;

		i = 0;
		while (unsigned(i) < maplist.size())
		{
			mapbox.additem(maplist[i].c_str(), false);
			if (maplist[i] == global.lastmap)
			{
				mapbox.setsel(i);
				prevmap = i;
			}
			i++;
		}
		if (maplist.size() == 0)
		{
			aremaps = false;
			mapbox.additem("NO MAPS FOUND!", false);
		}
		else
		{
			aremaps = true;
			s = mapbox.selected();
			s.erase(0, 5); //get rid of the (2P) / (3P) / (4P)
			sprintf(c, "maps/%s.map", s.c_str());
			load_map(mapbox.selected(), c);
			minimap.create(true);
			minimap.a = 1.0;
			oldsel = mapbox.getsel();
		}

		gameoptions.reset();
		i = 0;
		oldsel = -1;
		changemap = false;

		i = 0;
		while (i < 4)
		{
			const float player_y_pos = players_y + (players_spacing * i);
			const int centeredx = int(players_x * xratio + (players_size * (xratio - minratio) / 2.0));
			const int centeredy = int(player_y_pos * yratio + (players_size * (yratio - minratio) / 2.0));

			player[i].team = i + 1;
			teamcycle[i].init(int(150 * xratio), int((70 + (players_spacing * i)) * yratio), 40, 40, "", glb.bmp(14 + i));

			j = i;
			if (unsigned(j) >= character.size()) j -= character.size();  //in case playable characters < numplayers
			player[i].number = j;

			plyrcycle[i].init(centeredx, centeredy, int(players_size * minratio), int(players_size * minratio), "", 6, WHITE);
			player[i].tintcolor = player_color(player[i].number, 0);
			k = 0;
			l = 0;
			while (k < i)
			{
				if (player[k].tintcolor == player[i].tintcolor)
				{
					l++;
					if (l > 3) l = 0;
					player[i].tintcolor = player_color(player[i].number, l);
				}
				k++;
			}
			colors[i] = l;
			colorcycle[i].init(int(275 * xratio), int((32 + (players_spacing * i)) * yratio), 40, 40, "", NULL, 2, player[i].tintcolor);
			currentcharacter[i] = character[player[i].number];
			opt[i].init(int(137 * xratio), int((32 + (players_spacing * i)) * yratio), int(130 * xratio), int(15 * yratio), "Human");

			i++;
		}



		back.init(10, global.screen_height - 30, 100, 20, "Back");
		start.init(startx, starty, startw, starth, "  Start!", 1, BLACK);
		startingcash.init(options_x, options_y, button_width, 20, "Starting Cash: 0");
		fundsperbuilding.init(options_x, options_y + 22, button_width, 20, "Funds per Building: 4000");
		showdamage.init(options_x, options_y + 44, button_width, 20, "Show Attacking Damage: Yes");
		timelimit.init(options_x, options_y + 66, button_width, 20, "Turn Time Limit: None");
		techlevel.init(options_x, options_y + 88, button_width, 20, "Tech Level: 3");
		game->techlevel = 3;
		cashturns.init(options_x, options_y + 110, button_width, 20, "Derricks Last: 10 Turns");
		game->cashturns = 10;

		first = false;
	}

	glb.draw_fullscreen(36);

	if ((xratio > 1.0) || (yratio > 1.0))
		buffer_stretch_sprite(glb.bmp(52), help_x, help_y, int(glb.bmp(52)->Width() * xratio), int(glb.bmp(52)->Height() * yratio));
	else
		glb.draw(52, help_x, help_y);

	back.check();

	buffer_rect(start.x - 3, start.y - 3, start.x + start.w + 3, start.y + start.h + 3, BLACK);
	buffer_rect(start.x, start.y, start.x + start.w, start.y + start.h, BLACK);

	if (changemap)
	{
		mapbox.check();
		mapok.check();
		mapcancel.check();
		if (mapok.clicked())
		{
			prevmap = mapbox.getsel();
			changemap = false;
		}
		if (mapcancel.clicked())
		{
			mapbox.setsel(prevmap);
			changemap = false;
		}
	}
	else
	{
		if (aremaps)
		{
			start.check();
			if (start.clicked())
			{
				global.lastmap = mapbox.selected();;

				sprintf(c, "Starting game:\n  %d players\n", worldmap.get_num_players());
				empdebug(c);
				sprintf(c, "  Selected map: %s\n", mapbox.selected());
				empdebug(c);

				first = true;
				i = 0;
				while (i < 4)  //set whether players 3 and four are actually in the game
				{
					if (i < worldmap.get_num_players())
					{
						if (opt[i].get_text() == "Human")
						{
							player[i].controller = HUMAN;
						}
						else
						{
							player[i].controller = AI;
						}

						if (player[i].number == -1)
						{  //random army
							player[i].number = rand()%(character.size());
							currentcharacter[i] = character[player[i].number];
							player[i].tintcolor = player_color(player[i].number, 0);
							k = 0;
							l = 0;
							while (k < 4)
							{
								if ((k < worldmap.get_num_players()) && (i != k))
								{
									if (player[k].tintcolor == player[i].tintcolor)
									{
										l++;
										if (l > 3) l = 0;
										k = -1;
										player[i].tintcolor = player_color(player[i].number, l);
									}
								}
								k++;
								colors[i] = l;
							}
						}

						player[i].playing = 1;
						player[i].everplaying = 1;
						player[i].stats.reset();
						player[i].reapply_unitstats();  //apply army-specific stats now
					}
					else
					{
						player[i].playing = 0;
						player[i].everplaying = 0;
					}
					i++;
				}

				game->loaded_from_file = false;  //the game was not loaded from a saved file
				game->game_just_started = true;
				game->state = START_TURN_SYNC;

				s = mapbox.selected();
				s.erase(0, 5); //get rid of the (2P) / (3P) / (4P)
				load_ai(s);

				create_sidebars();
				get_connected_beaches();
				get_teleports();

				clear_particles();
				return LOGIC;
			}
		}

		if (maplist.size() > 0)
		{
			mapchange.check();

			if (mapchange.clicked())
				changemap = true;
		}
		else
		{
			buffer_textout_ex(med, "NO MAPS FOUND!", minimap_x, minimap_y - 18, RED);
		}

		startingcash.check();
		fundsperbuilding.check();
		showdamage.check();
		timelimit.check();
		techlevel.check();
		cashturns.check();

		if (startingcash.clicked())
		{
			player[0].cash += 5000;
			if (player[0].cash > 50000) player[0].cash = 0;
			i = 1;
			while (i < 4)
			{
				player[i].cash = player[0].cash;
				i++;
			}
			sprintf(c, "Starting Cash: %d", player[0].cash);
			startingcash.rename(c);
		}
		if (startingcash.rclicked())
		{
			player[0].cash -= 5000;
			if (player[0].cash < 0) player[0].cash = 50000;
			i = 1;
			while (i < 4)
			{
				player[i].cash = player[0].cash;
				i++;
			}
			sprintf(c, "Starting Cash: %d", player[0].cash);
			startingcash.rename(c);
		}

		if (fundsperbuilding.clicked())
		{
			gameoptions.funding += 1000;
			if (gameoptions.funding > 10000)
			{
				gameoptions.funding = 1000;
			}
			sprintf(c, "Funds per Building: %-1d", gameoptions.funding);
			fundsperbuilding.rename(c);
		}
		if (fundsperbuilding.rclicked())
		{
			gameoptions.funding -= 1000;
			if (gameoptions.funding < 1000) gameoptions.funding = 10000;
			sprintf(c, "Funds per Building: %-1d", gameoptions.funding);
			fundsperbuilding.rename(c);
		}

		if (showdamage.clicked() || showdamage.rclicked())
		{
			if (gameoptions.show_damage)
			{
				gameoptions.show_damage = false;
				showdamage.rename("Show Attacking Damage: No");
			}
			else
			{
				gameoptions.show_damage = true;
				showdamage.rename("Show Attacking Damage: Yes");
			}
		}

		if (timelimit.clicked())
		{
			if (gameoptions.time == -999)
			{
				gameoptions.time = 1000;
			}
			else
			{
				gameoptions.time += 1000;
				if (gameoptions.time > 15000)
				{
					gameoptions.time = -999;
				}
			}
			if (gameoptions.time == -999)
			{
				timelimit.rename("Turn Time Limit: None");
			}
			else
			{
				sprintf(c, "Turn Time Limit: %-1d seconds", gameoptions.time / 50);
				timelimit.rename(c);
			}
		}
		if (timelimit.rclicked())
		{
			if (gameoptions.time == -999)
			{
				gameoptions.time = 15000;
			}
			else
			{
				gameoptions.time -= 1000;
				if (gameoptions.time < 1000)
				{
					gameoptions.time = -999;
				}
			}
			if (gameoptions.time == -999)
			{
				timelimit.rename("Turn Time Limit: None");
			}
			else
			{
				sprintf(c, "Turn Time Limit: %-1d seconds", gameoptions.time / 50);
				timelimit.rename(c);
			}
		}

		if (techlevel.clicked())
		{
			game->techlevel++;
			if (game->techlevel > 3) game->techlevel = 1;
			sprintf(c, "Tech Level: %d", game->techlevel);
			techlevel.rename(c);
		}
		if (techlevel.rclicked())
		{
			game->techlevel--;
			if (game->techlevel < 1) game->techlevel = 3;
			sprintf(c, "Tech Level: %d", game->techlevel);
			techlevel.rename(c);
		}

		if (cashturns.clicked())
		{
			game->cashturns += 5;
			if (game->cashturns > 30) game->cashturns = 0;

			if (game->cashturns == 0)
			{
				cashturns.rename("Derricks Last: Forever");
			}
			else
			{
				sprintf(c, "Derricks Last: %d Turns", game->cashturns);
				cashturns.rename(c);
			}
		}
		if (cashturns.rclicked())
		{
			game->cashturns -= 5;
			if (game->cashturns < 0) game->cashturns = 30;

			if (game->cashturns == 0)
			{
				cashturns.rename("Derricks Last: Forever");
			}
			else
			{
				sprintf(c, "Derricks Last: %d Turns", game->cashturns);
				cashturns.rename(c);
			}
		}
	}
	if (oldsel != mapbox.getsel())
	{
		if (mapbox.getsel() >= 0)
		{
			s = mapbox.selected();
			s.erase(0, 5); //get rid of the (2P) / (3P) / (4P)
			sprintf(c, "maps/%s.map", s.c_str());
			load_map(mapbox.selected(), c, false);
			minimap.create(true);
			minimap.a = 1.0;
		}
		oldsel = mapbox.getsel();
	}

	i = 0;
	while ((i < 4) && (i < worldmap.get_num_players()))
	{
		const float player_y_pos = players_y + (players_spacing * i);
		const int teamlabel_x = int(157 * xratio);
		const int teamlabel_y = int((56 + 116 * i) * yratio);

		{  // draw over the "X?" in the background image, draw the player's army, and check the transparent button that's over it
			ol::Bitmap *player_image = glb.bmp(51);  //set the player army image to the "random dice"

			buffer_rectfill(int(players_x * xratio), int(player_y_pos * yratio), int((players_x + players_size) * xratio), int((player_y_pos + players_size) * yratio), WHITE);

			if (currentcharacter[i] != NULL)
				player_image = currentcharacter[i]->picture;

			buffer_stretch_sprite(player_image, plyrcycle[i].x, plyrcycle[i].y, plyrcycle[i].w, plyrcycle[i].h);

			plyrcycle[i].check();
		}

		//create a black-with-white-outline "Team" label
		buffer_textout_ex(med, "Team", teamlabel_x - 1, teamlabel_y - 1, WHITE);
		buffer_textout_ex(med, "Team", teamlabel_x + 1, teamlabel_y - 1, WHITE);
		buffer_textout_ex(med, "Team", teamlabel_x - 1, teamlabel_y + 1, WHITE);
		buffer_textout_ex(med, "Team", teamlabel_x + 1, teamlabel_y + 1, WHITE);
		buffer_textout_ex(med, "Team", teamlabel_x, teamlabel_y, BLACK);

		teamcycle[i].check();
		if (player[i].number != -1) colorcycle[i].check();
		opt[i].check();

		if (teamcycle[i].clicked())
		{
			player[i].team++;
			if (player[i].team > 4) player[i].team = 1;
			teamcycle[i].picture = glb.bmp(13 + player[i].team);
		}
		if (teamcycle[i].rclicked())
		{
			player[i].team--;
			if (player[i].team < 1) player[i].team = 4;
			teamcycle[i].picture = glb.bmp(13 + player[i].team);
		}

		if (opt[i].clicked() || opt[i].rclicked())
		{
			if (opt[i].get_text() == "Human")
				opt[i].rename("AI");
			else
				opt[i].rename("Human");
		}

		if (plyrcycle[i].clicked())
		{
			j = player[i].number + 1;
			if (unsigned(j) >= character.size()) j = -1;
			player[i].number = j;

			if (j != -1)
			{
				currentcharacter[i] = character[player[i].number];
				assign_tintcolor(i, colors, 1);
			}
			else
			{
				currentcharacter[i] = NULL;
				colors[i] = -1;
				player[i].tintcolor = WHITE;
			}
			colorcycle[i].color = player[i].tintcolor;
		}
		if (plyrcycle[i].rclicked())
		{
			j = player[i].number - 1;
			if (j < -1) j = character.size() - 1;
			player[i].number = j;

			if (j != -1)
			{
				currentcharacter[i] = character[player[i].number];
				assign_tintcolor(i, colors, 1);
			}
			else
			{
				currentcharacter[i] = NULL;
				colors[i] = -1;
				player[i].tintcolor = WHITE;
			}
			colorcycle[i].color = player[i].tintcolor;
		}

		if (plyrcycle[i].mouseover())
		{
			description(player[i].number, mouse_x + 20, mouse_y - 10);
		}

		if ((player[i].number != -1) && (colorcycle[i].clicked()))
		{
			colors[i]++;
			if (colors[i] > 3) colors[i] = 0;
			assign_tintcolor(i, colors, 1);
			colorcycle[i].color = player[i].tintcolor;
		}
		if ((player[i].number != -1) && (colorcycle[i].rclicked()))
		{
			colors[i]--;
			if (colors[i] < 0) colors[i] = 3;
			assign_tintcolor(i, colors, -1);
			colorcycle[i].color = player[i].tintcolor;
		}

		i++;
	}

	if (back.clicked())
	{
		first = true;
		play_song(TITLE_THEME);
		return MENU_FIRST;
	}

	if (maplist.size() > 0)
	{
		buffer_textout_ex(normal, worldmap.get_name(), minimap_x, minimap_y - 17, BLACK);

		if ((xratio > 1.0) || (yratio > 1.0))
		{
			buffer_rectfill(minimap_x, minimap_y, minimap_x + int(150 * xratio), minimap_y + int(150 * yratio), BLACK);
			minimap.draw_scaled(minimap_realx, minimap_realy, minratio);
		}
		else
			minimap.draw(false, minimap_x, minimap_y, false);
	}

	draw_mouse();

	return MENU_LOAD;
}

void description(int c, int x, int y)
{
	if ((c > -1) && (c < signed(character.size())))
	{
		description(character[c], x, y);
	}
	else if (c == -1)
	{
		const string s = "Random army";
		buffer_rectrounded(x - 5, y - 5, x + med.Width(s) + 5, y + med.Height(s) + 5, BLACK, 0.7);
		buffer_textout_ex(med, s, x, y, WHITE);
	}
}

void description(_character *c, int x, int y)
{
	const int heightgap = 5;
	string name = c->getname();
	string desc = c->getdescription();

	buffer_rectrounded(x - 5, y - 5, x + normal.Width(desc) + 5, y + med.Height(name) + heightgap + normal.Height(desc) + 5, BLACK, 0.7);

	buffer_textout_ex(med, name, x, y, WHITE);
	buffer_textout_ex(normal, desc, x, y + med.Height(name) + heightgap, WHITE);
}

void list_players(int numplayers)
{
	int i = 0;
	char m[15];
	while (i < numplayers)
	{
		sprintf(m, "Player %-1d", i + 1);
		//buffer_rectfill_gradient(0, 25 + (90 * i), 155, 75 + (90 * i), player_color(i), BLACK, BLACK, player_color(i));
		buffer_textout_ex(big, m, 30, 36 + (90 * i), WHITE);
		i++;
	}
}

int do_gameload()
{
//	int safety;
//	int type, tilex, tiley, ready, unum;
//	float health;
	int thechoice = -1;
//	char d[30];
	string mname;
	string ainame;
	string s;
	static bool first = true;
	static _button choice[10];
	static _button delsave[9];
	char path[30];

	if (first)
	{
		const float xratio = float(global.screen_width) / 800.0;
		const float yratio = float(global.screen_height) / 600.0;
		const int buttonx = int(260.0 * xratio);
		const int deletex = int(425.0 * xratio);
		const int buttony = int(80.0 * yratio);
		const int yspacer = buttony / 2;
		const int buttonw = int(140.0 * xratio);
		const int buttonh = int(25.0 * yratio);

		for (int o = 0; o < 9; o++)
		{
			sprintf(path, "saves/game%-1d.sav", o);
			if (exists(path) != 0)
			{
				ifstream n(path);
				if (n.bad())
				{
					choice[o].init(buttonx, buttony + (o * yspacer), buttonw, buttonh, "", 5);
				}
				else
				{
					string gamename = read_savefile_name(path);
					choice[o].init(buttonx, buttony + (o * yspacer), buttonw, buttonh, gamename, 5);
				}
				n.close();
			}
			else
			{
				choice[o].init(buttonx, buttony + (o * yspacer), buttonw, buttonh, "", 5);
			}
			delsave[o].init(deletex, buttony + ((buttonh - 20) / 2) + (o * yspacer), 80, 20, "Delete", 5);
		}

		choice[9].init(10, global.screen_height - 30, 100, 20, "Back");
		gameoptions.reset();
		first = false;
	}

	glb.draw_fullscreen(8);
	glb.draw(9, 0, 0);

	for (int i = 0; i < 10; i++)
	{
		choice[i].check();
		if ((choice[i].clicked()) && (choice[i].get_text() != ""))
		{
			thechoice = i;
			break;
		}
		if (i < 9)
		{
			delsave[i].check();
			if (delsave[i].clicked())
			{  //if the delete option was chosen for this save file
				sprintf(path, "saves/game%-1d.sav", i);
				delete_file(path);
				choice[i].rename("");
			}
		}
	}

	if (((thechoice != -1) && (thechoice != 9)) || (key[KEY_Z]))  //Z = LAST DEBUG SAVE
	{
		if ((thechoice != -1) && (thechoice != 9))
		{
			sprintf(path, "saves/game%-1d.sav", thechoice);
		}
		else
		{
			sprintf(path, "saves/gamedebug.sav");
		}

		if (load_game_from_file(path))
		{
			s = mname;
			s.erase(0, 5); //get rid of the (2P) / (3P) / (4P)
			load_ai(s);

			create_sidebars();
			get_connected_beaches();
			get_teleports();

			minimap.create();
			clear_particles();
			counter = 0;

			first = true;
			return LOGIC;
		}
	}
	else if (thechoice == 9)
	{
		first = true;
		return MENU_FIRST;
	}

	draw_mouse();
	return MENU_GAME_LOAD;
}

void get_connected_beaches()
{
	_loc d;
	_connectedlocs t;
	beaches.clear();
	beaches.reserve(5);

	for (int y = 0; y < worldmap.get_height(); y++)
	{
		for (int x = 0; x < worldmap.get_length(); x++)
		{
			if ((is_beach(x, y) == 1) && (beach_already_listed(x, y) == 0))
			{
				d.x = x;
				d.y = y;
				beaches.push_back(t);
				beaches[beaches.size() - 1].loc.reserve(10);
				beaches[beaches.size() - 1].loc.push_back(d);
				add_surrounding_beaches(beaches.size() - 1, x, y);
			}
		}
	}
}

void add_surrounding_beaches(int bnum, int x, int y)
{
	_loc d;
	if (x - 1 > -1)
	{
		if (is_beach(x - 1, y) == 1)
		{
			if (beach_already_listed(x - 1, y) == 0)
			{
				d.x = x - 1;
				d.y = y;
				beaches[bnum].loc.push_back(d);
				add_surrounding_beaches(bnum, x - 1, y);
			}
		}
	}
	if (x + 1 < worldmap.get_length())
	{
		if (is_beach(x + 1, y) == 1)
		{
			if (beach_already_listed(x + 1, y) == 0)
			{
				d.x = x + 1;
				d.y = y;
				beaches[bnum].loc.push_back(d);
				add_surrounding_beaches(bnum, x + 1, y);
			}
		}
	}
	if (y - 1 > -1)
	{
		if (is_beach(x, y - 1) == 1)
		{
			if (beach_already_listed(x, y - 1) == 0)
			{
				d.x = x;
				d.y = y - 1;
				beaches[bnum].loc.push_back(d);
				add_surrounding_beaches(bnum, x, y - 1);
			}
		}
	}
	if (y + 1 < worldmap.get_height())
	{
		if (is_beach(x, y + 1) == 1)
		{
			if (beach_already_listed(x, y + 1) == 0)
			{
				d.x = x;
				d.y = y + 1;
				beaches[bnum].loc.push_back(d);
				add_surrounding_beaches(bnum, x, y + 1);
			}
		}
	}
}

int is_beach(int x, int y)
{
	_tile *tile = worldmap.get_tile(x, y);

	if (tile->get_set() == 3)
	{  //3 is the set for beaches (called shoals in mapedit)
		if (tile->get_number() < 25)  //shoal tiles 25-28 are actually sea transitions
		{
			return 1;
		}
	}
	if (tile->is_building(PORT))
	{
		return 1;
	}
	return 0;
}

int beach_already_listed(int x, int y)
{
	unsigned int i, j;
	_loc d;
	d.x = x;
	d.y = y;
	i = 0;
	while (i < beaches.size())
	{
		j = 0;
		while (j < beaches[i].loc.size())
		{
			if ((d.x == beaches[i].loc[j].x) && (d.y == beaches[i].loc[j].y))
			{
				return 1;
			}
			j++;
		}
		i++;
	}
	return 0;
}

void get_teleports()
{
	_loc l;
	teleports.clear();

	for (int y = 0; y < worldmap.get_height(); y++)
	{
		for (int x = 0; x < worldmap.get_length(); x++)
		{
			if (worldmap.get_tile(x, y)->same_type(6, 0))
			{
				l.x = x;
				l.y = y;
				teleports.push_back(l);
			}
		}
	}
}

void assign_tintcolor(int p, int *colors, int searchdir)
{
	int k;

	searchdir = (searchdir > 0) ? 1 : -1;

	if (colors[p] > 3) colors[p] = 0;
	player[p].tintcolor = player_color(player[p].number, colors[p]);

	k = 0;
	while (k < worldmap.get_num_players())
	{
		if (p != k)
		{
			if (player[k].tintcolor == player[p].tintcolor)
			{
				colors[p] += searchdir;
				if (colors[p] > 3) colors[p] = 0;
				if (colors[p] < 0) colors[p] = 3;
				k = -1;
				player[p].tintcolor = player_color(player[p].number, colors[p]);
			}
		}
		k++;
	}
}
