 (def session-start-time (atom nil))
 (def requests-in-session (atom 0))
 
+(defn get-api-key-for-start-epoch
+  [credentials since-epoch]
+  (or (-> credentials (get since-epoch) :api-key)
+      (let [orig-epochs (keys credentials)
+            correct-key (str
+                         (first
+                          (last
+                           (sort-by
+                            first
+                            (filter
+                             (fn [[e d]]
+                               (pos? d))
+                             (map
+                              vector
+                              (map #(Long/parseLong %) orig-epochs)
+                              (map #(- since-epoch (Long/parseLong %))
+                                   orig-epochs)))))))]
+        (-> credentials (get correct-key) :api-key))))
+
 (defn create-url
   ([since-epoch]
      (create-url since-epoch nil))

        first-page  (rate-limited-download request-url)]
    (write-content start-epoch first-page)
    (discover-iteration start-epoch first-page)))

     (let [credentials (load-credentials)]
       (str thread-request-url
            "?api_key="
            (get-api-key-for-start-epoch credentials (Long/parseLong since-epoch))
            "&since="
            since-epoch
            "&order=asc"
