; foo runs a sequence of operations prior to saving as dxf
; https://forums.autodesk.com/t5/visual-lisp-autolisp-and-general/stop-command-in-script/m-p/12134637#M452381
(defun c:foo (/ b dwg s)
 (vl-load-com)
 ; add suffix to drawing name
 ; (setq dwg (strcat(getvar"dwgprefix")(vl-filename-base(getvar"dwgname"))"-R12")) 
 ; create DXF-R12 subfolder to save dxf there using same filename
   (setq dwg (strcat (getvar"dwgprefix") "DXF-R12"))
   (if (not (vl-file-directory-p dwg))(vl-mkdir dwg))
   (setq dwg (strcat dwg "\\" (vl-filename-base(getvar"dwgname"))))
  ;; To modelspace?
  (setvar 'tilemode 1)
  ;; If we have a selection in modelspace
  (if (setq s (ssget "_X" '((410 . "Model"))))
    (progn ;; Zoom
	   (command "_Zoom" "_Extents")
	   ;; Explode
	;   (vl-catch-all-apply 'vl-cmdf (list "_.Explode" s ""))
  ;  https://forums.augi.com/showthread.php?47903-Explode-all-not-working-in-lisping
      (foreach b (mapcar
                 (function
                   (lambda (b)
                     (vlax-ename->vla-object
                       (cadr b)
                     ) ;_  vlax-ename->vla-object
                   ) ;_  lambda
                 ) ;_  function
                 (ssnamex s)
               ) ;_  mapcar
      (if (vl-catch-all-error-p
            (VL-CATCH-ALL-APPLY
              (function vla-Explode)
              (list b)
            ) ;_  VL-CATCH-ALL-APPLY
          ) ;_  vl-catch-all-error-p
        (vlax-release-object b)
        (progn
          (vla-delete b)
          (vlax-release-object b)
        ) ;_  progn
      ) ;_  if
    ) ;_  foreach
	   ;; Join
	   (initcommandversion)
	   (vl-catch-all-apply 'vl-cmdf (list "_.Join" "_All" ""))
	   ;; To paperspace
	   (setvar 'tilemode 0)
	   ;; Add your line to save as DXF12 below replacing over current dxf
           (vl-cmdf "_.DXFOUT" dwg "_V" "_R12" "16")
	   ;; To modelspace
	   (setvar 'tilemode 1)
    )
  )
  (princ)
)