;   Copyright (c) Rich Hickey. All rights reserved.
;   The use and distribution terms for this software are covered by the
;   Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
;   which can be found in the file epl-v10.html at the root of this distribution.
;   By using this software in any fashion, you are agreeing to be bound by
;   the terms of this license.
;   You must not remove this notice, or any other, from this software.

(ns clojure.core)

;; Unstick clojerl directory when bootstrapping.
(clojerl_app/unstick)

(def
  ^{:arglists '([& items])
    :doc "Creates a new list containing the items."
    :added "1.0"}
  list (fn* [& items] (new clojerl.List items)))

(def
  ^{:arglists '([x seq])
    :doc "Returns a new seq where x is the first element and seq is
    the rest."
    :added "1.0"}
  cons (fn* [x s] (clj_rt/cons x s)))

(def
  ^{:macro true
    :added "1.0"}
  let (fn* let [_&form _&env & decl] (cons 'let* decl)))

(def
  ^{:macro true
    :added "1.0"}
  loop (fn* loop [_&form _&env & decl] (cons 'loop* decl)))

(def
  ^{:macro true
    :added "1.0"}
  fn (fn* fn [&form _&env & decl]
         (let [x (cons 'fn* (new clojerl.List decl))]
           (clj_rt/with_meta x (clj_rt/meta &form)))))

(def
  ^{:arglists '([coll])
    :doc "Returns the first item in the collection. Calls seq on its
    argument. If coll is nil, returns nil."
    :added "1.0"}
  first (fn first [coll] (clj_rt/first coll)))

(def
  ^{:arglists '([coll])
    :tag clojerl.ISeq
    :doc "Returns a seq of the items after the first. Calls seq on its
  argument.  If there are no more items, returns nil."
    :added "1.0"}
  next (fn next [x] (clj_rt/next x)))

(def
  ^{:arglists '([coll])
    :tag clojerl.ISeq
    :doc "Returns a possibly empty seq of the items after the first. Calls seq on its
  argument."
    :added "1.0"}
  rest (fn rest [x] (clj_rt/rest x)))

(def
  ^{:arglists '([coll x] [coll x & xs])
    :doc "conj[oin]. Returns a new collection with the xs
    'added'. (conj nil item) returns (item).  The 'addition' may
    happen at different 'places' depending on the concrete type."
    :added "1.0"}
  conj (fn conj
         ([] [])
         ([coll] coll)
         ([coll x] (clj_rt/conj coll x))
         ([coll x & xs]
          (if xs
            (recur (conj coll x) (first xs) (next xs))
            (conj coll x)))))

(def
  ^{:doc "Same as (first (next x))"
    :arglists '([x])
    :added "1.0"}
  second (fn second [x] (first (next x))))

(def
  ^{:doc "Same as (first (first x))"
    :arglists '([x])
    :added "1.0"}
  ffirst (fn ffirst [x] (first (first x))))

(def
  ^{:doc "Same as (next (first x))"
    :arglists '([x])
    :added "1.0"}
  nfirst (fn nfirst [x] (next (first x))))

(def
  ^{:doc "Same as (first (next x))"
    :arglists '([x])
    :added "1.0"}
  fnext (fn fnext [x] (first (next x))))

(def
  ^{:doc "Same as (next (next x))"
    :arglists '([x])
    :added "1.0"}
  nnext (fn nnext [x] (next (next x))))

(def
  ^{:arglists '([coll])
    :doc "Returns a seq on the collection. If the collection is
    empty, returns nil.  (seq nil) returns nil. seq also works on
    Strings, Erlang tuples and any type that implements Iterable.
    Note that seqs cache values, thus seq should not be used on
    any Iterable whose iterator repeatedly returns the same mutable
    object."
    :tag clojerl.ISeq
    :added "1.0"}
  seq (fn seq [coll] (clj_rt/seq coll)))

(def
  ^{:arglists '([protocol x])
    :doc "Returns true if x satisfies the protocol"
    :added "1.2"}
  satisfies? (fn satisfies? [^erlang.Type protocol x]
               (.satisfies? protocol x)))

(def
  ^{:arglists '([atype x])
    :doc "Returns true if x's type is atype"
    :added "1.0"}
  instance? (fn instance? [^erlang.Type atype x]
              (.instance? atype x)))

(def
  ^{:arglists '([x])
    :doc "Return true if x implements ISeq"
    :added "1.0"}
  seq? (fn seq? [x] (satisfies? clojerl.ISeq x)))

(def
  ^{:arglists '([x])
    :doc "Return true if x implements ISeq"
    :added "1.0"}
  lazy-seq? (fn seq? [x] (instance? clojerl.LazySeq x)))

(def
  ^{:arglists '([x])
    :doc "Return true if x implements IMeta"
    :added "1.0"}
  meta? (fn meta? [x] (satisfies? clojerl.IMeta x)))

(def
  ^{:arglists '([x])
    :doc "Return true if x is a String"
    :added "1.0"}
  string? (fn string? [x] (erlang/is_binary x)))

(def
  ^{:arglists '([x])
    :doc "Return true if x is a Character"
    :added "1.0"}
  char? (fn char? [x]
          (case* x
            #bin[[_ :type :utf8]] true
            _ false)))

(def
  ^{:arglists '([x])
    :doc "Return true if x implements IMap"
    :added "1.0"}
  map? (fn map? [x] (satisfies? clojerl.IMap x)))

(def
  ^{:arglists '([x])
    :doc "Return true if x is a Vector"
    :added "1.0"}
  vector? (fn vector? [x] (satisfies? clojerl.IVector x)))

(def
  ^{:arglists '([x])
    :doc "Return true if x is a Symbol"
    :added "1.0"}
  symbol? (fn symbol? [x] (instance? clojerl.Symbol x)))

(def
  ^{:arglists '([x])
    :doc "Returns true if x is an Erlang tuple"
    :added "1.0"}
  tuple? (fn [x] (erlang/is_tuple x)))

(def
  ^{:arglists '([map key val] [map key val & kvs])
    :doc "assoc[iate]. When applied to a map, returns a new map of the
    same (hashed/sorted) type, that contains the mapping of key(s) to
    val(s). When applied to a vector, returns a new vector that
    contains val at index. Note - index must be <= (count vector)."
    :added "1.0"}
  assoc
  (fn assoc
    ([map key val] (clj_rt/assoc map key val))
    ([map key val & kvs]
     (let [ret (assoc map key val)]
       (if kvs
         (if (next kvs)
           (recur ret (first kvs) (second kvs) (nnext kvs))
           (throw (clojerl.BadArgumentError.
                   "assoc expects even number of arguments after map/vector, found odd number")))
         ret)))))

;;;;;;;;;;;;;;;;; metadata ;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def
  ^{:arglists '([obj])
    :doc "Returns the metadata of obj, returns nil if there is no metadata."
    :added "1.0"}
  meta (fn meta [x]
         (if (meta? x)
           (clj_rt/meta x))))

(def
  ^{:arglists '([^clojerl.IMeta obj m])
    :doc "Returns an object of the same type and value as obj, with
    map m as its metadata."
    :added "1.0"}
  with-meta (fn with-meta [x m]
              (clj_rt/with_meta x m)))

(def ^{:private true :dynamic true}
  assert-valid-fdecl (fn [fdecl]))

(def
  ^{:private true}
  sigs
  (fn [fdecl]
    (assert-valid-fdecl fdecl)
    (let [asig
          (fn [fdecl]
            (let [arglist (first fdecl)
                  ;elide implicit macro args
                  arglist (if (clj_rt/equiv '&form (first arglist))
                            (clj_rt/subvec arglist 2 (clj_rt/count arglist))
                            arglist)
                  body (next fdecl)]
              (if (map? (first body))
                (if (next body)
                  (with-meta arglist (conj (if (meta arglist) (meta arglist) {}) (first body)))
                  arglist)
                arglist)))]
      (if (seq? (first fdecl))
        (loop [ret [] fdecls fdecl]
          (if fdecls
            (recur (conj ret (asig (first fdecls))) (next fdecls))
            (clojerl.List. (seq ret))))
        (list (asig fdecl))))))

(def
  ^{:arglists '([coll])
    :doc "Return the last item in coll, in linear time"
    :added "1.0"}
  last (fn last [s]
         (let [x (next s)]
           (if x
             (recur x)
             (first s)))))

(def
  ^{:arglists '([coll])
    :doc "Return a seq of all but the last item in coll, in linear time"
    :added "1.0"}
  butlast (fn butlast [s]
            (loop [ret [] s s]
              (let [x (next s)]
                (if x
                  (recur (conj ret (first s)) x)
                  (seq ret))))))

(def
  ^{:doc "Used to generate the code for defn and defn*"
    :private true}
  generate-defn
  (fn* [fn-sym &form &env name fdecl]
       (if (symbol? name)
         nil
         (throw (clojerl.BadArgumentError. "First argument to defn must be a symbol")))
       (let [m     (if (string? (first fdecl))
                     {:doc (first fdecl)}
                     {})
             fdecl (if (string? (first fdecl))
                     (next fdecl)
                     fdecl)
             m     (if (map? (first fdecl))
                     (conj m (first fdecl))
                     m)
             fdecl (if (map? (first fdecl))
                     (next fdecl)
                     fdecl)
             fdecl (if (vector? (first fdecl))
                     (list fdecl)
                     fdecl)
             m     (if (map? (last fdecl))
                     (conj m (last fdecl))
                     m)
             fdecl (if (map? (last fdecl))
                     (butlast fdecl)
                     fdecl)
             m     (conj {:arglists (list 'quote (sigs fdecl))} m)
             m     (conj (if (meta name) (meta name) {}) m)]
         (list 'def (with-meta name m)
               (cons fn-sym
                     ;; we haven't defined all the necessary functions
                     (new clojerl.List (seq fdecl)))))))

(def
  ^{:doc "Same as (def name (fn [params* ] exprs*)) or (def
    name (fn ([params* ] exprs*)+)) with any doc-string or attrs added
    to the var metadata. prepost-map defines a map with optional keys
    :pre and :post that contain collections of pre or post conditions."
    :arglists '([name doc-string? attr-map? [params*] prepost-map? body]
                [name doc-string? attr-map? ([params*] prepost-map? body)+ attr-map?])
    :added "1.0"
    :macro true}
  defn
  (fn* [&form &env name & fdecl]
       (generate-defn 'clojure.core/fn &form &env name fdecl)))

(def
  ^{:doc "Same as (def name (fn* [params* ] exprs*)) or (def
    name (fn* ([params* ] exprs*)+)) with any doc-string or attrs added
    to the var metadata. prepost-map defines a map with optional keys
    :pre and :post that contain collections of pre or post conditions."
    :arglists '([name doc-string? attr-map? [params*] prepost-map? body]
                [name doc-string? attr-map? ([params*] prepost-map? body)+ attr-map?])
    :added "1.0"
    :macro true}
  defn*
  (fn* [&form &env name & fdecl]
       (generate-defn 'fn* &form &env name fdecl)))

(defn vector
  "Creates a new vector containing the args."
  {:added "1.0"}
  ([] [])
  ([a] [a])
  ([a b] [a b])
  ([a b c] [a b c])
  ([a b c d] [a b c d])
  ([a b c d & args]
   (clj_rt/vector (cons a (cons b (cons c (cons d args)))))))

(defn vec
  "Creates a new vector containing the contents of coll."
  {:added "1.0"}
  ([coll]
   (if (vector? coll)
     (if (satisfies? clojerl.IMeta coll)
       (with-meta coll nil)
       (clj_rt/vector coll))
     (clj_rt/vector coll))))

(defn hash-map
  "keyval => key val
  Returns a new hash map with supplied mappings.  If any keys are
  equal, they are handled as if by repeated uses of assoc."
  {:added "1.0"}
  ([] {})
  ([& keyvals]
   (new clojerl.Map keyvals)))

(defn hash-set
  "Returns a new hash set with supplied keys.  Any equal keys are
  handled as if by repeated uses of conj."
  {:added "1.0"}
  ([] #{})
  ([& keys]
   (new clojerl.Set keys)))

(defn sorted-map
  "keyval => key val
  Returns a new sorted map with supplied mappings.  If any keys are
  equal, they are handled as if by repeated uses of assoc."
  {:added "1.0"}
  ([& keyvals]
   (new clojerl.SortedMap keyvals)))

(defn sorted-map-by
  "keyval => key val
  Returns a new sorted map with supplied mappings, using the supplied
  comparator.  If any keys are equal, they are handled as if by
  repeated uses of assoc."
  {:added "1.0"}
  ([comparator & keyvals]
   (new clojerl.SortedMap (clj_rt/compare_fun comparator :clojure) keyvals)))

(defn sorted-set
  "Returns a new sorted set with supplied keys.  Any equal keys are
  handled as if by repeated uses of conj."
  {:added "1.0"}
  ([& keys]
   (new clojerl.SortedSet keys)))

(defn sorted-set-by
  "Returns a new sorted set with supplied keys, using the supplied
  comparator.  Any equal keys are handled as if by repeated uses of
  conj."
  {:added "1.1"}
  ([comparator & keys]
   (new clojerl.SortedSet (clj_rt/compare_fun comparator :clojure) keys)))

;;;;;;;;;;;;;;;;;;;;

(defn nil?
  "Returns true if x is nil, false otherwise."
  {:tag clojerl.Boolean
   :inline '(fn* [x] (clojure.core/list 'erlang/=:= x nil))
   :added "1.0"}
  [x] (erlang/=:= x nil))

(def
  ^{:macro true
    :doc "Like defn, but the resulting function name is declared as a
  macro and will be used as a macro by the compiler when it is
  called."
    :arglists '([name doc-string? attr-map? [params*] body]
                [name doc-string? attr-map? ([params*] body)+ attr-map?])
    :added "1.0"}
  defmacro (fn [&form &env name & args]
             (let [name   (with-meta name (assoc (meta name) :macro true))
                   prefix (loop [p (list name) args args]
                            (let [f (first args)]
                              (if (string? f)
                                (recur (cons f p) (next args))
                                (if (map? f)
                                  (recur (cons f p) (next args))
                                  p))))
                   fdecl (loop [fd args]
                           (if (string? (first fd))
                             (recur (next fd))
                             (if (map? (first fd))
                               (recur (next fd))
                               fd)))
                   fdecl (if (vector? (first fdecl))
                           (list fdecl)
                           fdecl)
                   add-implicit-args (fn [fd]
                                       (let [args (first fd)]
                                         (cons (vec (cons '&form (cons '&env args)))
                                               (next fd))))
                   add-args (fn [acc ds]
                              (if (nil? ds)
                                acc
                                (let [d (first ds)]
                                  (if (map? d)
                                    (conj acc d)
                                    (recur (conj acc (add-implicit-args d))
                                           (next ds))))))
                   fdecl (seq (add-args [] fdecl))
                   decl (loop [p prefix d fdecl]
                          (if p
                            (recur (next p) (cons (first p) d))
                            d))]
               (cons 'clojure.core/defn decl))))

(defmacro when
  "Evaluates test. If logical true, evaluates body in an implicit do."
  {:added "1.0"}
  [test & body]
  (list 'if test (cons 'do body)))

(defmacro when-not
  "Evaluates test. If logical false, evaluates body in an implicit do."
  {:added "1.0"}
  [test & body]
  (list 'if test nil (cons 'do body)))

(defn false?
  "Returns true if x is the value false, false otherwise."
  {:tag clojerl.Boolean
   :added "1.0"}
  [x] (erlang/=:= x false))

(defn true?
  "Returns true if x is the value true, false otherwise."
  {:tag clojerl.Boolean
   :added "1.0"}
  [x] (erlang/=:= x true))

(defn boolean?
  "Return true if x is a Boolean"
  {:added "1.9"}
  [x] (instance? clojerl.Boolean x))

(defn not
  "Returns true if x is logical false, false otherwise."
  {:tag clojerl.Boolean
   :added "1.0"}
  [x] (if x false true))

(defn some?
  "Returns true if x is not nil, false otherwise."
  {:tag clojerl.Boolean
   :added "1.6"}
  [x] (not (nil? x)))

(defn str-helper
  [^clojerl.String acc more]
  (if more
    (recur (.append acc (clj_rt/str (first more)))
           (next more))
    acc))

(defn str
  "With no args, returns the empty string. With one arg x, returns
  x.toString().  (str nil) returns the empty string. With more than
  one arg, returns the concatenation of the str values of the args."
  {:tag clojerl.String
   :added "1.0"}
  (^clojerl.String [] "")
  (^clojerl.String [x]
   (clj_rt/str x))
  (^clojerl.String [x & ys]
   (str-helper (str x) ys)))

(defn keyword?
  "Return true if x is a Keyword"
  {:added "1.0"}
  [x] (instance? clojerl.Keyword x))

(defn symbol
  "Returns a Symbol with the given namespace and name."
  {:tag clojerl.Symbol
   :added "1.0"}
  ([name] (if (symbol? name) name (clj_rt/symbol name)))
  ([ns name] (clj_rt/symbol ns name)))

(defn gensym
  "Returns a new symbol with a unique name. If a prefix string is
  supplied, the name is prefix# where # is some unique number. If
  prefix is not supplied, the prefix is 'G__'."
  {:added "1.0"}
  ([] (gensym "G__"))
  ([prefix-string] (clj_rt/gensym prefix-string)))

(defmacro cond
  "Takes a set of test/expr pairs. It evaluates each test one at a
  time.  If a test returns logical true, cond evaluates and returns
  the value of the corresponding expr and doesn't evaluate any of the
  other tests or exprs. (cond) returns nil."
  {:added "1.0"}
  [& clauses]
  (when clauses
    (list 'if (first clauses)
          (if (next clauses)
            (second clauses)
            (throw (clojerl.BadArgumentError. "cond requires an even number of forms")))
          (cons 'clojure.core/cond (nnext clauses)))))

(defn keyword
  "Returns a Keyword with the given namespace and name.  Do not use :
  in the keyword strings, it will be added automatically."
  {:tag clojerl.Keyword
   :added "1.0"}
  ([name] (cond (keyword? name) name
                (symbol? name) (new clojerl.Keyword (clj_rt/namespace name)
                                                      (clj_rt/name name))
                (string? name) (new clojerl.Keyword name)))
  ([ns name] (new clojerl.Keyword ns name)))

(defn find-keyword
  "Returns a Keyword with the given namespace and name if one already
  exists.  This function will not intern a new keyword. If the keyword
  has not already been interned, it will return nil.  Do not use :
  in the keyword strings, it will be added automatically."
  {:tag clojerl.Keyword
   :added "1.3"}
  ([name] (cond (keyword? name) name
                (symbol? name) (clojerl.Keyword/find (clj_rt/namespace name)
                                                          (clj_rt/name name))
                (string? name) (clojerl.Keyword/find name)))
  ([ns name] (clojerl.Keyword/find ns name)))

(defn spread
  {:private true}
  [arglist]
  (cond
    (nil? arglist) nil
    (nil? (next arglist)) (seq (first arglist))
    :else (cons (first arglist) (spread (next arglist)))))

(defn list*
  "Creates a new list containing the items prepended to the rest, the
  last of which will be treated as a sequence."
  {:added "1.0"}
  ([args] (seq args))
  ([a args] (cons a args))
  ([a b args] (cons a (cons b args)))
  ([a b c args] (cons a (cons b (cons c args))))
  ([a b c d & more]
   (cons a (cons b (cons c (cons d (spread more)))))))

(defn apply
  "Applies fn f to the argument list formed by prepending intervening arguments to args."
  {:added "1.0"}
  ([f args]
   (clojerl.IFn/apply f (seq args)))
  ([f x args]
   (clojerl.IFn/apply f (list* x args)))
  ([f x y args]
   (clojerl.IFn/apply f (list* x y args)))
  ([f x y z args]
   (clojerl.IFn/apply f (list* x y z args)))
  ([f a b c d & args]
   (clojerl.IFn/apply f (cons a (cons b (cons c (cons d (spread args))))))))

(defn vary-meta
  "Returns an object of the same type and value as obj, with
  (apply f (meta obj) args) as its metadata."
  {:added "1.0"}
  [obj f & args]
  (with-meta obj (apply f (meta obj) args)))

(defmacro lazy-seq
  "Takes a body of expressions that returns an ISeq or nil, and yields
  a Seqable object that will invoke the body only the first time seq
  is called, and will cache the result and return it on all subsequent
  seq calls. See also - realized?"
  {:added "1.0"}
  [& body]
  (list 'new 'clojerl.LazySeq (list* '^{:once true} fn* [] body)))

(defn chunk-buffer [capacity]
  (clojerl.ChunkBuffer. capacity))

(defn chunk-append [^clojerl.ChunkBuffer b x]
  (.add b x))

(defn ^clojerl.IChunk chunk [^clojerl.ChunkBuffer b]
  (.chunk b))

(defn ^clojerl.IChunk chunk-first ^clojerl.IChunk [^clojerl.IChunkedSeq s]
  (.chunked_first s))

(defn ^clojerl.ISeq chunk-rest ^clojerl.ISeq [^clojerl.IChunkedSeq s]
  (.chunked_more s))

(defn ^clojerl.ISeq chunk-next ^clojerl.ISeq [^clojerl.IChunkedSeq s]
  (.chunked_next s))

(defn chunk-cons [chunk rest]
  (if (erlang/== (clj_rt/count chunk) 0)
    rest
    (clojerl.ChunkedCons. chunk rest)))

(defn chunked-seq? [s]
  (satisfies? clojerl.IChunkedSeq s))

(defn concat
    "Returns a lazy seq representing the concatenation of the elements in the supplied colls."
    {:added "1.0"}
    ([] (lazy-seq nil))
    ([x] (lazy-seq x))
    ([x y]
     (lazy-seq
      (let [s (seq x)]
        (if s
          (if (chunked-seq? s)
            (chunk-cons (chunk-first s) (concat (chunk-rest s) y))
            (cons (first s) (concat (rest s) y)))
          y))))
    ([x y & zs]
     (let [cat (fn cat [xys zs]
                 (lazy-seq
                  (let [xys (seq xys)]
                    (if xys
                      (if (chunked-seq? xys)
                        (chunk-cons (chunk-first xys)
                                    (cat (chunk-rest xys) zs))
                        (cons (first xys) (cat (rest xys) zs)))
                      (when zs
                        (cat (first zs) (next zs)))))))]
       (cat (concat x y) zs))))

;;;;;;;;;;;;;;;;at this point all the support for syntax-quote exists;;;;;;;;;;;;;;;;;;;;;;
(defmacro delay
  "Takes a body of expressions and yields a Delay object that will
  invoke the body only the first time it is forced (with force or deref/@), and
  will cache the result and return it on all subsequent force
  calls. See also - realized?"
  {:added "1.0"}
  [& body]
  (list 'new 'clojerl.Delay (list* `^{:once true} fn* [] body)))

(defn delay?
  "returns true if x is a Delay created with delay"
  {:added "1.0"}
  [x]
  (instance? clojerl.Delay x))

(defn force
  "If x is a Delay, returns the (possibly cached) value of its expression, else returns x"
  {:added "1.0"}
  [x]
  (clojerl.Delay/force x))

(defmacro if-not
  "Evaluates test. If logical false, evaluates and returns then expr,
  otherwise else expr, if supplied, else nil."
  {:added "1.0"}
  ([test then] `(if-not ~test ~then nil))
  ([test then else]
   `(if (not ~test) ~then ~else)))

(defn identical?
  "Tests if 2 arguments are the same object"
  {:inline '(fn* [x y] `(erlang/=:= ~x ~y))
   :inline-arities #{2}
   :added "1.0"}
  ([x y] (erlang/=:= x y)))

;equiv-based
(defn =
  "Equality. Returns true if x equals y, false if not. Compares
  numbers and collections in a type-independent manner.  Clojure's immutable data
  structures define equals() (and thus =) as a value, not an identity,
  comparison."
  {:inline '(fn* [x y] `(clj_rt/equiv ~x ~y))
   :inline-arities #{2}
   :added "1.0"}
  ([x] true)
  ([x y] (clj_rt/equiv x y))
  ([x y & more]
   (if (clj_rt/equiv x y)
     (let [x (next more)]
       (if x
         (recur y (first more) x)
         (clj_rt/equiv y (first more))))
     false)))

(defn not=
  "Same as (not (= obj1 obj2))"
  {:tag clojerl.Boolean
   :added "1.0"}
  ([x] false)
  ([x y] (not (= x y)))
  ([x y & more]
   (not (apply = x y more))))

(defn compare
  "Comparator. Returns a negative number, zero, or a positive number
  when x is logically 'less than', 'equal to', or 'greater than'
  y. Compares numbers and collections in a type-independent manner. x
  must implement Comparable"
  {:added "1.0"}
  [x y]
  (clj_utils/compare x y))

(defmacro and
  "Evaluates exprs one at a time, from left to right. If a form
  returns logical false (nil or false), and returns that value and
  doesn't evaluate any of the other expressions, otherwise it returns
  the value of the last expr. (and) returns true."
  {:added "1.0"}
  ([] true)
  ([x] x)
  ([x & next]
   `(let [and# ~x]
      (if and# (and ~@next) and#))))

(defmacro or
  "Evaluates exprs one at a time, from left to right. If a form
  returns a logical true value, or returns that value and doesn't
  evaluate any of the other expressions, otherwise it returns the
  value of the last expression. (or) returns nil."
  {:added "1.0"}
  ([] nil)
  ([x] x)
  ([x & next]
      `(let [or# ~x]
         (if or# or# (or ~@next)))))

;;;;;;;;;;;;;;;;;;; sequence fns  ;;;;;;;;;;;;;;;;;;;;;;;
(defn zero?
  "Returns true if num is zero, else false"
  {:inline '(fn* [x] `(erlang/== ~x 0))
   :added "1.0"}
  [x] (erlang/== x 0))

(defn count
  "Returns the number of items in the collection. (count nil) returns
  0. Also works on strings, arrays, and Erlang lists, tuples and maps"
  {:inline '(fn* [x] `(clj_rt/count ~x))
   :added "1.0"}
  [coll] (clj_rt/count coll))

(defn int
  "Coerce to int"
  {:inline '(fn* [x] `(erlang/trunc ~x))
   :added "1.0"}
  [x] (erlang/trunc x))

(defn nth
  "Returns the value at the index. get returns nil if index out of
  bounds, nth throws an exception unless not-found is supplied.  nth
  also works for strings, Erlang tuples, and lists, and, in O(n) time,
  for sequences."
  {:inline '(fn*  [c i & nf] `(clj_rt/nth ~c ~i ~@nf))
   :inline-arities #{2 3}
   :added "1.0"}
  ([coll index] (clj_rt/nth coll index))
  ([coll index not-found] (clj_rt/nth coll index not-found)))

(defn <
  "Returns non-nil if nums are in monotonically increasing order,
  otherwise false."
  {:inline '(fn* [x y] `(erlang/< ~x ~y))
   :inline-arities #{2}
   :added "1.0"}
  ([x] true)
  ([x y] (erlang/< x y))
  ([x y & more]
   (if (< x y)
     (let [x (next more)]
       (if x
         (recur y (first more) x)
         (< y (first more))))
     false)))

(defn inc
  "Returns a number one greater than num."
  {:inline '(fn* [x] `(erlang/+ ~x 1))
   :added "1.2"}
  [x] (erlang/+ x 1))

;; reduce is defined again later after InternalReduce loads
(defn ^:private
  reduce
  ([f coll]
   (let [s (seq coll)]
     (if s
       (reduce f (first s) (next s))
       (f))))
  ([f val coll]
   (let [s (seq coll)]
     (if s
       (if (chunked-seq? s)
         (recur f
                (.reduce (chunk-first s) f val)
                (chunk-next s))
         (recur f (f val (first s)) (next s)))
       val))))

(defn reverse
  "Returns a seq of the items in coll in reverse order. Not lazy."
  {:added "1.0"}
  [coll]
  (reduce conj '() coll))

;;math stuff
(defn ^:private nary-inline
  [op]
  `(fn*
     ([x#] (list '~op x#))
     ([x# y#] (list '~op x# y#))
     ([x# y# ~'& more#]
      (#'clojure.core/reduce
       (fn [a# b#] (list '~op a# b#))
       (list '~op x# y#)
       more#))))

(defn ^:private >1? [n] (erlang/> n 1))
(defn ^:private >0? [n] (erlang/> n 0))

(defn +
  "Returns the sum of nums. (+) returns 0."
  {:inline (nary-inline 'erlang/+)
   :inline-arities >1?
   :added "1.2"}
  ([] 0)
  ([x] x)
  ([x y] (erlang/+ x y))
  ([x y & more]
   (reduce erlang/+.2 (+ x y) more)))

(defn *
  "Returns the product of nums. (*) returns 1."
  {:inline (nary-inline 'erlang/*)
   :inline-arities >1?
   :added "1.2"}
  ([] 1)
  ([x] x)
  ([x y] (erlang/* x y))
  ([x y & more]
   (reduce * (* x y) more)))

(defn /
  "If no denominators are supplied, returns 1/numerator,
  else returns numerator divided by all of the denominators."
  {:inline (nary-inline 'erlang//)
   :inline-arities >1?
   :added "1.0"}
  ([x] (erlang// 1 x))
  ([x y] (erlang// x y))
  ([x y & more]
   (reduce / (/ x y) more)))

(defn -
  "If no ys are supplied, returns the negation of x, else subtracts
  the ys from x and returns the result."
  {:inline (nary-inline 'erlang/-)
   :inline-arities >0?
   :added "1.2"}
  ([x] (erlang/- x))
  ([x y] (erlang/- x y))
  ([x y & more]
   (reduce - (- x y) more)))

(defn <=
  "Returns non-nil if nums are in monotonically non-decreasing order,
  otherwise false."
  {:inline '(fn* [x y] `(erlang/=< ~x ~y))
   :inline-arities #{2}
   :added "1.0"}
  ([x] true)
  ([x y] (erlang/=< x y))
  ([x y & more]
   (if (<= x y)
     (let [x (next more)]
       (if x
         (recur y (first more) x)
         (<= y (first more))))
     false)))

(defn >
  "Returns non-nil if nums are in monotonically decreasing order,
  otherwise false."
  {:inline '(fn* [x y] `(erlang/> ~x ~y))
   :inline-arities #{2}
   :added "1.0"}
  ([x] true)
  ([x y] (erlang/> x y))
  ([x y & more]
   (if (> x y)
     (let [x (next more)]
       (if x
         (recur y (first more) x)
         (> y (first more))))
     false)))

(defn >=
  "Returns non-nil if nums are in monotonically non-increasing order,
  otherwise false."
  {:inline '(fn* [x y] `(erlang/>= ~x ~y))
   :inline-arities #{2}
   :added "1.0"}
  ([x] true)
  ([x y] (erlang/>= x y))
  ([x y & more]
   (if (>= x y)
     (let [x (next more)]
       (if x
         (recur y (first more) x)
         (>= y (first more))))
     false)))

(defn ==
  "Returns non-nil if nums all have the equivalent
  value (type-independent), otherwise false"
  {:inline '(fn* [x y] `(erlang/== ~x ~y))
   :inline-arities #{2}
   :added "1.0"}
  ([x] true)
  ([x y] (erlang/== x y))
  ([x y & more]
   (if (== x y)
     (let [x (next more)]
       (if x
         (recur y (first more) x)
         (== y (first more))))
     false)))

(defn max
  "Returns the greatest of the nums."
  {:inline (nary-inline 'erlang/max)
   :inline-arities >1?
   :added "1.0"}
  ([x] x)
  ([x y] (if (< x y) y x))
  ([x y & more]
   (reduce max (max x y) more)))

(defn min
  "Returns the least of the nums."
  {:inline (nary-inline 'erlang/min)
   :inline-arities >1?
   :added "1.0"}
  ([x] x)
  ([x y] (if (> x y) y x))
  ([x y & more]
   (reduce min (min x y) more)))

(defn dec
  "Returns a number one less than num."
  {:inline '(fn* [x] `(erlang/- ~x 1))
   :added "1.2"}
  [x] (erlang/- x 1))

(defn pos?
  "Returns true if num is greater than zero, else false"
  {:inline '(fn* [x] `(erlang/> ~x 0))
   :added "1.0"}
  [x] (> x 0))

(defn neg?
  "Returns true if num is less than zero, else false"
  {:inline '(fn* [x] `(erlang/< ~x 0))
   :added "1.0"}
  [x] (< x 0))

(defn quot
  "quot[ient] of dividing numerator by denominator."
  {:inline '(fn* [x y] `(clj_utils/quotient ~x ~y))
   :added "1.0"}
  [num div]
  (clj_utils/quotient num div))

(defn rem
  "remainder of dividing numerator by denominator."
  {:inline '(fn* [x y] `(clj_utils/rem ~x ~y))
   :added "1.0"}
  [num div]
  (clj_utils/rem num div))

;;Bit ops

(defn bit-not
  "Bitwise complement"
  {:inline '(fn* [x] `(erlang/bnot ~x))
   :added "1.0"}
  [x] (erlang/bnot x))


(defn bit-and
  "Bitwise and"
  {:inline (nary-inline 'erlang/band)
   :inline-arities >1?
   :added "1.0"}
   ([x y] (erlang/band x y))
   ([x y & more]
      (reduce bit-and (bit-and x y) more)))

(defn bit-or
  "Bitwise or"
  {:inline (nary-inline 'erlang/bor)
   :inline-arities >1?
   :added "1.0"}
  ([x y] (erlang/bor x y))
  ([x y & more]
    (reduce bit-or (bit-or x y) more)))

(defn bit-xor
  "Bitwise exclusive or"
  {:inline (nary-inline 'erlang/bxor)
   :inline-arities >1?
   :added "1.0"}
  ([x y] (erlang/bxor x y))
  ([x y & more]
    (reduce bit-xor (bit-xor x y) more)))

(defn bit-and-not
  "Bitwise and with complement"
  {:inline (nary-inline 'clj_utils/bnand)
   :inline-arities >1?
   :added "1.0"}
  ([x y] (bit-not (bit-and x y)))
  ([x y & more]
    (reduce bit-and-not (bit-and-not x y) more)))


(defn bit-clear
  "Clear bit at index n"
  {:added "1.0"}
  [x n]
  (erlang/band x (erlang/bnot (erlang/bsl 1 n))))

(defn bit-set
  "Set bit at index n"
  {:added "1.0"}
  [x n]
  (erlang/bor x (erlang/bsl 1 n)))

(defn bit-flip
  "Flip bit at index n"
  {:added "1.0"}
  [x n]
  (erlang/bxor x (erlang/bsl 1 n)))

(defn bit-test
  "Test bit at index n"
  {:added "1.0"}
  [x n]
  (erlang/=/= 0 (erlang/band x (erlang/bsl 1 n))))

(defn bit-shift-left
  "Bitwise shift left (same behaviour as erlang/bsl) "
  {:inline '(fn* [x n] `(erlang/bsl ~x ~n))
   :added "1.0"}
  [x n] (erlang/bsl x n))

(defn bit-shift-right
  "Bitwise shift right (same behaviour as erlang/bsr)"
  {:inline '(fn* [x n] `(erlang/bsr ~x ~n))
   :added "1.0"}
  [x n] (erlang/bsr x n))

(defn integer?
  "Returns true if n is an integer"
  {:inline '(fn* [x] `(erlang/is_integer ~x))
   :added "1.0"}
  [n]
  (erlang/is_integer n))

(defn even?
  "Returns true if n is even, throws an exception if n is not an integer"
  {:added "1.0"}
   [n] (if (integer? n)
        (zero? (bit-and n 1))
        (throw (clojerl.BadArgumentError. (str "Argument must be an integer: " n)))))

(defn odd?
  "Returns true if n is odd, throws an exception if n is not an integer"
  {:added "1.0"}
  [n] (not (even? n)))

(defn int?
  "Return true if x is a fixed precision integer"
  {:added "1.9"}
  [x] (instance? clojerl.Integer x))

(defn pos-int?
  "Return true if x is a positive fixed precision integer"
  {:added "1.9"}
  [x] (and (int? x)
           (pos? x)))

(defn neg-int?
  "Return true if x is a negative fixed precision integer"
  {:added "1.9"}
  [x] (and (int? x)
           (neg? x)))

(defn nat-int?
  "Return true if x is a non-negative fixed precision integer"
  {:added "1.9"}
  [x] (and (int? x)
           (not (neg? x))))

;;

(defn complement
  "Takes a fn f and returns a fn that takes the same arguments as f,
  has the same effects, if any, and returns the opposite truth value."
  {:added "1.0"}
  [f]
  (fn
    ([] (not (f)))
    ([x] (not (f x)))
    ([x y] (not (f x y)))
    ([x y & zs] (not (apply f x y zs)))))

(defn constantly
  "Returns a function that takes any number of arguments and returns x."
  {:added "1.0"}
  [x] (fn [& args] x))

(defn identity
  "Returns its argument."
  {:added "1.0"}
  [x] x)

;;Collection stuff

;;list stuff
(defn peek
  "For a list or queue, same as first, for a vector, same as, but much
  more efficient than, last. If the collection is empty, returns nil."
  {:added "1.0"}
  [coll] (clj_rt/peek coll))

(defn pop
  "For a list or queue, returns a new list/queue without the first
  item, for a vector, returns a new vector without the last item. If
  the collection is empty, throws an exception.  Note - not the same
  as next/butlast."
  {:added "1.0"}
  [coll] (clj_rt/pop coll))

;;map stuff

(defn map-entry?
  "Return true if x is a map entry"
  {:added "1.8"}
  [x]
  (and (satisfies? clojerl.IIndexed x) (= 2 (count x))))

(defn contains?
  "Returns true if key is present in the given collection, otherwise
  returns false.  Note that for numerically indexed collections like
  vectors and Erlang tuples, this tests if the numeric key is within the
  range of indexes. 'contains?' operates constant or logarithmic time;
  it will not perform a linear search for a value.  See also 'some'."
  {:added "1.0"}
  [coll key] (clj_rt/contains? coll key))

(defn get
  "Returns the value mapped to key, not-found or nil if key not present."
  {:inline '(fn* [m k & nf] `(clj_rt/get ~m ~k ~@nf))
   :inline-arities #{2 3}
   :added "1.0"}
  ([map key]
   (clj_rt/get map key))
  ([map key not-found]
   (clj_rt/get map key not-found)))

(defn dissoc
  "dissoc[iate]. Returns a new map of the same (hashed/sorted) type,
  that does not contain a mapping for key(s)."
  {:added "1.0"}
  ([map] map)
  ([map key]
   (clj_rt/dissoc map key))
  ([map key & ks]
   (let [ret (dissoc map key)]
     (if ks
       (recur ret (first ks) (next ks))
       ret))))

(defn disj
  "disj[oin]. Returns a new set of the same (hashed/sorted) type, that
  does not contain key(s)."
  {:added "1.0"}
  ([set] set)
  ([^clojerl.Set set key]
   (when set
     (clj_rt/disj set key)))
  ([set key & ks]
   (when set
     (let [ret (disj set key)]
       (if ks
         (recur ret (first ks) (next ks))
         ret)))))

(defn find
  "Returns the map entry for key, or nil if key not present."
  {:added "1.0"}
  [map key] (clj_rt/find map key))

(defn select-keys
  "Returns a map containing only those entries in map whose key is in keys"
  {:added "1.0"}
  [map keyseq]
    (loop [ret {} keys (seq keyseq)]
      (if keys
        (let [entry (clj_rt/find map (first keys))]
          (recur
           (if entry
             (conj ret entry)
             ret)
           (next keys)))
        (with-meta ret (meta map)))))

(defn keys
  "Returns a sequence of the map's keys, in the same order as (seq map)."
  {:added "1.0"}
  [map] (clj_rt/keys map))

(defn vals
  "Returns a sequence of the map's values, in the same order as (seq map)."
  {:added "1.0"}
  [map] (clj_rt/vals map))

(defn key
  "Returns the key of the map entry."
  {:added "1.0"}
  [e]
  (first e))

(defn val
  "Returns the value in the map entry."
  {:added "1.0"}
  [e]
  (second e))

(defn rseq
  "Returns, in constant time, a seq of the items in rev (which
  can be a vector or sorted-map), in reverse order. If rev is empty returns nil"
  {:added "1.0"}
  [^clojerl.IReversible rev]
    (. rev (rseq)))

(defn name
  "Returns the name String of a string, symbol or keyword."
  {:tag clojerl.String
   :added "1.0"}
  [x]
  (if (string? x) x (clj_rt/name x)))

(defn namespace
  "Returns the namespace String of a symbol or keyword, or nil if not present."
  {:tag clojerl.String
   :added "1.0"}
  [^clojerl.INamed x]
  (clj_rt/namespace x))

(defmacro ..
  "form => fieldName-symbol or (instanceMethodName-symbol args*)
  Expands into a member access (.) of the first member on the first
  argument, followed by the next member on the result, etc. For
  instance:
  (.. System (getProperties) (get \"os.name\"))
  expands to:
  (. (. System (getProperties)) (get \"os.name\"))
  but is easier to write, read, and understand."
  {:added "1.0"}
  ([x form] `(. ~x ~form))
  ([x form & more] `(.. (. ~x ~form) ~@more)))

(defmacro ->
  "Threads the expr through the forms. Inserts x as the
  second item in the first form, making a list of it if it is not a
  list already. If there are more forms, inserts the first form as the
  second item in second form, etc."
  {:added "1.0"}
  [x & forms]
  (loop [x x, forms forms]
    (if forms
      (let [form (first forms)
            threaded (if (seq? form)
                       (with-meta `(~(first form) ~x ~@(next form)) (meta form))
                       (list form x))]
        (recur threaded (next forms)))
      x)))

(defmacro ->>
  "Threads the expr through the forms. Inserts x as the
  last item in the first form, making a list of it if it is not a
  list already. If there are more forms, inserts the first form as the
  last item in second form, etc."
  {:added "1.1"}
  [x & forms]
  (loop [x x, forms forms]
    (if forms
      (let [form (first forms)
            threaded (if (seq? form)
              (with-meta `(~(first form) ~@(next form)  ~x) (meta form))
              (list form x))]
        (recur threaded (next forms)))
      x)))

(def map)

(defn ^:private check-valid-options
  "Throws an exception if the given option map contains keys not listed
  as valid, else returns nil."
  [options & valid-keys]
  (when (seq (apply disj (apply hash-set (keys options)) valid-keys))
    (throw
     (clojerl.BadArgumentError.
      (apply str "Only these options are valid: "
             (first valid-keys)
             (map #(str ", " %) (rest valid-keys)))))))

;;multimethods
(def global-hierarchy)

(defmacro defmulti
  "Creates a new multimethod with the associated dispatch function.
  The docstring and attr-map are optional.

  Options are key-value pairs and may be one of:

  :default

  The default dispatch value, defaults to :default

  :hierarchy

  The value used for hierarchical dispatch (e.g. ::square is-a ::shape)

  Hierarchies are type-like relationships that do not depend upon type
  inheritance. By default Clojure's multimethods dispatch off of a
  global hierarchy map.  However, a hierarchy relationship can be
  created with the derive function used to augment the root ancestor
  created with make-hierarchy.

  Multimethods expect the value of the hierarchy option to be supplied as
  a reference type e.g. a var (i.e. via the Var-quote dispatch macro #'
  or the var special form)."
  {:arglists '([name docstring? attr-map? dispatch-fn & options])
   :added "1.0"}
  [mm-name & options]
  (let [docstring   (if (string? (first options))
                      (first options)
                      nil)
        options     (if (string? (first options))
                      (next options)
                      options)
        m           (if (map? (first options))
                      (first options)
                      {})
        options     (if (map? (first options))
                      (next options)
                      options)
        dispatch-fn (first options)
        options     (next options)
        m           (if docstring
                      (assoc m :doc docstring)
                      m)
        m           (if (meta mm-name)
                      (conj (meta mm-name) m)
                      m)]
    (when (= (count options) 1)
      (throw (clojerl.Error. "The syntax for defmulti has changed. Example: (defmulti name dispatch-fn :default dispatch-value)")))
    (let [options   (apply hash-map options)
          default   (get options :default :default)
          hierarchy (get options :hierarchy #'global-hierarchy)
          mm-name-var (clj_multimethod/dispatch_map_var mm-name)
          mm-name-map (symbol (namespace mm-name-var) (name mm-name-var))]
      (check-valid-options options :default :hierarchy)
      (when-not (clj_multimethod/is_init mm-name)
        (clj_multimethod/init mm-name)
        `(defn ~(with-meta mm-name (assoc m :multi-method true))
           [& args#]
           (let [val# (clojerl.IFn/apply ~dispatch-fn args#)
                 dispatch-map# ~mm-name-map
                 f#   (or (clojerl.Map/get dispatch-map# val#)
                          (clojerl.Map/get dispatch-map# ~default)
                          (throw
                           (clojerl.Error. (str "No multimethod defined for dispatch value " val#
                                                " in " '~mm-name))))]
             (clojerl.IFn/apply f# args#)))))))

(defmacro defmethod
  "Creates and installs a new method of multimethod associated with dispatch-value. "
  {:added "1.0"}
  [^clojerl.Symbol multifn dispatch-val & fn-tail]
  (let [fn-name (gensym (str (.name multifn) "_method_"))]
    `(do
       (defn- ~fn-name ~@fn-tail)
       (clj_multimethod/add_method ~multifn ~dispatch-val ~fn-name))))

(defn remove-all-methods
  "Removes all of the methods of multimethod."
  {:added "1.2"}
  [^clojerl.Var multifn]
  (clj_multimethod/remove_all multifn)
  multifn)

(defn remove-method
  "Removes the method of multimethod associated with dispatch-value."
  {:added "1.0"}
  [^clojerl.Var multifn dispatch-val]
  (clj_multimethod/remove_method multifn dispatch-val))

(defn prefer-method
  "Causes the multimethod to prefer matches of dispatch-val-x over dispatch-val-y
   when there is a conflict"
  {:added "1.0"}
  [^clojerl.Var multifn dispatch-val-x dispatch-val-y]
  (throw "unimplemented hierarchy"))

(defn methods
  "Given a multimethod, returns a map of dispatch values -> dispatch fns"
  {:added "1.0"}
  [^clojerl.Var multifn]
  (clj_multimethod/get_method_table multifn))

(defn get-method
  "Given a multimethod and a dispatch value, returns the dispatch fn
  that would apply to that value, or nil if none apply and no default"
  {:added "1.0"}
  [^clojerl.Var multifn dispatch-val]
  (clj_multimethod/get_method multifn dispatch-val))

(defn prefers
  "Given a multimethod, returns a map of preferred value -> set of other values"
  {:added "1.0"}
  [^clojerl.Var multifn]
  (throw "unimplemented hierarchy"))

;;;;;;;;; var stuff

(defmacro ^{:private true} assert-args
  [& pairs]
  `(do (when-not ~(first pairs)
         (throw (clojerl.BadArgumentError.
                 (str (first ~'&form) " requires " ~(second pairs) " in " ~'*ns* ":" (:line (meta ~'&form))))))
     ~(let [more (nnext pairs)]
        (when more
          (list* `assert-args more)))))

(defmacro set!
  [x val]
  (assert-args (symbol? x) "a symbol as its first argument")
  `(clj_rt/set! (var ~x) ~val))

(defmacro if-let
  "bindings => binding-form test
  If test is true, evaluates then with binding-form bound to the value of
  test, if not, yields else"
  {:added "1.0"}
  ([bindings then]
   `(if-let ~bindings ~then nil))
  ([bindings then else & oldform]
   (assert-args
     (vector? bindings) "a vector for its binding"
     (nil? oldform) "1 or 2 forms after binding vector"
     (= 2 (count bindings)) "exactly 2 forms in binding vector")
   (let [form (bindings 0) tst (bindings 1)]
     `(let [temp# ~tst]
        (if temp#
          (let [~form temp#]
            ~then)
          ~else)))))

(defmacro when-let
  "bindings => binding-form test
  When test is true, evaluates body with binding-form bound to the value of test"
  {:added "1.0"}
  [bindings & body]
  (assert-args
     (vector? bindings) "a vector for its binding"
     (= 2 (count bindings)) "exactly 2 forms in binding vector")
   (let [form (bindings 0) tst (bindings 1)]
    `(let [temp# ~tst]
       (when temp#
         (let [~form temp#]
           ~@body)))))

(defmacro if-some
  "bindings => binding-form test
   If test is not nil, evaluates then with binding-form bound to the
   value of test, if not, yields else"
  {:added "1.6"}
  ([bindings then]
   `(if-some ~bindings ~then nil))
  ([bindings then else & oldform]
   (assert-args
     (vector? bindings) "a vector for its binding"
     (nil? oldform) "1 or 2 forms after binding vector"
     (= 2 (count bindings)) "exactly 2 forms in binding vector")
   (let [form (bindings 0) tst (bindings 1)]
     `(let [temp# ~tst]
        (if (nil? temp#)
          ~else
          (let [~form temp#]
            ~then))))))

(defmacro when-some
  "bindings => binding-form test
   When test is not nil, evaluates body with binding-form bound to the
   value of test"
  {:added "1.6"}
  [bindings & body]
  (assert-args
     (vector? bindings) "a vector for its binding"
     (= 2 (count bindings)) "exactly 2 forms in binding vector")
   (let [form (bindings 0) tst (bindings 1)]
    `(let [temp# ~tst]
       (if (nil? temp#)
         nil
         (let [~form temp#]
           ~@body)))))

(defn push-thread-bindings
  "WARNING: This is a low-level function. Prefer high-level macros like
  binding where ever possible.

  Takes a map of Var/value pairs. Binds each Var to the associated value for
  the current thread. Each call *MUST* be accompanied by a matching call to
  pop-thread-bindings wrapped in a try-finally!

      (push-thread-bindings bindings)
      (try
        ...
        (finally
          (pop-thread-bindings)))"
  {:added "1.1"}
  [bindings]
  (clojerl.Var/push_bindings bindings))

(defn pop-thread-bindings
  "Pop one set of bindings pushed with push-binding before. It is an error to
  pop bindings without pushing before."
  {:added "1.1"}
  []
  (clojerl.Var/pop_bindings))

(defn get-thread-bindings
  "Get a map with the Var/value pairs which is currently in effect for the
  current thread."
  {:added "1.1"}
  []
  (clojerl.Var/get_bindings_map))

(defmacro binding
  "binding => var-symbol init-expr

  Creates new bindings for the (already-existing) vars, with the
  supplied initial values, executes the exprs in an implicit do, then
  re-establishes the bindings that existed before.  The new bindings
  are made in parallel (unlike let); all init-exprs are evaluated
  before the vars are bound to their new values."
  {:added "1.0"}
  [bindings & body]
  (assert-args
    (vector? bindings) "a vector for its binding"
    (even? (count bindings)) "an even number of forms in binding vector")
  (let [var-ize (fn [var-vals]
                  (loop [ret [] vvs (seq var-vals)]
                    (if vvs
                      (recur  (conj (conj ret `(var ~(first vvs))) (second vvs))
                             (next (next vvs)))
                      (seq ret))))]
    `(let []
       (push-thread-bindings (hash-map ~@(var-ize bindings)))
       (try
         ~@body
         (finally
           (pop-thread-bindings))))))

(defn with-bindings*
  "Takes a map of Var/value pairs. Installs for the given Vars the associated
  values as thread-local bindings. Then calls f with the supplied arguments.
  Pops the installed bindings after f returned. Returns whatever f returns."
  {:added "1.1"}
  [binding-map f & args]
  (push-thread-bindings binding-map)
  (try
    (apply f args)
    (finally
      (pop-thread-bindings))))

(defmacro with-bindings
  "Takes a map of Var/value pairs. Installs for the given Vars the associated
  values as thread-local bindings. Then executes body. Pops the installed
  bindings after body was evaluated. Returns the value of body."
  {:added "1.1"}
  [binding-map & body]
  `(with-bindings* ~binding-map (fn [] ~@body)))

(defn bound-fn*
  "Returns a function, which will install the same bindings in effect as in
  the thread at the time bound-fn* was called and then call f with any given
  arguments. This may be used to define a helper function which runs on a
  different thread, but needs the same bindings in place."
  {:added "1.1"}
  [f]
  (let [bindings (get-thread-bindings)]
    (fn [& args]
      (apply with-bindings* bindings f args))))

(defmacro bound-fn
  "Returns a function defined by the given fntail, which will install the
  same bindings in effect as in the thread at the time bound-fn was called.
  This may be used to define a helper function which runs on a different
  thread, but needs the same bindings in place."
  {:added "1.1"}
  [& fntail]
  `(bound-fn* (fn ~@fntail)))

(defn find-var
  "Returns the global var named by the namespace-qualified symbol, or
  nil if no var with that name."
  {:added "1.0"}
  [sym] (clojerl.Var/find sym))

(defn binding-conveyor-fn
  {:private true
   :added "1.3"}
  [f]
  (let [frame (clojerl.Var/get_bindings)]
    (fn
      ([]
         (clojerl.Var/reset_bindings frame)
         (f))
      ([x]
         (clojerl.Var/reset_bindings frame)
         (f x))
      ([x y]
         (clojerl.Var/reset_bindings frame)
         (f x y))
      ([x y z]
         (clojerl.Var/reset_bindings frame)
         (f x y z))
      ([x y z & args]
         (clojerl.Var/reset_bindings frame)
         (apply f x y z args)))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Refs ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn ^{:private true}
  setup-reference [r options]
  (let [opts (apply hash-map options)]
    (when (:meta opts)
      (.reset_meta r (:meta opts)))
    (when (:validator opts)
      (.validator r (:validator opts)))
    r))

(defn agent
  "Creates and returns an agent with an initial value of state and
  zero or more options (in any order):

  :meta metadata-map

  :validator validate-fn

  :error-handler handler-fn

  :error-mode mode-keyword

  If metadata-map is supplied, it will become the metadata on the
  agent. validate-fn must be nil or a side-effect-free fn of one
  argument, which will be passed the intended new state on any state
  change. If the new state is unacceptable, the validate-fn should
  return false or throw an exception.  handler-fn is called if an
  action throws an exception or if validate-fn rejects a new state --
  see set-error-handler! for details.  The mode-keyword may be either
  :continue (the default if an error-handler is given) or :fail (the
  default if no error-handler is given) -- see set-error-mode! for
  details."
  {:added "1.0"
   }
  ([state & options]
   (let [a (new clojerl.Agent state)
         opts (apply hash-map options)]
     (setup-reference a options)
     (when (:error-handler opts)
       (.error_handler a (:error-handler opts)))
     (.error_mode a (or (:error-mode opts)
                        (if (:error-handler opts) :continue :fail)))
     a)))

(defn send-via
  "Dispatch an action to an agent. Returns the agent immediately.
  Subsequently, in a thread supplied by executor, the state of the agent
  will be set to the value of:

  (apply action-fn state-of-agent args)"
  {:added "1.5"}
  [a f & args]
  (.dispatch a (binding [*agent* a] (binding-conveyor-fn f)) args))

(defn send
  "Dispatch an action to an agent. Returns the agent immediately.
  Subsequently, in a thread from a thread pool, the state of the agent
  will be set to the value of:

  (apply action-fn state-of-agent args)"
  {:added "1.0"}
  [a f & args]
  (apply send-via a f args))

(defn send-off
  "Dispatch a potentially blocking action to an agent. Returns the
  agent immediately. Subsequently, in a separate thread, the state of
  the agent will be set to the value of:

  (apply action-fn state-of-agent args)"
  {:added "1.0"}
  [a f & args]
  (apply send-via a f args))

(defn release-pending-sends
  "Normally, actions sent directly or indirectly during another action
  are held until the action completes (changes the agent's
  state). This function can be used to dispatch any pending sent
  actions immediately. This has no impact on actions sent during a
  transaction, which are still held until commit. If no action is
  occurring, does nothing. Returns the number of actions dispatched."
  {:added "1.0"}
  []
  (clojerl.Agent/release_pending_sends))

(defn add-watch
  "Adds a watch function to an agent/atom/var/ref reference. The watch
  fn must be a fn of 4 args: a key, the reference, its old-state, its
  new-state. Whenever the reference's state might have been changed,
  any registered watches will have their functions called. The watch fn
  will be called synchronously, on the agent's thread if an agent,
  before any pending sends if agent or ref. Note that an atom's or
  ref's state may have changed again prior to the fn call, so use
  old/new-state rather than derefing the reference. Note also that watch
  fns may be called from multiple threads simultaneously. Var watchers
  are triggered only by root binding changes, not thread-local
  set!s. Keys must be unique per reference, and can be used to remove
  the watch with remove-watch, but are otherwise considered opaque by
  the watch mechanism."
  {:added "1.0"}
  [reference key fn]
  (throw "unimplemented watches")
  (.add_watch reference key fn))

(defn remove-watch
  "Removes a watch (set by add-watch) from a reference"
  {:added "1.0"}
  [reference key]
  (throw "unimplemented watches")
  (.remove_watch reference key))

(defn agent-error
  "Returns the exception thrown during an asynchronous action of the
  agent if the agent is failed.  Returns nil if the agent is not
  failed."
  {:added "1.2"}
  [a]
  (.error a))

(defn restart-agent
  "When an agent is failed, changes the agent state to new-state and
  then un-fails the agent so that sends are allowed again.  If
  a :clear-actions true option is given, any actions queued on the
  agent that were being held while it was failed will be discarded,
  otherwise those held actions will proceed.  The new-state must pass
  the validator if any, or restart will throw an exception and the
  agent will remain failed with its old state and error.  Watchers, if
  any, will NOT be notified of the new state.  Throws an exception if
  the agent is not failed."
  {:added "1.2"
   }
  [a, new-state & options]
  (let [opts (apply hash-map options)]
    (.restart a new-state (if (:clear-actions opts) true false))))

(defn set-error-handler!
  "Sets the error-handler of agent a to handler-fn.  If an action
  being run by the agent throws an exception or doesn't pass the
  validator fn, handler-fn will be called with two arguments: the
  agent and the exception."
  {:added "1.2"}
  [a, handler-fn]
  (.error_handler a handler-fn))

(defn error-handler
  "Returns the error-handler of agent a, or nil if there is none.
  See set-error-handler!"
  {:added "1.2"}
  [a]
  (.error_handler a))

(defn set-error-mode!
  "Sets the error-mode of agent a to mode-keyword, which must be
  either :fail or :continue.  If an action being run by the agent
  throws an exception or doesn't pass the validator fn, an
  error-handler may be called (see set-error-handler!), after which,
  if the mode is :continue, the agent will continue as if neither the
  action that caused the error nor the error itself ever happened.

  If the mode is :fail, the agent will become failed and will stop
  accepting new 'send' and 'send-off' actions, and any previously
  queued actions will be held until a 'restart-agent'.  Deref will
  still work, returning the state of the agent before the error."
  {:added "1.2"}
  [a, mode-keyword]
  (.error_mode a mode-keyword))

(defn error-mode
  "Returns the error-mode of agent a.  See set-error-mode!"
  {:added "1.2"}
  [a]
  (.error_mode a))

(defn agent-errors
  "DEPRECATED: Use 'agent-error' instead.
  Returns a sequence of the exceptions thrown during asynchronous
  actions of the agent."
  {:added "1.0"
   :deprecated "1.2"}
  [a]
  (when-let [e (agent-error a)]
    (list e)))

(defn clear-agent-errors
  "DEPRECATED: Use 'restart-agent' instead.
  Clears any exceptions thrown during asynchronous actions of the
  agent, allowing subsequent actions to occur."
  {:added "1.0"
   :deprecated "1.2"}
  [a]
  (restart-agent a (.deref a)))

(defn deref
  "Also reader macro: @ref/@agent/@var/@atom/@delay/@future/@promise. Within a transaction,
  returns the in-transaction-value of ref, else returns the
  most-recently-committed value of ref. When applied to a var, agent
  or atom, returns its current state. When applied to a delay, forces
  it if not already forced. When applied to a future, will block if
  computation not complete. When applied to a promise, will block
  until a value is delivered.  The variant taking a timeout can be
  used for blocking references (futures and promises), and will return
  timeout-val if the timeout (in milliseconds) is reached before a
  value is available. See also - realized?."
  {:added "1.0"}
  ([ref]
   (.deref ^clojerl.IDeref ref))
  ([ref timeout-ms timeout-val]
   (.deref ^clojerl.IBlockingDeref ref timeout-ms timeout-val)))

(defn atom
  "Creates and returns an Atom with an initial value of x and zero or
  more options (in any order):

  :meta metadata-map

  :validator validate-fn

  If metadata-map is supplied, it will become the metadata on the
  atom. validate-fn must be nil or a side-effect-free fn of one
  argument, which will be passed the intended new state on any state
  change. If the new state is unacceptable, the validate-fn should
  return false or throw an exception."
  {:added "1.0"}
  ([x]
   (new clojerl.Atom x))
  ([x & options] (setup-reference (atom x) options)))

(defn swap!
  "Atomically swaps the value of atom to be:
  (apply f current-value-of-atom args). Note that f may be called
  multiple times, and thus should be free of side effects.  Returns
  the value that was swapped in."
  {:added "1.0"}
  ([^clojerl.Atom atom f]
   (.swap atom f))
  ([^clojerl.Atom atom f x]
   (.swap atom f x))
  ([^clojerl.Atom atom f x y]
   (.swap atom f x y))
  ([^clojerl.Atom atom f x y & args]
   (.swap atom f x y args)))

(defn compare-and-set!
  "Atomically sets the value of atom to newval if and only if the
  current value of the atom is identical to oldval. Returns true if
  set happened, else false"
  {:added "1.0"}
  [^clojerl.Atom atom oldval newval]
  (.compare_and_set atom oldval newval))

(defn reset!
  "Sets the value of atom to newval without regard for the
  current value. Returns newval."
  {:added "1.0"}
  [^clojerl.Atom atom newval]
  (.reset atom newval))

(defn set-validator!
  "Sets the validator-fn for a var/agent/atom. validator-fn must be nil or a
  side-effect-free fn of one argument, which will be passed the intended
  new state on any state change. If the new state is unacceptable, the
  validator-fn should return false or throw an exception. If the current state (root
  value if var) is not acceptable to the new validator, an exception
  will be thrown and the validator will not be changed."
  {:added "1.0"}
  [iref validator-fn]
  (. iref (validator validator-fn)))

(defn get-validator
  "Gets the validator-fn for a var/agent/atom."
  {:added "1.0"}
  [iref]
  (. iref (validator)))

(defn alter-meta!
  "Atomically sets the metadata for a namespace/var/ref/agent/atom to be:

  (apply f its-current-meta args)

  f must be free of side-effects"
  {:added "1.0"}
  [^clojerl.IReference iref f & args]
  (.alter_meta iref f args))

(defn reset-meta!
  "Atomically resets the metadata for a namespace/var/ref/agent/atom"
  {:added "1.0"}
  [^clojerl.IReference iref metadata-map]
  (.reset_meta iref metadata-map))

(defn process-val!
  "Creates and returns a ProcessVal with an initial value of val."
  {:added "1.7"
   :tag clojerl.ProcessVal}
  [val]
  (clojerl.ProcessVal. val))

(defn vreset!
  "Sets the value of process-val to newval without regard for the
   current value. Returns newval."
  {:added "1.7"}
  [^clojerl.ProcessVal vol newval]
  (.reset vol newval))

(defmacro vswap!
  "Non-atomically swaps the value of the process-val as if:
   (apply f current-value-of-vol args). Returns the value that
   was swapped in."
  {:added "1.7"}
  [vol f & args]
  (let [v (with-meta vol {:tag 'clojerl.ProcessVal})]
    `(.reset ~v (~f (.deref ~v) ~@args))))

(defn process-val?
  "Returns true if x is a process-val."
  {:added "1.7"}
  [x]
  (instance? clojerl.ProcessVal x))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; fn stuff ;;;;;;;;;;;;;;;;

(defn comp
  "Takes a set of functions and returns a fn that is the composition
  of those fns.  The returned fn takes a variable number of args,
  applies the rightmost of fns to the args, the next
  fn (right-to-left) to the result, etc."
  {:added "1.0"}
  ([] identity)
  ([f] f)
  ([f g]
     (fn
       ([] (f (g)))
       ([x] (f (g x)))
       ([x y] (f (g x y)))
       ([x y z] (f (g x y z)))
       ([x y z & args] (f (apply g x y z args)))))
  ([f g & fs]
     (reduce comp (list* f g fs))))

(defn juxt
  "Takes a set of functions and returns a fn that is the juxtaposition
  of those fns.  The returned fn takes a variable number of args, and
  returns a vector containing the result of applying each fn to the
  args (left-to-right).
  ((juxt a b c) x) => [(a x) (b x) (c x)]"
  {:added "1.1"}
  ([f]
     (fn
       ([] [(f)])
       ([x] [(f x)])
       ([x y] [(f x y)])
       ([x y z] [(f x y z)])
       ([x y z & args] [(apply f x y z args)])))
  ([f g]
     (fn
       ([] [(f) (g)])
       ([x] [(f x) (g x)])
       ([x y] [(f x y) (g x y)])
       ([x y z] [(f x y z) (g x y z)])
       ([x y z & args] [(apply f x y z args) (apply g x y z args)])))
  ([f g h]
     (fn
       ([] [(f) (g) (h)])
       ([x] [(f x) (g x) (h x)])
       ([x y] [(f x y) (g x y) (h x y)])
       ([x y z] [(f x y z) (g x y z) (h x y z)])
       ([x y z & args] [(apply f x y z args) (apply g x y z args) (apply h x y z args)])))
  ([f g h & fs]
     (let [fs (list* f g h fs)]
       (fn
         ([] (reduce #(conj %1 (%2)) [] fs))
         ([x] (reduce #(conj %1 (%2 x)) [] fs))
         ([x y] (reduce #(conj %1 (%2 x y)) [] fs))
         ([x y z] (reduce #(conj %1 (%2 x y z)) [] fs))
         ([x y z & args] (reduce #(conj %1 (apply %2 x y z args)) [] fs))))))

(defn partial
  "Takes a function f and fewer than the normal arguments to f, and
  returns a fn that takes a variable number of additional args. When
  called, the returned function calls f with args + additional args."
  {:added "1.0"}
  ([f] f)
  ([f arg1]
   (fn
     ([] (f arg1))
     ([x] (f arg1 x))
     ([x y] (f arg1 x y))
     ([x y z] (f arg1 x y z))
     ([x y z & args] (apply f arg1 x y z args))))
  ([f arg1 arg2]
   (fn
     ([] (f arg1 arg2))
     ([x] (f arg1 arg2 x))
     ([x y] (f arg1 arg2 x y))
     ([x y z] (f arg1 arg2 x y z))
     ([x y z & args] (apply f arg1 arg2 x y z args))))
  ([f arg1 arg2 arg3]
   (fn
     ([] (f arg1 arg2 arg3))
     ([x] (f arg1 arg2 arg3 x))
     ([x y] (f arg1 arg2 arg3 x y))
     ([x y z] (f arg1 arg2 arg3 x y z))
     ([x y z & args] (apply f arg1 arg2 arg3 x y z args))))
  ([f arg1 arg2 arg3 & more]
   (fn [& args] (apply f arg1 arg2 arg3 (concat more args)))))

;;;;;;;;;;;;;;;;;;; sequence fns  ;;;;;;;;;;;;;;;;;;;;;;;

(defn sequence
  "Coerces coll to a (possibly empty) sequence, if it is not already
  one. Will not force a lazy seq. (sequence nil) yields (). When a
  transducer is supplied, returns a lazy sequence of applications of
  the transform to the items in coll(s), i.e. to the set of first
  items of each coll, followed by the set of second
  items in each coll, until any one of the colls is exhausted.  Any
  remaining items in other colls are ignored. The transform should accept
  number-of-colls arguments"
  {:added "1.0"}
  ([coll]
   (if (seq? coll) coll
       (or (seq coll) ())))
  ([xform coll]
   (lazy-seq
    (clojerl.TransducerSeq. xform coll)))
  ([xform coll & colls]
   (lazy-seq
    (clojerl.TransducerSeq. xform
                            (apply map list (cons coll colls))
                            true))))

(defn every?
  "Returns true if (pred x) is logical true for every x in coll, else
  false."
  {:tag clojerl.Boolean
   :added "1.0"}
  [pred coll]
  (cond
   (nil? (seq coll)) true
   (pred (first coll)) (recur pred (next coll))
   :else false))

(def
 ^{:tag clojerl.Boolean
   :doc "Returns false if (pred x) is logical true for every x in
  coll, else true."
   :arglists '([pred coll])
   :added "1.0"}
 not-every? (fn [pred coll] (not (every? pred coll))))

(defn some
  "Returns the first logical true value of (pred x) for any x in coll,
  else nil.  One common idiom is to use a set as pred, for example
  this will return :fred if :fred is in the sequence, otherwise nil:
  (some #{:fred} coll)"
  {:added "1.0"}
  [pred coll]
    (when (seq coll)
      (or (pred (first coll)) (recur pred (next coll)))))

(def
 ^{:tag clojerl.Boolean
   :doc "Returns false if (pred x) is logical true for any x in coll,
  else true."
   :arglists '([pred coll])
   :added "1.0"}
  not-any? (fn [pred coll] (not (some pred coll))))

;will be redefed later with arg checks
(defmacro dotimes
  "bindings => name n
  Repeatedly executes body (presumably for side-effects) with name
  bound to integers from 0 through n-1."
  {:added "1.0"}
  [bindings & body]
  (let [i (first bindings)
        n (second bindings)]
    `(let [n# ~n]
       (loop [~i 0]
         (when (< ~i n#)
           ~@body
           (recur (inc ~i)))))))

(defn map
  "Returns a lazy sequence consisting of the result of applying f to
  the set of first items of each coll, followed by applying f to the
  set of second items in each coll, until any one of the colls is
  exhausted.  Any remaining items in other colls are ignored. Function
  f should accept number-of-colls arguments. Returns a transducer when
  no collection is provided."
  {:added "1.0"}
  ([f]
    (fn [rf]
      (fn
        ([] (rf))
        ([result] (rf result))
        ([result input]
           (rf result (f input)))
        ([result input & inputs]
           (rf result (apply f input inputs))))))
  ([f coll]
   (lazy-seq
    (when-let [s (seq coll)]
      (if (chunked-seq? s)
        (let [^clojerl.TupleChunk c (chunk-first s)
              size (int (count c))
              b (loop [b (chunk-buffer size) i 0]
                  (if (< i size)
                    (recur (chunk-append b (f (.nth c i))) (inc i))
                    b))]
          (chunk-cons (chunk b) (map f (chunk-rest s))))
        (cons (f (first s)) (map f (rest s)))))))
  ([f c1 c2]
   (lazy-seq
    (let [s1 (seq c1) s2 (seq c2)]
      (when (and s1 s2)
        (cons (f (first s1) (first s2))
              (map f (rest s1) (rest s2)))))))
  ([f c1 c2 c3]
   (lazy-seq
    (let [s1 (seq c1) s2 (seq c2) s3 (seq c3)]
      (when (and  s1 s2 s3)
        (cons (f (first s1) (first s2) (first s3))
              (map f (rest s1) (rest s2) (rest s3)))))))
  ([f c1 c2 c3 & colls]
   (let [step (fn step [cs]
                 (lazy-seq
                  (let [ss (map seq cs)]
                    (when (every? identity ss)
                      (cons (map first ss) (step (map rest ss)))))))]
     (map #(apply f %) (step (conj colls c3 c2 c1))))))

(defmacro declare
  "defs the supplied var names with no bindings, useful for making forward declarations."
  {:added "1.0"}
  [& names] `(do ~@(map #(list 'def (vary-meta % assoc :declared true)) names)))

(declare cat)

(defn mapcat
  "Returns the result of applying concat to the result of applying map
  to f and colls.  Thus function f should return a collection. Returns
  a transducer when no collections are provided"
  {:added "1.0"}
  ([f] (comp (map f) cat))
  ([f & colls]
     (apply concat (apply map f colls))))

(defn filter
  "Returns a lazy sequence of the items in coll for which
  (pred item) returns true. pred must be free of side-effects.
  Returns a transducer when no collection is provided."
  {:added "1.0"}
  ([pred]
    (fn [rf]
      (fn
        ([] (rf))
        ([result] (rf result))
        ([result input]
           (if (pred input)
             (rf result input)
             result)))))
  ([pred coll]
   (lazy-seq
    (when-let [s (seq coll)]
      (if (chunked-seq? s)
        (let [^clojerl.TupleChunk c (chunk-first s)
              size (count c)
              b (loop [b (chunk-buffer size) i 0]
                  (if (< i size)
                    (let [v (.nth c i)]
                      (recur (if (pred v) (chunk-append b v) b)
                             (inc i)))
                    b))]
          (chunk-cons (chunk b) (filter pred (chunk-rest s))))
        (let [f (first s) r (rest s)]
          (if (pred f)
            (cons f (filter pred r))
            (filter pred r))))))))

(defn remove
  "Returns a lazy sequence of the items in coll for which
  (pred item) returns false. pred must be free of side-effects.
  Returns a transducer when no collection is provided."
  {:added "1.0"}
  ([pred] (filter (complement pred)))
  ([pred coll]
     (filter (complement pred) coll)))

(defn reduced
  "Wraps x in a way such that a reduce will terminate with the value x"
  {:added "1.5"}
  [x]
  (new clojerl.Reduced x))

(defn reduced?
  "Returns true if x is the result of a call to reduced"
  {:inline '(fn* [x] `(clojerl.Reduced/is_reduced ~x))
   :inline-arities #{1}
   :added "1.5"}
  [x]
  (clojerl.Reduced/is_reduced x))

(defn ensure-reduced
  "If x is already reduced?, returns it, else returns (reduced x)"
  {:added "1.7"}
  [x]
  (if (reduced? x) x (reduced x)))

(defn unreduced
  "If x is reduced?, returns (deref x), else returns x"
  {:added "1.7"}
  [x]
  (if (reduced? x) (deref x) x))

(defn take
  "Returns a lazy sequence of the first n items in coll, or all items if
  there are fewer than n.  Returns a stateful transducer when
  no collection is provided."
  {:added "1.0"}
  ([n]
     (fn [rf]
       (let [nv (process-val! n)]
         (fn
           ([] (rf))
           ([result]
              (.destroy nv)
              (rf result))
           ([result input]
              (let [n @nv
                    nn (vswap! nv dec)
                    result (if (pos? n)
                             (rf result input)
                             result)]
                (if (not (pos? nn))
                  (ensure-reduced result)
                  result)))))))
  ([n coll]
     (lazy-seq
      (when (pos? n)
        (when-let [s (seq coll)]
          (cons (first s) (take (dec n) (rest s))))))))

(defn take-while
  "Returns a lazy sequence of successive items from coll while
  (pred item) returns true. pred must be free of side-effects.
  Returns a transducer when no collection is provided."
  {:added "1.0"}
  ([pred]
     (fn [rf]
       (fn
         ([] (rf))
         ([result] (rf result))
         ([result input]
            (if (pred input)
              (rf result input)
              (reduced result))))))
  ([pred coll]
     (lazy-seq
      (when-let [s (seq coll)]
        (when (pred (first s))
          (cons (first s) (take-while pred (rest s))))))))

(defn drop
  "Returns a lazy sequence of all but the first n items in coll.
  Returns a stateful transducer when no collection is provided."
  {:added "1.0"}
  ([n]
     (fn [rf]
       (let [nv (process-val! n)]
         (fn
           ([] (rf))
           ([result]
              (.destroy nv)
              (rf result))
           ([result input]
              (let [n @nv]
                (vswap! nv dec)
                (if (pos? n)
                  result
                  (rf result input))))))))
  ([n coll]
     (let [step (fn [n coll]
                  (let [s (seq coll)]
                    (if (and (pos? n) s)
                      (recur (dec n) (rest s))
                      s)))]
       (lazy-seq (step n coll)))))

(defn drop-last
  "Return a lazy sequence of all but the last n (default 1) items in coll"
  {:added "1.0"}
  ([s] (drop-last 1 s))
  ([n s] (map (fn [x _] x) s (drop n s))))

(defn take-last
  "Returns a seq of the last n items in coll.  Depending on the type
  of coll may be no better than linear time.  For vectors, see also subvec."
  {:added "1.1"}
  [n coll]
  (loop [s (seq coll), lead (seq (drop n coll))]
    (if lead
      (recur (next s) (next lead))
      s)))

(defn drop-while
  "Returns a lazy sequence of the items in coll starting from the
  first item for which (pred item) returns logical false.  Returns a
  stateful transducer when no collection is provided."
  {:added "1.0"}
  ([pred]
     (fn [rf]
       (let [dv (process-val! true)]
         (fn
           ([] (rf))
           ([result]
              (.destroy dv)
              (rf result))
           ([result input]
              (let [drop? @dv]
                (if (and drop? (pred input))
                  result
                  (do
                    (vreset! dv nil)
                    (rf result input)))))))))
  ([pred coll]
     (let [step (fn [pred coll]
                  (let [s (seq coll)]
                    (if (and s (pred (first s)))
                      (recur pred (rest s))
                      s)))]
       (lazy-seq (step pred coll)))))

(defn cycle
  "Returns a lazy (infinite!) sequence of repetitions of the items in coll."
  {:added "1.0"}
  [coll]
  (clojerl.Cycle. (seq coll)))

(defn split-at
  "Returns a vector of [(take n coll) (drop n coll)]"
  {:added "1.0"}
  [n coll]
    [(take n coll) (drop n coll)])

(defn split-with
  "Returns a vector of [(take-while pred coll) (drop-while pred coll)]"
  {:added "1.0"}
  [pred coll]
    [(take-while pred coll) (drop-while pred coll)])

(defn repeat
  "Returns a lazy (infinite!, or length n if supplied) sequence of xs."
  {:added "1.0"}
  ([x] (clojerl.Repeat. x))
  ([n x] (clojerl.Repeat. n x)))

(defn replicate
  "DEPRECATED: Use 'repeat' instead.
   Returns a lazy seq of n xs."
  {:added "1.0"
   :deprecated "1.3"}
  [n x] (take n (repeat x)))

(defn iterate
  "Returns a lazy sequence of x, (f x), (f (f x)) etc. f must be free of side-effects"
  {:added "1.0"}
  [f x] (clojerl.Iterate. f x))

(defn range
  "Returns a lazy seq of nums from start (inclusive) to end
  (exclusive), by step, where start defaults to 0, step to 1, and end to
  infinity. When step is equal to 0, returns an infinite sequence of
  start. When start is equal to end, returns empty list."
  {:added "1.0"}
  ([] (iterate inc 0))
  ([end] (range 0 end 1))
  ([start end] (range start end 1))
  ([start end step]
   (new clojerl.Range start end step)))

(defn merge
  "Returns a map that consists of the rest of the maps conj-ed onto
  the first.  If a key occurs in more than one map, the mapping from
  the latter (left-to-right) will be the mapping in the result."
  {:added "1.0"}
  [& maps]
  (when (some identity maps)
    (reduce #(conj (or %1 {}) %2) maps)))

(defn merge-with
  "Returns a map that consists of the rest of the maps conj-ed onto
  the first.  If a key occurs in more than one map, the mapping(s)
  from the latter (left-to-right) will be combined with the mapping in
  the result by calling (f val-in-result val-in-latter)."
  {:added "1.0"}
  [f & maps]
  (when (some identity maps)
    (let [merge-entry (fn [m e]
                        (let [k (key e) v (val e)]
                          (if (contains? m k)
                            (assoc m k (f (get m k) v))
                            (assoc m k v))))
          merge2 (fn [m1 m2]
                   (reduce merge-entry (or m1 {}) (seq m2)))]
      (reduce merge2 maps))))



(defn zipmap
  "Returns a map with the keys mapped to the corresponding vals."
  {:added "1.0"}
  [keys vals]
    (loop [map {}
           ks (seq keys)
           vs (seq vals)]
      (if (and ks vs)
        (recur (assoc map (first ks) (first vs))
               (next ks)
               (next vs))
        map)))

(defn line-seq
  "Returns the lines of text from rdr as a lazy sequence of strings.
  rdr must implement erlang.io.IReader."
  {:added "1.0"}
  [rdr]
  (let [line (erlang.io.IReader/read_line rdr)]
    (when (string? line)
      (cons line (lazy-seq (line-seq rdr))))))

(defn comparator
  "Returns an comparator function based upon pred."
  {:added "1.0"}
  [pred]
  (fn [x y]
    (cond (pred x y) -1 (pred y x) 1 :else 0)))

(defn sort
  "Returns a sorted sequence of the items in coll. If no comparator is
  supplied, uses compare. Guaranteed to be stable: equal elements will
  not be reordered."
  {:added "1.0"}
  ([coll]
   (sort compare coll))
  ([comp coll]
   (if (seq coll)
     (lists/sort (clj_rt/compare_fun comp :erlang) (clj_rt/to_list coll))
     ())))

(defn sort-by
  "Returns a sorted sequence of the items in coll, where the sort
  order is determined by comparing (keyfn item).  If no comparator is
  supplied, uses compare.  comparator must implement
  java.util.Comparator.  Guaranteed to be stable: equal elements will
  not be reordered."
  {:added "1.0"}
  ([keyfn coll]
   (sort-by keyfn compare coll))
  ([keyfn comp coll]
   (sort (fn [x y] (comp (keyfn x) (keyfn y))) coll)))

(defn dorun
  "When lazy sequences are produced via functions that have side
  effects, any effects other than those needed to produce the first
  element in the seq do not occur until the seq is consumed. dorun can
  be used to force any effects. Walks through the successive nexts of
  the seq, does not retain the head and returns nil."
  {:added "1.0"}
  ([coll]
   (when-let [s (seq coll)]
     (recur (next s))))
  ([n coll]
   (when (and (seq coll) (pos? n))
     (recur (dec n) (next coll)))))

(defn doall
  "When lazy sequences are produced via functions that have side
  effects, any effects other than those needed to produce the first
  element in the seq do not occur until the seq is consumed. doall can
  be used to force any effects. Walks through the successive nexts of
  the seq, retains the head and returns it, thus causing the entire
  seq to reside in memory at one time."
  {:added "1.0"}
  ([coll]
   (loop [coll (seq coll)
          acc #erl()]
     (if coll
       (recur (next coll) (conj acc (first coll)))
       (lists/reverse acc))))
  ([n coll]
   (loop [coll (seq coll)
          acc #erl()
          n n]
     (if (and coll (pos? n))
       (let [x    (first coll)
             coll (next coll)]
         (recur coll (conj acc x) (dec n)))
       (lists/reverse acc)))))

(defn nthnext
  "Returns the nth next of coll, (seq coll) when n is 0."
  {:added "1.0"}
  [coll n]
    (loop [n n xs (seq coll)]
      (if (and xs (pos? n))
        (recur (dec n) (next xs))
        xs)))

(defn nthrest
  "Returns the nth rest of coll, coll when n is 0."
  {:added "1.3"}
  [coll n]
    (loop [n n xs coll]
      (if-let [xs (and (pos? n) (seq xs))]
        (recur (dec n) (rest xs))
        xs)))

(defn partition
  "Returns a lazy sequence of lists of n items each, at offsets step
  apart. If step is not supplied, defaults to n, i.e. the partitions
  do not overlap. If a pad collection is supplied, use its elements as
  necessary to complete last partition upto n items. In case there are
  not enough padding elements, return a partition with less than n items."
  {:added "1.0"}
  ([n coll]
     (partition n n coll))
  ([n step coll]
     (lazy-seq
       (when-let [s (seq coll)]
         (let [p (doall (take n s))]
           (when (= n (count p))
             (cons p (partition n step (nthrest s step))))))))
  ([n step pad coll]
     (lazy-seq
       (when-let [s (seq coll)]
         (let [p (doall (take n s))]
           (if (= n (count p))
             (cons p (partition n step pad (nthrest s step)))
             (list (take n (concat p pad)))))))))

;; evaluation

(defn eval
  "Evaluates the form data structure (not text!) and returns the result."
  {:added "1.0"}
  [form]
  (first (clj_compiler/eval form)))

(defmacro doseq
  "Repeatedly executes body (presumably for side-effects) with
  bindings and filtering as provided by \"for\".  Does not retain
  the head of the sequence. Returns nil."
  {:added "1.0"}
  [seq-exprs & body]
  (assert-args
     (vector? seq-exprs) "a vector for its binding"
     (even? (count seq-exprs)) "an even number of forms in binding vector")
  (let [step (fn step [recform exprs]
               (if-not exprs
                 [true `(do ~@body)]
                 (let [k (first exprs)
                       v (second exprs)]
                   (if (keyword? k)
                     (let [steppair (step recform (nnext exprs))
                           needrec (steppair 0)
                           subform (steppair 1)]
                       (cond
                         (= k :let) [needrec `(let ~v ~subform)]
                         (= k :while) [false `(when ~v
                                                ~subform
                                                ~@(when needrec [recform]))]
                         (= k :when) [false `(if ~v
                                               (do
                                                 ~subform
                                                 ~@(when needrec [recform]))
                                               ~recform)]))
                     (let [seq- (gensym "seq_")
                           chunk- (with-meta (gensym "chunk_")
                                             {:tag clojerl.IChunk})
                           count- (gensym "count_")
                           i- (gensym "i_")
                           recform `(recur (next ~seq-) nil 0 0)
                           steppair (step recform (nnext exprs))
                           needrec (steppair 0)
                           subform (steppair 1)
                           recform-chunk
                             `(recur ~seq- ~chunk- ~count- (inc ~i-))
                           steppair-chunk (step recform-chunk (nnext exprs))
                           subform-chunk (steppair-chunk 1)]
                       [true
                        `(loop [~seq- (seq ~v), ~chunk- nil,
                                ~count- 0, ~i- 0]
                           (if (< ~i- ~count-)
                             (let [~k (clj_rt/nth ~chunk- ~i-)]
                               ~subform-chunk
                               ~@(when needrec [recform-chunk]))
                             (when-let [~seq- (seq ~seq-)]
                               (if (chunked-seq? ~seq-)
                                 (let [c# (chunk-first ~seq-)]
                                   (recur (chunk-rest ~seq-) c#
                                          (int (count c#)) (int 0)))
                                 (let [~k (first ~seq-)]
                                   ~subform
                                   ~@(when needrec [recform]))))))])))))]
    (nth (step nil (seq seq-exprs)) 1)))


(defn await
  "Blocks the current thread (indefinitely!) until all actions
  dispatched thus far, from this thread or agent, to the agent(s) have
  occurred.  Will block on failed agents.  Will never return if
  a failed agent is restarted with :clear-actions true."
  {:added "1.0"}
  [& agents]
  (when *agent*
    (throw (new clojerl.Error "Can't await in agent action")))
  (let [latch (new erlang.util.CountDownLatch (count agents))
        count-down (fn [agent] (. latch (count_down)) agent)]
    (doseq [a agents]
      (send a count-down))
    (. latch (await))))

(defn await-for
  "Blocks the current thread until all actions dispatched thus
  far (from this thread or agent) to the agents have occurred, or the
  timeout (in milliseconds) has elapsed. Returns logical false if
  returning due to timeout, logical true otherwise."
  {:added "1.0"}
  [timeout-ms & agents]
  (when *agent*
    (throw (new clojerl.Error "Can't await in agent action")))
  (let [latch (new erlang.util.CountDownLatch (count agents))
        count-down (fn [agent] (. latch (count_down)) agent)]
    (doseq [a agents]
      (send a count-down))
    (. latch (await timeout-ms))))

(defmacro dotimes
  "bindings => name n

  Repeatedly executes body (presumably for side-effects) with name
  bound to integers from 0 through n-1."
  {:added "1.0"}
  [bindings & body]
  (assert-args
     (vector? bindings) "a vector for its binding"
     (= 2 (count bindings)) "exactly 2 forms in binding vector")
  (let [i (first bindings)
        n (second bindings)]
    `(let [n# ~n]
       (loop [~i 0]
         (when (< ~i n#)
           ~@body
           (recur (inc ~i)))))))

#_(defn into
  "Returns a new coll consisting of to-coll with all of the items of
  from-coll conjoined."
  {:added "1.0"}
  [to from]
    (let [ret to items (seq from)]
      (if items
        (recur (conj ret (first items)) (next items))
        ret)))

;redef into with batch support
(defn ^:private into
  "Returns a new coll consisting of to-coll with all of the items of
  from-coll conjoined."
  {:added "1.0"}
  [to from]
  (reduce conj to from))

(defmacro import
  "import-list => (ns-symbol type-name-symbols*)

  For each name in type-name-symbols, adds a mapping from name to the
  type named by package.name to the current namespace. Use :import in the ns
  macro in preference to calling this directly."
  {:added "1.0"}
  [& import-symbols-or-lists]
  (let [specs (map #(if (and (seq? %) (= 'quote (first %))) (second %) %)
                   import-symbols-or-lists)]
    `(do ~@(map #(list 'import* %)
                (reduce (fn [v spec]
                           (if (symbol? spec)
                             (conj v (name spec))
                             (let [p (first spec) cs (rest spec)]
                               (into v (map #(str p "." %) cs)))))
                         [] specs)))))

(defn clj->erl
  "Returns the Erlang representation of x when it implements IEncodeErlang,
  otherwise returns x unchanged. When x is a collection the conversion can
  be applied recursively, which is the default behavior."
  {:added "1.0"}
  ([x] (clj->erl x true))
  ([x recursive?]
   (clj_rt/clj->erl x recursive?)))

(defn erl->clj
  "Returns the Clojure representation of x when it implements IEncodeClojure,
  otherwise returns x unchanged. When x is a collection the conversion can
  be applied recursively, which is the default behavior."
  {:added "1.0"}
  ([x] (erl->clj x true))
  ([x recursive?]
   (clj_rt/erl->clj x recursive?)))

(defn into-tuple
  "Returns a tuple with components set to the values in aseq."
  {:added "1.0"}
  ([aseq]
   (-> (seq aseq) clj_rt/to_list.1 erlang/list_to_tuple.1))
  ([type aseq]
   (-> (seq aseq) clj_rt/to_list.1 erlang/list_to_tuple.1)))

(defn tuple
  "Returns a tuple with items."
  {:added "1.8"}
  [& items]
  (into-tuple items))

(defn type
  "Returns x's erlang.Type"
  {:added "1.0"}
  [x]
  (when-not (nil? x)
    (clj_rt/type x)))

(defn num
  "Coerce to Number"
  {:tag clojerl.Integer
   :inline '(fn* [x]
              `(if (erlang/is_number ~x)
                 ~x
                 (throw (clojerl.BadArgumentError. "Not a number"))))
   :added "1.0"}
  [x]
  (if (erlang/is_number x)
    x
    (throw (clojerl.BadArgumentError. "Not a number"))))

(defn float
  "Coerce to float"
  {:inline '(fn* [x] `(erlang/float ~x))
   :added "1.0"}
  [x]
  (erlang/float x))

(defn short
  "Coerce to short"
  {:inline '(fn* [x] `(clj_rt/short ~x))
   :added "1.0"}
  [x]
  (clj_rt/short x))

(defn byte
  "Coerce to byte"
  {:inline '(fn* [x] `(clj_rt/byte ~x))
   :added "1.0"}
  [x]
  (clj_rt/byte x))

(defn char
  "Coerce to char"
  {:inline '(fn* [x] `(clj_rt/char ~x))
   :added "1.1"}
  [x]
  (clj_rt/char x))

(defn boolean
  "Coerce to boolean"
  {:inline '(fn* [x] `(clj_rt/boolean ~x))
   :added "1.0"}
  [x] (clj_rt/boolean x))

(defn ident?
  "Return true if x is a symbol or keyword"
  {:added "1.9"}
  [x] (or (keyword? x) (symbol? x)))

(defn simple-ident?
  "Return true if x is a symbol or keyword without a namespace"
  {:added "1.9"}
  [x] (and (ident? x) (nil? (namespace x))))

(defn qualified-ident?
  "Return true if x is a symbol or keyword with a namespace"
  {:added "1.9"}
  [x] (boolean (and (ident? x) (namespace x) true)))

(defn simple-symbol?
  "Return true if x is a symbol without a namespace"
  {:added "1.9"}
  [x] (and (symbol? x) (nil? (namespace x))))

(defn qualified-symbol?
  "Return true if x is a symbol with a namespace"
  {:added "1.9"}
  [x] (boolean (and (symbol? x) (namespace x) true)))

(defn simple-keyword?
  "Return true if x is a keyword without a namespace"
  {:added "1.9"}
  [x] (and (keyword? x) (nil? (namespace x))))

(defn qualified-keyword?
  "Return true if x is a keyword with a namespace"
  {:added "1.9"}
  [x] (boolean (and (keyword? x) (namespace x) true)))

(defn number?
  "Returns true if x is a Number"
  {:inline '(fn* [x] `(erlang/is_number ~x))
   :added "1.0"}
  [x]
  (erlang/is_number x))

(defn mod
  "Modulus of num and div. Truncates toward negative infinity."
  {:added "1.0"}
  [num div]
  (let [m (rem num div)]
    (if (or (zero? m) (= (pos? num) (pos? div)))
      m
      (+ m div))))

(defn float?
  "Returns true if n is a floating point number"
  {:added "1.0"}
  [n]
  (erlang/is_float n))

(defn rational?
  "Returns true if n is a rational number"
  {:added "1.0"}
  [n]
  (integer? n))

(def ^:dynamic ^{:private true} print-initialized false)

(defmulti print-method (fn [x writer]
                         (let [t (get (meta x) :type)]
                           (if (keyword? t) t (type x)))))
(defmulti print-dup (fn [x writer] (type x)))

(defn pr-on
  {:private true}
  [x w]
  (if *print-dup*
    (print-dup x w)
    (print-method x w))
  nil)

(defn pr
  "Prints the object(s) to the output stream that is the current value
  of *out*.  Prints the object(s), separated by spaces if there is
  more than one.  By default, pr and prn print in a way that objects
  can be read by the reader"
  {:dynamic true
   :added "1.0"}
  ([] nil)
  ([x]
   (pr-on x *out*))
  ([x & more]
   (pr x)
   (erlang.io.IWriter/write *out* \space)
   (if-let [nmore (next more)]
     (recur (first more) nmore)
     (apply pr more))))

(def ^:private ^clojerl.String system-newline
  (erlang/list_to_binary (io_lib/nl)))

(defn newline
  "Writes a platform-specific newline to *out*"
  {:added "1.0"}
  []
  (erlang.io.IWriter/write *out* system-newline) nil)

(defn flush
  "Flushes the output stream that is the current value of
  *out*"
  {:added "1.0"}
  []
  (erlang.io.IWriter/write *out* "") nil)

(defn prn
  "Same as pr followed by (newline). Observes *flush-on-newline*"
  {:added "1.0"}
  [& more]
  (apply pr more)
  (newline)
  (when *flush-on-newline*
    (flush)))

(defn print
  "Prints the object(s) to the output stream that is the current value
  of *out*.  print and println produce output for human consumption."
  {:added "1.0"}
  [& more]
  (binding [*print-readably* nil]
    (apply pr more)))

(defn println
  "Same as print followed by (newline)"
  {:added "1.0"}
  [& more]
  (binding [*print-readably* nil]
    (apply prn more)))

(defn read
  "Reads the next object from stream, which must be an instance of
  erlang.io.PushbackReader or some derivee.  stream defaults to the
  current value of *in*.

  Opts is a persistent map with valid keys:
    :read-cond - :allow to process reader conditionals, or
                 :preserve to keep all branches
    :features - persistent set of feature keywords for reader conditionals
    :eof - on eof, return value unless :eofthrow, then throw.
           if not specified, will throw

  Note that read can execute code (controlled by *read-eval*),
  and as such should be used only with trusted sources.

  For data structure interop use clojure.edn/read"
  {:added "1.0"}
  ([]
   (read *in*))
  ([stream]
   (read stream true nil))
  ([stream eof-error? eof-value]
   (read {:eof (if eof-error? :eofthrow eof-value)}
         stream))
  ([opts stream]
   (clj_reader/read ""
                    (clj->erl (assoc opts :io-reader stream)))))

(defn read-line
  "Reads the next line from stream that is the current value of *in* ."
  {:added "1.0"}
  []
  (erlang.io.IReader/read_line *in*))

(defn read-string
  "Reads one object from the string s. Optionally include reader
  options, as specified in read.

  Note that read-string can execute code (controlled by *read-eval*),
  and as such should be used only with trusted sources.

  For data structure interop use clojure.edn/read-string"
  {:added "1.0"}
  ([s] (clj_reader/read s))
  ([opts s] (clj_reader/read s (clj->erl opts))))

(defn subvec
  "Returns a persistent vector of the items in vector from
  start (inclusive) to end (exclusive).  If end is not supplied,
  defaults to (count vector). This operation is O(1) and very fast, as
  the resulting vector shares structure with the original and no
  trimming is done."
  {:added "1.0"}
  ([v start]
   (subvec v start (count v)))
  ([v start end]
   (clj_rt/subvec v start end)))

(defmacro with-open
  "bindings => [name init ...]

  Evaluates body in a try expression with names bound to the values
  of the inits, and a finally clause that calls (.close name) on each
  name in reverse order."
  {:added "1.0"}
  [bindings & body]
  (assert-args
     (vector? bindings) "a vector for its binding"
     (even? (count bindings)) "an even number of forms in binding vector")
  (cond
    (= (count bindings) 0) `(do ~@body)
    (symbol? (bindings 0)) `(let ~(subvec bindings 0 2)
                              (try
                                (with-open ~(subvec bindings 2) ~@body)
                                (finally
                                  (erlang.io.ICloseable/close ~(bindings 0)))))
    :else (throw (clojerl.BadArgumentError. "with-open only allows Symbols in bindings"))))

(defmacro doto
  "Evaluates x then calls all of the methods and functions with the
  value of x supplied at the front of the given arguments.  The forms
  are evaluated in order.  Returns x.

  (doto (new erlang.util.Regex) str (.quote))"
  {:added "1.0"}
  [x & forms]
    (let [gx (gensym)]
      `(let [~gx ~x]
         ~@(map (fn [f]
                  (if (seq? f)
                    `(~(first f) ~gx ~@(next f))
                    `(~f ~gx)))
                forms)
         ~gx)))

(defmacro memfn
  "Expands into code that creates a fn that expects to be passed an
  object and any args and calls the named instance method on the
  object passing the args. name may be type-hinted with the method
  receiver's type in order to avoid reflective calls."
  {:added "1.0"}
  [name & args]
  (let [t (with-meta (gensym "target")
            (meta name))]
    `(fn [~t ~@args]
       (. ~t (~name ~@args)))))

(defmacro time
  "Evaluates expr and prints the time it took.  Returns the value of
 expr."
  {:added "1.0"}
  [expr]
  `(let [start# (erlang/monotonic_time :nano_seconds)
         ret#   ~expr
         stop#  (erlang/monotonic_time :nano_seconds)]
     (prn (str "Elapsed time: "
               (/ (- stop# start#) 1000000.0)
               " msecs"))
     ret#))

(defn macroexpand-1
  "If form represents a macro form, returns its expansion,
  else returns form."
  {:added "1.0"}
  [form]
  (clj_analyzer/macroexpand_1 form nil))

(defn macroexpand
  "Repeatedly calls macroexpand-1 on form until it no longer
  represents a macro form, then returns it.  Note neither
  macroexpand-1 nor macroexpand expand macros in subforms."
  {:added "1.0"}
  [form]
    (let [ex (macroexpand-1 form)]
      (if (identical? ex form)
        form
        (macroexpand ex))))

(defn load-reader
  "Sequentially read and evaluate the set of forms contained in the
  stream/file"
  {:added "1.0"}
  [rdr]
  (clj_compiler/load rdr))

(defn load-string
  "Sequentially read and evaluate the set of forms contained in the
  string"
  {:added "1.0"}
  [s]
  (clj_compiler/load_string s))

(defn set?
  "Returns true if x implements IPersistentSet"
  {:added "1.0"}
  [x] (satisfies? clojerl.ISet x))

(defn set
  "Returns a set of the distinct elements of coll."
  {:added "1.0"}
  [coll]
  (if (set? coll)
    (with-meta coll nil)
    (clj_rt/hash_set (clj_rt/to_list coll))))

(defn ^{:private true}
  filter-key [keyfn pred amap]
    (loop [ret {} es (seq amap)]
      (if es
        (if (pred (keyfn (first es)))
          (recur (assoc ret (key (first es)) (val (first es))) (next es))
          (recur ret (next es)))
        ret)))

(defn find-ns
  "Returns the namespace named by the symbol or nil if it doesn't exist."
  {:added "1.0"}
  [sym] (clojerl.Namespace/find sym))

(defn create-ns
  "Create a new namespace named by the symbol if one doesn't already
  exist, returns it or the already-existing namespace of the same
  name."
  {:added "1.0"}
  [sym]
  (clojerl.Namespace/find_or_create sym))

(defn remove-ns
  "Removes the namespace named by the symbol. Use with caution.
  Cannot be used to remove the clojure namespace."
  {:added "1.0"}
  [sym]
  (clojerl.Namespace/remove sym))

(defn all-ns
  "Returns a sequence of all namespaces."
  {:added "1.0"}
  [] (clojerl.Namespace/all))

(defn the-ns
  "If passed a namespace, returns it. Else, when passed a symbol,
  returns the namespace named by it, throwing an exception if not
  found."
  {:added "1.0"
   :tag clojerl.Namespace}
  [x]
  (if-not (symbol? x)
    x
    (or (find-ns x) (throw (clojerl.Error. (str "No namespace: " x " found"))))))

(defn ns-name
  "Returns the name of the namespace, a symbol."
  {:added "1.0"}
  [ns]
  (.name (the-ns ns)))

(defn ns-map
  "Returns a map of all the mappings for the namespace."
  {:added "1.0"}
  [ns]
  (.get_mappings (the-ns ns)))

(defn ns-unmap
  "Removes the mappings for the symbol from the namespace."
  {:added "1.0"}
  [ns sym]
  (.unmap (the-ns ns) sym))

;(defn export [syms]
;  (doseq [sym syms]
;   (.. *ns* (intern sym) (setExported true))))

(defn ns-publics
  "Returns a map of the public intern mappings for the namespace."
  {:added "1.0"}
  [ns]
  (let [ns (the-ns ns)]
    (filter-key val (fn [v] (and (instance? clojerl.Var v)
                                (identical? ns (find-ns (symbol (namespace v))))
                                (clojerl.Var/is_public v)))
                (ns-map ns))))

(defn ns-imports
  "Returns a map of the import mappings for the namespace."
  {:added "1.0"}
  [ns]
  (filter-key val (partial instance? erlang.Type) (ns-map ns)))

(defn ns-interns
  "Returns a map of the intern mappings for the namespace."
  {:added "1.0"}
  [ns]
  (let [ns (the-ns ns)]
    (filter-key val (fn [v]
                      (and (instance? clojerl.Var v)
                           (= ns (find-ns (symbol (namespace v))))))
                (ns-map ns))))

(defn refer
  "refers to all public vars of ns, subject to filters.
  filters can include at most one each of:

  :exclude list-of-symbols
  :only list-of-symbols
  :rename map-of-fromsymbol-tosymbol

  For each public interned var in the namespace named by the symbol,
  adds a mapping from the name of the var to the var to the current
  namespace.  Throws an exception if name is already mapped to
  something else in the current namespace. Filters can be used to
  select a subset, via inclusion or exclusion, or to provide a mapping
  to a symbol different from the var's name, in order to prevent
  clashes. Use :use in the ns macro in preference to calling this directly."
  {:added "1.0"}
  [ns-sym & filters]
  (let [ns (or (find-ns ns-sym) (throw (clojerl.Error. (str "No namespace: " ns-sym))))
        fs (apply hash-map filters)
        nspublics (ns-publics ns)
        rename (or (:rename fs) {})
        exclude (set (:exclude fs))
        to-do (if (= :all (:refer fs))
                (map symbol (keys nspublics))
                (or (:refer fs) (:only fs) (map symbol (keys nspublics))))]
    (when (and to-do (not (satisfies? clojerl.ISequential to-do)))
      (throw (clojerl.Error. ":only/:refer value must be a sequential collection of symbols")))
    ;; keys in maps are strings to avoid be able to use the underlying map
    ;; implementation. We convert all to-do's to strings since some filters
    ;; could contains symbols
    (doseq [sym to-do]
      (when-not (exclude sym)
        (let [v   (nspublics (name sym))]
          (when-not v
            (throw (clojerl.IllegalAccessError. (if (get (ns-interns ns) (name sym))
                                                  (str sym " is not public")
                                                  (str sym " does not exist")))))
          (.refer *ns* (or (rename sym) sym) v))))))

(defn ns-refers
  "Returns a map of the refer mappings for the namespace."
  {:added "1.0"}
  [ns]
  (let [ns (the-ns ns)]
    (filter-key val (fn [v] (and (instance? clojerl.Var v)
                                (not= ns (find-ns (symbol (namespace v))))))
                (ns-map ns))))

(defn alias
  "Add an alias in the current namespace to another
  namespace. Arguments are two symbols: the alias to be used, and
  the symbolic name of the target namespace. Use :as in the ns macro in preference
  to calling this directly."
  {:added "1.0"}
  [alias namespace-sym]
  (.add_alias *ns* alias (the-ns namespace-sym)))

(defn ns-aliases
  "Returns a map of the aliases for the namespace."
  {:added "1.0"}
  [ns]
  (.get_aliases (the-ns ns)))

(defn ns-unalias
  "Removes the alias for the symbol from the namespace."
  {:added "1.0"}
  [ns sym]
  (.remove_alias (the-ns ns) sym))

(defn take-nth
  "Returns a lazy seq of every nth item in coll.  Returns a stateful
  transducer when no collection is provided."
  {:added "1.0"}
  ([n]
     (fn [rf]
       (let [iv (process-val! -1)]
         (fn
           ([] (rf))
           ([result]
              (.destroy iv)
              (rf result))
           ([result input]
              (let [i (vswap! iv inc)]
                (if (zero? (rem i n))
                  (rf result input)
                  result)))))))
  ([n coll]
     (lazy-seq
      (when-let [s (seq coll)]
        (cons (first s) (take-nth n (drop n s)))))))

(defn interleave
  "Returns a lazy seq of the first item in each coll, then the second etc."
  {:added "1.0"}
  ([] ())
  ([c1] (lazy-seq c1))
  ([c1 c2]
     (lazy-seq
      (let [s1 (seq c1) s2 (seq c2)]
        (when (and s1 s2)
          (cons (first s1) (cons (first s2)
                                 (interleave (rest s1) (rest s2))))))))
  ([c1 c2 & colls]
     (lazy-seq
      (let [ss (map seq (conj colls c2 c1))]
        (when (every? identity ss)
          (concat (map first ss) (apply interleave (map rest ss))))))))

(defn var-get
  "Gets the value in the var object"
  {:added "1.0"}
  [x] (clojerl.Var/get x))

(defn var-set
  "Sets the value in the var object to val. The var must be
  thread-locally bound."
  {:added "1.0"}
  [x val] (clojerl.Var/dynamic_binding x val))

(defmacro with-local-vars
  "varbinding=> symbol init-expr

  Executes the exprs in a context in which the symbols are bound to
  vars with per-thread bindings to the init-exprs.  The symbols refer
  to the var objects themselves, and must be accessed with var-get and
  var-set"
  {:added "1.0"}
  [name-vals-vec & body]
  (assert-args
   (vector? name-vals-vec) "a vector for its binding"
   (even? (count name-vals-vec)) "an even number of forms in binding vector")
  `(let [~@(interleave (take-nth 2 name-vals-vec)
                       (repeat '(.. clojerl.Var create setDynamic)))]
     (clojerl.Var/push_bindings (hash-map ~@name-vals-vec))
     (try
       ~@body
       (finally (clojerl.Var/pop_bindings)))))

(defn ns-resolve
  "Returns the var or erlang.Type to which a symbol will be resolved in the
  namespace (unless found in the environment), else nil.  Note that
  if the symbol is fully qualified, the var/Type to which it resolves
  need not be present in the namespace."
  {:added "1.0"}
  ([ns sym]
   (ns-resolve ns nil sym))
  ([ns env sym]
   (when-not (contains? env sym)
     (.find_var (the-ns ns) sym))))

(defn resolve
  "same as (ns-resolve *ns* symbol) or (ns-resolve *ns* &env symbol)"
  {:added "1.0"}
  ([sym] (ns-resolve *ns* sym))
  ([env sym] (ns-resolve *ns* env sym)))

(defn array-map
  "Constructs an array-map. If any keys are equal, they are handled as
  if by repeated uses of assoc."
  {:added "1.0"}
  ([] (new clojerl.TupleMap #erl()))
  ([& keyvals]
   (. clojerl.TupleMap (create_with_assoc (clj_rt/to_list keyvals)))))

;redefine let and loop  with destructuring
(defn destructure [bindings]
  (let [bents (partition 2 bindings)
        pb (fn pb [bvec b v]
             (let [pvec
                   (fn [bvec b val]
                     (let [gvec (gensym "vec__")
                           gvec-orig (gensym "vec__")]
                       (loop [ret (-> bvec
                                      (conj gvec) (conj val)
                                      (conj gvec-orig) (conj gvec))
                              n 0
                              bs b
                              seen-rest? false]
                         (if (seq bs)
                           (let [firstb (first bs)]
                             (cond
                               (= firstb '&) (recur (pb ret (second bs) (list `next gvec))
                                                    n
                                                    (nnext bs)
                                                    true)
                               (= firstb :as) (pb ret (second bs) gvec-orig)
                               :else (if seen-rest?
                                       (throw (clojerl.Error. "Unsupported binding form, only :as can follow & parameter"))
                                       (recur (if (zero? n)
                                                (pb (-> ret
                                                        (conj gvec)
                                                        (conj (list `seq gvec)))
                                                    firstb (list `first gvec))
                                                (pb (-> ret
                                                        (conj gvec)
                                                        (conj (list `seq (list `next gvec))))
                                                    firstb (list `first gvec)))
                                              (inc n)
                                              (next bs)
                                              seen-rest?))))
                           ret))))
                   pmap
                   (fn [bvec b v]
                     (let [gmap (gensym "map__")
                           gmapseq (with-meta gmap {:tag 'clojerl.ISeq})
                           defaults (:or b)]
                       (loop [ret (-> bvec (conj gmap) (conj v)
                                      (conj gmap) (conj `(if (seq? ~gmap)
                                                           (new clojerl.Map (clj_rt/to_list ~gmapseq))
                                                           ~gmap))
                                      ((fn [ret]
                                         (if (:as b)
                                           (conj ret (:as b) gmap)
                                           ret))))
                              bes (reduce
                                   (fn [bes entry]
                                     (reduce #(assoc %1 %2 ((val entry) %2))
                                              (dissoc bes (key entry))
                                              ((key entry) bes)))
                                   (dissoc b :as :or)
                                   {:keys #(if (keyword? %) % (keyword (str %))),
                                    :strs str, :syms #(list `quote %)})]
                         (if (seq bes)
                           (let [bb (key (first bes))
                                 bk (val (first bes))
                                 bv (if (contains? defaults bb)
                                      (list `get gmap bk (defaults bb))
                                      (list `get gmap bk))]
                             (recur (cond
                                      (symbol? bb) (-> ret (conj (if (namespace bb) (symbol (name bb)) bb)) (conj bv))
                                      (keyword? bb) (-> ret (conj (symbol (name bb)) bv))
                                      :else (pb ret bb bv))
                                    (next bes)))
                           ret))))]
               (cond
                 (symbol? b) (-> bvec (conj b) (conj v))
                 (vector? b) (pvec bvec b v)
                 (map? b) (pmap bvec b v)
                 :else (throw (clojerl.Error. (str "Unsupported binding form: " b))))))
        process-entry (fn [bvec b] (pb bvec (first b) (second b)))]
    (if (every? symbol? (map first bents))
      bindings
      (reduce process-entry [] bents))))

(defmacro let
  "binding => binding-form init-expr

  Evaluates the exprs in a lexical context in which the symbols in
  the binding-forms are bound to their respective init-exprs or parts
  therein."
  {:added "1.0", :special-form true, :forms '[(let [bindings*] exprs*)]}
  [bindings & body]
  (assert-args
   (vector? bindings) "a vector for its binding"
   (even? (count bindings)) "an even number of forms in binding vector")
  `(let* ~(destructure bindings) ~@body))

(defn ^{:private true}
  maybe-destructured
  [params body]
  (if (every? symbol? params)
    (cons params body)
    (loop [params params
           new-params (with-meta [] (meta params))
           lets []]
      (if params
        (if (symbol? (first params))
          (recur (next params) (conj new-params (first params)) lets)
          (let [gparam (gensym "p__")]
            (recur (next params) (conj new-params gparam)
                   (-> lets (conj (first params)) (conj gparam)))))
        `(~new-params
          (let ~lets
            ~@body))))))

;redefine fn with destructuring and pre/post conditions
(defmacro fn
  "params => positional-params* , or positional-params* & next-param
  positional-param => binding-form
  next-param => binding-form
  name => symbol

  Defines a function"
  {:added "1.0", :special-form true,
   :forms '[(fn name? [params* ] exprs*) (fn name? ([params* ] exprs*)+)]}
  [& sigs]
  (let [name (if (symbol? (first sigs)) (first sigs) nil)
        sigs (if name (next sigs) sigs)
        sigs (if (vector? (first sigs))
               (list sigs)
               (if (seq? (first sigs))
                 sigs
                 ;; Assume single arity syntax
                 (throw (clojerl.BadArgumentError.
                         (if (seq sigs)
                           (str "Parameter declaration "
                                (first sigs)
                                " should be a vector")
                           (str "Parameter declaration missing"))))))
        psig (fn* [sig]
                  ;; Ensure correct type before destructuring sig
                  (when (not (seq? sig))
                    (throw (clojerl.BadArgumentError. (str "Invalid signature \"" sig
                                                           "\" should be a list"))))
                  (let [[params & body] sig
                        _ (when (not (vector? params))
                            (throw (clojerl.BadArgumentError.
                                    (if (seq? (first sigs))
                                      (str "Parameter declaration " params
                                           " should be a vector")
                                      (str "Invalid signature \"" sig
                                           "\" should be a list")))))
                        conds (when (and (next body) (map? (first body)))
                                (first body))
                        body (if conds (next body) body)
                        conds (or conds (meta params))
                        pre (:pre conds)
                        post (:post conds)
                        when (:when conds)
                        body (if post
                               `((let [~'% ~(if (< 1 (count body))
                                              `(do ~@body)
                                              (first body))]
                                   ~@(map (fn* [c] `(assert ~c)) post)
                                   ~'%))
                               body)
                        body (if pre
                               (concat (map (fn* [c] `(assert ~c)) pre)
                                       body)
                               body)
                        body (if when
                               (cons {:when when} body)
                               body)]
                    (maybe-destructured params body)))
        new-sigs (map psig sigs)]
    (with-meta
      (if name
        (list* 'fn* name new-sigs)
        (cons 'fn* new-sigs))
      (meta &form))))

(defmacro loop
  "Evaluates the exprs in a lexical context in which the symbols in
  the binding-forms are bound to their respective init-exprs or parts
  therein. Acts as a recur target."
  {:added "1.0", :special-form true, :forms '[(loop [bindings*] exprs*)]}
  [bindings & body]
  (assert-args
   (vector? bindings) "a vector for its binding"
   (even? (count bindings)) "an even number of forms in binding vector")
  (let [db (destructure bindings)]
    (if (= db bindings)
      `(loop* ~bindings ~@body)
      (let [vs (take-nth 2 (drop 1 bindings))
            bs (take-nth 2 bindings)
            gs (vec (map (fn [b] (if (symbol? b) b (gensym))) bs))
            bfs (reduce (fn [ret [b v g]]
                           (if (symbol? b)
                             (conj ret g v)
                             (conj ret g v b g)))
                         [] (map vector bs vs gs))]
        `(let ~bfs
           (loop* ~(vec (interleave gs gs))
                  (let ~(vec (interleave bs gs))
                    ~@body)))))))

(defmacro when-first
  "bindings => x xs

  Roughly the same as (when (seq xs) (let [x (first xs)] body)) but xs is evaluated only once"
  {:added "1.0"}
  [bindings & body]
  (assert-args
   (vector? bindings) "a vector for its binding"
   (= 2 (count bindings)) "exactly 2 forms in binding vector")
  (let [[x xs] bindings]
    `(when-let [xs# (seq ~xs)]
       (let [~x (first xs#)]
         ~@body))))

(defmacro lazy-cat
  "Expands to code which yields a lazy sequence of the concatenation
  of the supplied colls.  Each coll expr is not evaluated until it is
  needed.

  (lazy-cat xs ys zs) === (concat (lazy-seq xs) (lazy-seq ys) (lazy-seq zs))"
  {:added "1.0"}
  [& colls]
  `(concat ~@(map #(list `lazy-seq %) colls)))

(defmacro for
  "List comprehension. Takes a vector of one or more
   binding-form/collection-expr pairs, each followed by zero or more
   modifiers, and yields a lazy sequence of evaluations of expr.
   Collections are iterated in a nested fashion, rightmost fastest,
   and nested coll-exprs can refer to bindings created in prior
   binding-forms.  Supported modifiers are: :let [binding-form expr ...],
   :while test, :when test.

  (take 100 (for [x (range 100000000) y (range 1000000) :while (< y x)] [x y]))"
  {:added "1.0"}
  [seq-exprs body-expr]
  (assert-args
     (vector? seq-exprs) "a vector for its binding"
     (even? (count seq-exprs)) "an even number of forms in binding vector")
  (let [to-groups (fn [seq-exprs]
                    (reduce (fn [groups [k v]]
                              (if (keyword? k)
                                (conj (pop groups) (conj (peek groups) [k v]))
                                (conj groups [k v])))
                            [] (partition 2 seq-exprs)))
        err (fn [& msg] (throw (clojerl.BadArgumentError. (apply str msg))))
        emit-bind (fn emit-bind [[[bind expr & mod-pairs]
                                  & [[_ next-expr] :as next-groups]]]
                    (let [giter (gensym "iter__")
                          gxs (gensym "s__")
                          do-mod (fn do-mod [[[k v :as pair] & etc]]
                                   (cond
                                     (= k :let) `(let ~v ~(do-mod etc))
                                     (= k :while) `(when ~v ~(do-mod etc))
                                     (= k :when) `(if ~v
                                                    ~(do-mod etc)
                                                    (recur (rest ~gxs)))
                                     (keyword? k) (err "Invalid 'for' keyword " k)
                                     next-groups
                                      `(let [iterys# ~(emit-bind next-groups)
                                             fs# (seq (iterys# ~next-expr))]
                                         (if fs#
                                           (concat fs# (~giter (rest ~gxs)))
                                           (recur (rest ~gxs))))
                                     :else `(cons ~body-expr
                                                  (~giter (rest ~gxs)))))]
                      (if next-groups
                        #_"not the inner-most loop"
                        `(fn ~giter [~gxs]
                           (lazy-seq
                             (loop [~gxs ~gxs]
                               (when-first [~bind ~gxs]
                                 ~(do-mod mod-pairs)))))
                        #_"inner-most loop"
                        (let [gi (gensym "i__")
                              gb (gensym "b__")
                              do-cmod (fn do-cmod [[[k v :as pair] & etc]]
                                        (cond
                                          (= k :let) `(let ~v ~(do-cmod etc))
                                          (= k :while) `(if ~v ~(do-cmod etc) ~gb)
                                          (= k :when) `(if ~v
                                                         ~(do-cmod etc)
                                                         (recur
                                                           (inc ~gi) ~gb))
                                          (keyword? k)
                                            (err "Invalid 'for' keyword " k)
                                          :else
                                          `(recur (inc ~gi) (chunk-append ~gb ~body-expr))))]
                          `(fn ~giter [~gxs]
                             (lazy-seq
                               (loop [~gxs ~gxs]
                                 (when-let [~gxs (seq ~gxs)]
                                   (if (chunked-seq? ~gxs)
                                     (let [c# (chunk-first ~gxs)
                                           size# (int (count c#))
                                           ~gb (loop [~gi (int 0) ~gb (chunk-buffer size#)]
                                                 (if (< ~gi size#)
                                                   (let [~bind (clojerl.TupleChunk/nth c# ~gi)]
                                                     ~(do-cmod mod-pairs))
                                                   ~gb))]
                                       (if (= size# (clojerl.ChunkBuffer/count ~gb))
                                         (chunk-cons
                                           (chunk ~gb)
                                           (~giter (chunk-rest ~gxs)))
                                         (chunk-cons (chunk ~gb) nil)))
                                     (let [~bind (first ~gxs)]
                                       ~(do-mod mod-pairs)))))))))))]
    `(let [iter# ~(emit-bind (to-groups seq-exprs))]
        (iter# ~(second seq-exprs)))))

(defmacro comment
  "Ignores body, yields nil"
  {:added "1.0"}
  [& body])

(defmacro with-out-str
  "Evaluates exprs in a context in which *out* is bound to a fresh
  StringWriter.  Returns the string created by any nested printing
  calls."
  {:added "1.0"}
  [& body]
  `(with-open [s# (new erlang.io.StringWriter)]
     (binding [*out* s#]
       ~@body
       (str s#))))

(defmacro with-in-str
  "Evaluates body in a context in which *in* is bound to a fresh
  StringReader initialized with the string s."
  {:added "1.0"}
  [s & body]
  `(with-open [s# (-> (erlang.io.StringReader. ~s) erlang.io.PushbackReader.)]
     (binding [*in* s#]
       ~@body)))

(defn pr-str
  "pr to a string, returning it"
  {:tag clojerl.String
   :added "1.0"}
  [& xs]
  (with-out-str
    (apply pr xs)))

(defn prn-str
  "prn to a string, returning it"
  {:tag clojerl.String
   :added "1.0"}
  [& xs]
  (with-out-str
   (apply prn xs)))

(defn print-str
  "print to a string, returning it"
  {:tag clojerl.String
   :added "1.0"}
  [& xs]
  (with-out-str
    (apply print xs)))

(defn println-str
  "println to a string, returning it"
  {:tag clojerl.String
   :added "1.0"}
  [& xs]
  (with-out-str
    (apply println xs)))

(import clojerl.ExceptionInfo clojerl.IError)
(defn ex-info
  "Create an instance of ExceptionInfo, which implements IError
   that carries a map of additional data."
  {:added "1.4"}
  ([msg map]
   (ExceptionInfo. msg map))
  ([msg map cause]
   (ExceptionInfo. msg map cause)))

(defn ex-data
  "Returns exception data (a map) if ex is an IExceptionInfo.
   Otherwise returns nil."
  {:added "1.4"}
  [ex]
  (when (instance? ExceptionInfo ex)
    (.data ^ExceptionInfo ex)))

(defn ex-message
  "Returns the message attached to the given Error / ExceptionInfo object.
  For non-Errors returns nil."
  {:added "1.4"}
  [ex]
  (when (satisfies? IError ex)
    (.message ^IError ex)))

(defn ex-cause
  "Returns exception cause (an Error / ExceptionInfo) if ex is an
  ExceptionInfo.
  Otherwise returns nil."
  {:added "1.4"}
  [ex]
  (when (instance? ExceptionInfo ex)
    (.cause ^ExceptionInfo ex)))

(defmacro assert
  "Evaluates expr and throws an exception if it does not evaluate to
  logical true."
  {:added "1.0"}
  ([x]
   (when *assert*
     `(when-not ~x
        (throw (clojerl.AssertionError. (str "Assert failed: " (pr-str '~x)))))))
  ([x message]
   (when *assert*
     `(when-not ~x
        (throw (clojerl.AssertionError. (str "Assert failed: " ~message "\n" (pr-str '~x))))))))

(defn test
  "test [v] finds fn at key :test in var metadata and calls it,
  presuming failure will throw exception"
  {:added "1.0"}
  [v]
    (let [f (:test (meta v))]
      (if f
        (do (f) :ok)
        :no-test)))

(defn rand
  "Returns a random floating point number between 0 (inclusive) and
  n (default 1) (exclusive)."
  {:added "1.0"}
  ([] (rand/uniform))
  ([n] (* n (rand))))

(defn rand-int
  "Returns a random integer between 0 (inclusive) and n (exclusive)."
  {:added "1.0"}
  [n] (int (rand n)))

(defmacro defn-
  "same as defn, yielding non-public def"
  {:added "1.0"}
  [name & decls]
    (list* `defn (with-meta name (assoc (meta name) :private true)) decls))

(defn tree-seq
  "Returns a lazy sequence of the nodes in a tree, via a depth-first walk.
   branch? must be a fn of one arg that returns true if passed a node
   that can have children (but may not).  children must be a fn of one
   arg that returns a sequence of the children. Will only be called on
   nodes for which branch? returns true. Root is the root node of the
  tree."
  {:added "1.0"}
   [branch? children root]
   (let [walk (fn walk [node]
                (lazy-seq
                 (cons node
                  (when (branch? node)
                    (mapcat walk (children node))))))]
     (walk root)))

(defn file-seq
  "A tree seq on all files in a directory structure"
  {:added "1.0"}
  [dir]
  (tree-seq
   (fn [^erlang.io.File f] (filelib/is_dir f))
   (fn [^erlang.io.File d] (->> (file/list_dir d)
                               second
                               (map #(filename/join d %))
                               seq))
   dir))

(defn xml-seq
  "A tree seq on the xml elements as per xml/parse"
  {:added "1.0"}
  [root]
    (tree-seq
     (complement string?)
     (comp seq :content)
     root))

(defn special-symbol?
  "Returns true if s names a special form"
  {:added "1.0"}
  [s]
  (clj_analyzer/is_special s))

(defn var?
  "Returns true if v is of type clojerl.Var"
  {:added "1.0"}
  [v] (instance? clojerl.Var v))

(defn subs
  "Returns the substring of s beginning at start inclusive, and ending
  at end (defaults to length of string), exclusive."
  {:added "1.0"}
  ([s start] (subs s start (count s)))
  ([s start end] (clojerl.String/substring s start end)))

(defn regex? [x]
  (clj_rt/regex? x))

(defn re-run
  "Runs the matching of the pattern over the string using the provided
  options."
  {:added "1.0"}
  [^erlang.util.Regex re s & opts]
  (let* [opts (clj_rt/to_list opts)]
    (case* (.run re s opts)
      #erl[:match match] (vec match)
      _ nil)))

(defn re-pattern
  "Returns a compiled Erlang regular expression unless s is already a
  compiled pattern."
  {:tag erlang.util.Regex
   :added "1.0"}
  [s]
  (if (regex? s)
    s
    (new erlang.util.Regex s)))

(defn re-find
  "Returns the next regex match, if any, of string to pattern."
  {:added "1.0"}
  [re s]
  (let [matches (re-run re s #erl [:capture :all :binary])]
    (if (= (count matches) 1)
      (first matches)
      matches)))

(defn re-seq
  "Returns a lazy sequence of all matches of pattern in string."
  {:added "1.0"}
  [re s]
  (let [match-data (re-find re s)
        [idx len]  (first (re-run re s #erl [:capture :first :index]))
        match-str  (if (seq? match-data) (first match-data) match-data)
        len        (if (and (zero? len) (not (seq s))) 1 len)
        post-match (when idx (subs s (+ idx len)))]
    (when idx
      (lazy-seq (cons match-data
                      (when (seq post-match)
                        (re-seq re post-match)))))))

(defn re-matches
  "Returns the result of (re-find re s) if re fully matches s."
  {:added "1.0"}
  [re s]
  (if (string? s)
    (let [matches (re-find re s)
          match   (if (string? matches) matches (first matches))]
      (when (= match s)
        (if (== (count matches) 1)
          (first matches)
          matches)))
    (throw (clojerl.BadArgumentError. "re-matches must match against a string."))))

(defn max-key
  "Returns the x for which (k x), a number, is greatest."
  {:added "1.0"}
  ([k x] x)
  ([k x y] (if (> (k x) (k y)) x y))
  ([k x y & more]
   (reduce #(max-key k %1 %2) (max-key k x y) more)))

(defn min-key
  "Returns the x for which (k x), a number, is least."
  {:added "1.0"}
  ([k x] x)
  ([k x y] (if (< (k x) (k y)) x y))
  ([k x y & more]
   (reduce #(min-key k %1 %2) (min-key k x y) more)))

(defn distinct
  "Returns a lazy sequence of the elements of coll with duplicates removed.
  Returns a stateful transducer when no collection is provided."
  {:added "1.0"}
  ([]
   (fn [rf]
     (let [seen (process-val! #{})]
       (fn
         ([] (rf))
         ([result]
            (.destroy seen)
            (rf result))
         ([result input]
          (if (contains? @seen input)
            result
            (do (vswap! seen conj input)
                (rf result input))))))))
  ([coll]
   (let [step (fn step [xs seen]
                (lazy-seq
                  ((fn [[f :as xs] seen]
                     (when-let [s (seq xs)]
                       (if (contains? seen f)
                         (recur (rest s) seen)
                         (cons f (step (rest s) (conj seen f))))))
                   xs seen)))]
     (step coll #{}))))

(defn replace
  "Given a map of replacement pairs and a vector/collection, returns a
  vector/seq with any elements = a key in smap replaced with the
  corresponding val in smap.  Returns a transducer when no collection
  is provided."
  {:added "1.0"}
  ([smap]
     (map #(if-let [e (find smap %)] (val e) %)))
  ([smap coll]
     (if (vector? coll)
       (reduce (fn [v i]
                  (if-let [e (find smap (nth v i))]
                    (assoc v i (val e))
                    v))
                coll (range (count coll)))
       (map #(if-let [e (find smap %)] (val e) %) coll))))

#_(
    (defn mk-bound-fn
      {:private true}
      [sc test key]
      (fn [e]
        (test (.. sc comparator (compare (. sc entryKey e) key)) 0)))

    (defn subseq
      "sc must be a sorted collection, test(s) one of <, <=, > or
  >=. Returns a seq of those entries with keys ek for
  which (test (.. sc comparator (compare ek key)) 0) is true"
      {:added "1.0"}
      ([sc test key]
       (let [include (mk-bound-fn sc test key)]
         (if (#{> >=} test)
           (when-let [[e :as s] (. sc seqFrom key true)]
             (if (include e) s (next s)))
           (take-while include (. sc seq true)))))
      ([sc start-test start-key end-test end-key]
       (when-let [[e :as s] (. sc seqFrom start-key true)]
         (take-while (mk-bound-fn sc end-test end-key)
                     (if ((mk-bound-fn sc start-test start-key) e) s (next s))))))

    (defn rsubseq
      "sc must be a sorted collection, test(s) one of <, <=, > or
  >=. Returns a reverse seq of those entries with keys ek for
  which (test (.. sc comparator (compare ek key)) 0) is true"
      {:added "1.0"}
      ([sc test key]
       (let [include (mk-bound-fn sc test key)]
         (if (#{< <=} test)
           (when-let [[e :as s] (. sc seqFrom key false)]
             (if (include e) s (next s)))
           (take-while include (. sc seq false)))))
      ([sc start-test start-key end-test end-key]
       (when-let [[e :as s] (. sc seqFrom end-key false)]
         (take-while (mk-bound-fn sc start-test start-key)
                     (if ((mk-bound-fn sc end-test end-key) e) s (next s)))))))

(defn repeatedly
  "Takes a function of no args, presumably with side effects, and
  returns an infinite (or length n if supplied) lazy sequence of calls
  to it"
  {:added "1.0"}
  ([f] (lazy-seq (cons (f) (repeatedly f))))
  ([n f] (take n (repeatedly f))))

(defn add-codepath
  "Adds the path String to the codepath through code/add_patha.1"
  {:added "1.0"
   :deprecated "1.1"}
  [url]
  (code/add_patha (erlang/binary_to_list url)))

(defn hash
  "Returns the hash code of its argument. Note this is the hash code
  consistent with =, and thus is different than .hashCode for Integer,
  Short, Byte and Clojure collections."

  {:added "1.0"}
  [x]
  (clj_rt/hash x))

(defn mix-collection-hash
  "Mix final collection hash for ordered or unordered collections.
   hash-basis is the combined collection hash, count is the number
   of elements included in the basis. Note this is the hash code
   consistent with =, different from .hashCode.
   See http://clojure.org/data_structures#hash for full algorithms."
  {:added "1.6"}
  [hash-basis count]
  (clj_murmur3/mix_coll_hash hash-basis count))

(defn hash-ordered-coll
  "Returns the hash code, consistent with =, for an external ordered
   collection implementing Iterable.
   See http://clojure.org/data_structures#hash for full algorithms."
  {:added "1.6"}
  [coll]
  (clj_murmur3/ordered coll))

(defn hash-unordered-coll
  "Returns the hash code, consistent with =, for an external unordered
   collection implementing Iterable. For maps, the iterator should
   return map entries whose hash is computed as
     (hash-ordered-coll [k v]).
   See http://clojure.org/data_structures#hash for full algorithms."
  {:added "1.6"}
  [coll]
  (clj_murmur3/unordered coll))

(defn interpose
  "Returns a lazy seq of the elements of coll separated by sep.
  Returns a stateful transducer when no collection is provided."
  {:added "1.0"}
  ([sep]
   (fn [rf]
     (let [started (process-val! false)]
       (fn
         ([] (rf))
         ([result]
            (.destroy started)
            (rf result))
         ([result input]
          (if @started
            (let [sepr (rf result sep)]
              (if (reduced? sepr)
                sepr
                (rf sepr input)))
            (do
              (vreset! started true)
              (rf result input))))))))
  ([sep coll]
   (drop 1 (interleave (repeat sep) coll))))

(defmacro definline
  "Experimental - like defmacro, except defines a named function whose
  body is the expansion, calls to which may be expanded inline as if
  it were a macro. Cannot be used with variadic (&) args."
  {:added "1.0"}
  [name & decl]
  (let [[pre-args [args expr]] (split-with (comp not vector?) decl)
        [pre-args [metadata]]  (split-with (comp not map?) pre-args)
        metadata               (assoc metadata :inline `'(fn ~name ~args ~expr))]
    `(defn ~name ~@pre-args ~metadata
       ~args
       ~(apply (eval (list `fn args expr)) args))))

(defn empty
  "Returns an empty collection of the same category as coll, or nil"
  {:added "1.0"}
  [coll]
  (when (satisfies? clojerl.IColl coll)
    (clj_rt/empty coll)))

(defn seque
  "Creates a queued seq on another (presumably lazy) seq s. The queued
  seq will produce a concrete seq in the background, and can get up to
  n items ahead of the consumer. n-or-q can be an integer n buffer
  size, or an instance of java.util.concurrent BlockingQueue. Note
  that reading from a seque can block if the reader gets ahead of the
  producer."
  {:added "1.0"}
  ([s] (seque 100 s))
  ([n-or-q s]
   (throw "unimplemented queue")
   #_(let [^BlockingQueue q (if (instance? BlockingQueue n-or-q)
                             n-or-q
                             (LinkedBlockingQueue. (int n-or-q)))
         NIL (Object.) ;nil sentinel since LBQ doesn't support nils
         agt (agent (lazy-seq s)) ; never start with nil; that signifies we've already put eos
         log-error (fn [q e]
                     (if (.offer q q)
                       (throw e)
                       e))
         fill (fn [s]
                (when s
                  (if (instance? Exception s) ; we failed to .offer an error earlier
                    (log-error q s)
                    (try
                      (loop [[x & xs :as s] (seq s)]
                        (if s
                          (if (.offer q (if (nil? x) NIL x))
                            (recur xs)
                            s)
                          (when-not (.offer q q) ; q itself is eos sentinel
                            ()))) ; empty seq, not nil, so we know to put eos next time
                      (catch Exception e
                        (log-error q e))))))
         drain (fn drain []
                 (lazy-seq
                  (let [x (.take q)]
                    (if (identical? x q) ;q itself is eos sentinel
                      (do @agt nil)  ;touch agent just to propagate errors
                      (do
                        (send-off agt fill)
                        (release-pending-sends)
                        (cons (if (identical? x NIL) nil x) (drain)))))))]
     (send-off agt fill)
     (drain))))

(defn type?
  "Returns true if x is an instance of erlang.Type"
  {:added "1.0"}
  [x] (instance? erlang.Type x))

(defn alter-var-root
  "Atomically alters the root binding of var v by applying f to its
  current value plus any args"
  {:added "1.0"}
  [v f & args]
  (throw (clojerl.Error. "unsupported alter-var-root")))

(defn bound?
  "Returns true if all of the vars provided as arguments have any bound value, root or thread-local.
   Implies that deref'ing the provided vars will succeed. Returns true if no vars are provided."
  {:added "1.2"}
  [& vars]
  (every? clojerl.Var/is_bound.1 vars))

(defn thread-bound?
  "Returns true if all of the vars provided as arguments have thread-local bindings.
   Implies that set!'ing the provided vars will succeed.  Returns true if no vars are provided."
  {:added "1.2"}
  [& vars]
  (every? clojerl.Var/dynamic_binding.1 vars))

(defn make-hierarchy
  "Creates a hierarchy object for use with derive, isa? etc."
  {:added "1.0"}
  [] {:parents {} :descendants {} :ancestors {}})

(def ^{:private true}
     global-hierarchy (make-hierarchy))

(defn not-empty
  "If coll is empty, returns nil, else coll"
  {:added "1.0"}
  [coll] (when (seq coll) coll))

(defn isa?
  "Returns true if (= child parent), or child is directly or indirectly derived
  from parent, via a relationship established via derive. h must be a hierarchy
  obtained from make-hierarchy, if not supplied defaults to the global
  hierarchy"
  {:added "1.0"}
  ([child parent] (isa? global-hierarchy child parent))
  ([h child parent]
   (or (= child parent)
       (contains? ((:ancestors h) child) parent)
       (and (vector? parent) (vector? child)
            (= (count parent) (count child))
            (loop [ret true i 0]
              (if (or (not ret) (= i (count parent)))
                ret
                (recur (isa? h (child i) (parent i)) (inc i))))))))

(defn parents
  "Returns the immediate parents of tag, via a relationship established
  via derive. h must be a hierarchy obtained from make-hierarchy, if not
  supplied defaults to the global hierarchy"
  {:added "1.0"}
  ([tag] (parents global-hierarchy tag))
  ([h tag] (not-empty (get (:parents h) tag))))

(defn ancestors
  "Returns the immediate and indirect parents of tag, via a relationship
  established via derive. h must be a hierarchy obtained from make-hierarchy,
  if not supplied defaults to the global hierarchy"
  {:added "1.0"}
  ([tag] (ancestors global-hierarchy tag))
  ([h tag] (not-empty (get (:ancestors h) tag))))

(defn descendants
  "Returns the immediate and indirect children of tag, through a
  relationship established via derive. h must be a hierarchy obtained
  from make-hierarchy, if not supplied defaults to the global
  hierarchy."
  {:added "1.0"}
  ([tag] (descendants global-hierarchy tag))
  ([h tag] (not-empty (get (:descendants h) tag))))

(defn derive
  "Establishes a parent/child relationship between parent and
  tag. Parent must be a namespace-qualified symbol or keyword and
  child can be either a namespace-qualified symbol or keyword or a
  type. h must be a hierarchy obtained from make-hierarchy, if not
  supplied defaults to, and modifies, the global hierarchy."
  {:added "1.0"}
  ([tag parent]
   (assert (namespace parent))
   (assert (and (satisfies? clojerl.INamed tag) (namespace tag)))

   (alter-var-root #'global-hierarchy derive tag parent) nil)
  ([h tag parent]
   (assert (not= tag parent))
   (assert (satisfies? clojerl.INamed tag))
   (assert (satisfies? clojerl.INamed parent))

   (let [tp (:parents h)
         td (:descendants h)
         ta (:ancestors h)
         tf (fn [m source sources target targets]
              (reduce (fn [ret k]
                        (assoc ret k
                               (reduce conj (get targets k #{}) (cons target (targets target)))))
                      m (cons source (sources source))))]
     (or
      (when-not (contains? (tp tag) parent)
        (when (contains? (ta tag) parent)
          (throw (clojerl.Error. (print-str tag "already has" parent "as ancestor"))))
        (when (contains? (ta parent) tag)
          (throw (clojerl.Error. (print-str "Cyclic derivation:" parent "has" tag "as ancestor"))))
        {:parents (assoc (:parents h) tag (conj (get tp tag #{}) parent))
         :ancestors (tf (:ancestors h) tag td parent ta)
         :descendants (tf (:descendants h) parent ta tag td)})
      h))))

(declare flatten)

(defn underive
  "Removes a parent/child relationship between parent and
  tag. h must be a hierarchy obtained from make-hierarchy, if not
  supplied defaults to, and modifies, the global hierarchy."
  {:added "1.0"}
  ([tag parent] (alter-var-root #'global-hierarchy underive tag parent) nil)
  ([h tag parent]
    (let [parentMap (:parents h)
	  childsParents (if (parentMap tag)
			  (disj (parentMap tag) parent) #{})
	  newParents (if (not-empty childsParents)
		       (assoc parentMap tag childsParents)
		       (dissoc parentMap tag))
	  deriv-seq (flatten (map #(cons (key %) (interpose (key %) (val %)))
				       (seq newParents)))]
      (if (contains? (parentMap tag) parent)
	(reduce #(apply derive %1 %2) (make-hierarchy)
		(partition 2 deriv-seq))
	h))))


(defn distinct?
  "Returns true if no two of the arguments are ="
  {:tag clojerl.Boolean
   :added "1.0"}
  ([x] true)
  ([x y] (not (= x y)))
  ([x y & more]
   (if (not= x y)
     (loop [s #{x y} [x & etc :as xs] more]
       (if xs
         (if (contains? s x)
           false
           (recur (conj s x) etc))
         true))
     false)))

(defn format
  "Formats a string using io_lib/format, see io/format for format
  string syntax"
  {:added "1.0"}
  ^clojerl.String [fmt & args]
  (->> (clj_rt/to_list args)
       (io_lib/format fmt)
       erlang/list_to_binary))

(defn printf
  "Prints formatted output, as per format"
  {:added "1.0"}
  [fmt & args]
  (print (apply format fmt args)))

(defmacro with-loading-context [& body]
  `(do ~@body))

(defmacro ns
  "Sets *ns* to the namespace named by name (unevaluated), creating it
  if needed.  references can be zero or more of: (:refer-clojure ...)
  (:require ...) (:use ...) (:import ...) (:load ...) with the syntax of
  refer-clojure/require/use/import/load respectively, except the arguments
  are unevaluated and need not be quoted. If :refer-clojure is not used,
  a default (refer 'clojure.core) is used.  Use of ns is preferred to
  individual calls to in-ns/require/use/import:

  (ns foo.bar
    (:refer-clojure :exclude [ancestors printf])
    (:require (clojure.contrib sql combinatorics))
    (:use (my.lib this that))
    (:import (erlang.util Regex UUID)
             (erlang.io PushbackReader File)))"
  {:arglists '([name docstring? attr-map? references*])
   :added "1.0"}
  [name & references]
  (let [process-reference
        (fn [all-args]
          (let [kname    (first all-args)
                args     (rest all-args)
                name-str (clojure.core/name kname)
                name-sym (symbol "clojure.core" (str name-str "*"))]
            `(~(symbol "clojure.core" (clojure.core/name kname))
              ~@(map #(list 'quote %) args))))
        docstring  (when (string? (first references)) (first references))
        references (if docstring (next references) references)
        name (if docstring
               (vary-meta name assoc :doc docstring)
               name)
        metadata   (when (map? (first references)) (first references))
        references (if metadata (next references) references)
        name (if metadata
               (vary-meta name merge metadata)
               name)
        ;ns-effect (clojure.core/in-ns name)
        name-metadata (meta name)]
    `(do
       (clojure.core/in-ns '~name)
       (with-loading-context
         ~@(when (and (not= name 'clojure.core)
                      (not-any? #(= :refer-clojure (first %)) references))
             `((clojure.core/refer 'clojure.core)))
         ~@(map process-reference references))
       #_(if (= '~name 'clojure.core)
         nil
         (do (dosync (commute @#'*loaded-libs* conj '~name)) nil)))))

(defmacro refer-clojure
  "Same as (refer 'clojure.core <filters>)"
  {:added "1.0"}
  [& filters]
  `(clojure.core/refer 'clojure.core ~@filters))

(defmacro defonce
  "defs name to have the root value of the expr iff the named var has no root value,
  else expr is unevaluated"
  {:added "1.0"}
  [name expr]
  (let [name (if-not (namespace name)
               (with-meta (symbol (str (ns-name *ns*)) (str name))
                          (meta name))
               name)]
    (if-not (find-var name)
      `(def ~name ~expr))))

;;;;;;;;;;; require/use/load, contributed by Stephen C. Gilardi ;;;;;;;;;;;;;;;;;;

(defonce
  ^{:dynamic true
    :private true
    :doc "A ref to a sorted set of symbols representing loaded libs"}
  *loaded-libs* ;; TODO: should be a sorted-set
  #{})

(defonce ^:dynamic
  ^{:private true
    :doc "A stack of paths currently being loaded by this thread"}
  *pending-paths* ())

(defonce ^:dynamic
  ^{:private true :doc
    "True while a verbose load is pending"}
  *loading-verbosely* false)

(defn- throw-if
  "Throws an error with a message if pred is true"
  [pred fmt & args]
  (when pred
    (let [message   (apply format fmt (map str args))
          raw-trace (try (throw :ex) (catch :error _ :stack st st))
          ;;boring?   #(not= (.getMethodName %) "doInvoke")
          ;;trace (into-array (drop 2 (drop-while boring? raw-trace)))
          ]
      ;;(.setStackTrace exception trace)
      (throw message raw-trace))))

(defn- libspec?
  "Returns true if x is a libspec"
  [x]
  (or (symbol? x)
      (and (vector? x)
           (or
            (nil? (second x))
            (keyword? (second x))))))

(defn- prependss
  "Prepends a symbol or a seq to coll"
  [x coll]
  (if (symbol? x)
    (cons x coll)
    (concat x coll)))

(defn- root-resource
  "Returns the root directory path for a lib"
  {:tag clojerl.String}
  [lib]
  (str "/" (clj_utils/ns_to_resource (name lib))))

(defn- index-of [s x]
  (let [matches (binary/matches s x)]
    (if (seq matches)
      (ffirst matches)
      -1)))

(defn- last-index-of [s x]
  (let [matches (binary/matches s x)]
    (if (seq matches)
      (first (last matches))
      -1)))

(defn- root-directory
  "Returns the root resource path for a lib"
  [lib]
  (let [d (root-resource lib)]
    (subs d 0 (last-index-of d "/"))))

(def ^:declared ^:redef load)

(defn- load-one
  "Loads a lib given its name. If need-ns, ensures that the associated
  namespace exists after loading. If require, records the load so any
  duplicate loads can be skipped."
  [lib need-ns require]
  (load (root-resource lib))
  (throw-if (and need-ns (not (find-ns lib)))
            "namespace '~s' not found after loading '~s'"
            lib (root-resource lib))
  (when require
    (clj_rt/set! #'*loaded-libs* (conj *loaded-libs* lib))))

(defn- load-all
  "Loads a lib given its name and forces a load of any libs it directly or
  indirectly loads. If need-ns, ensures that the associated namespace
  exists after loading. If require, records the load so any duplicate loads
  can be skipped."
  [lib need-ns require]
  (clj_rt/set! #'*loaded-libs*
                   (reduce conj
                            *loaded-libs*
                            (binding [*loaded-libs* (sorted-set)]
                              (load-one lib need-ns require)
                              *loaded-libs*))))

(defn- load-lib
  "Loads a lib with options"
  [prefix lib & options]
  (throw-if (and prefix (pos? (index-of (name lib) "\\.")))
            "Found lib name '~s' containing period with prefix '~s'.  lib names inside prefix lists must not contain periods"
            (name lib) prefix)
  (let [lib (if prefix (symbol (str prefix \. lib)) lib)
        opts (apply hash-map options)
        as         (:as opts)
        reload     (:reload opts)
        reload-all (:reload-all opts)
        require    (:require opts)
        use        (:use opts)
        verbose    (:verbose opts)
        loaded (contains? @#'*loaded-libs* lib)
        load (cond reload-all
                   load-all
                   (or reload (not require) (not loaded))
                   load-one)
        need-ns (or as use)
        filter-opts (select-keys opts '(:exclude :only :rename :refer))
        undefined-on-entry (not (find-ns lib))]
    (binding [*loading-verbosely* (or *loading-verbosely* verbose)]
      (if load
        (try
          (load lib need-ns require)
          (catch :error e :stack st
            (when undefined-on-entry
              (remove-ns lib))
            (throw e st)))
        (throw-if (and need-ns (not (find-ns lib)))
                  "namespace '~s' not found" lib))
      (when (and need-ns *loading-verbosely*)
        (printf "(clojure.core/in-ns '~s)\n" (str (ns-name *ns*))))
      (when as
        (when *loading-verbosely*
          (printf "(clojure.core/alias '~s '~s)\n" (str as) (str lib)))
        (alias as lib))
      (when (or use (:refer filter-opts))
        (when *loading-verbosely*
          (printf "(clojure.core/refer '~s" (str lib))
          (doseq [opt filter-opts]
            (printf " ~s '~s" (key opt) (print-str (val opt))))
          (printf ")\n"))
        (apply refer lib (mapcat seq filter-opts))))))

(defn- load-libs
  "Loads libs, interpreting libspecs, prefix lists, and flags for
  forwarding to load-lib"
  [& args]
  (let [flags (filter keyword? args)
        opts (interleave flags (repeat true))
        args (filter (complement keyword?) args)]
    ; check for unsupported options
    (let [supported #{:as :reload :reload-all :require :use :verbose :refer}
          unsupported (seq (remove supported flags))]
      (throw-if unsupported
                (apply str "Unsupported option(s) supplied: "
                       (interpose "," unsupported))))
    ; check a load target was specified
    (throw-if (not (seq args)) "Nothing specified to load")
    (doseq [arg args]
      (if (libspec? arg)
        (apply load-lib nil (prependss arg opts))
        (let [prefix (first arg)
              args   (rest arg)]
          (throw-if (nil? prefix) "prefix cannot be nil")
          (doseq [arg args]
            (apply load-lib prefix (prependss arg opts))))))))

(defn- check-cyclic-dependency
  "Detects and rejects non-trivial cyclic load dependencies. The
  exception message shows the dependency chain with the cycle
  highlighted. Ignores the trivial case of a file attempting to load
  itself."
  [path]
  (when (some #{path} (rest *pending-paths*))
    (let [pending (map #(if (= % path) (str "[ " % " ]") %)
                       (cons path *pending-paths*))
          chain (apply str (interpose "->" pending))]
      (throw-if true "Cyclic load dependency: ~s" chain))))

;; Public

(defn require
  "Loads libs, skipping any that are already loaded. Each argument is
  either a libspec that identifies a lib, a prefix list that identifies
  multiple libs whose names share a common prefix, or a flag that modifies
  how all the identified libs are loaded. Use :require in the ns macro
  in preference to calling this directly.

  Libs

  A 'lib' is a named set of resources in codepath whose contents define a
  library of Clojure code. Lib names are symbols and each lib is associated
  with a Clojure namespace and a Erlang module that share its name. A lib's
  name also locates its root directory within codepath using Erlang's
  module name to code-path-relative path mapping. All resources in a lib
  should be contained in the directory structure under its root directory.
  All definitions a lib makes should be in its associated namespace.

  'require loads a lib by loading its root resource. The root resource path
  is derived from the lib name in the following manner:
  Consider a lib named by the symbol 'x.y.z; it has the root directory
  <codepath>/x/y/, and its root resource is <codepath>/x/y/z.clj. The root
  resource should contain code to create the lib's namespace (usually by using
  the ns macro) and load any additional lib resources.

  Libspecs

  A libspec is a lib name or a vector containing a lib name followed by
  options expressed as sequential keywords and arguments.

  Recognized options:
  :as takes a symbol as its argument and makes that symbol an alias to the
    lib's namespace in the current namespace.
  :refer takes a list of symbols to refer from the namespace or the :all
    keyword to bring in all public vars.

  Prefix Lists

  It's common for Clojure code to depend on several libs whose names have
  the same prefix. When specifying libs, prefix lists can be used to reduce
  repetition. A prefix list contains the shared prefix followed by libspecs
  with the shared prefix removed from the lib names. After removing the
  prefix, the names that remain must not contain any periods.

  Flags

  A flag is a keyword.
  Recognized flags: :reload, :reload-all, :verbose
  :reload forces loading of all the identified libs even if they are
    already loaded
  :reload-all implies :reload and also forces loading of all libs that the
    identified libs directly or indirectly load via require or use
  :verbose triggers printing information about each load, alias, and refer

  Example:

  The following would load the libraries clojure.zip and clojure.set
  abbreviated as 's'.

  (require '(clojure zip [set :as s]))"
  {:added "1.0"}

  [& args]
  (apply load-libs :require args))

(defn use
  "Like 'require, but also refers to each lib's namespace using
  clojure.core/refer. Use :use in the ns macro in preference to calling
  this directly.

  'use accepts additional options in libspecs: :exclude, :only, :rename.
  The arguments and semantics for :exclude, :only, and :rename are the same
  as those documented for clojure.core/refer."
  {:added "1.0"}
  [& args] (apply load-libs :require :use args))

(defn loaded-libs
  "Returns a sorted set of symbols naming the currently loaded libs"
  {:added "1.0"}
  [] *loaded-libs*)

(defn load
  "Loads Clojure code from resources in the code path. A path is interpreted
  as code path-relative if it begins with a slash or relative to the root
  directory for the current namespace otherwise."
  {:redef true
   :added "1.0"}
  [& paths]
  (doseq [path paths]
    (let [path (if (clojerl.String/starts_with path "/")
                 path
                 (str (root-directory (ns-name *ns*)) "/" path))]
      (when *loading-verbosely*
        (printf "(clojure.core/load \"~s\")\n" path)
        (flush))
      (check-cyclic-dependency path)
      (when-not (= path (first *pending-paths*))
        (binding [*pending-paths* (conj *pending-paths* path)]
          (clj_rt/load (subs path 1)))))))

(defn compile
  "Compiles the namespace named by the symbol lib into a set of
  beam files. The source for the lib must be in a proper
  codepath-relative directory. The output files will go into the
  directory specified by *compile-path*, and that directory too must
  be in the codepath."
  {:added "1.0"}
  [lib]
  (binding [*compile-files* true]
    (load-one lib true true))
  lib)

(defn load-file
  {:added "1.0"}
  [path]
  (clj_compiler/load_file path))

;;;;;;;;;;;;; nested associative ops ;;;;;;;;;;;

(defn get-in
  "Returns the value in a nested associative structure,
  where ks is a sequence of keys. Returns nil if the key
  is not present, or the not-found value if supplied."
  {:added "1.2"}
  ([m ks]
     (reduce get m ks))
  ([m ks not-found]
     (loop [sentinel (erlang/make_ref)
            m m
            ks (seq ks)]
       (if ks
         (let [m (get m (first ks) sentinel)]
           (if (identical? sentinel m)
             not-found
             (recur sentinel m (next ks))))
         m))))


(defn assoc-in
  "Associates a value in a nested associative structure, where ks is a
  sequence of keys and v is the new value and returns a new nested structure.
  If any levels do not exist, hash-maps will be created."
  {:added "1.0"}
  [m [k & ks] v]
  (if ks
    (assoc m k (assoc-in (get m k) ks v))
    (assoc m k v)))

(defn update-in
  "'Updates' a value in a nested associative structure, where ks is a
  sequence of keys and f is a function that will take the old value
  and any supplied args and return the new value, and returns a new
  nested structure.  If any levels do not exist, hash-maps will be
  created."
  {:added "1.0"}
  ([m [k & ks] f & args]
   (if ks
     (assoc m k (apply update-in (get m k) ks f args))
     (assoc m k (apply f (get m k) args)))))

(defn update
  "'Updates' a value in an associative structure, where k is a
  key and f is a function that will take the old value
  and any supplied args and return the new value, and returns a new
  structure.  If the key does not exist, nil is passed as the old value."
  {:added "1.7"}
  ([m k f]
   (assoc m k (f (get m k))))
  ([m k f x]
   (assoc m k (f (get m k) x)))
  ([m k f x y]
   (assoc m k (f (get m k) x y)))
  ([m k f x y z]
   (assoc m k (f (get m k) x y z)))
  ([m k f x y z & more]
   (assoc m k (apply f (get m k) x y z more))))

(defn empty?
  "Returns true if coll has no items - same as (not (seq coll)).
  Please use the idiom (seq x) rather than (not (empty? x))"
  {:added "1.0"}
  [coll] (not (seq coll)))

(defn coll?
  "Returns true if x implements IPersistentCollection"
  {:added "1.0"}
  [x] (satisfies? clojerl.IColl x))

(defn list?
  "Returns true if x implements IPersistentList"
  {:added "1.0"}
  [x] (or  (instance? clojerl.List x)
           (instance? erlang.List x)))

(defn seqable?
  "Return true if the seq function is supported for x"
  {:added "1.9"}
  [x] (or (nil? x) (satisfies? clojerl.ISeqable x)))

(defn ifn?
  "Returns true if x implements IFn. Note that many data structures
  (e.g. sets and maps) implement IFn"
  {:added "1.0"}
  [x] (satisfies? clojerl.IFn x))

(defn fn?
  "Returns true if x is a function, i.e. an Erlang function,
  a Clojure function or a var with a function as its value."
  {:added "1.0"}
  [x]
  (case* (clj_rt/type_module x)
     :erlang.Fn   true
     :clojerl.Fn  true
     :clojerl.Var (-> x meta :fn? boolean)
     false))

(defn associative?
 "Returns true if coll implements Associative"
 {:added "1.0"}
  [coll] (satisfies? clojerl.IAssociative coll))

(defn sequential?
 "Returns true if coll implements Sequential"
 {:added "1.0"}
  [coll] (satisfies? clojerl.ISequential coll))

(defn sorted?
 "Returns true if coll implements Sorted"
 {:added "1.0"}
  [coll]
  (satisfies? clojerl.ISorted coll))

(defn counted?
 "Returns true if coll implements count in constant time"
 {:added "1.0"}
  [coll] (satisfies? clojerl.ICounted coll))

(defn reversible?
 "Returns true if coll implements Reversible"
 {:added "1.0"}
  [coll]
  (satisfies? clojerl.IReversible coll))

(defn indexed?
  "Return true if coll implements Indexed, indicating efficient lookup by index"
  {:added "1.9"}
  [coll] (satisfies? clojerl.IIndexed coll))

(def ^:dynamic
 ^{:doc "bound in a repl thread to the most recent value printed"
   :added "1.0"}
 *1)

(def ^:dynamic
 ^{:doc "bound in a repl thread to the second most recent value printed"
   :added "1.0"}
 *2)

(def ^:dynamic
 ^{:doc "bound in a repl thread to the third most recent value printed"
   :added "1.0"}
 *3)

(def ^:dynamic
 ^{:doc "bound in a repl thread to the most recent exception caught by the repl"
   :added "1.0"}
 *e)

(def ^:dynamic
 ^{:doc "bound in a repl thread to the stacktrace of the most recent exception caught by the repl"
   :added "1.0"}
 *stacktrace)

(defn trampoline
  "trampoline can be used to convert algorithms requiring mutual
  recursion without stack consumption. Calls f with supplied args, if
  any. If f returns a fn, calls that fn with no arguments, and
  continues to repeat, until the return value is not a fn, then
  returns that non-fn value. Note that if you want to return a fn as a
  final value, you must wrap it in some data structure and unpack it
  after trampoline returns."
  {:added "1.0"}
  ([f]
     (let [ret (f)]
       (if (fn? ret)
         (recur ret)
         ret)))
  ([f & args]
     (trampoline #(apply f args))))

(defn intern
  "Finds or creates a var named by the symbol name in the namespace
  ns (which can be a symbol or a namespace), setting its root binding
  to val if supplied. The namespace must exist. The var will adopt any
  metadata from the name symbol.  Returns the var."
  {:added "1.0"}
  ([ns ^clojerl.Symbol name]
   (throw "unimplemented intern")
   #_(let [v (clojure.lang.Var/intern (the-ns ns) name)]
     (when (meta name) (.setMeta v (meta name)))
     v))
  ([ns name val]
   (throw "unimplemented intern")
   #_(let [v (clojure.lang.Var/intern (the-ns ns) name val)]
     (when (meta name) (.setMeta v (meta name)))
     v)))

(defmacro while
  "Repeatedly executes body while test expression is true. Presumes
  some side-effect will cause test to become false/nil. Returns nil"
  {:added "1.0"}
  [test & body]
  `(loop []
     (when ~test
       ~@body
       (recur))))

(defn memoize
  "Returns a memoized version of a referentially transparent function. The
  memoized version of the function keeps a cache of the mapping from arguments
  to results and, when calls with the same arguments are repeated often, has
  higher performance at the expense of higher memory use."
  {:added "1.0"}
  [f]
  (let [mem (atom {})]
    (fn [& args]
      (if-let [e (find @mem args)]
        (val e)
        (let [ret (apply f args)]
          (swap! mem assoc args ret)
          ret)))))

(defmacro condp
  "Takes a binary predicate, an expression, and a set of clauses.
  Each clause can take the form of either:

  test-expr result-expr

  test-expr :>> result-fn

  Note :>> is an ordinary keyword.

  For each clause, (pred test-expr expr) is evaluated. If it returns
  logical true, the clause is a match. If a binary clause matches, the
  result-expr is returned, if a ternary clause matches, its result-fn,
  which must be a unary function, is called with the result of the
  predicate as its argument, the result of that call being the return
  value of condp. A single default expression can follow the clauses,
  and its value will be returned if no clause matches. If no default
  expression is provided and no clause matches, an error is thrown."
  {:added "1.0"}

  [pred expr & clauses]
  (let [gpred (gensym "pred__")
        gexpr (gensym "expr__")
        emit (fn emit [pred expr args]
               (let [[[a b c :as clause] more]
                     (split-at (if (= :>> (second args)) 3 2) args)
                     n (count clause)]
                 (cond
                   (= 0 n) `(throw (clojerl.BadArgumentError. (str "No matching clause: " ~expr)))
                   (= 1 n) a
                   (= 2 n) `(if (~pred ~a ~expr)
                              ~b
                              ~(emit pred expr more))
                   :else `(if-let [p# (~pred ~a ~expr)]
                            (~c p#)
                            ~(emit pred expr more)))))]
    `(let [~gpred ~pred
           ~gexpr ~expr]
       ~(emit gpred gexpr clauses))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; var documentation ;;;;;;;;;;;;;;;;;;;;;;;;;;

;;(alter-meta! #'*agent* assoc :added "1.0")
;;(alter-meta! #'in-ns assoc :added "1.0")
;;(alter-meta! #'load-file assoc :added "1.0")

(defmacro add-doc-and-meta {:private true} [name docstring meta]
  nil
  #_`(alter-meta! (var ~name) merge (assoc ~meta :doc ~docstring)))

(add-doc-and-meta *file*
  "The path of the file being evaluated, as a String.

  When there is no file, e.g. in the REPL, the value is not defined."
  {:added "1.0"})

(add-doc-and-meta *command-line-args*
  "A sequence of the supplied command line arguments, or nil if
  none were supplied"
  {:added "1.0"})

(add-doc-and-meta *warn-on-infer*
  "When set to true, the compiler will emit warnings when reflection is
  needed to resolve Erlang function calls.

  Defaults to false."
  {:added "1.0"})

(add-doc-and-meta *compile-path*
  "Specifies the directory where 'compile' will write out .beam
  files. This directory must be in the codepath for 'compile' to
  work.

  Defaults to \"ebin\""
  {:added "1.0"})

(add-doc-and-meta *compile-protocol-path*
  "Specifies the directory where 'compile' will write out .beam
  files for protocols. This directory must be in the codepath for
  'compile' to work.

  Defaults to *compile-path*"
  {:added "1.0"})

(add-doc-and-meta *compile-files*
  "Set to true when compiling files, false otherwise."
  {:added "1.0"})

(add-doc-and-meta *compiler-options*
  "A map of keys to options.
  Note, when binding dynamically make sure to merge with previous value.
  Supported options:
  :elide-meta - a collection of metadata keys to elide during compilation.
  :disable-locals-clearing - set to true to disable clearing, useful for using a debugger
  Alpha, subject to change."
  {:added "1.4"})

(add-doc-and-meta *ns*
  "A clojure.lang.Namespace object representing the current namespace."
  {:added "1.0"})

(add-doc-and-meta *in*
  "A erlang.io.IReader object representing standard input for read operations.

  Defaults to System/in, wrapped in a LineNumberingPushbackReader"
  {:added "1.0"})

(add-doc-and-meta *out*
  "A erlang.io.IWriter object representing standard output for print operations.

  Defaults to System/out, wrapped in an OutputStreamWriter"
  {:added "1.0"})

(add-doc-and-meta *err*
  "A erlang.io.IWriter object representing standard error for print operations.

  Defaults to System/err, wrapped in a PrintWriter"
  {:added "1.0"})

(add-doc-and-meta *flush-on-newline*
  "When set to true, output will be flushed whenever a newline is printed.

  Defaults to true."
  {:added "1.0"})

(add-doc-and-meta *print-meta*
  "If set to logical true, when printing an object, its metadata will also
  be printed in a form that can be read back by the reader.

  Defaults to false."
  {:added "1.0"})

(add-doc-and-meta *print-dup*
  "When set to logical true, objects will be printed in a way that preserves
  their type when read in later.

  Defaults to false."
  {:added "1.0"})

(add-doc-and-meta *print-readably*
  "When set to logical false, strings and characters will be printed with
  non-alphanumeric characters converted to the appropriate escape sequences.

  Defaults to true"
  {:added "1.0"})

(add-doc-and-meta *read-eval*
 "Defaults to true (or value specified by system property, see below)
  ***This setting implies that the full power of the reader is in play,
  including syntax that can cause code to execute. It should never be
  used with untrusted sources. See also: clojure.edn/read.***

  When set to logical false in the thread-local binding,
  the eval reader (#=) and record/type literal syntax are disabled in read/load.
  Example (will fail): (binding [*read-eval* false] (read-string \"#=(* 2 21)\"))

  The default binding can be controlled by the application configuration
  parameter 'read_eval'. For more information about application parameters
  please refer to Erlang's documentation.

  The parameter can also be set to ':unknown' and all reads will fail
  in contexts where *read-eval* has not been explicitly bound to either true
  or false. This setting can be a useful diagnostic tool to ensure that all
  of your reads occur in considered contexts. You can also accomplish this in
  a particular scope by binding *read-eval* to :unknown
  "
  {:added "1.0"})

(defn future?
  "Returns true if x is a future"
  {:added "1.1"}
  [x]
  (instance? clojerl.Future x))

(defn future-done?
  "Returns true if future f is done"
  {:added "1.1"}
  [^clojerl.Future f]
  (.done? f))

(defmacro letfn
  "fnspec ==> (fname [params*] exprs) or (fname ([params*] exprs)+)

  Takes a vector of function specs and a body, and generates a set of
  bindings of functions to their names. All of the names are available
  in all of the definitions of the functions, as well as the body."
  {:added "1.0", :forms '[(letfn [fnspecs*] exprs*)],
   :special-form true, :url nil}
  [fnspecs & body]
  `(letfn* ~(vec (interleave (map first fnspecs)
                             (map #(cons `fn %) fnspecs)))
           ~@body))

(defn fnil
  "Takes a function f, and returns a function that calls f, replacing
  a nil first argument to f with the supplied value x. Higher arity
  versions can replace arguments in the second and third
  positions (y, z). Note that the function f can take any number of
  arguments, not just the one(s) being nil-patched."
  {:added "1.2"}
  ([f x]
   (fn
     ([a] (f (if (nil? a) x a)))
     ([a b] (f (if (nil? a) x a) b))
     ([a b c] (f (if (nil? a) x a) b c))
     ([a b c & ds] (apply f (if (nil? a) x a) b c ds))))
  ([f x y]
   (fn
     ([a b] (f (if (nil? a) x a) (if (nil? b) y b)))
     ([a b c] (f (if (nil? a) x a) (if (nil? b) y b) c))
     ([a b c & ds] (apply f (if (nil? a) x a) (if (nil? b) y b) c ds))))
  ([f x y z]
   (fn
     ([a b] (f (if (nil? a) x a) (if (nil? b) y b)))
     ([a b c] (f (if (nil? a) x a) (if (nil? b) y b) (if (nil? c) z c)))
     ([a b c & ds] (apply f (if (nil? a) x a) (if (nil? b) y b) (if (nil? c) z c) ds)))))

;;;;;;; case ;;;;;;;;;;;;;

(defmacro case
  "Takes an expression, and a set of clauses.

  Each clause can take the form of either:

  test-constant result-expr

  (test-constant1 ... test-constantN)  result-expr

  The test-constants are not evaluated. They must be compile-time
  literals, and need not be quoted.  If the expression is equal to a
  test-constant, the corresponding result-expr is returned. A single
  default expression can follow the clauses, and its value will be
  returned if no clause matches. If no default expression is provided
  and no clause matches, an error is thrown.

  Unlike cond and condp, case does a constant-time dispatch, the
  clauses are not considered sequentially.  All manner of constant
  expressions are acceptable in case, including numbers, strings,
  symbols, keywords, and (Clojure) composites thereof. Note that since
  lists are used to group multiple constants that map to the same
  expression, a vector can be used to match a list if needed. The
  test-constants need not be all of the same type."
  {:added "1.2"}

  [e & clauses]
  (let [default (if (odd? (count clauses))
                  (last clauses)
                  `(throw (clojerl.Error. (str "No matching clause: " ~e))))]
    (if (> 2 (count clauses))
      `(let [e# ~e] ~default)
      (let [f     (fn [[k expr]]
                    (if (list? k)
                      (map #(vector % expr) k)
                      [[k expr]]))
            pairs (->> clauses
                       (partition 2)
                       (mapcat f)
                       (zipmap (range)))
            m     (->> pairs
                       (map (fn [[i [v _]]] [(list 'quote  v) i]))
                       (into {}))
            clauses (->> pairs
                         (map (fn [[i [_ expr]]] [i expr]))
                         (apply concat))]
        `(let [i# (~m ~e)]
           (case* i# ~@clauses ~default))))))

;; redefine reduce with internal-reduce

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; helper files ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(alter-meta! (find-ns 'clojure.core) assoc :doc "Fundamental library of the Clojure language")
;; (load "core_proxy")
(load "core_print")
(load "core_deftype")
;; (load "gvec")
;; (load "core/protocols")
(load "instant")

(defprotocol Inst
  (inst-ms* [inst]))

(extend-protocol Inst
  erlang.util.Date
  (inst-ms* [inst] (* 1000 (.timestamp ^erlang.util.Date inst))))

(defn inst-ms
  "Return the number of milliseconds since January 1, 1970, 00:00:00 GMT"
  {:added "1.9"}
  [inst]
  (inst-ms* inst))

(defn inst?
  "Return true if x satisfies Inst"
  {:added "1.9"}
  [x]
  (satisfies? Inst x))

(load "uuid")

(defn uuid?
  "Return true if x is a java.util.UUID"
  {:added "1.9"}
  [x] (instance? erlang.util.UUID x))

; simple reduce based on seqs, used as default
(defn- seq-reduce
  ([f coll]
    (if-let [s (seq coll)]
      (reduce f (first s) (next s))
      (f)))
  ([f val coll]
    (loop [val val, coll (seq coll)]
      (if coll
        (let [nval (f val (first coll))]
          (if (reduced? nval)
            @nval
            (recur nval (next coll))))
        val))))

(defn reduce
  "f should be a function of 2 arguments. If val is not supplied,
  returns the result of applying f to the first 2 items in coll, then
  applying f to that result and the 3rd item, etc. If coll contains no
  items, f must accept no arguments as well, and reduce returns the
  result of calling f with no arguments.  If coll has only 1 item, it
  is returned and f is not called.  If val is supplied, returns the
  result of applying f to val and the first item in coll, then
  applying f to that result and the 2nd item, etc. If coll contains no
  items, returns val and f is not called."
  {:added "1.0"}
  ([f coll]
   (if (satisfies? clojerl.IReduce coll)
     (clojerl.IReduce/reduce coll f)
     (seq-reduce f coll)))
  ([f val coll]
   (if (satisfies? clojerl.IReduce coll)
     (clojerl.IReduce/reduce coll f val)
     (seq-reduce f val coll))))

(defn reduce-kv
  "Reduces an associative collection. f should be a function of 3
  arguments. Returns the result of applying f to init, the first key
  and the first value in coll, then applying f to that result and the
  2nd key and value, etc. If coll contains no entries, returns init
  and f is not called. Note that reduce-kv is supported on vectors,
  where the keys will be the ordinals."
  {:added "1.4"}
  ([f init coll]
   (if-not (nil? coll)
     (.kv-reduce ^clojerl.IKVReduce coll f init)
     init)))

(defn completing
  "Takes a reducing function f of 2 args and returns a fn suitable for
  transduce by adding an arity-1 signature that calls cf (default -
  identity) on the result argument."
  {:added "1.7"}
  ([f] (completing f identity))
  ([f cf]
     (fn
       ([] (f))
       ([x] (cf x))
       ([x y] (f x y)))))

(defn transduce
  "reduce with a transformation of f (xf). If init is not
  supplied, (f) will be called to produce it. f should be a reducing
  step function that accepts both 1 and 2 arguments, if it accepts
  only 2 you can add the arity-1 with 'completing'. Returns the result
  of applying (the transformed) xf to init and the first item in coll,
  then applying xf to that result and the 2nd item, etc. If coll
  contains no items, returns init and f is not called. Note that
  certain transforms may inject or skip items."  {:added "1.7"}
  ([xform f coll] (transduce xform f (f) coll))
  ([xform f init coll]
     (let [f (xform f)
           ret (if (satisfies? clojerl.IReduce coll)
                 (clojerl.IReduce/reduce coll f init)
                 (seq-reduce f init coll))]
       (f ret))))

(defn into
  "Returns a new coll consisting of to-coll with all of the items of
  from-coll conjoined. A transducer may be supplied."
  {:added "1.0"}
  ([to from]
   (reduce conj to from))
  ([to xform from]
   (transduce xform conj to from)))

(defn mapv
  "Returns a vector consisting of the result of applying f to the
  set of first items of each coll, followed by applying f to the set
  of second items in each coll, until any one of the colls is
  exhausted.  Any remaining items in other colls are ignored. Function
  f should accept number-of-colls arguments."
  {:added "1.4"}
  ([f coll]
   (reduce (fn [v o] (conj v (f o))) [] coll))
  ([f c1 c2]
     (into [] (map f c1 c2)))
  ([f c1 c2 c3]
     (into [] (map f c1 c2 c3)))
  ([f c1 c2 c3 & colls]
     (into [] (apply map f c1 c2 c3 colls))))

(defn filterv
  "Returns a vector of the items in coll for which
  (pred item) returns true. pred must be free of side-effects."
  {:added "1.4"}
  [pred coll]
  (reduce (fn [v o] (if (pred o) (conj v o) v))
          []
          coll))

(require '[clojure.erlang.io :as io])

(defn- normalize-slurp-opts
  [opts]
  (if (string? (first opts))
    (do
      (println "WARNING: (slurp f enc) is deprecated, use (slurp f :encoding enc).")
      [:encoding (first opts)])
    opts))

(defn slurp
  "Opens a reader on f and reads all its contents, returning a string.
  See clojure.erlang.io/reader for a complete list of supported arguments."
  {:added "1.0"}
  ([f & opts]
     (let [opts (normalize-slurp-opts opts)]
       (with-open [sw (new erlang.io.StringWriter)
                   r (apply io/reader f opts)]
         (io/copy r sw)
         (str sw)))))

(defn spit
  "Opposite of slurp.  Opens f with writer, writes content, then
  closes f. Options passed to clojure.erlang.io/writer."
  {:added "1.2"}
  [f content & options]
  (with-open [^erlang.io.IWriter w (apply io/writer f options)]
    (erlang.io.IWriter/write w (str content))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; futures (needs proxy);;;;;;;;;;;;;;;;;;
(defn future-call
  "Takes a function of no args and yields a future object that will
  invoke the function in another thread, and will cache the result and
  return it on all subsequent calls to deref/@. If the computation has
  not yet finished, calls to deref/@ will block, unless the variant
  of deref with timeout is used. See also - realized?."
  {:added "1.1"}
  [f]
  (clojerl.Future. (binding-conveyor-fn f)))

(defmacro future
  "Takes a body of expressions and yields a future object that will
  invoke the body in another thread, and will cache the result and
  return it on all subsequent calls to deref/@. If the computation has
  not yet finished, calls to deref/@ will block, unless the variant of
  deref with timeout is used. See also - realized?."
  {:added "1.1"}
  [& body] `(future-call (^{:once true} fn* [] ~@body)))

(defn future-cancel
  "Cancels the future, if possible."
  {:added "1.1"}
  [f]
  (.cancel f))

(defn future-cancelled?
  "Returns true if future f is cancelled"
  {:added "1.1"}
  [f]
  (.cancelled? f))

(defn pmap
  "Like map, except f is applied in parallel. Semi-lazy in that the
  parallel computation stays ahead of the consumption, but doesn't
  realize the entire result unless required. Only useful for
  computationally intensive functions where the time of f dominates
  the coordination overhead."
  {:added "1.0"}
  ([f coll]
   (let [n (+ 2 (erlang/system_info :logical_processors_online))
         rets (map #(future (f %)) coll)
         step (fn step [[x & xs :as vs] fs]
                (lazy-seq
                 (if-let [s (seq fs)]
                   (cons (deref x) (step xs (rest s)))
                   (map deref vs))))]
     (step rets (drop n rets))))
  ([f coll & colls]
   (let [step (fn step [cs]
                (lazy-seq
                 (let [ss (map seq cs)]
                   (when (every? identity ss)
                     (cons (map first ss) (step (map rest ss)))))))]
     (pmap #(apply f %) (step (cons coll colls))))))

(defn pcalls
  "Executes the no-arg fns in parallel, returning a lazy sequence of
  their values"
  {:added "1.0"}
  [& fns] (pmap #(%) fns))

(defmacro pvalues
  "Returns a lazy sequence of the values of the exprs, which are
  evaluated in parallel"
  {:added "1.0"}
  [& exprs]
  `(pcalls ~@(map #(list `fn [] %) exprs)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; clojure version number ;;;;;;;;;;;;;;;;;;;;;;

(def ^:dynamic *clojure-version*
  (let [properties (second (application/get_all_key :clojerl))
        vsn        (:vsn properties)
        version-string (erlang/list_to_binary vsn)
        [_ major minor incremental build ref]
        (re-matches
         #"(?:\w+-)?(\d+)\.(\d+)\.(\d+)(?:-\w+)?(?:\+build\.([a-zA-Z0-9_]+))?(?:\.ref([a-zA-Z0-9_]+))?"
         version-string)
        clojure-version {:major       (and major (erlang/binary_to_integer major))
                         :minor       (and minor (erlang/binary_to_integer minor))
                         :incremental (and incremental (erlang/binary_to_integer incremental))
                         :build       build
                         :ref         ref}]
    (if ref
      (assoc clojure-version :interim true)
      clojure-version)))

(add-doc-and-meta *clojure-version*
  "The version info for Clojure core, as a map containing :major :minor
  :incremental, :build and :ref keys. Feature releases may increment
  :minor and/or :major, bugfix releases will increment :incremental."
  {:added "1.0"})

(defn
  clojure-version
  "Returns clojure version as a printable string."
  {:added "1.0"}
  []
  (str (:major *clojure-version*)
       "."
       (:minor *clojure-version*)
       (when-let [i (:incremental *clojure-version*)]
         (str "." i))
       (when-let [b (:build *clojure-version*)]
         (str "-" b))
       (when-let [r (:ref *clojure-version*)]
         (str "." r))))

(defn promise
  "Returns a promise object that can be read with deref/@, and set,
  once only, with deliver. Calls to deref/@ prior to delivery will
  block, unless the variant of deref with timeout is used. All
  subsequent derefs will return the same delivered value without
  blocking. See also - realized?."
  {:added "1.1"}
  []
  (clojerl.Promise.))

(defn deliver
  "Delivers the supplied value to the promise, releasing any pending
  derefs. A subsequent call to deliver on a promise will have no effect."
  {:added "1.1"}
  [^clojerl.Promise promise val]
  (.deliver promise val))


(defn flatten
  "Takes any nested combination of sequential things (lists, vectors,
  etc.) and returns their contents as a single, flat sequence.
  (flatten nil) returns an empty sequence."
  {:added "1.2"}
  [x]
  (filter (complement sequential?)
          (rest (tree-seq sequential? seq x))))

(defn group-by
  "Returns a map of the elements of coll keyed by the result of
  f on each element. The value at each key will be a vector of the
  corresponding elements, in the order they appeared in coll."
  {:added "1.2"}
  [f coll]
  (reduce
   (fn [ret x]
     (let [k (f x)]
       (assoc ret k (conj (get ret k []) x))))
   {} coll))

(defn partition-by
  "Applies f to each value in coll, splitting it each time f returns a
   new value.  Returns a lazy seq of partitions.  Returns a stateful
   transducer when no collection is provided."
  {:added "1.2"}
  ([f]
   (fn [rf]
    (let [a (process-val! [])
          pv (process-val! ::none)]
      (fn
        ([] (rf))
        ([result]
           (let [result (if (empty? @a)
                          result
                          (let [v @a]
                            ;;clear first!
                            (vreset! a [])
                            (unreduced (rf result v))))]
             (.destroy a)
             (rf result)))
        ([result input]
           (let [pval @pv
                 val (f input)]
             (vreset! pv val)
             (if (or (identical? pval ::none)
                     (= val pval))
               (do
                 (vswap! a conj input)
                 result)
               (let [v @a]
                 (vreset! a [])
                 (let [ret (rf result v)]
                   (when-not (reduced? ret)
                     (vswap! a conj input))
                   ret)))))))))
  ([f coll]
     (lazy-seq
      (when-let [s (seq coll)]
        (let [fst (first s)
              fv (f fst)
              run (cons fst (take-while #(= fv (f %)) (next s)))]
          (cons run (partition-by f (seq (drop (count run) s)))))))))

(defn frequencies
  "Returns a map from distinct items in coll to the number of times
  they appear."
  {:added "1.2"}
  [coll]
  (reduce (fn [counts x]
            (assoc counts x (inc (get counts x 0))))
          {} coll))

(defn reductions
  "Returns a lazy seq of the intermediate values of the reduction (as
  per reduce) of coll by f, starting with init."
  {:added "1.2"}
  ([f coll]
     (lazy-seq
      (if-let [s (seq coll)]
        (reductions f (first s) (rest s))
        (list (f)))))
  ([f init coll]
     (if (reduced? init)
       (list @init)
       (cons init
             (lazy-seq
              (when-let [s (seq coll)]
                (reductions f (f init (first s)) (rest s))))))))

(defn rand-nth
  "Return a random element of the (sequential) collection. Will have
  the same performance characteristics as nth for the given
  collection."
  {:added "1.2"}
  [coll]
  (nth coll (rand-int (count coll))))

(defn partition-all
  "Returns a lazy sequence of lists like partition, but may include
  partitions with fewer than n items at the end.  Returns a stateful
  transducer when no collection is provided."
  {:added "1.2"}
  ([n]
   (fn [rf]
     (let [a (process-val! [])]
       (fn
         ([] (rf))
         ([result]
            (let [result (if (empty? @a)
                           result
                           (let [v @a]
                             ;;clear first!
                             (vreset! a [])
                             (unreduced (rf result v))))]
              (.destroy a)
              (rf result)))
         ([result input]
            (vswap! a conj input)
            (if (= n (count @a))
              (let [v @a]
                (vreset! a [])
                (rf result v))
              result))))))
  ([n coll]
     (partition-all n n coll))
  ([n step coll]
     (lazy-seq
      (when-let [s (seq coll)]
        (let [seg (doall (take n s))]
          (cons seg (partition-all n step (nthrest s step))))))))

(defn shuffle
  "Return a random permutation of coll"
  {:added "1.2"}
  [coll]
  (clj_rt/shuffle coll))

(defn map-indexed
  "Returns a lazy sequence consisting of the result of applying f to 0
  and the first item of coll, followed by applying f to 1 and the second
  item in coll, etc, until coll is exhausted. Thus function f should
  accept 2 arguments, index and item. Returns a stateful transducer when
  no collection is provided."
  {:added "1.2"}
  ([f]
   (fn [rf]
     (let [i (process-val! -1)]
       (fn
         ([] (rf))
         ([result]
            (.destroy i)
            (rf result))
         ([result input]
          (rf result (f (vswap! i inc) input)))))))
  ([f coll]
   (letfn [(mapi [idx coll]
                 (lazy-seq
                   (when-let [s (seq coll)]
                     (if (chunked-seq? s)
                       (let [^clojerl.TupleChunk c (chunk-first s)
                             size (int (count c))
                             b (loop [b (chunk-buffer size) i 0]
                                 (if (< i size)
                                   (recur (chunk-append b (f (+ idx i) (.nth c i)))
                                          (inc i))
                                   b))]
                         (chunk-cons (chunk b) (mapi (+ idx size) (chunk-rest s))))
                       (cons (f idx (first s)) (mapi (inc idx) (rest s)))))))]
     (mapi 0 coll))))

(defn keep
  "Returns a lazy sequence of the non-nil results of (f item). Note,
  this means false return values will be included.  f must be free of
  side-effects.  Returns a transducer when no collection is provided."
  {:added "1.2"}
  ([f]
   (fn [rf]
     (fn
       ([] (rf))
       ([result] (rf result))
       ([result input]
          (let [v (f input)]
            (if (nil? v)
              result
              (rf result v)))))))
  ([f coll]
   (lazy-seq
    (when-let [s (seq coll)]
      (if (chunked-seq? s)
        (let [^clojerl.TupleChunk c (chunk-first s)
              size (count c)
              b (loop [b (chunk-buffer size) i 0]
                  (if (< i size)
                    (let [x (f (.nth c i))]
                      (recur (if (nil? x) b (chunk-append b x))
                             (inc i)))
                    b))]
          (chunk-cons (chunk b) (keep f (chunk-rest s))))
        (let [x (f (first s))]
          (if (nil? x)
            (keep f (rest s))
            (cons x (keep f (rest s))))))))))

(defn keep-indexed
  "Returns a lazy sequence of the non-nil results of (f index item). Note,
  this means false return values will be included.  f must be free of
  side-effects.  Returns a stateful transducer when no collection is
  provided."
  {:added "1.2"}
  ([f]
   (fn [rf]
     (let [iv (process-val! -1)]
       (fn
         ([] (rf))
         ([result]
            (.destroy iv)
            (rf result))
         ([result input]
            (let [i (vswap! iv inc)
                  v (f i input)]
              (if (nil? v)
                result
                (rf result v))))))))
  ([f coll]
     (letfn [(keepi [idx coll]
               (lazy-seq
                (when-let [s (seq coll)]
                  (if (chunked-seq? s)
                    (let [^clojerl.TupleChunk c (chunk-first s)
                          size (count c)
                          b (loop [b (chunk-buffer size) i 0]
                              (if (< i size)
                                (let [x (f (+ idx i) (.nth c i))]
                                  (recur (if (nil? x) b (chunk-append b x))
                                         (inc i)))
                                b))]
                      (chunk-cons (chunk b) (keepi (+ idx size) (chunk-rest s))))
                    (let [x (f idx (first s))]
                      (if (nil? x)
                        (keepi (inc idx) (rest s))
                        (cons x (keepi (inc idx) (rest s)))))))))]
       (keepi 0 coll))))

(defn every-pred
  "Takes a set of predicates and returns a function f that returns true if all of its
  composing predicates return a logical true value against all of its arguments, else it returns
  false. Note that f is short-circuiting in that it will stop execution on the first
  argument that triggers a logical false result against the original predicates."
  {:added "1.3"}
  ([p]
     (fn ep1
       ([] true)
       ([x] (boolean (p x)))
       ([x y] (boolean (and (p x) (p y))))
       ([x y z] (boolean (and (p x) (p y) (p z))))
       ([x y z & args] (boolean (and (ep1 x y z)
                                     (every? p args))))))
  ([p1 p2]
     (fn ep2
       ([] true)
       ([x] (boolean (and (p1 x) (p2 x))))
       ([x y] (boolean (and (p1 x) (p1 y) (p2 x) (p2 y))))
       ([x y z] (boolean (and (p1 x) (p1 y) (p1 z) (p2 x) (p2 y) (p2 z))))
       ([x y z & args] (boolean (and (ep2 x y z)
                                     (every? #(and (p1 %) (p2 %)) args))))))
  ([p1 p2 p3]
     (fn ep3
       ([] true)
       ([x] (boolean (and (p1 x) (p2 x) (p3 x))))
       ([x y] (boolean (and (p1 x) (p2 x) (p3 x) (p1 y) (p2 y) (p3 y))))
       ([x y z] (boolean (and (p1 x) (p2 x) (p3 x) (p1 y) (p2 y) (p3 y) (p1 z) (p2 z) (p3 z))))
       ([x y z & args] (boolean (and (ep3 x y z)
                                     (every? #(and (p1 %) (p2 %) (p3 %)) args))))))
  ([p1 p2 p3 & ps]
     (let [ps (list* p1 p2 p3 ps)]
       (fn epn
         ([] true)
         ([x] (every? #(% x) ps))
         ([x y] (every? #(and (% x) (% y)) ps))
         ([x y z] (every? #(and (% x) (% y) (% z)) ps))
         ([x y z & args] (boolean (and (epn x y z)
                                       (every? #(every? % args) ps))))))))

(defn some-fn
  "Takes a set of predicates and returns a function f that returns the first logical true value
  returned by one of its composing predicates against any of its arguments, else it returns
  logical false. Note that f is short-circuiting in that it will stop execution on the first
  argument that triggers a logical true result against the original predicates."
  {:added "1.3"}
  ([p]
     (fn sp1
       ([] nil)
       ([x] (p x))
       ([x y] (or (p x) (p y)))
       ([x y z] (or (p x) (p y) (p z)))
       ([x y z & args] (or (sp1 x y z)
                           (some p args)))))
  ([p1 p2]
     (fn sp2
       ([] nil)
       ([x] (or (p1 x) (p2 x)))
       ([x y] (or (p1 x) (p1 y) (p2 x) (p2 y)))
       ([x y z] (or (p1 x) (p1 y) (p1 z) (p2 x) (p2 y) (p2 z)))
       ([x y z & args] (or (sp2 x y z)
                           (some #(or (p1 %) (p2 %)) args)))))
  ([p1 p2 p3]
     (fn sp3
       ([] nil)
       ([x] (or (p1 x) (p2 x) (p3 x)))
       ([x y] (or (p1 x) (p2 x) (p3 x) (p1 y) (p2 y) (p3 y)))
       ([x y z] (or (p1 x) (p2 x) (p3 x) (p1 y) (p2 y) (p3 y) (p1 z) (p2 z) (p3 z)))
       ([x y z & args] (or (sp3 x y z)
                           (some #(or (p1 %) (p2 %) (p3 %)) args)))))
  ([p1 p2 p3 & ps]
     (let [ps (list* p1 p2 p3 ps)]
       (fn spn
         ([] nil)
         ([x] (some #(% x) ps))
         ([x y] (some #(or (% x) (% y)) ps))
         ([x y z] (some #(or (% x) (% y) (% z)) ps))
         ([x y z & args] (or (spn x y z)
                             (some #(some % args) ps)))))))

(defn- ^{:dynamic true} assert-valid-fdecl
  "A good fdecl looks like (([a] ...) ([a b] ...)) near the end of defn."
  [fdecl]
  (when (empty? fdecl)
    (throw (clojerl.BadArgumentError. "Parameter declaration missing")))
  (let [argdecls (map
                   #(if (seq? %)
                      (first %)
                      (throw (clojerl.BadArgumentError.
                              (if (seq? (first fdecl))
                                (str "Invalid signature \""
                                     %
                                     "\" should be a list")
                                (str "Parameter declaration \""
                                     %
                                     "\" should be a vector")))))
                   fdecl)
        bad-args (seq (remove #(vector? %) argdecls))]
    (when bad-args
      (throw (clojerl.BadArgumentError.
              (str "Parameter declaration \"" (first bad-args)
                   "\" should be a vector"))))))

(defn with-redefs-fn
  "Temporarily redefines Vars during a call to func.  Each val of
  binding-map will replace the root value of its key which must be
  a Var.  After func is called with no args, the root values of all
  the Vars will be set back to their old values.  These temporary
  changes will be visible in all threads.  Useful for mocking out
  functions during testing."
  {:added "1.3"}
  [binding-map func]
  (throw "unimplemented with-redefs-fn")
  #_(let [root-bind (fn [m]
                    (doseq [[a-var a-val] m]
                      (.bindRoot a-var a-val)))
        old-vals (zipmap (keys binding-map)
                         (map #(.getRawRoot ^clojure.lang.Var %) (keys binding-map)))]
    (try
      (root-bind binding-map)
      (func)
      (finally
        (root-bind old-vals)))))

(defmacro with-redefs
  "binding => var-symbol temp-value-expr

  Temporarily redefines Vars while executing the body.  The
  temp-value-exprs will be evaluated and each resulting value will
  replace in parallel the root value of its Var.  After the body is
  executed, the root values of all the Vars will be set back to their
  old values.  These temporary changes will be visible in all threads.
  Useful for mocking out functions during testing."
  {:added "1.3"}
  [bindings & body]
  `(with-redefs-fn ~(zipmap (map #(list `var %) (take-nth 2 bindings))
                            (take-nth 2 (next bindings)))
                    (fn [] ~@body)))

(defn realized?
  "Returns true if a value has been produced for a promise, delay, future or lazy sequence."
  {:added "1.3"}
  [x]
  (.realized? x))

(defmacro cond->
  "Takes an expression and a set of test/form pairs. Threads expr (via ->)
  through each form for which the corresponding test
  expression is true. Note that, unlike cond branching, cond-> threading does
  not short circuit after the first true test expression."
  {:added "1.5"}
  [expr & clauses]
  (assert (even? (count clauses)))
  (let [g (gensym)
        steps (map (fn [[test step]] `(if ~test (-> ~g ~step) ~g))
                   (partition 2 clauses))]
    `(let [~g ~expr
           ~@(interleave (repeat g) (butlast steps))]
       ~(if (empty? steps)
          g
          (last steps)))))

(defmacro cond->>
  "Takes an expression and a set of test/form pairs. Threads expr (via ->>)
  through each form for which the corresponding test expression
  is true.  Note that, unlike cond branching, cond->> threading does not short circuit
  after the first true test expression."
  {:added "1.5"}
  [expr & clauses]
  (assert (even? (count clauses)))
  (let [g (gensym)
        steps (map (fn [[test step]] `(if ~test (->> ~g ~step) ~g))
                   (partition 2 clauses))]
    `(let [~g ~expr
           ~@(interleave (repeat g) (butlast steps))]
       ~(if (empty? steps)
          g
          (last steps)))))

(defmacro as->
  "Binds name to expr, evaluates the first form in the lexical context
  of that binding, then binds name to that result, repeating for each
  successive form, returning the result of the last form."
  {:added "1.5"}
  [expr name & forms]
  `(let [~name ~expr
         ~@(interleave (repeat name) (butlast forms))]
     ~(if (empty? forms)
        name
        (last forms))))

(defmacro some->
  "When expr is not nil, threads it into the first form (via ->),
  and when that result is not nil, through the next etc"
  {:added "1.5"}
  [expr & forms]
  (let [g (gensym)
        steps (map (fn [step] `(if (nil? ~g) nil (-> ~g ~step)))
                   forms)]
    `(let [~g ~expr
           ~@(interleave (repeat g) (butlast steps))]
       ~(if (empty? steps)
          g
          (last steps)))))

(defmacro some->>
  "When expr is not nil, threads it into the first form (via ->>),
  and when that result is not nil, through the next etc"
  {:added "1.5"}
  [expr & forms]
  (let [g (gensym)
        steps (map (fn [step] `(if (nil? ~g) nil (->> ~g ~step)))
                   forms)]
    `(let [~g ~expr
           ~@(interleave (repeat g) (butlast steps))]
       ~(if (empty? steps)
          g
          (last steps)))))

(defn ^:private preserving-reduced
  [rf]
  #(let [ret (rf %1 %2)]
     (if (reduced? ret)
       (reduced ret)
       ret)))

(defn cat
  "A transducer which concatenates the contents of each input, which must be a
  collection, into the reduction."
  {:added "1.7"}
  [rf]
  (let [rrf (preserving-reduced rf)]
    (fn
      ([] (rf))
      ([result] (rf result))
      ([result input]
         (reduce rrf result input)))))

(defn dedupe
  "Returns a sequence removing consecutive duplicates in coll.
  Returns a transducer when no collection is provided.

  NOTE: the returned sequence is *not* lazy, because of how
  lazy sequences work in clojerl, where the realized values
  are not cached, and the fact that the internal state of this
  transducer is destroyed once it reached the end of the
  collection."
  {:added "1.7"}
  ([]
   (fn [rf]
     (let [pv (process-val! ::none)]
       (fn
         ([] (rf))
         ([result]
            (.destroy pv)
            (rf result))
         ([result input]
            (let [prior @pv]
              (vreset! pv input)
              (if (= prior input)
                result
                (rf result input))))))))
  ([coll] (doall (sequence (dedupe) coll))))

(defn random-sample
  "Returns items from coll with random probability of prob (0.0 -
  1.0).  Returns a transducer when no collection is provided."
  {:added "1.7"}
  ([prob]
     (filter (fn [_] (< (rand) prob))))
  ([prob coll]
     (filter (fn [_] (< (rand) prob)) coll)))

(deftype Eduction [xform coll]
  clojerl.ISeqable
  (seq [this]
    (when (seq coll)
      (seq (clojerl.TransducerSeq. xform coll))))
  (to_list [this]
    (-> this seq clj_rt/to_list))

  clojerl.IReduce
  (reduce [this f] (transduce xform (completing f) coll))
  (reduce [this f init] (transduce xform (completing f) init coll))

  clojerl.IEquiv
  (equiv [this x] (= (.to_list this) x))

  clojerl.ISequential)

(defn eduction
  "Returns a reducible/iterable application of the transducers
  to the items in coll. Transducers are applied in order as if
  combined with comp. Note that these applications will be
  performed every time reduce/iterator is called."
  {:arglists '([xform* coll])
   :added "1.7"}
  [& xforms]
  (new Eduction (apply comp (butlast xforms)) (last xforms)))

(defmethod print-method Eduction [c, ^erlang.io.IWriter w]
  (if *print-readably*
    (do
      (print-sequential "(" pr-on " " ")" c w))
    (print-simple c w)))

(defn run!
  "Runs the supplied procedure (via reduce), for purposes of side
  effects, on successive items in the collection. Returns nil"
  {:added "1.7"}
  [proc coll]
  (reduce #(proc %2) nil coll)
  nil)


(defn tagged-literal?
  "Return true if the value is the data representation of a tagged literal"
  {:added "1.7"}
  [value]
  (instance? clojerl.reader.TaggedLiteral value))

(defn tagged-literal
  "Construct a data representation of a tagged literal from a
  tag symbol and a form."
  {:added "1.7"}
  [^clojerl.Symbol tag form]
  (new clojerl.reader.TaggedLiteral tag form))

(defn reader-conditional?
  "Return true if the value is the data representation of a reader conditional"
  {:added "1.7"}
  [value]
  (instance? clojerl.reader.ReaderConditional value))

(defn reader-conditional
  "Construct a data representation of a reader conditional.
  If true, splicing? indicates read-cond-splicing."
  {:added "1.7"}
  [form ^clojerl.Boolean splicing?]
  (new clojerl.reader.ReaderConditional form splicing?))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; data readers ;;;;;;;;;;;;;;;;;;

(def ^{:added "1.4"} default-data-readers
  "Default map of data reader functions provided by Clojure. May be
  overridden by binding *data-readers*."
  {'inst #'clojure.instant/read-instant-date
   'uuid #'clojure.uuid/default-uuid-reader})

(def ^{:added "1.4" :dynamic true} *data-readers*
  "Map from reader tag symbols to data reader Vars.

  When Clojure starts, it searches for files named 'data_readers.clj'
  at the root of the codepath. Each such file must contain a literal
  map of symbols, like this:

      {foo/bar my.project.foo/bar
       foo/baz my.project/baz}

  The first symbol in each pair is a tag that will be recognized by
  the Clojure reader. The second symbol in the pair is the
  fully-qualified name of a Var which will be invoked by the reader to
  parse the form following the tag. For example, given the
  data_readers.clj file above, the Clojure reader would parse this
  form:

      #foo/bar [1 2 3]

  by invoking the Var #'my.project.foo/bar on the vector [1 2 3]. The
  data reader function is invoked on the form AFTER it has been read
  as a normal Clojure data structure by the reader.

  Reader tags without namespace qualifiers are reserved for
  Clojure. Default reader tags are defined in
  clojure.core/default-data-readers but may be overridden in
  data_readers.clj or by rebinding this Var."
  {})

(def ^{:added "1.5" :dynamic true} *default-data-reader-fn*
  "When no data reader is found for a tag and *default-data-reader-fn*
  is non-nil, it will be called with two arguments,
  the tag and the value.  If *default-data-reader-fn* is nil (the
  default), an exception will be thrown for the unknown tag."
  nil)

;; (defn- data-reader-urls []
;;   (let [cl (.. Thread currentThread getContextClassLoader)]
;;     (concat
;;       (enumeration-seq (.getResources cl "data_readers.clj"))
;;       (enumeration-seq (.getResources cl "data_readers.cljc")))))

;; (defn- data-reader-var [sym]
;;   (intern (create-ns (symbol (namespace sym)))
;;           (symbol (name sym))))

;; (defn- load-data-reader-file [mappings ^java.net.URL url]
;;   (with-open [rdr (clojure.lang.LineNumberingPushbackReader.
;;                    (java.io.InputStreamReader.
;;                     (.openStream url) "UTF-8"))]
;;     (binding [*file* (.getFile url)]
;;       (let [read-opts (if (.endsWith (.getPath url) "cljc")
;;                         {:eof nil :read-cond :allow}
;;                         {:eof nil})
;;             new-mappings (read read-opts rdr)]
;;         (when (not (map? new-mappings))
;;           (throw (ex-info (str "Not a valid data-reader map")
;;                           {:url url})))
;;         (reduce
;;          (fn [m [k v]]
;;            (when (not (symbol? k))
;;              (throw (ex-info (str "Invalid form in data-reader file")
;;                              {:url url
;;                               :form k})))
;;            (let [v-var (data-reader-var v)]
;;              (when (and (contains? mappings k)
;;                         (not= (mappings k) v-var))
;;                (throw (ex-info "Conflicting data-reader mapping"
;;                                {:url url
;;                                 :conflict k
;;                                 :mappings m})))
;;              (assoc m k v-var)))
;;          mappings
;;          new-mappings)))))

;; (defn- load-data-readers []
;;   (alter-var-root #'*data-readers*
;;                   (fn [mappings]
;;                     (reduce load-data-reader-file
;;                             mappings (data-reader-urls)))))

;; (try
;;  (load-data-readers)
;;  (catch Throwable t
;;    (.printStackTrace t)
;;    (throw t)))

;;------------------------------------------------------------------------------
;;------------------------------------------------------------------------------

(defmacro simple-benchmark
  "Runs expr iterations times in the context of a let expression with
  the given bindings, then prints out the bindings and the expr
  followed by number of iterations and total time. The optional
  argument print-fn, defaulting to println, sets function used to
  print the result. expr's string representation will be produced
  using pr-str in any case."
  {:added "1.0"}
  [bindings expr iterations & {:keys [print-fn] :or {print-fn 'println}}]
  (let [bs-str   (pr-str bindings)
        expr-str (pr-str expr)]
    `(let ~bindings
       (let [start#   (erlang/monotonic_time :nano_seconds)
             ret#     (dotimes [_# ~iterations] ~expr)
             end#     (erlang/monotonic_time :nano_seconds)
             elapsed# (int (/ (- end# start#) 1000000))]
         (~print-fn (str ~bs-str ", " ~expr-str ", "
                      ~iterations " runs, " elapsed# " msecs"))))))
