;;; ==========================================================================
;;;  DWG2DXF.lsp  v3.5  -  batch DWG to DXF for AutoCAD and AutoCAD LT
;;;  Batch conversion of DWG -> ASCII DXF, binding external references
;;;  before the export (the DXF format cannot hold DWG xrefs).
;;;  Requires AutoCAD LT 2024 or later, or any full AutoCAD (Windows).
;;;  (AutoCAD LT supports AutoLISP only from version 2024 onwards; there is
;;;   no upper limit - the program checks at run time what it needs.)
;;;
;;;  Copyright (c) 2026 FreudsCAT.  Released under the MIT License.
;;;  https://github.com/FreudsCAT/dwg2dxf
;;;  Free to use, modify and redistribute, commercially or otherwise,
;;;  provided this notice and the LICENSE text travel with the code.
;;;
;;;  LANGUAGE INDEPENDENCE
;;;     Every AutoCAD command and option keyword is issued with the leading
;;;     underscore form (_.OPEN, _.SAVEAS, _DXF, _V, _B, _Y). That form is the
;;;     international one: it runs unchanged on a Spanish, German or English
;;;     installation. Only the user interface texts of this program are in
;;;     English; the commands sent to AutoCAD are locale independent.
;;;     Never write the localized name (_ABRE and the like) - it will fail.
;;;
;;;  COMMANDS
;;;     DWG2DXF   Converts every DWG in a folder and its subfolders.
;;;               At the folder prompt: ENTER accepts the default folder,
;;;               * opens a folder browser inside the command line itself,
;;;               or a path can be pasted with Ctrl+V.
;;;     DXFCFG    Shows the current configuration.
;;;     DXFRESET  Restores FILEDIA/CMDDIA/EXPERT/SDI if a batch is aborted
;;;               with ESC. (This command was named DXFRESTAURA in v2.8.)
;;;     DXFPATH   Registers the path of this file (once, remembered between
;;;               sessions) so the batch can reload the program when it ends.
;;;
;;;  INSTALLATION - IMPORTANT
;;;     Load the file through the *Startup Suite* of APPLOAD, not with a plain
;;;     one-off load. AutoLISP definitions live inside the document they were
;;;     loaded in: as soon as the batch opens the first drawing, the commands
;;;     above cease to exist in the new document, and typing DXFRESET when the
;;;     batch ends answers "no function definition". The Startup Suite loads
;;;     the file into every drawing and removes the problem for good.
;;;     Two fallbacks are built in for when it is not installed that way:
;;;       - the script reloads the whole program at the end if the path of this
;;;         file is known (findfile, or registered once with DXFPATH);
;;;       - failing that, the script carries a self-contained definition of
;;;         DXFRESET, so the rescue command always exists when the batch ends.
;;;
;;;  EXTERNAL REFERENCES
;;;     Before writing each DXF the program detects whether the drawing has
;;;     xrefs and binds them with -XREF Bind *, repeating up to 3 times in
;;;     case of nested xrefs. Two modes (system variable BINDTYPE):
;;;        Insert (BINDTYPE=1) layers keep their original name
;;;        Bind   (BINDTYPE=0) layers end up as xref$0$name
;;;     The source DWG is NEVER modified: the bind happens in memory and is
;;;     only written out to the resulting DXF.
;;;     Raster images and PDF underlays cannot be bound: if the drawing uses
;;;     them, they remain external references inside the DXF.
;;;
;;;  AEC OBJECTS (architectural drawings)
;;;     AEC walls, doors and windows do not exist in the DXF format: they are
;;;     stored as proxy objects together with their graphical representation.
;;;     They still display and plot the same, but they stop being intelligent
;;;     objects. This is why the batch forces PROXYGRAPHICS=1, so that the
;;;     representation travels inside the DXF and the receiving machine does
;;;     not see empty gaps.
;;;
;;;  HOW IT WORKS
;;;     AutoLISP cannot open another drawing by itself (the program dies as
;;;     soon as the active document changes). DWG2DXF therefore locates the
;;;     DWG files, writes a SCRIPT (.scr) holding the OPEN / XREF / SAVEAS DXF
;;;     orders and launches it automatically. On completion it leaves a log
;;;     file (DWG2DXF-log.txt) in the root folder.
;;;     The script NEVER uses CLOSE: an AutoCAD script dies if it closes the
;;;     document it is running in. Single document mode (SDI=1) is used
;;;     instead, so each OPEN replaces the previous drawing.
;;;
;;;  SAFETY
;;;     - The script never sends a "just in case" ENTER: an ENTER with no
;;;       active command REPEATS the last command. To clear a command left
;;;       hanging it uses (command), which is equivalent to ESC.
;;;     - Every bind and every SAVEAS runs only if the intended drawing is
;;;       really open. No DWG is ever overwritten: the only thing written to
;;;       disk is the DXF.
;;;     - Drawings that are open elsewhere (with a .dwl lock file) are skipped.
;;;     - If a drawing fails, ERROR is written to the log and the batch carries
;;;       on with the next one. When it ends, review the log and run DWG2DXF
;;;       again: the drawings already converted are skipped.
;;;
;;;  The file is pure ASCII (accented letters are built with (chr ..)), so it
;;;  can be saved as ANSI or as UTF-8 indistinctly.
;;; ==========================================================================

;;; --------------------------- DEFAULT SETTINGS -----------------------------
;;; Edit these values to suit the installation.

;; Folder offered by default when the batch asks where to start. Set it to the
;; folder you work from most often.
;; If it contains accented characters, build them with (chr ..) instead of typing
;; them, so this file stays pure ASCII and cannot be corrupted by an editor
;; saving it as UTF-8. For example, "C:/Proyectos/Tecnicos/" with an accent:
;;    (setq *dxf-root* (strcat "C:/Proyectos/T" (chr 233) "cnicos/"))
(setq *dxf-root*    "C:/")
(setq *dxf-dxfver*  "2013")   ; 2018 / 2013 / 2010 / 2007 / 2004 / 2000 / R12
(setq *dxf-newonly* T)        ; T = only when the DWG is newer than the DXF
(setq *dxf-recurse* T)        ; T = include subfolders
(setq *dxf-xref*    1)        ; 1 = bind by insert, 0 = classic bind, nil = do not bind
(setq *dxf-audit*   T)        ; T = AUDIT each drawing before exporting
(setq *dxf-page*    10)       ; subfolders listed per page in the folder browser

;; Full path of this very file, used to reload the whole program into the last
;; drawing the batch leaves open (LISP definitions do not survive a document
;; change). Plain AutoLISP cannot ask "where was I loaded from", so it is looked
;; up in three places, in order:
;;   1. the support file search path, through findfile;
;;   2. the path registered once with the DXFPATH command, kept in the AutoCAD
;;      profile with setenv so it survives between sessions;
;;   3. nothing - in which case the batch still writes a self-contained
;;      definition of DXFRESET into the tail of the script, so the rescue
;;      command always exists when the batch ends.
;; The path can also be hard coded here, e.g. (setq *dxf-lsp* "C:/lisp/DWG2DXF.lsp").
(setq *dxf-lsp*
  (cond
    ((findfile "DWG2DXF.lsp"))
    ((and (getenv "DWG2DXF-LSP") (findfile (getenv "DWG2DXF-LSP"))))
  )
)

;;; ------------------------------- HELPERS ----------------------------------

;; Replaces backslashes with forward slashes (AutoCAD accepts both)
(defun dxf:slash (s / i c r)
  (setq i 1 r "")
  (while (<= i (strlen s))
    (setq c (substr s i 1))
    (setq r (strcat r (if (= c "\\") "/" c)))
    (setq i (1+ i))
  )
  r
)

;; Makes sure a folder path ends with "/"
(defun dxf:trailslash (s)
  (if (and (> (strlen s) 0) (/= (substr s (strlen s) 1) "/"))
    (strcat s "/")
    s
  )
)

;; Position of the last character c inside s (0 if not present)
(defun dxf:lastpos (s c / i p)
  (setq i 1 p 0)
  (while (<= i (strlen s))
    (if (= (substr s i 1) c) (setq p i))
    (setq i (1+ i))
  )
  p
)

;; Full path without the extension
(defun dxf:noext (s / p b)
  (setq p (dxf:lastpos s ".")
        b (dxf:lastpos s "/")
  )
  (if (> p b) (substr s 1 (1- p)) s)
)

;; File name only
(defun dxf:name (s / p)
  (setq p (dxf:lastpos s "/"))
  (if (> p 0) (substr s (1+ p)) s)
)

;; T if the file ends exactly with the given extension
;; (the Windows pattern "*.dwg" also matches things like plan.dwgtmp)
(defun dxf:has-ext (s ext / n m)
  (setq n (strlen s) m (strlen ext))
  (and (> n m) (= (strcase (substr s (1+ (- n m)) m)) (strcase ext)))
)

;; Comparable time stamp (yyyymmdd.hhmmss as a real number)
(defun dxf:stamp (f / d)
  (if (and vl-file-systime (setq d (vl-file-systime f)))
    (+ (* (+ (* (nth 0 d) 10000.0) (* (nth 1 d) 100.0) (nth 3 d)) 1000000.0)
       (* (nth 4 d) 10000.0)
       (* (nth 5 d) 100.0)
       (nth 6 d)
    )
    nil
  )
)

;; List of the DWG files in a folder (recursive when *dxf-recurse* is on)
(defun dxf:dwgs (dir / res f d)
  (setq dir (dxf:trailslash (dxf:slash dir)))
  (foreach f (vl-directory-files dir "*.dwg" 1)
    (if (and (dxf:has-ext f ".dwg")
             (/= (substr f 1 1) "~")
             (/= (substr f 1 1) "$")
        )
      (setq res (cons (strcat dir f) res))
    )
  )
  (if *dxf-recurse*
    (foreach d (vl-directory-files dir nil -1)
      (if (and (/= d ".") (/= d ".."))
        (setq res (append (dxf:dwgs (strcat dir d)) res))
      )
    )
  )
  res
)

;; Returns a sensible value when restoring a system variable: if the value
;; found on entry is the very value the batch uses, a previous batch was
;; aborted halfway and left it there, so the normal AutoCAD value is restored.
(defun dxf:sane (found working standard)
  (if (equal found working) standard found)
)

;; Writes into the script the restoration of one system variable.
;; A nil value means the variable does not exist in this release: skip it.
(defun dxf:restvar (fh var val)
  (if (/= val nil)
    (write-line
      (strcat "(if (getvar \"" var "\") (setvar \"" var "\" "
              (if (= (type val) 'STR) (strcat "\"" val "\"") (itoa val))
              "))")
      fh
    )
  )
)

;; Checks that this AutoCAD release supports what is needed
(defun dxf:check ( / missing)
  (if (and (null vl-directory-files) vl-load-com) (vl-load-com))
  (setq missing "")
  (if (null vl-directory-files) (setq missing (strcat missing " vl-directory-files")))
  (if (null vl-file-delete)     (setq missing (strcat missing " vl-file-delete")))
  (if (/= missing "")
    (progn
      (princ (strcat "\n*** This AutoCAD release does not provide:" missing))
      (princ "\n*** AutoLISP is only available in AutoCAD LT 2024 or later.")
      nil
    )
    T
  )
)

;; T if the folder exists
(defun dxf:dir-p (d)
  (or (vl-directory-files d nil 1) (vl-directory-files d nil -1))
)

;; Goes one level up in the path (never past the drive root)
(defun dxf:parent (dir / d p)
  (setq d (dxf:slash dir))
  (if (and (> (strlen d) 0) (= (substr d (strlen d) 1) "/"))
    (setq d (substr d 1 (1- (strlen d))))
  )
  (setq p (dxf:lastpos d "/"))
  (if (>= p 3) (substr d 1 p) (dxf:trailslash d))
)

;; Folder browser running in the command line
;; (AutoCAD has no dialog box for picking a folder, only for picking files)
;;
;; The listing is paged, *dxf-page* subfolders at a time, because a folder with
;; a hundred subfolders would scroll the command line history away and leave the
;; user with nothing to read. Item numbers are ABSOLUTE over the whole list, not
;; per page: the number shown next to a name is always the one to type, and a
;; number already known can be typed from any page. N and P wrap around.
(defun dxf:browse ( / dir subs s i n d res cancel page pages total first last)
  (if (or (null *dxf-page*) (not (numberp *dxf-page*)) (< *dxf-page* 1))
    (setq *dxf-page* 10)
  )
  (setq dir (dxf:trailslash (dxf:slash *dxf-root*)))
  (if (not (dxf:dir-p dir)) (setq dir "C:/"))
  (setq page 0)
  (while (and (null res) (null cancel))
    (setq subs nil)
    (foreach d (vl-directory-files dir nil -1)
      (if (and (/= d ".") (/= d "..")) (setq subs (cons d subs)))
    )
    (if vl-sort (setq subs (vl-sort subs '<)) (setq subs (reverse subs)))
    (setq total (length subs)
          pages (if (> total 0) (1+ (/ (1- total) *dxf-page*)) 1)
    )
    (if (>= page pages) (setq page (1- pages)))
    (if (< page 0) (setq page 0))
    (setq first (1+ (* page *dxf-page*))
          last  (min total (* (1+ page) *dxf-page*))
    )
    (princ (strcat "\n\n  [ " dir " ]"))
    (if (= total 0)
      (princ "\n   (no subfolders)")
      (progn
        (princ (strcat "\n   " (itoa total) " subfolders - page "
                       (itoa (1+ page)) " of " (itoa pages)))
        (setq i first)
        (while (<= i last)
          (princ (strcat "\n   " (itoa i) ") " (nth (1- i) subs)))
          (setq i (1+ i))
        )
      )
    )
    (setq s (getstring T (strcat "\nNumber to enter"
                                 (if (> pages 1) " / N next page / P previous page" "")
                                 " / .. up / ENTER accept this folder / X cancel: ")))
    (cond
      ((= s "") (setq res dir))
      ((= (strcase s) "X") (setq cancel T))
      ((and (= (strcase s) "N") (> pages 1))
       (setq page (if (< page (1- pages)) (1+ page) 0))
      )
      ((and (= (strcase s) "P") (> pages 1))
       (setq page (if (> page 0) (1- page) (1- pages)))
      )
      ((= s "..") (setq dir (dxf:trailslash (dxf:parent dir)) page 0))
      ((or (> (dxf:lastpos s ":") 0) (= (substr s 1 2) "//"))
       (if (dxf:dir-p (dxf:trailslash (dxf:slash s)))
         (setq dir (dxf:trailslash (dxf:slash s)) page 0)
         (princ "\n   *** That path does not exist.")
       )
      )
      ((and (> (setq n (atoi s)) 0) (<= n total))
       (setq dir (dxf:trailslash (strcat dir (nth (1- n) subs))) page 0)
      )
      (T (princ "\n   *** Invalid entry."))
    )
  )
  (if cancel (princ "\nSelection cancelled."))
  res
)

;; Asks for the root folder
(defun dxf:ask-root ( / r)
  (princ (strcat "\nDefault folder: " *dxf-root*))
  (setq r (getstring T "\nRoot folder (ENTER = the one above, * = browse folders, or paste a path): "))
  (cond
    ((= r "") (setq r *dxf-root*))
    ((= r "*") (setq r (dxf:browse)))
    (T (setq r (dxf:trailslash (dxf:slash r))))
  )
  (if r
    (if (dxf:dir-p r)
      (setq *dxf-root* (dxf:trailslash (dxf:slash r)))
      (progn (princ (strcat "\n*** The folder does not exist or is empty: " r)) (setq r nil))
    )
  )
  (if r (dxf:trailslash (dxf:slash r)))
)

;;; ------------------------------- COMMANDS ---------------------------------

(defun c:DXFCFG ()
  (princ "\n--- DWG2DXF - current configuration ---")
  (princ (strcat "\n  Root folder : " *dxf-root*))
  (princ (strcat "\n  DXF version : " *dxf-dxfver* " (ASCII)"))
  (princ (strcat "\n  Convert     : " (if *dxf-newonly* "only the modified DWG files" "all of them")))
  (princ (strcat "\n  Subfolders  : " (if *dxf-recurse* "yes" "no")))
  (princ (strcat "\n  Xrefs       : " (cond ((= *dxf-xref* 1) "bind by insert")
                                            ((= *dxf-xref* 0) "classic bind")
                                            (T "do not bind"))))
  (princ (strcat "\n  Check       : " (if *dxf-audit* "AUDIT before exporting" "no")))
  (princ (strcat "\n  Self reload : " (if *dxf-lsp* *dxf-lsp*
                                        "unknown path - run DXFPATH once, or use the APPLOAD Startup Suite")))
  (princ)
)

;; Registers the path of this file so that the batch can reload the whole
;; program when it ends. Kept in the AutoCAD profile, so it is asked only once.
(defun c:DXFPATH ( / p)
  (princ "\nLocate the DWG2DXF.lsp file itself.")
  (setq p (getfiled "Locate DWG2DXF.lsp" (if *dxf-lsp* *dxf-lsp* "") "lsp" 4))
  (if p
    (progn
      (setq *dxf-lsp* (dxf:slash p))
      (setenv "DWG2DXF-LSP" *dxf-lsp*)
      (princ (strcat "\nPath registered: " *dxf-lsp*))
      (princ "\nIt is remembered between sessions.")
    )
    (princ "\nCancelled.")
  )
  (princ)
)

(defun c:DXFRESET ( / v)
  (foreach v (list '("FILEDIA" 1) '("CMDDIA" 1) '("EXPERT" 0)
                   '("ATTREQ" 1) '("ATTDIA" 0) '("ISAVEBAK" 1)
                   '("PROXYNOTICE" 1) '("XREFNOTIFY" 2) '("SYSMON" 1))
    (if (getvar (car v)) (setvar (car v) (cadr v)))
  )
  (if (and vl-catch-all-apply (getvar "SDI"))
    (vl-catch-all-apply 'setvar (list "SDI" 0))
  )
  (princ "\nSystem variables restored to their usual values.")
  (princ)
)

(defun c:DWG2DXF ( / ok root ver kw lst todo lck upd f dxf tdwg tdxf lname
                     scr log tmpx fh n i v pair
                     v-fdia v-cdia v-exp v-areq v-adia v-prox v-isb v-font
                     v-star v-bind v-xnot v-sysm v-sdi v-pgra v-psho)

  (princ "\n=================================================")
  (princ "\n   Batch DWG -> ASCII DXF")
  (princ "\n=================================================")

  (setq ok (dxf:check))

  ;; --- 0. warn if the current drawing has unsaved changes ------------------
  ;; (nothing is saved automatically: on an unnamed drawing QSAVE would open
  ;;  the Save As dialog box and lock the command line)
  (if (and ok (/= 0 (getvar "DBMOD")))
    (progn
      (princ "\nWARNING: the current drawing has unsaved changes and the batch will close it.")
      (princ "\n         If you continue, those changes are discarded (they are dumped to a")
      (princ "\n         temporary file). Files already on disk are not touched.")
      (initget "Continue Cancel")
      (setq kw (getkword "\nContinue and discard those changes? [Continue/Cancel] <Continue>: "))
      (if (= kw "Cancel") (progn (princ "\nCancelled.") (setq ok nil)))
    )
  )

  ;; --- 1. root folder ------------------------------------------------------
  (if ok
    (progn
      (setq root (dxf:ask-root))
      (if (null root) (setq ok nil))
    )
  )

  ;; --- 2. DXF version ------------------------------------------------------
  (if ok
    (progn
      (initget "2018 2013 2010 2007 2004 2000 R12")
      (setq ver (getkword (strcat "\nDXF version [2018/2013/2010/2007/2004/2000/R12] <"
                                  *dxf-dxfver* ">: ")))
      (if ver (setq *dxf-dxfver* ver))
      (setq ver *dxf-dxfver*)
    )
  )

  ;; --- 3. how to treat the external references -----------------------------
  (if ok
    (progn
      (initget "Insert Bind None")
      (setq kw (getkword (strcat "\nExternal references [Insert/Bind/None] <"
                                 (cond ((= *dxf-xref* 1) "Insert")
                                       ((= *dxf-xref* 0) "Bind")
                                       (T "None"))
                                 ">: ")))
      (cond ((= kw "Insert") (setq *dxf-xref* 1))
            ((= kw "Bind")   (setq *dxf-xref* 0))
            ((= kw "None")   (setq *dxf-xref* nil))
      )
    )
  )

  ;; --- 4. what to convert --------------------------------------------------
  (if ok
    (progn
      (initget "New All")
      (setq kw (getkword (strcat "\nWhat to convert [New/All] <"
                                 (if *dxf-newonly* "New" "All") ">: ")))
      (if kw (setq *dxf-newonly* (= kw "New")))
    )
  )

  ;; --- 5. locate the drawings ----------------------------------------------
  (if ok
    (progn
      (princ "\nLooking for drawings...")
      (setq lst (dxf:dwgs root))
      (if vl-sort (setq lst (vl-sort lst '<)))
      (princ (strcat "\n  DWG files found: " (itoa (length lst))))
      (if (null lst) (setq ok nil))
    )
  )

  ;; --- 6. filter by date and drop the locked drawings ----------------------
  (if ok
    (progn
      (setq todo nil lck nil upd 0)
      (foreach f lst
        (setq dxf  (strcat (dxf:noext f) ".dxf")
              tdwg (dxf:stamp f)
              tdxf (if (findfile dxf) (dxf:stamp dxf) nil)
        )
        (cond
          ((findfile (strcat (dxf:noext f) ".dwl"))
           (setq lck (cons f lck))
          )
          ((or (not *dxf-newonly*) (null tdxf) (null tdwg) (> tdwg tdxf))
           (setq todo (cons (cons f dxf) todo))
          )
          (T (setq upd (1+ upd)))
        )
      )
      (setq todo (reverse todo)
            n    (length todo)
      )
      (princ (strcat "\n  Pending conversion: " (itoa n)))
      (princ (strcat "\n  Already up to date (DXF newer): " (itoa upd)))
      (if lck
        (progn
          (princ (strcat "\n  SKIPPED because they are open or locked: " (itoa (length lck))))
          (foreach f lck (princ (strcat "\n     " (dxf:name f))))
        )
      )
      (if (= n 0)
        (progn (princ "\nThere is nothing to convert.") (setq ok nil))
      )
    )
  )

  ;; --- 7. confirmation -----------------------------------------------------
  (if ok
    (progn
      (setq i 0)
      (foreach pair todo
        (setq i (1+ i))
        (if (<= i 8) (princ (strcat "\n    " (dxf:name (car pair)))))
      )
      (if (> n 8) (princ (strcat "\n    ... and " (itoa (- n 8)) " more")))
      (princ "\nCAUTION: close beforehand any open drawing from those folders.")
      (initget "Yes No")
      (setq kw (getkword (strcat "\nConvert " (itoa n) " drawings to DXF " ver " ASCII"
                                 (cond ((= *dxf-xref* 1) " (binding xrefs by insert)")
                                       ((= *dxf-xref* 0) " (binding xrefs the classic way)")
                                       (T " (without binding xrefs)"))
                                 "? [Yes/No] <Yes>: ")))
      (if (= kw "No") (progn (princ "\nCancelled.") (setq ok nil)))
    )
  )

  ;; --- 8. build the script -------------------------------------------------
  (if ok
    (progn
      (setq scr  (strcat (dxf:slash (getvar "TEMPPREFIX")) "DWG2DXF.scr")
            log  (strcat root "DWG2DXF-log.txt")
            tmpx (strcat (dxf:slash (getvar "TEMPPREFIX")) "DWG2DXF-discard.dxf")
      )
      (if (findfile log)  (vl-file-delete log))
      (if (findfile tmpx) (vl-file-delete tmpx))
      ;; current values of the variables we are about to change
      (setq v-fdia (getvar "FILEDIA")  v-cdia (getvar "CMDDIA")
            v-exp  (getvar "EXPERT")   v-areq (getvar "ATTREQ")
            v-adia (getvar "ATTDIA")   v-prox (getvar "PROXYNOTICE")
            v-isb  (getvar "ISAVEBAK") v-font (getvar "FONTALT")
            v-star (getvar "STARTUP")  v-bind (getvar "BINDTYPE")
            v-xnot (getvar "XREFNOTIFY") v-sysm (getvar "SYSMON")
            v-sdi  (getvar "SDI")   v-pgra (getvar "PROXYGRAPHICS")
            v-psho (getvar "PROXYSHOW")
      )
      (setq fh (open scr "w"))
      (if (null fh)
        (progn (princ (strcat "\n*** Cannot write the script to " scr)) (setq ok nil))
        (progn
          (write-line ";; Script generated automatically by DWG2DXF.lsp v3.5" fh)
          (foreach v (list '("FILEDIA" 0) '("CMDDIA" 0) '("EXPERT" 5) '("ATTREQ" 0)
                           '("ATTDIA" 0) '("PROXYNOTICE" 0) '("ISAVEBAK" 0)
                           '("STARTUP" 0) '("XREFNOTIFY" 0) '("SYSMON" 0)
                           '("PROXYGRAPHICS" 1) '("PROXYSHOW" 1))
            (write-line (strcat "(if (getvar \"" (car v) "\") (setvar \"" (car v) "\" "
                                (itoa (cadr v)) "))") fh)
          )
          (if *dxf-xref*
            (write-line (strcat "(if (getvar \"BINDTYPE\") (setvar \"BINDTYPE\" "
                                (itoa *dxf-xref*) "))") fh)
          )
          (write-line "(if (getvar \"FONTALT\") (setvar \"FONTALT\" \"simplex.shx\"))" fh)
          ;; Single document mode: each OPEN replaces the previous drawing, so
          ;; documents do not pile up. CLOSE is NEVER used: a script dies if it
          ;; closes the document it is running in.
          (write-line (strcat "(if (and vl-catch-all-apply (getvar \"SDI\"))"
                              " (vl-catch-all-apply 'setvar (list \"SDI\" 1)))") fh)
          (write-line (strcat "(if (= 1 (getvar \"SDI\"))"
                              " (prompt \"\\n>>> Single document mode enabled.\")"
                              " (prompt \"\\n>>> WARNING: the converted drawings will stay open;"
                              " close them with CLOSEALL when the batch ends.\"))") fh)

          ;; ---- drawing by drawing conversion -------------------------------
          (setq i 0)
          (foreach pair todo
            (setq i     (1+ i)
                  f     (car pair)
                  dxf   (cdr pair)
                  lname (strcase (dxf:name f) T)
            )
            (write-line (strcat "(prompt \"\\n>>> [" (itoa i) "/" (itoa n) "] " (dxf:name f) "\")") fh)
            ;; with SDI=1 the OPEN replaces the current drawing: were there any
            ;; unsaved change, AutoCAD would ask whether to discard it and would
            ;; swallow the next line of the script. Dump it to a temporary DXF.
            (write-line (strcat "(if (> (getvar \"DBMOD\") 0)"
                                " (command \"_.SAVEAS\" \"_DXF\" \"_V\" \"" ver "\" \"\" \""
                                tmpx "\"))") fh)
            (write-line "(if (> (getvar \"CMDACTIVE\") 0) (command))" fh)
            (write-line "_.OPEN" fh)
            (write-line (strcat "\"" f "\"") fh)
            ;; %ok = the intended drawing is really the active one
            ;; %d  = DWG path     %p = DXF path to generate (same folder)
            (write-line (strcat "(setq %ok (= (strcase (getvar \"DWGNAME\") T) \"" lname "\")"
                                " %d (strcat (getvar \"DWGPREFIX\") (getvar \"DWGNAME\"))"
                                " %p (strcat (getvar \"DWGPREFIX\") (substr (getvar \"DWGNAME\") 1"
                                " (- (strlen (getvar \"DWGNAME\")) 4)) \".dxf\") %n 0)") fh)
            ;; drawing check (avoids corrupt DXF files caused by bad tables)
            (if *dxf-audit*
              (progn
                (write-line "(if %ok (command \"_.AUDIT\" \"_Y\"))" fh)
                (write-line "(if (> (getvar \"CMDACTIVE\") 0) (command))" fh)
              )
            )
            ;; bind the external references (up to 3 passes for nested xrefs)
            (if *dxf-xref*
              (write-line (strcat "(if %ok (progn (setq %r 0)"
                                  " (while (and (< %r 3)"
                                  " (progn (setq %x nil %b (tblnext \"BLOCK\" T))"
                                  " (while %b (if (= 4 (logand 4 (if (assoc 70 %b) (cdr (assoc 70 %b)) 0)))"
                                  " (setq %x T)) (setq %b (tblnext \"BLOCK\"))) %x))"
                                  " (command \"_.-XREF\" \"_B\" \"*\")"
                                  " (if (> (getvar \"CMDACTIVE\") 0) (command))"
                                  " (setq %n 1 %r (1+ %r)))))") fh)
            )
            ;; if xrefs are still there afterwards, flag it in the log
            (write-line (strcat "(if %ok (progn (setq %x nil %b (tblnext \"BLOCK\" T))"
                                " (while %b (if (= 4 (logand 4 (if (assoc 70 %b) (cdr (assoc 70 %b)) 0)))"
                                " (setq %x T)) (setq %b (tblnext \"BLOCK\"))) (if %x (setq %n 2))))") fh)
            ;; delete the previous DXF
            (write-line "(if %ok (if (findfile %p) (vl-file-delete %p)))" fh)
            ;; save as ASCII DXF
            ;;   SAVEAS -> DXF -> Version -> <version> -> ENTER (16 decimals) -> name
            (write-line (strcat "(if %ok (command \"_.SAVEAS\" \"_DXF\" \"_V\" \""
                                ver "\" \"\" %p))") fh)
            (write-line "(if (> (getvar \"CMDACTIVE\") 0) (command))" fh)
            ;; log
            (write-line (strcat "(if (setq %f (open \"" log "\" \"a\"))"
                                " (progn (write-line (strcat (if (and %ok (findfile %p)) \"OK     \" \"ERROR  \")"
                                " (cond ((= %n 1) \"[xref bound]   \") ((= %n 2) \"[XREF NOT BOUND]\") (T \"               \"))"
                                " (if %ok %d \"COULD NOT OPEN: " (dxf:name f) "\")) %f) (close %f)))") fh)
            ;; notice if something went wrong (the batch carries on regardless)
            (write-line (strcat "(if (and %ok (not (findfile %p)))"
                                " (prompt \"\\n*** CAUTION: this drawing was not converted ***\"))") fh)
          )

          ;; ---- restore the environment -------------------------------------
          (dxf:restvar fh "EXPERT"      (dxf:sane v-exp  5 0))
          (dxf:restvar fh "ATTREQ"      (dxf:sane v-areq 0 1))
          (dxf:restvar fh "ATTDIA"      v-adia)
          (dxf:restvar fh "PROXYNOTICE" (dxf:sane v-prox 0 1))
          (dxf:restvar fh "ISAVEBAK"    (dxf:sane v-isb  0 1))
          (dxf:restvar fh "FONTALT"     v-font)
          (dxf:restvar fh "STARTUP"     v-star)
          (dxf:restvar fh "XREFNOTIFY"  (dxf:sane v-xnot 0 2))
          (dxf:restvar fh "PROXYGRAPHICS" v-pgra)
          (dxf:restvar fh "PROXYSHOW"     v-psho)
          (if v-sysm (dxf:restvar fh "SYSMON" (dxf:sane v-sysm 0 1)))
          (if *dxf-xref* (dxf:restvar fh "BINDTYPE" (dxf:sane v-bind *dxf-xref* 0)))
          (write-line (strcat "(if (and vl-catch-all-apply (getvar \"SDI\"))"
                              " (vl-catch-all-apply 'setvar (list \"SDI\" "
                              (itoa (dxf:sane v-sdi 1 0)) ")))") fh)
          (dxf:restvar fh "CMDDIA"      (dxf:sane v-cdia 0 1))
          (dxf:restvar fh "FILEDIA"     (dxf:sane v-fdia 0 1))
          ;; The batch ends inside a document that never saw this file loaded, so
          ;; DWG2DXF / DXFCFG / DXFRESET would not exist there. If the path of the
          ;; file is known, reload the whole program.
          (if *dxf-lsp*
            (write-line (strcat "(if (findfile \"" (dxf:slash *dxf-lsp*)
                                "\") (load \"" (dxf:slash *dxf-lsp*) "\"))") fh)
          )
          ;; Whether or not that worked, write a self-contained definition of the
          ;; rescue command into the script, so it always exists when the batch
          ;; ends. Both definitions are guarded: if the program is already loaded
          ;; in the final document (APPLOAD Startup Suite), nothing is overwritten.
          (write-line (strcat "(if (null c:DXFRESET) (defun c:DXFRESET ( / v)"
                              " (foreach v (list '(\"FILEDIA\" 1) '(\"CMDDIA\" 1)"
                              " '(\"EXPERT\" 0) '(\"ATTREQ\" 1) '(\"ATTDIA\" 0)"
                              " '(\"ISAVEBAK\" 1) '(\"PROXYNOTICE\" 1)"
                              " '(\"XREFNOTIFY\" 2) '(\"SYSMON\" 1))"
                              " (if (getvar (car v)) (setvar (car v) (cadr v))))"
                              " (if (and vl-catch-all-apply (getvar \"SDI\"))"
                              " (vl-catch-all-apply 'setvar (list \"SDI\" 0)))"
                              " (princ \"\\nSystem variables restored to their"
                              " usual values.\") (princ)))") fh)
          (write-line (strcat "(if (null c:DWG2DXF) (defun c:DWG2DXF ()"
                              " (princ \"\\n*** DWG2DXF.lsp is not loaded in this"
                              " drawing: a batch replaces the document and LISP"
                              " definitions do not survive that.\")"
                              " (princ \"\\n*** Load it with APPLOAD (Startup Suite),"
                              " or load it once and run DXFPATH.\") (princ)))") fh)
          (write-line (strcat "(princ \"\\n\\n*** BATCH FINISHED: " (itoa n)
                              " drawings. Log: " log " ***\\n\")") fh)
          (close fh)
        )
      )
    )
  )

  ;; --- 9. launch the script ------------------------------------------------
  (if ok
    (progn
      (princ (strcat "\nLaunching the conversion of " (itoa n) " drawings..."))
      (princ "\nDo not touch the keyboard or the mouse until it is done.\n")
      (setvar "FILEDIA" 0)
      (command "_.script" scr)
    )
  )
  (princ)
)

(princ "\nDWG2DXF.lsp v3.5 loaded.  Type DWG2DXF to convert, DXFCFG to see the settings.")
(princ)
