(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)

(def loop-count 1000000)
(def expected-checksum 15000001)

(defn configured-loop-count []
  (try
    (let [line (read-line)
          value (Integer/parseInt (.trim ^String line))]
      (if (pos? value) value loop-count))
    (catch Exception _
      loop-count)))

(defn configured-target []
  (or (first *command-line-args*) "slo\"vo\\path"))

(defn quote-json-string [^String value]
  (let [builder (StringBuilder.)]
    (.append builder \")
    (dotimes [index (.length value)]
      (let [ch (.charAt value index)]
        (case ch
          \" (.append builder "\\\"")
          \\ (.append builder "\\\\")
          \newline (.append builder "\\n")
          \tab (.append builder "\\t")
          \return (.append builder "\\r")
          (.append builder ch))))
    (.append builder \")
    (.toString builder)))

(defn json-quote-loop [limit target]
  (loop [i 0
         acc 1]
    (if (< i limit)
      (recur (inc i) (+ acc (.length ^String (quote-json-string target))))
      acc)))

(let [result (json-quote-loop (configured-loop-count) (configured-target))]
  (println result)
  (System/exit (if (= result expected-checksum) 0 1)))
