 ;; On creation/reset, points to first key
 ;; On next, either point to next key or set .-end? true. Return (not .-end?)
 ;; On seek, point to first key greater than or equal to seek-key. Return (key= (.key this) seek-key)
-;; On push, push current position onto a stack
-;; On pop, pop last position from the stack
 ;; NOTE iterators are not write-safe unless reset after writing
 
-(deftype Iterator [tree ^:mutable node ^:mutable ix ^:mutable end? ^:mutable old-node ^:mutable old-ix ^:mutable old-end? pushed-nodes pushed-ixes pushed-end?s key-len]
+(deftype Iterator [tree ^:mutable node ^:mutable ix ^:mutable end? key-len]
   Object
   (reset [this]
          (set! node (.-root tree))
          (set! ix 0)
          (while (not (nil? (.-children node)))
            (set! node (aget (.-children node) 0)))
-         (set! end? (<= (alength (.-keys node)) 0))
-         (aclear pushed-nodes)
-         (aclear pushed-ixes)
-         (aclear pushed-end?s))
+         (set! end? (<= (alength (.-keys node)) 0)))
   (key [this]
        (when (false? end?)
          (aget (.-keys node) ix)))

    iterator))

;; used only inside Join
(deftype JoinIterator [iterator outer->inner inner->outer seek-key key-len]
  Object
  (reset [this]
         (.reset iterator))
  (outer-key [this]
             (when (false? (.-end? iterator))
               (let [inner-key (.key iterator)
                     outer-key (make-array key-len)]
                 (dotimes [i (alength inner->outer)]
                   (aset outer-key (aget inner->outer i) (aget inner-key i)))
                 outer-key)))
  (inner-key [this]
             (.key iterator))
  (key-at [this outer-ix]
          (when (false? (.-end? iterator))
            (let [inner-key (.key iterator)]
              (aget inner-key (aget outer->inner outer-ix)))))
  (next [this]
        (.next iterator))
  (seek [this outer-key]
        (dotimes [inner-ix (alength inner->outer)]
          (aset seek-key inner-ix (aget outer-key (aget inner->outer inner-ix))))
        (.seek iterator seek-key))
  (undo [this]
        (.undo iterator))
  (push [this]
        (.push iterator))
  (pop [this]
       (.pop iterator))
  (end? [this]
        (.-end? iterator)))

(deftype Join [seek-key iterators var->iterators var->nextable var->iterator->push|pop? ^:mutable end?]
  Object
  (reset [this]
         (debug)

                        (do
                          (set! node (aget (.-children node) ix))
                          (set! ix 0)
                          (recur))))))))))))

(defn iterator [tree]
  (let [iterator (Iterator. tree (.-root tree) 0 false nil nil nil #js [] #js [] #js [] (.-key-len tree))]
