--[[
netlib v1.0
Copyright 2006 by youresam
Thanks to Yeldarb for the hosting!
]]--

function replace(thestring,char1,char2)
lastfound = 1
while true do
hasfound = string.find(thestring,char1)
if hasfound == nil then break end
thestring = string.sub(thestring,1,hasfound-1)..char2..string.sub(thestring,hasfound+1)
lastfound = hasfound + 1
end
return thestring
end

function netsend(id, data, abtribute)
if id == "" then error("invalid id") end
if data == "" then return end
if not (abtribute == "a" or abtribute == "w") then
error("bad abtribute, must be 'a' or 'w'")
end
data = replace(data," ","%20")
data = replace(data,":","%3A")
socket = Socket.connect("www.psp-programming.com", 80)
while not socket:isConnected() do System.sleep(100) end
bytesSent = socket:send("GET /youresam/net/write"..abtribute..".php?id="..id.."&data="..data.." HTTP/1.0\r\n")
bytesSent = socket:send("host: www.psp-programming.com\r\n\r\n")
socket:close()
end

function netget(id)
if id == "" then error("invalid id") end
socket = Socket.connect("www.psp-programming.com", 80)
while not socket:isConnected() do System.sleep(100) end
bytesSent = socket:send("GET /youresam/net/id/"..id..".txt HTTP/1.0\r\n")
bytesSent = socket:send("host: www.psp-programming.com\r\n\r\n")
total = ""
request = 0
while true do
	buffer = socket:recv()
		if string.len(buffer) > 0 then 
			total = total..buffer
			request = 1
		else
			if request == 1 then request = 2 end
		end
	
	if request == 2 then 
		socket:close()
		break
	end
screen.waitVblankStart(6)
end
--sort out data
start = string.find(total,"text/plain") or 1
begin = start+14
total = string.sub(total,begin)
return total
end


function netcheck(id)
if id == "" then error("no id") end
socket = Socket.connect("www.psp-programming.com", 80)
while not socket:isConnected() do System.sleep(100) end
bytesSent = socket:send("GET /youresam/net/read.php?id="..id.." HTTP/1.0\r\n")
bytesSent = socket:send("host: www.psp-programming.com\r\n\r\n")
total = ""
request = 0
while true do
	buffer = socket:recv()
		if string.len(buffer) > 0 then 
			total = total..buffer
			request = 1
		else
			if request == 1 then request = 2 end
		end
	
	if request == 2 then 
		socket:close()
		break
	end
screen.waitVblankStart(6)
end
if string.find(total,"READ ERROR") == nil then
return true
else
return false
end
end

function netdelete(id)
if id == "" then error("invalid id") end
socket = Socket.connect("www.psp-programming.com", 80)
while not socket:isConnected() do System.sleep(100) end
bytesSent = socket:send("GET /youresam/net/delete.php?id="..id.." HTTP/1.0\r\n")
bytesSent = socket:send("host: www.psp-programming.com\r\n\r\n")
socket:close()
end

