;
; Porta Function (makes a programming task portable and sends it
; to the grid for execution on the machine with the highest ACR)
; Simple Grid Protocol 1.0 - Copyright (c) Brendan Kosowski 2004
;

(defun porta (task)

	(setq fr (open "/home/grid/token.dat" :direction :input))
	(setq token (read-line fr))
	(close fr)

	(setq fr (open "/home/grid/track_ip.dat" :direction :input))
	(setq track_ip (read-line fr))
	(close fr)

	(setq stm (socket:socket-connect 17667 track_ip))
	(read-line stm)

	(setq lin (read-line stm))
	(when (string= lin "token?")
		(format stm "~a~%" token)
	)

	(setq lin (read-line stm))
	(when (string= lin "what?")
		(format stm "show~%")
	)

	(setq grid (read-from-string (read-line stm)))

	(setq lin (read-line stm))
	(when (string= lin "what?")
		(format stm "bye~%")
	)

	(close stm)

	(setq stm nil)
	(loop	
		(setq best_ip (first (pop grid)))
		(ignore-errors (setq stm (socket:socket-connect 17666 best_ip)))
		(when stm (return))
	)

	(read-line stm)

	(setq lin (read-line stm))
	(when (string= lin "token?")
		(format stm "~a~%" token)
	)

	(setq lin (read-line stm))
	(when (string= lin "what?")
		(format stm "eval~%")
	)

	(setq lin (read-line stm))
	(when (string= lin "code?")
		(format stm "~a~%" task)
	)

	(setq result (read-from-string (read-line stm)))

	(setq lin (read-line stm))
	(when (string= lin "what?")
		(format stm "bye~%")
	)

	(close stm)
	(values result best_ip)
)
