;; DailyPainkiller CLEANTOOLS v0.2.0 - Windows AutoCAD / Visual LISP / ActiveX
;; Myo Myint Maung - DailyPainkiller
;;
;; INSTALL: APPLOAD this file. Run CLEANTOOLS. No edits occur on load.
;; CURSOR MENU: choices appear in Dynamic Input near the crosshairs.
;; Press Down Arrow to expand the list, then click a function.
;; Commands: CLEANTOOLS (main menu), CTOUTSIDE (delete outside directly).
;; Temporary DYNMODE, DYNPROMPT and CMDECHO changes are restored on exit/Esc.
;;
;; v0.2.0  2026-10-17
;; Added: Delete outside one closed 2D polyline; preview, count, Yes/No, undo.
;; Added: cursor keyword menu and help; current-space filtering.
;; Fixed: cloud recognition using RevcloudProps metadata, not shape guessing.
;; Improved: cancellation, locked/unwritable handling, shared-block traversal.
;; Preserved: remove objects, clean shared blocks, Purge/Audit/prepare OVERKILL,
;; and Lee Mac burst integration. Burst engine remains a separate dependency.
;; Outside never explodes or edits block definitions. Blocks stay whole.
;; Complex extents overlapping the boundary are retained conservatively.
;; Use HELP for limitations and the small drawing-copy acceptance test.
;; AutoCAD execution is still required; do not treat static checks as host tests.
;; Previous v0.1 is retained in this file's version history.
;;
;; Autodesk references:
;; Dynamic Input: https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-Core/files/GUID-3EBD4C17-F0A5-49FA-B131-4AABE2E727DB.htm
;; ssget: https://help.autodesk.com/cloudhelp/2026/ENU/AutoCAD-AutoLISP-Reference/files/GUID-0F37CC5E-1559-4011-B8CF-A3BA0973B2C3.htm
;; Undo: https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-ActiveX-Reference/files/GUID-7C669949-1327-4CFD-96CF-CE65EC38DAA8.htm
(vl-load-com)

(defun CT:space-name ()
  (if (= 1 (getvar "CVPORT")) (getvar "CTAB") "Model"))

(defun CT:space-owner ()
  (vlax-vla-object->ename
    (if (= 1 (getvar "CVPORT")) (vla-get-paperspace CT:doc) (vla-get-modelspace CT:doc))))

;; Escape wildcard metacharacters in literal layout names used by ssget.
(defun CT:literal (name / out ch)
  (foreach ch (vl-string->list name)
    (if (member ch '(35 64 46 42 63 126 91 93 45 44 96)) (setq out (cons 96 out)))
    (setq out (cons ch out)))
  (vl-list->string (reverse out)))

(defun CT:yes (msg / k)
  (initget "Yes No")
  (= "Yes" (getkword (strcat "\n" msg " [Yes/No] <No>: "))))

(defun CT:types (/ k)
  (initget "Dimensions Clouds Hatches Solids Wipeouts Fills")
  (setq k (getkword "\nRemove [Dimensions/Clouds/Hatches/Solids/Wipeouts/Fills] <cancel>: "))
  (cond ((not k) nil)
        ((= k "Dimensions") '("DIMENSION"))
        ((= k "Clouds") '("REVCLOUD"))
        ((= k "Hatches") '("HATCH"))
        ((= k "Solids") '("SOLID"))
        ((= k "Wipeouts") '("WIPEOUT"))
        (t '("HATCH" "SOLID" "WIPEOUT"))))

(defun CT:matches (e types / kind)
  (setq kind (cdr (assoc 0 (entget e))))
  (or (member kind types)
      (and (member "REVCLOUD" types) (member kind '("LWPOLYLINE" "POLYLINE"))
           (assoc -3 (entget e '("RevcloudProps"))))))

(defun CT:scope (/ k a b)
  (initget "Select Window Current Model Layouts")
  (setq k (getkword "\nScope [Select/Window/Current/Model/Layouts] <Select>: "))
  (cond
    ((= k "Window")
      (if (and (setq a (getpoint "\nFirst window corner <cancel>: "))
               (setq b (getcorner a "\nOpposite corner <cancel>: ")))
        (ssget "_W" a b)))
    ((= k "Current") (ssget "_X" (list (cons 410 (CT:literal (CT:space-name))))))
    ((= k "Model") (ssget "_X" '((410 . "Model"))))
    ((= k "Layouts") (ssget "_X" '((-4 . "<NOT") (410 . "Model") (-4 . "NOT>"))))
    (t (princ "\nSelect objects: ") (ssget))))

(defun CT:objects (ss / i out)
  (if ss (repeat (setq i (sslength ss))
    (setq out (cons (ssname ss (setq i (1- i))) out)))) out)

(defun CT:writable (e / o lay result)
  (if (and (entget e) (setq lay (tblsearch "LAYER" (cdr (assoc 8 (entget e))))))
    (progn
      (setq result (vl-catch-all-apply 'vlax-ename->vla-object (list e)))
      (if (not (vl-catch-all-error-p result))
        (and (= 0 (logand 4 (cdr (assoc 70 lay)))) (vlax-write-enabled-p result))))))

(defun CT:remove (lst / e result ok fail)
  (setq ok 0 fail 0)
  (foreach e lst
    (if (not (CT:writable e)) (setq fail (1+ fail))
      (progn
        (setq result (vl-catch-all-apply 'vla-delete (list (vlax-ename->vla-object e))))
        (if (vl-catch-all-error-p result) (setq fail (1+ fail)) (setq ok (1+ ok))))))
  (princ (strcat "\nDeleted: " (itoa ok) "; skipped/failed: " (itoa fail) "."))
  (if (> ok 0) (princ " One U restores this run.")))

(defun CT:delete-top (/ types ss candidates skipped e preview)
  (if (setq types (CT:types))
    (progn
      (setq ss (CT:scope) skipped 0 preview (ssadd))
      (foreach e (CT:objects ss)
        (if (CT:matches e types)
          (if (CT:writable e)
            (progn (setq candidates (cons e candidates)) (ssadd e preview))
            (setq skipped (1+ skipped)))))
      (sssetfirst nil preview)
      (princ (strcat "\nCandidates: " (itoa (length candidates)) "; locked/unwritable: " (itoa skipped)))
      (if candidates
        (if (CT:yes "Delete highlighted candidates?") (CT:remove candidates)
          (princ "\nCancelled. No objects deleted.")))
      (sssetfirst nil nil)
      (if (member "REVCLOUD" types)
        (princ "\nClouds without RevcloudProps metadata are left unchanged; erase those manually.")))))

;; Traverse definitions once. Never enter xref, dependent or layout definitions.
(defun CT:walk (name types / record obj e child)
  (if (not (member (strcase name) CT:visited))
    (progn
      (setq CT:visited (cons (strcase name) CT:visited) record (tblsearch "BLOCK" name))
      (if (and record (= 0 (logand 28 (cdr (assoc 70 record)))))
        (progn
          (setq obj (vla-item (vla-get-blocks CT:doc) name))
          (if (= :vlax-false (vla-get-islayout obj))
            (vlax-for child obj
              (setq e (vlax-vla-object->ename child))
              (cond
                ((= "INSERT" (cdr (assoc 0 (entget e))))
                  (if (CT:writable e) (CT:walk (cdr (assoc 2 (entget e))) types)
                    (setq CT:skipped (1+ CT:skipped))))
                ((CT:matches e types)
                  (if (CT:writable e) (setq CT:targets (cons e CT:targets))
                    (setq CT:skipped (1+ CT:skipped))))))))
        (setq CT:skipped (1+ CT:skipped))))))

(defun CT:blocks (/ types ss e)
  (if (setq types (CT:types))
    (progn
      (princ "\nSelect block references (shared definitions, including nested blocks): ")
      (setq ss (ssget '((0 . "INSERT"))) CT:visited nil CT:targets nil CT:skipped 0)
      (foreach e (CT:objects ss)
        (if (CT:writable e) (CT:walk (cdr (assoc 2 (entget e))) types)
          (setq CT:skipped (1+ CT:skipped))))
      (princ (strcat "\nDefinition objects to remove: " (itoa (length CT:targets))
        "; skipped objects/definitions: " (itoa CT:skipped)))
      (princ "\nEvery instance using these definitions changes, including instances on locked layers.")
      (if (and CT:targets (CT:yes "Modify shared block definitions?"))
        (progn (CT:remove CT:targets) (vla-regen CT:doc 1))))))

(defun CT:cleanup (/ k ss e current filtered other)
  (initget "Purge Audit Duplicates")
  (setq k (getkword "\nCleanup [Purge/Audit/Duplicates] <Purge>: "))
  (cond
    ((= k "Audit")
      (if (CT:yes "Run drawing-wide AUDIT with repair?") (command-s "_.AUDIT" "_Yes")))
    ((= k "Duplicates")
      (setq ss (CT:scope) current (CT:space-name) filtered (ssadd) other 0)
      (foreach e (CT:objects ss)
        (if (and (= current (cdr (assoc 410 (entget e)))) (CT:writable e)) (ssadd e filtered)
          (setq other (1+ other))))
      (if (> (sslength filtered) 0)
        (progn
          (sssetfirst nil filtered)
          (princ "\nSelection prepared. After this menu exits, run OVERKILL and review tolerance/options.")
          (setq CT:keep-selection T))
        (princ "\nNo editable objects selected in the current space."))
      (if (> other 0) (princ (strcat "\nSkipped locked/other-space objects: " (itoa other) "."))))
    (t (if (CT:yes "Purge unused named items throughout drawing?")
      (progn (repeat 3 (command-s "_.-PURGE" "_All" "*" "_No"))
        (princ "\nPURGE commands completed; see AutoCAD command history for results."))))))

(defun CT:burst (/ k)
  (if (not (member "LM:BURST" (atoms-family 1)))
    (princ "\nLoad your existing BurstUpgradedV1-8.lsp first, then retry Burst.")
    (progn
      (initget "Single Nested")
      (setq k (getkword "\nBurst depth [Single/Nested] <Single>: "))
      ;; Lee Mac's engine owns its undo group and retains its original credits.
      (LM:burst (= k "Nested")))))


;; Delete Outside Polyline helpers. All calculations are in the boundary's
;; plane; elevation is ignored. No screen-dependent CP/WP selection is used.
;; Circular arcs are sampled with a measured sagitta safety allowance.
;; Complex objects use enclosing extents: ambiguous overlaps are kept.

(defun CT:op-val (code data fallback / item)
  (if (setq item (assoc code data)) (cdr item) fallback))

(defun CT:op-sub (a b) (mapcar '- a b))
(defun CT:op-dot (a b) (+ (* (car a) (car b)) (* (cadr a) (cadr b))))
(defun CT:op-cross (a b) (- (* (car a) (cadr b)) (* (cadr a) (car b))))
(defun CT:op-d2 (a b / v) (setq v (CT:op-sub a b)) (CT:op-dot v v))

(defun CT:op-project (p frame / q)
  (setq q (trans p 0 (car frame)))
  (list (- (car q) (car (cadr frame))) (- (cadr q) (cadr (cadr frame)))))

(defun CT:op-parallel (e frame / a b d)
  (setq a (CT:op-val 210 (entget e) '(0.0 0.0 1.0))
        b (CT:op-val 210 (entget (car frame)) '(0.0 0.0 1.0))
        d (apply '+ (mapcar '* a b)))
  (if (> (abs d) 0.999999999) (if (minusp d) -1.0 1.0)))

(defun CT:op-extent (pts / lo hi p)
  (setq lo (car pts) hi lo)
  (foreach p (cdr pts)
    (setq lo (mapcar 'min lo p) hi (mapcar 'max hi p)))
  (list (car lo) (cadr lo) (car hi) (cadr hi)))

(defun CT:op-union (a b)
  (list (min (car a) (car b)) (min (cadr a) (cadr b))
        (max (nth 2 a) (nth 2 b)) (max (nth 3 a) (nth 3 b))))

(defun CT:op-box1 (e frame / low high pts x y z)
  (vla-getboundingbox (vlax-ename->vla-object e) 'low 'high)
  (setq low (vlax-safearray->list low) high (vlax-safearray->list high))
  ;; All eight corners are needed when the boundary plane is tilted.
  (foreach x (list (car low) (car high))
    (foreach y (list (cadr low) (cadr high))
      (foreach z (list (caddr low) (caddr high))
        (setq pts (cons (CT:op-project (list x y z) frame) pts)))))
  (CT:op-extent pts))

(defun CT:op-box (e frame / box child data)
  (setq box (CT:op-box1 e frame) data (entget e))
  ;; Explicitly include attached attributes, including invisible ones.
  (if (and (= "INSERT" (cdr (assoc 0 data))) (= 1 (CT:op-val 66 data 0)))
    (progn
      (setq child (entnext e))
      (while (and child (= "ATTRIB" (cdr (assoc 0 (entget child)))))
        (setq box (CT:op-union box (CT:op-box1 child frame)) child (entnext child)))))
  box)

(defun CT:op-boxes (a b eps)
  (and (<= (car a) (+ (nth 2 b) eps)) (>= (nth 2 a) (- (car b) eps))
       (<= (cadr a) (+ (nth 3 b) eps)) (>= (nth 3 a) (- (cadr b) eps))))

(defun CT:op-inbox (p box eps)
  (and (>= (car p) (- (car box) eps)) (<= (car p) (+ (nth 2 box) eps))
       (>= (cadr p) (- (cadr box) eps)) (<= (cadr p) (+ (nth 3 box) eps))))

(defun CT:op-pointseg2 (p a b / ab ap len2 u near)
  (setq ab (CT:op-sub b a) ap (CT:op-sub p a) len2 (CT:op-dot ab ab))
  (if (< len2 1e-30) (CT:op-d2 p a)
    (progn
      (setq u (max 0.0 (min 1.0 (/ (CT:op-dot ap ab) len2)))
            near (mapcar '+ a (mapcar '(lambda (v) (* u v)) ab)))
      (CT:op-d2 p near))))

;; Edge = (start end enclosing-box). Precompute boxes once per path.
(defun CT:op-edges (pts / out)
  (while (cdr pts)
    (setq out (cons (list (car pts) (cadr pts)
                     (CT:op-extent (list (car pts) (cadr pts)))) out)
          pts (cdr pts)))
  (reverse out))

(defun CT:op-near (ea eb eps / a b p q ab pq c1 c2 c3 c4 eps2)
  (if (CT:op-boxes (caddr ea) (caddr eb) eps)
    (progn
      (setq a (car ea) b (cadr ea) p (car eb) q (cadr eb)
            ab (CT:op-sub b a) pq (CT:op-sub q p)
            c1 (CT:op-cross ab (CT:op-sub p a))
            c2 (CT:op-cross ab (CT:op-sub q a))
            c3 (CT:op-cross pq (CT:op-sub a p))
            c4 (CT:op-cross pq (CT:op-sub b p)) eps2 (* eps eps))
      (or
        (and (> (CT:op-dot ab ab) 1e-30) (> (CT:op-dot pq pq) 1e-30)
             (or (and (<= c1 0.0) (>= c2 0.0)) (and (>= c1 0.0) (<= c2 0.0)))
             (or (and (<= c3 0.0) (>= c4 0.0)) (and (>= c3 0.0) (<= c4 0.0))))
        (<= (CT:op-pointseg2 a p q) eps2) (<= (CT:op-pointseg2 b p q) eps2)
        (<= (CT:op-pointseg2 p a b) eps2) (<= (CT:op-pointseg2 q a b) eps2)))))

(defun CT:op-inside (p edges eps / edge a b inside touch x)
  (while (and edges (not touch))
    (setq edge (car edges) a (car edge) b (cadr edge))
    (if (<= (CT:op-pointseg2 p a b) (* eps eps)) (setq touch T)
      (if (not (eq (> (cadr a) (cadr p)) (> (cadr b) (cadr p))))
        (progn
          (setq x (+ (car a) (* (- (cadr p) (cadr a))
                        (/ (- (car b) (car a)) (- (cadr b) (cadr a))))))
          (if (> x (car p)) (setq inside (not inside))))))
    (setq edges (cdr edges)))
  (or touch inside))

(defun CT:op-path-hit (pts edges eps / own rest hit)
  (setq hit (CT:op-inside (car pts) edges eps) own (CT:op-edges pts))
  (while (and own (not hit))
    (setq rest edges)
    (while (and rest (not hit))
      (setq hit (CT:op-near (car own) (car rest) eps) rest (cdr rest)))
    (setq own (cdr own)))
  hit)

(defun CT:op-box-hit (box edges eps / a b c d)
  (setq a (list (car box) (cadr box)) b (list (nth 2 box) (cadr box))
        c (list (nth 2 box) (nth 3 box)) d (list (car box) (nth 3 box)))
  (or (CT:op-inbox (caar edges) box eps)
      (CT:op-path-hit (list a b c d a) edges eps)))

;; Return (sample-points maximum-deviation). Segment angles stay below 5 deg
;; unless the 256-sample cap applies; the *actual* deviation is still retained.
(defun CT:op-arc (center radius start sweep target / step n i pts ang err)
  (setq step (min (/ pi 36.0) (sqrt (/ (* 8.0 target) radius)))
        n (max 1 (min 256 (1+ (fix (/ (abs sweep) step))))) i 0)
  (repeat (1+ n)
    (setq ang (+ start (* sweep (/ (float i) n)))
          pts (cons (list (+ (car center) (* radius (cos ang)))
                          (+ (cadr center) (* radius (sin ang)))) pts)
          i (1+ i)))
  (setq err (* radius (- 1.0 (cos (/ (abs sweep) (* 2.0 n))))))
  (list (reverse pts) err))

(defun CT:op-piece (p q bulge target / v chord k center radius start sampled pts)
  (setq v (CT:op-sub q p) chord (sqrt (CT:op-dot v v)))
  (if (or (= bulge 0.0) (< chord 1e-15) (< (abs bulge) 1e-8))
    (list (list p q) (* 0.5 chord (abs bulge)))
    (progn
      (setq k (/ (- 1.0 (* bulge bulge)) (* 4.0 bulge))
            center (list (- (/ (+ (car p) (car q)) 2.0) (* (cadr v) k))
                         (+ (/ (+ (cadr p) (cadr q)) 2.0) (* (car v) k)))
            radius (sqrt (CT:op-d2 p center))
            start (atan (- (cadr p) (cadr center)) (- (car p) (car center)))
            sampled (CT:op-arc center radius start (* 4.0 (atan bulge)) target)
            pts (car sampled))
      ;; Use the exact supplied endpoints, rather than recomputed trig values.
      (list (cons p (reverse (cons q (cdr (reverse (cdr pts)))))) (cadr sampled)))))

;; Polyline path = (points deviation maximum-width closed).
;; Reject fitted/3D/mesh polylines for precise path classification.
(defun CT:op-poly (e frame target / data kind flags sign elevation raw entry p b width child verts pair rest seg pts margin closed)
  (setq data (entget e) kind (cdr (assoc 0 data)) flags (CT:op-val 70 data 0)
        sign (CT:op-parallel e frame) width (max (abs (CT:op-val 39 data 0.0)) (CT:op-val 43 data 0.0)
                                              (CT:op-val 40 data 0.0) (CT:op-val 41 data 0.0)))
  (if (and sign (or (= kind "LWPOLYLINE")
                   (and (= kind "POLYLINE") (= 0 (logand flags 126)))))
    (progn
      (setq elevation (if (= kind "LWPOLYLINE") (CT:op-val 38 data 0.0)
                        (caddr (CT:op-val 10 data '(0.0 0.0 0.0)))))
      (if (= kind "LWPOLYLINE")
        (foreach entry data
          (cond
            ((= 10 (car entry))
              (if p (setq raw (cons (list p b) raw)))
              (setq p (cdr entry) b 0.0))
            ((= 42 (car entry)) (setq b (cdr entry)))
            ((member (car entry) '(40 41)) (setq width (max width (cdr entry))))))
        (progn
          (setq child (entnext e))
          (while (and child (= "VERTEX" (cdr (assoc 0 (entget child)))))
            (setq entry (entget child)
                  raw (cons (list (cdr (assoc 10 entry)) (CT:op-val 42 entry 0.0)) raw)
                  width (max width (CT:op-val 40 entry 0.0) (CT:op-val 41 entry 0.0))
                  child (entnext child)))))
      (if p (setq raw (cons (list p b) raw)))
      (foreach pair (reverse raw)
        (setq p (car pair)
              verts (cons (list (CT:op-project (trans (list (car p) (cadr p) elevation) e 0) frame)
                                (* sign (cadr pair))) verts)))
      (setq verts (reverse verts) closed (= 1 (logand flags 1))
            rest (if closed (append verts (list (car verts))) verts) margin 0.0)
      (while (cdr rest)
        (setq seg (CT:op-piece (caar rest) (caadr rest) (cadar rest) target)
              pts (append pts (if pts (cdr (car seg)) (car seg)))
              margin (max margin (cadr seg)) rest (cdr rest)))
      (if pts (list pts margin width closed)))))

(defun CT:op-curve (e frame target / data kind p q center radius start sweep sign sampled)
  (setq data (entget e) kind (cdr (assoc 0 data)))
  (cond
    ((member kind '("LWPOLYLINE" "POLYLINE")) (CT:op-poly e frame target))
    ((and (= kind "LINE") (= 0.0 (CT:op-val 39 data 0.0)))
      (list (list (CT:op-project (cdr (assoc 10 data)) frame)
                  (CT:op-project (cdr (assoc 11 data)) frame)) 0.0 0.0 nil))
    ((and (member kind '("ARC" "CIRCLE")) (= 0.0 (CT:op-val 39 data 0.0))
          (setq sign (CT:op-parallel e frame)))
      (setq center (CT:op-project (trans (cdr (assoc 10 data)) e 0) frame)
            radius (cdr (assoc 40 data))
            p (CT:op-project (vlax-curve-getstartpoint e) frame)
            start (atan (- (cadr p) (cadr center)) (- (car p) (car center)))
            sweep (if (= kind "CIRCLE") (* 2.0 pi)
                    (rem (+ (* 2.0 pi) (- (cdr (assoc 51 data)) (cdr (assoc 50 data)))) (* 2.0 pi)))
            sampled (CT:op-arc center radius start (* sign sweep) target))
      (list (car sampled) (cadr sampled) 0.0 (= kind "CIRCLE")))
    ((and (= kind "POINT") (= 0.0 (CT:op-val 39 data 0.0)))
      (list (list (CT:op-project (cdr (assoc 10 data)) frame)) 0.0 0.0 nil))))

(defun CT:op-simple (edges eps / rest a b i j n valid)
  (setq rest edges i 0 n (length edges) valid T)
  (while (and rest valid)
    (setq a (car rest) b (cdr rest) j (1+ i))
    (if (<= (CT:op-d2 (car a) (cadr a)) (* eps eps)) (setq valid nil))
    (while (and b valid)
      (if (and (/= j (1+ i)) (not (and (= i 0) (= j (1- n))))
               (CT:op-near a (car b) eps)) (setq valid nil))
      (setq b (cdr b) j (1+ j)))
    (setq rest (cdr rest) i (1+ i)))
  valid)

(defun CT:op-area (edges / area edge)
  (setq area 0.0)
  (foreach edge edges (setq area (+ area (CT:op-cross (car edge) (cadr edge)))))
  (* 0.5 (abs area)))

;; Result: Outside, Keep, Envelope (conservative keep), or Skip.
(defun CT:op-classify (e frame edges bbox eps target / kind box path)
  (setq kind (cdr (assoc 0 (entget e))))
  (if (member kind '("VIEWPORT" "RAY" "XLINE" "ACAD_PROXY_ENTITY")) 'Skip
    (progn
      (setq box (CT:op-box e frame))
      (if (not (CT:op-boxes box bbox eps)) 'Outside
        (progn
          (setq path (CT:op-curve e frame target))
          (if (and path (= 0.0 (caddr path)))
            (if (CT:op-path-hit (car path) edges (+ eps (cadr path))) 'Keep 'Outside)
            (if (CT:op-box-hit box edges eps) 'Envelope 'Outside)))))))

(defun CT:outside-help ()
  (alert (strcat
    "CLEANTOOLS - Delete outside polyline\n\n"
    "Pick one closed, simple 2D polyline, then review the highlighted deletion set.\n"
    "Inside, crossing and touching objects stay whole. The boundary stays.\n"
    "Current model space or current paper-space layout only. Elevation is ignored.\n"
    "Unlocked off/frozen-layer objects are included. Locked layers are skipped.\n\n"
    "Lines, arcs, circles and zero-width 2D polylines use their paths.\n"
    "Text, blocks, hatches, splines and other complex objects use enclosing extents.\n"
    "An overlapping extent is kept, so a few fully outside objects may remain.\n"
    "Curved paths use a safety allowance; very close objects are kept.\n"
    "Infinite lines, viewports, proxies and unreadable objects are skipped.\n"
    "Blocks/xrefs are whole references; their definitions are not edited.\n\n"
    "No deletion until Yes. Enter = No. One U restores a completed run.\n"
    "Cursor menus: press Down Arrow to expand choices, then click a choice.")))

(defun CT:outside (/ pick boundary data frame origin box diag target eps shape pts edges margin why ss i e result candidates preview kept skipped envelope)
  (princ "\nDelete outside: keep whole objects inside, crossing or touching the boundary.")
  (cond
    ((= 0 (logand (getvar "UNDOCTL") 1))
      (princ "\nUNDO recording is off. Enable UNDO Control All, then run again."))
    ((not (setq pick (entsel "\nSelect closed boundary polyline <cancel>: ")))
      (princ "\nCancelled. No objects deleted."))
    (t
      (setq boundary (car pick) data (entget boundary))
      (cond
        ((not (member (cdr (assoc 0 data)) '("LWPOLYLINE" "POLYLINE")))
          (setq why "Select a closed 2D polyline, such as a rectangle drawn with PLINE."))
        ((/= 1 (logand 1 (CT:op-val 70 data 0)))
          (setq why "The boundary is open. Close it with PEDIT > Close, then retry."))
        ((> (CT:op-val 90 data 0) 4096)
          (setq why "Boundary has too many vertices. Use a simpler closed outline."))
        ((not (equal (cdr (assoc 330 data)) (CT:space-owner)))
          (setq why "Select a top-level boundary in the current space."))
        (t
          (setq origin (trans (vlax-curve-getstartpoint boundary) 0 boundary)
                frame (list boundary (list (car origin) (cadr origin)))
                box (CT:op-box boundary frame)
                diag (distance (list (car box) (cadr box)) (list (nth 2 box) (nth 3 box)))
                target (max 1e-6 (* diag 1e-5)) eps (max 1e-7 (* diag 1e-9))
                shape (CT:op-poly boundary frame target))
          (cond
            ((not shape) (setq why "Use an unfitted 2D polyline; 3D/mesh/fitted boundaries are unsupported."))
            ((> (caddr shape) 0.0) (setq why "Set the boundary polyline width and thickness to zero, then retry."))
            ((> (length (car shape)) 4096) (setq why "Boundary too detailed. Use a simpler closed outline (maximum 4096 sampled points)."))
            (t
              (setq pts (car shape) margin (cadr shape) edges (CT:op-edges pts))
              (if (or (< (length edges) 3) (<= (CT:op-area edges) (* eps eps))
                      (not (CT:op-simple edges (+ eps (* 2.0 margin)))))
                (setq why "Boundary is degenerate, crosses itself, or has repeated vertices. Redraw a simple closed outline."))))))
      (if why (princ (strcat "\n" why " No objects deleted."))
        (progn
          (setq CT:boundary-highlight boundary)
          (redraw boundary 3)
          (setq ss (ssget "_X" (list (cons 410 (CT:literal (CT:space-name)))))
                i 0 kept 0 skipped 0 envelope 0 preview (ssadd))
          (princ (strcat "\nScanning " (CT:space-name) ". Unlocked off/frozen layers are included."))
          (if ss
            (repeat (sslength ss)
              (setq e (ssname ss i) i (1+ i))
              (if (not (equal e boundary))
                (progn
                  (setq result (vl-catch-all-apply 'CT:outside-one
                    (list e frame edges box (+ eps margin) target)))
                  (cond
                    ((or (vl-catch-all-error-p result) (eq result 'Skip)) (setq skipped (1+ skipped)))
                    ((eq result 'Outside) (setq candidates (cons e candidates)) (ssadd e preview))
                    ((eq result 'Envelope) (setq kept (1+ kept) envelope (1+ envelope)))
                    (t (setq kept (1+ kept))))))
              (if (= 0 (rem i 500)) (princ (strcat "\rScanned " (itoa i) " objects...")))))
          (princ (strcat "\nOutside candidates: " (itoa (length candidates))
            "; kept: " (itoa kept) "; skipped/locked: " (itoa skipped) "."))
          (if (> envelope 0)
            (princ (strcat "\n" (itoa envelope) " complex objects kept by enclosing extents; some may be fully outside.")))
          (if candidates
            (progn
              (sssetfirst nil preview)
              (if (CT:yes (strcat "Delete " (itoa (length candidates)) " outside objects?"))
                (CT:remove candidates)
                (princ "\nCancelled. No objects deleted.")))
            (princ "\nNothing eligible to delete outside this boundary."))
          (sssetfirst nil nil)
          (redraw boundary 4) (setq CT:boundary-highlight nil)))))
  (princ))

(defun CT:outside-one (e frame edges box eps target)
  (if (and (equal (cdr (assoc 330 (entget e)))
                  (cdr (assoc 330 (entget (car frame))))) (CT:writable e))
    (CT:op-classify e frame edges box eps target) 'Skip))


(defun CT:help ()
  (alert (strcat
    "DailyPainkiller CLEANTOOLS v0.2.0\n\n"
    "Remove - dimensions, recognised clouds, hatches, solids or wipeouts.\n"
    "Blocks - remove selected types inside shared/nested block definitions.\n"
    "Cleanup - drawing-wide Purge/Audit, or prepare an OVERKILL selection.\n"
    "Burst - your separately loaded Lee Mac burst engine; keep attribute text.\n"
    "Outside - delete objects completely outside a closed 2D polyline.\n\n"
    "Main command: CLEANTOOLS. Direct outside command: CTOUTSIDE.\n"
    "Cursor menus: press Down Arrow, then click an option.\n"
    "Dynamic Input settings are restored when the command ends.\n\n"
    "Acceptance test in a COPY of a drawing:\n"
    "1. Draw a closed rectangular PLINE. Add inside/outside/crossing lines.\n"
    "2. Add an outside block with an attribute reaching inside; it must stay.\n"
    "3. Add an outside item on a locked layer; it must be skipped.\n"
    "4. Run Outside, answer No/press Enter; nothing must be deleted.\n"
    "5. Repeat, answer Yes; only the highlighted outside candidates go.\n"
    "6. Run U; the deletions must be restored. Run again without reloading.\n"
    "7. Try an open boundary, Esc, curved boundary and another layout.\n"
    "8. Check the other four tools and restored Dynamic Input settings."))
  (CT:outside-help))

;; One runner owns the temporary UI settings and undo marks for all tools.
(defun CT:run (choice / *error* oldecho olddyn oldprompt undo k result
                CT:doc CT:visited CT:targets CT:skipped CT:keep-selection CT:boundary-highlight)
  (setq CT:doc (vla-get-activedocument (vlax-get-acad-object))
        oldecho (getvar "CMDECHO") olddyn (getvar "DYNMODE") oldprompt (getvar "DYNPROMPT"))
  (defun *error* (msg)
    (if undo (vl-catch-all-apply 'vla-endundomark (list CT:doc)))
    (if CT:boundary-highlight (vl-catch-all-apply 'redraw (list CT:boundary-highlight 4)))
    (setvar "CMDECHO" oldecho) (setvar "DYNMODE" olddyn) (setvar "DYNPROMPT" oldprompt)
    (sssetfirst nil nil)
    (if (and msg (not (wcmatch (strcase msg) "*CANCEL*,*QUIT*,*BREAK*")))
      (princ (strcat "\nCLEANTOOLS stopped: " msg)))
    (if undo (princ "\nUse U to revert any completed edits if needed."))
    (princ))
  (setvar "DYNMODE" 3) (setvar "DYNPROMPT" 1)
  (if (not choice)
    (progn
      (princ "\nDailyPainkiller CLEANTOOLS v0.2.0 - press Down Arrow for cursor choices.")
      (initget "Remove BLocks Cleanup BUrst Outside Help")
      (setq k (getkword "\nCLEANTOOLS [Remove/BLocks/Cleanup/BUrst/Outside/Help] <exit>: ")
            choice (cond ((= k "Remove") 1) ((= k "BLocks") 2) ((= k "Cleanup") 3)
                         ((= k "BUrst") 4) ((= k "Outside") 5) ((= k "Help") 6)))))
  (cond
    ((= choice 4) (CT:burst))
    ((= choice 6) (CT:help))
    ((member choice '(1 2 3 5))
      (setvar "CMDECHO" 0)
      (vla-startundomark CT:doc) (setq undo T)
      (cond ((= choice 1) (CT:delete-top)) ((= choice 2) (CT:blocks))
            ((= choice 3) (CT:cleanup)) ((= choice 5) (CT:outside)))
      (vla-endundomark CT:doc) (setq undo nil)))
  (if CT:boundary-highlight (vl-catch-all-apply 'redraw (list CT:boundary-highlight 4)))
  (if (not CT:keep-selection) (sssetfirst nil nil))
  (setvar "CMDECHO" oldecho) (setvar "DYNMODE" olddyn) (setvar "DYNPROMPT" oldprompt)
  (princ))

(defun c:CLEANTOOLS () (CT:run nil))
(defun c:CTOUTSIDE () (CT:run 5))

(princ "\nCLEANTOOLS v0.2.0 loaded. Type CLEANTOOLS or CTOUTSIDE. No drawing changes made on load.")
(princ)
