       (interruptible-sleep delta))
     (await-resume)
     (let [now (clock-ms)
-          wake-time (if (> now (+ target-time 10)) now target-time)]
+          wake-time (if (> now (+ target-time 10)) now target-time)
+          stage-dev (core getFocusDevice)
+          z (get-z-stage-position stage-dev)]
       (state-assoc! :last-wake-time wake-time
-                    :reference-z-position (get-z-stage-position (core getFocusDevice))))))
+                    :reference-z-position z)
+      (store-last-z-position z))))
 
 ;; image metadata
 

    (log (@state :last-positions) "," stage-dev)
    (when (not= z (get-in @state [:last-positions stage-dev]))
      (device-best-effort stage-dev (set-z-stage-position stage-dev z))
      (swap! state assoc-in [:last-positions stage-dev] z)
      (add-to-pending stage-dev)))
  ([stage-dev x y]
    (log (@state :last-positions) "," stage-dev)

(defn run-autofocus []
  (.. gui getAutofocusManager getDevice fullFocus)
  (log "running autofocus " (.. gui getAutofocusManager getDevice getDeviceName))
  (let [z (core getPosition (core getFocusDevice))]
    (state-assoc! :reference-z-position z)
    (store-last-z-position z)))

(defn snap-image [open-before close-after]
  (with-core-setting [getAutoShutter setAutoShutter false]
