;;; ---------------------------------------------------------------------
;;;  LYRWIPE-bgol.lsp
;;;  Command:  LWP
;;;
;;;  PURPOSE
;;;  Deletes every entity belonging to a target layer, identified simply
;;;  by picking one entity on that layer. Useful as the required first
;;;  step before a layer can be deleted (a layer must be empty first),
;;;  or for clearing stale content before a script regenerates a layer.
;;;
;;;  USAGE
;;;    1. Load this file (APPLOAD or drag-drop onto the drawing window).
;;;    2. Type   LWP   at the command line and press Enter.
;;;    3. Select (pick) one entity that resides on the layer you want to
;;;       clear.
;;;    4. Every entity in the current drawing that belongs to that same
;;;       layer is deleted.
;;;
;;;  NOTES
;;;    - Entities on locked layers cannot be erased by AutoLISP; the
;;;      routine reports how many were skipped, if any.
;;;    - This is an original, independently written implementation.
;;;      It is INSPIRED by the general idea of pick-based, layer-wide
;;;      deletion utilities common in CAD drafting workflows, but the
;;;      code, command name and file name here are new and are NOT
;;;      copied from, nor identical to, any specific third-party product.
;;;
;;;  ---------------------------------------------------------------------
;;;  Developed and shared for the CAD community by:  BGol Community
;;;  Community website:                              https://bgol.in/
;;;  License:  Open-source & free to use, modify, and share for all.
;;;            Provided "as is", without warranty of any kind.
;;;  ---------------------------------------------------------------------

(vl-load-com)

(defun C:LWP ( / ent edata lname ss n i deleted skipped result)
  (setq ent (car (entsel "\nSelect entity on layer to delete: ")))
  (if ent
    (progn
      (setq edata (entget ent))
      (setq lname (cdr (assoc 8 edata)))
      (setq ss (ssget "_X" (list (cons 8 lname))))
      (if ss
        (progn
          (setq deleted 0)
          (setq skipped 0)
          (setq n (sslength ss))
          (setq i 0)
          (while (< i n)
            (setq result (vl-catch-all-apply 'entdel (list (ssname ss i))))
            (if (vl-catch-all-error-p result)
              (setq skipped (1+ skipped))
              (setq deleted (1+ deleted))
            )
            (setq i (1+ i))
          )
          (princ (strcat "\nLWP: deleted " (itoa deleted)
                          " entity(ies) on layer \"" lname "\"."))
          (if (> skipped 0)
            (princ (strcat " (" (itoa skipped) " skipped, likely locked.)"))
          )
        )
        (princ (strcat "\nNo entities found on layer \"" lname "\"."))
      )
    )
    (princ "\nNo entity selected.")
  )
  (princ)
)

(princ "\nLYRWIPE-bgol.lsp loaded. Type LWP to delete all entities on a picked layer.")
(princ "\n  -- Free & open-source, courtesy of BGol Community (https://bgol.in/) --")
(princ)
