(load "~/quicklisp/setup.lisp")
(ql:quickload :usocket :silent t)

(defun send-to-swank (form-string)
  (let* ((msg (format nil "(:emacs-rex (swank:interactive-eval ~s) :opencortex t 1)" form-string))
         (len (format nil "~6,'0x" (length msg)))
         (socket (usocket:socket-connect "127.0.0.1" 4005))
         (stream (usocket:socket-stream socket)))
    (write-string len stream)
    (write-string msg stream)
    (finish-output stream)
    (let* ((resp-len-raw (make-string 6)))
      (read-sequence resp-len-raw stream)
      (let* ((resp-len (parse-integer resp-len-raw :radix 16))
             (resp-payload (make-string resp-len)))
        (read-sequence resp-payload stream)
        (format t "~a~%" resp-payload)))
    (usocket:socket-close socket)))

(let ((cmd (first (uiop:command-line-arguments))))
  (when cmd
    (send-to-swank cmd)))
