/*Pirate2 by Dale Swanson May 22, 2007
A space pirate game, thrilling sequel to pirate.
*/

/* 2024 TODOs:
Add commas to large numbers
Fix nav computer so it tends to keep the same route, unless the difference is big, or only update once a day, store somewhere, make it an old man option

typos
cost per day should increase as ship count does
spread cargo between ships to avoid losing it all?
sort ship list by class, model

Rename some options to be clearer
On display mode select, explain what the options are and what info is displayed where
Maybe add a help mode that explains main screen more?
Allow player to invade individual planets to flip them, similar to boss battle
Handle letters in inputs without crashing?
Create general getInput function that loops until player gives valid input, and handles chars

Cheaper class c transceiver that has 10% chance of getting world data per day
Ships should be more likely to belong to civ of nearby worlds
Bug: can do repairs without enough money
Buy upgrade - Autorepair 10HP / day, nanobots A prevent wear and tear, nanobots B repair damage
Ability to know other fleet strat
other strats themselves?
Show L and H on world price data?
Upgraded sensors, level 6 always sees other fleet first, and/or tie breaker that will always win ties
cheat in gambling
longer range sensors
Add other gambling games
Earn money on a planet
*/


/* Things to do:
possibly name the planets, find 20 star's names the use random numbers
add strategies to old man
check every function call, think about what they will do when called there, and what they call, note any global variable, how it changes
buffer overflow, from ship array into world array
pirates can run if slower, but must drop cargo
test boss fleet size, too small
automation stuff
run in cmd, copy into word spell check
pirate fire then run
negative HP
save game, to text, maybe some mild encryption, probably not
0 debt, some savings, no civ so no taxes, just resting forever.  Partially fixed by savings cap, but maybe some disaster type event.
Warn ship HP, display ship HP info, total fleet HP data, something
A way to just hang out in space, and wait for ships?
link highest and lowest price, make the highest and lowest likely to move in other direction to prevent huge gaps and mess with things
actually do the cargo management
move more constants to variables, skills, text names
ship upgrades, sensors, replace current value
possibly readd inflation, make it slight, effect everything, be more than savings interest
progressive continuously variable tax.  something like 1 - ((1/x) * 1000 )  where x is assets, note it doesn't look like that actually is a good formula
Warnings on reaching savings cap, also what happens when player tries to deposit over savings cap
prices tend to move toward average price
Pay to repair all ships
strategies: percentage remaining HP, and remaining HP/attack


Done: (monitor, and remove from list)
Remove the +1 to travel time, so fleet of speed 30 can go distance 30 in 1 day
Use reserve money when depositing/paying debt at bank
bug where you can buy more than money you have cause "as much as you can" is based on nominal price, but the price paid is based on the adjusted price
Maybe abridge the list of ships when it exceeds 10 (or whatever)
Show difficulty level, assets, cash, ships, etc at end
Show damage and ship number hit during combat
Autofight strategies: attack lowest HP ship, lowest attack ship, highest HP, highest attack, random ship, first ship
Allow pirates to choose an autofight strategy too
Rethink savings interest and the limit over 100k
Stats at the end, total battles won/lost, ships captured, money made from interest, from trading, from piracy, etc
Allow repairing ships just enough to get going after capturing
Make distance calc not all be multiples of 10
don't allow shooting on disabled ships

Allow player to set options: money to keep when buying "as much as possible", max ships to keep in filtered sale
Make boss battle more difficult
Show distance from current world to other worlds on main screen
Replace 1 and 2 with E and R for display of civs on screens
fix transceiver price
print ship list spaced with printf
Repair of lightly damaged ships should take less than a full day
show net worth on main screen

currently in your fleet you have: "nothing" <- add
qty of ships to buy
enter 138 to sell everything in every ship
sell all inventory at once
output day number on change
format both maps to be same shape/size
work on victory, require 20 turns of control, and positive income flow
tweek controlling worlds, make it easier
pirates have random HP, other stats
remove inflation, just messes things up
cap on savings
skip autorepair after boss battle, ruining empire
buggy mercenaries with multiple in queue?
age of price data
player 100 ship cap, check on shipping out, warn then delete
pirates, redo ship numbers and class/models.  Something based on skill
Re do skill, make all constants variables, to change with skill level, separate starting money and skill, maybe let each constant/variable be set individually (maybe from a list of options, with a custom available).
marooned, shipless, with money, enemy civ world, no one will do business, how do I get off?  <- rest it out
auto 138 self repair, ship 138, also what about real ship 138, where to cap players fleet, and how
prices are effected by buying and selling


*/

using namespace std;
#include <iostream> //Includes input/output header
#include <string> //string header
#include <math.h> //extra math functions
#include <locale.h> //thousands separator
#include <time.h> //clock() in rng

// Stats at the end, total battles won/lost, ships captured, money made from interest, from trading, from piracy, etc
// Show difficulty level, assets, cash, ships, etc at end
struct player_stats
{
	int total_ships = 0;
	int ships_bought = 0;
	int ships_captured = 0;
	int ships_cheated = 0;
	int battles_fought = 0;
	int battles_won = 0;
	int battles_lost = 0;
	int battles_ran_away = 0;
	int cheats_used = 0;
	int help_viewed = 0;
	int money_lost_to_interest = 0;
	int money_from_interest = 0;
	int money_from_trades = 0;
	int money_from_piracy = 0;
	int money_from_gambling = 0;
	int money_from_cheating = 0;
	int days_spent_traveling = 0;
	int days_spent_resting = 0;
	int days_spent_repairing = 0;

	void display()
	{
		int battles_won_pct = 0;
		if (battles_fought > 0) battles_won_pct = 100 * battles_won / battles_fought;
		printf("\nMoney from trades: %'d, piracy: %'d, lost to interest: %'d, gotten from interest: %'d, gambling: %'d", money_from_trades, money_from_piracy, money_lost_to_interest, money_from_interest, money_from_gambling);
		if (money_from_cheating > 0) printf(", from cheating: %'d", money_from_cheating);
		printf("\nDays spent traveling: %'d, resting: %'d, repairing: %'d", days_spent_traveling, days_spent_resting, days_spent_repairing);
		printf("\nTotal ships: %'d, bought: %'d, captured: %'d", total_ships, ships_bought, ships_captured);
		if (ships_cheated > 0) printf(", cheated for: %'d", ships_cheated);
		printf("\nTotal battles: %'d, won: %'d, lost: %'d, percent won: %'d%", battles_fought, battles_won, battles_lost, battles_won_pct);
		printf(", ran away: %'d", battles_ran_away);
		cout<<"\nCheats used: "<<cheats_used<<", help viewed: "<<help_viewed;
	}
};

int ships[10][10][50]; //stats on the ships for sale
int fleet[1000][20]; //ships in your fleet, x = index, y = stats 1 - speed, 2 - cargo, 3 - attack, 4 - cost, 5 - sensor range, 6 - hit points, 7 - max HP, 8 - class, 9 - model, 10 - total cargo, 11+ goods
int pfleet[1000][20]; //ships in a pirate fleet
int world[21][20]; //worlds, x = index, y = stats.  
int goods[21][10][3]; //prices of the goods
int upgrade[21][10][3]; //prices of the ship upgrades
int inf[3]; //influence on the worlds
int dis[4]; //distance to other worlds
int cday; //the current day
int debug; //sets mode to debug mode (138=on)
int curworld = 3; //the world the player is currently on
int previous_world = 3; //the previous world the player was on
long long int money; //player money
long long int savings; //players savings
long long int debt; //amount of debt player has
long long int assets; //players total assets
float worldpen = 1.01; //penalty for being on a world not belonging to your civ
int playerciv; //civ of the player
int play; //do you want to continue to play
int traveltime; //time it will take to travel any given distance
int travelto; //world to travel to
int civ[3]; //total number of worlds each civ owns
float taxper; //percentage of tax you will pay
int skill; //player skill level
int pmoney; //pirates money
bool paggressive; //are the pirates aggressive
bool bossfight; //will determine if it's a boss fight or not
int rebel[21][10]; //1 if attack pending, 2 who will control planet
int playerleader; //civ that player controls
int playertax; //% amount set by player if a leader (whole number)
int defense; //amount per planet user spends on defense
bool gameover; //if the game is over or not
float interest; //debt interest
float badworld; //worldpen for a world with a different civ
float goodworld; //worldpen for a world with same civ
float civpen; //pen for players civ in likelihood of getting planets in a flip
int visit[21]; //stores date of last visit to the worlds
int control; //stores how long the player has controlled all the worlds, used for victory
int score; //the players score, if he wins
float scorepen; //used to adjust score for skill level
bool win; //set true when the player wins
int mapmode = 1; //option for old - 0, or new - 1 map display
int pricemode = 1; //price display mode, 0-old, 1-new
long long int assetshis[22]; //a history of the players assets
int transceiver = 0; //the Transceiver gives updated price data, 0 - none, 1- some data, 2- all data.
int classaprice = 20000; //class A transceiver price
int classbprice = 7500; //class B transceiver price
int navcomp = 0; //navigational computer gives optimal route info.
int navcompprice = 15000; //price of the nav computer
int routeprice = 1000;
string goodname[6] = {"", "Zircon", "Ruthenium", "Graphene", "Tritium", "Carbon Nanotube"};
int distances[21]; //distances to each world from the current planet
int reserve_money = 150; // the money to keep in reserve when doing a "buy as many as possible" purchase
int max_ships_to_keep = 100; // the max ships to keep when doing a filter sale
player_stats stats;
int player_battle_strategy = 1; //which strategy the player will use in autofight mode
string version_string = "2.2";
int lowest_good_price[6] = {0};
int highest_good_price[6] = {0};
int lowest_known_good_price[6] = {0};
int highest_known_good_price[6] = {0};
int disabled_ship_display_mode = 1;

/******************** FUNCTION PROTOTYPES ***************************/
int ran(int, int);
void help();
void worldsetup();
void shipsetup();
void worlddisplay();
void displayBreak();
void displayPirateFleetInfo(int pciv);
string showOwnerLetter(int owner_num);
void calcDistances();
void flips();
void costs();
void findPriceExtremes();
void speedship();
void pspeedship();
void senseship();
void psenseship();
void loseship(int lostship);
void listships(int disabled_mode);
void listAbridgedShips();
void plistships(int disabled_mode);
void calcassets();
void victory();
void groundday();
void selfRepair();
void fullServiceRepair();
void shipRepair(float cost_per_hp, int hp_per_day, string text_name, bool automatic);
void removeDisabledShips();
void buyship();
void displaygoods();
void buygoods();
void bank();
void gamble();
void manage();
void piratetalk();
void oldman();
void destroypfleet();
void dropcargo();
void lostbattle();
void wonbattle();
void battle(int shot);
int chooseAutoFightTarget(int strategy, bool show_results, int fleet_array[1000][20]);
void bosspirates();
void pirates();
void forclose();
void day();
void travel();
void warn_low_hp_ships();
void playersetup();
void bar();
void options();
void debugoutput();
void start();
void calcoptimal();
void flipsetting(int&);
/********************************************************************/

/* General notes:
There are 5 goods and there good numbers are:
// 1 - Uranium, 2 - Tritanium, 3 - Silver Oxide, 4, - Platinum, 5 - Carbon Nanotube
note that in fleet[][] they are all +10 to the good numbers, so Uranium is stored at 11, and Nanotubes are 15.
There are 3 civs:
// 0-Neutral, 1-Galactic Star Empire, 2-United Republic of Planets
All the planets start as neutral, except planets 1 and 2, which are the home worlds to civs 1 and 2.  Planets can only go from neutral to 1 or 2, not 1 or 2 to neutral, they can also flip between 1 and 2.  Player starts as neutral.
Any other ship or fleet that isn't you is called pirates, even if friendly.  Generally any variable that deals with ships has a twin that has a p in front and deals with pirates.  Example shipnum is ship index number, pshipnum is pirate ship index number
worlds and planets are used interchangeably
goods is used for all the crap you trade, don't get confused if you see good it doesn't mean nice, positive, or whatever, rather it means tradable stuff.
player and user are used interchangeably

Description of the main arrays:
fleet[][] is your fleet, the first index is ship number, the second stores the various stats.  Example fleet[1][3] is first ship, and the 3 is the attack, so this stores the attack value of your first ship.  The 0's in the arrays are used to store totals, so fleet[0][3] will be the total attack for all ships.  fleet[0][0] is the total number of ships you have, and it used quite a bit.  The various stats are:
//ships in your fleet, x = index, y = stats 1 - speed, 2 - cargo, 3 - attack, 4 - cost, 5 - sensor range, 6 - hit points, 7 - max HP, 8 - class, 9 - model, 10 - total cargo, 11-15 goods
They are pretty self explanatory, 2-cargo is the cargo capacity, and 10-total cargo is the amount of actual cargo you have in that ship, 6-HP is your current hit points for that ship, and 7- max HP is the max HP you can have (100% health).  The other important totals are fleet[0][1] - fleet speed, this isn't a total, but rather the speed of the slowest ship, since the fleet can only move that fast. fleet[0][2] total cargo capacity, fleet[0][5] fleet sensor range, not a total, but the longest sensor range, fleet[0][6] total fleet HP, fleet[0][10] total cargo in your fleet.  fleet[0][11] totals of the different types of goods in your fleet.
pfleet[][] is just pirate fleet, everything is the same as the regular fleet array.
ships[][][] is the ships for sale.  The first two indexes replace the ship number from fleet, the last index is the same stats.  The first two indexes are ship class and model, they both range 1-3.  Each class/model combo (9 total) has it's own set of stats.  You can goto shipsetup to see the stats for all the ships.  Example ship[1][2][3] is class 1 (cargo) model 2 (med), and 3rd stat (attack).
world[][] is all the planets.  Like fleet[][] the first is an index and the second is the stats.  All the planets are on a 10x10 grid (actually I think its 11x11 since the grid goes 0-10), the grid cords are stored as stats 1 and 2.  The owner is stat 3.  I don't think any of the other stats are used, and none of the totals (the 0 indexes) are.
goods[][][] is the prices of the goods.  First index is planet number, second is good number, and last is just actual price or last known price.  Example goods[3][2][1] stores the actual price (1), of Tritanium (2) on world 3 (3).  Second example goods[14][4][2] stores the last known price (2) of Platinum (4) on world 14 (14).
upgrade[][] isn't currently used, but I want to.  It will be upgrades you can buy and store like cargo, but they will actually effect your ships stats.  Things like lasers, shields, extra engines, sensors, whatever.

The following string of numbers should set you up for winning the game, just rest after that, enter them at the first screen where it asks for skill:
2 3 138 1000000000 2 1 2 3 1138 2 1 2 3 1138 2 1 2 3 1138 2 1 2 3 1138 7 1 138 6 5 138 0 138 0 1 2 1 0 1 2 2 0 1 2 3 0 1 2 4 0 1 2 5 0 2 5 1 1 138 7 138 0 50000
*/

int ran(int min, int max) //returns a random number between a min, and b max, careful with number > 32k
{// custom random number gen, for no reason
	int skip; //stores amount of times we skip numbers
	int range; //the range from min to max
	int randresult = 0; //this is your real random number that will be used to return
	int temp; //used to switch min and max if they aren't in order
	
	if (max < min)
	{//if max is less than min we switch them
		temp = max; //put max in temp so we can over write max with min
		max = min;
		min = temp;
	}
	
	range = (max - min) + 1;
	if (rand() == 138) srand(rand() + clock()); 
	//1 in 32k odds to reseed the RNG uses both a rand number and the clock (clock isn't seconds, it's system ticks, faster than seconds) 
	if ((rand() + clock()) % 6 == 1) 
	//basically 1 in 5 chance of looping and wasting some random numbers
	{
		for (skip = ((clock() % 4) + ((rand() + clock()) % 7) + (rand() % 18) + 9); skip > 0; skip--)//comes up with a number to loop from about 10 to 70 times
		{
			rand(); //wastes some random numbers
		}
	}
	randresult = min + int(range * rand() / (RAND_MAX + 1));
	//randresult = int((rand() % int(max - min + 1)) + min);
   return randresult;
}

void help()
{//outputs help on the screen
	cout<<"\nPirate2 by Dale Swanson";
	cout<<"\nVersion: "<<version_string;
	cout<<"\nThis game is set in the future.  You have a spaceship and travel between various worlds (planets).";
	cout<<"\nYou will have to buy and sell goods at these worlds, for a profit.  Buy low, sell high.";
	cout<<"\nAlong the way you will come across other ships, they might attack you, or you may attack them.";
	cout<<"\nIf you lose a battle you'll lose your ships, if you win you'll get the cargo, money, and goods of the other fleet.";
	cout<<"\nThe galaxy is at war between two factions (civilizations), \nif you join one you'll only be able to do business on worlds controlled by them.";
	cout<<"\nJoining a civ does offer cheaper goods on the worlds they control and other benefits.";
	cout<<"\nYou can borrow money to get started, but pay it back quickly.  ";
	cout<<"\nMost of the menus are pretty self explanatory.  Your goal is basically to get as much money as possible.";
	cout<<"\nWhen you are strong enough you can take control of one of the factions, and try to eliminate the other.";
	cout<<"\nYou have options of what kind of ship to get.  Ships get a small amount of wear and tear damage per day.";
	cout<<"\nThere are Cargo ships, Attack ships, and Fast ships.";
	cout<<"\nIf you get a Cargo ship you'll have lots of space but it'll be slow and weak against attack.";
	cout<<"\nYou can either make your living as a trader or a pirate, attacking other ships.";
	cout<<"\nWhat choice you make will obviously effect your ship choice.";

	cout<<"\n\nIt's the future, and you're a trader.  Figure it out.";
	cout<<"\nMake sure that the following line is displayed as one line:";
	cout<<"\n*********************************************************************************************************************************";
	cout<<"\nIf it's not the layout will be messed up. \nTo fix it right click the title bar, Properties, Layout tab, Window Size, Width > 130, OK, Save.";
	money += 100;//cheat to get 100 dollars every time you use help
	stats.help_viewed++;
}

void worldsetup()
{//sets up the initial values for the worlds
	int planetnum; //index number of planets
	int tempplanetnum; //second index, for use in comparing 
	int goodnum; //index number for goods
	bool good; //stores if certain conditions are meet yet
	int lowprice; //the lowest price possible for goods, used for the generating them
	int highprice; //highest possible price
	setlocale(LC_ALL, "");

	for (planetnum = 1; planetnum <= 20; planetnum++)
	{//loops through each planet
		do 
		{//keep looping until we come up with a location that hasn't been taken yet
			good = 1; //set good to 1, if it isn't set to 0 in the if later then we will assume a good place has been found and exit the loop
			world[planetnum][1] = ran(0, 10); //finds the x coordinate for the world
			world[planetnum][2] = ran(0, 10); //finds the y coordinate for the world
			
			for (tempplanetnum = 1; tempplanetnum < planetnum; tempplanetnum++)
			{//loop through each world that has already been placed and compare the locations to see if this location is unoccupied
				if (world[planetnum][1] == world[tempplanetnum][1] && world[planetnum][2] == world[tempplanetnum][2]) 
				{//compares the x and y coordinates for the candidate location with each other world's locations, to see if it's already occupied
					good = 0; //if it is then set good to 0 since it's not good, and we will need to loop through the do loop again
					if (debug) cout<<"\nplanetnum - "<<planetnum<<"\tY - "<<goodnum<<"\tX1 = "<<world[planetnum][1]<<"\tY1 = "<<world[tempplanetnum][1]<<"\tX2 = "<<world[planetnum][2]<<"\tY2 = "<<world[tempplanetnum][2];
				}
			}
		} while (good == 0); //do loop checks to see if good was set to 0, if not we exit
		calcDistances();

		if (debug) cout<<"\n";
		for (goodnum = 1; goodnum <= 5; goodnum++)
		{//sets the initial prices for the various goods
			if (debug) cout<<" Good "<<goodnum<<", Range = "<<int(pow(9, goodnum))<<" - "<<int(pow(11, goodnum));
			//goods[planetnum][goodnum][1] = ran(int(pow(9, goodnum) + 50), int(pow(11, goodnum) + 50 + (goodnum * 10))); //formula to pick the initial cost of the goods in a certain range
			//=C35+(A35*11)+70-(A35 ^ A35)
			lowprice = pow(8, goodnum) + 50; //lowest possible price for goods
			highprice = pow(9, goodnum) + (goodnum * 11) + 70 - pow(goodnum, goodnum); //highest possible price for goods
			goods[planetnum][goodnum][1] = ran(lowprice, highprice); //formula to pick the initial cost of the goods in a certain range
			if (debug) cout<<", Result - "<<goods[planetnum][goodnum][1];
		}
	}
	world[1][3] = 1; //world 1 is home world of civ 1
	world[2][3] = 2; //world 2 is home world of civ 2
}

void shipsetup()
{// sets up the initial prices and stats for ships
	int shipclass; //class of ship
	int shipmodel; //model of ship
	int planetnum; //index number of planet
	
	//ships in your fleet, x = index, y = stats 1 - speed, 2 - cargo, 3 - attack, 4 - cost, 5 - sensor range, 6 - hit points, 7 - max HP, 8 - class, 9 - model, 10 - total cargo, 11+ goods
	ships[1][1][1] = 5; //speed
	ships[1][1][2] = 50; //cargo
	ships[1][1][3] = 5; //attack
	ships[1][1][5] = 1; //sensor range
	ships[1][1][7] = 50; //HP
	
	ships[1][2][1] = 9; //speed
	ships[1][2][2] = 135; //cargo
	ships[1][2][3] = 7; //attack
	ships[1][2][5] = 2; //sensor range
	ships[1][2][7] = 100; //HP
	
	ships[1][3][1] = 14; //speed
	ships[1][3][2] = 255; //cargo
	ships[1][3][3] = 13; //attack
	ships[1][3][5] = 3; //sensor range
	ships[1][3][7] = 175; //HP
	
	ships[2][1][1] = 9; //speed
	ships[2][1][2] = 10; //cargo
	ships[2][1][3] = 17; //attack
	ships[2][1][5] = 2; //sensor range
	ships[2][1][7] = 75; //HP
	
	ships[2][2][1] = 15; //speed
	ships[2][2][2] = 25; //cargo
	ships[2][2][3] = 35; //attack
	ships[2][2][5] = 3; //sensor range
	ships[2][2][7] = 150; //HP
	
	ships[2][3][1] = 18; //speed
	ships[2][3][2] = 45; //cargo
	ships[2][3][3] = 65; //attack
	ships[2][3][5] = 5; //sensor range
	ships[2][3][7] = 250; //HP
	
	ships[3][1][1] = 16; //speed
	ships[3][1][2] = 5; //cargo
	ships[3][1][3] = 5; //attack
	ships[3][1][5] = 2; //sensor range
	ships[3][1][7] = 25; //HP
	
	ships[3][2][1] = 30; //speed
	ships[3][2][2] = 10; //cargo
	ships[3][2][3] = 10; //attack
	ships[3][2][5] = 3; //sensor range
	ships[3][2][7] = 50; //HP
	
	ships[3][3][1] = 45; //speed
	ships[3][3][2] = 25; //cargo
	ships[3][3][3] = 18; //attack
	ships[3][3][5] = 4; //sensor range
	ships[3][3][7] = 75; //HP
	
	
	for (shipclass = 1; shipclass <= 3; shipclass++)
	{//loops through each class
		for (shipmodel = 1; shipmodel <= 3; shipmodel++)
		{//each model			
			for (planetnum = 1; planetnum <= 20; planetnum++)
			{//loop through each planet to set up an initial price for the ships
				ships[shipclass][shipmodel][planetnum+10] = ((ships[shipclass][shipmodel][1] + 5) * 55) + ((ships[shipclass][shipmodel][2] + 5) * 25) + ((ships[shipclass][shipmodel][3] + 5) * 100) + ((ships[shipclass][shipmodel][5] + 5) * 15) + ((ships[shipclass][shipmodel][7] + 5) * 75) + (shipmodel * shipmodel * 1000); //comes up with prices based on the stats of ship
			}
		}
	}
}

void worlddisplay()
{// displays various info
	int planetnum; //planet index number
	int ycord; //y coordinate of planets
	int xcord; //x coordinate of planets
	bool good; //used to store if certain conditions are met (different from it's usual meaning of dealing with tradable stuff)
	
	if (win) cout<<"\nYou've won!  Why are you still playing?  Score - "<<score;
	if (debt > 85000)
	{
		displayBreak();
		cout<<"\n\n***WARNING: Debt to bank is too high, pay off soon or risk seizure of property!***\n";//warning if you are getting too much debt
	}
	if (navcomp) calcoptimal(); //display best trade route if they have the nav computer
	cout<<"\n\nIndependent planets - "<<civ[0];
	cout<<", The Galactic Star Empire - "<<civ[1];
	cout<<", The United Republic of Planets - "<<civ[2];
	//world price info
	if (pricemode==0)
	{//old price display mode
		for (planetnum = 1; planetnum <= 20; planetnum++)
		{//loop through each world, display the stats about it
			printf("%s %2d %s %2d %s %2d %s %d ", "\nWorld #", planetnum, "X", world[planetnum][1], "Y", world[planetnum][2], "Owner", world[planetnum][3]);
			if (debug) 
			{
				printf("%s %3d %s %3d %s %3d %s %4d %s %5d %s %3d", goodname[1].c_str(), goods[planetnum][1][1], goodname[2].c_str(), goods[planetnum][2][1], goodname[3].c_str(), goods[planetnum][3][1], goodname[4].c_str(), goods[planetnum][4][1], goodname[5].c_str(), goods[planetnum][5][1], " Data Age", 1 - 1);
			}
			
			else 
			{
				// TODO: add distance to this world for each planet, is there room?
				printf("%s %3d %s %3d %s %3d %s %4d %s %5d %s %3d", goodname[1].c_str(), goods[planetnum][1][2], goodname[2].c_str(), goods[planetnum][2][2], goodname[3].c_str(), goods[planetnum][3][2], goodname[4].c_str(), goods[planetnum][4][2], goodname[5].c_str(), goods[planetnum][5][2], " Data Age", cday - visit[planetnum]);
			}
			
			if (curworld == planetnum) cout<<" * ";
		}
	}
	if (pricemode==1)
	{//new price display mode
		//headers:
		//World #  1 X  6 Y  9 Owner 1  Uranium  59  Tritanium 178  Silver Oxide 719  Platinum 5195  Carbon Nanotube 50150  Data Age   0
		//World   X       Y       Owner   Uranium Tritanium       Silver Oxide    Platinum        Carbon Nanotube Data Age
		cout<<"\nWorld  X  Y  Owner  "<<goodname[1]<<"  "<<goodname[2]<<"  "<<goodname[3]<<"  "<<goodname[4]<<"  "<<goodname[5]<<"  Data Age"<<"  Distance";
		for (planetnum = 1; planetnum <= 20; planetnum++)
		{//loop through each world, display the stats about it
			cout<<"\n";
			printf("%5d%3d%3d%7s ", planetnum, world[planetnum][1], world[planetnum][2], showOwnerLetter(world[planetnum][3]).c_str());
			for (int goodnum = 1; goodnum <= 5; goodnum++)
			{
				printf("%*d",goodname[goodnum].size()+1,goods[planetnum][goodnum][2]);
				// TODO: Enable this with known price data, make a buyable upgrade
				     if (highest_known_good_price[goodnum] == planetnum) cout<<"H";
				else if (lowest_known_good_price[goodnum]  == planetnum) cout<<"L";
				else cout<<" ";
				// cout<<" "; // TODO: Remove once you enable the above
			}
			printf("%9d",cday-visit[planetnum]);
			printf("%10d", distances[planetnum]);
			if (curworld == planetnum) cout<<" * ";
		}
	}

	if (mapmode == 0)
	{// Backup map display code
		for (ycord = 10; ycord >= 0; ycord--)
		{//loop through the y cord
			// The civ owner graph
			printf("%s%2d ", "\n", ycord);
			for (xcord = 0; xcord <= 10; xcord++)
			{//loop through the x cord
				good = 0; //good here will store if a world was in that particular grid cord, if not then we display a dot
				for (planetnum = 1; planetnum <= 20; planetnum++)
				{//loop through each of the planets, to check if they are in the current grid cord
					if (world[planetnum][1] == xcord && world[planetnum][2] == ycord)
					{//checks to see if the planet is in the cord
						cout<<" "<<showOwnerLetter(world[planetnum][3]).c_str(); //if so we display a number to represent its civ
						good = 1; //set good to 1 so that we don't display a dot
					}
				}
				if (good == 0) cout<<" ."; //if good is 0 then there was no planet, and we need to display a dot as a placeholder
			}
			
			// The planet num graph
			printf("%s%2d ", "\t", ycord);
			for (xcord = 0; xcord <= 10; xcord++)
			{//loop through the x cord
				good = 0; //good here will store if a world was in that particular grid cord, if not then we display a dot
				for (planetnum = 1; planetnum <= 20; planetnum++)
				{//loop through each of the planets, to check if they are in the current grid cord
					if (world[planetnum][1] == xcord && world[planetnum][2] == ycord)
					{//checks to see if the planet is in the cord
						printf("%02d", planetnum);
						good = 1; //set good to 1 so that we don't display a dot
					}
				}
				if (good == 0) cout<<" ."; //if good is 0 then there was no planet, and we need to display a dot as a placeholder
			}

			// Distance graph
			printf("%s%2d ", "\t", ycord);
			for (xcord = 0; xcord <= 10; xcord++)
			{//loop through the x cord
				good = 0; //good here will store if a world was in that particular grid cord, if not then we display a dot
				for (planetnum = 1; planetnum <= 20; planetnum++)
				{//loop through each of the planets, to check if they are in the current grid cord
					if (world[planetnum][1] == xcord && world[planetnum][2] == ycord)
					{//checks to see if the planet is in the cord
						// Some distances are > 100, so we can either use 3 digits, truncate those to '99' or divide all by 10
						if (planetnum == curworld) printf("XX");
						else if (distances[planetnum] < 100) printf("%02d", distances[planetnum]);
						else if (distances[planetnum] >= 100) printf("99");
						good = 1; //set good to 1 so that we don't display a dot
					}
				}
				if (good == 0) cout<<" ."; //if good is 0 then there was no planet, and we need to display a dot as a placeholder
			}
		}
		
		cout<<"\n   ";
		for (xcord = 0; xcord <= 10; xcord++)
		{//display the X grid numbers
			printf("%2d", xcord);
		}
		
		cout<<"\t   ";
		for (xcord = 0; xcord <= 10; xcord++)
		{//display the X grid numbers
			printf("%2d", xcord);
		}

		cout<<"\t   ";
		for (xcord = 0; xcord <= 10; xcord++)
		{//display the X grid numbers
			printf("%2d", xcord);
		}
	}
	
	if (mapmode == 1)
	{//New map display code
		for (ycord = 10; ycord >= 0; ycord--)
		{//loop through the y cord
			printf("%s%2d ", "\n", ycord);
			
			for (xcord = 0; xcord <= 10; xcord++)
			{//loop through the x cord
				good = 0; //good here will store if a world was in that particular grid cord, if not then we display a dot
				for (planetnum = 1; planetnum <= 20; planetnum++)
				{//loop through each of the planets, to check if they are in the current grid cord
					if (world[planetnum][1] == xcord && world[planetnum][2] == ycord)
					{//checks to see if the planet is in the cord
						printf(" %02d", planetnum);
						good = 1; //set good to 1 so that we don't display a dot
					}
				}
				if (good == 0) cout<<"   "; //if good is 0 then there was no planet, and we need to display a dot as a placeholder
			}
			cout<<"\n   ";		
			
			for (xcord = 0; xcord <= 10; xcord++)
			{//loop through the x cord
				good = 0; //good here will store if a world was in that particular grid cord, if not then we display a dot
				for (planetnum = 1; planetnum <= 20; planetnum++)
				{//loop through each of the planets, to check if they are in the current grid cord
					if (world[planetnum][1] == xcord && world[planetnum][2] == ycord)
					{//checks to see if the planet is in the cord, there are 3 spaces to be used, the 1st is a space, 2nd is a * for player, and 3rd is civ
						if (curworld == planetnum) cout<<" *"; //Player is here
						if (curworld != planetnum) cout<<"  "; //Player is not here
						cout<<showOwnerLetter(world[planetnum][3]).c_str();
						good = 1; //set good to 1 so that we don't display a dot
					}
				}
				if (good == 0) cout<<"   "; //if good is 0 then there was no planet, and we need to display 3 spaces as a placeholder
			}
		}
		
		cout<<"\n   ";
		for (xcord = 0; xcord <= 10; xcord++)
		{//display the X grid numbers
			printf(" %2d", xcord);
		}	
	}
}

void displayBreak()
{
	cout<<"\n\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n";
}

void displayPirateFleetInfo(int pciv)
{
	cout<<"\nYou have come across another fleet, it is ";
	if (pciv == 0) cout<<"neutral"; //a bunch of complicated nonsense to display the correct civ for player and pirates
	if (pciv == 1) cout<<"a member of The Galactic Star Empire";
	if (pciv == 2) cout<<"a member of The United Republic of Planets";
	cout<<", and you are ";
	if (playerciv == 0) cout<<"neutral";
	if (playerciv == 1) cout<<"a member of The Galactic Star Empire";
	if (playerciv == 2) cout<<"a member of The United Republic of Planets";
	cout<<".";
	cout<<"\nThey have ";
	cout<<pfleet[0][0]<<" ship";
	if (pfleet[0][0] > 1) cout<<"s";
	cout<<", their combined attack is "<<pfleet[0][3]<<", and combined HP is "<<pfleet[0][6];
	cout<<"\nYou have ";
	cout<<fleet[0][0]<<" ship";
	if (fleet[0][0] > 1) cout<<"s";
	cout<<", your combined attack is "<<fleet[0][3]<<", and combined HP is "<<fleet[0][6];
}

string showOwnerLetter(int owner_num)
{
	if (owner_num == 0) return "I";
	if (owner_num == 1) return "E";
	if (owner_num == 2) return "R";
	return "X";
}

void calcDistances()
{
	int x_distance;
	int y_distance;
	int planetnum;
	for (planetnum = 1; planetnum <= 20; planetnum++)
	{//loops through each planet
		x_distance = abs(world[curworld][1] - world[planetnum][1]); //finds A
		y_distance = abs(world[curworld][2] - world[planetnum][2]); //finds B
		distances[planetnum] = float(sqrt(pow(x_distance, 2) + pow(y_distance, 2))) * 10; //finds C using A^2 + B^2 = C^2
	}
}

void flips()
{//determines which planets will flip and to who
	int planetnum; //index number of planets
	int tempplanetnum; //a temp planet index
	
	// TODO: Prevent player from lowering tax rate except on tax day
	// Maybe just store desired_tax_rate and put it into effect on tax day

	civ[0] = 0; //total number of planets the civ controls, set it to 0 for all so we can add it up
	civ[1] = 0;
	civ[2] = 0;
	if (money - defense < defense * 10 && playerleader > 0)
	{//a warning if money is getting too low to keep up defense spending
		displayBreak();
		cout<<"\n\n***WARNING: Treasury getting low, defense spending could be halted***\n";
	}
	
	for (planetnum = 1; planetnum <= 20; planetnum++)
	{//loops through each planet
		if (money - defense < 10000 && playerleader > 0)
		{//a warning that money is too low to keep up defense spending
			displayBreak();
			cout<<"\n\n***WARNING: Treasury too low, defense spending halted***\n";
			defense = 0; //set defense spending to 0 so that player doesn't go bankrupt
			displayBreak();
		}
		if (world[planetnum][3] == playerleader) money -= defense; //if player owns planet he pays defense spending for it
		if (ran(1, 10) == 1)
		{//1 out of 10 odds of flipping
			inf[0] = 0; //the influence of civ 0
			inf[1] = 0; //the influence of civ 1
			inf[2] = 0; //the influence of civ 2
			calcDistances();
			for (tempplanetnum = 1; tempplanetnum <= 20; tempplanetnum++)
			{//loop through each planet again, to compare the distances, to determine the influence.  Uses A^2 + B^2 = C^2
				// Maybe we can't use distances[] array, because that is only for current planet, this is doing all planets
				dis[1] = abs(world[planetnum][1] - world[tempplanetnum][1]); //finds A
				dis[2] = abs(world[planetnum][2] - world[tempplanetnum][2]); //finds B
				dis[3] = int(sqrt(pow(dis[1], 2) + pow(dis[2], 2))); //finds C using A^2 + B^2 = C^2
				if (dis[3] == 0)
				{//since the influence is 10/distance if distance is 0 we'd get divide by 0, so we just set it to something
					inf[world[tempplanetnum][3]] += 50; //the higher this is the harder it'll be for a planet to flip to another civ
				}
				else
				{//if the distance is anything > 0 then we'll use this formula to determine the influence
					//cout<<"\ndis[3] - "<<dis[3];
					inf[world[tempplanetnum][3]] += ((10 / dis[3]) + 1); //formula for influence is just (10/distance) + 1.
				}
			}
			inf[playerciv] *= civpen; //skill level penalty for player's civ
			
			inf[1]++;
			inf[2]++; //ensures each civ has some chance of getting the planet, even if they are wiped out
			
			if (playerleader > 0)
			{// if the player is the leader of a civ
				if (debug) cout<<"\nBefore defense spending - "<<inf[playerleader];
				inf[playerleader] += (defense - 10000) / (200 * skill);//add players defense spending to inf, 10k is neutral, anything less hurts anything more helps, every 400 either way is 1 inf point
				if (debug) cout<<", After defense spending - "<<inf[playerleader];
			}
			
			if (debug) cout<<"\nWorld # "<<planetnum<<", inf 1 - "<<inf[1]<<", inf 2 - "<<inf[2];
			if (ran(1, inf[1] + inf[2]) <= inf[1]) 
			{//randomly decided if planet will flip.  If the random number in the range of 1 - inf1 + inf2 is <= to inf1 then civ 1 gets it, if not civ 2 does
				if (world[planetnum][3] != playerleader && playerleader == 1) cout<<"\nOur troops have successfully taken planet "<<planetnum<<"!";
				if (world[planetnum][3] == playerleader && playerleader != 1 && playerleader != 0) cout<<"\nWe have lost planet "<<planetnum<<"!";
				world[planetnum][3] = 1; //sets the new owner of the planet to 1 
				if (debug) cout<<" 1 gets it ";
			}
			else
			{//If the random number in the range of 1 - inf1 + inf2 is not <= to inf1 then civ 2 gets it.
				if (world[planetnum][3] != playerleader && playerleader == 2) cout<<"\nOur troops have successfully taken planet "<<planetnum<<"!";
				if (world[planetnum][3] == playerleader && playerleader != 2 && playerleader != 0) cout<<"\nWe have lost planet "<<planetnum<<"!";
				world[planetnum][3] = 2; //sets the new owner of the planet to 2
				if (debug) cout<<" 2 gets it ";
			}
			//if (debug) worlddisplay(); //displays the current world info
			//system("PAUSE");
		}
		
		if (ran(1, 1000) < (playertax - 3) && world[planetnum][3] == playerleader && playerleader > 0)
		{//decide if planets will rebel because of taxes.  13% taxes should yield 1/100 odds of rebellion.  Odds for rebellion are (taxes-3) / 1000
			cout<<"\n\n***Citizens on world "<<planetnum<<" have rebelled against you, citing high taxes!***\n";
			world[planetnum][3] = 0; //switch planet control
		}
		if (ran(1, 100) == 1 && world[planetnum][3] != playerleader)
		{//decide if planets will rebel because of taxes.  Non-player controlled planets
			world[planetnum][3] = 0; //switch planet control
		}
		civ[world[planetnum][3]]++; //adds up the number of planets under control of the civ
	}
}

void costs()
{//determines the amount of change in prices of the various goods
	int planetnum; //planet index number
	int goodnum; //good index number
	
	for (planetnum = 1; planetnum <= 20; planetnum++)
	{//loops through each planet
		for (goodnum = 1; goodnum <= 5; goodnum++)
		{//loops through each good
			if (planetnum == lowest_good_price[goodnum])
			{//this is the lowest price for this good, increase it
				goods[planetnum][goodnum][1]++;
				// TODO: Implement this better
			}
			if (planetnum == highest_good_price[goodnum])
			{//this is the highest price for this good, decrease it
				goods[planetnum][goodnum][1]--;
			}
			goods[planetnum][goodnum][1] += ran((goods[planetnum][goodnum][1] * -0.02) - 2, (goods[planetnum][goodnum][1] * 0.02) + 2); //determines the amount of change each price will get
			//used to have this so that there would be inflation, but didn't like it
			if (goods[planetnum][goodnum][1] < 5) goods[planetnum][goodnum][1] = 5; //checks to see if the price is < 5, if so set it at 5, prevents negative prices
		}
	}
	findPriceExtremes();
}

void findPriceExtremes()
{//find the highest and lowest price for each good, both based on actual data, and only known data
	int planetnum; //planet index number
	int goodnum; //good index number
	
	for (planetnum = 1; planetnum <= 20; planetnum++)
	{//loops through each planet
		// cout<<"\nPlanet # "<<planetnum;
		for (goodnum = 1; goodnum <= 5; goodnum++)
		{//loops through each good
			if (lowest_good_price[goodnum] == 0  || goods[planetnum][goodnum][1] < goods[lowest_good_price[goodnum]][goodnum][1])  lowest_good_price[goodnum]  = planetnum;
			if (highest_good_price[goodnum] == 0 || goods[planetnum][goodnum][1] > goods[highest_good_price[goodnum]][goodnum][1]) highest_good_price[goodnum] = planetnum;
			// cout<<", good # "<<goodnum<<" - "<<goods[planetnum][goodnum][2];
			if (goods[planetnum][goodnum][2] == 0) continue; //good price isn't known yet
			if (lowest_known_good_price[goodnum] == 0  || goods[planetnum][goodnum][2] < goods[lowest_known_good_price[goodnum]][goodnum][2])  lowest_known_good_price[goodnum]  = planetnum;
			if (highest_known_good_price[goodnum] == 0 || goods[planetnum][goodnum][2] > goods[highest_known_good_price[goodnum]][goodnum][2]) highest_known_good_price[goodnum] = planetnum;
		}
	}
}

void speedship()
{// calculates the speed of your fleet, by finding the slowest ship in it
	int shipnum; //ship index number
	
	fleet[0][1] = fleet[1][1]; //sets the fleet speed to that of your first ship
	for (shipnum = 1; shipnum <= fleet[0][0]; shipnum++)
	{//loop through each ship, check to see if it's slower than the current fleet speed
		if (debug) cout<<"\n fleet[0][1] - "<<fleet[0][1]<<" fleet[shipnum][1] - "<<fleet[shipnum][1];
		if (fleet[shipnum][1] < fleet[0][1]) fleet[0][1] = fleet[shipnum][1]; //if it is slower then it becomes the new fleet speed
	}
}

void pspeedship()
{// calculates the speed of pirate fleet, by finding the slowest ship in it
	int shipnum;//ship index number
	
	pfleet[0][1] = pfleet[1][1]; //sets the fleet speed to that of the first ship
	for (shipnum = 1; shipnum <= pfleet[0][0]; shipnum++)
	{//loop through each ship, check to see if it's slower than the current fleet speed
		if (debug) cout<<"\n pfleet[0][1] - "<<pfleet[0][1]<<" pfleet[shipnum][1] - "<<pfleet[shipnum][1];
		if (pfleet[shipnum][1] < pfleet[0][1]) pfleet[0][1] = pfleet[shipnum][1]; //if it is slower than it becomes the new fleet speed
	}
}

void senseship()
{// calculates the sensor range of your fleet, by finding the longest sensor range ship in it
	int shipnum;//ship index number
	
	fleet[0][5] = fleet[1][5]; //sets the range to that of your first ship
	for (shipnum = 1; shipnum <= fleet[0][0]; shipnum++)
	{//loop through each ship, check to see if it's farther than the current fleet range
		if (debug) cout<<"\n fleet[0][5] - "<<fleet[0][5]<<" fleet[shipnum][5] - "<<fleet[shipnum][5];
		if (fleet[shipnum][5] > fleet[0][5]) fleet[0][5] = fleet[shipnum][5]; //if it is farther than it becomes the new fleet range
	}
}

void psenseship()
{// calculates the sensor range of pirate fleet, by finding the longest sensor range ship in it
	int shipnum; //ship index number
	
	pfleet[0][5] = pfleet[1][5]; //sets the range to that of the first ship
	for (shipnum = 1; shipnum <= pfleet[0][0]; shipnum++)
	{//loop through each ship, check to see if it's farther than the current fleet range
		if (debug) cout<<"\n pfleet[0][5] - "<<pfleet[0][5]<<" pfleet[shipnum][5] - "<<pfleet[shipnum][5];
		if (pfleet[shipnum][5] > pfleet[0][5]) pfleet[0][5] = pfleet[shipnum][5]; //if it is farther than it becomes the new fleet range
	}
}

void loseship(int lostship)
{//takes ship index # passed to it and destroys it, assumes the player has already been paid for it (if selling).  Any cargo or ship value will be lost
	int shipnum;//ship index number
	int statnum;//stat index number
	//the following subtracts the ship we are losing form the fleet totals (stored as ship 0 in the fleet array)
	fleet[0][2] -= fleet[lostship][2]; //cargo
	fleet[0][3] -= fleet[lostship][3]; //attack
	fleet[0][4] -= fleet[lostship][4]; //cost,
	fleet[0][5] -= fleet[lostship][5]; //sensors
	fleet[0][6] -= fleet[lostship][6]; //hit points
	fleet[0][7] -= fleet[lostship][7]; //max hit points
	fleet[0][10] -= fleet[lostship][10]; //cargo used
	fleet[0][11] -= fleet[lostship][11]; //various total cargos
	fleet[0][12] -= fleet[lostship][12];
	fleet[0][13] -= fleet[lostship][13];
	fleet[0][14] -= fleet[lostship][14];
	fleet[0][15] -= fleet[lostship][15];
	for (shipnum = lostship; shipnum <= fleet[0][0]; shipnum++)
	{//loops through each ship, starting at the ship you will lose, replaces that ship with ship above it
		for (statnum = 1; statnum <= 20; statnum++)
		{//loops through each stat, to move each one
			fleet[shipnum][statnum] = fleet[shipnum + 1][statnum]; //actually moves the stats
		}
	}
	fleet[0][0]--; //lowers the total count of ships
	speedship(); //calculates the speed of the fleet, by finding the slowest ship
	senseship(); //calculates the sensor range of the fleet
}
	
void listships(int disabled_mode = 0)
{//lists the ships currently in your fleet
	int shipnum;//ship index number
	
	cout<<"\n\nCurrently in your fleet you have:";
	for (shipnum = 1; shipnum <= fleet[0][0]; shipnum++)
	{//loop through each ship in your fleet, so that the stats can be shown
		if (disabled_mode == 2 && fleet[shipnum][6] <= 0) continue;
		cout<<"\n";
		if (disabled_mode == 1 && fleet[shipnum][6] <= 0) cout<<"D ";
		printf("Ship # %3d Speed - %2d Cargo - %3d Attack - %2d Value - %5d Sensor - %2d Hit Points - %3d Max HP - %3d Class - %1d Model - %1d", shipnum, fleet[shipnum][1], fleet[shipnum][2], fleet[shipnum][3], fleet[shipnum][4], fleet[shipnum][5], fleet[shipnum][6], fleet[shipnum][7], fleet[shipnum][8], fleet[shipnum][9]);
		//ships in your fleet, shipnum = index, y = stats 1 - speed, 2 - cargo, 3 - attack, 4 - cost, 5 - sensor range, 6 - hit points, 7 - max HP, 8 - class, 9 - model, 11+ goods
	}
	if (fleet[0][0] == 0) cout<<"\nYou don't have any ships!";
}

void listAbridgedShips()
{
	cout<<"\n\nCurrently in your fleet you have "<<fleet[0][0]<<" ships.";
}

void plistships(int disabled_mode = 0)
{//lists the ships currently in the pirate fleet
	int shipnum;//ship index number
	
	if (debug) cout<<"\nPirate money - "<<pmoney<<", Aggressive - "<<paggressive;
	cout<<"\nCurrently the enemy fleet has:";
	for (shipnum = 1; shipnum <= pfleet[0][0]; shipnum++)
	{//loop through each ship in pirate fleet, so that the stats can be shown
		if (disabled_mode == 2 && pfleet[shipnum][6] <= 0) continue;
		cout<<"\n";
		if (disabled_mode == 1 && pfleet[shipnum][6] <= 0) cout<<"D ";
		printf("Ship # %3d Speed - %2d Cargo - %3d Attack - %2d Value - %5d Sensor - %2d Hit Points - %3d Max HP - %3d Class - %1d Model - %1d", shipnum, pfleet[shipnum][1], pfleet[shipnum][2], pfleet[shipnum][3], pfleet[shipnum][4], pfleet[shipnum][5], pfleet[shipnum][6], pfleet[shipnum][7], pfleet[shipnum][8], pfleet[shipnum][9]);
		// cout<<"\nShip # "<<shipnum<<" - Speed - "<<pfleet[shipnum][1]<<", Cargo - "<<pfleet[shipnum][2]<<", Attack - "<<pfleet[shipnum][3]<<", Value - "<<pfleet[shipnum][4]<<", Sensor - "<<pfleet[shipnum][5]<<", Hit Points - "<<pfleet[shipnum][6]<<", Max HP - "<<pfleet[shipnum][7]<<", Class - "<<pfleet[shipnum][8]<<", Model - "<<pfleet[shipnum][9];
		if (debug) cout<<"\nShip # "<<shipnum<<" - "<<goodname[1]<<" - "<<pfleet[shipnum][11]<<", "<<goodname[2]<<" - "<<pfleet[shipnum][12]<<", "<<goodname[3]<<" - "<<pfleet[shipnum][13]<<", "<<goodname[4]<<" - "<<pfleet[shipnum][14]<<", "<<goodname[5]<<" - "<<pfleet[shipnum][15];
		//ships in pirate fleet, shipnum = index, y = stats 1 - speed, 2 - cargo, 3 - attack, 4 - cost, 5 - sensor range, 6 - hit points, 7 - max HP, 8 - class, 9 - model, 11+ goods
	}
}

void calcassets()
{//calculates the total assets player has
	int shipnum;//ship index number
	
	assets = (money + savings) - debt; //your assets start as just your money and savings minus your debt
	for (shipnum = 1; shipnum <= fleet[0][0]; shipnum++)
	{//loop through each ship, so that its value can be added to your assets
		assets += fleet[shipnum][4]; //adds value of ship to your assets
		assets += fleet[shipnum][11] * goods[curworld][1][1]; //adds value of various goods to assets
		assets += fleet[shipnum][12] * goods[curworld][2][1];
		assets += fleet[shipnum][13] * goods[curworld][3][1];
		assets += fleet[shipnum][14] * goods[curworld][4][1];
		assets += fleet[shipnum][15] * goods[curworld][5][1];
	}
}

void victory()
{//the player wins the game
	calcassets(); //find the assets
	win = 1;
	displayBreak();
	cout<<"\n\n\n***** A WINNER IS YOU *****\n\nYou have maintained control over every world for 20 days!";
	score = (100000 / cday);
	if (cday < 1000) score += (1000 - cday);
	// TODO: replace assets formula with base 1.5 log of assets * 10
	score += pow(assets, 0.25);
	score *= scorepen;
	printf("\n\nYour score is - %'d", score);
	cout<<"\nCongratulations!";
	cout<<"\n\nDifficulty: "<<skill;
	printf("\nAssets: %'d", assets);
	printf("\nDay: %'d", cday);
	stats.display();
	cout<<"\n\nCredits:";
	cout<<"\nDale Swanson";
	cout<<"\nVersion: "<<version_string;
	cout<<"\nThe End!";
	cout<<"\n138 in the bank gives you free money";
	cout<<"\n\n\n";
	displayBreak();
	system("PAUSE");
}

void groundday()
{//time on the ground, a terrible way of doing it, but necessary because can't call day() from above it, and need to call it from stuff that it calls (namely pirate()) See day() for a note
	long long int taxed; //amount paid in taxes
	int tempplanetnum; //a temp planet index number
	int planetnum; //planet index number
	int tempass; //for the asshistory loop
	
	cday++; //increase the current day counter
	cout<<"\nDay - "<<cday;
	money -= (skill * skill); //3 dollars a day to pay for food I guess, ships aren't in space so we don't pay for fuel and stuff
	stats.money_lost_to_interest += (debt * interest) - debt;
	debt *= interest; //1% per day interest on loans
	int savings_increase = (savings * 1.005) - savings;
	if (savings_increase > 1000) savings_increase = 1000;
	savings += savings_increase;
	stats.money_from_interest += savings_increase;
	calcassets(); //find the assets
	
	for (tempass = 21; tempass >= 1; tempass--)
	{//loop through the assets history, move them all back a day
		assetshis[tempass] = assetshis[tempass - 1]; //move all the assets history one day
		if (debug) cout<<"\nAssets Day - "<<tempass<<", $"<<assetshis[tempass];
	}
	assetshis[0] = assets; //sets day 0 assets to current assets
	
	if (cday % 15 == 0 && playerciv > 0)
	{//every 15 days you pay taxes if you are a member of a civ
		if (playerleader == 0)
		{//if player isn't the leader of a civ then we will charge them taxes
			cout<<"\nPlayer civ - "<<playerciv;
			if (assets < 1000) assets = 1000;
			taxper = (civ[playerciv] + 1) * 0.005 * skill; //tax % is number of planets civ owns * 1%, so 10 planets is 10% (for skill - 2)
			cout<<"\nTax time";
			cout<<"\nTaxable assets = "<<assets<<", taxes paid = "<<int(assets * taxper);
			money -= int(assets * taxper);//% taxes on total assets
		}
		else if (playerleader > 0)
		{// if player is the leader of a civ then they get paid the taxes
			displayBreak();
			cout<<"\nTax time";
			cout<<"\nWelcome leader of ";
			if (playerleader == 0) cout<<"no civilization";
			if (playerleader == 1) cout<<"The Galactic Star Empire";
			if (playerleader == 2) cout<<"The United Republic of Planets";
			cout<<"\nindependent planets - "<<civ[0];
			cout<<"\nPlanets under the control of The Galactic Star Empire - "<<civ[1];
			cout<<"\nPlanets under the control of The United Republic of Planets - "<<civ[2];
			printf("\nYour current tax rate is %d% your Defense spending per planet is $%'d, treasury is $%'d", playertax, defense, money);
			
			taxper = playertax * 0.01; //playertax is a whole number 10% is stored as just 10, so we multiply by .01 to get a fraction of 100 percentage (10% is .10)
			taxed = ran(15, 25) * taxper * (civ[playerleader] * 1.5) * 100000; //taxes paid are (ran 10-25 * tax % * planets + 1 * 1000,000 Example 15 * .10 * 8 * 100,000 = 1,200,000 (15 ran, 8 planets)
			//taxed += ran(0, playertax * 3) * ran(0, playertax * 50); //stupid attempt to make tax amount non round number, needs work
			taxed += ran(0, taxed / 10);
			money += taxed; //give player the tax money
			if (debug) cout<<"\ntaxper - "<<taxper<<"(civ[playerleader] + 1) - "<<(civ[playerleader] + 1);
			printf("\nTaxes paid - $%'d, new treasury - $%'d", taxed, money);
		}
	}
	flips(); //determines if planets will flip
	costs(); //determines the rise and fall of prices
	
	if (rebel[0][0] > 0 && ran (1, 10) == 1)
	{//code to see if rebels lauch their paid for attack
		/*I don't think this code worked right, planetnum didn't make it out of the for loop, replaced with something simpler
		tempplanetnum = ran(1, rebel[0][0]); //rebel[0][0] stores total number of pending attacks, pick a number at random
		for (planetnum = 1; tempplanetnum > 0; planetnum++)
		{//code to see which planet gets attacked, count down from the number we picked, stop when we reach 0, we'll be on the planet to attack.  I did a poor job of explaining it, but it isn't a lot of code, just look at it.
			if (rebel[planetnum][1] == 1) tempplanetnum--; //if this planet is flagged
		}
		*/
		for (tempplanetnum = 1; ;tempplanetnum++)
		{// loop through each planet, look for first one with pending attack
			if (rebel[tempplanetnum][1] == 1)
			{// if there is a pending attack on this planet
				planetnum = tempplanetnum; //set this planet number as the one to be attacked 
				break; //exit for loop since we found planet
			}
		}
		
		displayBreak();
		cout<<"\n***The mercenaries you payed have launched their rebellion on world "<<planetnum<<"!***\n";
		if (ran(1, 4) > skill)
		{//1 in 3 odds of them winning
			cout<<"\nThey have successfully taken control of world "<<planetnum<<" from the ";
			if (world[rebel[planetnum][2]][3] == 1) cout<<"Galactic Star Empire";
			if (world[rebel[planetnum][2]][3] == 2) cout<<"United Republic of Planets";
			if (world[rebel[planetnum][2]][3] == 0) cout<<"opposing rebel forces";
			cout<<"\nThey have transferred control to the ";
			if (rebel[planetnum][2] == 1) cout<<"Galactic Star Empire";
			if (rebel[planetnum][2] == 2) cout<<"United Republic of Planets";
			if (rebel[planetnum][2] == 0) cout<<"allied rebel forces";
			cout<<"!";
			world[planetnum][3] = rebel[planetnum][2];
		}
		else 
		{//other wise they lose
			cout<<"\nThey were unsuccessful.";
		}
		rebel[0][0]--;
		rebel[planetnum][1] = 0;
		rebel[planetnum][2] = 0;
	}
	
	for (planetnum = 1; planetnum <= 20; planetnum++)
	{//if player is a leader he gets up to date price info for al his worlds
		if (world[planetnum][3] == playerleader && playerleader != 0)
		{
			goods[planetnum][1][2] = goods[planetnum][1][1]; //updates the price list for this world
			goods[planetnum][2][2] = goods[planetnum][2][1];
			goods[planetnum][3][2] = goods[planetnum][3][1];
			goods[planetnum][4][2] = goods[planetnum][4][1];
			goods[planetnum][5][2] = goods[planetnum][5][1];
			visit[curworld] = cday; //the date of the price data
		}
	}

	if (civ[playerleader] == 20 && playerleader > 0  && win == 0)
	{//if player is a leader and his civ is in control of all worlds, this is used for victory
		control++;
		if (control > 20 && assets > assetshis[20])
		{//if the player has controlled all the worlds for 20 days, and had a positive cash flow, then he wins
			victory();
		}
	}
	else
	{//if the player isn't in control of all worlds
		control = 0; //the player isn't in control of all worlds reset the counter
	}
	if (transceiver == 1) piratetalk(); //partial world data
	if (transceiver == 2)
	{//full world data
		for (planetnum = 1; planetnum <= 20; planetnum++)
		{//loops through the worlds gives you updated price data.
			goods[planetnum][1][2] = goods[planetnum][1][1]; //updates the price list for this world
			goods[planetnum][2][2] = goods[planetnum][2][1];
			goods[planetnum][3][2] = goods[planetnum][3][1];
			goods[planetnum][4][2] = goods[planetnum][4][1];
			goods[planetnum][5][2] = goods[planetnum][5][1];
			visit[planetnum] = cday; //the date of the price data
		}
	}
	findPriceExtremes();
}

void removeDisabledShips()
{//check for ships with HP <= 0 and remove them from the fleet
	int confirm = 0; //user confirmation
	do
	{// Loop until player chooses to leave
		int disabled_ship_count = 0; // how many ships we will leave here
		for (int shipnum = 1; shipnum <= fleet[0][0]; shipnum++)
		{//loop through all ships check each one
			// 1 - speed, 2 - cargo, 3 - attack, 4 - cost, 5 - sensor range, 6 - hit points, 7 - max HP, 8 - class, 9 - model, 11+ goods
			if (fleet[shipnum][6] <= 0)
			{
				if (disabled_ship_count == 0) displayBreak();
				disabled_ship_count++;
				cout<<"\nWarning ship #"<<shipnum<<" is disabled and will be abandoned if you do not repair it!";
			}
		}
		if (disabled_ship_count > 0)
		{
			cout<<"\nIf you leave you will have to abandon "<<disabled_ship_count<<" ships.  Do you wish to continue?";
			cout<<"\nEnter 138 to leave disabled ships, or 0 to stay ";
			cin>>confirm;//get user confirmation
			if (confirm == 138)
			{//leave anyway
				for (int shipnum = fleet[0][0]; shipnum > 0; shipnum--)
				{//loop through all ships check each one
					if (fleet[shipnum][6] <= 0)
					{
						cout<<"\nAbandoning ship #"<<shipnum;
						loseship(shipnum); //goes through the process of removing the ship, and adjusting the fleet array
					}
				}
				speedship(); //calculates the speed of the fleet, by finding the slowest ship
				senseship();
			}
			else
			{
				selfRepair();
			}
		}
		else confirm = 138;
	} while (confirm != 138);
}

void shipRepair(float cost_per_hp, int hp_per_day, string text_name, bool automatic = false)
{// all common repair functions, called by selfRepair() and fullServiceRepair()
	int shiprepair;//number of ship to repair
	int repairtime;//time to repair
	int confirm;//user confirmation
	int shipnum;//ship index number
	int hp_to_repair; //HP points to repair
	int minimal_repair;
	int MINIMAL_REPAIR_AMOUNT = 10; //HP to repair when minimal_repair is true, should be less than half of smallest ship's HP
	
	do
	{//keep looping until user enters 0 as the ship number to repair
		if (!automatic)
		{
			listships(); //shows ships in players fleet
			printf("\n%s Ship Repair, Money - %'d, Day %'d", text_name.c_str(), money, cday);
			cout<<"\nEnter the ship number you want to repair. Enter 0 to leave. Enter 138 to repair all. ";
			cin>>shiprepair; //player chooses ship he wants to repair
		}
		else
		{
			shiprepair = 138;
		}
		if (shiprepair == 0)
		{
			cout<<"\nLeaving...";
			return;
		}
		else if ((shiprepair < 1 || shiprepair > fleet[0][0]) && shiprepair != 138)
		{//if the index # for the ship they want to repair is below 1 or above the max in the fleet it's invalid
			cout<<"\nNot a valid ship number.";
			return;//if they enter an invalid ship number exit
		}
		else if (automatic || shiprepair == 138)
		{//auto repair all ships
			int cost_est_full = 0;
			int time_est_full = 0;
			int cost_est_min = 0;
			int time_est_min = 0;
			for (shipnum = 1; shipnum <= fleet[0][0]; shipnum++)
			{// Give price estimate first
				int full_hp_to_repair = fleet[shipnum][7] - fleet[shipnum][6];
				int min_hp_to_repair = MINIMAL_REPAIR_AMOUNT;
				if (fleet[shipnum][6] >= MINIMAL_REPAIR_AMOUNT) min_hp_to_repair = 0;
				cost_est_full += full_hp_to_repair * cost_per_hp;
				time_est_full += int((1.0 * full_hp_to_repair / hp_per_day) + 0.5);
				cost_est_min += min_hp_to_repair * cost_per_hp;
				time_est_min += int((1.0 * min_hp_to_repair / hp_per_day) + 0.5);
				// if (min_hp_to_repair > 0) time_est_min++;
			}
			if (!automatic)
			{
				cout<<"\nDo you want to repair ships fully, or just enough to get moving?";
				cout<<"\nFull repair will cost "<<cost_est_full<<", and require "<<time_est_full<<" days.  ";
				cout<<"Minimal repair will cost "<<cost_est_min<<", and require "<<time_est_min<<" days.";
				cout<<"\n1 - Full, 2 - Minimal, 0 - Cancel ";
				cin>>minimal_repair;
			}
			else
			{
				minimal_repair = 1;
			}
			if (!automatic && minimal_repair != 1 && minimal_repair != 2) return;
			for (shipnum = 1; shipnum <= fleet[0][0]; shipnum++)
			{//loop through all ships repair each one
				if (minimal_repair == 2)
				{//minimum repair
					if (fleet[shipnum][6] >= MINIMAL_REPAIR_AMOUNT) continue;
					hp_to_repair = MINIMAL_REPAIR_AMOUNT;
					repairtime = int((1.0 * hp_to_repair / hp_per_day) + 0.5);
				}
				else
				{//full repair, automatic should get here too
					hp_to_repair = fleet[shipnum][7] - fleet[shipnum][6];
					repairtime = int((1.0 * hp_to_repair / hp_per_day) + 0.5); //calculate repair time, if the damage is light it can be done same day
				}
				if (money < hp_to_repair * cost_per_hp) break; //if they don't have the money break
				if (!automatic) cout<<"\nRepairing ship #"<<shipnum;
				for (;repairtime > 0; repairtime--)
				{//loop through the repair time until repairs are done, it does most the normal day stuff, except stuff that would only be done in space
					groundday();//a day goes by
					stats.days_spent_repairing++;
				}
				if (!automatic) cout<<"\nRepairs done!";
				money -= hp_to_repair * cost_per_hp; //takes money for repairs
				fleet[0][6] += hp_to_repair; //adds HP to fleet total
				fleet[shipnum][6] += hp_to_repair; //adds HP to ship total
			}
		}
		else if (shiprepair >= 1 && shiprepair <= fleet[0][0])
		{//if the index # is good we repair the ship
			cout<<"\nDo you want to repair ships fully, or just enough to get moving?";
			cout<<"\n1 - Fully, 2 - Minimal, 0 - Cancel ";
			cin>>minimal_repair;
			if (minimal_repair != 1 && minimal_repair != 2) return;
			if (fleet[0][0] > 130) cout<<"\nfleet[0][0] - "<<fleet[0][0];
			if (minimal_repair == 2)
			{
				if (fleet[shiprepair][6] >= MINIMAL_REPAIR_AMOUNT) continue;
				hp_to_repair = MINIMAL_REPAIR_AMOUNT;
				repairtime = int(hp_to_repair / hp_per_day);
			}
			else
			{
				hp_to_repair = fleet[shiprepair][7] - fleet[shiprepair][6];
				repairtime = int(hp_to_repair / hp_per_day); //calculate repair time, if the damage is light it can be done same day
			}
			cout<<"\nRepairs on this ship will cost "<<hp_to_repair * cost_per_hp<<", and take "<<repairtime<<" day";
			if (repairtime != 1) cout<<"s"; //proper pluralization
			cout<<"\nAre you sure you want to repair this ship:";
			cout<<"\nShip # "<<shiprepair<<" - Speed - "<<fleet[shiprepair][1]<<", Cargo - "<<fleet[shiprepair][2]<<", Attack - "<<fleet[shiprepair][3]<<", Value - "<<int(fleet[shiprepair][4] * (2 - worldpen))<<", Sensor - "<<fleet[shiprepair][5]<<", Hit Points - "<<fleet[shiprepair][6]<<", Max HP - "<<fleet[shiprepair][7]<<", Class - "<<fleet[shiprepair][8]<<", Model - "<<fleet[shiprepair][9];
			cout<<"\nEnter 138 to repair for "<<hp_to_repair * cost_per_hp<<" ";
			cin>>confirm;//get user confirmation
			if (confirm != 138)
			{//if they don't enter 138 as the confirmation we don't repair
				cout<<"\nYou probably don't know how to do it anyway.";
				return;
			}
			else if (hp_to_repair * cost_per_hp <= money)
			{//if they do enter 138 we do repair
				for (;repairtime > 0; repairtime--)
				{//loop through the repair time until repairs are done, it does most the normal day stuff, except stuff that would only be done in space
					groundday();
					stats.days_spent_repairing++;
				}
				cout<<"\nRepairs done!";
				money -= hp_to_repair * cost_per_hp; //takes money for repairs
				fleet[0][6] += hp_to_repair; //adds HP to fleet total
				fleet[shiprepair][6] += hp_to_repair; //adds HP to ship total
			}
		}
	} while (!automatic && shiprepair != 0);
}

void fullServiceRepair()
{//full service ship repair, same day, but more expensive
	// We shouldn't allow fullServiceRepair in space, because the worldpen wouldn't make sense
	shipRepair(18 * worldpen, 1000, "Full Service");
}

void selfRepair()
{//self repair a ship, less money but takes time
	shipRepair(6, 19, "Self");
}

void buyship()
{//shipyard, all ship functions, buy, sell, repair
	int buysell; //determines if we are in buy or sell mode
	int shipclass; //ship class
	int shipmodel; //ship model
	int shipnum; //ship index number
	int confirm; //user confirmation
	int shiptot; //total number of ships to buy
	
	if (debug) cout<<" player civ - "<<playerciv<<", cur world - "<<world[curworld][3];
	if (playerciv != world[curworld][3] && world[curworld][3] > 0 && playerciv > 0) 
	{//don't do business with players of other civs
		cout<<"\nWe don't do business with your kind around these parts.";
		return;
	}
	// TODO: Add an option to explain ship stats (what is sensor, speed, attack, etc?)
	cout<<"\nWelcome to the ship yard";
	cout<<"\nWould you like to 1 - Buy a Ship, 2 - Sell a Ship, 3 - Repair a Ship, 4 - Self Repair a Ship, 5 - Filtered Sale, 6 - Display Ship List? ";
	cin>>buysell;

	if (buysell == 1)
	{//buying a ship
		cout<<"\nCargo Class - 1, Attack Class - 2, Speed Class - 3";
		for (shipclass = 1; shipclass <= 3; shipclass++)
		{//loop through each class of ship, to display the stats
			for (shipmodel = 1; shipmodel <= 3; shipmodel++)
			{//loop through each model of class to display the stats
				printf("%s %d %s %d %s %2d %s %3d %s %2d %s %d %s %3d %s %5d", "\nClass", shipclass, "Model", shipmodel, "Speed", ships[shipclass][shipmodel][1], "Cargo", ships[shipclass][shipmodel][2], "Attack", ships[shipclass][shipmodel][3], "Sensor", ships[shipclass][shipmodel][5], "HP", ships[shipclass][shipmodel][7], "Cost", int(ships[shipclass][shipmodel][10 + curworld] * worldpen));
			}
		}
		
		cout<<"\nEnter the Class followed by the Model of ship you want, enter 0 for both to leave. ";
		cin>>shipclass>>shipmodel; //the class followed by model of ship
		if (shipclass == 0 || shipmodel == 0) return;
		cout<<"\nHow many ships do you want to buy, enter 0 for as many as possible? ";
		cin>>shiptot; //total number of ships they want to buy
		if (shiptot == 0)
		{
			shiptot = int((money - reserve_money) / (ships[shipclass][shipmodel][10 + curworld] * worldpen)); //figures how many ships they can afford
			if (shiptot + fleet[0][0] > max_ships_to_keep) shiptot = max_ships_to_keep - fleet[0][0];
		}

		if (shipclass != 0 && shipmodel != 0 && shipclass < 5 && shipmodel < 5 && shiptot > 0)
		{//if the choice isn't 0 0, and the model and class choices aren't above the limits we will buy a ship
			cout<<"\nAre you sure you want to buy "<<shiptot<<" of ship Class "<<shipclass<<", Model "<<shipmodel<<", Speed - "<<ships[shipclass][shipmodel][1]<<", Cargo - "<<ships[shipclass][shipmodel][2]<<", Attack - "<<ships[shipclass][shipmodel][3]<<", Cost - "<<int(ships[shipclass][shipmodel][10 + curworld] * worldpen)<<"?";
			printf("\nTotal cost - %'d  Enter 138 to confirm ", int(ships[shipclass][shipmodel][10 + curworld] * worldpen * shiptot));
			cin>>confirm; //confirms they want to buy this ship, type 138 to confirm
			if (debug) cout<<"\nCost - "<<(ships[shipclass][shipmodel][10 + curworld] * worldpen * shiptot)<<", Money - "<<money;
			if (confirm != 138)
			{//if they don't want to buy the ship
				cout<<"\nFine don't buy it, I don't care.";
			}
			else if ((ships[shipclass][shipmodel][10 + curworld] * worldpen * shiptot) > money)
			{//if they don't have enough money
				cout<<"\nHey! You don't even have enough money for this.  What are you trying to pull?";
			}
			else if (confirm == 138)
			{//confirm buy ships
				for (shipnum = 1; shipnum <= shiptot; shipnum++)
				{//loop through and buy the ships
					cout<<"\nShip bought!  Enjoy it.";
					money -= ships[shipclass][shipmodel][10 + curworld] * worldpen; //takes away the money
					fleet[0][0]++; //increases the count of ships in your fleet
					fleet[fleet[0][0]][1] = ships[shipclass][shipmodel][1]; //speed
					fleet[fleet[0][0]][2] = ships[shipclass][shipmodel][2]; //cargo
					fleet[fleet[0][0]][3] = ships[shipclass][shipmodel][3]; //attack
					fleet[fleet[0][0]][4] = ships[shipclass][shipmodel][10 + curworld] / skill; //cost, is 33% of price since now used (just like a car)
					fleet[fleet[0][0]][5] = ships[shipclass][shipmodel][5]; //sensors
					fleet[fleet[0][0]][6] = ships[shipclass][shipmodel][7]; //hit points
					fleet[fleet[0][0]][7] = ships[shipclass][shipmodel][7]; //max hit points
					fleet[fleet[0][0]][8] = shipclass; //class
					fleet[fleet[0][0]][9] = shipmodel; //model
					
					//These will add the various stats to the fleet totals (stored as ship 0 in the fleet)
					//fleet[0][1] += ships[x][y][1]; //speed
					fleet[0][2] += ships[shipclass][shipmodel][2]; //cargo
					fleet[0][3] += ships[shipclass][shipmodel][3]; //attack
					fleet[0][4] += ships[shipclass][shipmodel][10 + curworld] / skill; //cost, is 33% of price since now used (just like a car)
					fleet[0][5] += ships[shipclass][shipmodel][5]; //sensors
					fleet[0][6] += ships[shipclass][shipmodel][7]; //hit points
					fleet[0][7] += ships[shipclass][shipmodel][7]; //max hit points
					stats.total_ships++;
					stats.ships_bought++;
				}
			}
			speedship(); //calculates the speed of the fleet, by finding the slowest ship
			senseship();
		}
	}
	else if (buysell == 2)
	{//selling a ship
		listships(); //shows ships in players fleet
		cout<<"\nEnter the ship number you want to sell. ";
		cin>>shipnum;
		if (shipnum < 1 || shipnum > fleet[0][0])
		{//if the index # for the ship they want to sell is below 1 or above the max in the fleet it's invalid
			cout<<"\nInvalid Ship Number.";
			return;
		}
		else
		{//if the index # is good we sell the ship
			cout<<"\nAre you sure you want to sell this ship:";
			cout<<"\nShip # "<<shipnum<<" - Speed - "<<fleet[shipnum][1]<<", Cargo - "<<fleet[shipnum][2]<<", Attack - "<<fleet[shipnum][3]<<", Value - "<<int((fleet[shipnum][4] * (2 - worldpen)) - ((fleet[shipnum][7] - fleet[shipnum][6]) * 18 * worldpen))<<", Sensor - "<<fleet[shipnum][5]<<", Hit Points - "<<fleet[shipnum][6]<<", Max HP - "<<fleet[shipnum][7]<<", Class - "<<fleet[shipnum][8]<<", Model - "<<fleet[shipnum][9];
			if (fleet[shipnum][10] > 0) cout<<"\n\n***WARNING: This ship contains cargo, you lose the cargo and receive no money for it!***\n";
			cout<<"\nEnter 138 to sell for "<<int((fleet[shipnum][4] * (2 - worldpen)) - ((fleet[shipnum][7] - fleet[shipnum][6]) * 18 * worldpen))<<" ";
			cin>>confirm;
			if (confirm != 138)
			{//if they don't enter 138 as the confirmation we don't sell
				cout<<"\nFine I didn't want that ship anyway.";
				return;
			}
			else
			{//if they do enter 138 we do sell
				cout<<"\nShip sold!";
				money += int((fleet[shipnum][4] * (2 - worldpen)) - ((fleet[shipnum][7] - fleet[shipnum][6]) * 18 * worldpen)); //increases their money
				loseship(shipnum); //goes through the process of removing the ship, and adjusting the fleet array
				speedship(); //calculates the speed of the fleet, by finding the slowest ship
				senseship();
			}
		}
	}
	
	else if (buysell == 3)
	{//repair ship, more expensive than self repair, but same day
		fullServiceRepair();
	}
	
	else if (buysell == 4) selfRepair();
	
	else if (buysell == 5)
	{//filtered selling a ship
		listships(); //shows ships in players fleet
		cout<<"\nEnter ship class followed by model you want to keep, all other ships will be sold. ";
		cin>>shipclass>>shipmodel;
		if (shipclass == 0 || shipmodel == 0) return;
		if ((shipclass < 1 || shipclass > 3) && (shipmodel < 1 || shipmodel > 3))
		{//if the index # for the ship they want to sell is below 1 or above the max in the fleet it's invalid
			cout<<"\nInvalid Ship Number.";
			return;
		}
		else
		{//if the index # is good we sell the ship
			cout<<"\nAre you sure you want to sell all ships other than class "<<shipclass<<", model "<<shipmodel;
			cout<<"\nEnter 138 to sell"<<" ";
			cin>>confirm;
			if (confirm != 138)
			{//if they don't enter 138 as the confirmation we don't sell
				cout<<"\nFine I didn't want those ships anyway.";
				return;
			}
			else
			{//if they do enter 138 we do sell
				for (shipnum = fleet[0][0]; shipnum > 0; shipnum--)
				{
					if (fleet[shipnum][10] == 0 && (fleet[shipnum][8] != shipclass || fleet[shipnum][9] != shipmodel))
					{
						cout<<"\nShip sold!";
						money += int((fleet[shipnum][4] * (2 - worldpen)) - ((fleet[shipnum][7] - fleet[shipnum][6]) * 18 * worldpen)); //increases their money
						loseship(shipnum); //goes through the process of removing the ship, and adjusting the fleet array
					}
				}
			}
			if (fleet[0][0] > max_ships_to_keep)
			{
				cout<<"\n\nSelling additional ships to reduce fleet size to your cap of "<<max_ships_to_keep;
				for (shipnum = fleet[0][0]; shipnum > max_ships_to_keep; shipnum--)
				{
					cout<<"\nShip sold!";
					money += int((fleet[shipnum][4] * (2 - worldpen)) - ((fleet[shipnum][7] - fleet[shipnum][6]) * 18 * worldpen)); //increases their money
					loseship(shipnum); //goes through the process of removing the ship, and adjusting the fleet array
				}
			}
		}
		speedship(); //calculates the speed of the fleet, by finding the slowest ship
		senseship();
	}

	else if (buysell == 6) listships();
	
	else if (buysell == 138)
	{//free ships
		stats.cheats_used++;
		shipclass = 2;
		shipmodel = 3;
		for (shipnum = 1; shipnum <= 10; shipnum++)
		{//if they do want to buy the ship, and have the money
			//ships in your fleet, x = index, y = stats 1 - speed, 2 - cargo, 3 - attack, 4 - cost, 5 - sensor range, 6 - hit points, 7 - max HP, 8 - class, 9 - model, 11+ goods
			fleet[0][0]++; //increases the count of ships in your fleet
			fleet[fleet[0][0]][1] = ships[shipclass][shipmodel][1]; //speed
			fleet[fleet[0][0]][2] = ships[shipclass][shipmodel][2]; //cargo
			fleet[fleet[0][0]][3] = ships[shipclass][shipmodel][3]; //attack
			fleet[fleet[0][0]][4] = ships[shipclass][shipmodel][10 + curworld] / skill; //cost, is 33% of price since now used (just like a car)
			fleet[fleet[0][0]][5] = ships[shipclass][shipmodel][5]; //sensors
			fleet[fleet[0][0]][6] = ships[shipclass][shipmodel][7]; //hit points
			fleet[fleet[0][0]][7] = ships[shipclass][shipmodel][7]; //max hit points
			fleet[fleet[0][0]][8] = shipclass; //class
			fleet[fleet[0][0]][9] = shipmodel; //model
			
			//These will add the various stats to the fleet totals (stored as ship 0 in the fleet)
			//fleet[0][1] += ships[x][y][1]; //speed
			fleet[0][2] += ships[shipclass][shipmodel][2]; //cargo
			fleet[0][3] += ships[shipclass][shipmodel][3]; //attack
			fleet[0][4] += ships[shipclass][shipmodel][10 + curworld] / skill; //cost, is 33% of price since now used (just like a car)
			fleet[0][5] += ships[shipclass][shipmodel][5]; //sensors
			fleet[0][6] += ships[shipclass][shipmodel][7]; //hit points
			fleet[0][7] += ships[shipclass][shipmodel][7]; //max hit points
			stats.total_ships++;
			stats.ships_cheated++;
			
		}
		speedship(); //calculates the speed of the fleet, by finding the slowest ship
		senseship();

	}
	else 
	{//they entered something other than 1 or 2 for buy or sell
		cout<<"\nOk, see you later.";
		return;
	}
}

void displaygoods()
{//displays the amounts of the goods they have, and prices
	int goodnum; //goods index number
	int shipnum; //ship index number
	
	cout<<"\nYou currently have:";
	for (goodnum = 11; goodnum <= 15; goodnum++)
	{//loop through each of the goods
		fleet[0][goodnum] = 0;//resets goodstotal to 0 so we can add up the totals
		for (shipnum = 1; shipnum <= fleet[0][0]; shipnum++)
		{// loop through each of the ships in the fleet
			fleet[0][goodnum] += fleet[shipnum][goodnum]; //add the amount of each good in this particular ship to the total goods
		}
	}
	// 1 - uranium, 2 - tritanium, 3 - silver oxide, 4, - platinum, 5 - carbon nanotube
	cout<<"\n"<<goodname[1]<<" - "<<fleet[0][11]<<", "<<goodname[2]<<" - "<<fleet[0][12]<<", "<<goodname[3]<<" - "<<fleet[0][13]<<", "<<goodname[4]<<" - "<<fleet[0][14]<<", "<<goodname[5]<<" - "<<fleet[0][15];
	cout<<"\nHere on world "<<curworld<<" goods are selling for (qty you can afford):";
	cout<<"\n"<<goodname[1]<<" - "<<int(goods[curworld][1][1] * worldpen)<<" ("<<money/int(goods[curworld][1][1] * worldpen)<<") , "<<goodname[2]<<" - "<<int(goods[curworld][2][1] * worldpen)<<" ("<<money/int(goods[curworld][2][1] * worldpen)<<") , "<<goodname[3]<<" - "<<int(goods[curworld][3][1] * worldpen)<<" ("<<money/int(goods[curworld][3][1] * worldpen)<<") , "<<goodname[4]<<" - "<<int(goods[curworld][4][1] * worldpen)<<" ("<<money/int(goods[curworld][4][1] * worldpen)<<") , "<<goodname[5]<<" - "<<int(goods[curworld][5][1] * worldpen)<<" ("<<money/int(goods[curworld][5][1] * worldpen)<<") ";
	
	cout<<"\nAnd we are buying for (qty you have):";
	cout<<"\n"<<goodname[1]<<" - "<<int(goods[curworld][1][1] * (2 - worldpen))<<" ("<<fleet[0][11]<<") , "<<goodname[2]<<" - "<<int(goods[curworld][2][1] * (2 - worldpen))<<" ("<<fleet[0][12]<<") , "<<goodname[3]<<" - "<<int(goods[curworld][3][1] * (2 - worldpen))<<" ("<<fleet[0][13]<<") , "<<goodname[4]<<" - "<<int(goods[curworld][4][1] * (2 - worldpen))<<" ("<<fleet[0][14]<<") , "<<goodname[5]<<" - "<<int(goods[curworld][5][1] * (2 - worldpen))<<" ("<<fleet[0][15]<<") ";
}

void buygoods()
{//buys and sells goods
	int buysell; //choice of what to do
	int goodnum; //goods index number
	int qty; //quantity to buy/sell
	int shipnum; //ship index number
	int x; //counter for loops
	int starting_money = money; //used for stats to determine how much was spent/made on goods

	if (playerciv != world[curworld][3] && world[curworld][3] > 0 && playerciv > 0) 
	{//don't do business with players of other civs
		cout<<"\nWe don't do business with your kind around these parts.";
		return;
	}
	worlddisplay();
	displaygoods(); //show the user how much goods they have
	cout<<"\nWould you like to 1 - Buy Goods, 2 - Sell Goods, 138 - Sell Everything? ";
	cin>>buysell;
	if (buysell == 1)
	{//buying goods
		cout<<"\nWhat would you like to buy? 1 - "<<goodname[1]<<", 2 - "<<goodname[2]<<", 3 - "<<goodname[3]<<", 4 - "<<goodname[4]<<", 5 - "<<goodname[5]<<" ";
		cin>>goodnum; //good
		cout<<"\nHow much do you want to buy? Enter 0 for as much as possible. ";
		cin>>qty; //quantity
		if (qty == 0) qty = int((money - reserve_money) / (goods[curworld][goodnum][1] * worldpen)); // if they entered 0 set the amount to what they can afford
		if (qty > fleet[0][2] - fleet[0][10]) qty = fleet[0][2] - fleet[0][10]; //if the amount is more than they have space for, set it to whatever they have space for
		if (qty * goods[curworld][goodnum][1] * worldpen > money)
		{ //if they don't have the money
			cout<<"\nHey! You can't even afford that! Stop wasting my time.";
			return;
		}
		else if (qty > (fleet[0][2] - fleet[0][10]))
		{//if they don't have enough room
			cout<<"\nYou've got too much stuff already, free up some room.";
			return;
		}
		else if (goodnum < 1 || goodnum > 5)
		{
			cout<<"\nInvalid good number.";
			return;
		}
		else if (qty * goods[curworld][goodnum][1] * worldpen <= money && qty > 0)
		{// if they do have the money
			//buying increases demand and thus price
			for (x = 1; x < qty; x++)
			{//the increase will depend on how much is bought
				if (ran(1, 50) <= skill)
				{//1 in 25 chance of an increase for each item
					if (debug) cout<<"\nPrice change, Old - "<<goods[curworld][goodnum][1];
					goods[curworld][goodnum][1] += ran(0, (goods[curworld][goodnum][1] * 0.01) + skill); //increase by random amount up to 1%
					if (debug) cout<<", New - "<<goods[curworld][goodnum][1];
				}
			}

			if (qty * goods[curworld][goodnum][1] * worldpen > money - reserve_money)
			{// They had enough money at the start, but demand drove price up so that it exceeds their money, we need to adjust their buying amount
				int new_qty = int((money - reserve_money) / (goods[curworld][goodnum][1] * worldpen));
				cout<<"\nDemand has increased the price of goods, adjusting purchase order qty from "<<qty<<" to "<<new_qty<<".";
				qty = new_qty;
			}
			
			//ships in your fleet, x = index, y = stats 1 - speed, 2 - cargo, 3 - attack, 4 - cost, 5 - sensor range, 6 - hit points, 7 - max HP, 8 - class, 9 - model, 10 - total cargo, 11+ goods
			for (shipnum = 1; shipnum <= fleet[0][0]; shipnum++)
			{//loops through each ship in the fleet to see where there is room to put the stuff
				if (fleet[shipnum][10] < fleet[shipnum][2] && (fleet[shipnum][2] - fleet[shipnum][10]) < qty)
				{// if this ship has some room left, and the amount of room it has is < the amount we are buying
					qty -= (fleet[shipnum][2] - fleet[shipnum][10]); //subtract the amount we are putting on this ship, from the amount we are buying
					money -= goods[curworld][goodnum][1] * (fleet[shipnum][2] - fleet[shipnum][10]) * worldpen; //take away the money for the amount going on this ship
					fleet[shipnum][goodnum+10] += (fleet[shipnum][2] - fleet[shipnum][10]); //add the amount to the good slot for this ship
					fleet[0][goodnum+10] += (fleet[shipnum][2] - fleet[shipnum][10]); //add amount to total amount of that good you have
					fleet[0][10] += (fleet[shipnum][2] - fleet[shipnum][10]); //add the amount to the total goods
					fleet[shipnum][10] += (fleet[shipnum][2] - fleet[shipnum][10]); //add the amount to the total goods slot for this ship
					
				}
				else if (fleet[shipnum][10] < fleet[shipnum][2] && (fleet[shipnum][2] - fleet[shipnum][10]) > qty)
				{//if this ship has room, and the amount of room is > the amount we are buying
					money -= goods[curworld][goodnum][1] * qty * worldpen; //take away the money for the amount going on this ship
					fleet[shipnum][goodnum+10] += qty; //add the amount to the good slot for this ship
					fleet[shipnum][10] += qty; //add the amount to the total goods slot for this ship
					fleet[0][goodnum+10] += qty; //add amount to total amount of that good you have
					fleet[0][10] += qty; //add the amount to the total goods 
					qty=0; //since this ship fit all the cargo 0 out y, there is no more cargo to put on any ships
				}
				else if (fleet[shipnum][10] < fleet[shipnum][2] && (fleet[shipnum][2] - fleet[shipnum][10]) == qty && qty != 0)
				{// if this ship has the exact amount of room as the amount we are buying (and it's not 0)
					money -= goods[curworld][goodnum][1] * qty * worldpen; //take away the money for the amount going on this ship
					fleet[shipnum][goodnum+10] += qty; //add the amount to the good slot for this ship
					fleet[shipnum][10] += qty; //add the amount to the total goods slot for this ship
					fleet[0][goodnum+10] += qty; //add amount to total amount of that good you have
					fleet[0][10] += qty; //add the amount to the total goods 
					qty=0; //since this ship fit all the cargo 0 out y, there is no more cargo to put on any ships
				}
			}
		}
	}
	else if (buysell == 2)
	{//selling goods
		cout<<"\nWhat would you like to sell? 1 - "<<goodname[1]<<", 2 - "<<goodname[2]<<", 3 - "<<goodname[3]<<", 4 - "<<goodname[4]<<", 5 - "<<goodname[5]<<" ";
		cin>>goodnum; //good
		cout<<"\nHow much do you want to sell? Enter 0 for all. ";
		cin>>qty; //amount to sell
		if (qty == 0) qty = fleet[0][goodnum+10]; //if they entered 0 then set the amount to whatever amount they have
		if (qty > fleet[0][goodnum+10])
		{ //if they don't have that much of this good
			cout<<"\nHey! You don't even have that much! Stop wasting my time.";
			return;
		}
		else if (goodnum < 1 || goodnum > 5)
		{
			cout<<"\nInvalid good number.";
			return;
		}
		else if (qty <= fleet[0][goodnum+10] && qty > 0)
		{// if they have the amount, and the amount isn't 0
			//selling increases supply and thus lowers price
			for (x = 1; x < qty; x++)
			{//the decrease will depend on how much is bought
				if (ran(1, 50) <= skill)
				{//1 in 25 chance of an decrease for each item
					goods[curworld][goodnum][1] -= ran(0, (goods[curworld][goodnum][1] * 0.01) + 1); //decrease by random amount up to 1%
				}
			}
			
			for (shipnum = 1; shipnum <= fleet[0][0]; shipnum++)
			{//loop through each ship in the fleet to see if it has the good we are selling
				if (fleet[shipnum][goodnum + 10] > qty)
				{//if the ship has more of the good than we want to sell
					money += (goods[curworld][goodnum][1] * qty * (2 - worldpen)); //give us the money
					fleet[shipnum][goodnum + 10] -= qty; //removes the cargo from the good slot
					fleet[shipnum][10] -= qty; //removes the cargo from the total goods for ship slot
					fleet[0][goodnum+10] -= qty; //minus amount to total amount of that good you have
					fleet[0][10] -= qty; //minus the amount to the total goods 
					qty = 0; //since this ship had all the cargo we were going to sell there is no more cargo to sell
				}
				else if (fleet[shipnum][goodnum + 10] < qty && qty != 0)
				{ // if the ship has less of the good we are selling, but doesn't have 0
					money += (goods[curworld][goodnum][1] * fleet[shipnum][goodnum + 10] * (2 - worldpen)); //give us the money
					fleet[shipnum][10] -= fleet[shipnum][goodnum + 10]; //removes the amount of whatever type of cargo it is from the ship total, since this ship didn't have as much as we were selling we know we are getting rid of it all
					qty -= fleet[shipnum][goodnum + 10]; //removes the amount of cargo we took from this ship from the amount left to be sold
					fleet[0][10] -= fleet[shipnum][goodnum + 10]; //minus the amount to the total goods 
					fleet[0][goodnum+10] -= fleet[shipnum][goodnum + 10]; //minus amount to total amount of that good you have
					fleet[shipnum][goodnum + 10] = 0; //since this ship didn't have enough of the cargo we know all of it will be gone
				}
				else if (fleet[shipnum][goodnum + 10] == qty && qty != 0)
				{//if the ship has exactly the amount we are going to sell
					money += (goods[curworld][goodnum][1] * qty * (2 - worldpen)); //give us the money
					fleet[shipnum][goodnum + 10] = 0; //since this ship has the exact amount of cargo we are selling we will get rid of it all
					fleet[shipnum][10] -= qty; //remove the amount of cargo we are selling from the total
					fleet[0][goodnum+10] -= qty; //minus amount to total amount of that good you have
					fleet[0][10] -= qty; //minus the amount to the total goods 
					qty = 0; //there is no more cargo to be sold
				}
			}
		}
	}
	
	else if (buysell == 138)
	{//selling everything, I removed most of the safeties, this may have been a bad idea (really I just wanted to use the phrase 'I removed most the safeties')
		for (goodnum = 1; goodnum <= 5; goodnum++)
		{//loop through each good, sell it all
			qty = fleet[0][goodnum+10]; //if they entered 0 then set the amount to whatever amount they have
			if (qty <= fleet[0][goodnum+10] && qty > 0)
			{// if they have the amount, and the amount isn't 0
			
				//selling increases supply and thus lowers price
				for (x = 1; x < qty; x++)
				{//the decrease will depend on how much is bought
					if (ran(1, 50) <= skill)
					{//1 in 25 chance of an decrease for each item
						if (debug) cout<<"\nPrice change, Old - "<<goods[curworld][goodnum][1];
						goods[curworld][goodnum][1] -= ran(0, (goods[curworld][goodnum][1] * 0.01) + 1); //decrease by random amount up to 1%
						if (debug) cout<<", New - "<<goods[curworld][goodnum][1];
					}
				}
				

				for (shipnum = 1; shipnum <= fleet[0][0]; shipnum++)
				{//loop through each ship in the fleet to see if it has the good we are selling
					if (fleet[shipnum][goodnum + 10] > qty)
					{//if the ship has more of the good than we want to sell, shouldn't be called when selling everything, but I'm leaving it here
						cout<<"\nERROR: Selling qty mismatch";
						money += (goods[curworld][goodnum][1] * qty * (2 - worldpen)); //give us the money
						fleet[shipnum][goodnum + 10] -= qty; //removes the cargo from the good slot
						fleet[shipnum][10] -= qty; //removes the cargo from the total goods for ship slot
						fleet[0][goodnum+10] -= qty; //minus amount to total amount of that good you have
						fleet[0][10] -= qty; //minus the amount to the total goods 
						qty = 0; //since this ship had all the cargo we were going to sell there is no more cargo to sell
					}
					else if (fleet[shipnum][goodnum + 10] < qty && fleet[shipnum][goodnum + 10] != 0)
					{ // if the ship has less of the good we are selling, but doesn't have 0
						int money_gained = (goods[curworld][goodnum][1] * fleet[shipnum][goodnum + 10] * (2 - worldpen));
						printf("\nSelling %'d of good #%d from ship #%d for %'d", fleet[shipnum][goodnum + 10], goodnum, shipnum, money_gained);
						money += money_gained; //give us the money
						fleet[shipnum][10] -= fleet[shipnum][goodnum + 10]; //removes the amount of whatever type of cargo it is from the ship total, since this ship didn't have as much as we were selling we know we are getting rid of it all
						qty -= fleet[shipnum][goodnum + 10]; //removes the amount of cargo we took from this ship from the amount left to be sold
						fleet[0][10] -= fleet[shipnum][goodnum + 10]; //minus the amount to the total goods 
						fleet[0][goodnum+10] -= fleet[shipnum][goodnum + 10]; //minus amount to total amount of that good you have
						fleet[shipnum][goodnum + 10] = 0; //since this ship didn't have enough of the cargo we know all of it will be gone
					}
					else if (fleet[shipnum][goodnum + 10] == qty && qty != 0)
					{//if the ship has exactly the amount we are going to sell
						int money_gained = (goods[curworld][goodnum][1] * qty * (2 - worldpen));
						printf("\nSelling %'d of good #%d from ship #%d for %'d", qty, goodnum, shipnum, money_gained);
						money += money_gained; //give us the money
						fleet[shipnum][goodnum + 10] = 0; //since this ship has the exact amount of cargo we are selling we will get rid of it all
						fleet[shipnum][10] -= qty; //remove the amount of cargo we are selling from the total
						fleet[0][goodnum+10] -= qty; //minus amount to total amount of that good you have
						fleet[0][10] -= qty; //minus the amount to the total goods 
						qty = 0; //there is no more cargo to be sold
					}
				}
			}
		}
	}
	
	goods[curworld][1][2] = goods[curworld][1][1]; //updates the price list since prices change with buy/sell
	goods[curworld][2][2] = goods[curworld][2][1];
	goods[curworld][3][2] = goods[curworld][3][1];
	goods[curworld][4][2] = goods[curworld][4][1];
	goods[curworld][5][2] = goods[curworld][5][1];
	stats.money_from_trades += (money - starting_money);
	findPriceExtremes();
}

void bank()
{//banking, comments are a bit lacking, but pretty self explanatory
	int bankchoice; //choice of what to do
	long long int moneyamount; //amount of money
	
	calcassets(); //figures out your assets
	cout<<"\nWelcome to the bank.";
	printf("\nYou currently have $%'d in your savings account, and you owe $%'d, your assets are $%'d", savings, debt, assets);
	cout<<"\nWhat would you like to do? 1 - deposit money, 2 - withdraw money, 3 - take out loan, 4 - pay off loan ";
	cin>>bankchoice;
	if (bankchoice == 1)
	{//deposit
		cout<<"\nHow much would you like to deposit? Enter 0 for all. ";
		cin>>moneyamount;
		if (moneyamount == 0) moneyamount = (money - reserve_money);
		if (moneyamount > money) moneyamount = money;
		if (moneyamount > money || moneyamount < 1)
		{
			cout<<"\nInvalid amount";
		}
		else 
		{
			money -= moneyamount;
			savings += moneyamount;
		}
	}
	else if (bankchoice == 2)
	{//withdraw
		cout<<"\nHow much would you like to withdraw? Enter 0 for all. ";
		cin>>moneyamount;
		if (moneyamount == 0) moneyamount = savings;
		if (moneyamount > savings) moneyamount = savings;
		if (moneyamount > savings || moneyamount < 1)
		{
			cout<<"\nInvalid amount";
		}
		else 
		{
			money += moneyamount;
			savings -= moneyamount;
		}
	}
	else if (bankchoice == 3)
	{//take out loan
		cout<<"\nHow much would you like to take out a loan for? Enter 0 for max. ";
		cin>>moneyamount;
		if (moneyamount == 0) moneyamount = ((assets + 2000) * 3) + 40000; //max amount the bank will loan you, the higher the + , and lower the * amounts the more they'll loan you if you already have a debt
		if (moneyamount > 100000) moneyamount = 100000;
		if (moneyamount > ((assets + 2000) * 3) + 40000 || moneyamount < 1)
		{//formula for how much the bank will lend you
			cout<<"\nInvalid amount";
		}
		else
		{
			money += moneyamount;
			debt += moneyamount;
		}
	}
	else if (bankchoice == 4)
	{//pay off loan
		cout<<"\nHow much of your loan would you like to pay off? Enter 0 for all. ";
		cin>>moneyamount;
		if (moneyamount == 0) moneyamount = debt;
		if (moneyamount > (money - reserve_money)) moneyamount = (money - reserve_money);
		if (moneyamount > money || moneyamount < 1 || moneyamount > debt)
		{
			cout<<"\nInvalid amount";
		}
		else
		{
			money -= moneyamount;
			debt -= moneyamount;
		}
	}
	else if (bankchoice == 138)
	{//free money!!!
		stats.cheats_used++;
		cout<<"\nI like you, how much free money do you want? ";
		cin>>moneyamount;
		money += moneyamount;
		stats.money_from_cheating += moneyamount;
	}
	
}

void gamble()
{//gambling, a number guessing game
	// TODO: Add other games?
	int bet; //bet for gambling	
	int playerguess; //players guess for gambling
	int cpunum; //computer number to be guessed for gambling
	
	if (playerciv != world[curworld][3] && world[curworld][3] > 0 && playerciv > 0) 
	{//don't do business with players of other civs
		cout<<"\nWe don't do business with your kind around these parts.";
		return;
	}
	cout<<"\nWelcome to the Casino!";
	cout<<"\nThe house picks a number from 1 - 100, then you try to guess it, you continue until you guess right or you quit";
	
	do
	{//do while the player has money, and the bet is > 0
		cout<<"\nHow much would you like to bet? ";
		cin>>bet; //asks for players bet, he puts in 0 to end
		cpunum = ran(1, 100); //cpu picks number from 1 - 100
		if (bet == 0) 
		{//if the bet is 0 we end the game
			return;
		}
		else if (bet > 1000) 
		{ //max bet is 1000
			cout<<"\n$1000 max";
		}
		else if (bet > money)
		{//if they don't have enough money
			cout<<"\nYou don't have that much money";
		}
		else
		{//play the game
			do 
			{//do until they guess the number
				cout<<"\nEnter your guess, 0 to exit ";
				cin>>playerguess; //player guess
				if (playerguess < 1) break; //if they entered 0 we exit
				if (money < bet) break; //if they don't have the money we exit
				money -= bet; //charge them for the guess
				stats.money_from_gambling -= bet;
				if (cpunum > playerguess) 
				{//if they guessed under the cpu's number
					cout<<"\n"<<playerguess<<" is less than my number.";
					cout<<"\nYou have "<<money;
				}
				else if (cpunum < playerguess)
				{//if they guessed over the cpu's number
					cout<<"\n"<<playerguess<<" is more than my number.";
					cout<<"\nYou have "<<money;
				}
				else if (cpunum == playerguess)
				{//if they guessed right they win
					cout<<"\nYou guessed right!";
					money += bet * 6; //award winning money, on average the player will lose just over 6 bets, so 6 is a good payout.  Over long period player will lose about 1/5 of bet per game.
					stats.money_from_gambling += bet * 6;
					cout<<"\nYou have "<<money;
				}
			} while (playerguess != cpunum && money >= bet);
		}
	} while (bet > 0 && money > 0);
}

void manage()
{//manage your cargo, move it from ship to ship, not done at all
	int shipnum; //ship index number
	
	// 1 - Uranium, 2 - Tritanium, 3 - Silver Oxide, 4, - Platinum, 5 - Carbon Nanotube
	listships(); //show user ships
	cout<<"\n\nCargo Management";
	cout<<"\nYou currently have in your ships' holds:";
	for (shipnum = 1; shipnum <= fleet[0][0]; shipnum++)
	{//loops through each ship to display what cargo it has
		// cout<<"\nShip # "<<shipnum<<": "<<goodname[1]<<" - "<<fleet[shipnum][11]<<", "<<goodname[2]<<" - "<<fleet[shipnum][12]<<", "<<goodname[3]<<" - "<<fleet[shipnum][13]<<", "<<goodname[4]<<" - "<<fleet[shipnum][14]<<", "<<goodname[5]<<" - "<<fleet[shipnum][15];
		printf("\nShip # %3d: %s - %3d, %s - %3d, %s - %3d, %s - %3d, %s - %3d", shipnum, goodname[1].c_str(), fleet[shipnum][11], goodname[2].c_str(), fleet[shipnum][12], goodname[3].c_str(), fleet[shipnum][13], goodname[4].c_str(), fleet[shipnum][14], goodname[5].c_str(), fleet[shipnum][15]);
		// std::print("Follow this command: {}", myString);
	}
}

void piratetalk()
{//get world data, either from another ship or from guy in bar
	int numworlds; //number of worlds the pirates have info on
	int planetnum; //index of world they have info on

	numworlds = 1; //how many worlds you will get data for, defaults to 1
	if (ran (1, 2) == 1) numworlds++; //each a chance of getting another world, with increasingly less odds
	if (ran (1, 2) == 1) numworlds++;
	if (ran (1, 3) == 1) numworlds++;
	if (ran (1, 3) == 1) numworlds++;
	if (ran (1, 4) == 1) numworlds++;
	if (ran (1, 4) == 1) numworlds++;
	if (ran (1, 5) == 1) numworlds++;
	if (ran (1, 5) == 1) numworlds++;
	if (ran (1, 7) == 1) numworlds++;
	if (ran (1, 8) == 1) numworlds++;
	if (ran (1, 9) == 1) numworlds++;
	if (ran (1, 3) == 1) numworlds += 3;
	if (ran (1, 5) == 1) numworlds += 5;
	
	if (debug) cout<<"\nHe has price data for "<<numworlds<<" worlds";
	cout<<"\nTransmitting price data to you now...";
	for (;numworlds >= 1; numworlds--)
	{//loops through the worlds gives you updated price data, I know that the same world may happened twice, chalk that up to you and him already having that data, or something.  Also aware that it's not outdated at all, whatever.
		planetnum = ran(1, 20);//random world to give you data for
		goods[planetnum][1][2] = goods[planetnum][1][1]; //updates the price list for this world
		goods[planetnum][2][2] = goods[planetnum][2][1];
		goods[planetnum][3][2] = goods[planetnum][3][1];
		goods[planetnum][4][2] = goods[planetnum][4][1];
		goods[planetnum][5][2] = goods[planetnum][5][1];
		visit[planetnum] = cday; //the date of the price data
	}
	findPriceExtremes();
	cout<<"\nWorld price data updated.";
}

void oldman()
{//old man that gives you secrets in the bar
	int secretnum; //number of advice old man gives you
	int secretlevel; //level of the secret advice
	
	secretlevel = 1;//how good of a secret you get, starts at 1
	if (ran (1, 2) == 1) secretlevel++; //50% chance of increasing secret level by one
	if (ran (1, 10) == 1) secretlevel++; //10% chance of increasing secret level by one
	
	if (secretlevel == 1)
	{//low level secrets, all pretty much useless
		secretnum = ran(1, 6);//pick which secret to give you (from this level)
		if (secretnum == 1)
		{
			cout<<"\nBuy low, sell high!";
		}
		else if (secretnum == 2)
		{
			cout<<"\nGambling is a waste of money!";
		}
		else if (secretnum == 3)
		{
			cout<<"\nNot all my advice is worthless!";
		}
		else if (secretnum == 4)
		{
			cout<<"\nLooks like ";
			if (civ[1] > civ[2]) cout<<"The Galactic Star Empire";
			if (civ[2] > civ[1]) cout<<"The United Republic of Planets";
			if (civ[1] == civ[2]) cout<<"neither side";
			cout<<" is winning the war!";
		}
		else if (secretnum == 5)
		{
			cout<<"\nThe ";
			if (world[curworld][3] == 1) cout<<"Galactic Star Empire";
			if (world[curworld][3] == 2) cout<<"United Republic of Planets";
			if (world[curworld][3] == 0) cout<<"rebel";
			cout<<" troops here sure do buy a lot of alcohol!";
		}
		else if (secretnum == 6)
		{
			cout<<"\nIf you ask me this place would be a lot better off under the control of ";
			if (world[curworld][3] == 2) cout<<"The Galactic Star Empire";
			if (world[curworld][3] == 1) cout<<"The United Republic of Planets";
			if (world[curworld][3] == 0) cout<<"a real civilization";
			cout<<"!";
		}
	}
	
	else if (secretlevel == 2)
	{//mid level secrets
		secretnum = ran(1, 5);//pick which secret to give you (from this level)
		if (secretnum == 1)
		{
			cout<<"\nHere's the price data for the worlds I've been to!";
			piratetalk();
			piratetalk();
		}
		else if (secretnum == 2)
		{
			cout<<"\nEven for a trader, attack can be better than cargo space!";
		}
		else if (secretnum == 3)
		{
			cout<<"\nWe are 138, We are 138, We are 138";
			cout<<"\nWe are 138, We are 138, We are 138";
			cout<<"\nWe are 138, We are 138";
			cout<<"\nIn the eyes of tiger";
			cout<<"\n";
			cout<<"\nDo you think we're robot clean";
			cout<<"\nDoes this face look almost mean";
			cout<<"\nIs it time to be an android not a man";
			cout<<"\n";
			cout<<"\nThe pleasantries are gone";
			cout<<"\nWe're stripped of all we were";
			cout<<"\nIn the eyes of tiger";
			cout<<"\n";
			cout<<"\nWe are 138, We are 138, We are 138";
			cout<<"\nWe are 138, We are 138, We are 138";
			cout<<"\n8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8";
			cout<<"\n8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8";
			cout<<"\n";
		}
		else if (secretnum == 4)
		{
			cout<<"\nRebels are more likely to be sympathetic to your cause if you don't have much money!";
		}
		else if (secretnum == 5)
		{
			cout<<"\nWatch out for inflation!";
		}
	}
	
	else if (secretlevel == 3)
	{//high level secrets
		secretnum = ran(1, 3);//pick which secret to give you (from this level)
		if (secretnum == 1)
		{
			cout<<"\nMoney is helpful, but help is moneyful!";
		}
		else if (secretnum == 2)
		{
			cout<<"\n138 is a blank check!";
		}
		else if (secretnum == 3)
		{
			cout<<"\nYou just won the lottery!";
			money += 50000;
		}
	}
	
	else
	{
		cout<<"\nBuy low sell high!";
	}
}

void destroypfleet()
{//destroys the pirate fleet, 0's every number in pfleet array
	int pshipnum; //pirate ship index number
	int pstatnum; //pirate stat index number
	
	pmoney = 0;
	for (pshipnum = 0; pshipnum <= 99; pshipnum++)
	{//loop through each number in pfleet array, set to 0
		for (pstatnum = 0; pstatnum <= 19; pstatnum++)
		{//loop through each number in pfleet array, set to 0
			pfleet[pshipnum][pstatnum] = 0;//loop through each number in pfleet array, set to 0
		}
	}
}

void dropcargo()
{//simulates you dropping your cargo so you can run away, just sets all cargo totals to 0
	int shipnum; //ship index number
	int goodnum; //goods index number
	
	cout<<"\nDropping cargo...";
	for (shipnum = 1; shipnum <= fleet[0][0]; shipnum++)
	{//loop through each ship in fleet, to 0 out cargo
		for (goodnum = 10; goodnum <= 19; goodnum++)
		{//loop through each type of cargo to 0 it out, yes I realize it's wasteful to do this for every ship
			fleet[0][goodnum] = 0;
		}
		
		for (goodnum = 10; goodnum <= 19; goodnum++)
		{//loop through each cargo type in each ship, 0 it out
			fleet[shipnum][goodnum] = 0;
		}
	}
}

void lostbattle()
{// player loses battle
	int shipnum; //ship index number
	stats.battles_lost++;
	for (shipnum = fleet[0][0]; shipnum > 0; shipnum--)
	{
		loseship(shipnum); //take away all the player's ships
	}
	if (bossfight == 1) 
	{//if it was a boss fight and you lost you're screwed
		cout<<"\nThe leader of ";
		if (playerciv == 1) cout<<"The Galactic Star Empire";
		if (playerciv == 2) cout<<"The United Republic of Planets";
		cout<<" has destroyed your fleet, and arrested you for high treason!";
		cout<<"\nYou are to be executed at midnight!";
		cout<<"\nYou Lose!";
		gameover = 1; //gameover
		money = 0;
		return;
	}
	travelto = ran(1, 20); //picks random world that ship that picks player up is going to
	displayBreak();
	cout<<"\n\nAll your ships were destroyed.";
	cout<<"\nAfter floating in an escape pod for a while another ship has picked you up.\nThey drop you off at their destination, world "<<travelto;
	traveltime = 0;//sets travel time to 0, so that they don't have any chance of coming across other pirates
}

void wonbattle()
{//player wins battle
	int pshipnum; //pirate ship index number
	
	if (bossfight == 0) cout<<"\nWe have taken the pirate fleet!";
	if (bossfight == 1) 
	{//if you won a boss fight then you are now a civ leader
		displayBreak();
		cout<<"\nYou've won the battle!";
		cout<<"\nYou are now the leader of ";
		if (playerciv == 1) cout<<"The Galactic Star Empire";
		if (playerciv == 2) cout<<"The United Republic of Planets";
		cout<<"!";
		playerleader = playerciv;
		playertax = 10; //default settings for players civ
		defense = 10000; //default defense spending
	}
	stats.battles_won++;
	stats.money_from_piracy += pmoney;
	money += pmoney; //takes pirate money
	
	for (pshipnum = 1; pshipnum <= pfleet[0][0]; pshipnum++)
	{//loop through each pirate ship, build it, give its goods to player
		pfleet[pshipnum][6] = 0; //ensures the HP of the disabled ships is 0
		fleet[0][0]++; //increases the count of ships in your fleet
		fleet[fleet[0][0]][1] = pfleet[pshipnum][1]; //speed
		fleet[fleet[0][0]][2] = pfleet[pshipnum][2]; //cargo
		fleet[fleet[0][0]][3] = pfleet[pshipnum][3]; //attack
		fleet[fleet[0][0]][4] = pfleet[pshipnum][4]; //cost
		fleet[fleet[0][0]][5] = pfleet[pshipnum][5]; //sensors
		fleet[fleet[0][0]][6] = pfleet[pshipnum][6]; //hit points
		fleet[fleet[0][0]][7] = pfleet[pshipnum][7]; //max hit points
		fleet[fleet[0][0]][8] = pfleet[pshipnum][8]; //class
		fleet[fleet[0][0]][9] = pfleet[pshipnum][9]; //model
		fleet[fleet[0][0]][10] = pfleet[pshipnum][10]; //goods
		fleet[fleet[0][0]][11] = pfleet[pshipnum][11]; //goods
		fleet[fleet[0][0]][12] = pfleet[pshipnum][12]; //goods
		fleet[fleet[0][0]][13] = pfleet[pshipnum][13]; //goods
		fleet[fleet[0][0]][14] = pfleet[pshipnum][14]; //goods
		fleet[fleet[0][0]][15] = pfleet[pshipnum][15]; //goods
		for (int ii = 11; ii <= 15; ii++)
		{// Account for the value of these goods in the money_from_piracy stat, and subtract from the money_from_trading stat
			int value_of_good = goods[curworld][ii][1] * pfleet[pshipnum][ii] * (2 - worldpen);
			stats.money_from_piracy += value_of_good; // Assume they sell at world they're traveling to
			stats.money_from_trades -= value_of_good; // Remove this amount from the trade stat, since it's accounted for in the piracy stat
		}

		//These will add the various stats to the fleet totals (stored as ship 0 in the fleet)
		fleet[0][2] += pfleet[pshipnum][2]; //cargo
		fleet[0][3] += pfleet[pshipnum][3]; //attack
		fleet[0][4] += pfleet[pshipnum][4]; //cost
		fleet[0][5] += pfleet[pshipnum][5]; //sensors
		fleet[0][6] += pfleet[pshipnum][6]; //hit points
		fleet[0][7] += pfleet[pshipnum][7]; //max hit points
		fleet[0][10] += pfleet[pshipnum][10]; //goods
		fleet[0][11] += pfleet[pshipnum][11]; //goods
		fleet[0][12] += pfleet[pshipnum][12]; //goods
		fleet[0][13] += pfleet[pshipnum][13]; //goods
		fleet[0][14] += pfleet[pshipnum][14]; //goods
		fleet[0][15] += pfleet[pshipnum][15]; //goods
		stats.total_ships++;
		stats.ships_captured++;
		
	}
	speedship(); //calculates the speed of the fleet, by finding the slowest ship
	senseship();
	if (bossfight == 0)
	{
		selfRepair(); //skip repair after boss fight, takes too much time
	}
	else
	{
		shipRepair(0, 1000, "", true); // A special free full automatic repair of all ships, just for the boss fight
	}
	destroypfleet();
	removeDisabledShips(); // Warn and destroy any player ships with <= 0 HP
}

int chooseAutoFightTarget(int strategy, bool show_results, int fleet_array[1000][20])
{
	//strategy: 0 - first ship, 1 - min HP, 2 - max HP, 3 - min attack, 4 - max attack, 5 - pct hp lost, 6 - lowest ratio hp/attack, 7 - random
	//Median win percentages against other stratgies, with 1000 rounds of random fleets:
	// 0 - 47%, 1 - 52%, 2 - 45%, 3 - 27%, 4 - 68%, 5 - 64%, 6 - 78%, 7 - 46%
	int shipnum; //ship index number
	int lowest_hp_ship = 0;
	int highest_hp_ship = 0;
	int lowest_attack_ship = 0;
	int highest_attack_ship = 0;
	int first_ship_with_hp = 0;
	int lowest_hp_pct_ship = 0;
	int lowest_hp_attack_ratio_ship = 0;
	for (shipnum = 1; shipnum <= fleet_array[0][0]; shipnum++)
	{//go through each ship, see if HP or attack are min/max and record them if so
		if (fleet_array[shipnum][6] < 1) continue; // Don't target already disabled ships
		if (lowest_hp_ship == 0 || fleet_array[shipnum][6] < fleet_array[lowest_hp_ship][6]) lowest_hp_ship = shipnum;
		if (highest_hp_ship == 0 || fleet_array[shipnum][6] > fleet_array[highest_hp_ship][6]) highest_hp_ship = shipnum;
		if (lowest_attack_ship == 0 || fleet_array[shipnum][3] < fleet_array[lowest_attack_ship][3]) lowest_attack_ship = shipnum;
		if (highest_attack_ship == 0 || fleet_array[shipnum][3] > fleet_array[highest_attack_ship][3]) highest_attack_ship = shipnum;
		if (lowest_hp_pct_ship == 0 || (1.0 * fleet_array[shipnum][6] / fleet_array[shipnum][7]) < (1.0 * fleet_array[lowest_hp_pct_ship][6] / fleet_array[lowest_hp_pct_ship][7])) lowest_hp_pct_ship = shipnum;
		if (lowest_hp_attack_ratio_ship == 0 || (1.0 * fleet_array[shipnum][6] / fleet_array[shipnum][3]) < (1.0 * fleet_array[lowest_hp_attack_ratio_ship][6] / fleet_array[lowest_hp_attack_ratio_ship][3])) lowest_hp_attack_ratio_ship = shipnum;
		if (first_ship_with_hp == 0) first_ship_with_hp = shipnum;
	}

	if (show_results) cout<<"\nLowest HP: "<<lowest_hp_ship<<", Highest HP: "<<highest_hp_ship;
	if (show_results) cout<<", Lowest Attack: "<<lowest_attack_ship<<", Highest Attack: "<<highest_attack_ship;
	if (show_results) cout<<"\nLowest remaining HP percentage: "<<lowest_hp_pct_ship<<", Lowest HP/attack ratio: "<<lowest_hp_attack_ratio_ship;
	if (show_results) cout<<", First ship with HP: "<<first_ship_with_hp;
	if (strategy == 0)
	{//first ship
		if (show_results) cout<<"\nFirst ship with HP is "<<first_ship_with_hp;
		return first_ship_with_hp;
	}
	else if (strategy == 1)
	{//min hp
		// if (show_results) cout<<"\nAutofight chooses ship # "<<lowest_hp_ship;
		return lowest_hp_ship;
	}
	else if (strategy == 2)
	{//max hp
		// if (show_results) cout<<"\nAutofight chooses ship # "<<highest_hp_ship;
		return highest_hp_ship;
	}
	else if (strategy == 3)
	{//min attack
		// if (show_results) cout<<"\nAutofight chooses ship # "<<lowest_attack_ship;
		return lowest_attack_ship;
	}
	else if (strategy == 4)
	{//max attack
		// if (show_results) cout<<"\nAutofight chooses ship # "<<highest_attack_ship;
		return highest_attack_ship;
	}
	else if (strategy == 5)
	{//largest percent HP lost
		// if (show_results) cout<<"\nAutofight chooses ship # "<<lowest_hp_pct_ship;
		return lowest_hp_pct_ship;
	}
	else if (strategy == 6)
	{//best ratio of remaining HP to attack
		// if (show_results) cout<<"\nAutofight chooses ship # "<<lowest_hp_attack_ratio_ship;
		return lowest_hp_attack_ratio_ship;
	}
	else if (strategy == 7)
	{//random
		int attempt_count = 0;
		do
		{
			attempt_count++;
			int possible_ship = ran(1, fleet_array[0][0]);
			if (fleet_array[possible_ship][6] > 0) return possible_ship;
		} while (attempt_count < 1000);
		cout<<"\nERROR: Could not find random ship";
		return first_ship_with_hp;
	}
	else
	{
		cout<<"\nERROR: Unable to determine autofight target!";
		return 1;
	}
}

void battle(int shot)
{//battle between two fleets, the int passed to it determines who goes first 0 - pirates, 1 - player
	int attackship; //ship doing the shooting
	int target; //target to shoot at
	int hit; //whether or not shot hit
	int dam; //damage
	int battletype = 1; //1 - normal, 2 - pirates lose, 3 - player lose, 4 pirates run, 5 - player runs
	int ptarget; //pirates target
	int shipnum; //ship index number
	int pshipnum; //pirate ship index number
	bool autofight = 0; //auto fight mode, 0-off, 1-on
	int confirm; //user confirmation
	int atarget; //auto fight mode target
	int pirate_battle_strategy = 1; //autofight strategy of the pirates
	pirate_battle_strategy = ran(0,7); //randomly choose the pirate battle strategy
	if (debug) cout<<"\nPirate strategy - "<<pirate_battle_strategy;
	// TODO: Add ability to see pirate strategy as buyable equipment

	displayBreak();
	cout<<"\nA battle has started!\n\n";
	stats.battles_fought++;
	ptarget = chooseAutoFightTarget(pirate_battle_strategy, false, fleet);
	atarget = chooseAutoFightTarget(player_battle_strategy, true, pfleet);
	cout<<"\nAutofight strategy "<<player_battle_strategy<<" chooses ship # "<<atarget;
	do
	{//loop until battle over (battle type != 0)
		if (fleet[0][6] < 1) 
		{//players fleet HP < 1
			battletype = 3;//1 - normal, 2 - pirates lose, 3 - player lose, 4 pirates run, 5 - player runs
			break;
		}
		else if (pfleet[0][6] < 1)
		{//pirates fleet HP < 1
			battletype = 2;//1 - normal, 2 - pirates lose, 3 - player lose, 4 pirates run, 5 - player runs
			break;
		}
		if (shot == 0)
		{//pirates shot
			if (autofight == 0) cout<<"\n";
			for (attackship = 1; attackship <= pfleet[0][0]; attackship++)
			{//loop through each pirate ship letting it attack player
				if (debug) cout<<"\nfleet HP "<<fleet[0][6];
				if (pfleet[0][1] > fleet[0][1] && bossfight == 0 && paggressive == 0) 
				{//pirates out run player
					battletype = 4;//1 - normal, 2 - pirates lose, 3 - player lose, 4 pirates run, 5 - player runs
					break;
				}
				if (debug) cout<<"\nNo break";
				if (pfleet[attackship][6] < 1) continue; //prevents pirate ships with less than 1 HP from firing on player
				if (autofight == 0) cout<<"\nEnemy fleet firing at you!";
				target = ptarget; //pick a random target
				hit = 0; //set hit to 0, so that if it's not set to 1 by the next line it's a miss
				if (ran (1, fleet[target][3] + pfleet[attackship][3]) > fleet[target][3]) hit = 1; //odds of a hit are a in a + b where a is attacker's attack, and b is targets attack
				if (hit == 1) 
				{//hit
					dam = ran (1, pfleet[attackship][3]); //figure the damage done, a random amount of the attack value
					if (autofight == 0) cout<<"\nWe have been hit! "<<dam<<" damage done to ship # "<<target;
					if (debug) cout<<"\nDam - "<<dam<<", fleet HP - "<<fleet[0][6]<<" Ship HP - "<<fleet[target][6];
					if (dam > fleet[target][6]) fleet[0][6] -= fleet[target][6]; //if the damage is more than the ship can take that ship is gone, take it away from the fleet total
					if (dam <= fleet[target][6]) fleet[0][6] -= dam; //if the damage is less than the ship can take than take the damage away
					if (dam > fleet[target][6]) fleet[target][6] = 0; //if the damage is more than the ship can take, that ship is gone, 0 it out
					if (dam <= fleet[target][6]) fleet[target][6] -= dam; //if the damage is less than the ship can take than take the damage away
					if (debug) cout<<"\nDam - "<<dam<<", fleet HP - "<<fleet[0][6]<<" Ship HP - "<<fleet[target][6];
					if (fleet[target][6] < 1) 
					{ //if the ship has been destroyed
						cout<<"\nOur ship # "<<target<<" was disabled!";
						fleet[target][6] = 0; //make sure HP isn't < 0
						if (fleet[0][6] < 1) 
						{//if entire fleet is gone the battle is over
							battletype = 3;//1 - normal, 2 - pirates lose, 3 - player lose, 4 pirates run, 5 - player runs
							break;
						}
						ptarget = chooseAutoFightTarget(pirate_battle_strategy, false, fleet); //since the ship was disabled time to pick a new target
					}
				}
				if (hit == 0 && autofight == 0) cout<<"\nThey missed!";
			}
			shot = 1; //players turn
		}
		else if (shot == 1)
		{//players shot
			for (attackship = 1; attackship <= fleet[0][0]; attackship++)
			{//loop through each player's ships
				if (fleet[attackship][6] < 1) continue; //prevents ships with less than 1 HP from firing
				if (autofight == 0)
				{
					plistships(disabled_ship_display_mode); //let the player see the enemy ships
					listships(disabled_ship_display_mode); //let the player see his ships
					atarget = chooseAutoFightTarget(player_battle_strategy, true, pfleet); //Show the autofight stats even when not in autofight
					cout<<"\nAutofight strategy "<<player_battle_strategy<<" chooses ship # "<<atarget;
					cout<<"\nWhat ship do you wish to fire upon, with your ship # "<<attackship<<"? ";
					if (bossfight == 0) cout<<"Enter 138 to run, if they are faster you will have to drop the cargo ";
					cout<<"\nEnter 0 to autofight ";
					cin>>target; //player picks target
				}
				else
				{
					target = atarget;
				}

				if (target == 138 && bossfight == 0) 
				{//run away!
					if (pfleet[0][1] >= fleet[0][1]) dropcargo(); //drops the cargo if we are slower to distract them, and runs
					battletype = 5;//1 - normal, 2 - pirates lose, 3 - player lose, 4 pirates run, 5 - player runs
					stats.battles_ran_away++;
					break;
				}
				if (target == 138 && bossfight == 1) 
				{//cheating
					stats.cheats_used++;
					battletype = 2;//1 - normal, 2 - pirates lose, 3 - player lose, 4 pirates run, 5 - player runs
					break;
				}
				if (target == 0)
				{//auto fire mode
					if (autofight == 0) cout<<"\nEnter autofight mode?  Enter 138 to confirm ";
					cin>>confirm; //confirm it
					if (confirm == 138) autofight = 1;
				}
				if (pfleet[target][6] <= 0)
				{//check to make sure we aren't trying to fire on a disabled ship, could loop, but this just checks once
					cout<<"\nShip # "<<target<<" is already disabled.";
					cout<<"\nWhat ship do you wish to fire upon, with your ship # "<<attackship<<"? ";
					cin>>target; //player picks target
				}
				if (target > pfleet[0][0] || pfleet[target][6] < 1)
				{
					target = atarget;
				}
				hit = 0; //set hit to 0, so that if it's not set to 1 by the next line it's a miss
				if (ran (1, pfleet[target][3] + fleet[attackship][3]) > pfleet[target][3] && target <= pfleet[0][0]) hit = 1; //odds of a hit are a in a + b where a is attacker's attack, and b is targets attack
				if (hit == 1 && target <= pfleet[0][0]) 
				{//hit
					dam = ran (1, fleet[attackship][3]); //figure the damage done, a random amount of the attack value
					if (autofight == 0) cout<<"\nDirect hit! "<<dam<<" damage done to ship # "<<target;
					if (dam > pfleet[target][6]) pfleet[0][6] -= pfleet[target][6]; //if the damage is more than the ship can take that ship is gone, take it away from the fleet total
					if (dam <= pfleet[target][6]) pfleet[0][6] -= dam; //if the damage is less than the ship can take than take the damage away
					if (dam > pfleet[target][6]) pfleet[target][6] = 0; //if the damage is more than the ship can take, that ship is gone, 0 it out
					if (dam <= pfleet[target][6]) pfleet[target][6] -= dam; //if the damage is less than the ship can take than take the damage away
					if (pfleet[target][6] < 1 && target <= pfleet[0][0]) 
					{ //if the ship has been destroyed
						cout<<"\nTheir ship # "<<target<<" was disabled!";
						pfleet[target][6] = 0;
						if (pfleet[0][6] < 1) 
						{//if fleet is gone battle over
							battletype = 2;//1 - normal, 2 - pirates lose, 3 - player lose, 4 pirates run, 5 - player runs
							break;
						}
						atarget = chooseAutoFightTarget(player_battle_strategy, autofight == 0, pfleet); //since our target was disabled, pick new auto target
						if (autofight == 0) cout<<"\nAutofight strategy "<<player_battle_strategy<<" chooses ship # "<<atarget;
					}
				}
				if (hit == 0 && target <= pfleet[0][0] && autofight == 0) cout<<"\nWe missed";
			}
			shot = 0; //pirates turn
		}
		
		if (pfleet[0][6] < 1)
		{//double check to see if fleet is destroyed
			battletype = 2;
			break;
		}
		else if (fleet[0][6] < 1)
		{//double check to see if fleet is destroyed
			battletype = 3;
			break;
		}		
	} while (battletype == 1); //do while battletype = 1 //1 - normal, 2 - pirates lose, 3 - player lose, 4 pirates run, 5 - player runs
	
	//1 - normal, 2 - pirates lose, 3 - player lose, 4 pirates run, 5 - player runs
	if (battletype == 2)
	{//if we survived the battle
		cout<<"\n\nWe have won!\n\n";
		wonbattle();
	}
	else if (battletype == 3)
	{//we lost all ships
		displayBreak();
		cout<<"\n\nWe lost.\n\n";
		plistships();
		listships();
		lostbattle();
	}

	else if (battletype == 4)
	{//they ran away
		for (pshipnum = pfleet[0][0]; pshipnum > 0; pshipnum--)
		{//loop through each pirate ship, to check if any were disabled, if so we get them since they ran away
			if (debug) cout<<"\npshipnum - "<<pshipnum<<", pfleet[pshipnum][6] - "<<pfleet[pshipnum][6];
			if (pfleet[pshipnum][6] < 1) 
			{//if the ship is disabled give it to player
				pfleet[pshipnum][6] = 0; //ensures the HP of the disabled ships is 0
				fleet[0][0]++; //increases the count of ships in your fleet
				fleet[fleet[0][0]][1] = pfleet[pshipnum][1]; //speed
				fleet[fleet[0][0]][2] = pfleet[pshipnum][2]; //cargo
				fleet[fleet[0][0]][3] = pfleet[pshipnum][3]; //attack
				fleet[fleet[0][0]][4] = pfleet[pshipnum][4]; //cost
				fleet[fleet[0][0]][5] = pfleet[pshipnum][5]; //sensors
				fleet[fleet[0][0]][6] = pfleet[pshipnum][6]; //hit points
				fleet[fleet[0][0]][7] = pfleet[pshipnum][7]; //max hit points
				fleet[fleet[0][0]][8] = pfleet[pshipnum][8]; //class
				fleet[fleet[0][0]][9] = pfleet[pshipnum][9]; //model
				fleet[fleet[0][0]][10] = pfleet[pshipnum][10]; //goods
				fleet[fleet[0][0]][11] = pfleet[pshipnum][11]; //goods
				fleet[fleet[0][0]][12] = pfleet[pshipnum][12]; //goods
				fleet[fleet[0][0]][13] = pfleet[pshipnum][13]; //goods
				fleet[fleet[0][0]][14] = pfleet[pshipnum][14]; //goods
				fleet[fleet[0][0]][15] = pfleet[pshipnum][15]; //goods
				
				//These will add the various stats to the fleet totals (stored as ship 0 in the fleet)
				fleet[0][2] += pfleet[pshipnum][2]; //cargo
				fleet[0][3] += pfleet[pshipnum][3]; //attack
				fleet[0][4] += pfleet[pshipnum][4]; //cost
				fleet[0][5] += pfleet[pshipnum][5]; //sensors
				fleet[0][6] += pfleet[pshipnum][6]; //hit points
				fleet[0][7] += pfleet[pshipnum][7]; //max hit points
				fleet[0][10] += pfleet[pshipnum][10]; //goods
				fleet[0][11] += pfleet[pshipnum][11]; //goods
				fleet[0][12] += pfleet[pshipnum][12]; //goods
				fleet[0][13] += pfleet[pshipnum][13]; //goods
				fleet[0][14] += pfleet[pshipnum][14]; //goods
				fleet[0][15] += pfleet[pshipnum][15]; //goods
				stats.total_ships++;
				stats.ships_captured++;
			}
			else if (pfleet[pshipnum][6] > 0 && pfleet[0][1] < fleet[0][1])
			{//pirate fleet is slower, so they had to drop cargo to run.
				
			}
		}
		
		cout<<"\nThey have ran away.";
	}
	else if (battletype == 5)
	{//we ran away
		for (shipnum = fleet[0][0]; shipnum > 0; shipnum--)
		{//check each of our ships, if any are disabled we lose them, since we are running away.  Note we loop from high to low since loseship changes the ship index number it'll skip the ship after any it removes if we go up from 1 
			if (debug) cout<<"\nshipnum - "<<shipnum<<", fleet[shipnum][6] - "<<fleet[shipnum][6];
			if (fleet[shipnum][6] < 1) loseship(shipnum); //if HP is <1 we lose the ship
		}
		cout<<"\nWe have run away.";
	}
	else
	{//should never happen, but probably will
		cout<<"\nSome crazy wormhole ended the battle, or something.";
		cout<<"\nfleet[0][6] - "<<fleet[0][6]<<", pfleet[0][6] - "<<pfleet[0][6]<<", paggressive - "<<paggressive<<", battletype - "<<battletype;
	}
	speedship();
	senseship();
}

void bosspirates()
{//special spawning of boss pirates
	int bossciv; //boss's civ
	int pshipclass; //pirate ship class
	int pshipmodel; //pirate ship model
	int pshipnum; //pirate ship index number
	int pgoodnum; //good index number
	int qty; //quantity
	int confirm; //confirmation input
	int min_boss_ships; //minimum number of boss ships

	bossfight = 1; //this is a boss fight
	destroypfleet(); //destroy any previous pirate fleet
	bossciv = playerciv; //boss is whatever civ the player is
	min_boss_ships = skill * 10;
	pfleet[0][0] = ran(min_boss_ships, (civ[bossciv] * 5) + min_boss_ships); //determine the number of ships in the pirate fleet, uses the civs number of worlds
	pfleet[0][0] += ran(3, 15);
	pmoney = (ran (10000, 20000) * 100) + (civ[bossciv] * civ[bossciv] * 12345); //determines the amount of money the pirates have

	for (pshipnum = 1; pshipnum <= pfleet[0][0]; pshipnum++)
	{//loop through each pirate ship, build it, give it goods
		pshipclass=2; //boss gets all maxed out attack ships
		pshipmodel=3; //boss gets all maxed out attack ships
		
		pfleet[pshipnum][1] = ships[pshipclass][pshipmodel][1]; //speed
		pfleet[pshipnum][2] = ships[pshipclass][pshipmodel][2]; //cargo
		pfleet[pshipnum][3] = ships[pshipclass][pshipmodel][3]; //attack
		pfleet[pshipnum][4] = ships[pshipclass][pshipmodel][10 + ran(1, 20)] / skill; //cost
		pfleet[pshipnum][5] = ships[pshipclass][pshipmodel][5]; //sensors
		pfleet[pshipnum][6] = ships[pshipclass][pshipmodel][7]; //hit points
		pfleet[pshipnum][7] = ships[pshipclass][pshipmodel][7]; //mapship hit points
		pfleet[pshipnum][8] = pshipclass; //class
		pfleet[pshipnum][9] = pshipmodel; //model
		
		pfleet[0][2] += ships[pshipclass][pshipmodel][2]; //cargo
		pfleet[0][3] += ships[pshipclass][pshipmodel][3]; //attack
		pfleet[0][4] += pfleet[pshipnum][4]; //cost
		pfleet[0][5] += ships[pshipclass][pshipmodel][5]; //sensors
		pfleet[0][6] += ships[pshipclass][pshipmodel][7]; //hit points
		pfleet[0][7] += ships[pshipclass][pshipmodel][7]; //max hit points
		
		pspeedship(); //determine the pirates fleet speed
		psenseship(); //determine the pirates fleet sensor range
				
		qty = ran (1, pfleet[pshipnum][2]); //random amount of good to give each ship
		pgoodnum = 1; //start as the cheapest good, move up each level is less and less likely
		if (ran (1, 2) == 1) pgoodnum++; //1 in 3 odds of increasing good level
		if (ran (1, 2) == 1) pgoodnum++; //1 in 3 odds of increasing good level
		if (ran (1, 2) == 1) pgoodnum++; //1 in 3 odds of increasing good level
		if (ran (1, 2) == 1) pgoodnum++; //1 in 5 odds of increasing good level
		if (qty > pfleet[0][2]) qty = pfleet[0][2]; //if the qty of goods is more than cargo room than just do the max
		if (debug) cout<<"\nPirate goods pshipnum - "<<pshipnum<<", qty - "<<qty<<", pgoodnum - "<<pgoodnum;
		
		if (pfleet[pshipnum][10] < pfleet[pshipnum][2] && (pfleet[pshipnum][2] - pfleet[pshipnum][10]) < qty)
		{// if this ship has some room left, and the amount of room it has is < the amount we are buying
			qty -= (pfleet[pshipnum][2] - pfleet[pshipnum][10]); //subtract the amount we are putting on this ship, from the amount we are buying
			pfleet[pshipnum][pgoodnum+10] += (pfleet[pshipnum][2] - pfleet[pshipnum][10]); //add the amount to the good slot for this ship
			pfleet[0][pgoodnum+10] += (pfleet[pshipnum][2] - pfleet[pshipnum][10]); //add amount to total amount of that good you have
			pfleet[0][10] += (pfleet[pshipnum][2] - pfleet[pshipnum][10]); //add the amount to the total goods
			pfleet[pshipnum][10] += (pfleet[pshipnum][2] - pfleet[pshipnum][10]); //add the amount to the total goods slot for this ship
		}
		else if (pfleet[pshipnum][10] < pfleet[pshipnum][2] && (pfleet[pshipnum][2] - pfleet[pshipnum][10]) > qty)
		{//if this ship has room, and the amount of room is > the amount we are buying
			pfleet[pshipnum][pgoodnum+10] += qty; //add the amount to the good slot for this ship
			pfleet[pshipnum][10] += qty; //add the amount to the total goods slot for this ship
			pfleet[0][pgoodnum+10] += qty; //add amount to total amount of that good you have
			pfleet[0][10] += qty; //add the amount to the total goods 
			qty=0; //since this ship fit all the cargo 0 out qty, there is no more cargo to put on any ships
		}
		else if (pfleet[pshipnum][10] < pfleet[pshipnum][2] && (pfleet[pshipnum][2] - pfleet[pshipnum][10]) == qty && qty != 0)
		{// if this ship has the exact amount of room as the amount we are buying (and it's not 0)
			pfleet[pshipnum][pgoodnum+10] += qty; //add the amount to the good slot for this ship
			pfleet[pshipnum][10] += qty; //add the amount to the total goods slot for this ship
			pfleet[0][pgoodnum+10] += qty; //add amount to total amount of that good you have
			pfleet[0][10] += qty; //add the amount to the total goods 
			qty=0; //since this ship fit all the cargo 0 out qty, there is no more cargo to put on any ships
		}
	}
	
	paggressive = 1; //default to aggressive pirates
	if (debug) plistships();
	cout<<"\nA massive fleet looms at the edge of your sensor range";
	cout<<", their combined attack is "<<pfleet[0][3]<<", and combined HP is "<<pfleet[0][6];
	cout<<"\nThe greatest battle of your life has begun...";
	cout<<"\n\nEnter 0 to begin ";
	cin>>confirm;
	battle(0);//goto battle, player gets first shot, might change to boss gets first shot, not sure.
	destroypfleet();
}

// TODO: simulate battles using different autofight strategies
// Just copy the player's fleet to pirate fleet
void pirates()
{//player comes across another ship
	int pciv; //pirate's civ
	int sensortiebreaker; //breaks ties in the sensor range
	int attackrun; //players choice to attack or run
	int pshipclass; //pirate ship class
	int pshipmodel; //pirate ship model
	int pshipnum; //pirate ship index number
	int pgoodnum; //good index number
	int qty; //quantity
	int tempdam; //the amount of HP damage the pirate ships will start with
	int tempass; //assets used, values < 0 will be made 0

	bossfight = 0; //not a boss fight
	destroypfleet(); //destroy any previous pirate fleet
	calcassets(); //figure player assets, they are used to determine size of pirate fleet
	tempass = assets; //use tempass so we can change it if we need to
	if (tempass < 0) tempass = 0; //ensure that the assets can't be less than 0
	pciv = 1; //set pirate civ to 1, if we determine it to be 2 we will move it up, other wise it stays
	// TODO: Allow starting and destination planets to influence odds of ships you encounter too
	// TODO: Change this so that independent planet numbers influence odds of independent ships too
	// Maybe just a 50/50 chance of curworld or previous_world?
	// Then like a 1/10 chance of choosing one of the 3 at random so there is always some chance?
	if (ran(1, 20) > civ[1]) pciv++; //if the random chance was more than the worlds controlled by civ 1 than civ 2 gets the fleet
	if (ran (1, 3) == 1) pciv = 0; //random 1 in 3 chance of the pirates being independent, regardless of planet ownership numbers
	
	pfleet[0][0] = ran(1, (tempass / 10000) + 1); //determine the number of ships in the pirate fleet, uses the players assets as a scale of how he's doing
	if (pfleet[0][0] > 100) pfleet[0][0] = 100; //caps pirate fleet at 100 ships, it was just getting annoying beyond that, might change I guess, or might just cap player too.
	pfleet[0][0] += ran(0, skill*2); //adds a few ships based on skill level
	pmoney = ran (100, (tempass / 10) + 1000); //determines the amount of money the pirates have
	if (ran(1, 5) == 1) pmoney += 1000; //20% of bonus pirate money
	for (pshipnum = 1; pshipnum <= pfleet[0][0]; pshipnum++)
	{//loop through each pirate ship, build it, give it goods
		pshipclass=1;//default to the low class and model
		pshipmodel=1;
		if (ran (1, 2) == 1) pshipclass++; //1 in 2 odds of increasing the class
		if (ran (1, 3) == 1) pshipclass++; //1 in 3 odds of increasing the class
		if (ran (1, 6) <= skill) pshipmodel++; //1 in 3 odds of increasing the model
		if (ran (1, 6) <= skill) pshipmodel++; //1 in 3 odds of increasing the model
		
		//if (ran (1, abs(assets)) > 1000) pshipmodel = 3; //the greater the player assets the higher odds of them getting the highest class pirate ship
		
		tempdam = ran(0, ships[pshipclass][pshipmodel][7] / (11 - skill)); //mild HP damage
		if (ran(1, 100) >= skill * 33) tempdam = ran(0, ships[pshipclass][pshipmodel][7] - 1); //severe HP damage
		
		pfleet[pshipnum][1] = ships[pshipclass][pshipmodel][1]; //speed
		pfleet[pshipnum][2] = ships[pshipclass][pshipmodel][2]; //cargo
		pfleet[pshipnum][3] = ships[pshipclass][pshipmodel][3]; //attack
		pfleet[pshipnum][4] = ships[pshipclass][pshipmodel][10 + ran(1, 20)] / 3; //cost
		pfleet[pshipnum][5] = ships[pshipclass][pshipmodel][5]; //sensors
		pfleet[pshipnum][6] = ships[pshipclass][pshipmodel][7] - tempdam; //hit points
		pfleet[pshipnum][7] = ships[pshipclass][pshipmodel][7]; //max hit points
		pfleet[pshipnum][8] = pshipclass; //class
		pfleet[pshipnum][9] = pshipmodel; //model
		
		pfleet[0][2] += ships[pshipclass][pshipmodel][2]; //cargo
		pfleet[0][3] += ships[pshipclass][pshipmodel][3]; //attack
		pfleet[0][4] += pfleet[pshipnum][4]; //cost
		pfleet[0][5] += ships[pshipclass][pshipmodel][5]; //sensors
		pfleet[0][6] += (ships[pshipclass][pshipmodel][7] - tempdam); //hit points
		pfleet[0][7] += ships[pshipclass][pshipmodel][7]; //max hit points
		
		pspeedship(); //determine the pirates fleet speed
		psenseship(); //determine the pirates fleet sensor range
		
		qty = ran (1, pfleet[pshipnum][2]); //random amount of goods to give each ship
		pgoodnum = 1; //start as the cheapest good, move up each level is less and less likely
		if (ran (1, 3) == 1) pgoodnum++; //1 in 3 odds of increasing good level
		if (ran (1, 5) == 1) pgoodnum++; //1 in 5 odds of increasing good level
		if (ran (1, 6) >= skill * 2) pgoodnum++; //1 in 2 odds of increasing good level
		if (ran (1, 6) >= skill * 2) pgoodnum++; //1 in 2 odds of increasing good level
		
		if (qty > pfleet[0][2]) qty = pfleet[0][2]; //if the qty of goods is more than cargo room than just do the max
		
		if (debug) cout<<"\nPirate goods pshipnum - "<<pshipnum<<", qty - "<<qty<<", pgoodnum - "<<pgoodnum;
		
		if (pfleet[pshipnum][10] < pfleet[pshipnum][2] && (pfleet[pshipnum][2] - pfleet[pshipnum][10]) < qty)
		{// if this ship has some room left, and the amount of room it has is < the amount we are buying
			qty -= (pfleet[pshipnum][2] - pfleet[pshipnum][10]); //subtract the amount we are putting on this ship, from the amount we are buying
			pfleet[pshipnum][pgoodnum+10] += (pfleet[pshipnum][2] - pfleet[pshipnum][10]); //add the amount to the good slot for this ship
			pfleet[0][pgoodnum+10] += (pfleet[pshipnum][2] - pfleet[pshipnum][10]); //add amount to total amount of that good you have
			pfleet[0][10] += (pfleet[pshipnum][2] - pfleet[pshipnum][10]); //add the amount to the total goods
			pfleet[pshipnum][10] += (pfleet[pshipnum][2] - pfleet[pshipnum][10]); //add the amount to the total goods slot for this ship
		}
		else if (pfleet[pshipnum][10] < pfleet[pshipnum][2] && (pfleet[pshipnum][2] - pfleet[pshipnum][10]) > qty)
		{//if this ship has room, and the amount of room is > the amount we are buying
			pfleet[pshipnum][pgoodnum+10] += qty; //add the amount to the good slot for this ship
			pfleet[pshipnum][10] += qty; //add the amount to the total goods slot for this ship
			pfleet[0][pgoodnum+10] += qty; //add amount to total amount of that good you have
			pfleet[0][10] += qty; //add the amount to the total goods 
			qty=0; //since this ship fit all the cargo 0 out qty, there is no more cargo to put on any ships
		}
		else if (pfleet[pshipnum][10] < pfleet[pshipnum][2] && (pfleet[pshipnum][2] - pfleet[pshipnum][10]) == qty && qty != 0)
		{// if this ship has the exact amount of room as the amount we are buying (and it's not 0)
			pfleet[pshipnum][pgoodnum+10] += qty; //add the amount to the good slot for this ship
			pfleet[pshipnum][10] += qty; //add the amount to the total goods slot for this ship
			pfleet[0][pgoodnum+10] += qty; //add amount to total amount of that good you have
			pfleet[0][10] += qty; //add the amount to the total goods 
			qty=0; //since this ship fit all the cargo 0 out qty, there is no more cargo to put on any ships
		}
	}
	
	paggressive = 0; //default to non aggressive pirates
	//just adds fleet attack to 25% of fleet HP, adds the two fleets together and if a random number in that range is greater than players attack + 25% HP than the pirates will attack
	if (ran(1, (pfleet[0][3] + (pfleet[0][6] / 4)) + (fleet[0][3] + (fleet[0][6] / 4))) > (fleet[0][3] + (fleet[0][6] / 4))) paggressive = 1;
	
	if (pciv == playerciv && playerciv != 0) paggressive = 0; //if the player and pirates both belong to a civ (not neutral) then they will not attack
	if (pciv > 0 && playerciv > 0 && playerciv != pciv) paggressive = 1; //if the pirates and the player belong to opposite civs (neither neutral) then they will attack
	if (debug) plistships();
	
	sensortiebreaker = 0; //tie breaker if sensor ranges are same
	if (pfleet[0][5] == fleet[0][5]) sensortiebreaker = ran(0, 1); //if it's 1 we get the tie breaker, if 0 they do
	
	displayBreak();
	displayPirateFleetInfo(pciv);
	if (pfleet[0][5] >= fleet[0][5] + sensortiebreaker)
	{//if the pirates sensor range is better than players, they have the first choice of what to do
		if (paggressive == 1) battle(0); //battle, pirates get first shot
		else if (paggressive == 0 && pciv == playerciv && playerciv != 0) piratetalk(); //pirates talk
		else cout<<"\nThe other fleet leaves without contacting you...";
	}
	else if (pfleet[0][5] <= fleet[0][5] + sensortiebreaker)
	{//if players sensor range is better, the player has first choice
		if (pciv > 0 && playerciv > 0 && playerciv != pciv) cout<<"\n\nWhat do you want to do? 1 - attack, 2 - run "; //if the pirates and the player belong to opposite civs (neither neutral) they attack
		if (pciv == 0 || playerciv == 0) cout<<"\n\nWhat do you want to do? 1 - attack, 2 - run, 3 - talk ";
		
		if (pciv != playerciv || playerciv == 0) cin>>attackrun; //player decided to attack or run, if player and pirates are same civ then it defaults to talk
		if (pciv == playerciv && playerciv != 0) attackrun = 3; //talk to same civ pirates
		if (attackrun > 3 || attackrun < 1) attackrun = 2; //attack rival civ pirates
		
		if (pciv == playerciv && playerciv != 0 && attackrun == 1) attackrun = 2; //if the player and pirates both belong to a civ (not neutral) than they will not attack
		if (pciv > 0 && playerciv > 0 && playerciv != pciv && attackrun == 3) attackrun = 2; //if the pirates and the player belong to opposite civs (neither neutral) they attack
		
		if (attackrun == 1) 
		{//attack
			battle(1); //if you attack then we battle, player gets first shot
		}
		else if (attackrun == 2 && pfleet[0][1] > fleet[0][1] && paggressive == 1)
		{// if you try to run but they are faster and want to attack then we battle
			cout<<"\nThe enemy fleet is faster, they have fired upon you!";
			battle(0); //goto battle, pirates get first shot
		}
		else if (attackrun == 2)
		{// run away
			cout<<"\nYou have out run them.";
			return;
		}
		else if (attackrun == 3 && paggressive == 1)
		{// try to talk, but they attack
			cout<<"\nYou attempted to contact the enemy fleet, but they have fired upon you!";
			battle(0); //goto battle, pirates get first shot
		}
		else if (attackrun == 3 && paggressive == 0)
		{// talk
			cout<<"\nContacting fleet...";
			piratetalk(); //goto battle, pirates get first shot
		}
		else
		{//shouldn't happen, but it did a few times, added the output, even without the debug to help when it does happen.
			cout<<"\nSome crazy wormhole bullshit happened";
			cout<<"\nattackrun - "<<attackrun<<", pfleet[0][1] - "<<pfleet[0][1]<<", fleet[0][1]"<<fleet[0][1]<<", paggressive - "<<paggressive;
		}
	}
	destroypfleet();
}

void forclose()
{//player debt gets too high, bank starts taking stuff
	displayBreak();
	cout<<"\n\n***You have defaulted on your loan, the bank is now seizing your property!***\n";
	money += savings;//put any money you have in savings into your main money pile
	savings = 0;
	if (debt > money) 
	{//if your debt is greater than your money bank will take money and ships
		debt -= money;//take away as much money as you have from the debt
		money = 0;//you don't have any more money after you pay off the debt
		if (fleet[0][0] > 0)
		{//since you still owe more money the bank will take your first ship, and cargo
			cout<<"\nThe bank has seized ship# 1, and all goods on it, and sold it at auction.";
			debt -= (fleet[1][4] / 2); //gives you half cost for ship, no money for goods
			loseship(1); //take away the ship
		}
	}
	else if (debt <= money)
	{//if you have enough money to pay back debt than bank will just take the money
		money -= debt; //pay off debt
		debt = 0;
	}
	
	if (debt > money && fleet[0][0] < 1)
	{//if after paying as much as you can you don't have any money, or ships you lose
		cout<<"\nYou have no more money or property, but you still owe the bank money!";
		cout<<"\nYou'll have to go into hiding as a bum in the Flordidia System";
		cout<<"\nYou Lose!";
		gameover = 1; //gameover
		displayBreak();
	}
}

void day()
{//the flow of time, this should only include the code that needs to execute only when in space, all other day code goes in groundday
	int shipnum; //ship index number
	int planetnum; //index number of planets
	int tempplanetnum; //second index, for use in comparing 
	int taxed; //amount taxed
	/*
	A Note about day() and groundday():
	day needs to call pirate(), but groundday needs to be called by something above pirate, thus they needed to be separated (bad explanation)
	Instead of duplicating the code between the two (as I had been doing), now day calls groundday, thus anything that needs to be done both on the ground and in space goes in groundday
	*/
	stats.days_spent_traveling++;
	groundday(); //call ground day to do the stuff that gets done on the ground or in space
	money -= (fleet[0][0] * 3 * skill) + 3; //cost per day in space (fuel or whatever)

	for (shipnum = fleet[0][0]; shipnum > 0; shipnum--)
	{//loop through each ship, for the purpose of slow damage
		if (ran(1, 4) <= skill) 
		{//25% of losing a HP per day, simulates wear and tear
			fleet[shipnum][6]--; //takes HP from ship
			fleet[0][6]--; //takes HP from fleet
		}
		if (fleet[shipnum][6] <= 0)
		{
			displayBreak();
			cout<<"\nShip # "<<shipnum<<" has been destroyed during the journey!";
			loseship(shipnum);
			if (fleet[0][0] == 0) lostbattle; // Check if they still have ships or use escape pod
		}
	}
	if (ran (1, 10) == 1) pirates(); //1 in 10 odds of coming across another fleet	
}

void warn_low_hp_ships()
{
	for (int shipnum = fleet[0][0]; shipnum > 0; shipnum--)
	{
		if (fleet[shipnum][6] < 15)
		{
			displayBreak();
			cout<<"\nShip # "<<shipnum<<" is damaged, and may be lost during journey!";
		}
	}
}

void travel()
{//calculates travel
	if (fleet[0][0] < 1)
	{//no ship
		cout<<"\nHow do you plan to leave without a ship?";
		return;
	}
	else if (fleet[0][0] > 100)
	{//no ship
		cout<<"\nFleet too large, please reduce to less than 100 ships.";
		return;
	}

	warn_low_hp_ships();
	worlddisplay();
	speedship();
	senseship();
	cout<<"\nSpeed of the fleet is "<<fleet[0][1]<<".  Where do you want to go? ";
	cin>>travelto;
	if (money <= 100)
	{
		cout<<"\nYou don't have enough money";
	}
	else if (travelto < 1 || travelto > 20)
	{
		cout<<"\nI don't know where that is";
	}
	else if (travelto == curworld)
	{
		cout<<"\nUm, that's where we are now, maybe you need to get some rest";
	}
	else if (fleet[0][0] < 1)
	{
		cout<<"\nFirst we need a ship";
	}
	else if (playerleader > 0 && money < 100000)
	{//Warn if they're a leader of a civ and their money isn't at least 20k or something
		displayBreak();
		cout<<"\nTreasury is dangerously low.";
	}
	else if (travelto > 0 && travelto <= 20 && travelto != curworld && fleet[0][0] > 0 && money > 100)
	{//if it's a valid world to travel to we will do the calculations and travel there
		removeDisabledShips();
		if (debug) cout<<"\ndistances[travelto] - "<<distances[travelto]<<", fleet[0][1] - "<<fleet[0][1];
		traveltime = ceil(1.0 * distances[travelto] / fleet[0][1]); //travel time is just the distance divided by the fleet speed
		cout<<"\nDistance is "<<distances[travelto]<<", speed of the fleet is "<<fleet[0][1]<<", travel time will be "<<traveltime;
		cout<<((traveltime == 1) ? " day." : " days.");
		
		previous_world = curworld;
		curworld = travelto; //sets the curworld to the travel to world
		if (playerciv != world[curworld][3]) 
		{//if the player isn't this world's civ then he gets a 5% penalty on any purchases
			worldpen = badworld;
		}
		else if (playerciv == world[curworld][3])
		{//if the player is the world's civ he gets a 1% penalty on any purchases
			worldpen = goodworld;
		}
		for (;traveltime > 0; traveltime--)
		{//loop through the travel time, letting one day pass for each unit of travel time
			day();
		}
		
		goods[curworld][1][2] = goods[curworld][1][1]; //updates the price list for this world
		goods[curworld][2][2] = goods[curworld][2][1];
		goods[curworld][3][2] = goods[curworld][3][1];
		goods[curworld][4][2] = goods[curworld][4][1];
		goods[curworld][5][2] = goods[curworld][5][1];
		visit[curworld] = cday; //the date of the price data
		findPriceExtremes();
		calcDistances();
		//worlddisplay();
		if (debt > 125000 && ran(1,10) == 1) forclose();//max debt you can have is 125,000 after that bank starts taking your stuff
	}
	else 
	{
		cout<<"\nCan't let you do that";
	}
	
}

void playersetup()
{//player picks his civ
	int newciv; //the civ player is switching to
	int confirm; //user confirmation
	
	/*
	Neutral
	Galactic Star Empire
	United Republic of Planets
	*/
	if (playerleader == 0)
	{//not a civ leader, gets the standard player civ change stuff
		cout<<"\nWelcome to player set up";
		cout<<"\nYou are currently a member of ";
		if (playerciv == 0) cout<<"no civilization";
		if (playerciv == 1) cout<<"The Galactic Star Empire";
		if (playerciv == 2) cout<<"The United Republic of Planets";
		cout<<"\nindependent planets - "<<civ[0];
		cout<<"\nPlanets under the control of The Galactic Star Empire - "<<civ[1];
		cout<<"\nPlanets under the control of The United Republic of Planets - "<<civ[2];
		cout<<"\nPick your alignment, 0 - Neutral, 1 - Galactic Star Empire, Cost - "<<(civ[1] * 50) + 100<<", 2 - United Republic of Planets, Cost - "<<(civ[2] * 50) + 100<<" ";
		cin>>newciv; //player picks civ
		if (newciv != playerciv && newciv == 0)
		{//player chooses neutral
			cout<<"\nEnter 138 to confirm Neutral, this is free ";
			cin>>confirm;
			if (confirm == 138) playerciv = 0; //if the confirmation was 138 than we switch to neutral
		}
		else if (newciv != playerciv && newciv == 1  && money >= civ[1] * 50)
		{//player chooses GSE
			cout<<"\nEnter 138 to confirm Galactic Star Empire, this will cost "<<(civ[1] * 50) + 100<<" ";
			cin>>confirm;
			if (confirm == 138 && money >= civ[1] * 50) 
			{//if the confirmation was 138 and the player has the money we switch to neutral
				playerciv = 1;
				money -= (civ[1] * 50) + 100; //take the money for the membership dues
			}
		}
		else if (newciv != playerciv && newciv == 2  && money >= civ[2] * 50)
		{//player chooses URP
			cout<<"\nEnter 138 to confirm United Republic of Planets, this will cost "<<(civ[2] * 50) + 100<<" ";
			cin>>confirm;
			if (confirm == 138 && money >= civ[2] * 50) 
			{//if the confirmation is 138 and player has the money we switch
				playerciv = 2;
				money -= (civ[2] * 50) + 100; //take the money for the membership dues
			}
		}
	}
	else if (playerleader > 0)
	{//player is a civ leader this is the civ management
		cout<<"\nWelcome leader of ";
		if (playerleader == 0) cout<<"no civilization";
		if (playerleader == 1) cout<<"The Galactic Star Empire";
		if (playerleader == 2) cout<<"The United Republic of Planets";
		cout<<"\nindependent planets - "<<civ[0];
		cout<<"\nPlanets under the control of The Galactic Star Empire - "<<civ[1];
		cout<<"\nPlanets under the control of The United Republic of Planets - "<<civ[2];
		cout<<"\nYour current tax rate is "<<playertax<<"% your Defense spending per planet is "<<defense<<", treasury is "<<money;
		cout<<"\nEnter 138 to change them ";
		cin>>confirm; //change tax and defense spending
		if (confirm == 138)
		{
			cout<<"\nEnter new tax rate as a percentage, followed by new defense per planet ";
			cin>>playertax; //new tax
			cin>>defense; //new defense spending
			//you can goto flips to see how tax and defense work, I took these two comments from there to help explain here
			//add players defense spending to inf, 10k is neutral, anything less hurts anything more helps, every 500 either way is 1 inf point
			//decide if planets will rebel because of taxes.  10% taxes should yield 1/50 odds of rebellion.  Odds for rebellion are taxes / 500
			if (playertax < 0 || playertax > 100)
			{//make sure it's a real percentage
				cout<<"\nInvalid amount, defaulting to 10%";
				playertax = 10; 
			}
			if (defense < 0) defense = 0; //user input checking
		}
	}
}

void calcoptimal()
{//calculate the optimal shipping route
	//we will just brute force every possible route/good combo (20*20*5*5 = 10000)
	//flaws in logic:
	//doesn't consider external costs, like debt or taxes or risk of pirate attack
	//doesn't consider possibility of buying nothing at one of the worlds (unless there is a good that exceeds money)
	int bestincome = 0; //the income of the best route
	int bestworld[3]; //best worlds [1] and [2]
	int bestgood[3]; //best goods at those same worlds
	int numgooda; //the number of goods
	int numgoodb; //number of goods
	int profit; //profit from route being tested
	float pena; //world penalty
	float penb; //world penalty
	int besttravel; //travel time of best route
	int cost; //cost of goods
	
	speedship(); //make sure our speed data is up to date
	if (fleet[0][1] < 1) return; //speed, prevent divide by zero
	for (int worlda = 1; worlda <= 20; worlda++)
	{//loop through all the worlds, compare each possible combo
		for (int worldb = 1; worldb <= 20; worldb++)
		{//just brute forcing 20 * 20 * 5 * 5 = 10,000
			if (worlda >= worldb) continue; //same world, can't be a route
			if (playerciv != world[worlda][3])
			{//if the player isn't this world's civ then he gets a 5% penalty on any purchases
				pena = badworld;
			}
			else if (playerciv == world[worlda][3])
			{//if the player is the world's civ he gets a 1% penalty on any purchases
				pena = goodworld;
			}
			if (playerciv != world[worldb][3]) 
			{//if the player isn't this world's civ then he gets a 5% penalty on any purchases
				penb = badworld;
			}
			else if (playerciv == world[worldb][3])
			{//if the player is the world's civ he gets a 1% penalty on any purchases
				penb = goodworld;
			}
			
			for (int gooda = 1; gooda <= 5; gooda++)
			{//loop through each of the 5 goods
				for (int goodb = 1; goodb <= 5; goodb++)
				{//loop through each of the 5 goods
					if (gooda == goodb) continue; //same good, doesn't make sense to trade
					dis[1] = 10 * abs(world[worlda][1] - world[worldb][1]); //x
					dis[2] = 10 * abs(world[worlda][2] - world[worldb][2]); //y
					// Can't use distances[] array, maybe make new method that takes in a planet num and returns a distances[] array?
					dis[3] = sqrt((dis[1] * dis[1]) + (dis[2] * dis[2])); //finds distance a^2 + b^2 = c^2
					traveltime = ceil(1.0 * dis[3] / fleet[0][1]);
					numgooda = int(money / (goods[worlda][gooda][2] * pena)); //how many goods can we buy
					numgoodb = int(money / (goods[worldb][goodb][2] * penb)); //how much can we buy
					if (numgooda > fleet[0][2]) numgooda = fleet[0][2]; //exceeds cargo space
					if (numgoodb > fleet[0][2]) numgoodb = fleet[0][2]; //exceeds cargo space
					cost = (numgooda * goods[worlda][gooda][2] * pena) + (numgoodb * goods[worldb][goodb][2] * penb); //what's the cost to buy?
					profit = (numgooda * goods[worldb][gooda][2] * (2-penb)) + (numgoodb * goods[worlda][goodb][2] * (2-pena)); //price sold?
					profit -= cost; //price sold minus cost to buy is profits
					if (traveltime == 0)
					{
						// TODO: Remove if this never happens for a while
						cout<<"\n!!! traveltime is 0 !!!\n";
						cout<<"\ndis[3] = "<<dis[3];
						cout<<"\nfleet[0][1] = "<<fleet[0][1];
						cout<<"\ntraveltime = "<<traveltime;
						return;
					}
					profit /= (traveltime*2); //round trip
					if (profit > bestincome)
					{//this is the best route found so far
						if (debug)
						{
							cout<<"\n\nBest world:";
							cout<<"\nworlda - "<<worlda<<", worldb - "<<worldb;
							cout<<"\ngooda - "<<gooda<<", goodb - "<<goodb;
							cout<<"\nnumgooda - "<<numgooda<<", numgoodb - "<<numgoodb;
							cout<<"\nGood A, Sell - "<<goods[worldb][gooda][2] * (2-penb)<<", Buy - "<<goods[worlda][gooda][2] * pena;
							cout<<"\nGood B, Sell - "<<goods[worlda][goodb][2] * pena<<", Buy - "<<goods[worldb][goodb][2] * (2-penb);
							cout<<"\nA - "<<(numgooda * goods[worldb][gooda][2] * (2-penb))<<", B - "<<(numgoodb * goods[worlda][goodb][2] * (2-pena));
						}
						bestincome = profit;
						bestworld[1] = worlda;
						bestworld[2] = worldb;
						bestgood[1] = gooda;
						bestgood[2] = goodb;
						besttravel = traveltime;
					}
				}
			}
		}
	}
	
	cout<<"\n\nOptimal Trade Route:";
	cout<<"\nAt world "<<bestworld[1]<<" buy good "<<bestgood[1]<<" ";
	cout<<"\nSell it at world "<<bestworld[2]<<" and buy good "<<bestgood[2]<<" there.";
	cout<<"\nExpected profit/day - "<<bestincome;
	cout<<"\nOne way travel time - "<<besttravel;
}

void flipsetting(int& x)
{//flips the value passed to it, from 0 to 1 or vice versa
	x--; //if it was 1 it will now be 0 (false)
	if(x) x=1; //if it is true then it was 0, so it should now be 1
	return;
}

void bar()
{//bar where various underworld transactions take place, gambling, secrets, mercenaries, and for some reason challenging civ leader
/*
Ideas for bar:
some kind of illegal stolen goods
multiple gambling games
some non gambling games
buy something high cost high value, maybe something that gives you updated prices on all worlds
some kind of influence on the war
some kind of updated info on war

*/
	int barchoice; //players choice in bar
	int datachoice; //players choice to buy would data
	int dataprice; //the price of the world data
	int rebelchoice; //players choice for the rebels
	int rebelcontrol; //civ to control planet if rebels succeed
	int rebelworld; //world that rebellion will attack on
	
	calcassets();
	cout<<"\nWelcome to the world "<<curworld<<" bar.";
	cout<<"\nWhat would you like to do?\n1 - Gamble, 2 - Buy updated world data, 3 - Talk to old man, 4 - Mercenaries, 5 - Buy transceiver, 6 - Find optimal trade route ";
	if (assets > 100000 && fleet[0][0] > 10 && playerciv > 0 && playerleader == 0) 
	{//if player meets requirements let him challenge leader, reqs are over 100,000 in assets, more than 10 ships, member of civ, not current leader
		cout<<"\n9 - Challenge leader of ";
		if (playerciv == 1) cout<<"The Galactic Star Empire";
		if (playerciv == 2) cout<<"The United Republic of Planets";
		cout<<" ";
	}
	cin>>barchoice;//user decided what he wants
	if (barchoice == 1)
	{//gambling goto the function already made for it
		gamble();
	}
	else if (barchoice == 2)
	{// buy updated price data, same as talk to other ships, but you pay 1000 here
		dataprice = 500; //set to 1000, used to have worldpen, but took it off here
		cout<<"\nA man offers to sell you updated world data for an unknown number of worlds, for "<<dataprice;
		cout<<"\nIs it a deal? 1 - Yes, 2 - No ";
		cin>>datachoice;//decide if they want to buy it or not
		if (datachoice == 1 && money > dataprice)
		{//yes they buy it
			money -= dataprice;//takes price for data
			piratetalk();//give the actual data
		}
	}
	else if (barchoice == 3)
	{//secrets
		dataprice = 1000;//no world pen
		cout<<"\nAn old man offers to give you secret advice for "<<dataprice;
		cout<<"\nIs it a deal? 1 - Yes, 2 - No ";
		cin>>datachoice;// buy secret yes or no
		if (datachoice == 1 && money > dataprice)
		{//yes they buy a secret
			money -= dataprice;
			oldman();
		}
	}
	else if (barchoice == 4)
	{//hire mercenaries to try to take over control of planet, and give it to whatever faction you choose.
		cout<<"\nThe local rebel leader would be willing to attempt a coup against the ";
		if (world[curworld][3] == 1) cout<<"Galactic Star Empire";
		if (world[curworld][3] == 2) cout<<"United Republic of Planets";
		if (world[curworld][3] == 0) cout<<"opposing rebel forces";
		cout<<" that currently control this place.";
		cout<<"\nThat is, if the price was right.";
		cout<<"\nHow does 50000 sound?";
		cout<<"\n1 - It sounds right!, 2 - No way, 3 - How about 25000 ";
		cin>>rebelchoice;//decide yes or no, or bargain
		if (rebelchoice == 1 && money >= 50000)
		{//pay the 50k for a rebellion
			cout<<"\nOk, and if we are victorious who do you want put in control?";
			cout<<"\n1 - Galactic Star Empire, 2 - United Republic of Planets, 0 - Neutral ";
			cin>>rebelcontrol;//decide who will get the planet
			if (rebelcontrol >= 0 && rebelcontrol < 3)
			{//if you pick a valid choice then it goes ahead, if not nothing
				cout<<"Ok, we'll start planning our attack immediately!";
				rebel[curworld][1] = 1; //set first index to 1, as a flag that rebellion is pending
				rebel[curworld][2] = rebelcontrol; //set second index to whoever player wants to control planet
				rebel[0][0]++; //add one more pending rebellion to total
				money -= 50000;
			}
		}
		else if (rebelchoice == 2)
		{//choice not to pay, nothing
			cout<<"\nFine, our services aren't cheap";
		}
		else if (rebelchoice == 3 && money >= 25000)
		{//try to bargain, I don't think this ever works but I guess it may, I leave it in here so people can waste time trying
			if (ran (1, assets + 2000) > 1000)
			{//if a rand num from 1 to your assets + 2000 is over 1000 no deal.  Since you need 25k just to get here your assets are at least 25k (unless you have lots of debt I guess)
				cout<<"\nNo way!  Our services aren't cheap ";
				return;
			}
			else
			{//they go for the bargain
				cout<<"Ok fine, but only because we support your cause.  If we are victorious who do you want put in control?";
				cout<<"\n1 - Galactic Star Empire, 2 - United Republic of Planets, 0 - Neutral ";
				cin>>rebelcontrol;
				if (rebelcontrol >= 0 && rebelcontrol < 3)
				{//choose the new owner after rebellion
					cout<<"Ok, we'll start planning our attack immediately!";
					rebel[curworld][1] = 1; //set first index to 1, as a flag that rebellion is pending
					rebel[curworld][2] = rebelcontrol; //set second index to whoever player wants to control planet
					rebel[0][0]++; //add one more pending rebellion to total
					money -= 25000;
				}
			}
		}
	}
	else if (barchoice == 5)
	{//a transceiver to allow daily updated price data
		cout<<"\nA transceiver will receive updated price data every day.  ";
		cout<<"\nA class B transceiver will receive some updates, and a class A will receive all updates.";
		cout<<"\n1 - Class B transceiver for "<<classbprice<<", 2 - Class A transceiver for "<<classaprice<<" ";
		cin>>datachoice;
		if (datachoice == 2 && money > classaprice)
		{
			transceiver = 2;
			money -= classaprice;
		}
		else if (datachoice == 1 && money > classbprice)
		{
			transceiver = 1;
			money -= classbprice;
		}	
	}
	else if (barchoice == 6)
	{//calculate the optimal trade route
		cout<<"\nThe navigational computer can determine the optimal trade route for you (based on your price data). ";
		cout<<"\nYou can also buy your own navigational computer for a constantly updated optimal route. ";
		cout<<"\n1 - Get a single optimal route for "<<routeprice<<", 2 - Purchase your own navigational computer for "<<navcompprice<<" ";
		cin>>datachoice;
		
		if (datachoice == 1 && money > routeprice)
		{//single route calculation
			money -= routeprice;
			calcoptimal();
		}
		else if (datachoice == 2 && money > navcompprice)
		{//nav comp for constant route calculations
			navcomp = 1;
			money -= navcompprice;
		}	
	}
	
	
	else if (barchoice == 9 && assets > 100000 && fleet[0][0] > 10 && playerciv > 0 && playerleader == 0)
	{//challenge the civ leader
		displayBreak();
		cout<<"\nIf you fail you will surely be caught and punished, the leader will have the entire fleet of his civilization at his disposal.";
		cout<<"\nAre you sure?  Enter 138 to confirm ";
		cin>>rebelchoice;//reused rebelchoice here, don't be confused
		if (rebelchoice == 138) bosspirates();
	}
}

void options()
{//player options
	// TODO: Show current options
	int opt; //store the option being set
	do
	{
		// Should this be two levels deep, or just all listed on one page with double digit options?
		cout<<"\n\n1-Change map mode, 2-Change price display mode, 3-Set max fleet size, 4-Set reserve money, 5-Set autofight strategy";
		cout<<"\n6-Set disabled ship display mode";
		cout<<"\n7-Show player stats, 8-Show game help, 9-Explain options, 0-Return to game ";
		cin>>opt;
		if (opt==1) flipsetting(mapmode);
		if (opt==2) flipsetting(pricemode);
		if (opt==3)
		{
			cout<<"\nEnter your preferred max fleet size (default 100): ";
			cin>>max_ships_to_keep;
			if (max_ships_to_keep < 0 || max_ships_to_keep > 120)
			{
				cout<<"\nInvalid selection, using default of 100";
				max_ships_to_keep = 100;
			}
		}
		if (opt==4)
		{
			cout<<"\nEnter your preferred reserve cash amount (default 150): ";
			cin>>reserve_money;
			if (reserve_money < 0 || reserve_money > 1000000)
			{
				cout<<"\nInvalid selection, using default of 150";
				reserve_money = 150;
			}
		}
		if (opt==5)
		{
			cout<<"\nPossible autofight targets:";
			cout<<"\n0 - First ship, 1 - Min HP, 2 - Max HP, 3 - Min attack, 4 - Max attack, 5 - Min HP percentage, 6 - Min HP/attack ratio, 7 - Random";
			cout<<"\nEnter your preferred autofight strategy: ";
			cin>>player_battle_strategy;
			if (player_battle_strategy < 0 || player_battle_strategy > 7)
			{
				cout<<"\nInvalid selection, using default of 1";
				player_battle_strategy = 1;
			}
		}
		if (opt==6)
		{
			cout<<"\nEnter display mode for disabled ships during combat:";
			cout<<"\n0-Display as normal, 1-Show a 'D' at beginning of line, 2-Hide disabled ships: ";
			cin>>disabled_ship_display_mode;
			if (disabled_ship_display_mode < 0 || disabled_ship_display_mode > 2)
			{
				cout<<"\nInvalid disabled ship display mode, using default of 1";
				disabled_ship_display_mode = 1;
			}
		}
		if (opt==7) stats.display();
		if (opt==8) help();
		if (opt==9)
		{
			cout<<"\nChange Map Mode:";
			cout<<"\nToggles between the two available map modes.";
			cout<<"\nThe first map mode shows planet number, owners, and your location on one large grid.";
			cout<<"\nThe second map mode displays 3 small grids.";
			cout<<"\nOne showing owners, another one showing planet numbers, and one showing your location, and distances to other planets.";
			cout<<"\n";
			cout<<"\nPrice Display Mode:";
			cout<<"\nToggles between price display modes.";
			cout<<"\nThe first price display mode shows just numbers in a grid, with the names of goods as a header.";
			cout<<"\nThe second price display mode shows the names of goods next to the prices.";
			cout<<"\n";
			cout<<"\nMax Fleet Size:";
			cout<<"\nThis is your preferred maximum fleet size, when buying 'as many as possible' or doing a filtered sale.";
			cout<<"\nThere is a hard limit of 100 ships allowed before you can ship out.";
			cout<<"\n";
			cout<<"\nReserve money:";
			cout<<"\nThis is the money you want to keep available when doing a 'as much as possible' purchase.";
			cout<<"\n";
			cout<<"\nAutofight Strategy";
			cout<<"\nDuring autofight your computer will choose one enemy ship to target and then continue firing until it's destroyed.";
			cout<<"\nIt will then choose another ship to target, and continue until all enemy ships are destroyed, or you are destroyed.";
			cout<<"\nThe strategies here determine which ship you will target.";
			cout<<"\n";
			cout<<"\nDisabled Ship Display Mode";
			cout<<"\nDetermines how to display disabled ships during combat.";
			cout<<"\nYour options are to either show them the same way as any other ship.";
			cout<<"\nOr to put a 'D' at the start of their lines, and shift over everything to make them stand out.";
			cout<<"\nOr to hide them entirely.";
		}
	} while (opt != 0);
}

void debugoutput()
{//displays debug info
/*
int ships[10][10][50]; //stats on the ships for sale
int fleet[100][20]; //ships in your fleet, x = index, y = stats 1 - speed, 2 - cargo, 3 - attack, 4 - cost, 5 - sensor range, 6 - hit points, 7 - max HP, 8 - class, 9 - model, 10 - total cargo, 11+ goods
int pfleet[100][20]; //ships in a pirate fleet
int world[21][20]; //worlds, x = index, y = stats
int goods[21][10][3]; //prices of the goods
int goodschange[21][10]; //the amount change in prices
int upgrade[21][10][3]; //prices of the ship upgrades
int inf[3]; //influence on the worlds
int dis[4]; //distance to other worlds
int cday; //the current day
int debug = 0; //sets mode to debug mode
int curworld = 3; //the world the player is currently on
int money; //player money
int savings; //players savings
int debt; //amount of debt player has
int assets; //players total assets
float worldpen = 1.01; //penalty for being on a world not belonging to your civ
int playerciv; //civ of the player
int play; //do you want to continue to play
int traveltime; //time it will take to travel any given distance
int travelto; //world to travel to
int civ[3]; //total number of worlds each civ owns
float taxper; //percentage of tax you will pay
int skill; //player skill level
int pmoney; //pirates money
bool paggressive; //are the pirates aggressive
bool bossfight; //will determine if it's a boss fight or not
int rebel[21][10] //1 if attack pending, 2 who will control planet
*/
	int x, y, z;
	debug=138;
	cout<<"\nDebug Info:\n";
	cout<<"\nMoney - "<<money<<", Day - "<<cday;
	for (x = 0; x <= fleet[0][0] + 3; x++)
	{
		cout<<"\n\nShip # "<<x;
		for(y = 0; y <= 19; y++)
		{
			cout<<" Item # "<<y<<" - "<<fleet[x][y];
		}
	}
	for (x = 0; x <= 20; x++)
	{
		cout<<"\n\nWorld # "<<x;
		for(y = 0; y <= 19; y++)
		{
			cout<<" Item # "<<y<<" - "<<world[x][y];
		}
	}
	for (x = 0; x <= 20; x++)
	{
		cout<<"\n\nGood # "<<x;
		for(y = 0; y <= 9; y++)
		{
			for (z = 0; z <= 2; z++)
			{
				cout<<" Item # "<<y<<" - "<<goods[x][y][z];
			}
		}
	}
	for (x = 0; x <= 20; x++)
	{
		cout<<"\n\nRebel # "<<x;
		for(y = 0; y <= 9; y++)
		{
			cout<<" Item # "<<y<<" - "<<rebel[x][y];
		}
	}
}

void start()
{//start up screen, gets skill level, and displays help
	/*
	float interest; //debt interest
	float badworld; //worldpen for a world with a different civ
	float goodworld; //worldpen for a world with same civ
	float civpen; //pen for players civ in likelihood of getting planets in a flip
	float scorepen; //used to adjust score for skill level
	*/
	cout<<"\nPirate2 by Dale Swanson!";
	do
	{//loop until play makes valid choice
		cout<<"\nEnter skill level 1 - Easy, 2 - Normal, 3 - Hard, 0 - Help ";
		cin>>skill; //get skill level from player
		if (skill == 1) 
		{//easy
			cout<<"\nOk, baby...";
			money = 10000;
			debt = 0;
			interest = 1.006;
			badworld = 1.03;
			goodworld = 1.01;
			civpen = 1.1;
			scorepen = 0.1;
			classaprice = 8000;
			classbprice = 3000;
		}
		else if (skill == 2) 
		{//normal
			cout<<"\nNow we're talking.";
			money = 0;
			debt = 0;
			interest = 1.01;
			badworld = 1.05;
			goodworld = 1.01;
			civpen = 1;
			scorepen = 1;
			classaprice = 20000;
			classbprice = 7500;
		}
		else if (skill == 3) 
		{//hard
			cout<<"\nYou're a braver man than I!";
			money = 0;
			debt = 10000;
			interest = 1.02;
			badworld = 1.1;
			goodworld = 1.03;
			civpen = 0.9;
			scorepen = 11;
			classaprice = 100000;
			classbprice = 25000;
		}
		else if (skill == 138)
		{//special
			cout<<"\nEnter starting money: ";
			cin>>money;
			cout<<"\nEnter 138 to turn debug mode on ";
			cin>>debug;
			debt = 0;
			interest = 1.01;
			badworld = 1.05;
			goodworld = 1.01;
			civpen = 1;
			skill = 2;
			scorepen = 1;
			stats.money_from_cheating += money;
			stats.cheats_used++;
		}
		else
		{//help
			cout<<"\nHelp!";
			help();
		}
	}
	while (skill != 1 && skill != 2 && skill != 3 && skill != 138); //continue looping until player picks a skill
	if (debug)
	{//give some goodies for debug mode
		navcomp=1;
		transceiver=2;
	}
}

int main()
{//main loop, displays main menu, calls all the above functions, exits game
    time_t sseconds; //start seconds, will be used to seed the rng
    time(&sseconds); //get our seed for rng
    srand((unsigned int) sseconds); //seed rng
	int confirm;
	int days;
	start(); //get user input on skill
	money += 3; //3 free dollars since first day is automatic, and you'll lose 3 dollars before you begin
	worldsetup(); //setup the planets
	shipsetup(); //setup ships
	groundday(); //run the first day
	goods[curworld][1][2] = goods[curworld][1][1]; //give you good prices for current world
	goods[curworld][2][2] = goods[curworld][2][1];
	goods[curworld][3][2] = goods[curworld][3][1];
	goods[curworld][4][2] = goods[curworld][4][1];
	goods[curworld][5][2] = goods[curworld][5][1];
	visit[curworld] = cday; //the date of the price data
	findPriceExtremes();
	
	do
	{//main loop of the game, will continue until play equals 0
		listAbridgedShips();
		worlddisplay();
		calcassets();
		cout<<"\nWelcome to world "<<curworld<<"!  What would you like to do?";
		printf("\nDay - %d, Money - %'d, Savings - %'d, Debt - %'d, Assets - %'d, Cargo Space - %'d, Cargo Used - %'d", cday, money, savings, debt, assets, fleet[0][2], fleet[0][10]);
		cout<<"\n1-Buy/Sell Goods, 2-Visit Ship Yard, 3-Bank, 4-Ship Out, 5-Manage Cargo, 6-Bar, 7-Player Setup, 8-Rest, 9-Options, 0-Exit ";
		cin>>play;
		if (gameover == 1) play = 0;
		if (play == 1)
		{//Buy/Sell Goods
			buygoods();
		}
		else if (play == 2)
		{//Visit Ship Yard
			buyship();
		}
		else if (play == 3)
		{//Bank
			bank();
		}
		else if (play == 4)
		{//Ship Out
			travel();
		}
		else if (play == 5)
		{//Manage Cargo
			manage();
		}
		else if (play == 6)
		{//Bar
			bar();
		}
		else if (play == 7)
		{//player setup
			playersetup();
		}
		else if (play == 8)
		{//rest
			cout<<"\nHow many days do you want to rest for? ";
			cin>>days;
			for(; days > 0; days--)
			{
				groundday();
				stats.days_spent_resting++;
				if (debt > 125000 || money < 10)
				{
					cout<<"\nYou can't rest while your finances are in such bad shape.";
					break; //max debt you can have is 125,000 after that bank starts taking our stuff
				}
			}
		}
		else if (play == 9)
		{//options
			options();
		}
		else if (play == 10)
		{//testing stuff
			bosspirates();
		}
		else if (play == 138)
		{//debug
			debugoutput();
		}
		else if (play == 0)
		{//end
			cout<<"\nAre you sure you want to leave?  Enter 138 to confirm ";
			cin>>confirm;
			if (confirm == 138) gameover = 1;//user ends game
		}
	} while (gameover == 0);
	
	displayBreak();
	stats.display();
	cout<<"\n";
	if (ran(1, 4) == 1) oldman(); //25% of a free secret on exit.
	cout<<"\nGood bye\n";
    system("PAUSE");
    return EXIT_SUCCESS;
}
