Hopefully a working merge with trunk (could be one error left in raytrace.c - will...
[blender.git] / release / scripts / import_dxf.py
index bb0119a9a813596dfddda1ed91bb6676b34a79b6..4de1de1ee39c525397545ba1d4959820e28c31ff 100644 (file)
@@ -1,21 +1,22 @@
 #!BPY
 
 """
-Name: 'Autodesk DXF (.dxf)'
+Name: 'Autodesk DXF (.dxf .dwg)'
 Blender: 246
 Group: 'Import'
-Tooltip: 'Import for DXF geometry data (Drawing eXchange Format).'
+Tooltip: 'Import for DWG/DXF geometry data.'
 """
 __author__ = 'Kitsu(Ed Blake) & migius(Remigiusz Fiedler)'
-__version__ = '1.12 - 2008.08.03 by migius'
+__version__ = '1.12 - 2009.04.11 by migius'
 __url__ = ["http://blenderartists.org/forum/showthread.php?t=84319",
         "http://wiki.blender.org/index.php/Scripts/Manual/Import/DXF-3D"]
 __email__ = ["migius(at)4d-vectors.de","Kitsune_e(at)yahoo.com"]
 __bpydoc__ = """\
-This script imports objects from DXF (2d/3d) into Blender.
+This script imports objects from DWG/DXF (2d/3d) into Blender.
 
 This script imports 2d and 3d geometery from DXF files.
-Supported DXF format versions: from (r2.5) r12 up to 2008.
+It supports DWG format too, with help of an external converter.
+Supported DXF format versions: from (r2.5) r12 up to r2008.
 Enhanced features are:
 - configurable object filtering and geometry manipulation,
 - configurable material pre-processing,
@@ -32,7 +33,7 @@ MINSERT (=array of blocks),
 CIRCLE,
 ARC,
 3DFACE,
-2d-POLYLINE (=plane, incl. arc, variable-width, curve, spline),
+2d-POLYLINE (=in plane, incl. arc, variable-width, curve, spline),
 3d-POLYLINE (=non-plane),
 3d-POLYMESH,
 3d-POLYFACE,
@@ -57,7 +58,7 @@ Supported layout modes:
 "model space" is default,
 "paper space" as option (= "layout views")
 
-Supported scene definition objescts produced with AVE_RENDER:
+Supported scene definition objects produced with AVE_RENDER:
 scene: selection of lights assigned to the camera,
 lights: DIRECT, OVERHEAD, SH_SPOT,
 (wip v1.13 import of AVE_RENDER material definitions)
@@ -88,7 +89,7 @@ in creating new objects in scene database - probably a database management probl
 
 """
 History:
- v1.0 - 2007/2008 by migius
+ v1.0 - 2007/2008/2009 by migius
  planned tasks:
  -- (to see more, search for "--todo--" in script code)
  -- command-line-mode/batch-mode
@@ -111,6 +112,16 @@ History:
  -- support ortho mode for VIEWs and VPORTs as cameras 
 
 
+ v1.12 - 2009.04.11 by migius
+ d4 added DWG support, Stani Michiels idea for binding an extern DXF-DWG-converter 
+ v1.12 - 2009.03.14 by migius
+ d3 removed all set()functions (problem with osx/python<2.4 reported by Blinkozo)
+ d3 code-cleaning
+ v1.12 - 2009.01.14 by migius
+ d2 temp patch for noname BLOCKS (*X,*U,*D)
+ v1.12 - 2008.11.16 by migius
+ d1 remove try_finally: cause not supported in python <2.5
+ d1 add Bezier curves bevel radius support (default 1.0)
  v1.12 - 2008.08.03 by migius
  c2 warningfix: relocating of globals: layersmap, oblist 
  c2 modif UI: buttons newScene+targetLayer moved to start panel
@@ -297,7 +308,8 @@ History:
 # --------------------------------------------------------------------------
 
 import Blender
-from Blender import *
+from Blender import Mathutils, BezTriple, Draw, Registry, sys,\
+Text3d, Window, Mesh, Material, Group
 #from Blender.Mathutils import Vector, Matrix
 import bpy
 #import BPyMessages
@@ -306,12 +318,21 @@ from dxfReader import readDXF
 #from dxfReader import get_name, get_layer
 from dxfReader import Object as dxfObject
 from dxfColorMap import color_map
-
-from math import *
-
-try:
-       import os
-       if os.name:# != 'mac':
+from math import log10, sqrt, radians, degrees, atan, cos, sin
+
+# osx-patch by Blinkozo
+#todo: avoid additional modules, prefer Blender-build-in test routines
+#import platform
+#if platform.python_version() < '2.4':
+#    from sets import Set as set
+#from sys import version_info
+#ver = '%s.%s' % version_info[0:2]
+# end osx-patch
+
+import subprocess
+import os
+if os.name != 'mac':
+       try:
                import psyco
                psyco.log(Blender.Get('tempdir')+"/blender.log-psyco")
                #psyco.log()
@@ -319,14 +340,13 @@ try:
                psyco.profile(0.05, memory=100)
                psyco.profile(0.2)
                #print 'psyco imported'
-except ImportError:
-       #print 'psyco not imported'
-       pass
+       except ImportError:
+               print 'psyco not imported'
 
 #try: Curve.orderU
 
 print '\n\n\n'
-print 'DXF-Importer v%s *** start ***' %(__version__)   #---------------------
+print 'DXF/DWG-Importer v%s *** start ***' %(__version__)   #---------------------
 
 SCENE = None
 WORLDX = Mathutils.Vector((1,0,0))
@@ -370,6 +390,29 @@ FREE = BezTriple.HandleTypes.FREE
 VECT = BezTriple.HandleTypes.VECT
 ALIGN = BezTriple.HandleTypes.ALIGN
 
+UI_MODE = True #activates UI-popup-print, if not multiple files imported
+
+
+#-------- DWG support ------------------------------------------
+extCONV_OK = True
+extCONV = 'DConvertCon.exe'
+extCONV_PATH = os.path.join(Blender.Get('scriptsdir'),extCONV)
+if not os.path.isfile(extCONV_PATH):
+       extCONV_OK = False
+       extCONV_TEXT = 'DWG-Importer cant find external DWG-converter (%s) in Blender script directory.|\
+More details in online Help.' %extCONV
+else:
+       if not os.sys.platform.startswith('win'):
+               # check if Wine installed:   
+               if subprocess.Popen(('which', 'winepath'), stdout=subprocess.PIPE).stdout.read().strip():
+                       extCONV_PATH    = 'wine %s'%extCONV_PATH
+               else: 
+                       extCONV_OK = False
+                       extCONV_TEXT = 'The external DWG-converter (%s) needs Wine installed on your system.|\
+More details in online Help.' %extCONV
+#print 'extCONV_PATH = ', extCONV_PATH
+
+
 
 class View:  #-----------------------------------------------------------------
        """Class for objects representing dxf VIEWs.
@@ -738,7 +781,7 @@ class Solid:  #-----------------------------------------------------------------
 
                if settings.var['vGroup_on'] and not M_OBJ:
                        # each MeshSide becomes vertexGroup for easier material assignment ---------------------
-                       replace = Blender.Mesh.AssignModes.ADD  #or .AssignModes.ADD/REPLACE
+                       replace = Mesh.AssignModes.ADD  #or .AssignModes.ADD/REPLACE
                        if vg_left: me.addVertGroup('side.left')  ; me.assignVertsToGroup('side.left',  vg_left, 1.0, replace)
                        if vg_right:me.addVertGroup('side.right') ; me.assignVertsToGroup('side.right', vg_right, 1.0, replace)
                        if vg_top:  me.addVertGroup('side.top')   ; me.assignVertsToGroup('side.top',   vg_top, 1.0, replace)
@@ -882,7 +925,7 @@ class Line:  #-----------------------------------------------------------------
                                ob.link(me) # link mesh to that object
                                vG_name = 'color_%s' %self.color_index
                                if edges: faces = edges
-                               replace = Blender.Mesh.AssignModes.ADD  #or .AssignModes.REPLACE or ADD
+                               replace = Mesh.AssignModes.ADD  #or .AssignModes.REPLACE or ADD
                                try:
                                        me.assignVertsToGroup(vG_name,  faces[0], 1.0, replace)
                                        #print 'deb: existed vGroup:', vG_name #---------------------
@@ -946,7 +989,7 @@ class Point:  #-----------------------------------------------------------------
                if thic < settings.var['dist_min']: thic = settings.var['dist_min']
 
                if points_as in [1,3,4,5]:
-                       if True: # points_as in [1,5]: # as 'empty'
+                       if points_as in [1,5]: # as 'empty'
                                c = 'Empty'
                        elif points_as == 3: # as 'thin sphere'
                                res = settings.var['thin_res']
@@ -1272,66 +1315,6 @@ class Polyline:  #--------------------------------------------------------------
                pline = Curve.New(obname)   # create new curve data
                #pline.setResolu(24) #--todo-----                                               
 
-               if False: #old self.spline:  # NURBSplines-----OK-----
-                       #print 'deb:polyline2dCurve.draw self.spline!' #---------------
-                       weight1 = 0.5
-                       weight2 = 1.0
-                       if self.curvQuadrati:
-                               # Bezier-curve form simulated in NURBS-curve
-                               # generate middlepoints except start/end-segments ---
-                               #print 'deb:polyline2dCurve.draw extraQBspline!' #---------------
-                               temp_points = []
-                               point = d_points[0].loc
-                               point.append(weight1)
-                               temp_points.append(point)
-                               for i in xrange(1,len(d_points)-2):
-                                       point1 = d_points[i].loc
-                                       point2 = d_points[i+1].loc
-                                       mpoint = list((Mathutils.Vector(point1) + Mathutils.Vector(point2)) * 0.5)
-                                       mpoint.append(weight2)
-                                       point1.append(weight1)
-                                       temp_points.append(point1)
-                                       temp_points.append(mpoint)
-                               point2.append(weight1)
-                               temp_points.append(point2)
-                               point = d_points[-1].loc
-                               point.append(weight1)
-                               temp_points.append(point)
-                               d_points = temp_points
-                       else:
-                               temp_points = []
-                               for d in d_points:
-                                       d = d.loc
-                                       d.append(weight1)
-                                       temp_points.append(d)
-                               d_points = temp_points
-
-                       if not self.closed:
-                               # generate extended startpoint and endpoint------
-                               point1 = Mathutils.Vector(d_points[0][:3])
-                               point2 = Mathutils.Vector(d_points[1][:3])
-                               startpoint = list(point1 - point2 + point1)
-                               startpoint.append(weight1)
-                               point1 = Mathutils.Vector(d_points[-1][:3])
-                               point2 = Mathutils.Vector(d_points[-2][:3])
-                               endpoint = list(point1 - point2 + point1)
-                               endpoint.append(weight1)
-                               temp_points = []
-                               temp_points.append(startpoint)
-                               temp_points.extend(d_points)
-                               d_points = temp_points
-                               d_points.append(endpoint)
-
-                       point = d_points[0]
-                       curve = pline.appendNurb(point)
-                       curve.setType(4) #NURBS curve
-                       for point in d_points[1:]:
-                               curve.append(point)
-                       if self.closed:
-                               curve.flagU = 1 # Set curve cyclic=close
-                       else:
-                               curve.flagU = 0 # Set curve not cyclic=open
-
                if self.spline:  # NURBSplines-----OK-----
                        #print 'deb:polyline2dCurve.draw self.spline!' #---------------
                        nurbs_points = []
@@ -1352,20 +1335,6 @@ class Polyline:  #--------------------------------------------------------------
                        except AttributeError: pass
                        #print 'deb: dir(curve):', dir(curve) #----------------
 
-               elif  False: #orig self.curved:  #--Bezier-curves---OK-------
-                       #print 'deb:polyline2dCurve.draw self.curved!' #---------------
-                       curve = pline.appendNurb(BezTriple.New(d_points[0]))
-                       for p in d_points[1:]:
-                               curve.append(BezTriple.New(p))
-                       for point in curve:
-                               point.handleTypes = [AUTO, AUTO]
-                       if self.closed:
-                               curve.flagU = 1 # Set curve cyclic=close
-                       else:
-                               curve.flagU = 0 # Set curve not cyclic=open
-                               curve[0].handleTypes = [FREE, ALIGN]   #remi--todo-----
-                               curve[-1].handleTypes = [ALIGN, FREE]   #remi--todo-----
-
                elif  self.curved:  #--SPLINE as Bezier-curves---wip------
                        #print 'deb:polyline2dCurve.draw self.curved!' #---------------
                        begtangent, endtangent = None, None
@@ -1414,61 +1383,47 @@ class Polyline:  #--------------------------------------------------------------
                        for i in xrange(len(d_points)):
                                point1 = d_points[i]
                                #point2 = d_points[i+1]
-                               if False: #-----outdated!- standard calculation ----------------------------------
-                                       if point1.bulge and (i < len(d_points)-2 or self.closed):
-                                               verts, center = calcBulge(point1, point2, arc_res, triples=False)
-                                               if i == 0: curve = pline.appendNurb(BezTriple.New(verts[0]))
-                                               else: curve.append(BezTriple.New(verts[0]))
-                                               curve[-1].handleTypes = [VECT, VECT]  #--todo--calculation of bezier-tangents
-                                               for p in verts[1:]:
-                                                       curve.append(BezTriple.New(p))
-                                                       curve[-1].handleTypes = [AUTO, AUTO]
-                                       else:
-                                               if i == 0: curve = pline.appendNurb(BezTriple.New(point1.loc))
-                                               else: curve.append(BezTriple.New(point1.loc))
-                                               curve[-1].handleTypes = [VECT, VECT]   #--todo--calculation of bezier-tangents
-
-                               elif True:   #----- optimised Bezier-Handles calculation --------------------------------
-                                       #print 'deb:drawPlineCurve: i:', i #---------
-                                       if point1.bulge and not (i == len(d_points)-1 and point1.bulge and not self.closed):
-                                               if i == len(d_points)-1: point2 = d_points[0]
-                                               else: point2 = d_points[i+1]
+                               #----- optimised Bezier-Handles calculation --------------------------------
+                               #print 'deb:drawPlineCurve: i:', i #---------
+                               if point1.bulge and not (i == len(d_points)-1 and point1.bulge and not self.closed):
+                                       if i == len(d_points)-1: point2 = d_points[0]
+                                       else: point2 = d_points[i+1]
 
 
-                                               # calculate additional points for bulge
-                                               VectorTriples = calcBulge(point1, point2, arc_res, triples=True)
+                                       # calculate additional points for bulge
+                                       VectorTriples = calcBulge(point1, point2, arc_res, triples=True)
 
-                                               if prevHandleType == FREE:
-                                                       #print 'deb:drawPlineCurve: VectorTriples[0]:', VectorTriples[0] #---------
-                                                       VectorTriples[0][:3] = prevHandleVect
-                                                       #print 'deb:drawPlineCurve: VectorTriples[0]:', VectorTriples[0] #---------
+                                       if prevHandleType == FREE:
+                                               #print 'deb:drawPlineCurve: VectorTriples[0]:', VectorTriples[0] #---------
+                                               VectorTriples[0][:3] = prevHandleVect
+                                               #print 'deb:drawPlineCurve: VectorTriples[0]:', VectorTriples[0] #---------
 
-                                               if i == 0: curve = pline.appendNurb(BezTriple.New(VectorTriples[0]))
-                                               else: curve.append(BezTriple.New(VectorTriples[0]))
-                                               curve[-1].handleTypes = [prevHandleType, FREE]
+                                       if i == 0: curve = pline.appendNurb(BezTriple.New(VectorTriples[0]))
+                                       else: curve.append(BezTriple.New(VectorTriples[0]))
+                                       curve[-1].handleTypes = [prevHandleType, FREE]
+                                       curve[-1].radius = 1.0
 
-                                               for p in VectorTriples[1:-1]:
-                                                       curve.append(BezTriple.New(p))
-                                                       curve[-1].handleTypes = [FREE, FREE]
+                                       for p in VectorTriples[1:-1]:
+                                               curve.append(BezTriple.New(p))
+                                               curve[-1].handleTypes = [FREE, FREE]
 
-                                               prevHandleVect = VectorTriples[-1][:3]
-                                               prevHandleType = FREE
-                                               #print 'deb:drawPlineCurve: prevHandleVect:', prevHandleVect #---------
+                                       prevHandleVect = VectorTriples[-1][:3]
+                                       prevHandleType = FREE
+                                       #print 'deb:drawPlineCurve: prevHandleVect:', prevHandleVect #---------
+                               else:
+                                       #print 'deb:drawPlineCurve: else' #----------
+                                       if prevHandleType == FREE:
+                                               VectorTriples = prevHandleVect + list(point1) + list(point1)
+                                               #print 'deb:drawPlineCurve: VectorTriples:', VectorTriples #---------
+                                               curve.append(BezTriple.New(VectorTriples))
+                                               curve[-1].handleTypes = [FREE, VECT]
+                                               prevHandleType = VECT
+                                               curve[-1].radius = 1.0
                                        else:
-                                               #print 'deb:drawPlineCurve: else' #----------
-                                               if prevHandleType == FREE:
-                                                       VectorTriples = prevHandleVect + list(point1) + list(point1)
-                                                       #print 'deb:drawPlineCurve: VectorTriples:', VectorTriples #---------
-                                                       curve.append(BezTriple.New(VectorTriples))
-                                                       curve[-1].handleTypes = [FREE, VECT]
-                                                       prevHandleType = VECT
-                                               else:
-                                                       if i == 0: curve = pline.appendNurb(BezTriple.New(point1.loc))
-                                                       else: curve.append(BezTriple.New(point1.loc))
-                                                       curve[-1].handleTypes = [VECT, VECT]
-                                                       
-
-
+                                               if i == 0: curve = pline.appendNurb(BezTriple.New(point1.loc))
+                                               else: curve.append(BezTriple.New(point1.loc))
+                                               curve[-1].handleTypes = [VECT, VECT]
+                                               curve[-1].radius = 1.0
                                        #print 'deb:drawPlineCurve: curve[-1].vec[0]', curve[-1].vec[0] #----------
 
                        if self.closed:
@@ -1565,23 +1520,6 @@ class Polyline:  #--------------------------------------------------------------
                d_points = self.doubles_out(settings, d_points)
                #print 'deb:drawPolyCurve d_pointsList =after DV-outsorting=====:\n ', d_points #------------------------
 
-               """# routine to sort out of "double.vertices" ------------------------------------
-               minimal_dist =  settings.var['dist_min'] * 0.1
-               temp_points = []
-               for i in xrange(len(d_points)-1):
-                       point = d_points[i]
-                       point2 = d_points[i+1]
-                       #print 'deb:double.vertex p1,p2', point, point2 #------------------------
-                       delta = Mathutils.Vector(point2.loc) - Mathutils.Vector(point.loc)
-                       if delta.length > minimal_dist:
-                                temp_points.append(point)
-                       #else: print 'deb:drawPoly2d double.vertex sort out!' #------------------------
-               temp_points.append(d_points[-1])  #------ incl. last vertex -------------
-               #if self.closed: temp_points.append(d_points[1])  #------ loop start vertex -------------
-               d_points = temp_points   #-----vertex.list without "double.vertices"
-               #print 'deb:drawPoly2d d_pointsList =after DV-outsorting=====:\n ', d_points #------------------------
-               """
-
                #print 'deb:drawPoly2d len of d_pointsList ====== ', len(d_points) #------------------------
                if len(d_points) < 2:  #if too few vertex, then return
                        #print 'deb:drawPoly2d corrupted Vertices' #---------
@@ -1777,29 +1715,6 @@ class Polyline:  #--------------------------------------------------------------
                                                        # clean corner intersection
                                                        pointsLc.append(cornerpointL)
                                                        pointsRc.append(cornerpointR)
-                                               elif False: # the standard no-intersection
-                                                       # --todo-- not optimal, because produces X-face
-                                                       pointsLc.extend((pointsLe[i],pointsLs[i+1]))
-                                                       pointsRc.extend((pointsRe[i],pointsRs[i+1]))
-                                               elif False: # --todo-- the optimised non-intersection
-                                                       if (cornerpointL - vecL1).length < (cornerpointR - vecR1).length:
-                                                               left_angle = True
-                                                       else:
-                                                               left_angle = False
-                                                       limit_dist = settings.var['dist_min']
-                                                       if left_angle:  # if left turning angle
-                                                               #print 'deb:drawPoly2d it is left turning angle' #-------------
-                                                               # to avoid triangelface/doubleVertex
-                                                               delta1 = (cornerpointL - vecL1).normalize() * limit_dist
-                                                               delta4 = (cornerpointL - vecL4).normalize() * limit_dist
-                                                               pointsLc.extend((cornerpointL - delta1, cornerpointL - delta4))
-                                                               pointsRc.extend((pointsRe[i],pointsRs[i+1]))
-                                                       else:  # if right turning angle
-                                                               #print 'deb:drawPoly2d right turning angle' #-------------
-                                                               delta1 = (cornerpointR - vecR1).normalize() * limit_dist
-                                                               delta4 = (cornerpointR - vecR4).normalize() * limit_dist
-                                                               pointsRc.extend((cornerpointR - delta1, cornerpointR - delta4))
-                                                               pointsLc.extend((pointsLe[i],pointsLs[i+1]))
                                                else:
                                                        pointsLc.extend((pointsLe[i],points[i+1],pointsLs[i+1]))
                                                        pointsRc.extend((pointsRe[i],points[i+1],pointsRs[i+1]))
@@ -1836,14 +1751,10 @@ class Polyline:  #--------------------------------------------------------------
                                        vecR3, vecR4 = pointsRs[i+1], pointsRe[i+1]
                                        if bulg_points[i] != None:
                                                #compute left- and right-cornerpoints
-                                               if True:
-                                                       cornerpointL = Mathutils.LineIntersect(vecL1, vecL2, vecL3, vecL4)
-                                                       cornerpointR = Mathutils.LineIntersect(vecR1, vecR2, vecR3, vecR4)
-                                                       pointsLc.append(cornerpointL[0])
-                                                       pointsRc.append(cornerpointR[0])
-                                               else:
-                                                       pointVec = Mathutils.Vector(point[i])
-
+                                               cornerpointL = Mathutils.LineIntersect(vecL1, vecL2, vecL3, vecL4)
+                                               cornerpointR = Mathutils.LineIntersect(vecR1, vecR2, vecR3, vecR4)
+                                               pointsLc.append(cornerpointL[0])
+                                               pointsRc.append(cornerpointR[0])
                                        else: # IF non-bulg
                                                pointsLc.extend((pointsLe[i],points[i+1],pointsLs[i+1]))
                                                pointsRc.extend((pointsRe[i],points[i+1],pointsRs[i+1]))
@@ -1899,27 +1810,26 @@ class Polyline:  #--------------------------------------------------------------
                                # which may be linked to more than one object.
                                if settings.var['vGroup_on'] and not M_OBJ:
                                        # each MeshSide becomes vertexGroup for easier material assignment ---------------------
-                                       replace = Blender.Mesh.AssignModes.REPLACE  #or .AssignModes.ADD
+                                       replace = Mesh.AssignModes.REPLACE  #or .AssignModes.ADD
                                        vg_left, vg_right, vg_top, vg_bottom = [], [], [], []
                                        for v in f_left: vg_left.extend(v)
                                        for v in f_right: vg_right.extend(v)
                                        for v in f_top: vg_top.extend(v)
                                        for v in f_bottom: vg_bottom.extend(v)
-                                       me.addVertGroup('side.left')  ; me.assignVertsToGroup('side.left',  list(set(vg_left)), 1.0, replace)
-                                       me.addVertGroup('side.right') ; me.assignVertsToGroup('side.right', list(set(vg_right)), 1.0, replace)
-                                       me.addVertGroup('side.top')   ; me.assignVertsToGroup('side.top',   list(set(vg_top)), 1.0, replace)
-                                       me.addVertGroup('side.bottom'); me.assignVertsToGroup('side.bottom',list(set(vg_bottom)), 1.0, replace)
+                                       me.addVertGroup('side.left')  ; me.assignVertsToGroup('side.left',  vg_left, 1.0, replace)
+                                       me.addVertGroup('side.right') ; me.assignVertsToGroup('side.right', vg_right, 1.0, replace)
+                                       me.addVertGroup('side.top')   ; me.assignVertsToGroup('side.top',   vg_top, 1.0, replace)
+                                       me.addVertGroup('side.bottom'); me.assignVertsToGroup('side.bottom',vg_bottom, 1.0, replace)
                                        if not self.closed:
                                                me.addVertGroup('side.start'); me.assignVertsToGroup('side.start', f_start[0], 1.0, replace)
                                                me.addVertGroup('side.end')  ; me.assignVertsToGroup('side.end',   f_end[0],   1.0, replace)
 
                                if settings.var['meshSmooth_on']:  # left and right side become smooth ----------------------
                                        #if self.spline or self.curved:
-                                       if True:
-                                               smooth_len = len(f_left) + len(f_right)
-                                               for i in xrange(smooth_len):
-                                                       me.faces[i].smooth = True
-                                               #me.Modes(AUTOSMOOTH)
+                                       smooth_len = len(f_left) + len(f_right)
+                                       for i in xrange(smooth_len):
+                                               me.faces[i].smooth = True
+                                       #me.Modes(AUTOSMOOTH)
 
                        # 2.level:IF width, but no-thickness  ---------------------
                        else:
@@ -1958,10 +1868,9 @@ class Polyline:  #--------------------------------------------------------------
 
                        if settings.var['meshSmooth_on']:  # left and right side become smooth ----------------------
                                #if self.spline or self.curved:
-                               if True:
-                                       for i in xrange(len(faces)):
-                                               me.faces[i].smooth = True
-                                       #me.Modes(AUTOSMOOTH)
+                               for i in xrange(len(faces)):
+                                       me.faces[i].smooth = True
+                               #me.Modes(AUTOSMOOTH)
 
                # 1.level:IF no-width and no-thickness  ---------------------
                else:
@@ -2664,36 +2573,17 @@ class Circle:  #----------------------------------------------------------------
                        cyl_rad = 0.5 * settings.var['width_min']
 
                if settings.var['lines_as'] == 5:  # draw CIRCLE as curve -------------
-                       if True:  # universal version
-                               arc_res = settings.var['curve_arc']
-                               #arc_res = 3
-                               start, end = 0.0, 360.0
-                               VectorTriples = calcArc(None, radius, start, end, arc_res, True)
-                               c = Curve.New(obname) # create new curve data
-                               curve = c.appendNurb(BezTriple.New(VectorTriples[0]))
-                               for p in VectorTriples[1:-1]:
-                                       curve.append(BezTriple.New(p))
-                               for point in curve:
-                                       point.handleTypes = [FREE, FREE]
-                       else:   # standard version
-                               c = Curve.New(obname)   # create new curve data
-                               p1 = (0, -radius, 0)
-                               p2 = (radius, 0, 0)
-                               p3 = (0, radius, 0)
-                               p4 = (-radius, 0, 0)
-       
-                               p1 = BezTriple.New(p1)
-                               p2 = BezTriple.New(p2)
-                               p3 = BezTriple.New(p3)
-                               p4 = BezTriple.New(p4)
-       
-                               curve = c.appendNurb(p1)
-                               curve.append(p2)
-                               curve.append(p3)
-                               curve.append(p4)
-                               for point in curve:
-                                       point.handleTypes = [AUTO, AUTO]
-
+                       arc_res = settings.var['curve_arc']
+                       #arc_res = 3
+                       start, end = 0.0, 360.0
+                       VectorTriples = calcArc(None, radius, start, end, arc_res, True)
+                       c = Curve.New(obname) # create new curve data
+                       curve = c.appendNurb(BezTriple.New(VectorTriples[0]))
+                       for p in VectorTriples[1:-1]:
+                               curve.append(BezTriple.New(p))
+                       for point in curve:
+                               point.handleTypes = [FREE, FREE]
+                               point.radius = 1.0
                        curve.flagU = 1  # 1 sets the curve cyclic=closed
                        if settings.var['fill_on']:
                                c.setFlag(6) # 2+4 set top and button caps
@@ -2715,24 +2605,6 @@ class Circle:  #----------------------------------------------------------------
                                ob.SizeZ *= abs(thic)
                        return ob
 
-               elif False: # create a new mesh_object with buildin_circle_primitive
-                       verts_num = settings.var['arc_res'] * sqrt(radius / settings.var['arc_rad'])
-                       if verts_num > 100: verts_num = 100 # Blender accepts only values [3:500]
-                       if verts_num < 4: verts_num = 4 # Blender accepts only values [3:500]
-                       if thic != 0:
-                               loc2 = thic * 0.5   #-----blenderAPI draw Cylinder with 2*thickness
-                               self.loc[2] += loc2  #---new location for the basis of cylinder
-                               #print 'deb:circleDraw:self.loc2:', self.loc  #-----------------------
-                               c = Mesh.Primitives.Cylinder(int(verts_num), radius*2, abs(thic))
-                       else:
-                               c = Mesh.Primitives.Circle(int(verts_num), radius*2)
-
-                       #c.update()
-                       ob = SCENE.objects.new(c, obname) # create a new circle_mesh_object
-                       ob.loc = tuple(self.loc)
-                       transform(self.extrusion, 0, ob)
-                       return ob
-
                else:  # draw CIRCLE as mesh -----------------------------------------------
                        if M_OBJ: obname, me, ob = makeNewObject()
                        else: 
@@ -2785,15 +2657,16 @@ class Circle:  #----------------------------------------------------------------
                                # each MeshSide becomes vertexGroup for easier material assignment ---------------------
                                if settings.var['vGroup_on'] and not M_OBJ:
                                        # each MeshSide becomes vertexGroup for easier material assignment ---------------------
-                                       replace = Blender.Mesh.AssignModes.REPLACE  #or .AssignModes.ADD
+                                       replace = Mesh.AssignModes.REPLACE  #or .AssignModes.ADD
                                        vg_band, vg_top, vg_bottom = [], [], []
                                        for v in f_band: vg_band.extend(v)
-                                       me.addVertGroup('side.band')  ; me.assignVertsToGroup('side.band',  list(set(vg_band)), 1.0, replace)
+                                       me.addVertGroup('side.band')  ; me.assignVertsToGroup('side.band',  vg_band, 1.0, replace)
+
                                        if settings.var['fill_on']:
                                                for v in f_top: vg_top.extend(v)
                                                for v in f_bottom: vg_bottom.extend(v)
-                                               me.addVertGroup('side.top')   ; me.assignVertsToGroup('side.top',   list(set(vg_top)), 1.0, replace)
-                                               me.addVertGroup('side.bottom'); me.assignVertsToGroup('side.bottom',list(set(vg_bottom)), 1.0, replace)
+                                               me.addVertGroup('side.top')   ; me.assignVertsToGroup('side.top',   vg_top, 1.0, replace)
+                                               me.addVertGroup('side.bottom'); me.assignVertsToGroup('side.bottom',vg_bottom, 1.0, replace)
 
                        else: # if thic == 0
                                if settings.var['fill_on']:
@@ -2963,16 +2836,16 @@ class Arc:  #-----------------------------------------------------------------
                                        # each MeshSide becomes vertexGroup for easier material assignment ---------------------
                                        if settings.var['vGroup_on'] and not M_OBJ:
                                                # each MeshSide becomes vertexGroup for easier material assignment ---------------------
-                                               replace = Blender.Mesh.AssignModes.REPLACE  #or .AssignModes.ADD
+                                               replace = Mesh.AssignModes.REPLACE  #or .AssignModes.ADD
                                                vg_left, vg_right, vg_top, vg_bottom = [], [], [], []
                                                for v in f_left: vg_left.extend(v)
                                                for v in f_right: vg_right.extend(v)
                                                for v in f_top: vg_top.extend(v)
                                                for v in f_bottom: vg_bottom.extend(v)
-                                               me.addVertGroup('side.left')  ; me.assignVertsToGroup('side.left',  list(set(vg_left)), 1.0, replace)
-                                               me.addVertGroup('side.right') ; me.assignVertsToGroup('side.right', list(set(vg_right)), 1.0, replace)
-                                               me.addVertGroup('side.top')   ; me.assignVertsToGroup('side.top',   list(set(vg_top)), 1.0, replace)
-                                               me.addVertGroup('side.bottom'); me.assignVertsToGroup('side.bottom',list(set(vg_bottom)), 1.0, replace)
+                                               me.addVertGroup('side.left')  ; me.assignVertsToGroup('side.left',  vg_left, 1.0, replace)
+                                               me.addVertGroup('side.right') ; me.assignVertsToGroup('side.right', vg_right, 1.0, replace)
+                                               me.addVertGroup('side.top')   ; me.assignVertsToGroup('side.top',   vg_top, 1.0, replace)
+                                               me.addVertGroup('side.bottom'); me.assignVertsToGroup('side.bottom',vg_bottom, 1.0, replace)
                                                me.addVertGroup('side.start'); me.assignVertsToGroup('side.start', f_start[0], 1.0, replace)
                                                me.addVertGroup('side.end')  ; me.assignVertsToGroup('side.end',   f_end[0],   1.0, replace)
                                        
@@ -3224,8 +3097,6 @@ class Insert:  #----------------------------------------------------------------
 
                                if a_data.key == 'SCENE': # define set of lights as blender group
                                        scene_lights = 1
-                               elif False: # define set of lights as blender group
-                                       scene_lights = 1
                                return
                elif name == 'ave_global':
                        if settings.var['lights_on']:  #if lights support activated
@@ -3386,35 +3257,12 @@ class Ellipse:  #---------------------------------------------------------------
                obname = obname[:MAX_NAMELENGTH]
 
                center = self.loc
-               if True:
-                       start = degrees(self.start_angle)
-                       end = degrees(self.end_angle)
-                       if abs(end - 360.0) < 0.00001: end = 360.0
-                       ellipse_closed = False
-                       if end - start == 360.0: ellipse_closed = True
+               start = degrees(self.start_angle)
+               end = degrees(self.end_angle)
+               if abs(end - 360.0) < 0.00001: end = 360.0
+               ellipse_closed = False
+               if end - start == 360.0: ellipse_closed = True
        
-               else: # bug in AutoCAD_2002 dxf-exporter into r12 for ELLIPSE->POLYLINE_ARC
-                       #print 'deb:calcEllipse---------:\n start=%s\n   end=%s' %(self.start_angle, self.end_angle)  #---------
-                       if self.start_angle > pi+pi: self.start_angle %= pi+pi
-                       if self.end_angle > pi+pi: self.end_angle %= pi+pi
-                       if abs(self.end_angle - pi - pi) < 0.00001: self.end_angle = pi + pi
-                       ellipse_closed = False
-                       if abs(self.end_angle - self.start_angle) == pi + pi: ellipse_closed = True
-                       test = self.start_angle % pi
-                       if  test < 0.001 or pi - test < 0.001: start = self.start_angle
-                       else:
-                               start = atan(tan(self.start_angle) * self.ratio)
-                               if start < 0.0: start += pi
-                               if self.start_angle > pi: start += pi
-                       test = self.end_angle % pi
-                       if test < 0.001 or pi - test < 0.001: end = self.end_angle
-                       else:
-                               end = atan(tan(self.end_angle) * self.ratio)
-                               if end < 0.0: end += pi
-                               if self.end_angle > pi: end += pi
-                       start = degrees(start)
-                       end = degrees(end)
-
                # rotation = Angle between major and WORLDX
                # doesnt work, couse produces always positive value: rotation = Mathutils.AngleBetweenVecs(major, WORLDX)
                if self.major[0] == 0:
@@ -3487,8 +3335,6 @@ class Ellipse:  #---------------------------------------------------------------
 
                        verts = calcArc(None, radius, start, end, arc_res, False)
                        #verts = [list(point) for point in verts]
-                       if False: #--todo--: if ellipse_closed:
-                               verts = verts[:-1] #list without last point/edge (cause closed curve)
                        len1 = len(verts)
                        #print 'deb:len1:', len1  #-----------------------
                        if width != 0:
@@ -3532,16 +3378,16 @@ class Ellipse:  #---------------------------------------------------------------
                                                        me.faces[i].smooth = True
                                        if settings.var['vGroup_on'] and not M_OBJ:
                                                # each MeshSide becomes vertexGroup for easier material assignment ---------------------
-                                               replace = Blender.Mesh.AssignModes.REPLACE  #or .AssignModes.ADD
+                                               replace = Mesh.AssignModes.REPLACE  #or .AssignModes.ADD
                                                vg_left, vg_right, vg_top, vg_bottom = [], [], [], []
                                                for v in f_left: vg_left.extend(v)
                                                for v in f_right: vg_right.extend(v)
                                                for v in f_top: vg_top.extend(v)
                                                for v in f_bottom: vg_bottom.extend(v)
-                                               me.addVertGroup('side.left')  ; me.assignVertsToGroup('side.left',  list(set(vg_left)), 1.0, replace)
-                                               me.addVertGroup('side.right') ; me.assignVertsToGroup('side.right', list(set(vg_right)), 1.0, replace)
-                                               me.addVertGroup('side.top')   ; me.assignVertsToGroup('side.top',   list(set(vg_top)), 1.0, replace)
-                                               me.addVertGroup('side.bottom'); me.assignVertsToGroup('side.bottom',list(set(vg_bottom)), 1.0, replace)
+                                               me.addVertGroup('side.left')  ; me.assignVertsToGroup('side.left',  vg_left, 1.0, replace)
+                                               me.addVertGroup('side.right') ; me.assignVertsToGroup('side.right', vg_right, 1.0, replace)
+                                               me.addVertGroup('side.top')   ; me.assignVertsToGroup('side.top',   vg_top, 1.0, replace)
+                                               me.addVertGroup('side.bottom'); me.assignVertsToGroup('side.bottom',vg_bottom, 1.0, replace)
                                                me.addVertGroup('side.start'); me.assignVertsToGroup('side.start', f_start[0], 1.0, replace)
                                                me.addVertGroup('side.end')  ; me.assignVertsToGroup('side.end',   f_end[0],   1.0, replace)
                                        
@@ -3685,7 +3531,7 @@ class Face:  #-----------------------------------------------------------------
                        ob.link(me) # link mesh to that object
                        vG_name = 'color_%s' %self.color_index
                        if edges: faces = edges
-                       replace = Blender.Mesh.AssignModes.ADD  #or .AssignModes.REPLACE or ADD
+                       replace = Mesh.AssignModes.ADD  #or .AssignModes.REPLACE or ADD
                        try:
                                me.assignVertsToGroup(vG_name,  faces[0], 1.0, replace)
                                #print 'deb: existed vGroup:', vG_name #---------------------
@@ -4190,10 +4036,8 @@ class Settings:  #--------------------------------------------------------------
                """Wraps the built-in print command in a optimization check.
                """
                if self.var['optimization'] <= self.MID:
-                       if newline:
-                               print text
-                       else:
-                               print text,
+                       if newline: print text
+                       else: print text,
 
 
        def redraw(self):
@@ -4235,9 +4079,9 @@ def       analyzeDXF(dxfFile): #---------------------------------------
        """
        Window.WaitCursor(True)   # Let the user know we are thinking
        print 'reading DXF file: %s.' % dxfFile
-       time1 = Blender.sys.time()  #time marker1
+       time1 = sys.time()  #time marker1
        drawing = readDXF(dxfFile, objectify)
-       print 'finish reading in %.4f sec.' % (Blender.sys.time()-time1)
+       print 'finish reading in %.4f sec.' % (sys.time()-time1)
 
        # First sort out all the section_items
        sections = dict([(item.name, item) for item in drawing.data])
@@ -4353,8 +4197,9 @@ def       analyzeDXF(dxfFile): #---------------------------------------
 
                for item2 in drawing.entities.data:
                        if type(item2) != list and item2.type == 'insert':
-                               if not layersmap or (layersmap and not layersmap[item2.layer][1]): #if insert_layer is not frozen
-                                       blocksmap[item2.name][0] = True # marked as world used BLOCK
+                               if item2.name in blocksmap.keys():
+                                       if not layersmap or (layersmap and not layersmap[item2.layer][1]): #if insert_layer is not frozen
+                                               blocksmap[item2.name][0] = True # marked as world used BLOCK
 
                key_list = blocksmap.keys()
                key_list.reverse()
@@ -4449,10 +4294,45 @@ def main(dxfFile):  #---------------#############################-----------
                if dxfFile.lower().endswith('.dxf') and sys.exists(dxfFile):
                        Window.WaitCursor(True)   # Let the user know we are thinking
                        print 'reading file: %s.' % dxfFile
-                       time1 = Blender.sys.time()  #time marker1
+                       time1 = sys.time()  #time marker1
                        drawing = readDXF(dxfFile, objectify)
-                       print 'reading finished in %.4f sec.' % (Blender.sys.time()-time1)
+                       print 'reading finished in %.4f sec.' % (sys.time()-time1)
                        Window.WaitCursor(False)
+               elif dxfFile.lower().endswith('.dwg') and sys.exists(dxfFile):
+                       if not extCONV_OK:
+                               Draw.PupMenu(extCONV_TEXT)
+                               Window.WaitCursor(False)
+                               if editmode: Window.EditMode(1) # and put things back how we fond them
+                               return None
+                       else:
+                               Window.WaitCursor(True)   # Let the user know we are thinking
+                               #todo: issue: in DConvertCon.exe the output filename is fixed to dwg_name.dxf
+                               
+                               if 0: # works only for Windows
+                                       dwgTemp = 'temp_01.dwg'
+                                       dxfTemp = 'temp_01.dxf'
+                                       os.system('copy %s %s' %(dxfFile,dwgTemp))
+                               else:
+                                       dwgTemp = dxfFile
+                                       dxfTemp = dxfFile[:-3]+'dxf'
+                               #print 'temp. converting: %s\n              to: %s' %(dxfFile, dxfTemp)
+                               #os.system('%s %s  -acad11 -dxf' %(extCONV_PATH, dxfFile))
+                               os.system('%s %s  -dxf' %(extCONV_PATH, dwgTemp))
+                               #os.system('%s %s  -dxf' %(extCONV_PATH, dxfFile_temp))
+                               if sys.exists(dxfTemp):
+                                       print 'reading file: %s.' % dxfTemp
+                                       time1 = sys.time()  #time marker1
+                                       drawing = readDXF(dxfTemp, objectify)
+                                       #os.remove(dwgTemp)
+                                       os.remove(dxfTemp) # clean up
+                                       print 'reading finished in %.4f sec.' % (sys.time()-time1)
+                                       Window.WaitCursor(False)
+                               else:
+                                       if UI_MODE: Draw.PupMenu('DWG importer:  nothing imported!%t|No valid DXF-representation found!')
+                                       print 'DWG importer:  nothing imported. No valid DXF-representation found.'
+                                       Window.WaitCursor(False)
+                                       if editmode: Window.EditMode(1) # and put things back how we fond them
+                                       return None
                else:
                        if UI_MODE: Draw.PupMenu('DXF importer:  Alert!%t| no valid DXF-file selected!')
                        print "DXF importer: Alert! - no valid DXF-file selected."
@@ -4462,7 +4342,7 @@ def main(dxfFile):  #---------------#############################-----------
 
                # Draw all the know entity types in the current scene
                oblist = []  # a list of all created AND linked objects for final f_globalScale
-               time2 = Blender.sys.time()  #time marker2
+               time2 = sys.time()  #time marker2
 
                Window.WaitCursor(True)   # Let the user know we are thinking
                settings.write("\n\nDrawing entities...")
@@ -4489,7 +4369,7 @@ def main(dxfFile):  #---------------#############################-----------
                #SCENE.objects.selected = SCENE.objects   #select all objects in current scene            
                Blender.Redraw()
 
-               time_text = Blender.sys.time() - time2
+               time_text = sys.time() - time2
                Window.WaitCursor(False)
                if settings.var['paper_space_on']: space = 'from paper space'
                else: space = 'from model space'
@@ -4738,7 +4618,7 @@ def drawer(_type, entities, settings, block_def):  #----------------------------
                activObjectLayer = ''
                activObjectName = ''
 
-               message = "Drawing dxf\'%ss\'..." %_type
+               message = "Drawing dxf \'%ss\'..." %_type
                cur_COUNTER += len_temp - len(entities)
                settings.write(message, False)
                settings.progress(cur_COUNTER, message)
@@ -4764,10 +4644,12 @@ def drawer(_type, entities, settings, block_def):  #----------------------------
                                group = getGroup('l:%s' % layernamesmap[entity.layer])
 
                        if _type == 'insert':   #---- INSERT and MINSERT=array --------------------
-                               if not settings.var['block_nn'] and entity.name.startswith('*X'):   #---- support for noname BLOCKs
-                                       #print 'deb:drawer entity.name:', entity.name #------------
-                                       continue
-                               elif settings.var['blockFilter_on'] and not settings.accepted_block(entity.name):
+                               if not settings.var['block_nn']:  #----turn off support for noname BLOCKs
+                                       prefix = entity.name[:2]
+                                       if prefix in ('*X', '*U', '*D'):
+                                               #print 'deb:drawer entity.name:', entity.name #------------
+                                               continue
+                               if settings.var['blockFilter_on'] and not settings.accepted_block(entity.name):
                                        continue
 
                                #print 'deb:insert entity.loc:', entity.loc #----------------
@@ -5241,7 +5123,7 @@ def drawCurveArc(self):  #---- only for ELLIPSE --------------------------------
 
 
 # GUI STUFF -----#################################################-----------------
-from Blender.BGL import *
+from Blender.BGL import glColor3f, glRecti, glClear, glRasterPos2d
 
 EVENT_NONE = 1
 EVENT_START = 2
@@ -5746,7 +5628,7 @@ def draw_UI():  #---------------------------------------------------------------
 
        y += 30
        colorbox(x, y+20, x+menu_w+menu_margin*2, menu_margin)
-       Draw.Label("DXF-Importer  v" + __version__, but0c, y, menu_w, 20)
+       Draw.Label("DXF/DWG-Importer v" + __version__, but0c, y, menu_w, 20)
 
        if config_UI.val:
                b0, b0_ = but0c, but_0c + butt_margin
@@ -6022,9 +5904,9 @@ def draw_UI():  #---------------------------------------------------------------
 
        #y -= 10
        Draw.BeginAlign()
-       Draw.PushButton('DXFfile >', EVENT_CHOOSE_DXF, but0c, y, but_0c, 20, 'Select DXF-file from project directory')
-       dxfFileName = Draw.String(' :', EVENT_NONE, but1c, y, but_1c+but_2c+but_3c-20, 20, dxfFileName.val, FILENAME_MAX, "type the name of DXF-file or type *.dxf for multi-import")
-       Draw.PushButton('*.*', EVENT_DXF_DIR, but3c+but_3c-20, y, 20, 20, 'import all dxf files from this directory')
+       Draw.PushButton('DXFfile >', EVENT_CHOOSE_DXF, but0c, y, but_0c, 20, 'Select DXF/DWG-file for import')
+       dxfFileName = Draw.String(' :', EVENT_NONE, but1c, y, but_1c+but_2c+but_3c-20, 20, dxfFileName.val, FILENAME_MAX, "type the name of DXF/DWG-file or type *.dxf/*.dwg for multiple files")
+       Draw.PushButton('*.*', EVENT_DXF_DIR, but3c+but_3c-20, y, 20, 20, 'set filter for import all files from this directory')
        Draw.EndAlign()
 
        y -= 30
@@ -6071,8 +5953,9 @@ def colorbox(x,y,xright,bottom):
 
 def dxf_callback(input_filename):
        global dxfFileName
-       dxfFileName.val=input_filename
-#      dirname == Blender.sys.dirname(Blender.Get('filename'))
+       if input_filename.lower()[-3:] in ('dwg','dxf'):
+               dxfFileName.val=input_filename
+#      dirname == sys.dirname(Blender.Get('filename'))
 #      update_RegistryKey('DirName', dirname)
 #      update_RegistryKey('dxfFileName', input_filename)
        
@@ -6082,17 +5965,17 @@ def ini_callback(input_filename):
 
 def event(evt, val):
        if evt in (Draw.QKEY, Draw.ESCKEY) and not val:
-               Blender.Draw.Exit()
+               Draw.Exit()
 
 def bevent(evt):
 #   global EVENT_NONE,EVENT_LOAD_DXF,EVENT_LOAD_INI,EVENT_SAVE_INI,EVENT_EXIT
        global config_UI, user_preset
-       global GUI_A
+       global GUI_A, UI_MODE
 
        ######### Manages GUI events
        if (evt==EVENT_EXIT):
-               Blender.Draw.Exit()
-               print 'DXF-Importer  *** exit ***'   #---------------------
+               Draw.Exit()
+               print 'DXF/DWG-Importer  *** exit ***'   #---------------------
        elif (evt==EVENT_CHOOSE_INI):
                Window.FileSelector(ini_callback, "INI-file Selection", '*.ini')
        elif (evt==EVENT_REDRAW):
@@ -6149,13 +6032,14 @@ http://wiki.blender.org/index.php?title=Scripts/Manual/Import/DXF-3D')
                Draw.Redraw()
        elif (evt==EVENT_DXF_DIR):
                dxfFile = dxfFileName.val
+               dxfFileExt = '*'+dxfFile.lower()[-4:]  #can be .dxf or .dwg
                dxfPathName = ''
                if '/' in dxfFile:
                        dxfPathName = '/'.join(dxfFile.split('/')[:-1]) + '/'
                elif '\\' in dxfFile:
                        dxfPathName = '\\'.join(dxfFile.split('\\')[:-1]) + '\\'
-               dxfFileName.val = dxfPathName + '*.dxf'
-#              dirname == Blender.sys.dirname(Blender.Get('filename'))
+               dxfFileName.val = dxfPathName + dxfFileExt 
+#              dirname == sys.dirname(Blender.Get('filename'))
 #              update_RegistryKey('DirName', dirname)
 #              update_RegistryKey('dxfFileName', dxfFileName.val)
                GUI_A['newScene_on'].val = 1
@@ -6163,45 +6047,55 @@ http://wiki.blender.org/index.php?title=Scripts/Manual/Import/DXF-3D')
        elif (evt==EVENT_CHOOSE_DXF):
                filename = '' # '*.dxf'
                if dxfFileName.val:     filename = dxfFileName.val
-               Window.FileSelector(dxf_callback, "DXF-file Selection", filename)
+               Window.FileSelector(dxf_callback, "DXF/DWG-file Selection", filename)
        elif (evt==EVENT_START):
                dxfFile = dxfFileName.val
                #print 'deb: dxfFile file: ', dxfFile #----------------------
                if E_M: dxfFileName.val, dxfFile = e_mode(dxfFile) #evaluation mode
                update_RegistryKey('dxfFileName', dxfFileName.val)
                if dxfFile.lower().endswith('*.dxf'):
-                       if Draw.PupMenu('DXF importer:  OK?|will import all DXF-files from:|%s' % dxfFile) == 1:
-                               global UI_MODE
+                       if Draw.PupMenu('DXF importer will import all DXF-files from:|%s|OK?' % dxfFile) != -1:
                                UI_MODE = False
-                               multi_import(dxfFile[:-5])  # cut last 5 characters '*.dxf'
+                               multi_import(dxfFile)
+                               UI_MODE = True
                                Draw.Redraw()
-                               #Draw.Exit()
-                       else:
+
+               elif dxfFile.lower().endswith('*.dwg'):
+                       if not extCONV_OK: Draw.PupMenu(extCONV_TEXT)
+                       elif Draw.PupMenu('DWG importer will import all DWG-files from:|%s|OK?' % dxfFile) != -1:
+                       #elif Draw.PupMenu('DWG importer will import all DWG-files from:|%s|Caution! overwrites existing DXF-files!| OK?' % dxfFile) != -1:
+                               UI_MODE = False
+                               multi_import(dxfFile)
+                               UI_MODE = True
                                Draw.Redraw()
-               elif dxfFile.lower().endswith('.dxf') and sys.exists(dxfFile):
-                       print '\nStandard Mode: active'
-                       if GUI_A['newScene_on'].val:
-                               _dxf_file = dxfFile.split('/')[-1].split('\\')[-1]
-                               _dxf_file = _dxf_file[:-4]  # cut last char:'.dxf'
-                               _dxf_file = _dxf_file[:MAX_NAMELENGTH]  #? [-MAX_NAMELENGTH:])
-                               global SCENE
-                               SCENE = Blender.Scene.New(_dxf_file)
-                               SCENE.makeCurrent()
-                               Blender.Redraw()
-                               #or so? Blender.Scene.makeCurrent(_dxf_file)
-                               #sce = bpy.data.scenes.new(_dxf_file)
-                               #bpy.data.scenes.active = sce
+                               
+               elif sys.exists(dxfFile) and dxfFile.lower()[-4:] in ('.dxf','.dwg'):
+                       if dxfFile.lower().endswith('.dwg') and (not extCONV_OK):
+                               Draw.PupMenu(extCONV_TEXT)
                        else:
-                               SCENE = Blender.Scene.GetCurrent()
-                               SCENE.objects.selected = [] # deselect all
-                       main(dxfFile)
-                       #SCENE.objects.selected = SCENE.objects          
-                       #Window.RedrawAll()
-                       #Blender.Redraw()
-                       #Draw.Redraw()
+                               #print '\nStandard Mode: active'
+                               if GUI_A['newScene_on'].val:
+                                       _dxf_file = dxfFile.split('/')[-1].split('\\')[-1]
+                                       _dxf_file = _dxf_file[:-4]  # cut last char:'.dxf'
+                                       _dxf_file = _dxf_file[:MAX_NAMELENGTH]  #? [-MAX_NAMELENGTH:])
+                                       global SCENE
+                                       SCENE = Blender.Scene.New(_dxf_file)
+                                       SCENE.makeCurrent()
+                                       Blender.Redraw()
+                                       #or so? Blender.Scene.makeCurrent(_dxf_file)
+                                       #sce = bpy.data.scenes.new(_dxf_file)
+                                       #bpy.data.scenes.active = sce
+                               else:
+                                       SCENE = Blender.Scene.GetCurrent()
+                                       SCENE.objects.selected = [] # deselect all
+                               main(dxfFile)
+                               #SCENE.objects.selected = SCENE.objects          
+                               #Window.RedrawAll()
+                               #Blender.Redraw()
+                               #Draw.Redraw()
                else:
-                       Draw.PupMenu('DXF importer:  Alert!%t|no valid DXF-file selected!')
-                       print "DXF importer: error, no valid DXF-file selected! try again"
+                       Draw.PupMenu('DXF importer: nothing imported!%t|no valid DXF-file selected!')
+                       print "DXF importer: nothing imported, no valid DXF-file selected! try again"
                        Draw.Redraw()
 
 
@@ -6212,20 +6106,25 @@ def multi_import(DIR):
        
        """
        global SCENE
-       batchTIME = Blender.sys.time()
+       batchTIME = sys.time()
        #if #DIR == "": DIR = os.path.curdir
-       if DIR == "": DIR = Blender.sys.dirname(Blender.Get('filename'))
-       print 'Multifiles Import from %s' %DIR
+       if DIR == "":
+               DIR = sys.dirname(Blender.Get('filename'))
+               EXT = '.dxf'
+       else:
+               EXT = DIR[-4:]  # get last 4 characters '.dxf'
+               DIR = DIR[:-5]  # cut last 5 characters '*.dxf'
+       print 'importing multiple %s files from %s' %(EXT,DIR)
        files = \
-               [sys.join(DIR, f) for f in os.listdir(DIR) if f.lower().endswith('.dxf')] 
+               [sys.join(DIR, f) for f in os.listdir(DIR) if f.lower().endswith(EXT)] 
        if not files:
-               print '...None DXF-files found. Abort!'
+               print '...None %s-files found. Abort!' %EXT
                return
        
        i = 0
        for dxfFile in files:
                i += 1
-               print '\nDXF-file', i, 'of', len(files) #,'\nImporting', dxfFile
+               print '\n%s-file' %EXT, i, 'of', len(files) #,'\nImporting', dxfFile
                if GUI_A['newScene_on'].val:
                        _dxf_file = dxfFile.split('/')[-1].split('\\')[-1]
                        _dxf_file = _dxf_file[:-4]  # cut last char:'.dxf'
@@ -6241,13 +6140,11 @@ def multi_import(DIR):
                main(dxfFile)
                #Blender.Redraw()
 
-       print 'TOTAL TIME: %.6f' % (Blender.sys.time() - batchTIME)
+       print 'TOTAL TIME: %.6f' % (sys.time() - batchTIME)
        print '\a\r', # beep when done
+       Draw.PupMenu('DXF importer:     Done!|finished in %.4f sec.' % (sys.time() - batchTIME))
 
 
-
-UI_MODE = True
-
 if __name__ == "__main__":
        UI_MODE = True
        # recall last used DXF-file and INI-file names
@@ -6255,7 +6152,7 @@ if __name__ == "__main__":
        #print 'deb:start dxffilename:', dxffilename #----------------
        if dxffilename: dxfFileName.val = dxffilename
        else:
-               dirname = Blender.sys.dirname(Blender.Get('filename'))
+               dirname = sys.dirname(Blender.Get('filename'))
                #print 'deb:start dirname:', dirname #----------------
                dxfFileName.val = sys.join(dirname, '')
        inifilename = check_RegistryKey('iniFileName')
@@ -6268,7 +6165,7 @@ if __name__ == "__main__":
 if 1:
        # DEBUG ONLY
        UI_MODE = False
-       TIME= Blender.sys.time()
+       TIME= sys.time()
        #DIR = '/dxf_r12_testfiles/'
        DIR = '/metavr/'
        import os
@@ -6297,5 +6194,5 @@ if 1:
                        dxfFileName.val = _dxf
                        main(_dxf)
 
-       print 'TOTAL TIME: %.6f' % (Blender.sys.time() - TIME)
+       print 'TOTAL TIME: %.6f' % (sys.time() - TIME)
 """
\ No newline at end of file