;;; AutoCATS 리습 자료실
;; 명령: DSCALE
;; 기능: 선택한 치수의 전체 축척을 같은 양수 값으로 지정합니다.
;; 출처: https://www.autocats.co.kr/lisp/dimension-scale
;; 버전: 1.0 (2026-10-23)
;; 라이선스: 자유 사용·수정, 재배포 시 출처(autocats.co.kr) 표기
;; 안전: 잠긴 레이어·외부참조 보호, 변경은 UNDO 그룹, 명령별 범위는 상세 가이드 참고

(vl-load-com)

(defun autocats-dscale-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-dscale-put (ent property value / old result)
  (if (autocats-dscale-safe-p ent)
    (progn
      (setq old (getvar "DIMSCALE")
        result (vl-catch-all-apply
          '(lambda () (command "_.DIMOVERRIDE" "DIMSCALE" value "" ent "") T)))
      (setvar "DIMSCALE" old)
      (not (vl-catch-all-error-p result)))))

(defun autocats-dscale-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-dscale-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[DSCALE] 완료: " (itoa changed) " / 건너뜀: " (itoa skipped)))
  (list changed skipped))

(defun autocats-dscale-apply (ent value)
  (and (and (numberp value) (> value 0.0)) (member (cdr (assoc 0 (entget ent))) '("DIMENSION"))
    (autocats-dscale-put ent 'ScaleFactor value)))

(defun c:DSCALE (/ *error* undo-open value 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[DSCALE] 중단: " msg)))
    (princ))
  (initget 7) (setq value (getreal "\n치수 전체 축척 (예: 50): "))
  (if value (progn
      (princ "\n대상 객체를 선택하세요: ")
      (setq selection (ssget '((0 . "DIMENSION"))))
      (if selection
        (progn
          (command "_.UNDO" "_Begin")

          (setq undo-open T)
          (autocats-dscale-batch selection '(lambda (ent) (autocats-dscale-apply ent value)))
          (command "_.UNDO" "_End")
          (setq undo-open nil)))))
  (princ))

(princ "\n[AutoCATS] DSCALE 로드 완료")
(princ)
