 
 exports.Iterator = class Iterator
 
-  busy = false
-  isValid = false
-  keybuf = null
-  valbuf = null
-
-  lock = ->
-    throw new Error 'Concurrent operations not supported' if busy
-    busy = true
-
-  unlock = ->
-    throw new Error 'Not locked' unless busy
-    busy = false
-
-  afterSeek = (callback) -> (err, valid, key, val) ->
-    unlock()
-    isValid = valid
-    keybuf = key
-    valbuf = val
-    callback err if callback
-
-  getKey = (options = {}) ->
-    unless keybuf
-      return null
-    else unless options.as_buffer
-      keybuf.toString 'utf8'
+  toBuffer = (val) ->
+    new Buffer val unless Buffer.isBuffer val
+
+  toValue = (val, options) ->
+    unless val
+      null
+    else unless options?.as_buffer
+      val.toString 'utf8'
     else
-      keybuf
-
-  getValue = (options = {}) ->
-    unless valbuf
-      return null
-    else unless options.as_buffer
-      valbuf.toString 'utf8'
-    else
-      valbuf
+      val
+
+  wrapSeek = (callback, validate) ->
+    @_lock()
+
+    throw new Error 'Illegal state' if validate and not @_valid
+    throw new Error 'Missing callback' unless callback
+
+    (err, valid, key, val) =>
+      @_unlock()
+      @_valid = valid
+      @_key = key
+      @_val = val
+      callback err if callback
+
+  _lock: ->
+    throw new Error 'Concurrent operations not supported' if @_busy
+    @_busy = true
+
+  _unlock: ->
+    throw new Error 'Not locked' unless @_busy
+    @_busy = false
+
+  _getKey: (options) ->
+    toValue @_key, options
+
+  _getVal: (options) ->
+    toValue @_val, options
 
 
   ###

  ###

  key: (options, callback) ->
    throw new Error 'Illegal state' unless isValid

    # optional options
    if typeof options is 'function'
      callback = options
      options = null

    throw new Error 'Missing callback' unless callback

    callback null, getKey options


  ###

  ###

  first: (callback) ->
    @self.first @_wrapSeek callback


  ###
