;;;--- CPYXREF - Copy any entity from an XREF or a block.
;;;--- Legalities:
;;; Copyright 2002-2004 by JefferyPSanders.com
;;; All rights reserved.
;;;; You may use this program for free. You may not obtain profit without consent
;;; from Jeffery P Sanders. You may make copies of this program and distribute as
;;; long as the legalities remain in tact.
;;; End of Legalities
;;;--- Created on 7/18/02

;;;--- Main application
(defun C:CXF()

;;;--- Turn the command echo off
(setvar "cmdecho" 0)

;;;--- Save some system variables
(setq origCmddia(getvar "cmddia"))
(setq origFiledia(getvar "filedia"))

;;;--- Set some system variables
(setvar "cmddia" 0)
(setvar "filedia" 0)

;;;--- Select an entity
(if (setq entselected(entsel "\n Select XRef or Block: "))

;;;--- Save the entity name
(setq en(car entselected))

;;;--- Save the point selected
(setq selectedPt(cadr entselected))

;;;--- Get entity's DXF group codes
(setq enlist(entget en))

;;;--- If it is a block
(if(= "INSERT" (cdr(assoc 0 enlist)))

;;;--- Get the dxf group codes for the first sub-entity
(setq enlist2(tblNext "block" en))

;;;--- Save the file name of the block
(setq shortFileName(cdr(assoc 2 enlist))) ;thanks to Gьnther Bittner for fix

;;;--- Set a mark for the undo command
(command "undo" "mark")

;;;--- Make the XREF part of the drawing temporarily
(command "-xref" "bind" shortFileName)

;;;--- Explode the block temporarily
(command "explode" en)

;;;--- Get the entity at the point selected originally if it exist
(if (setq eset(ssget selectedPt))

;;;--- Get the name of the entity selected
(setq en(ssname eset 0))

;;;--- Get the DXF group codes of the entity
(setq enlist(entget en))

;;;--- Make a wblock named "X2"
(if(findfile "x2.dwg")
(command "_wblock" "x2" "y" "" selectedPt en "")
(command "_wblock" "x2" "" selectedPt en "")

;;;--- Undo everything back to the marked position
(command "undo" "Back")

;;;--- Insert the X2 block
(setq pt1(getpoint selectedPt "\n Insertion Point: "))
(command "insert" "*x2" pt1 "" "")

(alert "*Error* - Select a sub-entity.")
(alert "*Error* - Select a block or an XREF.")
(alert "*Error* - Select a block or an XREF please.")

;;;--- Reset system variables
(setvar "cmddia" origCmddia)
(setvar "filedia" origFiledia)

;;;--- Turn command echo back on
(setvar "cmdecho" 1)

;;;--- Inform the user
(princ "\n ...CPYXREF.lsp Complete. ")
(princ "\n By: Jeffery P. Sanders 7/19/02 Copyright 2002-2004 by JefferyPSanders.com")

;;;--- Suppress last echo for a clean exit