function drawScene(target)
	drawCarpet(target)	
	drawCardsOnTheTable(target)
	drawPlayers(target)
	drawIngameCursor(target)
	drawSpeechBubbles(target)
	
	itmess=iterations.." iter."
	printBicolor(target, 380, 230, itmess, black, white)
	
	mem=getMemoryInfo()
	printBicolor(target, 380, 245, mem, black, white)

	printBicolor(target, 5, 5, "active: "..activePlayer, black, white)
	printBicolor(target, 5, 15, "nb cards: "..numberOfCardsPlayed, black, white)
	printBicolor(target, 5, 25, "power: "..powerOfCardsPlayed, black, white)
	if findNextPlayer==true then
		printBicolor(target, 5, 35, "find?: true", black, white)
	else
		printBicolor(target, 5, 35, "find?: false", black, white)
	end
	printBicolor(target, 5, 45, "nb play.: "..nbPlayersInGame, black, white)
	if waitingTurn==true then
		printBicolor(target, 5, 55, "wait?: true", black, white)
	else
		printBicolor(target, 5, 55, "wait?: false", black, white)
	end
	if playEvent~=nil then
		printBicolor(target, 5, 65, "Event!!!!", black, white)
	end
	printBicolor(target, 90, 180, players[1].state, black, white)
	printBicolor(target, 5, 145, players[2].state, black, white)
	printBicolor(target, 300, 5, players[3].state, black, white)
	printBicolor(target, 400, 65, players[4].state, black, white)
	

	iterations=iterations+1
end

function drawPlayingSpace(target, playerNum)
	local position=nil
	if playerNum==1 then
		position="Bottom"
	elseif playerNum==2 then
		position="Left"
	elseif playerNum==3 then
		position="Top"
	else
		position="Right"
	end
	local x=GAMEPREF["player"..position.."TableMinX"]
	local y=GAMEPREF["player"..position.."TableMinY"]
	local width=GAMEPREF["player"..position.."TableMaxX"]-GAMEPREF["player"..position.."TableMinX"]
	local height=GAMEPREF["player"..position.."TableMaxY"]-GAMEPREF["player"..position.."TableMinY"]
	target:fillRect(x, y, width, height, black)
end

--based on the number of cards in hand
function stopGameIfNeeded()
	local nbCardsInHands={}
	local i=1
	local nb0=0
	for i=1,4 do
		nbCardsInHands[i]=handSize(i)
		if nbCardsInHands[i]==0 then
			nb0=nb0+1
		end
	end
	
	if nb0>=3 then
		--3 players have 0 cards (or more?)
		--so it is the end of the game
		--find the one with cards in hand, he's the asshole!
		for i=1,4 do
			if nbCardsInHands[i]>0 then
				players[i].rank="asshole"
			end
			players[i].state="not_playing"
		end
		stopTimer()
		playEvent=false
		aGameIsRunning=false
		--TODO: blame player 1 if he's the asshole, or congrat him if pres.
		fdebug("end game\r\n")
		return true
	end
	return false
end









alert("reloading preferences...")
USERPREF=loadPropertiesFile("configuration/preferences.properties")
GAMEPREF=loadPropertiesFile("configuration/game.properties")

mainDeck=prepareMainDeck()

alert("shuffling main deck...")
shuffleMainDeck()

alert("distributing cards...")
distributeCards()

--order the hands

alert("ordering hands...")
for i=1,4 do
	players[i].hand=orderCards(players[i].hand)
end

alert("positionning objects...")
disposePlayersAroundTheTable()
for i=1,4 do
	positionCards(players[i])
end

--for i=1,4 do
	--for j=1,handSize(i) do
		--debugForced("player "..i, players[i].hand[j].orientation)
	--end
--end

--find the president, and if everyone is neutral, choose random
activePlayer=playerNumByRank("president")
findNextPlayer=true --watches if, when someone has played, we ask the
					--next player to play, or if he keeps the advantage
numberOfCardsPlayed=0 --0
powerOfCardsPlayed=NOVALUE --NOVALUE
waitingTurn=false
nbPlayersInGame=4
nbRanksAvailable=4
ranks={}
ranks[4]="president"
ranks[3]="vice president"
ranks[2]="vice asshole"
ranks[1]="asshole"
playEvent=false
aGameIsRunning=true
fdebug("looking for active player")

if activePlayer==nil then
	activePlayer=4 --random(1,4)
	alert("neutral game, active player is player "..activePlayer, 40)
else
	alert("president is player "..activePlayer, 40)
	--insert exchanging cards
end

putEveryOneInState("in_game")

if activePlayer==1 then
	placeCursorOnCardNum(1)
	makeCursorAvailable()
else
	startTimer()
end

-- debug variables
num=1
iterations=1
fdebug("init ok, starting loop")
while true do
	
	if aGameIsRunning then
	   	updateInputs(Controls.read())
	   	
	   	if inputLongPress("select") then
			break
		end
		
		if inputFirstPress("start") then
			local bg=Image.createEmpty(480, 272)
			drawScene(bg)
			local mmchoice=mainMenu(bg, false) --return can be: quitMenu cancel exit
			if mmchoice=="exit" then
				return "exit"
			end
		end
	   	
		playEvent=getPlayEvent(inputAnalogIsTouched() or inputIsPressed("triangle"))
	   	
	   	--2 cases: it's the turn of the user or of the AI
	   	--turn of the user
	   	if activePlayer==1 and playEvent then--first loop for the turn of the user, place everything
	   		if findNextPlayer==false then
		   		if handSize(1)==0 then
		   			powerOfCardsPlayed=NOVALUE
		   			numberOfCardsPlayed=0
		   			cleanTableDeck()
		   			players[1].state="finished"
		   			players[1].rank=ranks[nbRanksAvailable]
		   			nbRanksAvailable=nbRanksAvailable-1
		   			findNextPlayer=true
		   			--debugForced("see if game over")
		   			if stopGameIfNeeded() then
		   				debugForced("player 1 end game")
		   			end
		   		--trump is there since last event
		   		elseif powerOfCardsPlayed==TRUMP then
		   			powerOfCardsPlayed=NOVALUE
		   			numberOfCardsPlayed=0
		   			cleanTableDeck()
		   			for i=1,4 do
		   				if players[i].state=="passed" then
		   					players[i].state="in_game"
		   				end
		   			end
		   		end   		
	   		end
	   		
	   		--detect end of round or end of game
	   		--end of round?
	   		nbPlayersInGame=4
	   		local i=0
	   		for i=1,4 do
	   			if players[i].state=="passed" or players[i].state=="not_playing" or players[i].state=="finished" then
	   				nbPlayersInGame=nbPlayersInGame-1
	   			end
	   		end
	   		if nbPlayersInGame==1 then
	   			--debugForced("nbPlayersInGame==1")
	   			powerOfCardsPlayed=NOVALUE
	   			numberOfCardsPlayed=0
	   			cleanTableDeck()
	   			for i=1,4 do
	   				if players[i].state=="passed" then
	   					players[i].state="in_game"
	   				end
	   			end
	   		end
	   		
	   		if aGameIsRunning then
		   		if handSize(1)==0 then
		   			--debugForced("see if game over")
		   			activePlayer=nextAvailablePlayerNum(activePlayer)
		   		else
		   			stopTimer()
		   			placeCursorOnCardNum(1)
		   			--alert("you play")
		   			makeCursorAvailable()
		   		end
		   	end
	   	elseif activePlayer==1 and cursorIsAvailable() and aGameIsRunning then --next turns for the user, let him play
	   		if inputFirstPress("cross") then
	   			--select the card
	   			invertSelectionOfCardNum(ingameCursor.indice)
	   			placeCursorOnCardNum(ingameCursor.indice)
	   		elseif inputLongPress("cross") then
	   			selectAllCardsWithValue(players[1].hand[ingameCursor.indice].value, players[1].hand[ingameCursor.indice].selected)
	   		end
	   		if inputFirstPress("square") then
	   			--cancel selection
	   			deselectAllCards(1)
	   			placeCursorOnCardNum(ingameCursor.indice) --in the case the card it was on was selected
	   		end
	   		if inputFirstPress("circle") then
	   			--validate selection
	   			--startTimer() --if it's ok
	   			--local bg=Image.createEmpty(480, 272)
	   			--drawCarpet(bg)	
				--drawPlayers(bg)
				--drawIngameCursor(bg)
				--drawScene(bg)
				drawScene(screen) --needed by the cancelPassAcceptMenu
	   			local cpamchoice=cancelPassAcceptMenu() --accept, cancel, pass
	   			if cpamchoice=="accept" then
					local tableOfCards=takeSelectedCardsFromHand(1, false)
					local validity=theGroupIsValid(tableOfCards)
					
					if validity=="ok" or validity=="cut" then
						makePlayerLeader(1)
						numberOfCardsPlayed=tableLength(tableOfCards)
						powerOfCardsPlayed=tableOfCards[1].power
						removeSelectedCardsFromHand(1)
						positionCards(players[1])
			   			putCardsOnTheTable(tableOfCards, 1)
			   			if validity=="cut" then
			   				findNextPlayer=false
			   			elseif handSize(1)==0 then
			   				findNextPlayer=false
			   			else
			   				findNextPlayer=true
			   			end
			   			if findNextPlayer then
							activePlayer=nextAvailablePlayerNum(1)
						end
						makeCursorAvailable(false)
						
						--[[if handSize(1)==0 then
				   			powerOfCardsPlayed=NOVALUE
				   			numberOfCardsPlayed=0
				   			cleanTableDeck()
				   			players[1].state="finished"
				   			players[1].rank=ranks[nbRanksAvailable]
				   			nbRanksAvailable=nbRanksAvailable-1
				   		end]]
						
	   					startTimer()
	   				else
	   					local bgimg=Image.createEmpty(480,272)
	   					drawScene(bgimg)
	   					messageBox(bgimg, "error "..validity)
	   				end
	   			elseif cpamchoice=="pass" then
	   				if powerOfCardsPlayed==NOVALUE then
	   					local bgimg=Image.createEmpty(480,272)
	   					drawScene(bgimg)
	   					messageBox(bgimg, "you have to play")
	   				else
		   				players[1].state="passed"
		   				findNextPlayer=true
		   				activePlayer=nextAvailablePlayerNum(1)
		   				makeCursorAvailable(false)
		   				deselectAllCards(1)
		   				startTimer()
		   				--waitingTurn=true
		   			end
	   			end
	   		end 
	   		if inputFirstPress("right") or inputIsRepeating("right") then
	   			moveCursorToThe("right")
	   		elseif inputFirstPress("left") or inputIsRepeating("left") then
	   			moveCursorToThe("left")
	   		elseif inputFirstPress("r") or inputIsRepeating("r") then
	   			moveCursorToThe("right", 5)
	   		elseif inputFirstPress("l") or inputIsRepeating("l") then
	   			moveCursorToThe("left", 5)
	   		end
	   		
	   		
	   		
	   	elseif playEvent~=nil then  --the AI has to play
	   		fdebug("playEvent:")
	   		nbPlayersInGame=4
	   		local i=0
	   		for i=1,4 do
	   			if players[i].state=="passed" or players[i].state=="not_playing" or players[i].state=="finished" then
	   				nbPlayersInGame=nbPlayersInGame-1
	   			end
	   		end
	   		
	   		fdebug("activePlayer: "..activePlayer)
			fdebug("numberOfCardsPlayed: "..numberOfCardsPlayed)
			fdebug("powerOfCardsPlayed: "..powerOfCardsPlayed)
			if findNextPlayer==true then
				fdebug("findNextPlayer?: true")
			else
				fdebug("findNextPlayer?: false")
			end
			fdebug("nbPlayersInGame: "..nbPlayersInGame)
			if waitingTurn==true then
				fdebug("waitingTurn?: true")
			else
				fdebug("waitingTurn?: false")
			end
	   		
	   		--debug
	   		drawScene(screen)
	   		screen.waitVblankStart()
			screen.flip()
	   		------
	   		
	   		if nbPlayersInGame==1 then
	   			--debugForced("nbPlayersInGame==1")
	   			powerOfCardsPlayed=NOVALUE
	   			numberOfCardsPlayed=0
	   			cleanTableDeck()
	   			for i=1,4 do
	   				if players[i].state=="passed" then
	   					players[i].state="in_game"
	   				end
	   			end
	   			findNextPlayer=false
	   		else --nbplayersingame<>1 ---HERE
	   			--debugForced("nbPlayersInGame<>1")
		   		if findNextPlayer==false then
			   		if handSize(activePlayer)==0 then
			   			powerOfCardsPlayed=NOVALUE
			   			numberOfCardsPlayed=0
			   			cleanTableDeck()
			   			players[activePlayer].state="finished"
			   			players[activePlayer].rank=ranks[nbRanksAvailable]
		   				nbRanksAvailable=nbRanksAvailable-1
			   			findNextPlayer=true
		   				--debugForced("see if game over")
		   				stopGameIfNeeded()
			   		--trump is there since last event
			   		elseif powerOfCardsPlayed==TRUMP then
			   			powerOfCardsPlayed=NOVALUE
			   			numberOfCardsPlayed=0
			   			cleanTableDeck()
			   			waitingTurn=true
			   		end   		
		   		end
		   		
		   		if waitingTurn then
		   			--detect if players must be put in game again
					if powerOfCardsPlayed==NOVALUE then
						local i=0
						for i=1,4 do
							if players[i].state=="passed" then
								players[i].state="in_game"
							end
						end
					end
		   			waitingTurn=false
		   		else--not a waiting turn -----HERE
					local ai=AI()
					if ai==nil then
						players[activePlayer].state="passed"
					else --ai is not null
						makePlayerLeader(activePlayer)
						positionCards(players[activePlayer])
				   		numberOfCardsPlayed=tableLength(ai)
				   		powerOfCardsPlayed=ai[1].power
				   		putCardsOnTheTable(ai, activePlayer)
				   		
				   		if powerOfCardsPlayed==TRUMP then
				   			findNextPlayer=false
				   		elseif handSize(activePlayer)==0 then
				   			findNextPlayer=false
				   			waitingTurn=true
				   		else
				   			findNextPlayer=true
				   			waitingTurn=false
				   		end
					end
				end
			end
			
			
			if findNextPlayer and aGameIsRunning then
				activePlayer=nextAvailablePlayerNum(activePlayer)
			end
	   	end
	end 	
   	
   	
   	
   	
   	
	
	
	
	
	
	--draw the scene
	drawScene(screen)
	if inputIsPressed("triangle") then
		drawPlayingSpace(screen, math.mod(iterations,4)+1)
	end
	
	if inputFirstPress("select") then
		say("bottom", "je suis\nen bas")
		say("top", "je suis\nen haut")
		say("left", "je suis\nà gauche")
		say("right", "je suis\nà droite")
	end
	
	screen.waitVblankStart()
	screen.flip()
end


