              "document.write('<script>if (typeof goog != \"undefined\") { goog.require(\"" (comp/munge (:main opts))
              "\"); } else { console.warn(\"ClojureScript could not load :main, did you forget to specify :asset-path?\"); };</script>');\n")))))
 
+(declare foreign-deps-str)
+
 (defn output-modules
   "Given compiler options and a sequence of module name and module description
    tuples output module sources to disk. Modules description must define
    :output-to and supply :source entry with the JavaScript source to write
    to disk."
-  [opts {:keys [foreign-deps modules]}]
-  (doseq [[name {:keys [output-to source] :as module-desc}] modules]
+  [opts modules]
+  (doseq [[name {:keys [output-to source foreign-deps] :as module-desc}] modules]
     (assert (not (nil? output-to))
       (str "Module " name " does not define :output-to"))
     (assert (not (nil? source))
       (str "Module " name " did not supply :source"))
-    (spit (io/file output-to) source)
+    (spit (io/file output-to)
+      (if-not (empty? foreign-deps)
+        (str (foreign-deps-str opts foreign-deps) "\n" source)
+        source))
     (when (:source-map opts)
       (spit (io/file (:source-map-name module-desc))
         (:source-map-json module-desc)))))


(defn optimize-modules
  "Use the Closure Compiler to optimize one or more Closure JSModules. Returns
   a modules map containing :foreign-deps, a dependency sorted list of foreign
   dependencies, and :modules a dependency sorted list of module name and
   description tuples."
  [opts & sources]
  {:pre [(and (contains? opts :modules)
              (not (contains? opts :output-to)))]}

        sources (if (= :whitespace (:optimizations opts))
                  (cons "var CLOSURE_NO_DEPS = true;" sources)
                  sources)
        modules (build-modules sources opts)
        ^List inputs (map (comp :closure-module second) modules)
        _ (doseq [^JSModule input inputs]
            (.sortInputsByDeps input closure-compiler))
