;;; AutoCATS 리습 자료실
;; 명령: DREAL
;; 기능: 치수 문자 재지정을 지워 측정값 표시로 복원합니다.
;; 출처: https://www.autocats.co.kr/lisp/dimension-reset
;; 버전: 1.0 (2026-10-23)
;; 라이선스: 자유 사용·수정, 재배포 시 출처(autocats.co.kr) 표기
;; 안전: 잠긴 레이어·외부참조 보호, 변경은 UNDO 그룹, 명령별 범위는 상세 가이드 참고

(vl-load-com)

(defun autocats-dreal-safe-p (ent / data row block)
  (setq data (entget ent)
    row (tblsearch "LAYER" (cdr (assoc 8 data))))
  (and data row (= 0 (logand 4 (cdr (assoc 70 row))))
    (or (/= "INSERT" (cdr (assoc 0 data)))
      (and (setq block (tblsearch "BLOCK" (cdr (assoc 2 data))))
        (= 0 (logand 12 (cdr (assoc 70 block))))))))

(defun autocats-dreal-replace-pair (code value data)
  (if (assoc code data) (subst (cons code value) (assoc code data) data)
    (append data (list (cons code value)))))

(defun autocats-dreal-put (ent property value / data)
  (if (autocats-dreal-safe-p ent)
    (progn
      (setq data (autocats-dreal-replace-pair 1 value (entget ent)))
      (if (entmod data) (progn (entupd ent) T)))))

(defun autocats-dreal-batch (selection action / index changed skipped ent result)
  (setq index 0 changed 0 skipped 0)
  (if selection
    (repeat (sslength selection)
      (setq ent (ssname selection index)
        result (if (autocats-dreal-safe-p ent) (vl-catch-all-apply action (list ent))))
      (if (and result (not (vl-catch-all-error-p result)))
        (setq changed (1+ changed))
        (setq skipped (1+ skipped)))
      (setq index (1+ index))))
  (princ (strcat "\n[DREAL] 완료: " (itoa changed) " / 건너뜀: " (itoa skipped)))
  (list changed skipped))

(defun autocats-dreal-apply (ent)
  (and (= "DIMENSION" (cdr (assoc 0 (entget ent)))) (autocats-dreal-put ent 'TextOverride "")))

(defun c:DREAL (/ *error* undo-open  selection)
  (defun *error* (msg)
    (if undo-open (progn (command-s "_.UNDO" "_End") (setq undo-open nil)))
    (if (and msg (not (wcmatch (strcase msg) "*CANCEL*,*QUIT*,*EXIT*,*취소*")))
      (princ (strcat "\n[DREAL] 중단: " msg)))
    (princ))

  (princ "\n대상 객체를 선택하세요: ")
  (setq selection (ssget '((0 . "DIMENSION"))))
  (if selection
    (progn
      (command "_.UNDO" "_Begin")

      (setq undo-open T)
      (autocats-dreal-batch selection 'autocats-dreal-apply)
      (command "_.UNDO" "_End")
      (setq undo-open nil)))

  (princ))

(princ "\n[AutoCATS] DREAL 로드 완료")
(princ)
