;;; AutoCATS 리습 자료실
;; 명령: LAYLENGTH
;; 기능: 선·호·원·경량 폴리선의 길이를 레이어별로 합산합니다.
;; 출처: https://www.autocats.co.kr/lisp/layer-length-sum
;; 버전: 1.0 (2026-10-23)
;; 라이선스: 자유 사용·수정, 재배포 시 출처(autocats.co.kr) 표기
;; 안전: 잠긴 레이어·외부참조 보호, 변경은 UNDO 그룹, 명령별 범위는 상세 가이드 참고

(vl-load-com)

(defun autocats-laylength-length (ent / end)
  (setq end (vl-catch-all-apply 'vlax-curve-getEndParam (list ent)))
  (if (not (vl-catch-all-error-p end)) (vlax-curve-getDistAtParam ent end)))
(defun autocats-laylength-data (ss / index rows ent key pair value)
  (setq index 0 rows nil)
  (repeat (sslength ss)
    (setq ent (ssname ss index) key (cdr (assoc 8 (entget ent))) value (autocats-laylength-length ent) pair (assoc key rows))
    (if value (setq rows (if pair (subst (cons key (+ value (cdr pair))) pair rows) (cons (cons key value) rows))))
    (setq index (1+ index)))
  (vl-sort rows '(lambda (a b) (< (car a) (car b)))))

(defun c:LAYLENGTH (/ *error* undo-open result row 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[LAYLENGTH] 중단: " msg)))
    (princ))

  (setq selection (ssget '((0 . "LINE,ARC,CIRCLE,LWPOLYLINE"))))
  (if selection (progn
      (setq result (autocats-laylength-data selection))
      (foreach row result (princ (strcat "\n" (car row) " / L=" (rtos (cdr row) 2 4))))))

  (princ))

(princ "\n[AutoCATS] LAYLENGTH 로드 완료")
(princ)
