   (:require [clojure.core.async :as async :refer [<! <!! >!! >! go chan close! merge]]))
 
 (def doi-channel (chan))
-(def dois-resolved-channel (chan))
 
 (def issued-type-id (data/get-type-id-by-name "issued"))
 (def resolved-type-id (data/get-type-id-by-name "first-resolution-test"))
 (def source-id (data/get-source-id-by-name "CrossRefRobot"))
 
+(defn prnl [& args] (locking *out* (apply prn args)))
+
 (defn get-resolutions
   "Get the first and last redirects or nil if it doesn't exist."
   [doi]
   (try 
+    (locking *out* (prn "Start resolve" doi))
     (let [url (crdoi/normalise-doi doi)
           result (try-try-again {:sleep 5000 :tries 2} #(client/get url
                                                          {:follow-redirects true

  (go
     (loop [doi (<! doi-channel)]
       (when doi
         (locking *out* (prn "Get resolutions for" doi))
         (let [result (get-resolutions doi)]
           (if result
             (let [[first-redirect last-redirect] result]
                 (locking *out* (prn "Return to channel" ch doi))
                 (>!! ch [doi first-redirect last-redirect]))
             (do
               (locking *out* (prn "Close ch" ch))
               (close! ch))))
         (recur (<!! doi-channel))))))

(defn run-doi-resolution []
  ; Insert recently published.
  (let [yesterday (t/minus (t/now) (t/weeks 1))
        recently-published (k/select d/events-isam (k/where {:type issued-type-id :event [>= (coerce/to-sql-date yesterday)]}))]
    (doseq [event recently-published]
      (prn "Add to resolutions table" (:doi event))
      (k/exec-raw ["INSERT INTO resolutions (doi) VALUES (?) ON DUPLICATE KEY UPDATE doi = doi"

          resolve-channel (merge doi-resolve-channels)]
      
      ; Stick the DOIs on a channel for them to be resolved asynchronously and returned via doi-resolve-channels.
      (go
        (doseq [doi dois]
          (locking *out* (prn "Spool" doi))
          (>! doi-channel doi))
        (prn "Closing DOI channel")
        (close! doi-channel))
            
      ; Get resolutions from the merged doi-resolve-channel and insert them.
      ; TODO maybe batch into transactions?
      (loop [resolution (<!! resolve-channel)]
        (when resolution
          (let [[doi first-redirect last-redirect] resolution]
            (insert-resolutions doi first-redirect last-redirect))
          (recur (<!! resolve-channel)))))))
