;;; ------------------------------------------------------------
;;; AutoCATS ¸®½À ÀÚ·á½Ç
;; ¸í·É: LAYCOUNT
;; ±â´É: µµ¸é ÀüÃ¼ÀÇ ·¹ÀÌ¾îº° °´Ã¼ ¼ö¿Í ºó ·¹ÀÌ¾î Á¶È¸
;; ÃâÃ³: https://www.autocats.co.kr/lisp/layer-object-count
;; ¹öÀü: 1.0 (2026-07-27)
;; ¶óÀÌ¼±½º: ÀÚÀ¯ »ç¿ë¡¤¼öÁ¤, Àç¹èÆ÷ ½Ã ÃâÃ³(autocats.co.kr) Ç¥±â
;; ¾ÈÀü: *error* ÇÚµé·¯, Á¶È¸ Àü¿ëÀ¸·Î µµ¸é °´Ã¼¸¦ º¯°æÇÏÁö ¾ÊÀ½
;;; ------------------------------------------------------------

(vl-load-com)

(defun autocats-laycount-seed (/ row rows)
  (setq row (tblnext "LAYER" T) rows nil)
  (while row
    (setq rows (cons (cons (cdr (assoc 2 row)) 0) rows)
          row (tblnext "LAYER")))
  rows)

(defun autocats-laycount-add (name rows / found)
  (if (setq found (assoc name rows))
    (subst (cons name (1+ (cdr found))) found rows)
    (cons (cons name 1) rows)))

(defun autocats-laycount-data (/ ss idx block-row block-name block-ent ent data layer rows)
  (setq rows (autocats-laycount-seed)
        ss (ssget "_X")
        idx 0)
  (if ss
    (while (< idx (sslength ss))
      (setq data (entget (ssname ss idx))
            layer (cdr (assoc 8 data)))
      (if layer (setq rows (autocats-laycount-add layer rows)))
      (setq idx (1+ idx))))
  (setq block-row (tblnext "BLOCK" T))
  (while block-row
    (setq block-name (cdr (assoc 2 block-row)))
    (if (and (null (vl-string-search "*MODEL_SPACE" (strcase block-name)))
             (null (vl-string-search "*PAPER_SPACE" (strcase block-name))))
      (progn
        (setq block-ent (tblobjname "BLOCK" block-name)
              ent (if block-ent (entnext block-ent) nil))
        (while (and ent (/= "ENDBLK" (cdr (assoc 0 (entget ent)))))
          (setq data (entget ent)
                layer (cdr (assoc 8 data)))
          (if layer (setq rows (autocats-laycount-add layer rows)))
          (setq ent (entnext ent)))))
    (setq block-row (tblnext "BLOCK")))
  (vl-sort rows
    '(lambda (left right)
       (< (strcase (car left)) (strcase (car right))))))

(defun c:LAYCOUNT (/ *error* rows empty total)
  (defun *error* (msg)
    (if (and msg (not (wcmatch (strcase msg) "*CANCEL*,*QUIT*,*EXIT*,*Ãë¼Ò*")))
      (princ (strcat "\n[LAYCOUNT] Áß´Ü: " msg)))
    (princ))

  (setq rows (autocats-laycount-data)
        empty 0 total 0)
  (princ "\n[LAYCOUNT] ·¹ÀÌ¾îº° °´Ã¼ ¼ö")
  (foreach row rows
    (setq total (+ total (cdr row)))
    (if (= 0 (cdr row))
      (progn
        (setq empty (1+ empty))
        (princ (strcat "\n  " (car row) ": 0 [ºó ·¹ÀÌ¾î]")))
      (princ (strcat "\n  " (car row) ": " (itoa (cdr row))))))
  (princ (strcat "\n[LAYCOUNT] ¿Ï·á: " (itoa (length rows))
                 "°³ ·¹ÀÌ¾î / " (itoa empty) "°³ ºó ·¹ÀÌ¾î / "
                 (itoa total) "°³ °´Ã¼"))
  (princ))

(princ "\n[AutoCATS] LAYCOUNT ·Îµå ¿Ï·á - ¸í·ÉÇà¿¡ LAYCOUNT ¸¦ ÀÔ·ÂÇÏ¼¼¿ä.")
(princ)
