-- WLAN example: reads a test file from www.luaplayer.org
-- and provides a very simple webserver on the PSP
-- init WLAN and choose connection config

white = Color.new(255, 255, 255)
offscreen = Image.createEmpty(480, 272)
offscreen:clear(Color.new(0, 0, 0))
y = 0
x = 0
nickname = System.nickName()
nickname = tostring(nickname)
macaddress = Adhoc.getMac()
macaddress = tostring(macaddress)
function graphicsPrint(text)
	for i = 1, string.len(text) do
		char = string.sub(text, i, i)
		if char == "\n" then
			y = y + 8
			x = 0
		elseif char ~= "\r" then
			offscreen:print(x, y, char, white)
			x = x + 8
		end
	end
	screen:blit(0, 0, offscreen)
	screen.waitVblankStart()
	screen.flip()
end

function graphicsPrintln(text)
	graphicsPrint(text .. "\n")
end
choice = false
while choice == false do
	screen:clear()
	screen:print(1,1,"Press R trigger to use single psp test",white)
	screen:print(1,10,"Press L trigger to use dual psp test",white)
	screen.flip()
	pad = Controls.read()
	if pad:r() then
		select = 1
		break
	end
	if pad:l() then
		select = 2
		break
	end
end
if select == 1 then
-- start server socket
graphicsPrintln("Connecting...")
Adhoc.connect()

-- start connection and wait until it is connected
graphicsPrintln("Determining Statis of adhoc connection...")
while true do
	adhocstat = Adhoc.getState()
	graphicsPrintln("The state is  " .. adhocstat)
	if adhocstat == 1 or adhocstat == 2 then break end
	System.sleep(100)
end
if adhocstat == 1 then
	stat = "All is OK"
end
if adhocstat == 0 then
	stat = "error"
end
graphicsPrintln("State is  " .. stat)
	if Controls.read():start() then 
screen.waitVblankStart() 
end
graphicsPrintln("Adhoc by PiCkDaT")
graphicsPrintln("Making Adhoc name")
graphicsPrintln("Done Press Cross")
while true do
	
if Controls.read():cross() then 
	
screen.waitVblankStart()
	
System.memclean()
	
Adhoc.term()
dofile("./System/system2.lua")
end

end
end

--2 psp mode
if select == 2 then
	err = 0
	Adhoc.connect()
	while err ~= 1 do
		err = Adhoc.getState()
	end
while true do
	screen:clear()
	screen:print(1,1,"Press R trigger to send info to other psp",white)
	screen.flip()
	pad = Controls.read()
	if pad:r() then 
		Adhoc.send(nickname.." "..macaddress)
	end
	data= Adhoc.recv()
	if (data ~= "") then
		screen:print(1,10,data,white)
		screen.flip()
		System.sleep(100)
	end
	if pad:start() then
		Adhoc.send(nickname.." Has left the adhoc network")
		System.memclean()
		Adhoc.term()
		dofile("./System/system2.lua")
	end
end
end
