'''Simple Server.  Conditions of GPL apply.'''
'''Orig. Author: Nick Zaillian (feel free to append your name if you modify)'''
import socket
import sys

args = sys.argv
if(len(args)!=2):
	print 'usage: python server.py <port number>'
	sys.exit(0)
'''grab first command line argument (port number)'''
port = int(args[1])

'''Function determines what resource has been requested and returns a 
   corresponding file object if the resource exists'''
def parse_req_and_get_file(request):
	req_line = request[0:request.find('\n')]
	print req_line
	if req_line.startswith('GET'):	
		truncated = req_line[req_line.find(' ')+1: len(req_line)-1]
		path = truncated[0:truncated.find(' ')]
		'''by now, we have parsed out the file path specified in the request...'''
		path = '.'+path
		try:
			f = open(path)
			return f
		except IOError:
			print 'no corresponding file'
	return None
	
'''initialize an INET socket, bind it to user-specified port, and listen...'''
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serverSocket.bind(('', port))
serverSocket.listen(5)
print 'starting server...'

'''main loop, if a request has been received, pass it to the parse_req_and_get_file
   function, then send the corresponding file contents out through the socket (along with 200 status line)'''
while(1):
	print 'listening on port ' + str(port)
	(clientsocket, address) = serverSocket.accept()
	req = clientsocket.recv(1024)
	if req:
		p = parse_req_and_get_file(req)
		if p is not None:
			clientsocket.send('200 OK')
			clientsocket.send(p.read())
		else:
			clientsocket.send('404 file not found')
	clientsocket.close()
