--[[
Source code for Company
Copyright Nakano 2011.
License: No specific license. Code may be used for non-commercial / non-profitable purposes.
                        
 ######## VERSION HISTORY ##########
 # v0.1 05/21/2011 by Nakano       #
 # * initial release for           #
 #   PSP Genesis Competition 2011  #
 # v1.0 07/22/2011 by Nakano       #
 # * Release for NEO Compo 2011    #
 # v1.1 09/16/2011                 #
 # * Added a new option to set time#
 #   how long game info texts are  #
 #   shown.                        #
 ###################################
 --]]
 
math.randomseed( os.time() ); -- random seed
 
-- FONT DIFFERENCE (LUA EUPHORIA (83) VS LUADEV (94)) 
yDifference = 10;
 
-- COLORS
gray = color.new(180, 180, 180);
white = color.new(255, 255, 255);
black = color.new(0, 0, 0);
darkgray = color.new(100, 100, 100);
lime = color.new(50,205,50);
red = color.new(255,0,0);
lightblue = color.new(64,255,255);
yellow = color.new(255,215,0);
blue = color.new(65, 105, 225);

playColor = blue;
discardColor = black;
errorColor = red;
shadowColor = nil;

-- CPU DIFFICULTY COLOR
cpuEasyColor = color.new(38, 96, 10);
cpuMediumColor = yellow;
cpuHardColor = red;

-- LOGO
logo = image.load("images/neoflash.png");

deck = {}
currentCard = nil;
maxHandSize = 7;
playersSize = 4;
sellCompanyMin = 0;
userOptions = {"4", "yes", "easy", "$0", 1}
difficulty = {"easy", "easy", "easy"} -- difficulty of cpu
cardMax2 = {} -- card names that only exist 2 or less (for cpu logic)
curStyle = 1;
waitSeconds = 2; -- wait time for showing image
playMode = ""; -- arcade, story

-- BONUSES
randomBonus = false;
moderateBonus = false;
extremeBonus = false;
cardListBonus = false;

rotateTableBonus = false;
rotateHandsBonus = false;
newIdentityBonus = false;
sabotageBonus = false;

-- MUSIC
allowMusic = true;
musicGame = "music/game.mp3"

-- SOUND EFFECTS
allowSoundEffects = true;
soundObject = nil
soundPlayMoneyCard = "sounds/money.wav"
soundPlayThreatCard = "sounds/threat.wav"
soundPlaySafeCard = "sounds/bank.wav"
soundPlayRemoveCard = "sounds/remove.wav"
soundPlayThiefCard = "sounds/thief.wav"
soundPlayLuckCard = "sounds/luck.wav"
soundPlayCompanyCard = "sounds/company.wav"
soundPlayBankruptcyCard = "sounds/bankruptcy.wav"
soundPlayRotateCard = "sounds/rotate.wav"
soundPlayRobberyCard = "sounds/robbery.wav"
soundPlayNewBeginningCard = "sounds/newbeginning.wav"
soundPlaySabotageCard = "sounds/sabotage.wav"
soundPlayDealCard = "sounds/deal.wav"
soundPlayNewIdentityCard = "sounds/newidentity.wav"

-- ANALOG STICK
waitAnalog = 0
waitMoment = os.clock()

freeStyle = function()
	-- Free memory
	image.free(storyMenu)
	image.free(arcadeVisible)
	image.free(arcadeHide)
	image.free(storyVisible)
	image.free(storyHide)
	image.free(optionsVisible)
	image.free(optionsHide)
	image.free(options)
	image.free(menu)
	image.free(background)
	image.free(cardList)
	image.free(keys)
	image.free(results1)
	image.free(results2)
	image.free(results3)
	image.free(leftArrow)
	image.free(rightArrow)
	image.free(messageBox)
	image.free(companyBox)
	image.free(selector)
	image.free(selector2)
	image.free(selector3)
	image.free(targeter)
	image.free(p1)
	image.free(p2)
	image.free(p3)
	image.free(p4)
	image.free(cardBackSmall)
	image.free(cardOpenCompany)
	image.free(cardOpenCompanySmall)
	image.free(card15000)
	image.free(card15000Small)
	image.free(card25000)
	image.free(card25000Small)
	image.free(card50000)
	image.free(card50000Small)
	image.free(card100000)
	image.free(card100000Small)
	image.free(cardSellCompany)
	image.free(cardSellCompanySmall)
	image.free(cardThief)
	image.free(cardThiefSmall)
	image.free(cardSmallSafe)
	image.free(cardSmallSafeSmall)
	image.free(cardBigSafe)
	image.free(cardBigSafeSmall)
	image.free(cardConviction)
	image.free(cardConvictionSmall)
	image.free(cardRemoveConviction)
	image.free(cardRemoveConvictionSmall)
	image.free(cardTaxEvasion)
	image.free(cardTaxEvasionSmall)
	image.free(cardRemoveTaxEvasion)
	image.free(cardRemoveTaxEvasionSmall)
	image.free(cardStrike)
	image.free(cardStrikeSmall)
	image.free(cardRemoveStrike)
	image.free(cardRemoveStrikeSmall)
	image.free(cardEcoCrime)
	image.free(cardEcoCrimeSmall)
	image.free(cardRemoveEcoCrime)
	image.free(cardRemoveEcoCrimeSmall)
	image.free(cardBribe)
	image.free(cardBribeSmall)
	image.free(cardBankruptcy)
	image.free(cardBankruptcySmall)
	image.free(cardDeal)
	image.free(cardDealSmall)
	image.free(cardNewBeginning)
	image.free(cardNewBeginningSmall)
	image.free(cardRobbery)
	image.free(cardRobberySmall)
	image.free(cardBanker)
	image.free(cardBankerSmall)
	image.free(cardLuck)
	image.free(cardLuckSmall)
	image.free(cardRotateTable)
	image.free(cardRotateTableSmall)
	image.free(cardRotateHands)
	image.free(cardRotateHandsSmall)
	image.free(cardNewIdentity)
	image.free(cardNewIdentitySmall)
	image.free(cardSabotage)
	image.free(cardSabotageSmall)
	collectgarbage()
end

setStyle = function(clear)
	
	if (clear) then
		draw.fillrect(30,100,421,90,black)
		screen.print(240, 150 - yDifference, "Changing style. Please wait...", 1.0, lightblue, shadowColor, "center");
		
		screen.flip()
		freeStyle()
	end
	
	-- Load new images
	storyMenu = image.load("images/style" .. curStyle .."/storyMenu.png");
	arcadeVisible = image.load("images/style" .. curStyle .."/arcadeVisible.png");
	arcadeHide = image.load("images/style" .. curStyle .."/arcadeHide.png");
	storyVisible = image.load("images/style" .. curStyle .."/storyVisible.png");
	storyHide = image.load("images/style" .. curStyle .."/storyHide.png");
	optionsVisible = image.load("images/style" .. curStyle .."/optionsVisible.png");
	optionsHide = image.load("images/style" .. curStyle .."/optionsHide.png");
	options = image.load("images/style" .. curStyle .. "/options.png");
	menu = image.load("images/style" .. curStyle .. "/menu.png");
	background = image.load("images/style" .. curStyle .. "/background.png");
	cardList = image.load("images/style" .. curStyle .. "/cardList.png")
	keys = image.load("images/style" .. curStyle .. "/keys.png");
	results1 = image.load("images/style" .. curStyle .. "/results1.png")
	results2 = image.load("images/style" .. curStyle .. "/results2.png")
	results3 = image.load("images/style" .. curStyle .. "/results3.png")
	leftArrow = image.load("images/style" .. curStyle .. "/leftArrow.png")
	rightArrow = image.load("images/style" .. curStyle .. "/rightArrow.png")
	messageBox = image.load("images/style" .. curStyle .. "/messageBox.png");
	companyBox = image.load("images/style" .. curStyle .. "/companyBox.png");
	selector = image.load("images/style" .. curStyle .. "/selector.png");
	selector2 = image.load("images/style" .. curStyle .. "/selector2.png");
	selector3 = image.load("images/style" .. curStyle .. "/selector3.png");
	targeter = image.load("images/style" .. curStyle .. "/targeter.png");
	p1 = image.load("images/style" .. curStyle .. "/p1.png");
	p2 = image.load("images/style" .. curStyle .. "/p2.png");
	p3 = image.load("images/style" .. curStyle .. "/p3.png");
	p4 = image.load("images/style" .. curStyle .. "/p4.png");
	cardBackSmall = image.load("images/style" .. curStyle .. "/cardBackSmall.png");
	cardOpenCompany = image.load("images/style" .. curStyle .. "/cardOpenCompany.png");
	cardOpenCompanySmall = image.load("images/style" .. curStyle .. "/cardOpenCompanySmall.png");
	card15000 = image.load("images/style" .. curStyle .. "/card15000.png");
	card15000Small = image.load("images/style" .. curStyle .. "/card15000Small.png");
	card25000 = image.load("images/style" .. curStyle .. "/card25000.png");
	card25000Small = image.load("images/style" .. curStyle .. "/card25000Small.png");
	card50000 = image.load("images/style" .. curStyle .. "/card50000.png");
	card50000Small = image.load("images/style" .. curStyle .. "/card50000Small.png");
	card100000 = image.load("images/style" .. curStyle .. "/card100000.png");
	card100000Small = image.load("images/style" .. curStyle .. "/card100000Small.png");
	cardSellCompany = image.load("images/style" .. curStyle .. "/cardSellCompany.png");
	cardSellCompanySmall = image.load("images/style" .. curStyle .. "/cardSellCompanySmall.png");
	cardThief = image.load("images/style" .. curStyle .. "/cardThief.png");
	cardThiefSmall = image.load("images/style" .. curStyle .. "/cardThiefSmall.png");
	cardSmallSafe = image.load("images/style" .. curStyle .. "/cardSmallSafe.png");
	cardSmallSafeSmall = image.load("images/style" .. curStyle .. "/cardSmallSafeSmall.png");
	cardBigSafe = image.load("images/style" .. curStyle .. "/cardBigSafe.png");
	cardBigSafeSmall = image.load("images/style" .. curStyle .. "/cardBigSafeSmall.png");
	cardConviction = image.load("images/style" .. curStyle .. "/cardConviction.png");
	cardConvictionSmall = image.load("images/style" .. curStyle .. "/cardConvictionSmall.png");
	cardRemoveConviction = image.load("images/style" .. curStyle .. "/cardRemoveConviction.png");
	cardRemoveConvictionSmall = image.load("images/style" .. curStyle .. "/cardRemoveConvictionSmall.png");
	cardTaxEvasion = image.load("images/style" .. curStyle .. "/cardTaxEvasion.png");
	cardTaxEvasionSmall = image.load("images/style" .. curStyle .. "/cardTaxEvasionSmall.png");
	cardRemoveTaxEvasion = image.load("images/style" .. curStyle .. "/cardRemoveTaxEvasion.png");
	cardRemoveTaxEvasionSmall = image.load("images/style" .. curStyle .. "/cardRemoveTaxEvasionSmall.png");
	cardStrike = image.load("images/style" .. curStyle .. "/cardStrike.png");
	cardStrikeSmall = image.load("images/style" .. curStyle .. "/cardStrikeSmall.png");
	cardRemoveStrike = image.load("images/style" .. curStyle .. "/cardRemoveStrike.png");
	cardRemoveStrikeSmall = image.load("images/style" .. curStyle .. "/cardRemoveStrikeSmall.png");
	cardEcoCrime = image.load("images/style" .. curStyle .. "/cardEcoCrime.png");
	cardEcoCrimeSmall = image.load("images/style" .. curStyle .. "/cardEcoCrimeSmall.png");
	cardRemoveEcoCrime = image.load("images/style" .. curStyle .. "/cardRemoveEcoCrime.png");
	cardRemoveEcoCrimeSmall = image.load("images/style" .. curStyle .. "/cardRemoveEcoCrimeSmall.png");
	cardBribe = image.load("images/style" .. curStyle .. "/cardBribe.png");
	cardBribeSmall = image.load("images/style" .. curStyle .. "/cardBribeSmall.png");
	cardBankruptcy = image.load("images/style" .. curStyle .. "/cardBankruptcy.png");
	cardBankruptcySmall = image.load("images/style" .. curStyle .. "/cardBankruptcySmall.png");
	cardDeal = image.load("images/style" .. curStyle .. "/cardDeal.png");
	cardDealSmall = image.load("images/style" .. curStyle .. "/cardDealSmall.png");
	cardNewBeginning = image.load("images/style" .. curStyle .. "/cardNewBeginning.png");
	cardNewBeginningSmall = image.load("images/style" .. curStyle .. "/cardNewBeginningSmall.png");
	cardRobbery = image.load("images/style" .. curStyle .. "/cardRobbery.png");
	cardRobberySmall = image.load("images/style" .. curStyle .. "/cardRobberySmall.png");
	cardBanker = image.load("images/style" .. curStyle .. "/cardBanker.png");
	cardBankerSmall = image.load("images/style" .. curStyle .. "/cardBankerSmall.png");
	cardLuck = image.load("images/style" .. curStyle .. "/cardLuck.png");
	cardLuckSmall = image.load("images/style" .. curStyle .. "/cardLuckSmall.png");
	cardRotateTable = image.load("images/style" .. curStyle .. "/cardRotateTable.png");
	cardRotateTableSmall = image.load("images/style" .. curStyle .. "/cardRotateTableSmall.png");
	cardRotateHands = image.load("images/style" .. curStyle .. "/cardRotateHands.png");
	cardRotateHandsSmall = image.load("images/style" .. curStyle .. "/cardRotateHandsSmall.png");
	cardNewIdentity = image.load("images/style" .. curStyle .. "/cardNewIdentity.png");
	cardNewIdentitySmall = image.load("images/style" .. curStyle .. "/cardNewIdentitySmall.png");
	cardSabotage = image.load("images/style" .. curStyle .. "/cardSabotage.png");
	cardSabotageSmall = image.load("images/style" .. curStyle .. "/cardSabotageSmall.png");
	
	saveOptions()
end

changeStyle = function(change)

	local prevStyle = curStyle;
	curStyle = curStyle + change;

	if (curStyle < 0) then 
		curStyle = 1;
	end
	
	-- check folder exist by reading one image
	local file = io.open("images/style" .. curStyle .. "/menu.png", "r");

	if not file then
		-- folder not exist, don't change style
		curStyle = prevStyle;
		return; -- no options file stored
	end
	
	file:close()

	setStyle(true);
end

setDifficulty = function()
	if (userOptions[3] == "easy") then
		difficulty = {"easy", "easy", "easy"}
	elseif (userOptions[3] == "medium") then
		difficulty = {"medium", "easy", "medium"}
	elseif (userOptions[3] == "hard") then
		difficulty = {"hard", "medium", "easy"}
	elseif (userOptions[3] == "moderate") then
		difficulty = {"medium", "medium", "medium"}
	elseif (userOptions[3] == "extreme") then
		difficulty = {"hard", "hard", "hard"}
	else
		local difficulty1 = "easy";
		local difficulty2 = "easy";
		local difficulty3 = "easy";
		local diff = math.random(1,3)
		
		if (diff == 1) then
			difficulty1 = "easy";
		elseif (diff == 2) then
			difficulty1 = "medium";
		elseif (diff == 3) then
			difficulty1 = "hard";
		end
		
		diff = math.random(1,3)
		if (diff == 1) then
			difficulty2 = "easy";
		elseif (diff == 2) then
			difficulty2 = "medium";
		elseif (diff == 3) then
			difficulty2 = "hard";
		end
		
		diff = math.random(1,3)
		if (diff == 1) then
			difficulty3 = "easy";
		elseif (diff == 2) then
			difficulty3 = "medium";
		elseif (diff == 3) then
			difficulty3 = "hard";
		end
		
		difficulty = {difficulty1, difficulty2, difficulty3};
	end

end

showLogo = function()
	
	image.blit(0, 0, logo);
	screen.flip()
	image.free(logo)
end

playMusic = function(currentMusicPath)
	if (allowMusic) then
		sound.loop(currentMusicPath)
	else
		sound.loop()
	end
end

playSound = function(currentSound)

	if (allowSoundEffects) then
		if (soundObject ~= nil) then
			sound.free(soundObject)
		end
		soundObject = sound.load(currentSound)
		sound.play(soundObject, 2)
	end
	
end

string.splitCards = function(str, pattern)
	pattern = pattern or "[^%s]+"
	if pattern:len() == 0 then pattern = "[^%s]+" end
	local parts = {__index = table.insert}
	setmetatable(parts, parts)
	str:gsub(pattern, parts)
	setmetatable(parts, nil)
	parts.__index = nil
	return parts
end

string.splitOptions = function(str, pattern)
	pattern = pattern or "[^%s]+"
	if pattern:len() == 0 then pattern = "[^%s]+" end
	local parts = {__index = table.insert}
	setmetatable(parts, parts)
	str:gsub(pattern, parts)
	setmetatable(parts, nil)
	parts.__index = nil
	return parts
end

function trim (str)
	return (string.gsub(str, "^%s*(.-)%s*$", "%1"))
end

function calculateCompanyPoints()
	
	local i = 0;
	local value1 = 0;
	local value2 = 0;
	local value3 = 0;
	local value4 = 0;
	
	while (i < #company1) do
		i = i + 1;
      if (company1[i] == "$15000") then
         value1 = value1 + 15000;
      elseif (company1[i] == "$25000") then
         value1 = value1 + 25000;
      elseif (company1[i] == "$50000") then
         value1 = value1 + 50000;
      elseif (company1[i] == "$100000") then
         value1 = value1 + 100000;
		end
	end
	
	i = 0;
	while (i < #company2) do
		i = i + 1;
      if (company2[i] == "$15000") then
         value2 = value2 + 15000;
      elseif (company2[i] == "$25000") then
         value2 = value2 + 25000;
      elseif (company2[i] == "$50000") then
         value2 = value2 + 50000;
      elseif (company2[i] == "$100000") then
         value2 = value2 + 100000;
      end
	end

	i = 0;
	while (i < #company3) do
		i = i + 1;
      if (company3[i] == "$15000") then
         value3 = value3 + 15000;
      elseif (company3[i] == "$25000") then
         value3 = value3 + 25000;
      elseif (company3[i] == "$50000") then
         value3 = value3 + 50000;
      elseif (company3[i] == "$100000") then
         value3 = value3 + 100000;
      end
	end
	
	i = 0;
	while (i < #company4) do
		i = i + 1;
      if (company4[i] == "$15000") then
         value4 = value4 + 15000;
      elseif (company4[i] == "$25000") then
         value4 = value4 + 25000;
      elseif (company4[i] == "$50000") then
         value4 = value4 + 50000;
      elseif (company4[i] == "$100000") then
         value4 = value4 + 100000;
      end
	end
	
	return value1, value2, value3, value4;
	
end

function getCpuColors()

	if (difficulty[1] == "easy") then
		cpuColor1 = cpuEasyColor;
	elseif (difficulty[1] == "medium") then
		cpuColor1 = cpuMediumColor;
	elseif (difficulty[1] == "hard") then
		cpuColor1 = cpuHardColor;
	end
	
	if (difficulty[2] == "easy") then
		cpuColor2 = cpuEasyColor;
	elseif (difficulty[2] == "medium") then
		cpuColor2 = cpuMediumColor;
	elseif (difficulty[2] == "hard") then
		cpuColor2 = cpuHardColor;
	end
	
	if (difficulty[3] == "easy") then
		cpuColor3 = cpuEasyColor;
	elseif (difficulty[3] == "medium") then
		cpuColor3 = cpuMediumColor;
	elseif (difficulty[3] == "hard") then
		cpuColor3 = cpuHardColor;
	end

	return cpuColor1, cpuColor2, cpuColor3
end

-- reason: text why game ended
function showResults(reason)
	
	local points1, points2, points3, points4 = calculateCompanyPoints();
	local cpuColor1, cpuColor2, cpuColor3 = getCpuColors();
	
	while true do
	
	image.blit(0, 0, results1);
	image.blit(400, 200, rightArrow);
	
	screen.print(240, 15, reason, 0.8, red, shadowColor, "center");
	
	screen.print(100,35, "Company", 0.8, white, shadowColor, "left")
	screen.print(200,35, "Bank", 0.8, white, shadowColor, "left")
	screen.print(300,35, "Total", 0.8, white, shadowColor, "left")
	screen.print(20,55, "Player1", 0.8, white, shadowColor, "left")
	screen.print(100,55, "$" .. points1, 0.8, white, shadowColor, "left")
	screen.print(200,55, "$" .. bank1, 0.8, white, shadowColor, "left")
	screen.print(300,55, "$" .. points1 + bank1, 0.8, white, shadowColor, "left")
	
	screen.print(20,85, "Player2", 0.8, cpuColor1, shadowColor, "left")
	
	screen.print(100,85, "$" .. points2, 0.8, white, shadowColor, "left")
	screen.print(200,85, "$" .. bank2, 0.8, white, shadowColor, "left")
	screen.print(300,85, "$" .. points2 + bank2, 0.8, white, shadowColor, "left")
	
	if (playersSize > 2) then
		screen.print(20,115, "Player3", 0.8, cpuColor2, shadowColor, "left")
		
		screen.print(100,115, "$" .. points3, 0.8, white, shadowColor, "left")
		screen.print(200,115, "$" .. bank3, 0.8, white, shadowColor, "left")
		screen.print(300,115, "$" .. points3 + bank3, 0.8, white, shadowColor, "left")
	end
	
	if (playersSize > 3) then
		screen.print(20,145, "Player4", 0.8, cpuColor3, shadowColor, "left")
		
		screen.print(100,145, "$" .. points4, 0.8, white, shadowColor, "left")
		screen.print(200,145, "$" .. bank4, 0.8, white, shadowColor, "left")
		screen.print(300,145, "$" .. points4 + bank4, 0.8, white, shadowColor, "left")
	end
	
	controls.read()

	if controls.press("select") then
		returnMenu()
	elseif controls.press("right") or controls.analogx() == 127 + waitAnalog + waitAnalog then
		waitAnalog = 0.2
		waitMoment = os.clock()
		showResults2(points1, points2, points3, points4, reason)
	elseif controls.press("r") then
		changeStyle(1);
	elseif controls.press("l") then
		changeStyle(-1);
	end
	
	screen.flip()
	
	if (os.clock() - waitMoment >= waitAnalog) then
		waitAnalog = 0;
	end
	
	end
end

calculateMoneyCardDebt = function()
	local i = 0;
	local minus1 = 0;
	local minus2 = 0;
	local minus3 = 0;
	local minus4 = 0;
	
	while (i < maxHandSize) do
		i = i + 1
		if (hand1[i] ~= nil) then
			if (hand1[i] == "$15000") then
				minus1 = minus1 + 15000;
			elseif (hand1[i] == "$25000") then
				minus1 = minus1 + 25000;
			elseif (hand1[i] == "$50000") then
				minus1 = minus1 + 50000;
			elseif (hand1[i] == "$100000") then
				minus1 = minus1 + 100000;
			end
		end
		
		if (hand2[i] ~= nil) then
			if (hand2[i] == "$15000") then
				minus2 = minus2 + 15000;
			elseif (hand2[i] == "$25000") then
				minus2 = minus2 + 25000;
			elseif (hand2[i] == "$50000") then
				minus2 = minus2 + 50000;
			elseif (hand2[i] == "$100000") then
				minus2 = minus2 + 100000;
			end
		end
		
		if (hand3[i] ~= nil) then
			if (hand3[i] == "$15000") then
				minus3 = minus3 + 15000;
			elseif (hand3[i] == "$25000") then
				minus3 = minus3 + 25000;
			elseif (hand3[i] == "$50000") then
				minus3 = minus3 + 50000;
			elseif (hand3[i] == "$100000") then
				minus3 = minus3 + 100000;
			end
		end
		
		if (hand4[i] ~= nil) then
			if (hand4[i] == "$15000") then
				minus4 = minus4 + 15000;
			elseif (hand4[i] == "$25000") then
				minus4 = minus4 + 25000;
			elseif (hand4[i] == "$50000") then
				minus4 = minus4 + 50000;
			elseif (hand4[i] == "$100000") then
				minus4 = minus4 + 100000;
			end
		end
	end
	
	return minus1, minus2, minus3, minus4;
end

calculateCardDebt = function(cardName)
	local i = 0;
	local cardTotal1 = 0;
	local cardTotal2 = 0;
	local cardTotal3 = 0;
	local cardTotal4 = 0;
	
	while (i < maxHandSize) do
		i = i + 1
		if (hand1[i] == cardName) then
			cardTotal1 = cardTotal1 + 1;
		end
		
		if (hand2[i] == cardName) then
			cardTotal2 = cardTotal2 + 1;
		end
		
		if (hand3[i] == cardName) then
			cardTotal3 = cardTotal3 + 1;
		end
		
		if (hand4[i] == cardName) then
			cardTotal4 = cardTotal4 + 1;
		end
	end
	
	return cardTotal1, cardTotal2, cardTotal3, cardTotal4;
end

calculateBankerBonus = function(companyEarnings1, companyEarnings2, companyEarnings3, companyEarnings4)
	local i = 0;
	local bonusIssued1 = false;
	local bonusIssued2 = false;
	local bonusIssued3 = false;
	local bonusIssued4 = false;
	
	while (i < maxHandSize) do
		i = i + 1
		
		if (hand1[i] == "Banker") then
			bonusIssued1 = true;
		end
		if (hand2[i] == "Banker") then
			bonusIssued2 = true;
		end
		if (hand3[i] == "Banker") then
			bonusIssued3 = true;
		end
		if (hand4[i] == "Banker") then
			bonusIssued4 = true;
		end
	end
	
	local procent1 = companyEarnings1 * 0.2;
	local procent2 = companyEarnings2 * 0.2;
	local procent3 = companyEarnings3 * 0.2;
	local procent4 = companyEarnings4 * 0.2;
	
	local bonus1 = 0;
	local bonus2 = 0;
	local bonus3 = 0;
	local bonus4 = 0;
	
	if (bonusIssued1) then
		if (companyEarnings2 > 0) then
			bonus1 = bonus1 + procent2;
			bonus2 = bonus2 - procent2;
		end
		
		if (companyEarnings3 > 0) then
			bonus1 = bonus1 + procent3;
			bonus3 = bonus3 - procent3;
		end
		
		if (companyEarnings4 > 0) then
			bonus1 = bonus1 + procent4;
			bonus4 = bonus4 - procent4;
		end
	end
	
	if (bonusIssued2) then
		if (companyEarnings1 > 0) then
			bonus2 = bonus2 + procent1;
			bonus1 = bonus1 - procent1;
		end
		
		if (companyEarnings3 > 0) then
			bonus2 = bonus2 + procent3;
			bonus3 = bonus3 - procent3;
		end
		
		if (companyEarnings4 > 0) then
			bonus2 = bonus2 + procent4;
			bonus4 = bonus4 - procent4;
		end
	end
	
	if (bonusIssued3) then
		if (companyEarnings1 > 0) then
			bonus3 = bonus3 + procent1;
			bonus1 = bonus1 - procent1;
		end
		
		if (companyEarnings2 > 0) then
			bonus3 = bonus3 + procent2;
			bonus2 = bonus2 - procent2;
		end
		
		if (companyEarnings4 > 0) then
			bonus3 = bonus3 + procent4;
			bonus4 = bonus4 - procent4;
		end
	end
	
	if (bonusIssued4) then
		if (companyEarnings1 > 0) then
			bonus4 = bonus4 + procent1;
			bonus1 = bonus1 - procent1;
		end
		
		if (companyEarnings2 > 0) then
			bonus4 = bonus4 + procent2;
			bonus2 = bonus2 - procent2;
		end
		
		if (companyEarnings3 > 0) then
			bonus4 = bonus4 + procent3;
			bonus3 = bonus3 - procent3;
		end
	end
	
	return bonus1,bonus2,bonus3,bonus4;
	
end

checkAchivement = function()
	
	if (playMode == "arcade") then
	
	if(randomBonus == false and (userOptions[3] == "hard") and sellCompanyMin >= 200000) then
		if not updatedConsecutiveWinnings then
			consecutiveWinnings = consecutiveWinnings + 1;
			updatedConsecutiveWinnings = true;
		end
		if (consecutiveWinnings == 2) then
			local bonusFile = "randomBonus";
			local file = io.open(bonusFile,"w")
			file:close();
			randomBonus = true;
			
			draw.fillrect(25,95,431,100,lime)
			draw.fillrect(30,100,421,90,black)
			screen.print(240, 150 - yDifference, "Unlocked a new bonus: Random Difficulty", 1.0, lime, shadowColor, "center");
			
			screen.flip()
			screen.waitvblankstart(250);
		end
	elseif(moderateBonus == false and (userOptions[3] == "random") and playersSize > 2 and userOptions[2] == "yes" and sellCompanyMin >= 200000) then
		local bonusFile = "moderateBonus";
		local file = io.open(bonusFile,"w")
		file:close();
		moderateBonus = true;
		
		draw.fillrect(20,95,441,100,lime)
		draw.fillrect(25,100,430,90,black)
		screen.print(240, 150 - yDifference, "Unlocked a new bonus: Moderate Difficulty", 1.0, lime, shadowColor, "center");
		
		screen.flip()
		screen.waitvblankstart(250);
	elseif(extremeBonus == false and (userOptions[3] == "moderate") and playersSize > 3 and sellCompanyMin >= 200000) then
		local bonusFile = "extremeBonus";
		local file = io.open(bonusFile,"w")
		file:close();
		extremeBonus = true;
		
		draw.fillrect(25,95,431,100,lime)
		draw.fillrect(30,100,421,90,black)
		screen.print(240, 150 - yDifference, "Unlocked a new bonus: Extreme Difficulty", 1.0, lime, shadowColor, "center");
		
		screen.flip()
		screen.waitvblankstart(250);
	elseif(cardListBonus == false and (userOptions[3] == "extreme") and playersSize > 3 and sellCompanyMin >= 200000) then
		local bonusFile = "cardListBonus";
		local file = io.open(bonusFile,"w")
		file:close();
		cardListBonus = true;
		
		draw.fillrect(25,95,431,100,lime)
		draw.fillrect(30,100,421,90,black)
		screen.print(240, 150 - yDifference, "Unlocked a new bonus: Card List Menu", 1.0, lime, shadowColor, "center");
		
		screen.flip()
		screen.waitvblankstart(250);
	end
	
	elseif (playMode == "story") then
		-- achivement of story mode
		if (rotateHandsBonus == false and currentStage == 3) then
			local bonusFile = "rotateHandsBonus";
			local file = io.open(bonusFile,"w")
			file:close();
			rotateHandsBonus = true;
		
			draw.fillrect(25,95,431,100,lime)
			draw.fillrect(30,100,421,90,black)
			screen.print(240, 150 - yDifference, "Unlocked a new card: Rotate Hands", 1.0, lime, shadowColor, "center");
		
			screen.flip()
			screen.waitvblankstart(250);
		elseif (rotateTableBonus == false and currentStage == 4) then
			local bonusFile = "rotateTableBonus";
			local file = io.open(bonusFile,"w")
			file:close();
			rotateTableBonus = true;
		
			draw.fillrect(25,95,431,100,lime)
			draw.fillrect(30,100,421,90,black)
			screen.print(240, 150 - yDifference, "Unlocked a new card: Rotate Table", 1.0, lime, shadowColor, "center");
		
			screen.flip()
			screen.waitvblankstart(250);
		elseif (newIdentityBonus == false and currentStage == 5) then
			local bonusFile = "newIdentityBonus";
			local file = io.open(bonusFile,"w")
			file:close();
			newIdentityBonus = true;
		
			draw.fillrect(25,95,431,100,lime)
			draw.fillrect(30,100,421,90,black)
			screen.print(240, 150 - yDifference, "Unlocked a new card: New Identity", 1.0, lime, shadowColor, "center");
		
			screen.flip()
			screen.waitvblankstart(250);
		elseif (sabotageBonus == false and currentStage == 6) then
			local bonusFile = "sabotageBonus";
			local file = io.open(bonusFile,"w")
			file:close();
			sabotageBonus = true;
		
			draw.fillrect(25,95,431,100,lime)
			draw.fillrect(30,100,421,90,black)
			screen.print(240, 150 - yDifference, "Unlocked a new card: Sabotage", 1.0, lime, shadowColor, "center");
		
			screen.flip()
			screen.waitvblankstart(250);
		end
		
	end
	
end

showResults3 = function(companyEarnings1, companyEarnings2, companyEarnings3, companyEarnings4, points1, points2, points3, points4, reason)
    
	local banker1, banker2, banker3, banker4 = calculateBankerBonus(companyEarnings1, companyEarnings2, companyEarnings3, companyEarnings4);
	local total1 = companyEarnings1 + banker1 + bank1;
	local total2 = companyEarnings2 + banker2 + bank2;
	local total3 = companyEarnings3 + banker3 + bank3;
	local total4 = companyEarnings4 + banker4 + bank4;
	
	local most = math.max(total1, total2, total3, total4);
	
	local winner = 1;
	local multipleWinners = 0;
	
	if (most == total1) then
		winner = 1;
		multipleWinners = multipleWinners + 1;
	end
	if (most == total2) then
		winner = 2;
		multipleWinners = multipleWinners + 1;
	end
	if (most == total3) then
		winner = 3;
		multipleWinners = multipleWinners + 1;
	end
	if (most == total4) then
		winner = 4;
		multipleWinners = multipleWinners + 1;
	end
	
	local winnerDeclaration = "Player" .. winner .. " wins!";
	
	if (most < 1) then
		winnerDeclaration = "Not much winnigs, have we?";
		consecutiveWinnings = 0;
	elseif (multipleWinners > 1) then
		winnerDeclaration = "Draw between players!";
		consecutiveWinnings = 0;
	elseif (winner == 1) then
		checkAchivement(); -- player 1 one wins, check whether player unlocks a bonus
	else
		consecutiveWinnings = 0;
	end
	
	while true do
		
		image.blit(0, 0, results3);
		image.blit(20, 200, leftArrow);
		
		screen.print(240, 15, winnerDeclaration, 0.8, red, shadowColor, "center");
	
		screen.print(100,35, "Company", 0.8, white, shadowColor, "left")
		screen.print(190,35, "Banker", 0.8, white, shadowColor, "left")
		screen.print(280,35, "Bank", 0.8, white, shadowColor, "left")
		screen.print(370,35, "Total", 0.8, white, shadowColor, "left")
	
		screen.print(20,55, "Player1", 0.8, white, shadowColor, "left")
		
		if (companyEarnings1 >= 0) then
			screen.print(100,55, "$" .. companyEarnings1, 0.8, white, shadowColor, "left")
		else
			screen.print(100,55, "-$" .. companyEarnings1 * -1, 0.8, white, shadowColor, "left")
		end
		
		if (banker1 >= 0) then
			screen.print(190,55, "$" .. banker1, 0.8, white, shadowColor, "left")
		else
			screen.print(190,55, "-$" .. banker1 * -1, 0.8, white, shadowColor, "left")
		end
	
		screen.print(280,55, "$" .. bank1, 0.8, white, shadowColor, "left")
		
		if (total1 >= 0) then
			screen.print(370,55, "$" .. total1, 0.8, white, shadowColor, "left")
		else
			screen.print(370,55, "-$" .. total1 * -1, 0.8, white, shadowColor, "left")
		end
	
		screen.print(20,85, "Player2", 0.8, cpuColor1, shadowColor, "left")
		
		if (companyEarnings2 >= 0) then
			screen.print(100,85, "$" .. companyEarnings2, 0.8, white, shadowColor, "left")
		else
			screen.print(100,85, "-$" .. companyEarnings2 * -1, 0.8, white, shadowColor, "left")
		end
		
		if (banker2 >= 0) then
			screen.print(190,85, "$" .. banker2, 0.8, white, shadowColor, "left")
		else
			screen.print(190,85, "-$" .. banker2 * -1, 0.8, white, shadowColor, "left")
		end
	
		screen.print(280,85, "$" .. bank2, 0.8, white, shadowColor, "left")
		
		if (total2 >= 0) then
			screen.print(370,85, "$" .. total2, 0.8, white, shadowColor, "left")
		else
			screen.print(370,85, "-$" .. total2 * -1, 0.8, white, shadowColor, "left")
		end
		
		if (playersSize > 2) then
		
			screen.print(20,115, "Player3", 0.8, cpuColor2, shadowColor, "left")
			
			if (companyEarnings3 >= 0) then
				screen.print(100,115, "$" .. companyEarnings3, 0.8, white, shadowColor, "left")
			else
				screen.print(100,115, "-$" .. companyEarnings3 * -1, 0.8, white, shadowColor, "left")
			end
		
			if (banker3 >= 0) then
				screen.print(190,115, "$" .. banker3, 0.8, white, shadowColor, "left")
			else
				screen.print(190,115, "-$" .. banker3 * -1, 0.8, white, shadowColor, "left")
			end
	
			screen.print(280,115, "$" .. bank3, 0.8, white, shadowColor, "left")
		
			if (total3 >= 0) then
				screen.print(370,115, "$" .. total3, 0.8, white, shadowColor, "left")
			else
				screen.print(370,115, "-$" .. total3 * -1, 0.8, white, shadowColor, "left")
			end
		end
		
		if (playersSize > 3) then
			screen.print(20,145, "Player4", 0.8, cpuColor3, shadowColor, "left")
			
			if (companyEarnings4 >= 0) then
				screen.print(100,145, "$" .. companyEarnings4, 0.8, white, shadowColor, "left")
			else
				screen.print(100,145, "-$" .. companyEarnings4 * -1, 0.8, white, shadowColor, "left")
			end
		
			if (banker4 >= 0) then
				screen.print(190,145, "$" .. banker4, 0.8, white, shadowColor, "left")
			else
				screen.print(190,145, "-$" .. banker4 * -1, 0.8, white, shadowColor, "left")
			end
	
			screen.print(280,145, "$" .. bank4, 0.8, white, shadowColor, "left")
		
			if (total4 >= 0) then
				screen.print(370,145, "$" .. total4, 0.8, white, shadowColor, "left")
			else
				screen.print(370,145, "-$" .. total4 * -1, 0.8, white, shadowColor, "left")
			end
		end
		
		if (playMode == "arcade") then
			screen.print(240, 220, "Press Cross for rematch.", 0.8, red, shadowColor, "center")	
		else
			screen.print(240, 220, "Press Cross to return story.", 0.8, red, shadowColor, "center")	
		end
		
		screen.print(240, 235, "Press Select for menu.", 0.8, red, shadowColor, "center")
		screen.print(240, 250, "Press Home to quit.", 0.8, red, shadowColor, "center")
		
		controls.read()
	
		if controls.press("select") then			
			returnMenu()
		elseif controls.press("left") or controls.analogx() == -128 - waitAnalog then	
			waitAnalog = 0.2
			waitMoment = os.clock()
			showResults2(points1, points2, points3, points4, reason)
		elseif controls.press("cross") then			
			if (playMode == "arcade") then
				start("cards.ini")
			else
				-- playing story mode, did player 1 win?
				local victory = false
				if (winner == 1 and most > 1 and multipleWinners == 1) then
					victory = true
				end
				
				-- if the player did cheat, his income is considered as 0
				if (cheater) then
					total1 = 0;
				end
				
				-- end stage
				if (currentStage == 1) then
					endStage1(victory, total1)
				elseif (currentStage == 2) then
					endStage2(victory, total1)
				elseif (currentStage == 3) then
					endStage3(victory, total1)
				elseif (currentStage == 4) then
					endStage4(victory, total1)
				elseif (currentStage == 5) then
					endStage5(victory, total1)
				elseif (currentStage == 6) then
					endStage6(victory, total1)
				elseif (currentStage == 7) then
					endStage7(victory, total1)	
				end
			end
		elseif controls.r() and controls.l() and controls.right() then
			-- cheat
			showCurrentHands()
		elseif controls.press("r") then			
			changeStyle(1);
		elseif controls.press("l") then			
			changeStyle(-1);
		end
		
		screen.flip()
		
		if (os.clock() - waitMoment >= waitAnalog) then
			waitAnalog = 0;
		end
	end
	
end

showCurrentHands = function()
	local cpuColor1, cpuColor2, cpuColor3 = getCpuColors();
	local i = 0;
	local y = 65;
	local x = 20;
	while true do
		
		screen.clear(black)
		screen.print(240, 15, "Hidden menu - Current hands", 0.8, red, shadowColor, "center");
		
		screen.print(20,45, "Player1", 0.8, white, shadowColor, "left")
		
			i = 0;
			y = 65;
			x = 20;
			while (i < maxHandSize) do
				i = i + 1;
				if (hand1[i] ~= nil) then
					screen.print(x,y, hand1[i], 0.6, blue, shadowColor, "left")
					y = y + 20;
				end
			end
			
		screen.print(150,45, "Player2", 0.8, cpuColor1, shadowColor, "left")
		
			i = 0;
			y = 65;
			x = 150;
			while (i < maxHandSize) do
				i = i + 1;
				if (hand2[i] ~= nil) then
					screen.print(x,y, hand2[i], 0.6, blue, shadowColor, "left")
					y = y + 20;
				end
			end
		
		screen.print(280,45, "Player3", 0.8, cpuColor2, shadowColor, "left")
		
			i = 0;
			y = 65;
			x = 280;
			while (i < maxHandSize) do
				i = i + 1;
				if (hand3[i] ~= nil) then
					screen.print(x,y, hand3[i], 0.6, blue, shadowColor, "left")
					y = y + 20;
				end
			end
		
		screen.print(410,45, "Player4", 0.8, cpuColor3, shadowColor, "left")
	
			i = 0;
			y = 65;
			x = 410;
			while (i < maxHandSize) do
				i = i + 1;
				if (hand4[i] ~= nil) then
					screen.print(x,y, hand4[i], 0.6, blue, shadowColor, "left")
					y = y + 20;
				end
			end
	
		screen.print(240, 250, "Press Circle to return", 0.8, red, shadowColor, "center")
	
	screen.flip()
	
	controls.read()
	
		if controls.press("circle") then			
			break;
		end
	end
	return
end

showResults2 = function(points1, points2, points3, points4, reason)

	local moneyDebt1, moneyDebt2, moneyDebt3, moneyDebt4 = calculateMoneyCardDebt();
	local bankruptcy1, bankruptcy2, bankruptcy3, bankruptcy4 = calculateCardDebt("Bankruptcy");
	local dealDebt1, dealDebt2, dealDebt3, dealDebt4 = calculateCardDebt("Deal");
	local robberyDebt1, robberyDebt2, robberyDebt3, robberyDebt4 = calculateCardDebt("Robbery");

	local debt1 = moneyDebt1 + (bankruptcy1 * 100000) + (dealDebt1 * 50000) + (robberyDebt1 * 25000);
	local debt2 = moneyDebt2 + (bankruptcy2 * 100000) + (dealDebt2 * 50000) + (robberyDebt2 * 25000);
	local debt3 = moneyDebt3 + (bankruptcy3 * 100000) + (dealDebt3 * 50000) + (robberyDebt3 * 25000);
	local debt4 = moneyDebt4 + (bankruptcy4 * 100000) + (dealDebt4 * 50000) + (robberyDebt4 * 25000);
	
	local companyEarnings1 = points1 - debt1;
	local companyEarnings2 = points2 - debt2;
	local companyEarnings3 = points3 - debt3;
	local companyEarnings4 = points4 - debt4;
	
while true do
	
	image.blit(0, 0, results2);
	image.blit(20, 200, leftArrow);
	image.blit(400, 200, rightArrow);
	
	screen.print(240, 15, "Hand cards effect to profit", 0.8, red, shadowColor, "center");
	
	screen.print(100,35, "Debt", 0.8, white, shadowColor, "left")
	screen.print(180,35, "=>", 0.8, white, shadowColor, "left")
	screen.print(240,35, "Company", 0.8, white, shadowColor, "left")
	screen.print(340,35, "Bank", 0.8, white, shadowColor, "left")
	
	screen.print(20,55, "Player1", 0.8, white, shadowColor, "left")
	screen.print(100,55, "-$" .. debt1, 0.8, white, shadowColor, "left")
	
	if (companyEarnings1 >= 0) then
		screen.print(240,55, "$" .. companyEarnings1, 0.8, white, shadowColor, "left")
	else
		screen.print(240,55, "-$" .. companyEarnings1 * -1, 0.8, white, shadowColor, "left")
	end
	
	screen.print(340,55,"($" .. bank1 .. ")", 0.8, white, shadowColor, "left")
	
	screen.print(20,85, "Player2", 0.8, cpuColor1, shadowColor, "left")
	
	screen.print(100,85, "-$" .. debt2, 0.8, white, shadowColor, "left")
	
	if (companyEarnings2 >= 0) then
		screen.print(240,85, "$" .. companyEarnings2, 0.8, white, shadowColor, "left")
	else
		screen.print(240,85, "-$" .. companyEarnings2 * -1, 0.8, white, shadowColor, "left")
	end
	
	screen.print(340,85,"($" .. bank2 .. ")", 0.8, white, shadowColor, "left")
	
	if (playersSize > 2) then
		screen.print(20,115, "Player3", 0.8, cpuColor2, shadowColor, "left")
		
		screen.print(100,115, "-$" .. debt3, 0.8, white, shadowColor, "left")
	
		if (companyEarnings3 >= 0) then
			screen.print(240,115, "$" .. companyEarnings3, 0.8, white, shadowColor, "left")
		else
			screen.print(240,115, "-$" .. companyEarnings3 * -1, 0.8, white, shadowColor, "left")
		end
		
		screen.print(340,115,"($" .. bank3 .. ")", 0.8, white, shadowColor, "left")
	end
	
	if (playersSize > 3) then
		screen.print(20,145, "Player4", 0.8, cpuColor3, shadowColor, "left")
		
		screen.print(100,145, "-$" .. debt4, 0.8, white, shadowColor, "left")
	
		if (companyEarnings4 >= 0) then
			screen.print(240,145, "$" .. companyEarnings4, 0.8, white, shadowColor, "left")
		else
			screen.print(240,145, "-$" .. companyEarnings4 * -1, 0.8, white, shadowColor, "left")
		end
		
		screen.print(340,145,"($" .. bank4 .. ")", 0.8, white, shadowColor, "left")
	end
	
	controls.read()
	
	if controls.press("select") then
		returnMenu()
	elseif controls.press("left") or controls.analogx() == -128 - waitAnalog then
		waitAnalog = 0.2
		waitMoment = os.clock()
		showResults(reason)
	elseif controls.press("right") or controls.analogx() == 127 + waitAnalog then
		waitAnalog = 0.2
		waitMoment = os.clock()
		showResults3(companyEarnings1, companyEarnings2, companyEarnings3, companyEarnings4, points1, points2, points3, points4, reason)
	elseif controls.press("r") then
		changeStyle(1);
	elseif controls.press("l") then
		changeStyle(-1);
	end
	
	screen.flip()
	
	if (os.clock() - waitMoment >= waitAnalog) then
		waitAnalog = 0;
	end
	
	end
	
end

function shuffle()
	local i = 0;
	while (i < #deck) do
		i = i + 1;
		local number = math.random(1,#deck);
		deck[i], deck[number] = deck[number], deck[i]
	end
end

saveOptions = function()

	userOptions[5] = curStyle;

	local optionFile = "options.ini";
	local file = io.open(optionFile,"w")
				
	local i = 0;
	while (i < #userOptions) do
		i = i + 1;
		file:write(userOptions[i] .. ";");
	end
	
	file:close();
end

loadOptions = function()
	local file = io.open("options.ini", "r");

	if not file then
		userOptions = {"4", "yes", "easy", "$0", "1"}
		return; -- no options file stored
	end
	
	local line = file:read();
	
	userOptions = line:splitOptions("[^;]+");
	
	if (#userOptions ~= 5) then
		-- corrupted data
		userOptions = {"4", "yes", "easy", "$0", "1"}
	end
	
	curStyle = tonumber(userOptions[5])
	
	file:close();
end

-- Parameter is used cards.ini
loadCards = function(iniFileName)
	deck = {} -- empty deck
	cardMax2 = {}
	local file = io.open(iniFileName, "r");
	
	if (file == nil ) then
		-- ini file was not found, quit
		screen.print(240, 150 - yDifference, "Cards.ini file not found.", 0.8, blue, shadowColor, "center");
		
		screen.flip()
		screen.waitvblankstart(150);
		os.quit();
	end
	
	for line in file:lines() do

		local item = line:splitCards("[^;]+");
		local numberOfSameCard = tonumber(item[2]);
		local i = 0;
		
		if (numberOfSameCard < 3) then -- additional logic for cpu 6.4.2011
			cardMax2[#cardMax2 + 1] = item[1];
		end
		
		if (numberOfSameCard < 0) then -- limit added 7.4.2011
			numberOfSameCard = 0;
		elseif (numberOfSameCard > 40) then
				numberOfSameCard = 40;
		end
	
		while (i < numberOfSameCard) do
			i = i + 1;
			table.insert(deck,item[1]);
			--deck[#deck + 1] = item[1];
		end
	end
	
	file:close()
end

-- should never deal more than 6 cards using this!
dealCard = function(cardName, player)
	local i = 0;
	
	while (i < #deck) do
		i = i + 1;
		if (deck[i] == cardName) then
			
			if (player == 1) then
				table.insert(hand1, deck[i])
			elseif (player == 2) then
				table.insert(hand2, deck[i])
			elseif (player == 3) then
				table.insert(hand3, deck[i])
			elseif (player == 4) then
				table.insert(hand4, deck[i])
			end
			
			break;
		end
	end
end

deal = function()
	local i = #hand1;

	if (playersSize == 2) then
		while (i < 6) do
			i = i + 1;
			hand1[i] = deck[deckIndex];
			deckIndex = deckIndex + 1;
		end
		hand1[7] = nil;
		
		i = #hand2;
		while (i < 6) do
			i = i + 1;
			hand2[i] = deck[deckIndex];
			deckIndex = deckIndex + 1;
		end
		hand2[7] = nil;
		
	elseif(playersSize == 3) then
		while (i < 6) do
			i = i + 1;
			hand1[i] = deck[deckIndex];
			deckIndex = deckIndex + 1;
		end
		hand1[7] = nil;
		
		i = #hand2;
		while (i < 6) do
			i = i + 1;
			hand2[i] = deck[deckIndex];
			deckIndex = deckIndex + 1;
		end
		hand2[7] = nil;
		
		i = #hand3;
		while (i < 6) do
			i = i + 1;
			hand3[i] = deck[deckIndex];
			deckIndex = deckIndex + 1;
		end
		hand3[7] = nil;
	else -- 4 players
		while (i < 6) do
			i = i + 1;
			hand1[i] = deck[deckIndex];
			deckIndex = deckIndex + 1;
		end
		hand1[7] = nil;
		
		i = #hand2;
		while (i < 6) do
			i = i + 1;
			hand2[i] = deck[deckIndex];
			deckIndex = deckIndex + 1;
		end
		hand2[7] = nil;
		
		i = #hand3;
		while (i < 6) do
			i = i + 1;
			hand3[i] = deck[deckIndex];
			deckIndex = deckIndex + 1;
		end
		hand3[7] = nil;
		
		i = #hand4;
		while (i < 6) do
			i = i + 1;
			hand4[i] = deck[deckIndex];
			deckIndex = deckIndex + 1;
		end
		hand4[7] = nil;
	end

end

checkCurrentCard = function(cardName, showType)

	if (showType == "small") then
		if (cardName == "Open Company") then
			currentCard = cardOpenCompanySmall;
		elseif (cardName == "$15000") then
			currentCard = card15000Small;
		elseif (cardName == "$25000") then
			currentCard = card25000Small;
		elseif (cardName == "$50000") then
			currentCard = card50000Small;
		elseif (cardName == "$100000") then
			currentCard = card100000Small;
		elseif (cardName == "Sell Company") then
			currentCard = cardSellCompanySmall;
		elseif (cardName == "Thief") then
			currentCard = cardThiefSmall;
		elseif (cardName == "Small Safe") then
			currentCard = cardSmallSafeSmall;
		elseif (cardName == "Big Safe") then
			currentCard = cardBigSafeSmall;
		elseif (cardName == "Conviction") then
			currentCard = cardConvictionSmall;
		elseif (cardName == "Remove Conviction") then
			currentCard = cardRemoveConvictionSmall;
		elseif (cardName == "Tax Evasion") then
			currentCard = cardTaxEvasionSmall;
		elseif (cardName == "Remove Tax Evasion") then
			currentCard = cardRemoveTaxEvasionSmall;
		elseif (cardName == "Strike") then
			currentCard = cardStrikeSmall;
		elseif (cardName == "Remove Strike") then
			currentCard = cardRemoveStrikeSmall;
		elseif (cardName == "Eco Crime") then
			currentCard = cardEcoCrimeSmall;
		elseif (cardName == "Remove Eco Crime") then
			currentCard = cardRemoveEcoCrimeSmall;
		elseif (cardName == "Bribe") then
			currentCard = cardBribeSmall;
		elseif (cardName == "Bankruptcy") then
			currentCard = cardBankruptcySmall;
		elseif (cardName == "Deal") then
			currentCard = cardDealSmall;
		elseif (cardName == "New Beginning") then
			currentCard = cardNewBeginningSmall;
		elseif (cardName == "Robbery") then
			currentCard = cardRobberySmall;
		elseif (cardName == "Luck") then
			currentCard = cardLuckSmall;
		elseif (cardName == "Banker") then
			currentCard = cardBankerSmall;
		elseif (cardName == "Rotate Table") then
			currentCard = cardRotateTableSmall;
		elseif (cardName == "Rotate Hands") then
			currentCard = cardRotateHandsSmall;
		elseif (cardName == "New Identity") then
			currentCard = cardNewIdentitySmall;
		elseif (cardName == "Sabotage") then
			currentCard = cardSabotageSmall;
		end
	else
		-- Big image
		if (cardName == "Open Company") then
			currentCard = cardOpenCompany;
		elseif (cardName == "$15000") then
			currentCard = card15000;
		elseif (cardName == "$25000") then
			currentCard = card25000;
		elseif (cardName == "$50000") then
			currentCard = card50000;
		elseif (cardName == "$100000") then
			currentCard = card100000;
		elseif (cardName == "Sell Company") then
			currentCard = cardSellCompany;
		elseif (cardName == "Thief") then
			currentCard = cardThief;
		elseif (cardName == "Small Safe") then
			currentCard = cardSmallSafe;
		elseif (cardName == "Big Safe") then
			currentCard = cardBigSafe;
		elseif (cardName == "Conviction") then
			currentCard = cardConviction;
		elseif (cardName == "Remove Conviction") then
			currentCard = cardRemoveConviction;
		elseif (cardName == "Tax Evasion") then
			currentCard = cardTaxEvasion;
		elseif (cardName == "Remove Tax Evasion") then
			currentCard = cardRemoveTaxEvasion;
		elseif (cardName == "Strike") then
			currentCard = cardStrike;
		elseif (cardName == "Remove Strike") then
			currentCard = cardRemoveStrike;
		elseif (cardName == "Eco Crime") then
			currentCard = cardEcoCrime;
		elseif (cardName == "Remove Eco Crime") then
			currentCard = cardRemoveEcoCrime;
		elseif (cardName == "Bribe") then
			currentCard = cardBribe;
		elseif (cardName == "Bankruptcy") then
			currentCard = cardBankruptcy;
		elseif (cardName == "Deal") then
			currentCard = cardDeal;
		elseif (cardName == "New Beginning") then
			currentCard = cardNewBeginning;
		elseif (cardName == "Robbery") then
			currentCard = cardRobbery;
		elseif (cardName == "Luck") then
			currentCard = cardLuck;
		elseif (cardName == "Banker") then
			currentCard = cardBanker;
		elseif (cardName == "Rotate Table") then
			currentCard = cardRotateTable;
		elseif (cardName == "Rotate Hands") then
			currentCard = cardRotateHands;
		elseif (cardName == "New Identity") then
			currentCard = cardNewIdentity;
		elseif (cardName == "Sabotage") then
			currentCard = cardSabotage;
		end
	end

end

checkNumberOfThreats = function(player)

	local numberOfThreats = 0;
	local i = 0;
	
	if (player == 1) then
		while (i < #table1) do
			i = i + 1
			if (table1[i] == "Conviction") then
				numberOfThreats = numberOfThreats + 1;
			elseif (table1[i] == "Tax Evasion") then
				numberOfThreats = numberOfThreats + 1;
			elseif (table1[i] == "Strike") then
				numberOfThreats = numberOfThreats + 1;
			elseif (table1[i] == "Eco Crime") then
				numberOfThreats = numberOfThreats + 1;
			end
		end
	elseif (player == 2) then
		while (i < #table2) do
			i = i + 1
			if (table2[i] == "Conviction") then
				numberOfThreats = numberOfThreats + 1;
			elseif (table2[i] == "Tax Evasion") then
				numberOfThreats = numberOfThreats + 1;
			elseif (table2[i] == "Strike") then
				numberOfThreats = numberOfThreats + 1;
			elseif (table2[i] == "Eco Crime") then
				numberOfThreats = numberOfThreats + 1;
			end
		end
	elseif (player == 3) then
		while (i < #table3) do
			i = i + 1
			if (table3[i] == "Conviction") then
				numberOfThreats = numberOfThreats + 1;
			elseif (table3[i] == "Tax Evasion") then
				numberOfThreats = numberOfThreats + 1;
			elseif (table3[i] == "Strike") then
				numberOfThreats = numberOfThreats + 1;
			elseif (table3[i] == "Eco Crime") then
				numberOfThreats = numberOfThreats + 1;
			end
		end
	elseif (player == 4) then
		while (i < #table4) do
			i = i + 1
			if (table4[i] == "Conviction") then
				numberOfThreats = numberOfThreats + 1;
			elseif (table4[i] == "Tax Evasion") then
				numberOfThreats = numberOfThreats + 1;
			elseif (table4[i] == "Strike") then
				numberOfThreats = numberOfThreats + 1;
			elseif (table4[i] == "Eco Crime") then
				numberOfThreats = numberOfThreats + 1;
			end
		end
	end
	
	return numberOfThreats;
end

showHands = function()
	-- Player 1
	local i = 0;
	local between = 0;
		
	while (i < maxHandSize) do
		i = i + 1
		if (hand1[i] ~= nil) then
			checkCurrentCard(hand1[i], "small");
			image.blit(90 + between, 252, currentCard);
		end
		between = between + 40;
	end
	
	i = 0;
	between = 0;
	
	while (i < maxHandSize) do
		i = i + 1;
		if (hand2[i] ~= nil) then
			image.blit(-10, 40 + between, cardBackSmall);
		end
		between = between + 25;
	end
	
	i = 0;
	between = 0;
	
	while (i < maxHandSize) do
		i = i + 1
		if (hand3[i] ~= nil) then
			image.blit(90 + between, -25, cardBackSmall);
		end
		between = between + 40;
	end
	
	i = 0;
	between = 0;
	
	while (i < maxHandSize) do
		i = i + 1;
		if (hand4[i] ~= nil) then
			image.blit(455, 40 + between, cardBackSmall);
		end
		between = between + 25;
	end
	
end

showTable = function()
	local i = 0;
	local x = 0;
	local y = 0;
		
	while (i < #table1) do
		i = i + 1
      checkCurrentCard(table1[i], "small");
      
      if (table1[i] == "Open Company") then
         x = 30;
         y = 200;
      elseif (table1[i] == "Conviction") then
         x = 70;
         y = 200;
      elseif (table1[i] == "Tax Evasion") then
         x = 110;
         y = 200;
      elseif (table1[i] == "Strike") then
         x = 150;
         y = 200;
      elseif (table1[i] == "Eco Crime") then
         x = 190;
         y = 200;
      end
      
      image.blit(x, y, currentCard);
	end
	
	i = 0;
	x = 0;
	y = 0;
	
	while (i < #table2) do
		i = i + 1
      checkCurrentCard(table2[i], "small");
      
      if (table2[i] == "Open Company") then
         x = 30;
         y = 88;
      elseif (table2[i] == "Conviction") then
         x = 70;
         y = 88;
      elseif (table2[i] == "Tax Evasion") then
         x = 110;
         y = 88;
      elseif (table2[i] == "Strike") then
         x = 150;
         y = 88;
      elseif (table2[i] == "Eco Crime") then
         x = 190;
         y = 88;
      end
      
      image.blit(x, y, currentCard);
	end
	
	i = 0;
	x = 0;
	y = 0;
	
	while (i < #table3) do
		i = i + 1
      checkCurrentCard(table3[i], "small");
      
      if (table3[i] == "Open Company") then
         x = 240;
         y = 88;
      elseif (table3[i] == "Conviction") then
         x = 280;
         y = 88;
      elseif (table3[i] == "Tax Evasion") then
         x = 320;
         y = 88;
      elseif (table3[i] == "Strike") then
         x = 360;
         y = 88;
      elseif (table3[i] == "Eco Crime") then
         x = 400;
         y = 88;
      end
      
      image.blit(x, y, currentCard);
	end
	
	i = 0;
	x = 0;
	y = 0;
	
	while (i < #table4) do
		i = i + 1
      checkCurrentCard(table4[i], "small");
      
      if (table4[i] == "Open Company") then
         x = 240;
         y = 200;
      elseif (table4[i] == "Conviction") then
         x = 280;
         y = 200;
      elseif (table4[i] == "Tax Evasion") then
         x = 320;
         y = 200;
      elseif (table4[i] == "Strike") then
         x = 360;
         y = 200;
      elseif (table4[i] == "Eco Crime") then
         x = 400;
         y = 200;
      end
      
      image.blit(x, y, currentCard);
	end
	
end

showMoney = function()
	local i = 0;
	local value1 = 0;
	local value2 = 0;
	local value3 = 0;
	local value4 = 0;
	
	while (i < #company1) do
		i = i + 1;
      if (company1[i] == "$15000") then
         value1 = value1 + 15000;
      elseif (company1[i] == "$25000") then
         value1 = value1 + 25000;
      elseif (company1[i] == "$50000") then
         value1 = value1 + 50000;
      elseif (company1[i] == "$100000") then
         value1 = value1 + 100000;
      end
	end
	
	i = 0;
	while (i < #company2) do
		i = i + 1;
      if (company2[i] == "$15000") then
         value2 = value2 + 15000;
      elseif (company2[i] == "$25000") then
         value2 = value2 + 25000;
      elseif (company2[i] == "$50000") then
         value2 = value2 + 50000;
      elseif (company2[i] == "$100000") then
         value2 = value2 + 100000;
      end
	end

	i = 0;
	while (i < #company3) do
		i = i + 1;
      if (company3[i] == "$15000") then
         value3 = value3 + 15000;
      elseif (company3[i] == "$25000") then
         value3 = value3 + 25000;
      elseif (company3[i] == "$50000") then
         value3 = value3 + 50000;
      elseif (company3[i] == "$100000") then
         value3 = value3 + 100000;
      end
	end
	
	i = 0;
	while (i < #company4) do
		i = i + 1;
      if (company4[i] == "$15000") then
         value4 = value4 + 15000;
      elseif (company4[i] == "$25000") then
         value4 = value4 + 25000;
      elseif (company4[i] == "$50000") then
         value4 = value4 + 50000;
      elseif (company4[i] == "$100000") then
         value4 = value4 + 100000;
		end
	end
	
	screen.print(50, 155 - yDifference, "Company $" .. value1, 0.8, blue, shadowColor, "left");
	screen.print(50, 175 - yDifference, "Account $" .. bank1, 0.8, blue, shadowColor, "left")
	screen.print(50, 40 - yDifference, "Company $" .. value2, 0.8, blue, shadowColor, "left");
	screen.print(50, 60 - yDifference, "Account $" .. bank2, 0.8, blue, shadowColor, "left")
	
	if (playersSize > 2) then
		screen.print(260, 40 - yDifference, "Company $" .. value3, 0.8, blue, shadowColor, "left");
		screen.print(260, 60 - yDifference, "Account $" .. bank3, 0.8, blue, shadowColor, "left")
	end
	
	if (playersSize > 3) then
		screen.print(260, 155 - yDifference, "Company $" .. value4, 0.8, blue, shadowColor, "left");
		screen.print(260, 175 - yDifference, "Account $" .. bank4, 0.8, blue, shadowColor, "left")
	end
	
end

showMessage = function(message, messageColor, cardName)

	if (messageColor == nil) then
		messageColor = blue;
	end

	--image.blit(210,90,messageBox)
	image.blit(30,90,messageBox)
	
	if (cardName ~= nil) then
		checkCurrentCard(cardName, "big");
		--image.blit(30, 3, currentCard);
		image.blit(270, 3, currentCard);
	end
	
	--screen.print(215, 110, message);
	screen.print(45, 115 - yDifference, message, 0.8, messageColor, shadowColor, "left");
	showText = true;
end

showCompanyBox = function(message)
	local messageColor = blue;
	image.blit(30,90,companyBox)
	screen.print(45, 115 - yDifference, message, 0.8, messageColor, shadowColor, "left");
end

showTargets = function()
	image.blit(220,140, p1)
	image.blit(220,115, p2)
	image.blit(245,115, p3)
	image.blit(245,140, p4)
end

chooseTarget = function(selection, selectorX)
	local target = 1;

	while true do
		
	
		image.blit(0, 0, background);
		
		--screen.print(380, 10, #deck - deckIndex + 1 .. " / " .. #deck);
		screen.print(35, 10 - yDifference, #deck - deckIndex + 1 .. " / " .. #deck, 0.6, blue, shadowColor, "left");
		showHands();
		showTable();
		showTargets();
		showMoney();
		checkCurrentCard(hand1[selection], "big");
		--image.blit(30, 3, currentCard);
		image.blit(270, 3, currentCard);
		image.blit(90 + selectorX, 254, selector2);
	
		if (target == 1) then
			image.blit(208, 135, targeter)
		elseif (target == 2) then
			image.blit(208, 110, targeter)
		elseif (target == 3) then
			image.blit(235, 110, targeter)
		else
			image.blit(235,135,targeter)
		end
	
		controls.read()

			if controls.press("cross") then
				break;
			elseif controls.press("circle") then
				-- cancel
				target = 0;
				break;
			elseif controls.press("down") or controls.analogy() == 127 + waitAnalog then
				waitAnalog = 0.2
				waitMoment = os.clock()
				if (target == 1) then
					target = 2;
				elseif (target == 2) then
					target = 1;
				elseif (target == 3) then
					target = 4;
				elseif (target == 4) then
					target = 3;
				end
				
			elseif controls.press("up") or controls.analogy() == -128 - waitAnalog then
				waitAnalog = 0.2
				waitMoment = os.clock()
				if (target == 1) then
					target = 2;
				elseif (target == 2) then
					target = 1;
				elseif (target == 3) then
					target = 4;
				elseif (target == 4) then
					target = 3;
				end
				
			elseif controls.press("left") or controls.analogx() == -128 - waitAnalog then
				waitAnalog = 0.2
				waitMoment = os.clock()
				if (target == 1) then
					target = 4;
				elseif (target == 2) then
					target = 3;
				elseif (target == 3) then
					target = 2;
				elseif (target == 4) then
					target = 1;
				end
				
			elseif controls.press("right") or controls.analogx() == 127 + waitAnalog then
				waitAnalog = 0.2
				waitMoment = os.clock()
				if (target == 1) then
					target = 4;
				elseif (target == 2) then
					target = 3;
				elseif (target == 3) then
					target = 2;
				elseif (target == 4) then
					target = 1;
				end
				
			elseif controls.press("r") then
				changeStyle(1);
			elseif controls.press("l") then
				changeStyle(-1);
			end
			
			screen.flip()
			if (os.clock() - waitMoment >= waitAnalog) then
				waitAnalog = 0;
			end
	end

return target;
end

checkCompany = function(target)
	local i = 0;
	if (target == 1) then
		while (i < #table1) do
			i = i + 1;
			if (table1[i] == "Open Company") then
				return true;
			end
		end
	elseif (target == 2) then
		while (i < #table2) do
			i = i + 1;
			if (table2[i] == "Open Company") then
				return true;
			end
		end
	
	elseif (target == 3) then
		while (i < #table3) do
			i = i + 1;
			if (table3[i] == "Open Company") then
				return true;
			end
		end
	elseif (target == 4) then
		while (i < #table4) do
			i = i + 1;
			if (table4[i] == "Open Company") then
				return true;
			end
		end
	end
	
	return false;
end

drawCard = function(turn, playingNewBeginning)
	
	if (playingNewBeginning == false) then
		if (deckIndex > #deck or gameEnds) then
			
			if (deckIndex > #deck) then
				showResults("Deck ends, game ends.")
			else
				local finisher = turn - 1;
				if (finisher < 1) then
					finisher = playersSize;
				end
				showResults("Player" .. finisher .. " sells company and ends the game.")
			end
		end
	end

	local i = 0;
	if (turn == 1) then
		while (i < maxHandSize) do
			i = i + 1;
			if (hand1[i] == nil) then
				hand1[i] = deck[deckIndex];
				deckIndex = deckIndex + 1;
				break;
			end
		end
	elseif (turn == 2) then
		while (i < maxHandSize) do
			i = i + 1;
			if (hand2[i] == nil) then
				hand2[i] = deck[deckIndex];
				deckIndex = deckIndex + 1;
				break;
			end
		end
	elseif (turn == 3) then
		while (i < maxHandSize) do
			i = i + 1;
			if (hand3[i] == nil) then
				hand3[i] = deck[deckIndex];
				deckIndex = deckIndex + 1;
				break;
			end
		end
	else
		while (i < maxHandSize) do
			i = i + 1;
			if (hand4[i] == nil) then
				hand4[i] = deck[deckIndex];
				deckIndex = deckIndex + 1;
				break;
			end
		end
	end
end

discardCard = function(turn, index)

	if (turn == 1) then
		if (hand1[index] ~= "Bankruptcy" and hand1[index] ~= "Robbery" and hand1[index] ~= "Deal") then
			showMessage("Player" .. turn .. " discards card\n" .. hand1[index], discardColor, hand1[index])
			numberOfUsedCards = numberOfUsedCards + 1;
			usedCards[#usedCards + 1] = hand1[index];
			hand1[index] = nil;
			legalMove = true;
		else
			local i = 0;
			local elseCanBeRemoved = false;
			while (i < maxHandSize) do
				i = i + 1;
				if (hand1[i] ~= "Bankruptcy" and hand1[i] ~= "Robbery" and hand1[i] ~= "Deal") then
					showMessage("Cannot discard card\n" .. hand1[index], errorColor, hand1[index]);
					elseCanBeRemoved = true;
					legalMove = false;
					break;
				end
			end
			
			-- Player hand is full of cards that cannot be otherwise discarded
			if (elseCanBeRemoved == false) then
				showMessage("Player" .. turn .. " discards card\n" .. hand1[index], discardColor, hand1[index])
				numberOfUsedCards = numberOfUsedCards + 1;
				usedCards[#usedCards + 1] = hand1[index];
				hand1[index] = nil;
				legalMove = true;
			end
		end
	-- Discard legality check should be done in cpu logic
	elseif (turn == 2) then
		showMessage("Player" .. turn .. " discards card\n" .. hand2[index], discardColor, hand2[index])
		numberOfUsedCards = numberOfUsedCards + 1;
		usedCards[#usedCards + 1] = hand2[index];
		hand2[index] = nil;
		legalMove = true;
	elseif (turn == 3) then
		showMessage("Player" .. turn .. " discards card\n" .. hand3[index], discardColor, hand3[index])
		numberOfUsedCards = numberOfUsedCards + 1;
		usedCards[#usedCards + 1] = hand3[index];
		hand3[index] = nil;
		legalMove = true;
	elseif (turn == 4) then
		showMessage("Player" .. turn .. " discards card\n" .. hand4[index], discardColor, hand4[index])
		numberOfUsedCards = numberOfUsedCards + 1;
		usedCards[#usedCards + 1] = hand4[index];
		hand4[index] = nil;
		legalMove = true;
	end
	
end

playOpenCompany = function(turn, target)

	-- Check whether target is self
	if (turn ~= target) then
		showMessage("This card can only be\ntargeted to self.", errorColor);
		legalMove = false;
		return
	end

	if (turn == 1) then
		-- Check whether table already has Company
		local i = 0;
		
		while (i < #table1) do
			i = i + 1
			if (table1[i] == "Open Company") then
				-- Already played
				showMessage("You have already opened\na company.", errorColor);
				legalMove = false;
				return;
			end
		end
		
		-- Legal move 
		table.insert(table1,"Open Company");
	
	-- cpu action legality in cpu level
	elseif (turn == 2) then
		table.insert(table2,"Open Company");
	elseif (turn == 3) then
		table.insert(table3,"Open Company");
	elseif (turn == 4) then
		table.insert(table4,"Open Company");
	end
	
	playSound(soundPlayCompanyCard)

end

playMoneyCard = function(turn, target, cardName)
	if (checkSelfLegality(turn, target) == false) then
		legalMove = false;
		return
	end
	
	if (turn == 1) then
		table.insert(company1,cardName);
	elseif (turn == 2) then
		table.insert(company2,cardName);
	elseif (turn == 3) then
		table.insert(company3,cardName);
	elseif (turn == 4) then
		table.insert(company4,cardName);
	end
	
	playSound(soundPlayMoneyCard)
end

threatCompany = function(target)
	local i = 0;

	if (target == 1) then
		
		while (i < #table1) do
			i = i + 1;
			if (table1[i] == "Conviction" or table1[i] == "Tax Evasion" or table1[i] == "Strike" or table1[i] == "Eco Crime") then
				return true;
			end
		end
	elseif (target == 2) then
		while (i < #table2) do
			i = i + 1;
			if (table2[i] == "Conviction" or table2[i] == "Tax Evasion" or table2[i] == "Strike" or table2[i] == "Eco Crime") then
				return true;
			end
		end
	elseif (target == 3) then
		while (i < #table3) do
			i = i + 1;
			if (table3[i] == "Conviction" or table3[i] == "Tax Evasion" or table3[i] == "Strike" or table3[i] == "Eco Crime") then
				return true;
			end
		end
	elseif (target == 4) then
		while (i < #table4) do
			i = i + 1;
			if (table4[i] == "Conviction" or table4[i] == "Tax Evasion" or table4[i] == "Strike" or table4[i] == "Eco Crime") then
				return true;
			end
		end
	end

	return false; -- not under a threat
end

checkMoney = function(target)
	local i = 0;
	if (target == 1) then
		while (i < #company1) do
			i = i + 1
			if (company1[i] == "$15000" or company1[i] == "$25000" or company1[i] == "$50000" or company1[i] == "$100000") then
				return true; -- enough money for bribing
			end
		end
	elseif (target == 2) then
		while (i < #company2) do
			i = i + 1
			if (company2[i] == "$15000" or company2[i] == "$25000" or company2[i] == "$50000" or company2[i] == "$100000") then
				return true; -- enough money for bribing
			end
		end
	elseif (target == 3) then
		while (i < #company3) do
			i = i + 1
			if (company3[i] == "$15000" or company3[i] == "$25000" or company3[i] == "$50000" or company3[i] == "$100000") then
				return true; -- enough money for bribing
			end
		end
	elseif (target == 4) then
		while (i < #company4) do
			i = i + 1
			if (company4[i] == "$15000" or company4[i] == "$25000" or company4[i] == "$50000" or company4[i] == "$100000") then
				return true; -- enough money for bribing
			end
		end
	end
	
	return false; -- no money within company
end

checkBribeLegality = function(turn, target)
	if (turn ~= target) then
		showMessage("This card can only be\ntargeted to self.", errorColor);
		return false
	end
	
	if (checkCompany(target) == false) then
		showMessage("You need to open\na company first.", errorColor);
		return false
	end
	
	if (threatCompany(target) == false) then
		showMessage("Your company is not\nunder a threat.", errorColor);
		return false;
	end
	
	if (checkMoney(target) == false) then
		showMessage("No money for bribing\nwithin your company.", errorColor);
		return false
	end
	
	return true;
end

checkSelfLegality = function(turn, target)
	if (turn ~= target) then
		showMessage("This card can only be\ntargeted to self.", errorColor);
		return false
	end
	
	if (checkCompany(target) == false) then
		showMessage("You need to open\na company first.", errorColor);
		return false
	end
	
	if (threatCompany(target)) then
		showMessage("You cannot play this card\nunder a threat.", errorColor);
		return false;
	end
	
	return true;
end

checkTargetLegality = function(turn, target)
	if (turn == target) then
		showMessage("This card cannot be\ntargeted to self.", errorColor);
		return false
	end
	
	if (target > playersSize) then
		showMessage("Target player is not\nparticipating the game.", errorColor);
		return false
	end

	if (checkCompany(target) == false) then
		showMessage("Target player has not\nopened a company yet.", errorColor);
		return false
	end
	
	return true;
end

playConviction = function(turn, target)
	
	if (checkTargetLegality(turn, target) == false) then
		legalMove = false;
		return;
	end
	
	if (target == 1) then
		local i = 0;
		
		while (i < #table1) do
			i = i + 1;
			if (table1[i] == "Conviction") then
				showMessage("Player " .. target .. " is already under\na conviction threat.", errorColor);
				legalMove = false;
				return
			elseif (userOptions[2] == "no" and (table1[i] == "Tax Evasion" or table1[i] == "Strike" or table1[i] == "Eco Crime")) then
				showMessage("Player " .. target .. " is already under\na threat.", errorColor);
				legalMove = false;
				return
			end
		end
		-- Legal move
		table.insert(table1,"Conviction");
		
	elseif (target == 2) then
		local i = 0;
		
		while (i < #table2) do
			i = i + 1;
			if (table2[i] == "Conviction") then
				showMessage("Player " .. target .. " is already under\na conviction threat.", errorColor);
				legalMove = false;
				return
			elseif (userOptions[2] == "no" and (table2[i] == "Tax Evasion" or table2[i] == "Strike" or table2[i] == "Eco Crime")) then
				showMessage("Player " .. target .. " is already under\na threat.", errorColor);
				legalMove = false;
				return
			end
		end
		-- Legal move
		table.insert(table2,"Conviction");
	elseif (target == 3) then
		local i = 0;
		
		while (i < #table3) do
			i = i + 1;
			if (table3[i] == "Conviction") then
				showMessage("Player " .. target .. " is already under\na conviction threat.", errorColor);
				legalMove = false;
				return
			elseif (userOptions[2] == "no" and (table3[i] == "Tax Evasion" or table3[i] == "Strike" or table3[i] == "Eco Crime")) then
				showMessage("Player " .. target .. " is already under\na threat.", errorColor);
				legalMove = false;
				return
			end
		end
		-- Legal move
		table.insert(table3,"Conviction");
	elseif (target == 4) then
		local i = 0;
		
		while (i < #table4) do
			i = i + 1;
			if (table4[i] == "Conviction") then
				showMessage("Player " .. target .. " is already under\na conviction threat.", errorColor);
				legalMove = false;
				return
			elseif (userOptions[2] == "no" and (table4[i] == "Tax Evasion" or table4[i] == "Strike" or table4[i] == "Eco Crime")) then
				showMessage("Player " .. target .. " is already under\na threat.", errorColor);
				legalMove = false;
				return
			end
		end
		-- Legal move
		table.insert(table4,"Conviction");
	end
	playSound(soundPlayThreatCard)
end

playTaxEvasion = function(turn, target)
	
	if (checkTargetLegality(turn, target) == false) then
		legalMove = false;
		return;
	end
	
	if (target == 1) then
		local i = 0;
		
		while (i < #table1) do
			i = i + 1;
			if (table1[i] == "Tax Evasion") then
				showMessage("Player " .. target .. " is already under\na tax evasion threat.", errorColor);
				legalMove = false;
				return
			elseif (userOptions[2] == "no" and (table1[i] == "Conviction" or table1[i] == "Strike" or table1[i] == "Eco Crime")) then
				showMessage("Player " .. target .. " is already under\na threat.", errorColor);
				legalMove = false;
				return
			end
		end
		-- Legal move
		table.insert(table1,"Tax Evasion");
		
	elseif (target == 2) then
		local i = 0;
		
		while (i < #table2) do
			i = i + 1;
			if (table2[i] == "Tax Evasion") then
				showMessage("Player " .. target .. " is already under\na tax evasion threat.", errorColor);
				legalMove = false;
				return
			elseif (userOptions[2] == "no" and (table2[i] == "Conviction" or table2[i] == "Strike" or table2[i] == "Eco Crime")) then
				showMessage("Player " .. target .. " is already under\na threat.", errorColor);
				legalMove = false;
				return
			end
		end
		-- Legal move
		table.insert(table2,"Tax Evasion");
	elseif (target == 3) then
		local i = 0;
		
		while (i < #table3) do
			i = i + 1;
			if (table3[i] == "Tax Evasion") then
				showMessage("Player " .. target .. " is already under\na tax evasion threat.", errorColor);
				legalMove = false;
				return
			elseif (userOptions[2] == "no" and (table3[i] == "Conviction" or table3[i] == "Strike" or table3[i] == "Eco Crime")) then
				showMessage("Player " .. target .. " is already under\na threat.", errorColor);
				legalMove = false;
				return
			end
		end
		-- Legal move
		table.insert(table3,"Tax Evasion");
	elseif (target == 4) then
		local i = 0;
		
		while (i < #table4) do
			i = i + 1;
			if (table4[i] == "Tax Evasion") then
				showMessage("Player " .. target .. " is already under\na tax evasion threat.", errorColor);
				legalMove = false;
				return
			elseif (userOptions[2] == "no" and (table4[i] == "Conviction" or table4[i] == "Strike" or table4[i] == "Eco Crime")) then
				showMessage("Player " .. target .. " is already under\na threat.", errorColor);
				legalMove = false;
				return
			end
		end
		-- Legal move
		table.insert(table4,"Tax Evasion");
	end
	playSound(soundPlayThreatCard)
end

playStrike = function(turn, target)
	
	if (checkTargetLegality(turn, target) == false) then
		legalMove = false;
		return;
	end

	if (target == 1) then
		local i = 0;
		
		while (i < #table1) do
			i = i + 1;
			if (table1[i] == "Strike") then
				showMessage("Player " .. target .. " is already under\na strike threat.", errorColor);
				legalMove = false;
				return
			elseif (userOptions[2] == "no" and (table1[i] == "Conviction" or table1[i] == "Tax Evasion" or table1[i] == "Eco Crime")) then
				showMessage("Player " .. target .. " is already under\na threat.", errorColor);
				legalMove = false;
				return
			end
		end
		-- Legal move
		table.insert(table1,"Strike");
		
	elseif (target == 2) then
		local i = 0;
		
		while (i < #table2) do
			i = i + 1;
			if (table2[i] == "Strike") then
				showMessage("Player " .. target .. " is already under\na strike threat.", errorColor);
				legalMove = false;
				return
			elseif (userOptions[2] == "no" and (table2[i] == "Conviction" or table2[i] == "Tax Evasion" or table2[i] == "Eco Crime")) then
				showMessage("Player " .. target .. " is already under\na threat.", errorColor);
				legalMove = false;
				return
			end
		end
		-- Legal move
		table.insert(table2,"Strike");
	elseif (target == 3) then
		local i = 0;
		
		while (i < #table3) do
			i = i + 1;
			if (table3[i] == "Strike") then
				showMessage("Player " .. target .. " is already under\na strike threat.", errorColor);
				legalMove = false;
				return
			elseif (userOptions[2] == "no" and (table3[i] == "Conviction" or table3[i] == "Tax Evasion" or table3[i] == "Eco Crime")) then
				showMessage("Player " .. target .. " is already under\na threat.", errorColor);
				legalMove = false;
				return
			end
		end
		-- Legal move
		table.insert(table3,"Strike");
	elseif (target == 4) then
		local i = 0;
		
		while (i < #table4) do
			i = i + 1;
			if (table4[i] == "Strike") then
				showMessage("Player " .. target .. " is already under\na strike threat.", errorColor);
				legalMove = false;
				return
			elseif (userOptions[2] == "no" and (table4[i] == "Conviction" or table4[i] == "Tax Evasion" or table4[i] == "Eco Crime")) then
				showMessage("Player " .. target .. " is already under\na threat.", errorColor);
				legalMove = false;
				return
			end
		end
		-- Legal move
		table.insert(table4,"Strike");
	end
	playSound(soundPlayThreatCard)
end

playEcoCrime = function(turn, target)
	
	if (checkTargetLegality(turn, target) == false) then
		legalMove = false;
		return;
	end

	if (target == 1) then
		local i = 0;
		
		while (i < #table1) do
			i = i + 1;
			if (table1[i] == "Eco Crime") then
				showMessage("Player " .. target .. " is already under\nan eco crime threat.", errorColor);
				legalMove = false;
				return
			elseif (userOptions[2] == "no" and (table1[i] == "Conviction" or table1[i] == "Tax Evasion" or table1[i] == "Strike")) then
				showMessage("Player " .. target .. " is already under\na threat.", errorColor);
				legalMove = false;
				return
			end
		end
		-- Legal move
		table.insert(table1,"Eco Crime");
		
	elseif (target == 2) then
		local i = 0;
		
		while (i < #table2) do
			i = i + 1;
			if (table2[i] == "Eco Crime") then
				showMessage("Player " .. target .. " is already under\nan eco crime threat.", errorColor);
				legalMove = false;
				return
			elseif (userOptions[2] == "no" and (table2[i] == "Conviction" or table2[i] == "Tax Evasion" or table2[i] == "Strike")) then
				showMessage("Player " .. target .. " is already under\na threat.", errorColor);
				legalMove = false;
				return
			end
		end
		-- Legal move
		table.insert(table2,"Eco Crime");
	elseif (target == 3) then
		local i = 0;
		
		while (i < #table3) do
			i = i + 1;
			if (table3[i] == "Eco Crime") then
				showMessage("Player " .. target .. " is already under\nan eco crime threat.", errorColor);
				legalMove = false;
				return
			elseif (userOptions[2] == "no" and (table3[i] == "Conviction" or table3[i] == "Tax Evasion" or table3[i] == "Strike")) then
				showMessage("Player " .. target .. " is already under\na threat.", errorColor);
				legalMove = false;
				return
			end
		end
		-- Legal move
		table.insert(table3,"Eco Crime");
	elseif (target == 4) then
		local i = 0;
		
		while (i < #table4) do
			i = i + 1;
			if (table4[i] == "Eco Crime") then
				showMessage("Player " .. target .. " is already under\nan eco crime threat.", errorColor);
				legalMove = false;
				return
			elseif (userOptions[2] == "no" and (table4[i] == "Conviction" or table4[i] == "Tax Evasion" or table4[i] == "Strike")) then
				showMessage("Player " .. target .. " is already under\na threat.", errorColor);
				legalMove = false;
				return
			end
		end
		-- Legal move
		table.insert(table4,"Eco Crime");
	end
	playSound(soundPlayThreatCard)
end

playSmallSafe = function(turn, target)
	if (checkSelfLegality(turn, target) == false) then
		legalMove = false;
		return
	end
	
	local i = 0;
	
	if (turn == 1) then
		while (i < #company1) do
			i = i + 1;
			if (company1[i] == "$15000" or company1[i] == "$25000") then
				local value = tonumber(string.sub(company1[i], 2));
				bank1 = bank1 + value;
				table.remove(company1,i);
				i = i - 1;
			end
		end
	elseif (turn == 2) then
		while (i < #company2) do
			i = i + 1;
			if (company2[i] == "$15000" or company2[i] == "$25000") then
				local value = tonumber(string.sub(company2[i], 2));
				bank2 = bank2 + value;
				table.remove(company2,i);
				i = i - 1;
			end
		end
	elseif (turn == 3) then
		while (i < #company3) do
			i = i + 1;
			if (company3[i] == "$15000" or company3[i] == "$25000") then
				local value = tonumber(string.sub(company3[i], 2));
				bank3 = bank3 + value;
				table.remove(company3,i);
				i = i - 1;
			end
		end	
	elseif (turn == 4) then
		while (i < #company4) do
			i = i + 1;
			if (company4[i] == "$15000" or company4[i] == "$25000") then
				local value = tonumber(string.sub(company4[i], 2));
				bank4 = bank4 + value;
				table.remove(company4,i);
				i = i - 1;
			end
		end
	end
	playSound(soundPlaySafeCard)
end

playBigSafe = function(turn, target)
	if (checkSelfLegality(turn, target) == false) then
		legalMove = false;
		return
	end
	
	local i = 0;
	
	if (turn == 1) then
		while (i < #company1) do
			i = i + 1;
			if (company1[i] == "$15000" or company1[i] == "$25000" or company1[i] == "$50000") then
				local value = tonumber(string.sub(company1[i], 2));
				bank1 = bank1 + value;
				table.remove(company1,i);
				i = i - 1;
			end
		end
	elseif (turn == 2) then
		while (i < #company2) do
			i = i + 1;
			if (company2[i] == "$15000" or company2[i] == "$25000" or company2[i] == "$50000") then
				local value = tonumber(string.sub(company2[i], 2));
				bank2 = bank2 + value;
				table.remove(company2,i);
				i = i - 1;
			end
		end
	elseif (turn == 3) then
		while (i < #company3) do
			i = i + 1;
			if (company3[i] == "$15000" or company3[i] == "$25000" or company3[i] == "$50000") then
				local value = tonumber(string.sub(company3[i], 2));
				bank3 = bank3 + value;
				table.remove(company3,i);
				i = i - 1;
			end
		end	
	elseif (turn == 4) then
		while (i < #company4) do
			i = i + 1;
			if (company4[i] == "$15000" or company4[i] == "$25000" or company4[i] == "$50000") then
				local value = tonumber(string.sub(company4[i], 2));
				bank4 = bank4 + value;
				table.remove(company4,i);
				i = i - 1;
			end
		end
	end
	playSound(soundPlaySafeCard)
end

playRemoveConviction = function(target)
	
	if (target > playersSize) then
		showMessage("Target player is not\nparticipating the game.", errorColor);
		legalMove = false;
		return
	end

	if (checkCompany(target) == false) then
		showMessage("Target player has not\nopened a company yet.", errorColor);
		legalMove = false;
		return
	end
	
	local i = 0;
	local foundThreat = false;
	
	if (target == 1) then
		while (i < #table1) do
			i = i + 1;
			if (table1[i] == "Conviction") then
				table.remove(table1,i);
				foundThreat = true;
				break;
			end
		end
	
	elseif (target == 2) then
		while (i < #table2) do
			i = i + 1;
			if (table2[i] == "Conviction") then
				table.remove(table2,i);
				foundThreat = true;
				break;
			end
		end
	
	elseif (target == 3) then
		while (i < #table3) do
			i = i + 1;
			if (table3[i] == "Conviction") then
				table.remove(table3,i);
				foundThreat = true;
				break;
			end
		end
	
	elseif (target == 4) then
		while (i < #table4) do
			i = i + 1;
			if (table4[i] == "Conviction") then
				table.remove(table4,i);
				foundThreat = true;
				break;
			end
		end
	end
	
	if (foundThreat == false) then
		showMessage("Player" .. target .. " is not\nunder a Conviction threat.", errorColor);
		legalMove = false;
		return
	end
	
	playSound(soundPlayRemoveCard)
end

playRemoveTaxEvasion = function(target)
	
	if (target > playersSize) then
		showMessage("Target player is not\nparticipating the game.", errorColor);
		legalMove = false;
		return
	end

	if (checkCompany(target) == false) then
		showMessage("Target player has not\nopened a company yet.", errorColor);
		legalMove = false;
		return
	end
	
	local i = 0;
	local foundThreat = false;
	
	if (target == 1) then
		while (i < #table1) do
			i = i + 1;
			if (table1[i] == "Tax Evasion") then
				table.remove(table1,i);
				foundThreat = true;
				break;
			end
		end
	
	elseif (target == 2) then
		while (i < #table2) do
			i = i + 1;
			if (table2[i] == "Tax Evasion") then
				table.remove(table2,i);
				foundThreat = true;
				break;
			end
		end
	
	elseif (target == 3) then
		while (i < #table3) do
			i = i + 1;
			if (table3[i] == "Tax Evasion") then
				table.remove(table3,i);
				foundThreat = true;
				break;
			end
		end
	
	elseif (target == 4) then
		while (i < #table4) do
			i = i + 1;
			if (table4[i] == "Tax Evasion") then
				table.remove(table4,i);
				foundThreat = true;
				break;
			end
		end
	end
	
	if (foundThreat == false) then
		showMessage("Player" .. target .. " is not\nunder a Tax Evasion threat.", errorColor);
		legalMove = false;
		return
	end
	
	playSound(soundPlayRemoveCard)
end

playRemoveStrike = function(target)
	
	if (target > playersSize) then
		showMessage("Target player is not\nparticipating the game.", errorColor);
		legalMove = false;
		return
	end

	if (checkCompany(target) == false) then
		showMessage("Target player has not\nopened a company yet.", errorColor);
		legalMove = false;
		return
	end
	
	local i = 0;
	local foundThreat = false;
	
	if (target == 1) then
		while (i < #table1) do
			i = i + 1;
			if (table1[i] == "Strike") then
				table.remove(table1,i);
				foundThreat = true;
				break;
			end
		end
	
	elseif (target == 2) then
		while (i < #table2) do
			i = i + 1;
			if (table2[i] == "Strike") then
				table.remove(table2,i);
				foundThreat = true;
				break;
			end
		end
	
	elseif (target == 3) then
		while (i < #table3) do
			i = i + 1;
			if (table3[i] == "Strike") then
				table.remove(table3,i);
				foundThreat = true;
				break;
			end
		end
	
	elseif (target == 4) then
		while (i < #table4) do
			i = i + 1;
			if (table4[i] == "Strike") then
				table.remove(table4,i);
				foundThreat = true;
				break;
			end
		end
	end
	
	if (foundThreat == false) then
		showMessage("Player" .. target .. " is not\nunder a Strike threat.", errorColor);
		legalMove = false;
		return
	end
	
	playSound(soundPlayRemoveCard)
end

playRemoveEcoCrime = function(target)
	
	if (target > playersSize) then
		showMessage("Target player is not\nparticipating the game.", errorColor);
		legalMove = false;
		return
	end

	if (checkCompany(target) == false) then
		showMessage("Target player has not\nopened a company yet.", errorColor);
		legalMove = false;
		return
	end
	
	local i = 0;
	local foundThreat = false;
	
	if (target == 1) then
		while (i < #table1) do
			i = i + 1;
			if (table1[i] == "Eco Crime") then
				table.remove(table1,i);
				foundThreat = true;
				break;
			end
		end
	
	elseif (target == 2) then
		while (i < #table2) do
			i = i + 1;
			if (table2[i] == "Eco Crime") then
				table.remove(table2,i);
				foundThreat = true;
				break;
			end
		end
	
	elseif (target == 3) then
		while (i < #table3) do
			i = i + 1;
			if (table3[i] == "Eco Crime") then
				table.remove(table3,i);
				foundThreat = true;
				break;
			end
		end
	
	elseif (target == 4) then
		while (i < #table4) do
			i = i + 1;
			if (table4[i] == "Eco Crime") then
				table.remove(table4,i);
				foundThreat = true;
				break;
			end
		end
	end
	
	if (foundThreat == false) then
		showMessage("Player" .. target .. " is not\nunder a Eco Crime threat.", errorColor);
		legalMove = false;
		return
	end
	
	playSound(soundPlayRemoveCard)
end

playBankruptcy = function(turn, target)
	
	if (turn ~= target) then
		showMessage("This card can only be\ntargeted to self.", errorColor);
		legalMove = false;
		return	
	end
	
	if (turn == 1) then
		table1 = {}
		company1 = {}
		bank1 = 0
	elseif (turn == 2) then
		table2 = {}
		company2 = {}
		bank2 = 0
	elseif (turn == 3) then
		table3 = {}
		company3 = {}
		bank3 = 0
	elseif (turn == 4) then
		table4 = {}
		company4 = {}
		bank4 = 0
	end
	playSound(soundPlayBankruptcyCard)
end

playBanker = function()
	showMessage("Banker is not a\nplayable card.", errorColor);
	legalMove = false;
end

playNewBeginning = function(turn, target, index)
	
	if (turn ~= target) then
		showMessage("This card can only be\ntargeted to self.", errorColor);
		legalMove = false;
		return;
	end
	
	local i = 0;
	
	if (turn == 1) then
		while (i < maxHandSize) do
			i = i +1;
			if (i ~= index) then
				hand1[i] = nil;
			end
		end
		
	elseif (turn == 2) then
		while (i < maxHandSize) do
			i = i +1;
			if (i ~= index) then
				hand2[i] = nil;
			end
		end
	
	elseif (turn == 3) then
		while (i < maxHandSize) do
			i = i +1;
			if (i ~= index) then
				hand3[i] = nil;
			end
		end
	
	elseif (turn == 4) then
		while (i < maxHandSize) do
			i = i +1;
			if (i ~= index) then
				hand4[i] = nil;
			end
		end
	end
	
	-- draw six cards
	drawCard(turn, true);
	drawCard(turn, true);
	drawCard(turn, true);
	drawCard(turn, true);
	drawCard(turn, true);
	drawCard(turn, true);
	
	playSound(soundPlayNewBeginningCard)
end

-- third parameter is needed because bribe uses this logic
playRobbery = function(turn, target, noSound)
				
	if (turn ~= target) then
		showMessage("This card can only be\ntargeted to self.", errorColor);
		legalMove = false;
		return;
	end
	
	local i = 0;
	local index = 0;
	
	if (turn == 1) then
		while (i < #company1) do
			i = i + 1
			
			if (company1[i] == "$15000" or company1[i] == "$25000" or company1[i] == "$50000" or company1[i] == "$100000") then
				if (index == 0 or tonumber(string.sub(company1[i], 2)) < tonumber(string.sub(company1[index], 2))) then -- CRASH WITH BRIBE only strike left
					index = i;
				end
			end
		end
		
		if (index ~= 0) then
			table.remove(company1,index);
		end
		
	elseif (turn == 2) then
		while (i < #company2) do
			i = i + 1
			if (company2[i] == "$15000" or company2[i] == "$25000" or company2[i] == "$50000" or company2[i] == "$100000") then
				if (index == 0 or tonumber(string.sub(company2[i], 2)) < tonumber(string.sub(company2[index], 2))) then
					index = i;
				end
			end
		end
		
		if (index ~= 0) then
			table.remove(company2,index);
		end
		
	elseif (turn == 3) then
		while (i < #company3) do
			i = i + 1
			if (company3[i] == "$15000" or company3[i] == "$25000" or company3[i] == "$50000" or company3[i] == "$100000") then
				if (index == 0 or tonumber(string.sub(company3[i], 2)) < tonumber(string.sub(company3[index], 2))) then
					index = i;
				end
			end
		end
		
		if (index ~= 0) then
			table.remove(company3,index);
		end
	
	elseif (turn == 4) then
		while (i < #company4) do
			i = i + 1
			if (company4[i] == "$15000" or company4[i] == "$25000" or company4[i] == "$50000" or company4[i] == "$100000") then
				if (index == 0 or tonumber(string.sub(company4[i], 2)) < tonumber(string.sub(company4[index], 2))) then
					index = i;
				end
			end
		end
		
		if (index ~= 0) then
			table.remove(company4,index);
		end
	end
	
	if (noSound == false) then
		playSound(soundPlayRobberyCard)
	end
end

playLuck = function(turn, target)

	--if (checkCompany(turn) == false) then
	--	showMessage("You need to open\na company first.", errorColor);
	--	legalMove = false;
	--	return
	--end

	if (checkTargetLegality(turn, target) == false) then
		legalMove = false;
		return;
	end
	
	local i = 0;
	local index = 0;
	local buyingCard = nil;
	
	-- Take the money
	if (target == 1) then
		while (i < #company1) do
			i = i + 1
			if (company1[i] == "$15000" or company1[i] == "$25000" or company1[i] == "$50000" or company1[i] == "$100000") then
				if (index == 0 or tonumber(string.sub(company1[i], 2)) < tonumber(string.sub(company1[index], 2))) then
					index = i;
				end
			end
		end
		
		if (index ~= 0 and checkCompany(turn)) then -- 9.4.2011 added a condition that company is required for money to be moved.
			buyingCard = company1[index];
			table.remove(company1,index);
		end
		
	elseif (target == 2) then
		while (i < #company2) do
			i = i + 1
			if (company2[i] == "$15000" or company2[i] == "$25000" or company2[i] == "$50000" or company2[i] == "$100000") then
				if (index == 0 or tonumber(string.sub(company2[i], 2)) < tonumber(string.sub(company2[index], 2))) then
					index = i;
				end
			end
		end
		
		if (index ~= 0 and checkCompany(turn)) then
			buyingCard = company2[index];
			table.remove(company2,index);
		end
		
	elseif (target == 3) then
		while (i < #company3) do
			i = i + 1
			if (company3[i] == "$15000" or company3[i] == "$25000" or company3[i] == "$50000" or company3[i] == "$100000") then
				if (index == 0 or tonumber(string.sub(company3[i], 2)) < tonumber(string.sub(company3[index], 2))) then
					index = i;
				end
			end
		end
		
		if (index ~= 0 and checkCompany(turn)) then
			buyingCard = company3[index];
			table.remove(company3,index);
		end
	
	elseif (target == 4) then
		while (i < #company4) do
			i = i + 1
			if (company4[i] == "$15000" or company4[i] == "$25000" or company4[i] == "$50000" or company4[i] == "$100000") then
				if (index == 0 or tonumber(string.sub(company4[i], 2)) < tonumber(string.sub(company4[index], 2))) then
					index = i;
				end
			end
		end
		
		if (index ~= 0 and checkCompany(turn)) then
			buyingCard = company4[index];
			table.remove(company4,index);
		end
	end
	
	-- add the money
	if (buyingCard ~= nil) then
		if (turn == 1) then
			table.insert(company1,buyingCard);
		elseif (turn == 2) then
			table.insert(company2,buyingCard);
		elseif (turn == 3) then
			table.insert(company3,buyingCard);
		elseif (turn == 4) then
			table.insert(company4,buyingCard);
		end
	end
	
	playSound(soundPlayLuckCard)
end

playThief = function(turn, target)
	if (checkCompany(turn) == false) then
		showMessage("You need to open\na company first.", errorColor);
		legalMove = false;
		return
	end

	if (checkTargetLegality(turn, target) == false) then
		legalMove = false;
		return;
	end
	
	local i = 0;
	local index = 0;
	local stealingCard = nil;
	local statusEffect = {}
	
	-- Take the money
	if (target == 1) then
		while (i < #company1) do
			i = i + 1
			if (company1[i] == "$15000" or company1[i] == "$25000" or company1[i] == "$50000" or company1[i] == "$100000") then
				if (index == 0 or tonumber(string.sub(company1[i], 2)) > tonumber(string.sub(company1[index], 2))) then
					index = i;
				end
			end
		end
		
		if (index ~= 0) then
			stealingCard = company1[index];
			table.remove(company1,index);
		end
		
		-- get and nil threats
		i = 0;
		while (i < #table1) do
			i = i + 1;
			if (table1[i] == "Conviction" or table1[i] == "Tax Evasion" or table1[i] == "Strike" or table1[i] == "Eco Crime") then
				statusEffect[#statusEffect + 1] = table1[i];
				table.remove(table1,i);
				i = i - 1;
			end
		end
		
	elseif (target == 2) then
		while (i < #company2) do
			i = i + 1
			if (company2[i] == "$15000" or company2[i] == "$25000" or company2[i] == "$50000" or company2[i] == "$100000") then
				if (index == 0 or tonumber(string.sub(company2[i], 2)) > tonumber(string.sub(company2[index], 2))) then
					index = i;
				end
			end
		end
		
		if (index ~= 0) then
			stealingCard = company2[index];
			table.remove(company2,index);
		end
		
		-- get and nil threats
		i = 0;
		while (i < #table2) do
			i = i + 1;
			if (table2[i] == "Conviction" or table2[i] == "Tax Evasion" or table2[i] == "Strike" or table2[i] == "Eco Crime") then
				statusEffect[#statusEffect + 1] = table2[i];
				table.remove(table2,i);
				i = i - 1;
			end
		end
		
	elseif (target == 3) then
		while (i < #company3) do
			i = i + 1
			if (company3[i] == "$15000" or company3[i] == "$25000" or company3[i] == "$50000" or company3[i] == "$100000") then
				if (index == 0 or tonumber(string.sub(company3[i], 2)) > tonumber(string.sub(company3[index], 2))) then
					index = i;
				end
			end
		end
		
		if (index ~= 0) then
			stealingCard = company3[index];
			table.remove(company3,index);
		end
		
		-- get and nil threats
		i = 0;
		while (i < #table3) do
			i = i + 1;
			if (table3[i] == "Conviction" or table3[i] == "Tax Evasion" or table3[i] == "Strike" or table3[i] == "Eco Crime") then
				statusEffect[#statusEffect + 1] = table3[i];
				table.remove(table3,i);
				i = i - 1;
			end
		end
	
	elseif (target == 4) then
		while (i < #company4) do
			i = i + 1
			if (company4[i] == "$15000" or company4[i] == "$25000" or company4[i] == "$50000" or company4[i] == "$100000") then
				if (index == 0 or tonumber(string.sub(company4[i], 2)) > tonumber(string.sub(company4[index], 2))) then
					index = i;
				end
			end
		end
		
		if (index ~= 0) then
			stealingCard = company4[index];
			table.remove(company4,index);
		end
		
		-- get and nil threats
		i = 0;
		while (i < #table4) do
			i = i + 1;
			if (table4[i] == "Conviction" or table4[i] == "Tax Evasion" or table4[i] == "Strike" or table4[i] == "Eco Crime") then
				statusEffect[#statusEffect + 1] = table4[i];
				table.remove(table4,i);
				i = i - 1;
			end
		end
	end
	
	-- add the money and possible status effects
	i = 0;
	local j = 0;
	local effectAlredy = false;
	
	-- check the rule of multiple threats allowed
	local allowNewThreat = true;
	if (userOptions[2] == "no") then 
		if (checkNumberOfThreats(turn) > 0) then 
			allowNewThreat = false;
		end
	end
	
	if (turn == 1) then
		if (stealingCard ~= nil) then
			table.insert(company1,stealingCard);
		end
		
		while (i < #statusEffect and allowNewThreat) do
			i = i + 1
			j = 0;
			effectAlready = false;
			while (j < #table1) do
				j = j + 1
				if (table1[j] == statusEffect[i]) then
					effectAlready = true;
					break;
				end
			end
			if (effectAlready == false) then
				table.insert(table1,statusEffect[i]);
			end
		end
	elseif (turn == 2) then
		if (stealingCard ~= nil) then
			table.insert(company2,stealingCard);
		end
		while (i < #statusEffect and allowNewThreat) do
			i = i + 1
			j = 0;
			effectAlready = false;
			while (j < #table2) do
				j = j + 1
				if (table2[j] == statusEffect[i]) then
					effectAlready = true;
					break;
				end
			end
			if (effectAlready == false) then
				table.insert(table2,statusEffect[i]);
			end
		end
	elseif (turn == 3) then
		if (stealingCard ~= nil) then
			table.insert(company3,stealingCard);
		end
		while (i < #statusEffect and allowNewThreat) do
			i = i + 1
			j = 0;
			effectAlready = false;
			while (j < #table3) do
				j = j + 1
				if (table3[j] == statusEffect[i]) then
					effectAlready = true;
					break;
				end
			end
			if (effectAlready == false) then
				table.insert(table3,statusEffect[i]);
			end
		end
	elseif (turn == 4) then
		if (stealingCard ~= nil) then
			table.insert(company4,stealingCard);
		end
		while (i < #statusEffect and allowNewThreat) do
			i = i + 1
			j = 0;
			effectAlready = false;
			while (j < #table4) do
				j = j + 1
				if (table4[j] == statusEffect[i]) then
					effectAlready = true;
					break;
				end
			end
			if (effectAlready == false) then
				table.insert(table4,statusEffect[i]);
			end
		end
	end
	playSound(soundPlayThiefCard)
end

selectThreat = function(turn)

	local i = 0;
	local cursorX = 0;
	local threatSelection = 1;
	local firstSelection = true;
	local threatConviction = false;
	local threatTaxEvasion = false;
	local threatStrike = false;
	local threatEcoCrime = false;

	if (turn == 1) then
		while (i < #table1) do
			i = i + 1
			if (table1[i] == "Conviction") then
				threatConviction = true;
			elseif (table1[i] == "Tax Evasion") then
				threatTaxEvasion = true;
			elseif (table1[i] == "Strike") then
				threatStrike = true;
			elseif (table1[i] == "Eco Crime") then
				threatEcoCrime = true;
			end
		end
		
		while true do
				image.blit(0, 0, background);
	
				--screen.print(380, 10, #deck - deckIndex + 1 .. " / " .. #deck);
				screen.print(35, 10 - yDifference, #deck - deckIndex + 1 .. " / " .. #deck, 0.6, blue, shadowColor, "left");
				
				if (firstSelection) then
					if (threatConviction) then
						cursorX = 0;
						threatSelection = 1;
					elseif (threatTaxEvasion) then
						cursorX = 40;
						threatSelection = 2;
					elseif (threatStrike) then
						cursorX = 80;
						threatSelection = 3;
					elseif (threatEcoCrime) then
						cursorX = 120;
						threatSelection = 4;
					end
					
					firstSelection = false;
				end
				
				showHands();
				showTable();
				showTargets();
				showMoney();
				
				image.blit(70 + cursorX, 200, selector2);
				
				controls.read()

				if controls.press("r") then	
					changeStyle(1);
				elseif controls.press("l") then
					changeStyle(-1);
				elseif controls.press("cross") then -- return threat
					if (threatSelection == 1) then
						return "Conviction"
					elseif (threatSelection == 2) then
						return "Tax Evasion"
					elseif (threatSelection == 3) then
						return "Strike"
					elseif (threatSelection == 4) then
						return "Eco Crime"
					end
				elseif controls.press("left") or controls.analogx() == -128 - waitAnalog then
					waitAnalog = 0.2
					waitMoment = os.clock()
					threatSelection = threatSelection - 1;
					cursorX = cursorX - 40;
					if (threatSelection < 1) then
						if (threatEcoCrime) then
							cursorX = 120;
							threatSelection = 4;
						elseif (threatStrike) then
							cursorX = 80;
							threatSelection = 3;
						elseif (threatTaxEvasion) then
							cursorX = 40;
							threatSelection = 2;
						elseif (threatConviction) then
							cursorX = 0;
							threatSelection = 1;
						end
					end
					
					local looper = 0;
					
					while (looper < 3) do -- ensure not empty selection
					looper = looper + 1;
					
						if (threatSelection == 1 and threatConviction == false) then
							threatSelection = 4;
							cursorX = 120;
						end
					
						if (threatSelection == 2 and threatTaxEvasion == false) then
							threatSelection = 1;
							cursorX = 0;
						end
					
						if (threatSelection == 3 and threatStrike == false) then
							threatSelection = 2;
							cursorX = 40;
						end
					
						if (threatSelection == 4 and threatEcoCrime == false) then
							threatSelection = 3;
							cursorX = 80;
						end
					end
					
				elseif controls.press("right") or controls.analogx() == 127 + waitAnalog then
					waitAnalog = 0.2
					waitMoment = os.clock()
					threatSelection = threatSelection + 1;
					cursorX = cursorX + 40;
					
					if (threatSelection > 4) then
						if (threatConviction) then
							cursorX = 0;
							threatSelection = 1;
						elseif (threatTaxEvasion) then
							cursorX = 40;
							threatSelection = 2;
						elseif (threatStrike) then
							cursorX = 80;
							threatSelection = 3;
						elseif (threatEcoCrime) then
							cursorX = 120;
							threatSelection = 4;
						end
					end
					
					local looper = 0;
					
					while (looper < 3) do
					looper = looper + 1;
					
						if (threatSelection == 1 and threatConviction == false) then
							threatSelection = 2;
							cursorX = 40;
						end
					
						if (threatSelection == 2 and threatTaxEvasion == false) then
							threatSelection = 3;
							cursorX = 80;
						end
					
						if (threatSelection == 3 and threatStrike == false) then
							threatSelection = 4;
							cursorX = 120;
						end
					
						if (threatSelection == 4 and threatEcoCrime == false) then
							threatSelection = 1;
							cursorX = 0;
						end
					end
				end
				screen.flip()
				
				if (os.clock() - waitMoment >= waitAnalog) then
					waitAnalog = 0;
				end
		end
	
	elseif(turn == 2) then
		while (i < #table2) do
			i = i + 1;
			if (table2[i] == "Conviction") then
				return "Conviction";
			elseif (table2[i] == "Tax Evasion") then
				return "Tax Evasion"
			elseif (table2[i] == "Strike") then
				return "Strike"
			elseif (table2[i] == "Eco Crime") then
				return "Eco Crime"
			end
		end
	elseif(turn == 3) then
		while (i < #table3) do
			i = i + 1;
			if (table3[i] == "Conviction") then
				return "Conviction";
			elseif (table3[i] == "Tax Evasion") then
				return "Tax Evasion"
			elseif (table3[i] == "Strike") then
				return "Strike"
			elseif (table3[i] == "Eco Crime") then
				return "Eco Crime"
			end
		end
	elseif(turn == 4) then
		while (i < #table4) do
			i = i + 1;
			if (table4[i] == "Conviction") then
				return "Conviction";
			elseif (table4[i] == "Tax Evasion") then
				return "Tax Evasion"
			elseif (table4[i] == "Strike") then
				return "Strike"
			elseif (table4[i] == "Eco Crime") then
				return "Eco Crime"
			end
		end
	end
end

-- advanced cpu should play this card if not basic remove card available
playBribe = function(turn, target)
	if (checkBribeLegality(turn, target) == false) then
		legalMove = false;
		return;
	end
	
	-- select threat to be removed
	threatName = selectThreat(turn)
	
	local i = 0;
	
	-- remove selected threat
	if (target == 1) then
		while (i < #table1) do
			i = i + 1;
			if (table1[i] == threatName) then
				table.remove(table1,i);
				break;
			end
		end
	
	elseif (target == 2) then
		while (i < #table2) do
			i = i + 1;
			if (table2[i] == threatName) then
				table.remove(table2,i);
				break;
			end
		end
	
	elseif (target == 3) then
		while (i < #table3) do
			i = i + 1;
			if (table3[i] == threatName) then
				table.remove(table3,i);
				break;
			end
		end
	
	elseif (target == 4) then
		while (i < #table4) do
			i = i + 1;
			if (table4[i] == threatName) then
				table.remove(table4,i);
				break;
			end
		end
	end
	
	-- decrease the income using robbery logic
	playRobbery(turn, target, true);
	playSound(soundPlayRemoveCard)
	
end

--index card is the card that is played. Do not allow switch!
-- parameter turn is given if cpu targets player
selectOwnCard = function(index, additionalMessage, turn)
	local cursorX = 0;
	local cardIndexSelection = 1;
	
	if (index == cardIndexSelection) then
		cursorX = 40;
		cardIndexSelection = 2;
	end
	
	while true do
				
		image.blit(0, 0, background);
	
		--screen.print(380, 10, #deck - deckIndex + 1 .. " / " .. #deck);
		screen.print(35, 10 - yDifference, #deck - deckIndex + 1 .. " / " .. #deck, 0.6, blue, shadowColor, "left");
				
		showHands();
		showTable();
		showTargets();
		showMoney();
		
		checkCurrentCard(hand1[cardIndexSelection], "big");
		--image.blit(30, 3, currentCard);
		image.blit(270, 3, currentCard);
		image.blit(90 + cursorX, 254, selector2);
		
		if (additionalMessage) then
			if (turn == nil) then -- a check just in case.
				turn = "";
			end
			showMessage("Select a card to be\nswitched with player" .. turn .. ".")
		end
		
		controls.read()

		if controls.press("r") then	
			changeStyle(1);
		elseif controls.press("l") then
			changeStyle(-1);
		elseif controls.press("left") or controls.analogx() == -128 - waitAnalog then
			waitAnalog = 0.2
			waitMoment = os.clock()
			cursorX = cursorX - 40;
			cardIndexSelection = cardIndexSelection - 1;
			
			if (cardIndexSelection < 1) then
				cursorX = 240;
				cardIndexSelection = 7;
			end
			
			if (cardIndexSelection == index) then
				cursorX = cursorX - 40;
				cardIndexSelection = cardIndexSelection - 1;
			end
			
			if (cardIndexSelection < 1) then
				cursorX = 240;
				cardIndexSelection = 7;
			end
			
		elseif controls.press("right") or controls.analogx() == 127 + waitAnalog then
			waitAnalog = 0.2
			waitMoment = os.clock()
			cursorX = cursorX + 40;
			cardIndexSelection = cardIndexSelection + 1;
			
			if (cardIndexSelection > 7) then
				cursorX = 0;
				cardIndexSelection = 1;
			end
			
			if (cardIndexSelection == index) then
				cursorX = cursorX + 40;
				cardIndexSelection = cardIndexSelection + 1;
			end
			
			if (cardIndexSelection > 7) then
				cursorX = 0;
				cardIndexSelection = 1;
			end
			
		elseif controls.press("cross") then
			
			image.blit(0, 0, background);
			
			--screen.print(380, 10, #deck - deckIndex + 1 .. " / " .. #deck);
			screen.print(35, 10 - yDifference, #deck - deckIndex + 1 .. " / " .. #deck, 0.6, blue, shadowColor, "left");
			showHands();
			showTable();
			showTargets();
			showMoney();
			return cardIndexSelection
		end
		screen.flip()
		if (os.clock() - waitMoment >= waitAnalog) then
			waitAnalog = 0;
		end
	end
end

getNoCardIndex = function(target)
	local i = 0;
	if (target == 1) then
		while (i < maxHandSize) do
			i = i + 1;
			if (hand1[i] == nil) then
				return i;
			end
		end
	elseif (target == 2) then
		while (i < maxHandSize) do
			i = i + 1;
			if (hand2[i] == nil) then
				return i;
			end
		end
	elseif (target == 3) then
		while (i < maxHandSize) do
			i = i + 1;
			if (hand3[i] == nil) then
				return i;
			end
		end
	elseif (target == 4) then
		while (i < maxHandSize) do
			i = i + 1;
			if (hand4[i] == nil) then
				return i;
			end
		end
	end
end

playDeal = function(turn, target, index)
	
	if (turn == target) then
		showMessage("This card cannot be\ntargeted to self.", errorColor);
		legalMove = false;
		return
	end
	
	if (target > playersSize) then
		showMessage("Target player is not\nparticipating the game.", errorColor);
		legalMove = false;
		return
	end
	
	-- Remove the most valuable card
	local i = 0;
	local index2 = 0;
	
	if (turn == 1) then
		while (i < #company1) do
			i = i + 1
			if (company1[i] == "$15000" or company1[i] == "$25000" or company1[i] == "$50000" or company1[i] == "$100000") then
				if (index2 == 0 or tonumber(string.sub(company1[i], 2)) > tonumber(string.sub(company1[index2], 2))) then
					index2 = i;
				end
			end
		end
		
		if (index2 ~= 0) then
			table.remove(company1,index2);
		end
	elseif (turn == 2) then
		while (i < #company2) do
			i = i + 1
			if (company2[i] == "$15000" or company2[i] == "$25000" or company2[i] == "$50000" or company2[i] == "$100000") then
				if (index2 == 0 or tonumber(string.sub(company2[i], 2)) > tonumber(string.sub(company2[index2], 2))) then
					index2 = i;
				end
			end
		end
		
		if (index2 ~= 0) then
			table.remove(company2,index2);
		end
	elseif (turn == 3) then
		while (i < #company3) do
			i = i + 1
			if (company3[i] == "$15000" or company3[i] == "$25000" or company3[i] == "$50000" or company3[i] == "$100000") then
				if (index2 == 0 or tonumber(string.sub(company3[i], 2)) > tonumber(string.sub(company3[index2], 2))) then
					index2 = i;
				end
			end
		end
		
		if (index2 ~= 0) then
			table.remove(company3,index2);
		end
	elseif (turn == 4) then
		while (i < #company4) do
			i = i + 1
			if (company4[i] == "$15000" or company4[i] == "$25000" or company4[i] == "$50000" or company4[i] == "$100000") then
				if (index2 == 0 or tonumber(string.sub(company4[i], 2)) > tonumber(string.sub(company4[index2], 2))) then
					index2 = i;
				end
			end
		end
		
		if (index2 ~= 0) then
			table.remove(company4,index2);
		end
	end
	
	-- Select card
	if (turn == 1) then
		switchIndex1 = selectOwnCard(index, false)
		
		local noCardIndex = getNoCardIndex(target) -- get index that should not be selected (no card in that index)
		switchIndex2 = cpuSelectCard(noCardIndex, target)
	else
		switchIndex1 = cpuSelectCard(index, turn)
		
		local noCardIndex = getNoCardIndex(target)
		
		if (target == 1) then
			switchIndex2 = selectOwnCard(noCardIndex, true, turn)
		else
			switchIndex2 = cpuSelectCard(noCardIndex, target)
		end
	end
	
	-- Switch cards
	if (turn == 1) then
		if (target == 2) then
			hand1[switchIndex1], hand2[switchIndex2] = hand2[switchIndex2], hand1[switchIndex1]
		elseif (target == 3) then
			hand1[switchIndex1], hand3[switchIndex2] = hand3[switchIndex2], hand1[switchIndex1]
		elseif (target == 4) then
			hand1[switchIndex1], hand4[switchIndex2] = hand4[switchIndex2], hand1[switchIndex1]
		end
	elseif (turn == 2) then
		if (target == 1) then
			hand2[switchIndex1], hand1[switchIndex2] = hand1[switchIndex2], hand2[switchIndex1]
		elseif (target == 3) then
			hand2[switchIndex1], hand3[switchIndex2] = hand3[switchIndex2], hand2[switchIndex1]
		elseif (target == 4) then
			hand2[switchIndex1], hand4[switchIndex2] = hand4[switchIndex2], hand2[switchIndex1]
		end
	elseif (turn == 3) then
		if (target == 1) then
			hand3[switchIndex1], hand1[switchIndex2] = hand1[switchIndex2], hand3[switchIndex1]
		elseif (target == 2) then
			hand3[switchIndex1], hand2[switchIndex2] = hand2[switchIndex2], hand3[switchIndex1]
		elseif (target == 4) then
			hand3[switchIndex1], hand4[switchIndex2] = hand4[switchIndex2], hand3[switchIndex1]
		end
	elseif (turn == 4) then
		if (target == 1) then
			hand4[switchIndex1], hand1[switchIndex2] = hand1[switchIndex2], hand4[switchIndex1]
		elseif (target == 2) then
			hand4[switchIndex1], hand2[switchIndex2] = hand2[switchIndex2], hand4[switchIndex1]
		elseif (target == 3) then
			hand4[switchIndex1], hand3[switchIndex2] = hand3[switchIndex2], hand4[switchIndex1]
		end
	end
	
	playSound(soundPlayDealCard)
end

enoughMoneyForSelling = function(target)
	local earnedMoney = 0;
	local i = 0;
	if (target == 1) then
		earnedMoney = earnedMoney + bank1;
		
		while (i < #company1) do
			i = i + 1;
         if (company1[i] == "$15000") then
            earnedMoney = earnedMoney + 15000;
         elseif (company1[i] == "$25000") then
            earnedMoney = earnedMoney + 25000;
         elseif (company1[i] == "$50000") then
            earnedMoney = earnedMoney + 50000;
         elseif (company1[i] == "$100000") then
            earnedMoney = earnedMoney + 100000;
			end
		end
	elseif (target == 2) then
		earnedMoney = earnedMoney + bank2;
		
		while (i < #company2) do
			i = i + 1;
         if (company2[i] == "$15000") then
            earnedMoney = earnedMoney + 15000;
         elseif (company2[i] == "$25000") then
            earnedMoney = earnedMoney + 25000;
         elseif (company2[i] == "$50000") then
            earnedMoney = earnedMoney + 50000;
         elseif (company2[i] == "$100000") then
            earnedMoney = earnedMoney + 100000;
			end
		end
		
	elseif (target == 3) then
		earnedMoney = earnedMoney + bank3;
		
		while (i < #company3) do
			i = i + 1;
         if (company3[i] == "$15000") then
            earnedMoney = earnedMoney + 15000;
         elseif (company3[i] == "$25000") then
            earnedMoney = earnedMoney + 25000;
         elseif (company3[i] == "$50000") then
            earnedMoney = earnedMoney + 50000;
         elseif (company3[i] == "$100000") then
            earnedMoney = earnedMoney + 100000;
			end
		end
	elseif (target == 4) then
		earnedMoney = earnedMoney + bank4;
		
		while (i < #company4) do
			i = i + 1;
         if (company4[i] == "$15000") then
            earnedMoney = earnedMoney + 15000;
         elseif (company4[i] == "$25000") then
            earnedMoney = earnedMoney + 25000;
         elseif (company4[i] == "$50000") then
            earnedMoney = earnedMoney + 50000;
         elseif (company4[i] == "$100000") then
            earnedMoney = earnedMoney + 100000;
			end
		end
	end
	
	if (earnedMoney < sellCompanyMin) then
		showMessage("Selling a company\nrequires $" .. sellCompanyMin, errorColor)
		return false;
	end
	
	return true; -- player has earned enough money for selling the company
end

playSellCompany = function(turn, target)
	
	if (checkSelfLegality(turn, target) == false) then
		legalMove = false;
		return
	end
	
	-- check min money limit rule before selling
	if (enoughMoneyForSelling(target) == false) then
		legalMove = false
		return
	end

	gameEnds = true;
	playSound(soundPlayCompanyCard)
	
end

playNewIdentity = function(turn, target)

	if (turn ~= target) then
		showMessage("This card can only be\ntargeted to self.", errorColor);
		legalMove = false;
		return
	end
	
	if (checkCompany(target) == false) then
		showMessage("You need to open\na company first.", errorColor);
		legalMove = false;
		return
	end
	
	local i = 0;
	local foundThreat = false;
	
	if (target == 1) then
		while (i < #table1) do
			i = i + 1;
			if (table1[i] == "Conviction" or table1[i] == "Strike" or table1[i] == "Tax Evasion" or table1[i] == "Eco Crime") then
				table.remove(table1,i);
				foundThreat = true;
				i = i - 1; -- remember this!
			end
		end
	
	elseif (target == 2) then
		while (i < #table2) do
			i = i + 1;
			if (table2[i] == "Conviction" or table2[i] == "Strike" or table2[i] == "Tax Evasion" or table2[i] == "Eco Crime") then
				table.remove(table2,i);
				foundThreat = true;
				i = i - 1; -- remember this!
			end
		end
	
	elseif (target == 3) then
		while (i < #table3) do
			i = i + 1;
			if (table3[i] == "Conviction" or table3[i] == "Strike" or table3[i] == "Tax Evasion" or table3[i] == "Eco Crime") then
				table.remove(table3,i);
				foundThreat = true;
				i = i - 1; -- remember this!
			end
		end
	
	elseif (target == 4) then
		while (i < #table4) do
			i = i + 1;
			if (table4[i] == "Conviction" or table4[i] == "Strike" or table4[i] == "Tax Evasion" or table4[i] == "Eco Crime") then
				table.remove(table4,i);
				foundThreat = true;
				i = i - 1; -- remember this!
			end
		end
	end
	
	if (foundThreat == false) then
		showMessage("Your company is not\nunder any threat.", errorColor);
		legalMove = false;
		return
	end
	playSound(soundPlayNewIdentityCard)
end

playSabotage = function(turn, target)
	
	if (checkTargetLegality(turn, target) == false) then
		legalMove = false;
		return;
	end
	
	if (target == 1) then
		local i = 0;
		
		while (i < #table1) do
			i = i + 1;
			-- Do not allow multiple threats if target is already under a thread.	
			if (userOptions[2] == "no" and (table1[i] == "Conviction" or table1[i] == "Strike" or table1[i] == "Tax Evasion" or table1[i] == "Eco Crime")) then
				showMessage("Player " .. target .. " is already under\na threat.", errorColor);
				legalMove = false;
				return
			else
				-- Remove all threats first
				if (table1[i] == "Conviction" or table1[i] == "Strike" or table1[i] == "Tax Evasion" or table1[i] == "Eco Crime") then
					table.remove(table1,i);
					i = i - 1;
				end
				
			end
		end
		
		-- Legal move
		if (userOptions[2] == "no") then
			-- Apply a random threat
			local threat = math.random(1,4)
			if (threat == 1) then
				table.insert(table1,"Conviction");
			elseif (threat == 2) then
				table.insert(table1,"Strike");
			elseif (threat == 3) then
				table.insert(table1,"Tax Evasion");
			else
				table.insert(table1,"Eco Crime");
			end
		else
			-- Apply all threats
			table.insert(table1,"Conviction");
			table.insert(table1,"Strike");
			table.insert(table1,"Tax Evasion");
			table.insert(table1,"Eco Crime");
		end
			
	elseif (target == 2) then
		local i = 0;
		
		while (i < #table2) do
			i = i + 1;
			-- Do not allow multiple threats if target is already under a thread.	
			if (userOptions[2] == "no" and (table2[i] == "Conviction" or table2[i] == "Strike" or table2[i] == "Tax Evasion" or table2[i] == "Eco Crime")) then
				showMessage("Player " .. target .. " is already under\na threat.", errorColor);
				legalMove = false;
				return
			else
				-- Remove all threats first
				if (table2[i] == "Conviction" or table2[i] == "Strike" or table2[i] == "Tax Evasion" or table2[i] == "Eco Crime") then
					table.remove(table2,i);
					i = i - 1;
				end
			end
		end
		
		-- Legal move
		if (userOptions[2] == "no") then
			-- Apply a random threat
			local threat = math.random(1,4)
			if (threat == 1) then
				table.insert(table2,"Conviction");
			elseif (threat == 2) then
				table.insert(table2,"Strike");
			elseif (threat == 3) then
				table.insert(table2,"Tax Evasion");
			else
				table.insert(table2,"Eco Crime");
			end
		else
			-- Apply all threats
			table.insert(table2,"Conviction");
			table.insert(table2,"Strike");
			table.insert(table2,"Tax Evasion");
			table.insert(table2,"Eco Crime");
		end
	elseif (target == 3) then
		local i = 0;
		
		while (i < #table3) do
			i = i + 1;
			-- Do not allow multiple threats if target is already under a thread.	
			if (userOptions[2] == "no" and (table3[i] == "Conviction" or table3[i] == "Strike" or table3[i] == "Tax Evasion" or table3[i] == "Eco Crime")) then
				showMessage("Player " .. target .. " is already under\na threat.", errorColor);
				legalMove = false;
				return
			else
				-- Remove all threats first
				if (table3[i] == "Conviction" or table3[i] == "Strike" or table3[i] == "Tax Evasion" or table3[i] == "Eco Crime") then
					table.remove(table3,i);
					i = i - 1;
				end
			end
		end
		
		-- Legal move
		if (userOptions[2] == "no") then
			-- Apply a random threat
			local threat = math.random(1,4)
			if (threat == 1) then
				table.insert(table3,"Conviction");
			elseif (threat == 2) then
				table.insert(table3,"Strike");
			elseif (threat == 3) then
				table.insert(table3,"Tax Evasion");
			else
				table.insert(table3,"Eco Crime");
			end
		else
			-- Apply all threats
			table.insert(table3,"Conviction");
			table.insert(table3,"Strike");
			table.insert(table3,"Tax Evasion");
			table.insert(table3,"Eco Crime");
		end
		
	elseif (target == 4) then
		local i = 0;
		
		while (i < #table4) do
			i = i + 1;
			-- Do not allow multiple threats if target is already under a thread.	
			if (userOptions[2] == "no" and (table4[i] == "Conviction" or table4[i] == "Strike" or table4[i] == "Tax Evasion" or table4[i] == "Eco Crime")) then
				showMessage("Player " .. target .. " is already under\na threat.", errorColor);
				legalMove = false;
				return
			else
				-- Remove all threats first
				if (table4[i] == "Conviction" or table4[i] == "Strike" or table4[i] == "Tax Evasion" or table4[i] == "Eco Crime") then
					table.remove(table4,i);
					i = i - 1;
				end
			end
		end
		
		-- Legal move
		if (userOptions[2] == "no") then
			-- Apply a random threat
			local threat = math.random(1,4)
			if (threat == 1) then
				table.insert(table4,"Conviction");
			elseif (threat == 2) then
				table.insert(table4,"Strike");
			elseif (threat == 3) then
				table.insert(table4,"Tax Evasion");
			else
				table.insert(table4,"Eco Crime");
			end
		else
			-- Apply all threats
			table.insert(table4,"Conviction");
			table.insert(table4,"Strike");
			table.insert(table4,"Tax Evasion");
			table.insert(table4,"Eco Crime");
		end
	end
	
	playSound(soundPlaySabotageCard)
end

playRotateTable = function()
	if (playersSize == 2) then
		table1, table2 = table2, table1
		company1, company2 = company2, company1
	elseif (playersSize == 3) then
		table1, table2, table3 = table3, table1, table2
		company1, company2, company3 = company3, company1, company2
	else
		table1, table2, table3, table4 = table4, table1, table2, table3
		company1, company2, company3, company4 = company4, company1, company2, company3
	end
	
	playSound(soundPlayRotateCard)
end

playRotateHands = function(turn, index)
				
	if (playersSize == 2) then
		
		-- order the cards in order that last card is nil / removed card is last.
		if (turn == 1) then
			hand1[index], hand1[7] = hand1[7], hand1[index]
			
			local i = 0
			while (i < 7) do
				i = i + 1;
				-- find nil card and put it last
				if (hand2[i] == nil) then
					hand2[i], hand2[7] = hand2[7], hand2[i]
					break;
				end
			end
		else
			hand2[index], hand2[7] = hand2[7], hand2[index]
			
			local i = 0
			while (i < 7) do
				i = i + 1;
				-- find nil card and put it last
				if (hand1[i] == nil) then
					hand1[i], hand1[7] = hand1[7], hand1[i]
					break;
				end
			end
		end
		
		-- switch hands
		hand1[1], hand2[1] = hand2[1], hand1[1]
		hand1[2], hand2[2] = hand2[2], hand1[2]
		hand1[3], hand2[3] = hand2[3], hand1[3]
		hand1[4], hand2[4] = hand2[4], hand1[4]
		hand1[5], hand2[5] = hand2[5], hand1[5]
		hand1[6], hand2[6] = hand2[6], hand1[6]
		
		-- Switch card to be removed back to its original place
		if (turn == 1) then
			hand1[index], hand1[7] = hand1[7], hand1[index]
		else
			hand2[index], hand2[7] = hand2[7], hand2[index]
		end
		
	elseif (playersSize == 3) then
	
		-- order the cards in order that last card is nil / removed card is last.
		if (turn == 1) then
			hand1[index], hand1[7] = hand1[7], hand1[index]
			
			local i = 0
			while (i < 7) do
				i = i + 1;
				-- find nil card and put it last
				if (hand2[i] == nil) then
					hand2[i], hand2[7] = hand2[7], hand2[i]
					break;
				end
			end
			
			local i = 0
			while (i < 7) do
				i = i + 1;
				-- find nil card and put it last
				if (hand3[i] == nil) then
					hand3[i], hand3[7] = hand3[7], hand3[i]
					break;
				end
			end
		elseif (turn == 2) then
			hand2[index], hand2[7] = hand2[7], hand2[index]
			
			local i = 0
			while (i < 7) do
				i = i + 1;
				-- find nil card and put it last
				if (hand1[i] == nil) then
					hand1[i], hand1[7] = hand1[7], hand1[i]
					break;
				end
			end
			
			local i = 0
			while (i < 7) do
				i = i + 1;
				-- find nil card and put it last
				if (hand3[i] == nil) then
					hand3[i], hand3[7] = hand3[7], hand3[i]
					break;
				end
			end
		else
			-- turn = 3
			hand3[index], hand3[7] = hand3[7], hand3[index]
			
			local i = 0
			while (i < 7) do
				i = i + 1;
				-- find nil card and put it last
				if (hand1[i] == nil) then
					hand1[i], hand1[7] = hand1[7], hand1[i]
					break;
				end
			end
			
			local i = 0
			while (i < 7) do
				i = i + 1;
				-- find nil card and put it last
				if (hand2[i] == nil) then
					hand2[i], hand2[7] = hand2[7], hand2[i]
					break;
				end
			end
		end
		
		-- Switch hands
		hand1[1], hand2[1], hand3[1] = hand3[1], hand1[1], hand2[1]
		hand1[2], hand2[2], hand3[2] = hand3[2], hand1[2], hand2[2]
		hand1[3], hand2[3], hand3[3] = hand3[3], hand1[3], hand2[3]
		hand1[4], hand2[4], hand3[4] = hand3[4], hand1[4], hand2[4]
		hand1[5], hand2[5], hand3[5] = hand3[5], hand1[5], hand2[5]
		hand1[6], hand2[6], hand3[6] = hand3[6], hand1[6], hand2[6]
		
		-- Removed card back to its original place
		if (turn == 1) then
			hand1[index], hand1[7] = hand1[7], hand1[index]
		elseif (turn == 2) then
			hand2[index], hand2[7] = hand2[7], hand2[index]
		else
			hand3[index], hand3[7] = hand3[7], hand3[index]
		end
		
	else
		-- 4 player mode
		-- order the cards in order that last card is nil / removed card is last.
		if (turn == 1) then
			hand1[index], hand1[7] = hand1[7], hand1[index]
			
			local i = 0
			while (i < 7) do
				i = i + 1;
				-- find nil card and put it last
				if (hand2[i] == nil) then
					hand2[i], hand2[7] = hand2[7], hand2[i]
					break;
				end
			end
			
			local i = 0
			while (i < 7) do
				i = i + 1;
				-- find nil card and put it last
				if (hand3[i] == nil) then
					hand3[i], hand3[7] = hand3[7], hand3[i]
					break;
				end
			end
			
			local i = 0
			while (i < 7) do
				i = i + 1;
				-- find nil card and put it last
				if (hand4[i] == nil) then
					hand4[i], hand4[7] = hand4[7], hand4[i]
					break;
				end
			end
		elseif (turn == 2) then
			hand2[index], hand2[7] = hand2[7], hand2[index]
			
			local i = 0
			while (i < 7) do
				i = i + 1;
				-- find nil card and put it last
				if (hand1[i] == nil) then
					hand1[i], hand1[7] = hand1[7], hand1[i]
					break;
				end
			end
			
			local i = 0
			while (i < 7) do
				i = i + 1;
				-- find nil card and put it last
				if (hand3[i] == nil) then
					hand3[i], hand3[7] = hand3[7], hand3[i]
					break;
				end
			end
			
			local i = 0
			while (i < 7) do
				i = i + 1;
				-- find nil card and put it last
				if (hand4[i] == nil) then
					hand4[i], hand4[7] = hand4[7], hand4[i]
					break;
				end
			end
		elseif (turn == 3) then
			hand3[index], hand3[7] = hand3[7], hand3[index]
			
			local i = 0
			while (i < 7) do
				i = i + 1;
				-- find nil card and put it last
				if (hand1[i] == nil) then
					hand1[i], hand1[7] = hand1[7], hand1[i]
					break;
				end
			end
			
			local i = 0
			while (i < 7) do
				i = i + 1;
				-- find nil card and put it last
				if (hand2[i] == nil) then
					hand2[i], hand2[7] = hand2[7], hand2[i]
					break;
				end
			end
			
			local i = 0
			while (i < 7) do
				i = i + 1;
				-- find nil card and put it last
				if (hand4[i] == nil) then
					hand4[i], hand4[7] = hand4[7], hand4[i]
					break;
				end
			end
		else
			-- turn = 4
			hand4[index], hand4[7] = hand4[7], hand4[index]
			
			local i = 0
			while (i < 7) do
				i = i + 1;
				-- find nil card and put it last
				if (hand1[i] == nil) then
					hand1[i], hand1[7] = hand1[7], hand1[i]
					break;
				end
			end
			
			local i = 0
			while (i < 7) do
				i = i + 1;
				-- find nil card and put it last
				if (hand2[i] == nil) then
					hand2[i], hand2[7] = hand2[7], hand2[i]
					break;
				end
			end
			
			local i = 0
			while (i < 7) do
				i = i + 1;
				-- find nil card and put it last
				if (hand3[i] == nil) then
					hand3[i], hand3[7] = hand3[7], hand3[i]
					break;
				end
			end
		end
	
		-- Switch hands
		hand1[1], hand2[1], hand3[1], hand4[1] = hand4[1], hand1[1], hand2[1], hand3[1]
		hand1[2], hand2[2], hand3[2], hand4[2] = hand4[2], hand1[2], hand2[2], hand3[2]
		hand1[3], hand2[3], hand3[3], hand4[3] = hand4[3], hand1[3], hand2[3], hand3[3]
		hand1[4], hand2[4], hand3[4], hand4[4] = hand4[4], hand1[4], hand2[4], hand3[4]
		hand1[5], hand2[5], hand3[5], hand4[5] = hand4[5], hand1[5], hand2[5], hand3[5]
		hand1[6], hand2[6], hand3[6], hand4[6] = hand4[6], hand1[6], hand2[6], hand3[6]
		
		-- Removed card back to its original place
		if (turn == 1) then
			hand1[index], hand1[7] = hand1[7], hand1[index]
		elseif (turn == 2) then
			hand2[index], hand2[7] = hand2[7], hand2[index]
		elseif (turn == 3) then
			hand3[index], hand3[7] = hand3[7], hand3[index]
		else
			hand4[index], hand4[7] = hand4[7], hand4[index]
		end
	end
	
	playSound(soundPlayRotateCard)
end

playCard = function(turn, cardName, index, target)
	
	legalMove = true; -- assume everything goes right
	
	if (cardName == "Open Company") then
		playOpenCompany(turn, target)
	elseif (cardName == "$15000") then
		playMoneyCard(turn, target, cardName)
	elseif (cardName == "$25000") then
		playMoneyCard(turn, target, cardName)
	elseif (cardName == "$50000") then
		playMoneyCard(turn, target, cardName)
	elseif (cardName == "$100000") then
		playMoneyCard(turn, target, cardName)
	elseif (cardName == "Sell Company") then
		playSellCompany(turn, target)	
	elseif (cardName == "Thief") then
		playThief(turn, target)
	elseif (cardName == "Small Safe") then
		playSmallSafe(turn, target)
	elseif (cardName == "Big Safe") then
		playBigSafe(turn, target)
	elseif (cardName == "Conviction") then
		playConviction(turn, target);
	elseif (cardName == "Remove Conviction") then
		playRemoveConviction(target);
	elseif (cardName == "Tax Evasion") then
		playTaxEvasion(turn, target);
	elseif (cardName == "Remove Tax Evasion") then
		playRemoveTaxEvasion(target);	
	elseif (cardName == "Strike") then
		playStrike(turn, target);
	elseif (cardName == "Remove Strike") then
		playRemoveStrike(target);	
	elseif (cardName == "Eco Crime") then
		playEcoCrime(turn, target);
	elseif (cardName == "Remove Eco Crime") then
		playRemoveEcoCrime(target);	
	elseif (cardName == "Bribe") then
		playBribe(turn, target);
	elseif (cardName == "Bankruptcy") then
		playBankruptcy(turn, target);
	elseif (cardName == "Deal") then
		playDeal(turn, target, index)
	elseif (cardName == "New Beginning") then
		playNewBeginning(turn, target, index);
	elseif (cardName == "Robbery") then
		playRobbery(turn, target, false)
	elseif (cardName == "Luck") then
		playLuck(turn, target);
	elseif (cardName == "Banker") then
		playBanker();
	elseif (cardName == "Rotate Table") then
		playRotateTable();
	elseif (cardName == "Rotate Hands") then
		playRotateHands(turn, index);
	elseif (cardName == "New Identity") then
		playNewIdentity(turn, target);
	elseif (cardName == "Sabotage") then
		playSabotage(turn, target);
	else
		-- card is unknown
		legalMove = false;
		showMessage("Unknown card is tried to be played.", errorColor);
	end
	
	if (legalMove) then
		if (turn == 1) then
			showMessage("Player" .. turn .. " plays card\n" .. hand1[index] .. "\n\nTarget: Player" .. target, playColor, hand1[index])
			numberOfUsedCards = numberOfUsedCards + 1;
			usedCards[#usedCards + 1] = hand1[index];
			hand1[index] = nil;
		elseif (turn == 2) then
			showMessage("Player" .. turn .. " plays card\n" .. hand2[index] .. "\n\nTarget: Player" .. target, playColor, hand2[index])
			numberOfUsedCards = numberOfUsedCards + 1;
			usedCards[#usedCards + 1] = hand2[index];
			hand2[index] = nil;
		elseif (turn == 3) then
			showMessage("Player" .. turn .. " plays card\n" .. hand3[index] .. "\n\nTarget: Player" .. target, playColor, hand3[index])
			numberOfUsedCards = numberOfUsedCards + 1;
			usedCards[#usedCards + 1] = hand3[index];
			hand3[index] = nil;
		elseif (turn == 4) then
			showMessage("Player" .. turn .. " plays card\n" .. hand4[index] .. "\n\nTarget: Player" .. target, playColor, hand4[index])
			numberOfUsedCards = numberOfUsedCards + 1;
			usedCards[#usedCards + 1] = hand4[index];
			hand4[index] = nil;
		end
	end
	
	if (cardName == "Luck") then
		return true;
	end
	
	return false; -- no new turn
	
end

getCompanyMoneys = function()

local i = 0;
local money15000 = 0;
local money25000 = 0;
local money50000 = 0;
local money100000 = 0;

	while (i < #company1) do
		i = i + 1;
		if (company1[i] == "$15000") then
			money15000 = money15000 + 1;
		elseif (company1[i] == "$25000") then
			money25000 = money25000 + 1;
		elseif (company1[i] == "$50000") then
			money50000 = money50000 + 1;
		elseif (company1[i] == "$100000") then
			money100000 = money100000 + 1;
		end
	end
	
	local comp1 = "Player1 \n$15000 x " .. money15000 .. "\n" .. "$25000 x " .. money25000 .. "\n" .. "$50000 x " .. money50000 .. "\n" .. "$100000 x " .. money100000 .. "\n"
	
	i = 0;
	money15000 = 0;
	money25000 = 0;
	money50000 = 0;
	money100000 = 0;
	
	while (i < #company2) do
		i = i + 1;
		if (company2[i] == "$15000") then
			money15000 = money15000 + 1;
		elseif (company2[i] == "$25000") then
			money25000 = money25000 + 1;
		elseif (company2[i] == "$50000") then
			money50000 = money50000 + 1;
		elseif (company2[i] == "$100000") then
			money100000 = money100000 + 1;
		end
	end
	
	local comp2 = "Player2 \n$15000 x " .. money15000 .. "\n" .. "$25000 x " .. money25000 .. "\n" .. "$50000 x " .. money50000 .. "\n" .. "$100000 x " .. money100000 .. "\n"

	i = 0;
	money15000 = 0;
	money25000 = 0;
	money50000 = 0;
	money100000 = 0;
	
	while (i < #company3) do
		i = i + 1;
		if (company3[i] == "$15000") then
			money15000 = money15000 + 1;
		elseif (company3[i] == "$25000") then
			money25000 = money25000 + 1;
		elseif (company3[i] == "$50000") then
			money50000 = money50000 + 1;
		elseif (company3[i] == "$100000") then
			money100000 = money100000 + 1;
		end
	end
	
	local comp3 = "Player3 \n$15000 x " .. money15000 .. "\n" .. "$25000 x " .. money25000 .. "\n" .. "$50000 x " .. money50000 .. "\n" .. "$100000 x " .. money100000 .. "\n"
	
	
	i = 0;
	money15000 = 0;
	money25000 = 0;
	money50000 = 0;
	money100000 = 0;
	
	while (i < #company4) do
		i = i + 1;
		if (company4[i] == "$15000") then
			money15000 = money15000 + 1;
		elseif (company4[i] == "$25000") then
			money25000 = money25000 + 1;
		elseif (company4[i] == "$50000") then
			money50000 = money50000 + 1;
		elseif (company4[i] == "$100000") then
			money100000 = money100000 + 1;
		end
	end
	
	local comp4 = "Player4 \n$15000 x " .. money15000 .. "\n" .. "$25000 x " .. money25000 .. "\n" .. "$50000 x " .. money50000 .. "\n" .. "$100000 x " .. money100000 .. "\n"
	
	return comp1, comp2, comp3, comp4
	
end

showCompany = function(selectorX)
	local levelY = 1;
	local levelX = 1;
	local target = 1;
	
	local comp1, comp2, comp3, comp4 = getCompanyMoneys()

	while true do
	
		image.blit(0, 0, background);
		
		screen.print(35, 10 - yDifference, #deck - deckIndex + 1 .. " / " .. #deck, 0.6, blue, shadowColor, "left");
		showHands();
		showTable();
		showTargets();
		showMoney();
		
		image.blit(90 + selectorX, 254, selector2);
	
		if (target == 1) then
			image.blit(208, 135, targeter)
			showCompanyBox(comp1)
		elseif (target == 2) then
			image.blit(208, 110, targeter)
			showCompanyBox(comp2)
		elseif (target == 3) then
			image.blit(235, 110, targeter)
			showCompanyBox(comp3)
		else
			image.blit(235,135,targeter)
			showCompanyBox(comp4)
		end
	
		controls.read()

			if controls.press("r") then
				changeStyle(1);
			elseif controls.press("l") then
				changeStyle(-1);
			elseif controls.press("circle") then
				break;
			elseif controls.press("down") or controls.analogy() == 127 + waitAnalog then
				waitAnalog = 0.2
				waitMoment = os.clock()
				if (target == 1) then
					break;
				elseif (target == 2) then
					target = 1;
				elseif (target == 3) then
					target = 4;
				elseif (target == 4) then
					break;
				end
				
			elseif controls.press("up") or controls.analogy() == -128 - waitAnalog then
				waitAnalog = 0.2
				waitMoment = os.clock()
				if (target == 1) then
					target = 2;
				elseif (target == 2) then
					target = 1;
				elseif (target == 3) then
					target = 4;
				elseif (target == 4) then
					target = 3;
				end
				
			elseif controls.press("left") or controls.analogx() == -128 - waitAnalog then
				waitAnalog = 0.2
				waitMoment = os.clock()
				if (target == 1) then
					target = 4;
				elseif (target == 2) then
					target = 3;
				elseif (target == 3) then
					target = 2;
				elseif (target == 4) then
					target = 1;
				end
				
			elseif controls.press("right") or controls.analogx() == 127 + waitAnalog then
				waitAnalog = 0.2
				waitMoment = os.clock()
				if (target == 1) then
					target = 4;
				elseif (target == 2) then
					target = 3;
				elseif (target == 3) then
					target = 2;
				elseif (target == 4) then
					target = 1;
				end
			end
			screen.flip();
			if (os.clock() - waitMoment >= waitAnalog) then
				waitAnalog = 0;
			end
	end
end

-- GAME
start = function(iniFileName)

	loadCards(iniFileName);
	usedCards = {}
	numberOfUsedCards = 1;
	updatedConsecutiveWinnings = false;
	
	playersSize = tonumber(userOptions[1])
	sellCompanyMin = tonumber(string.sub(userOptions[4], 2));
	setDifficulty();
	shuffle();
	
	gameEnds = false;
	
	deckIndex = 1;
	-- hand cards
	hand1 = {}
	hand2 = {}
	hand3 = {}
	hand4 = {}
	-- table cards
	table1 = {}
	table2 = {}
	table3 = {}
	table4 = {}
	-- company cards
	company1 = {}
	company2 = {}
	company3 = {}
	company4 = {}
	-- bank account
	bank1 = 0;
	bank2 = 0;
	bank3 = 0;
	bank4 = 0;
	
	showText = false;
	legalMove = false;
	local waitTriangle = false;
	local waitStart = false;
	local selectorX = 0;
	local selection = 1;
	
	doDiscardCard = false; -- necessary to know due to waitTriangle loop
	doPlayCard = false;
	
	cheater = false; -- assume the player plays the game honestly
	
	-- deal special hand in story mode
	if (playMode == "story" and currentStage == 1) then
		-- deal both players Open Company from the deck in the beginning hand
		dealCard("Open Company", 1)
		dealCard("Open Company", 2)
	elseif (playMode == "story" and currentStage == 3) then
		dealCard("Open Company", 1)
		dealCard("Open Company", 2)
		dealCard("Open Company", 3)
		dealCard("Open Company", 4)
	elseif (playMode == "story" and currentStage == 4) then
		dealCard("Open Company", 1)
		dealCard("Open Company", 2)
		dealCard("Open Company", 3)
		dealCard("Open Company", 4)
		dealCard("Rotate Table", 3)
	elseif (playMode == "story" and currentStage == 6) then
		dealCard("Open Company", 1)
		dealCard("Open Company", 4)
		dealCard("Sabotage", 4)
	elseif (playMode == "story" and currentStage == 7) then
		dealCard("Open Company", 1)
		dealCard("Open Company", 2)
		dealCard("Open Company", 3)
		dealCard("Open Company", 4)
		dealCard("Rotate Table", 2)
		dealCard("Rotate Hands", 3)
		dealCard("Sabotage", 4)
	end
	
	deal();
	
	local turn = math.random(1,playersSize)
	phase = 0; -- 1 draw, 2 play, 3 end
	
	while true do
		
		image.blit(0, 0, background);
	
		--screen.print(380, 10, #deck - deckIndex + 1 .. " / " .. #deck);
		screen.print(35, 10 - yDifference, #deck - deckIndex + 1 .. " / " .. #deck, 0.6, blue, shadowColor, "left");
		
		showHands();
		showTable();
		showTargets();
		showMoney();
		
		if (phase == 0) then
			showMessage("Player " .. turn .. " starts the game.");
			phase = 1;
		elseif (phase == 1) then
			-- DRAWING CARD
			drawCard(turn, false);
			phase = 2;
		elseif (phase == 2 and turn ~= 1) then
			-- PLAYING CARD BY CPU
			local playCardIndex, playCardTarget = cpu(turn); -- Define what card to be played, call play card, if luck check return value
			local newTurn = false; -- assume no luck is played
			
			if (playCardTarget == 0) then
				discardCard(turn, playCardIndex) -- discard card if return [1-7], 0
			else
				-- play card if return [1-7], [1-4]
				if (turn == 2) then
					newTurn = playCard(turn, hand2[playCardIndex], playCardIndex, playCardTarget) --turn, cardName, card index in hand, target number
				elseif (turn == 3) then
					newTurn = playCard(turn, hand3[playCardIndex], playCardIndex, playCardTarget)
				elseif (turn == 4) then
					newTurn = playCard(turn, hand4[playCardIndex], playCardIndex, playCardTarget)
				end
			end
			
			phase = 3;
			
			-- However, if the card was luck, new turn
			if (newTurn) then
				phase = 1;
			end
			
		elseif (phase == 3) then
			-- CHANGING TURN
			turn = turn + 1;
			if (turn > playersSize) then
				turn = 1;
			end
			phase = 1;
			legalMove = false;
		end
		
		controls.read()

		if controls.press("r") then
			changeStyle(1);
		elseif controls.press("l") then
			changeStyle(-1);
		elseif controls.press("triangle") and turn == 1 then -- show big image of current card
			waitTriangle = true;
		elseif controls.press("select") and turn == 1 then
			returnMenu()
		elseif controls.press("start") and turn == 1 then
			waitStart = true;
		elseif controls.press("left") or controls.analogx() == -128 - waitAnalog and turn == 1 then
			waitAnalog = 0.2
			waitMoment = os.clock()
			selectorX = selectorX - 40;
			selection = selection - 1;
			if (selection < 1) then
				selectorX = 240;
				selection = 7;
			end
		elseif controls.press("right") or controls.analogx() == 127 + waitAnalog and turn == 1 then
			waitAnalog = 0.2
			waitMoment = os.clock()
			selectorX = selectorX + 40;
			selection = selection + 1;
			if (selection > 7) then
				selectorX = 0;
				selection = 1;
			end
		elseif controls.press("up") or controls.analogy() == -128 - waitAnalog and turn == 1 then
			waitAnalog = 0.2
			waitMoment = os.clock()
			showCompany(selectorX)
		elseif (controls.press("square") or doDiscardCard) and turn == 1 and hand1[selection] ~= nil then
			--discard
			doDiscardCard = false;
			discardCard(1, selection)
			if (legalMove) then
				legalMove = false;
				phase = 3;
			end
		elseif (controls.press("cross") or doPlayCard) and turn == 1 and hand1[selection] ~= nil then
			--play card
			doPlayCard = false;
			local target = chooseTarget(selection, selectorX);
			
			if (target ~= 0 and target ~= nil) then
				local newTurn = playCard(1, hand1[selection], selection, target)
			
				if (legalMove) then
					legalMove = false;
					phase = 3;
					
					-- However, if the card was luck, new turn
					if (newTurn) then
						phase = 1;
					end
				end
			end
		end
		
		if (os.clock() - waitMoment >= waitAnalog) then
			waitAnalog = 0;
		end
		
		-- Selector
		image.blit(90 + selectorX, 254, selector2);
		screen.flip()
		
		if (showText) then
		
			local starttime = os.clock()
			while os.clock() - starttime < waitSeconds do -- wait seconds or press
				controls.read()
		
				if (controls.press("cross") or controls.press("triangle") or controls.press("circle") or controls.press("square") or controls.press("up") or controls.analogy() == -128 - waitAnalog or controls.press("down") or controls.analogy() == 127 + waitAnalog or controls.press("left") or controls.analogx() == -128 - waitAnalog or controls.press("right") or controls.analogx() == 127 + waitAnalog) then
					break;
				end
			end
			showText = false;
		end
		
		while (waitStart and turn == 1) do
			
			image.blit(0, 0, background);
			
			--screen.print(380, 10, #deck - deckIndex + 1 .. " / " .. #deck);
			screen.print(35, 10 - yDifference, #deck - deckIndex + 1 .. " / " .. #deck, 0.6, blue, shadowColor, "left");
			showHands();
			showTable();
			showTargets();
			showMoney();
			image.blit(90 + selectorX, 254, selector2);
			image.blit(28,23, keys);
			
			screen.print(50, 40, "( R / L - Change Style )", 0.6, white, shadowColor, "left");
			screen.print(50, 60, "Cross - Play Card", 0.6, white, shadowColor, "left");
			screen.print(50, 80, "Square - Discard Card", 0.6, white, shadowColor, "left");
			screen.print(50, 100, "Triangle - Zoom Card", 0.6, white, shadowColor, "left");
			screen.print(50, 120, "Circle - Cancel Selection", 0.6, white, shadowColor, "left");
			screen.print(50, 140, "SELECT - Return to Menu", 0.6, white, shadowColor, "left");
			screen.print(50, 160, "START - Show keys", 0.6, white, shadowColor, "left");
			screen.print(50, 180, "HOME - Quit", 0.6, white, shadowColor, "left");
			screen.print(50, 200, "Left / Right / Up / Down - Select", 0.6, white, shadowColor, "left");
			
			screen.flip()
			
			controls.read()
			
			if controls.press("r") then
				changeStyle(1);
			elseif controls.press("l") then
				changeStyle(-1);
			elseif controls.press("start") then			
				waitStart = false;
				break;
			elseif controls.press("select") then
				returnMenu()
			end
		end
		
		while (waitTriangle and hand1[selection] ~= nil and turn == 1) do
			image.blit(0, 0, background);
			
			--screen.print(380, 10, #deck - deckIndex + 1 .. " / " .. #deck);
			screen.print(35, 10 - yDifference, #deck - deckIndex + 1 .. " / " .. #deck, 0.6, blue, shadowColor, "left");
			showHands();
			showTable();
			showTargets();
			showMoney();
			checkCurrentCard(hand1[selection], "big");
			--image.blit(30, 3, currentCard);
			image.blit(270, 3, currentCard);
			image.blit(90 + selectorX, 254, selector2);
			
			if (waitStart) then
				image.blit(28,23, keys);
				
				screen.print(50, 40, "( R / L - Change Style )", 0.6, white, shadowColor, "left");
				screen.print(50, 60, "Cross - Play Card", 0.6, white, shadowColor, "left");
				screen.print(50, 80, "Square - Discard Card", 0.6, white, shadowColor, "left");
				screen.print(50, 100, "Triangle - Zoom Card", 0.6, white, shadowColor, "left");
				screen.print(50, 120, "Circle - Cancel Selection", 0.6, white, shadowColor, "left");
				screen.print(50, 140, "SELECT - Return to Menu", 0.6, white, shadowColor, "left");
				screen.print(50, 160, "START - Show keys", 0.6, white, shadowColor, "left");
				screen.print(50, 180, "HOME - Quit", 0.6, white, shadowColor, "left");
				screen.print(50, 200, "Left / Right / Up / Down - Select", 0.6, white, shadowColor, "left");
			end
		
			screen.flip()
		
			controls.read()
			
			-- cheat
			if controls.r() and controls.l() and controls.up() and waitStart then
				cheater = true;
				bank1 = bank1 + 200000;
				deck = {};
			elseif controls.r() and controls.l() and controls.down() and waitStart then
				cheater = true;
				bank2 = bank2 + 200000;
				deck = {};
			elseif controls.r() and controls.l() and controls.right() then
				cheater = true;
				showCurrentHands()
			elseif controls.press("r") then
				changeStyle(1);
			elseif controls.press("l") then
				changeStyle(-1);
			elseif controls.press("start") then
				if (waitStart == false) then
					waitStart = true;
				else
					waitStart = false
				end
				
			elseif controls.press("select") then
				returnMenu()
			elseif controls.press("triangle") and waitStart == false then -- show big image of current card
				waitTriangle = false;
			elseif controls.press("left") or controls.analogx() == -128 - waitAnalog and waitStart == false then
				waitAnalog = 0.2
				waitMoment = os.clock()
				selectorX = selectorX - 40;
				selection = selection - 1;
				if (selection < 1) then
					selectorX = 240;
					selection = 7;
				end
				
			elseif controls.press("right") or controls.analogx() == 127 + waitAnalog and waitStart == false then
				waitAnalog = 0.2
				waitMoment = os.clock()
				selectorX = selectorX + 40;
				selection = selection + 1;
				if (selection > 7) then
					selectorX = 0;
					selection = 1;
				end
				
			elseif controls.press("up") or controls.analogy() == -128 - waitAnalog and waitStart == false then
				waitAnalog = 0.2
				waitMoment = os.clock()
				showCompany(selectorX)
			elseif controls.press("square") and waitStart == false and hand1[selection] ~= nil then
			--discard
			doDiscardCard = true;
			break;
			elseif controls.press("cross") and waitStart == false and hand1[selection] ~= nil then
			--play card
			doPlayCard = true;
			break;
			end
			
			if (os.clock() - waitMoment >= waitAnalog) then
				waitAnalog = 0;
			end
			
		end
	end
end

getIniCardList = function()
	local file = io.open("cards.ini", "r");
	local cardList = {};
	
	if (file == nil ) then
		-- ini file was not found, quit
		
		screen.print(240, 150 - yDifference, "Cards.ini file not found.", 0.8, blue, shadowColor, "center");
		
		screen.flip()
		screen.waitvblankstart(150);
		os.quit();
	end
	
	for line in file:lines() do

		local item = line:splitCards("[^;]+");
		local numberOfSameCard = tonumber(item[2]);
		
		if (numberOfSameCard < 0) then -- limit added 7.4.2011
			numberOfSameCard = 0;
		elseif (numberOfSameCard > 40) then
				numberOfSameCard = 40;
		end
		
		cardList[#cardList + 1] = numberOfSameCard;
		
	end
	
	file:close()
	return cardList;
end

getDefaultCardList = function()
	return {12, 8, 8, 6, 1, 4, 6, 5, 5, 3, 4, 3, 4, 3, 4, 3, 4, 4, 2, 2, 2, 4, 2, 1, 0, 0, 0, 0}
end

saveCardList = function(cardNumbers)
	local cardFile = "cards.ini";
	file = io.open(cardFile,"w")
				
	file:write("Open Company;" .. cardNumbers[1] .. "\n");
	file:write("$15000;" .. cardNumbers[2] .. "\n");
	file:write("$25000;" .. cardNumbers[3] .. "\n");
	file:write("$50000;" .. cardNumbers[4] .. "\n");
	file:write("$100000;" .. cardNumbers[5] .. "\n");
	file:write("Sell Company;" .. cardNumbers[6] .. "\n");
	file:write("Thief;" .. cardNumbers[7] .. "\n");
	file:write("Small Safe;" .. cardNumbers[8] .. "\n");
	file:write("Big Safe;" .. cardNumbers[9] .. "\n");
	file:write("Conviction;" .. cardNumbers[10] .. "\n");
	file:write("Remove Conviction;" .. cardNumbers[11] .. "\n");
	file:write("Tax Evasion;" .. cardNumbers[12] .. "\n");
	file:write("Remove Tax Evasion;" .. cardNumbers[13] .. "\n");
	file:write("Strike;" .. cardNumbers[14] .. "\n");
	file:write("Remove Strike;" .. cardNumbers[15] .. "\n");
	file:write("Eco Crime;" .. cardNumbers[16] .. "\n");
	file:write("Remove Eco Crime;" .. cardNumbers[17] .. "\n");
	file:write("Bribe;" .. cardNumbers[18] .. "\n");
	file:write("Bankruptcy;" .. cardNumbers[19] .. "\n");
	file:write("Deal;" .. cardNumbers[20] .. "\n");
	file:write("New Beginning;" .. cardNumbers[21] .. "\n");
	file:write("Robbery;" .. cardNumbers[22] .. "\n");
	file:write("Luck;" .. cardNumbers[23] .. "\n");
	file:write("Banker;" .. cardNumbers[24] .. "\n");
	file:write("Rotate Table;" .. cardNumbers[25] .. "\n");
	file:write("Rotate Hands;" .. cardNumbers[26] .. "\n");
	file:write("New Identity;" .. cardNumbers[27] .. "\n");
	file:write("Sabotage;" .. cardNumbers[28]);
	
	file:close();
end

getCardNameFromCardList = function(selection)

	if (selection == 1) then
		return "Open Company";
	elseif (selection == 2) then
		return "$15000";
	elseif (selection == 3) then
		return "$25000";
	elseif (selection == 4) then
		return "$50000";
	elseif (selection == 5) then
		return "$100000";
	elseif (selection == 6) then
		return "Sell Company";
	elseif (selection == 7) then
		return "Thief";
	elseif (selection == 8) then
		return "Small Safe";
	elseif (selection == 9) then
		return "Big Safe";
	elseif (selection == 10) then
		return "Conviction";
	elseif (selection == 11) then
		return "Remove Conviction";
	elseif (selection == 12) then
		return "Tax Evasion";
	elseif (selection == 13) then
		return "Remove Tax Evasion";
	elseif (selection == 14) then
		return "Strike";
	elseif (selection == 15) then
		return "Remove Strike";
	elseif (selection == 16) then
		return "Eco Crime";
	elseif (selection == 17) then
		return "Remove Eco Crime";
	elseif (selection == 18) then
		return "Bribe";
	elseif (selection == 19) then
		return "Bankruptcy";
	elseif (selection == 20) then
		return "Deal";
	elseif (selection == 21) then
		return "New Beginning";
	elseif (selection == 22) then
		return "Robbery";
	elseif (selection == 23) then
		return "Luck";
	elseif (selection == 24) then
		return "Banker";
	elseif (selection == 25) then
		return "Rotate Table"
	elseif (selection == 26) then
		return "Rotate Hands"
	elseif (selection == 27) then
		return "New Identity"
	elseif (selection == 28) then
		return "Sabotage";
	end
end

showCardList = function()
	
	local selectorY = 0;
	local selectorX = 0;
	local selection = 1;
	local waitTriangle = false;
	local cardNumbers = getIniCardList();
	
	while true do
		
		image.blit(0, 0, cardList);
		image.blit(2 + selectorX, 52 + selectorY, selector3);
		
		screen.print(20, 64 - yDifference, "Open Company", 0.6, white, shadowColor, "left");
		screen.print(20, 74 - yDifference, "$15000", 0.6, white, shadowColor, "left");
		screen.print(20, 84 - yDifference, "$25000", 0.6, white, shadowColor, "left");
		screen.print(20, 94 - yDifference, "$50000", 0.6, white, shadowColor, "left");
		screen.print(20, 104 - yDifference, "$100000", 0.6, white, shadowColor, "left");
		screen.print(20, 114 - yDifference, "Sell Company", 0.6, white, shadowColor, "left");
		screen.print(20, 124 - yDifference, "Thief", 0.6, white, shadowColor, "left");
		screen.print(20, 134 - yDifference, "Small Safe", 0.6, white, shadowColor, "left");
		screen.print(20, 144 - yDifference, "Big Safe", 0.6, white, shadowColor, "left");
		screen.print(20, 154 - yDifference, "Conviction", 0.6, white, shadowColor, "left");
		screen.print(20, 164 - yDifference, "Remove Conviction", 0.6, white, shadowColor, "left");
		screen.print(20, 174 - yDifference, "Tax Evasion", 0.6, white, shadowColor, "left");
		screen.print(20, 184 - yDifference, "Remove Tax Evasion", 0.6, white, shadowColor, "left");
		screen.print(20, 194 - yDifference, "Strike", 0.6, white, shadowColor, "left");
		
		screen.print(150, 64 - yDifference, "< " .. cardNumbers[1] .. " >", 0.6, white, shadowColor, "left");
		screen.print(150, 74 - yDifference, "< " .. cardNumbers[2] .. " >", 0.6, white, shadowColor, "left");
		screen.print(150, 84 - yDifference, "< " .. cardNumbers[3] .. " >", 0.6, white, shadowColor, "left");
		screen.print(150, 94 - yDifference, "< " .. cardNumbers[4] .. " >", 0.6, white, shadowColor, "left");
		screen.print(150, 104 - yDifference, "< " .. cardNumbers[5] .. " >", 0.6, white, shadowColor, "left");
		screen.print(150, 114 - yDifference, "< " .. cardNumbers[6] .. " >", 0.6, white, shadowColor, "left");
		screen.print(150, 124 - yDifference, "< " .. cardNumbers[7] .. " >", 0.6, white, shadowColor, "left");
		screen.print(150, 134 - yDifference, "< " .. cardNumbers[8] .. " >", 0.6, white, shadowColor, "left");
		screen.print(150, 144 - yDifference, "< " .. cardNumbers[9] .. " >", 0.6, white, shadowColor, "left");
		screen.print(150, 154 - yDifference, "< " .. cardNumbers[10] .. " >", 0.6, white, shadowColor, "left");
		screen.print(150, 164 - yDifference, "< " .. cardNumbers[11] .. " >", 0.6, white, shadowColor, "left");
		screen.print(150, 174 - yDifference, "< " .. cardNumbers[12] .. " >", 0.6, white, shadowColor, "left");
		screen.print(150, 184 - yDifference, "< " .. cardNumbers[13] .. " >", 0.6, white, shadowColor, "left");
		screen.print(150, 194 - yDifference, "< " .. cardNumbers[14] .. " >", 0.6, white, shadowColor, "left");
		
		screen.print(205, 64 - yDifference, "Remove Strike", 0.6, white, shadowColor, "left");
		screen.print(205, 74 - yDifference, "Eco Crime", 0.6, white, shadowColor, "left");
		screen.print(205, 84 - yDifference, "Remove Eco Crime", 0.6, white, shadowColor, "left");
		screen.print(205, 94 - yDifference, "Bribe", 0.6, white, shadowColor, "left");
		screen.print(205, 104 - yDifference, "Bankruptcy", 0.6, white, shadowColor, "left");
		screen.print(205, 114 - yDifference, "Deal", 0.6, white, shadowColor, "left");
		screen.print(205, 124 - yDifference, "New Beginning", 0.6, white, shadowColor, "left");
		screen.print(205, 134 - yDifference, "Robbery", 0.6, white, shadowColor, "left");
		screen.print(205, 144 - yDifference, "Luck", 0.6, white, shadowColor, "left");
		screen.print(205, 154 - yDifference, "Banker", 0.6, white, shadowColor, "left");
		if (rotateTableBonus) then
			screen.print(205, 164 - yDifference, "Rotate Table", 0.6, white, shadowColor, "left");
		else
			screen.print(205, 164 - yDifference, "Rotate Table", 0.6, red, shadowColor, "left");
		end
		if (rotateHandsBonus) then
			screen.print(205, 174 - yDifference, "Rotate Hands", 0.6, white, shadowColor, "left");
		else
			screen.print(205, 174 - yDifference, "Rotate Hands", 0.6, red, shadowColor, "left");
		end
		if (newIdentityBonus) then
			screen.print(205, 184 - yDifference, "New Identity", 0.6, white, shadowColor, "left");
		else
			screen.print(205, 184 - yDifference, "New Identity", 0.6, red, shadowColor, "left");
		end
		if (sabotageBonus) then
			screen.print(205, 194 - yDifference, "Sabotage", 0.6, white, shadowColor, "left");
		else
			screen.print(205, 194 - yDifference, "Sabotage", 0.6, red, shadowColor, "left");
		end
		
		screen.print(335, 64 - yDifference, "< " .. cardNumbers[15] .. " >", 0.6, white, shadowColor, "left");
		screen.print(335, 74 - yDifference, "< " .. cardNumbers[16] .. " >", 0.6, white, shadowColor, "left");
		screen.print(335, 84 - yDifference, "< " .. cardNumbers[17] .. " >", 0.6, white, shadowColor, "left");
		screen.print(335, 94 - yDifference, "< " .. cardNumbers[18] .. " >", 0.6, white, shadowColor, "left");
		screen.print(335, 104 - yDifference, "< " .. cardNumbers[19] .. " >", 0.6, white, shadowColor, "left");
		screen.print(335, 114 - yDifference, "< " .. cardNumbers[20] .. " >", 0.6, white, shadowColor, "left");
		screen.print(335, 124 - yDifference, "< " .. cardNumbers[21] .. " >", 0.6, white, shadowColor, "left");
		screen.print(335, 134 - yDifference, "< " .. cardNumbers[22] .. " >", 0.6, white, shadowColor, "left");
		screen.print(335, 144 - yDifference, "< " .. cardNumbers[23] .. " >", 0.6, white, shadowColor, "left");
		screen.print(335, 154 - yDifference, "< " .. cardNumbers[24] .. " >", 0.6, white, shadowColor, "left");
		screen.print(335, 164 - yDifference, "< " .. cardNumbers[25] .. " >", 0.6, white, shadowColor, "left");
		screen.print(335, 174 - yDifference, "< " .. cardNumbers[26] .. " >", 0.6, white, shadowColor, "left");
		screen.print(335, 184 - yDifference, "< " .. cardNumbers[27] .. " >", 0.6, white, shadowColor, "left");
		screen.print(335, 194 - yDifference, "< " .. cardNumbers[28] .. " >", 0.6, white, shadowColor, "left");

		screen.print(20, 220 - yDifference, "Press Cross to Save | Square for Default |", 0.8, blue, shadowColor, "left");
		screen.print(20, 240 - yDifference, "Circle to Cancel | Triangle for Card Details |", 0.8, blue, shadowColor, "left");
		screen.print(20, 260 - yDifference, "R double card amount | L half card amount", 0.8, blue, shadowColor, "left");
		
		if (waitTriangle) then
			local cardName = getCardNameFromCardList(selection);
			checkCurrentCard(cardName, "big");
			
			if (selection > 14) then
				image.blit(5, 3, currentCard);
			else
				image.blit(300, 3, currentCard);
			end
		end
		
		controls.read()

		if controls.press("r") then
			--changeStyle(1);
			cardNumbers[selection] = cardNumbers[selection] * 2;
			if (cardNumbers[selection] > 40) then
				cardNumbers[selection] = 40;
			elseif(cardNumbers[selection] == 0) then
				cardNumbers[selection] = 1;
			end
		elseif controls.press("l") then
			--changeStyle(-1);
			cardNumbers[selection] = math.floor(cardNumbers[selection] / 2);
		elseif controls.press("select") then
			returnMenu();
		elseif controls.press("cross") then
			saveCardList(cardNumbers);
			showMenu();
		elseif controls.press("circle") then
			showMenu();
		elseif controls.press("square") then
			cardNumbers = getDefaultCardList()
			saveCardList(cardNumbers);
			showMenu();
		elseif controls.press("triangle") then
			if (waitTriangle) then
				waitTriangle = false;
			else
				waitTriangle = true;
			end
			
		elseif controls.press("down") or controls.analogy() == 127 + waitAnalog then
			waitAnalog = 0.2
			waitMoment = os.clock()
			selection = selection + 1;
			selectorY = selectorY + 10;
			
			if (selection > 28) then
				selection = 1;
				selectorY = 0;
				selectorX = 0;
			end
			
			if (selection == 15) then
				selectorY = 0;
			end
			
			if (selection > 14) then
				selectorX = 188;
			else
				selectorX = 0;
			end
			
		elseif controls.press("up") or controls.analogy() == -128 - waitAnalog then
			waitAnalog = 0.2
			waitMoment = os.clock()
			selection = selection - 1;
			selectorY = selectorY - 10;
			
			if (selection < 1) then
				selection = 28;
				selectorY = 130;
				selectorX = 188
			end
			
			if (selection == 14) then
				selectorY = 130;
			end
			
			if (selection > 14) then
				selectorX = 188;
			else
				selectorX = 0;
			end
			
		elseif controls.press("left") or controls.analogx() == -128 - waitAnalog then
			waitAnalog = 0.2
			waitMoment = os.clock()
			
			if ((selection == 25 and rotateTableBonus == false) or (selection == 26 and rotateHandsBonus == false) or (selection == 27 and newIdentityBonus == false) or (selection == 28 and sabotageBonus == false)) then
				-- no bonus earned, can't change amount
				-- do nothing
			else
			
				cardNumbers[selection] = cardNumbers[selection] - 1;
				if (cardNumbers[selection] < 0) then
					cardNumbers[selection] = 0;	
				end
			end
		elseif controls.press("right") or controls.analogx() == 127 + waitAnalog then
			waitAnalog = 0.2
			waitMoment = os.clock()
			
			if ((selection == 25 and rotateTableBonus == false) or (selection == 26 and rotateHandsBonus == false) or (selection == 27 and newIdentityBonus == false) or (selection == 28 and sabotageBonus == false)) then
				-- no bonus earned, can't change amount
				-- do nothing
			else
				cardNumbers[selection] = cardNumbers[selection] + 1;
				if (cardNumbers[selection] > 40) then
					cardNumbers[selection] = 40;	
				end
			end
		end
		screen.flip()
		if (os.clock() - waitMoment >= waitAnalog) then
			waitAnalog = 0;
		end
	end
		
end

showOptions = function()

	local optionSelection = 1;
	local selectorY = 0;
	local previousOptions = {allowSoundEffects, allowMusic, waitSeconds}

	while true do
	
	image.blit(0, 0, options);
	image.blit(2, 60 + selectorY, selector);
	
	if (allowSoundEffects) then
		screen.print(175, 74, "< Yes >")
	else
		screen.print(175, 74, "< No >")
	end
	
	if (allowMusic) then
		screen.print(175, 108, "< Yes >")
	else
		screen.print(175, 108, "< No >")
	end
	
	screen.print(175, 142, "< " .. waitSeconds .. "s >")
	
		controls.read()
	
		if controls.press("r") then
			changeStyle(1);
			
		elseif controls.press("l") then
			changeStyle(-1);
			
		elseif controls.press("cross") or controls.press("circle") or controls.press("square") or controls.press("triangle") then
			if (optionSelection == 4) then
				saveSoundOptions();
				playMusic(musicGame);
				return;
			elseif (optionSelection == 5) then
				allowSoundEffects = previousOptions[1]
				allowMusic = previousOptions[2]
				waitSeconds = previousOptions[3]
				return
			end
			
		elseif controls.press("down") or controls.analogy() == 127 + waitAnalog then
			waitAnalog = 0.2
			waitMoment = os.clock()
			optionSelection = optionSelection + 1;
			selectorY = selectorY + 34;
			
			if (optionSelection > 5) then
				optionSelection = 1;
				selectorY = 0;
			end
			
		elseif controls.press("up") or controls.analogy() == -128 - waitAnalog then
			waitAnalog = 0.2
			waitMoment = os.clock()
			optionSelection = optionSelection - 1;
			selectorY = selectorY - 34;
			
			if (optionSelection < 1) then
				optionSelection = 5;
				selectorY = 136;
			end
		
		elseif (controls.press("left") or controls.analogx() == -128 - waitAnalog or controls.press("right") or controls.analogx() == 127 + waitAnalog) and (optionSelection == 1 or optionSelection == 2) then
			waitAnalog = 0.2
			waitMoment = os.clock()
			if (optionSelection == 1) then
				if (allowSoundEffects) then
					allowSoundEffects = false;
				else
					allowSoundEffects = true;
				end
			elseif (optionSelection == 2) then
				if (allowMusic) then
					allowMusic = false;
				else
					allowMusic = true;
				end
			end
			
		elseif optionSelection == 3 and (controls.press("left") or controls.analogx() == -128 - waitAnalog) then
			waitSeconds = waitSeconds - 1;
			if (waitSeconds < 1) then
				waitSeconds = 60;
			end
		elseif optionSelection == 3 and (controls.press("right") or controls.analogx() == 127 + waitAnalog) then
			waitSeconds = waitSeconds + 1;
			if (waitSeconds > 60) then
				waitSeconds = 1;
			end
		end
	
	screen.flip();
	if (os.clock() - waitMoment >= waitAnalog) then
		waitAnalog = 0;
	end
	end

end

showMain = function(styleSet)
	-- Program starts
	loadOptions();
	
	if (styleSet == false) then
		setStyle(false); -- false: first image load, do not clear
		mainmenuButton1 = arcadeVisible;
		mainmenuButton2 = storyHide;
		mainmenuButton3 = optionsHide;
		menuSelection = 1;
	end
	
	while true do
	
	image.blit(0, 0, storyMenu);
	image.blit(163, 86, mainmenuButton1);
	image.blit(163, 140, mainmenuButton2);
	image.blit(163, 195, mainmenuButton3);
	
		controls.read()
	
		if controls.press("r") then
			changeStyle(1);
			
		elseif controls.press("l") then
			changeStyle(-1);
			
		elseif controls.press("cross") or controls.press("circle") or controls.press("square") or controls.press("triangle") then
			if (menuSelection == 1) then
				playMode = "arcade"
				showMenu();
			elseif (menuSelection == 2) then
				playMode = "story"
				showStory();
			else
				showOptions();
			end
			
		elseif controls.press("down") or controls.analogy() == 127 + waitAnalog then
			waitAnalog = 0.2
			waitMoment = os.clock()
			menuSelection = menuSelection + 1;
			
			if (menuSelection == 2) then
				mainmenuButton1 = arcadeHide;
				mainmenuButton2 = storyVisible;
				mainmenuButton3 = optionsHide;
			elseif (menuSelection == 3) then
				mainmenuButton1 = arcadeHide;
				mainmenuButton2 = storyHide;
				mainmenuButton3 = optionsVisible;
			else
				menuSelection = 1;
				mainmenuButton1 = arcadeVisible;
				mainmenuButton2 = storyHide;
				mainmenuButton3 = optionsHide;
			end
			
		elseif controls.press("up") or controls.analogy() == -128 - waitAnalog then
			waitAnalog = 0.2
			waitMoment = os.clock()
			menuSelection = menuSelection - 1;
			if (menuSelection == 1) then
				mainmenuButton1 = arcadeVisible;
				mainmenuButton2 = storyHide;
				mainmenuButton3 = optionsHide;
			elseif (menuSelection == 2) then
				mainmenuButton1 = arcadeHide;
				mainmenuButton2 = storyVisible;
				mainmenuButton3 = optionsHide;
			else
				menuSelection = 3;
				mainmenuButton1 = arcadeHide;
				mainmenuButton2 = storyHide;
				mainmenuButton3 = optionsVisible;
			end
		end
	
	screen.flip();
	if (os.clock() - waitMoment >= waitAnalog) then
		waitAnalog = 0;
	end
	end
end

showMenu = function()
	consecutiveWinnings = 0; -- needed for random bonus, going back to menu clears consecutive winnings
	updatedConsecutiveWinnings = false;
	
	local newsFlashText = "";
	local newsFlashX = 480;

	local denyScreenFlip = false;
	
	if (randomBonus == false) then
		newsFlashText = "Unlock Random Difficulty: Win a hard player twice in a row (select rematch). Required income for playing \"Sell Company\" is required to be at least $200000."
	elseif(moderateBonus == false) then
		newsFlashText = "Unlock Moderate Difficulty: Win a match with the random difficulty. There must be at least 3 players, allow multiple threats is set to \"yes\" and required income for playing \"Sell Company\" is required to be at least $200000."
	elseif(extremeBonus == false) then
		newsFlashText = "Unlock Extreme Difficulty: Win a match with the moderate difficulty. There must be 4 players and required income for playing \"Sell Company\" is required to be at least $200000."
	elseif(cardListBonus == false) then
		newsFlashText = "Unlock Card List: Win a match with the extreme difficulty. There must be 4 players and required income for playing \"Sell Company\" is required to be at least $200000."
	end
	
	local selectorY = 0;
	local selection = 0;
	while true do
		
		image.blit(0, 0, menu);
		image.blit(2, 60 + selectorY, selector);
		
		newsFlashX = newsFlashX - 1.0;
		-- 60 chars ~ 480
		if (newsFlashX < -480 * math.ceil(string.len(newsFlashText) / 60)) then
			newsFlashX = 480;
		end
		
		screen.print(newsFlashX, 5, newsFlashText);
		
		screen.print(312, 84 - yDifference, "< " .. userOptions[1] .. " >", 1.0, blue, shadowColor, "center");
		screen.print(312, 118 - yDifference, "< " .. userOptions[2] .. " >", 1.0, blue, shadowColor, "center");
		screen.print(312, 152 - yDifference, "< " .. userOptions[3] .. " >", 1.0, blue, shadowColor, "center");
		screen.print(312, 186 - yDifference, "< " .. userOptions[4] .. " >", 1.0, blue, shadowColor, "center");
		screen.print(36, 235 - yDifference, "Press Cross to Play | Select for MAIN MENU");
		
		if (cardListBonus) then
			screen.print(36, 255 - yDifference, "Press Triangle for Card List");
		end

		controls.read()
  
		if controls.press("down") or controls.analogy() == 127 + waitAnalog then
			waitAnalog = 0.2
			waitMoment = os.clock()
			selectorY = selectorY + 34;
			selection = selection + 1;
			if (selection > 3) then
				selectorY = 0;
				selection = 0;
			end
		elseif controls.press("up") or controls.analogy() == -128 - waitAnalog then
			waitAnalog = 0.2
			waitMoment = os.clock()
			selectorY = selectorY - 34;
			selection = selection - 1;
			if (selection < 0) then
				selectorY = 102;
				selection = 3;
			end
		elseif controls.press("left") or controls.analogx() == -128 - waitAnalog then
			waitAnalog = 0.2
			waitMoment = os.clock()
			if (selection == 0) then
				if (userOptions[1] == "2") then
					userOptions[1] = "4";
				elseif (userOptions[1] == "3") then
					userOptions[1] = "2";
				else
					userOptions[1] = "3";
				end
				
			elseif (selection == 1) then
				if (userOptions[2] == "yes") then
					userOptions[2] = "no";
				else
					userOptions[2] = "yes";
				end
			elseif (selection == 2) then
				if (userOptions[3] == "easy") then
					userOptions[3] = "random";
					if (randomBonus == false) then
						userOptions[3] = "hard";
					end
				elseif (userOptions[3] == "medium") then
					userOptions[3] = "easy";
				elseif (userOptions[3] == "hard") then
					userOptions[3] = "medium";
				elseif (userOptions[3] == "moderate") then
					userOptions[3] = "hard";
				elseif (userOptions[3] == "extreme") then
					userOptions[3] = "moderate";
				else
					userOptions[3] = "extreme";
					if (extremeBonus == false) then
						userOptions[3] = "moderate";
					end
					
					if (moderateBonus == false) then
						userOptions[3] = "hard";
					end
				end
			elseif (selection == 3) then
				if (userOptions[4] == "$0") then
					userOptions[4] = "$500000"
				elseif (userOptions[4] == "$25000") then
					userOptions[4] = "$0"	
				elseif (userOptions[4] == "$50000") then
					userOptions[4] = "$25000"
				elseif (userOptions[4] == "$75000") then
					userOptions[4] = "$50000"	
				elseif (userOptions[4] == "$100000") then
					userOptions[4] = "$75000"
				elseif (userOptions[4] == "$150000") then
					userOptions[4] = "$100000"
				elseif (userOptions[4] == "$200000") then
					userOptions[4] = "$150000"
				elseif (userOptions[4] == "$300000") then
					userOptions[4] = "$200000"
				elseif (userOptions[4] == "$400000") then
					userOptions[4] = "$300000"
				elseif (userOptions[4] == "$500000") then
					userOptions[4] = "$400000"
				end
			end			
		elseif controls.press("right") or controls.analogx() == 127 + waitAnalog then
			waitAnalog = 0.2
			waitMoment = os.clock()
			if (selection == 0) then
				if (userOptions[1] == "2") then
					userOptions[1] = "3";
				elseif (userOptions[1] == "3") then
					userOptions[1] = "4";
				else
					userOptions[1] = "2";
				end
				
			elseif (selection == 1) then
				if (userOptions[2] == "yes") then
					userOptions[2] = "no";
				else
					userOptions[2] = "yes";
				end
			elseif (selection == 2) then
				if (userOptions[3] == "easy") then
					userOptions[3] = "medium";
				elseif (userOptions[3] == "medium") then
					userOptions[3] = "hard";
				elseif (userOptions[3] == "hard") then
					userOptions[3] = "moderate";
					if (moderateBonus == false) then
						userOptions[3] = "random";
					end
					
					if (randomBonus == false) then
						userOptions[3] = "easy";
					end
					
				elseif (userOptions[3] == "moderate") then
					userOptions[3] = "extreme";
					
					if (extremeBonus == false) then
						userOptions[3] = "random";
					end
					
				elseif (userOptions[3] == "extreme") then
					userOptions[3] = "random";
				else
					userOptions[3] = "easy";
				end
			elseif (selection == 3) then
				if (userOptions[4] == "$0") then
					userOptions[4] = "$25000"
				elseif (userOptions[4] == "$25000") then
					userOptions[4] = "$50000"
				elseif (userOptions[4] == "$50000") then
					userOptions[4] = "$75000"
				elseif (userOptions[4] == "$75000") then
					userOptions[4] = "$100000"	
				elseif (userOptions[4] == "$100000") then
					userOptions[4] = "$150000"
				elseif (userOptions[4] == "$150000") then
					userOptions[4] = "$200000"
				elseif (userOptions[4] == "$200000") then
					userOptions[4] = "$300000"
				elseif (userOptions[4] == "$300000") then
					userOptions[4] = "$400000"
				elseif (userOptions[4] == "$400000") then
					userOptions[4] = "$500000"
				elseif (userOptions[4] == "$500000") then
					userOptions[4] = "$0"
				end
			end
		
		elseif controls.press("cross") then
			saveOptions()
			start("cards.ini")
		elseif controls.press("triangle") and cardListBonus then
			saveOptions()
			showCardList()
		elseif controls.press("r") then
			changeStyle(1);
		elseif controls.press("l") then
			changeStyle(-1);
		elseif controls.press("select") then
			local choice = os.message("Return back to MAIN MENU?", 1)
			denyScreenFlip = true;
			if (choice == 1) then
				showMain(true)
			end
		end
		
		if (denyScreenFlip == false) then
			screen.flip();
		else
			denyScreenFlip = false;
		end
		
		if (os.clock() - waitMoment >= waitAnalog) then
			waitAnalog = 0;
		end
		
	end
	
end

returnMenu = function()
	
	local menuSelection = 3;
	local menuSelectorX = 355;
	local menuWidth = 95;
	local menuHeigth = 45;

	while true do
		screen.clear(darkgray)
		
		screen.print(240, 100 - yDifference, "Return back to", 1.0, lightblue, shadowColor, "center");
		
		if (playMode == "story") then
			screen.print(100, 150, "MAIN MENU", 1.0, lightblue, shadowColor, "center");
			screen.print(250, 150, "STORY MENU", 1.0, lightblue, shadowColor, "center");
			screen.print(400, 150, "CANCEL", 1.0, lightblue, shadowColor, "center");
		elseif (playMode == "arcade") then
			screen.print(100, 150, "MAIN MENU", 1.0, lightblue, shadowColor, "center");
			screen.print(250, 150, "ARCADE MENU", 1.0, lightblue, shadowColor, "center");
			screen.print(400, 150, "CANCEL", 1.0, lightblue, shadowColor, "center");
		end
		
		draw.rect(menuSelectorX, 130, menuWidth, menuHeigth, blue);
		screen.flip();
		
		controls.read()
  
		if controls.press("cross") or controls.press("triangle") or controls.press("square") or controls.press("circle") then
			if (menuSelection == 1) then
				showMain()
			elseif (menuSelection == 2) then
				if (playMode == "arcade") then
					showMenu()
				elseif (playMode == "story") then
					showStory()
				end
			elseif (menuSelection == 3) then
				return
			end
		
		elseif controls.press("left") or controls.analogx() == -128 - waitAnalog then
			menuSelection = menuSelection - 1;
			waitAnalog = 0.2
			waitMoment = os.clock()
			if (menuSelection < 1) then
				menuSelection = 3;
			end
			
			if (menuSelection == 1) then
				menuSelectorX = 30;
				menuWidth = 135;
			elseif (menuSelection == 2) then
				menuSelectorX = 170;
				menuWidth = 160;
			else
				menuSelectorX = 355;
				menuWidth = 95;
			end
			
		elseif controls.press("right") or controls.analogx() == 127 + waitAnalog then
			menuSelection = menuSelection + 1;
			waitAnalog = 0.2
			waitMoment = os.clock()
			if (menuSelection > 3) then
				menuSelection = 1;
			end
			
			if (menuSelection == 1) then
				menuSelectorX = 30;
				menuWidth = 135;
			elseif (menuSelection == 2) then
				menuSelectorX = 170;
				menuWidth = 160;
			else
				menuSelectorX = 355;
				menuWidth = 95;
			end
		end
		
		if (os.clock() - waitMoment >= waitAnalog) then
			waitAnalog = 0;
		end
		
	end
end

checkBonus = function()
	
	file = io.open("randomBonus", "r");

	if file then
		randomBonus = true;
		file:close()
	end
	
	file = io.open("moderateBonus", "r");

	if file then
		moderateBonus = true;
		file:close()
	end
	
	file = io.open("extremeBonus", "r");
	
	if file then
		extremeBonus = true;
		file:close()
	end
	
	file = io.open("cardListBonus", "r");
	
	if file then
		cardListBonus = true;
		file:close()
	end
	
	file = io.open("rotateTableBonus", "r");
	
	if file then
		rotateTableBonus = true;
		file:close()
	end
	
	file = io.open("rotateHandsBonus", "r");
	
	if file then
		rotateHandsBonus = true;
		file:close()
	end
	
	file = io.open("newIdentityBonus", "r");
	
	if file then
		newIdentityBonus = true;
		file:close()
	end
	
	file = io.open("sabotageBonus", "r");
	
	if file then
		sabotageBonus = true;
		file:close()
	end
	
end

loadSoundOptions = function()

local file = io.open("sound.ini", "r");

	if not file then
		return
	end

	local line = file:read();
	local soundOptions = line:splitOptions("[^;]+"); -- note: causes problem if file is empty.
	file:close();
	
	if (#soundOptions ~= 3) then
		-- corrupted data
		return;
	end
	
	if (soundOptions[1] == "false") then
		allowSoundEffects = false;
	end
	
	if (soundOptions[2] == "false") then
		allowMusic = false;
	end
	
	waitSeconds = tonumber(soundOptions[3])
	
end

saveSoundOptions = function()
	sound.loop() -- stop current music before saving
	local file = io.open("sound.ini","w")
	file:write(tostring(allowSoundEffects) .. ";" .. tostring(allowMusic) .. ";" .. waitSeconds);
	file:close();
end

-- PROGRAM STARTS
showLogo();
loadSoundOptions();
playMusic(musicGame);
checkBonus();
dofile("cpu.lua"); -- include cpu logic functions
dofile("story.lua"); -- include story scenarios
showMain(false);