0029993: Visualization - AIS_TextLabel computes selection primitive only for attachme...
[occt.git] / src / ViewerTest / ViewerTest_ObjectCommands.cxx
index a83f43d..3db6e67 100644 (file)
 
 #include <ViewerTest.hxx>
 
+#include <AIS_PlaneTrihedron.hxx>
+
 #include <Quantity_NameOfColor.hxx>
 #include <Draw_Interpretor.hxx>
 #include <Draw.hxx>
 #include <Draw_Appli.hxx>
 #include <DBRep.hxx>
+#include <DBRep_DrawableShape.hxx>
 
 #include <Font_BRepFont.hxx>
 #include <Font_BRepTextBuilder.hxx>
 #include <Font_FontMgr.hxx>
+#include <Message.hxx>
+#include <NCollection_List.hxx>
+
 #include <OSD_Chronometer.hxx>
 #include <TCollection_AsciiString.hxx>
 #include <V3d_Viewer.hxx>
@@ -62,6 +68,7 @@
 #include <Draw_Window.hxx>
 #include <AIS_ListIteratorOfListOfInteractive.hxx>
 #include <AIS_ListOfInteractive.hxx>
+#include <AIS_ColoredShape.hxx>
 #include <AIS_DisplayMode.hxx>
 #include <AIS_Shape.hxx>
 
 #include <AIS_Trihedron.hxx>
 #include <AIS_Axis.hxx>
 #include <gp_Trsf.hxx>
+#include <gp_Quaternion.hxx>
 #include <TopLoc_Location.hxx>
 
 #include <HLRAlgo_Projector.hxx>
+#include <HLRBRep_Algo.hxx>
 #include <HLRBRep_PolyAlgo.hxx>
 #include <HLRBRep_PolyHLRToShape.hxx>
+#include <HLRBRep_HLRToShape.hxx>
 #include <Aspect_Window.hxx>
 
 #include <Graphic3d_ArrayOfPoints.hxx>
 #include <Graphic3d_ArrayOfQuadrangles.hxx>
 #include <Graphic3d_ArrayOfQuadrangleStrips.hxx>
 #include <Graphic3d_ArrayOfPolygons.hxx>
+#include <Graphic3d_AttribBuffer.hxx>
 #include <Graphic3d_AspectMarker3d.hxx>
 #include <Graphic3d_Group.hxx>
 #include <Standard_Real.hxx>
 #include <BRepBuilderAPI_MakeWire.hxx>
 #include <Geom_Circle.hxx>
 #include <GC_MakeCircle.hxx>
-#include <Prs3d_Presentation.hxx>
 #include <Select3D_SensitiveCircle.hxx>
 #include <SelectMgr_EntityOwner.hxx>
 #include <SelectMgr_Selection.hxx>
 #include <TColStd_ListOfInteger.hxx>
 #include <TColStd_ListIteratorOfListOfInteger.hxx>
 
-#include <Select3D_SensitiveTriangle.hxx>
-#include <Select3D_SensitiveCurve.hxx>
+#include <Select3D_SensitiveSegment.hxx>
+#include <Select3D_SensitivePrimitiveArray.hxx>
 #include <Select3D_SensitivePoint.hxx>
 #include <BRepAdaptor_Curve.hxx>
 #include <StdPrs_Curve.hxx>
 #include <BRepExtrema_ExtPC.hxx>
 #include <BRepExtrema_ExtPF.hxx>
 
+#include <Prs3d_Arrow.hxx>
+#include <Prs3d_ArrowAspect.hxx>
+#include <Prs3d_DatumAttribute.hxx>
+#include <Prs3d_DatumAspect.hxx>
 #include <Prs3d_Drawer.hxx>
 #include <Prs3d_VertexDrawMode.hxx>
 #include <Prs3d_LineAspect.hxx>
 #include <Prs3d_PointAspect.hxx>
+#include <Prs3d_Presentation.hxx>
 #include <Prs3d_TextAspect.hxx>
 
 #include <Image_AlienPixMap.hxx>
 #include <TColStd_HArray1OfAsciiString.hxx>
-
-#ifdef _WIN32
-# define _CRT_SECURE_NO_DEPRECATE
-# pragma warning (disable:4996)
-#endif
+#include <TColStd_HSequenceOfAsciiString.hxx>
 
 extern ViewerTest_DoubleMapOfInteractiveAndName& GetMapOfAIS();
 extern Standard_Boolean VDisplayAISObject (const TCollection_AsciiString& theName,
                                            const Handle(AIS_InteractiveObject)& theAISObj,
                                            Standard_Boolean theReplaceIfExists = Standard_True);
-extern int ViewerMainLoop(Standard_Integer argc, const char** argv);
 extern Handle(AIS_InteractiveContext)& TheAISContext();
 
+namespace
+{
+  static bool convertToColor (const Handle(TColStd_HSequenceOfAsciiString)& theColorValues,
+                              Quantity_Color& theColor)
+  {
+    const char* anArgs[3] =
+    {
+      theColorValues->Size() >= 1 ? theColorValues->Value (1).ToCString() : "",
+      theColorValues->Size() >= 2 ? theColorValues->Value (2).ToCString() : "",
+      theColorValues->Size() >= 3 ? theColorValues->Value (3).ToCString() : ""
+    };
+    return ViewerTest::ParseColor (theColorValues->Size(), anArgs, theColor) != 0;
+  }
+
+  static bool convertToDatumPart (const TCollection_AsciiString& theValue,
+                                  Prs3d_DatumParts& theDatumPart)
+  {
+    TCollection_AsciiString aValue = theValue;
+    aValue.LowerCase();
+    if      (aValue == "origin")  theDatumPart = Prs3d_DP_Origin;
+    else if (aValue == "xaxis")   theDatumPart = Prs3d_DP_XAxis;
+    else if (aValue == "yaxis")   theDatumPart = Prs3d_DP_YAxis;
+    else if (aValue == "zaxis")   theDatumPart = Prs3d_DP_ZAxis;
+    else if (aValue == "xarrow")  theDatumPart = Prs3d_DP_XArrow;
+    else if (aValue == "yarrow")  theDatumPart = Prs3d_DP_YArrow;
+    else if (aValue == "zarrow")  theDatumPart = Prs3d_DP_ZArrow;
+    else if (aValue == "xoyaxis") theDatumPart = Prs3d_DP_XOYAxis;
+    else if (aValue == "yozaxis") theDatumPart = Prs3d_DP_YOZAxis;
+    else if (aValue == "xozaxis") theDatumPart = Prs3d_DP_XOZAxis;
+    else if (aValue == "whole")   theDatumPart = Prs3d_DP_None;
+    else
+    {
+      return false;
+    }
+    return true;
+  }
+
+  static void convertToDatumParts (const TCollection_AsciiString& theValue,
+                                   NCollection_List<Prs3d_DatumParts>& theParts)
+  {
+    TCollection_AsciiString aValue = theValue;
+    const Standard_Integer aSplitPos = theValue.Search ("|");
+    Prs3d_DatumParts aPart = Prs3d_DP_None;
+    if (aSplitPos > 0)
+    {
+      convertToDatumParts (theValue.SubString (aSplitPos + 1, theValue.Length()), theParts);
+      if (aSplitPos == 1) // first symbol
+      {
+        return;
+      }
+      aValue = theValue.SubString (1, aSplitPos - 1);
+    }
+    if (convertToDatumPart (aValue, aPart))
+    {
+      theParts.Append (aPart);
+    }
+  }
+
+  static bool convertToDatumAttribute (const TCollection_AsciiString& theValue,
+                                       Prs3d_DatumAttribute& theAttribute)
+  {
+    TCollection_AsciiString aValue = theValue;
+    aValue.LowerCase();
+    if      (aValue == "xaxislength")       theAttribute = Prs3d_DA_XAxisLength;
+    else if (aValue == "yaxislength")       theAttribute = Prs3d_DA_YAxisLength;
+    else if (aValue == "zaxislength")       theAttribute = Prs3d_DA_ZAxisLength;
+    else if (aValue == "tuberadiuspercent") theAttribute = Prs3d_DP_ShadingTubeRadiusPercent;
+    else if (aValue == "coneradiuspercent") theAttribute = Prs3d_DP_ShadingConeRadiusPercent;
+    else if (aValue == "conelengthpercent") theAttribute = Prs3d_DP_ShadingConeLengthPercent;
+    else if (aValue == "originradiuspercent") theAttribute = Prs3d_DP_ShadingOriginRadiusPercent;
+    else if (aValue == "shadingnumberoffacettes") theAttribute = Prs3d_DP_ShadingNumberOfFacettes;
+    else
+      return false;
+    return true;
+  }
+
+  static void convertToDatumAttributes (const TCollection_AsciiString& theValue,
+                                        NCollection_List<Prs3d_DatumAttribute>& theAttributes)
+  {
+    TCollection_AsciiString aValue = theValue;
+    const Standard_Integer aSplitPos = theValue.Search ("|");
+    Prs3d_DatumAttribute anAttribute = Prs3d_DA_XAxisLength;
+    if (aSplitPos > 0)
+    {
+      convertToDatumAttributes (theValue.SubString (aSplitPos + 1, theValue.Length()), theAttributes);
+      if (aSplitPos == 1) // first symbol
+      {
+        return;
+      }
+      aValue = theValue.SubString (1, aSplitPos - 1);
+    }
+    if (convertToDatumAttribute (aValue, anAttribute))
+    {
+      theAttributes.Append (anAttribute);
+    }
+  }
+
+  static bool convertToDatumAxes (const TCollection_AsciiString& theValue,
+                                  Prs3d_DatumAxes& theDatumAxes)
+  {
+    TCollection_AsciiString aValue = theValue;
+    aValue.LowerCase();
+    if      (aValue == "x")   theDatumAxes = Prs3d_DA_XAxis;
+    else if (aValue == "y")   theDatumAxes = Prs3d_DA_YAxis;
+    else if (aValue == "z")   theDatumAxes = Prs3d_DA_ZAxis;
+    else if (aValue == "xy")  theDatumAxes = Prs3d_DA_XYAxis;
+    else if (aValue == "zy")  theDatumAxes = Prs3d_DA_YZAxis;
+    else if (aValue == "xz")  theDatumAxes = Prs3d_DA_XZAxis;
+    else if (aValue == "xyz") theDatumAxes = Prs3d_DA_XYZAxis;
+    else
+    {
+      return false;
+    }
+    return true;
+  }
+
+  static Standard_Boolean setTrihedronParams (Standard_Integer  theArgsNb,
+                                              const char** theArgVec,
+                                              Handle(AIS_Trihedron) theTrihedron)
+  {
+    NCollection_DataMap<TCollection_AsciiString, Handle(TColStd_HSequenceOfAsciiString)> aMapOfArgs;
+    TCollection_AsciiString aParseKey;
+    for (Standard_Integer anArgIt = 1; anArgIt < theArgsNb; ++anArgIt)
+    {
+      TCollection_AsciiString anArg (theArgVec [anArgIt]);
+      if (anArg.Value (1) == '-'
+      && !anArg.IsRealValue())
+      {
+        aParseKey = anArg;
+        aParseKey.Remove (1);
+        aParseKey.LowerCase();
+        std::string aKey = aParseKey.ToCString();
+        aMapOfArgs.Bind (aParseKey, new TColStd_HSequenceOfAsciiString());
+        continue;
+      }
+
+      if (aParseKey.IsEmpty())
+      {
+        continue;
+      }
+
+      aMapOfArgs (aParseKey)->Append (anArg);
+    }
+
+    // Check parameters
+    if ((aMapOfArgs.IsBound ("xaxis") && !aMapOfArgs.IsBound ("zaxis"))
+    || (!aMapOfArgs.IsBound ("xaxis") &&  aMapOfArgs.IsBound ("zaxis")))
+    {
+      Message::SendFail ("Syntax error: -xaxis and -zaxis parameters are to set together");
+      return Standard_False;
+    }
+
+    Handle(TColStd_HSequenceOfAsciiString) aValues;
+    Handle(Geom_Axis2Placement) aComponent = theTrihedron->Component();
+    if (aMapOfArgs.Find ("origin", aValues))
+    {
+      aComponent->SetLocation (gp_Pnt (aValues->Value (1).RealValue(),
+                                       aValues->Value (2).RealValue(),
+                                       aValues->Value (3).RealValue()));
+    }
+    Handle(TColStd_HSequenceOfAsciiString) aXValues, aZValues;
+    if (aMapOfArgs.Find ("xaxis", aXValues) && aMapOfArgs.Find ("zaxis", aZValues))
+    {
+      gp_Dir aXDir (aXValues->Value (1).RealValue(),
+                    aXValues->Value (2).RealValue(),
+                    aXValues->Value (3).RealValue());
+
+      gp_Dir aZDir (aZValues->Value (1).RealValue(),
+                    aZValues->Value (2).RealValue(),
+                    aZValues->Value (3).RealValue());
+
+      if (!aZDir.IsNormal (aXDir, M_PI / 180.0))
+      {
+        Message::SendFail ("Syntax error - parameters 'xaxis' and 'zaxis' are not applied as VectorX is not normal to VectorZ");
+        return Standard_False;
+      }
+
+      aComponent->SetAx2 (gp_Ax2 (aComponent->Location(), aZDir, aXDir));
+    }
+
+    if (aMapOfArgs.Find ("dispmode", aValues))
+    {
+      TCollection_AsciiString aValue (aValues->Value (1));
+      bool isWireframe = true;
+      if (aValue.IsEqual ("sh") || aValue.IsEqual ("shading"))
+        isWireframe = false;
+      theTrihedron->SetDatumDisplayMode (isWireframe ? Prs3d_DM_WireFrame
+                                                     : Prs3d_DM_Shaded);
+    }
+
+    if (aMapOfArgs.Find ("hidelabels", aValues))
+    {
+      Standard_Boolean toHideLabels = Standard_True;
+      if (aValues->Size() == 1)
+      {
+        ViewerTest::ParseOnOff (aValues->First().ToCString(), toHideLabels);
+      }
+      else if (aValues->Size() != 0)
+      {
+        Message::SendFail ("Syntax error: -hidelabels expects parameter 'on' or 'off' after");
+        return Standard_False;
+      }
+
+      if (!theTrihedron->Attributes()->HasOwnDatumAspect())
+      {
+        theTrihedron->Attributes()->SetDatumAspect (new Prs3d_DatumAspect());
+      }
+      theTrihedron->Attributes()->DatumAspect()->SetDrawLabels (!toHideLabels);
+    }
+
+    if (aMapOfArgs.Find ("hidearrows", aValues))
+    {
+      Standard_Boolean toHideArrows = Standard_True;
+      if (aValues->Size() == 1)
+      {
+        ViewerTest::ParseOnOff (aValues->First().ToCString(), toHideArrows);
+      }
+      else if (aValues->Size() != 0)
+      {
+        Message::SendFail ("Syntax error: -hidearrows expects parameter 'on' or 'off' after");
+        return Standard_False;
+      }
+
+      if (!theTrihedron->Attributes()->HasOwnDatumAspect())
+      {
+        theTrihedron->Attributes()->SetDatumAspect (new Prs3d_DatumAspect());
+      }
+      theTrihedron->Attributes()->DatumAspect()->SetDrawArrows (!toHideArrows);
+    }
+
+    if (aMapOfArgs.Find ("color", aValues))
+    {
+      NCollection_List<Prs3d_DatumParts> aParts;
+      if (aValues->Size() < 2)
+      {
+        Message::SendFail ("Syntax error: -color wrong parameters");
+        return Standard_False;
+      }
+
+      convertToDatumParts (aValues->Value(1), aParts);
+      aValues->Remove (1); // datum part is processed
+      Quantity_Color aColor;
+      if (!convertToColor (aValues, aColor))
+      {
+        Message::SendFail ("Syntax error: -color wrong parameters");
+        return Standard_False;
+      }
+
+      for (NCollection_List<Prs3d_DatumParts>::Iterator anIterator (aParts); anIterator.More(); anIterator.Next())
+      {
+        Prs3d_DatumParts aDatumPart = anIterator.Value();
+        if (aDatumPart == Prs3d_DP_None)
+        {
+          theTrihedron->SetColor (aColor);
+        }
+        else
+        {
+          theTrihedron->SetDatumPartColor (aDatumPart, aColor);
+        }
+      }
+    }
+
+    if (aMapOfArgs.Find ("textcolor", aValues))
+    {
+      Quantity_Color aColor;
+      if (!convertToColor (aValues, aColor))
+      {
+        Message::SendFail ("Syntax error: -textcolor wrong parameters");
+        return Standard_False;
+      }
+      theTrihedron->SetTextColor (aColor);
+    }
+
+    if (aMapOfArgs.Find ("arrowcolor", aValues))
+    {
+      Quantity_Color aColor;
+      if (!convertToColor (aValues, aColor))
+      {
+        Message::SendFail ("Syntax error: -arrowcolor wrong parameters");
+        return Standard_False;
+      }
+      theTrihedron->SetArrowColor (aColor);
+    }
+
+    if (aMapOfArgs.Find ("attribute", aValues))
+    {
+      NCollection_List<Prs3d_DatumAttribute> anAttributes;
+      if (aValues->Size() != 2)
+      {
+        Message::SendFail ("Syntax error: -attribute wrong parameters");
+        return Standard_False;
+      }
+
+      convertToDatumAttributes (aValues->Value (1), anAttributes);
+      if (!theTrihedron->Attributes()->HasOwnDatumAspect())
+        theTrihedron->Attributes()->SetDatumAspect(new Prs3d_DatumAspect());
+      for (NCollection_List<Prs3d_DatumAttribute>::Iterator anIterator (anAttributes); anIterator.More(); anIterator.Next())
+      {
+        theTrihedron->Attributes()->DatumAspect()->SetAttribute (anIterator.Value(), aValues->Value (2).RealValue());
+      }
+    }
+
+    if (aMapOfArgs.Find ("priority", aValues))
+    {
+      Prs3d_DatumParts aDatumPart;
+      if (aValues->Size() < 2
+      || !convertToDatumPart (aValues->Value (1), aDatumPart))
+      {
+        Message::SendFail ("Syntax error: -priority wrong parameters");
+        return Standard_False;
+      }
+      theTrihedron->SetSelectionPriority (aDatumPart, aValues->Value (2).IntegerValue());
+    }
+
+    if (aMapOfArgs.Find ("labels", aValues)
+     || aMapOfArgs.Find ("label", aValues))
+    {
+      Prs3d_DatumParts aDatumPart = Prs3d_DP_None;
+      if (aValues->Size() >= 2
+       && convertToDatumPart(aValues->Value(1), aDatumPart)
+       && aDatumPart >= Prs3d_DP_XAxis
+       && aDatumPart <= Prs3d_DP_ZAxis) // labels are set to axes only
+      {
+        theTrihedron->SetLabel (aDatumPart, aValues->Value (2));
+      }
+      else
+      {
+        Message::SendFail ("Syntax error: -labels wrong parameters");
+        return Standard_False;
+      }
+    }
+
+    if (aMapOfArgs.Find ("drawaxes", aValues))
+    {
+      Prs3d_DatumAxes aDatumAxes = Prs3d_DA_XAxis;
+      if (aValues->Size() < 1
+      || !convertToDatumAxes (aValues->Value (1), aDatumAxes))
+      {
+        Message::SendFail ("Syntax error: -drawaxes wrong parameters");
+        return Standard_False;
+      }
+      if (!theTrihedron->Attributes()->HasOwnDatumAspect())
+        theTrihedron->Attributes()->SetDatumAspect(new Prs3d_DatumAspect());
+      theTrihedron->Attributes()->DatumAspect()->SetDrawDatumAxes (aDatumAxes);
+    }
+    return Standard_True;
+  }
+
+  //! Auxiliary function to parse font aspect style argument
+  static Standard_Boolean parseFontStyle (const TCollection_AsciiString& theArg,
+                                          Font_FontAspect&               theAspect)
+  {
+    if (theArg == "regular"
+     || *theArg.ToCString() == 'r')
+    {
+      theAspect = Font_FA_Regular;
+      return Standard_True;
+    }
+    else if (theArg == "bolditalic"
+          || theArg == "bold-italic"
+          || theArg == "italic-bold"
+          || theArg == "italicbold")
+    {
+      theAspect = Font_FA_BoldItalic;
+      return Standard_True;
+    }
+    else if (theArg == "bold"
+          || *theArg.ToCString() == 'b')
+    {
+      theAspect = Font_FA_Bold;
+      return Standard_True;
+    }
+    else if (theArg == "italic"
+          || *theArg.ToCString() == 'i')
+    {
+      theAspect = Font_FA_Italic;
+      return Standard_True;
+    }
+    return Standard_False;
+  }
+
+  //! Auxiliary function to parse font strict level argument
+  static Standard_Integer parseFontStrictLevel (const Standard_Integer theArgNb,
+                                                const char**           theArgVec,
+                                                Font_StrictLevel&      theLevel)
+  {
+    if (theArgNb >= 1)
+    {
+      TCollection_AsciiString anArg (theArgVec[0]);
+      anArg.LowerCase();
+      if (anArg == "any")
+      {
+        theLevel = Font_StrictLevel_Any;
+        return 1;
+      }
+      else if (anArg == "aliases")
+      {
+        theLevel = Font_StrictLevel_Aliases;
+        return 1;
+      }
+      else if (anArg == "strict")
+      {
+        theLevel = Font_StrictLevel_Strict;
+        return 1;
+      }
+    }
+    theLevel = Font_StrictLevel_Strict;
+    return 0;
+  }
+}
 
 //==============================================================================
 //function : Vtrihedron 2d
 //purpose  : Create a plane with a 2D  trihedron from a faceselection
 //Draw arg : vtri2d  name
 //==============================================================================
-#include <AIS_PlaneTrihedron.hxx>
+static int VTrihedron2D (Draw_Interpretor& /*theDI*/,
+                         Standard_Integer  theArgsNum,
+                         const char**      theArgVec)
+{
+  if (theArgsNum != 2)
+  {
+    Message::SendFail() << "Syntax error: wrong number of arguments.";
+    return 1;
+  }
 
+  TopTools_ListOfShape aShapes;
+  ViewerTest::GetSelectedShapes (aShapes);
 
+  if (aShapes.Extent() != 1)
+  {
+    Message::SendFail ("Error: wrong number of selected shapes.");
+    return 1;
+  }
 
-static int VTrihedron2D (Draw_Interpretor& di, Standard_Integer argc, const char** argv)
+  const TopoDS_Shape& aShape = aShapes.First();
 
-{
-  // Verification des arguments
-  if ( argc!=2) {di<<argv[0]<<" error"<<"\n"; return 1;}
+  TopoDS_Face     aFace = TopoDS::Face (aShape);
+  TopExp_Explorer aFaceExp (aFace, TopAbs_EDGE);
+  TopoDS_Edge     anEdge0 = TopoDS::Edge (aFaceExp.Current());
 
-  // Declarations
-  Standard_Integer myCurrentIndex;
-  // Fermeture des contextes
-  TheAISContext()->CloseAllContexts();
-  // Ouverture d'un contexte local et recuperation de son index.
-  TheAISContext()->OpenLocalContext();
-  myCurrentIndex=TheAISContext()->IndexOfCurrentLocal();
-  // On active les modes de selections faces.
-  TheAISContext()->ActivateStandardMode (AIS_Shape::SelectionType(4) );
-  di<<" Select a face ."<<"\n";
-
-  // Boucle d'attente waitpick.
-  Standard_Integer argccc = 5;
-  const char *bufff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-  const char **argvvv = (const char **) bufff;
-  while (ViewerMainLoop( argccc, argvvv) ) { }
-  // fin de la boucle
-
-  TopoDS_Shape ShapeB;
-  for(TheAISContext()->InitSelected() ;TheAISContext()->MoreSelected() ;TheAISContext()->NextSelected() ) {
-    ShapeB = TheAISContext()->SelectedShape();
-  }
-
-  TopoDS_Face  FaceB=TopoDS::Face(ShapeB);
-
-  // Construction du Plane
-  // recuperation des edges des faces.
-  TopExp_Explorer FaceExpB(FaceB,TopAbs_EDGE);
-
-  TopoDS_Edge EdgeB=TopoDS::Edge(FaceExpB.Current() );
-  // declarations
   gp_Pnt A,B,C;
-
-  // si il y a plusieurs edges
-  if (FaceExpB.More() ) {
-    FaceExpB.Next();
-    TopoDS_Edge EdgeC=TopoDS::Edge(FaceExpB.Current() );
-    BRepAdaptor_Curve theCurveB(EdgeB);
-    BRepAdaptor_Curve theCurveC(EdgeC);
-    A=theCurveC.Value(0.1);
-    B=theCurveC.Value(0.9);
-    C=theCurveB.Value(0.5);
+  if (aFaceExp.More())
+  {
+    aFaceExp.Next();
+    TopoDS_Edge anEdge1 = TopoDS::Edge (aFaceExp.Current() );
+    BRepAdaptor_Curve aCurve0 (anEdge0);
+    BRepAdaptor_Curve aCurve1 (anEdge1);
+    A = aCurve1.Value (0.1);
+    B = aCurve1.Value (0.9);
+    C = aCurve0.Value (0.5);
   }
-  else {
-    // FaceB a 1 unique edge courbe
-    BRepAdaptor_Curve theCurveB(EdgeB);
-    A=theCurveB.Value(0.1);
-    B=theCurveB.Value(0.9);
-    C=theCurveB.Value(0.5);
+  else
+  {
+    BRepAdaptor_Curve aCurve0 (anEdge0);
+    A = aCurve0.Value (0.1);
+    B = aCurve0.Value (0.9);
+    C = aCurve0.Value (0.5);
   }
-  // Construction du Geom_Plane
-  GC_MakePlane MkPlane(A,B,C);
-  Handle(Geom_Plane) theGeomPlane=MkPlane.Value();
 
-  // Construction de l'AIS_PlaneTrihedron
-  Handle(AIS_PlaneTrihedron) theAISPlaneTri= new AIS_PlaneTrihedron(theGeomPlane );
+  GC_MakePlane aMkPlane (A,B,C);
 
-  // Fermeture du contexte local.
-  TheAISContext()->CloseLocalContext(myCurrentIndex);
+  Handle(AIS_PlaneTrihedron) anAISPlaneTri = new AIS_PlaneTrihedron (aMkPlane.Value());
+  TCollection_AsciiString aName (theArgVec[1]);
 
-  // on le display & bind
-  TheAISContext()->Display(theAISPlaneTri );
-  GetMapOfAIS().Bind ( theAISPlaneTri ,argv[1]);
+  VDisplayAISObject (aName, anAISPlaneTri);
 
   return 0;
 }
 
-
-
-//==============================================================================
-//function : VTriherdron
-//purpose  : Create a trihedron. If no arguments are set, the default
-//           trihedron (Oxyz) is created.
-//Draw arg : vtrihedron  name  [Xo] [Yo] [Zo] [Zu] [Zv] [Zw] [Xu] [Xv] [Xw]
-//==============================================================================
-
-static int VTrihedron (Draw_Interpretor& theDi,
-                       Standard_Integer  theArgsNb,
-                       const char**      theArgVec)
+//=======================================================================
+//function : VTrihedron
+//purpose  :
+//=======================================================================
+static int VTrihedron (Draw_Interpretor& ,
+                       Standard_Integer theArgsNb,
+                       const char** theArgVec)
 {
-  if (theArgsNb != 2 && theArgsNb != 5 && theArgsNb != 11)
+  if (theArgsNb < 2)
   {
-    theDi << theArgVec[0] << " Syntax error\n";
+    Message::SendFail ("Syntax error: the wrong number of input parameters");
     return 1;
   }
 
-  gp_Pnt anOrigin (0.0, 0.0, 0.0);
-  gp_Dir aDirZ = gp::DZ();
-  gp_Dir aDirX = gp::DX();
-  Standard_Integer anArgIter = 2; // 1st is an IO name
-  if (anArgIter < theArgsNb)
+  TCollection_AsciiString aName (theArgVec[1]);
+  gp_Pln aWorkingPlane;
+  Standard_Boolean toUpdate = Standard_True;
+
+  NCollection_DataMap<TCollection_AsciiString, Standard_Real> aRealParams;
+  NCollection_DataMap<TCollection_AsciiString, TCollection_AsciiString> aStringParams;
+
+  Handle(AIS_Trihedron) aTrihedron;
+  Handle(AIS_InteractiveObject) anObject;
+  if (GetMapOfAIS().Find2 (aName, anObject))
   {
-    anOrigin.SetX (Draw::Atof (theArgVec[anArgIter++]));
-    anOrigin.SetY (Draw::Atof (theArgVec[anArgIter++]));
-    anOrigin.SetZ (Draw::Atof (theArgVec[anArgIter++]));
-    if (anArgIter < theArgsNb)
+    aTrihedron = Handle(AIS_Trihedron)::DownCast (anObject);
+    if (aTrihedron.IsNull())
     {
-      Standard_Real aX = Draw::Atof (theArgVec[anArgIter++]);
-      Standard_Real aY = Draw::Atof (theArgVec[anArgIter++]);
-      Standard_Real aZ = Draw::Atof (theArgVec[anArgIter++]);
-      aDirZ.SetCoord (aX, aY, aZ);
-
-      aX = Draw::Atof (theArgVec[anArgIter++]);
-      aY = Draw::Atof (theArgVec[anArgIter++]);
-      aZ = Draw::Atof (theArgVec[anArgIter++]);
-      aDirX.SetCoord (aX, aY, aZ);
+      Message::SendFail ("Syntax error: no trihedron with this name");
+      return 1;
     }
   }
+  else
+  {
+    Handle(Geom_Axis2Placement) aPlacement = new Geom_Axis2Placement (gp_Pnt (0.0, 0.0, 0.0),
+                                                                      gp::DZ(), gp::DX());
+    aTrihedron = new AIS_Trihedron (aPlacement);
+  }
 
-  if (!aDirZ.IsNormal (aDirX, M_PI / 180.0))
+  if (!setTrihedronParams (theArgsNb, theArgVec, aTrihedron))
   {
-    theDi << theArgVec[0] << " - VectorX is not normal to VectorZ\n";
     return 1;
   }
 
-  Handle(Geom_Axis2Placement) aPlacement = new Geom_Axis2Placement (anOrigin, aDirZ, aDirX);
-  Handle(AIS_Trihedron) aShape = new AIS_Trihedron (aPlacement);
-  VDisplayAISObject (theArgVec[1], aShape);
+  // Redisplay a dimension after parameter changing.
+  if (ViewerTest::GetAISContext()->IsDisplayed (aTrihedron))
+  {
+    ViewerTest::GetAISContext()->Redisplay (aTrihedron, toUpdate);
+  }
+  else
+  {
+    VDisplayAISObject (theArgVec[1], aTrihedron);
+  }
+
   return 0;
 }
 
@@ -304,20 +704,16 @@ static int VSize (Draw_Interpretor& di, Standard_Integer argc, const char** argv
   Standard_Real                value;
   Standard_Boolean             hascol;
 
-  Quantity_NameOfColor         col = Quantity_NOC_BLACK ;
+  Quantity_Color col = Quantity_NOC_BLACK;
 
   // Verification des arguments
-  if ( argc>3 ) {di<<argv[0]<<" Syntaxe error"<<"\n"; return 1;}
+  if ( argc>3 ) {di<<argv[0]<<" Syntaxe error\n"; return 1;}
 
   // Verification du nombre d'arguments
   if (argc==1)      {ThereIsName=Standard_False;value=100;}
   else if (argc==2) {ThereIsName=Standard_False;value=Draw::Atof(argv[1]);}
   else              {ThereIsName=Standard_True;value=Draw::Atof(argv[2]);}
 
-  // On ferme le contexte local pour travailler dans le contexte global
-  if(TheAISContext()->HasOpenedContext())
-    TheAISContext()->CloseLocalContext();
-
   // On set le booleen ThereIsCurrent
   if (TheAISContext() -> NbSelected() > 0) {ThereIsCurrent=Standard_True;}
   else {ThereIsCurrent=Standard_False;}
@@ -335,8 +731,7 @@ static int VSize (Draw_Interpretor& di, Standard_Integer argc, const char** argv
 
     while ( it.More() ) {
 
-      Handle(AIS_InteractiveObject) aShape=
-        Handle(AIS_InteractiveObject)::DownCast(it.Key1());
+      Handle(AIS_InteractiveObject) aShape = it.Key1();
 
       if (!aShape.IsNull() &&  TheAISContext()->IsSelected(aShape) )
       {
@@ -345,13 +740,17 @@ static int VSize (Draw_Interpretor& di, Standard_Integer argc, const char** argv
         // un AIS_Trihedron
         if (aShape->Type()==AIS_KOI_Datum && aShape->Signature()==3) {
 
-          if (aShape->HasColor()) {
-            hascol=Standard_True;
+          if (aShape->HasColor())
+          {
+            hascol = Standard_True;
 
             // On recupere la couleur de aShape
-            col=aShape->Color();}
-
-          else hascol=Standard_False;
+            aShape->Color (col);
+          }
+          else
+          {
+            hascol = Standard_False;
+          }
 
           // On downcast aShape  de AIS_InteractiveObject a AIS_Trihedron
           // pour lui appliquer la methode SetSize()
@@ -392,27 +791,25 @@ static int VSize (Draw_Interpretor& di, Standard_Integer argc, const char** argv
     TCollection_AsciiString name=argv[1];
 
     // on verifie que ce nom correspond bien a une shape
-    Standard_Boolean IsBound= GetMapOfAIS().IsBound2(name);
-
-    if (IsBound) {
-
-      // on recupere la shape dans la map des objets displayes
-      Handle(AIS_InteractiveObject) aShape =
-        Handle(AIS_InteractiveObject)::DownCast(GetMapOfAIS().Find2(name));
-
+    Handle(AIS_InteractiveObject) aShape;
+    if (GetMapOfAIS().Find2(name, aShape))
+    {
       // On verifie que l'AIS InteraciveObject est bien
       // un AIS_Trihedron
       if (!aShape.IsNull() &&
         aShape->Type()==AIS_KOI_Datum && aShape->Signature()==3)
       {
-
-        if (aShape->HasColor()) {
+        if (aShape->HasColor())
+        {
           hascol=Standard_True;
 
           // On recupere la couleur de aShape
-          col=aShape->Color();}
-
-        else hascol=Standard_False;
+          aShape->Color (col);
+        }
+        else
+        {
+          hascol = Standard_False;
+        }
 
         // On downcast aShape de AIS_InteractiveObject a AIS_Trihedron
         // pour lui appliquer la methode SetSize()
@@ -452,59 +849,24 @@ static int VPlaneTrihedron (Draw_Interpretor& di, Standard_Integer argc, const c
 
 {
   // Verification des arguments
-  if ( argc!=2) {di<<argv[0]<<" error"<<"\n"; return 1;}
+  if ( argc!=2) {di<<argv[0]<<" error\n"; return 1;}
 
-  // Declarations
-  Standard_Integer myCurrentIndex;
-  // Fermeture des contextes locaux
-  TheAISContext()->CloseAllContexts();
-
-  // On recupere tous les trihedrons de la GetMapOfAIS()
-  // et on active le mode de selection par face.
-  // =================================================
-
-  // Ouverture d'un contexte local et recuperation de son index.
-  TheAISContext()->OpenLocalContext(Standard_False);
-  myCurrentIndex=TheAISContext()->IndexOfCurrentLocal();
-
-  ViewerTest_DoubleMapIteratorOfDoubleMapOfInteractiveAndName
-    it (GetMapOfAIS());
-  while(it.More()){
-    Handle(AIS_InteractiveObject) ShapeA =
-      Handle(AIS_InteractiveObject)::DownCast(it.Key1());
-    // On verifie que c'est bien un trihedron
-    if (!ShapeA.IsNull() &&
-      ShapeA->Type()==AIS_KOI_Datum  && ShapeA->Signature()==3  ) {
-        // on le downcast
-        Handle(AIS_Trihedron) TrihedronA =(Handle(AIS_Trihedron)::DownCast (ShapeA));
-        // on le charge dans le contexte et on active le mode Plane.
-        TheAISContext()->Load(TrihedronA,0,Standard_False);
-        TheAISContext()->Activate(TrihedronA,3);
-      }
-      it.Next();
+  if (TheAISContext()->NbSelected() != 1)
+  {
+    Message::SendFail ("Error: Wrong number of selected shapes.");
+    return 1;
   }
 
-  di<<" Select a plane."<<"\n";
-  // Boucle d'attente waitpick.
-  Standard_Integer argccc = 5;
-  const char *bufff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-  const char **argvvv = (const char **) bufff;
-  while (ViewerMainLoop( argccc, argvvv) ) { }
-  // fin de la boucle
-
-  Handle(AIS_InteractiveObject) theIOB;
-  for(TheAISContext()->InitSelected() ;TheAISContext()->MoreSelected() ;TheAISContext()->NextSelected() ) {
-    theIOB = TheAISContext()->SelectedInteractive();
+  TheAISContext()->InitSelected();
+  Handle(AIS_InteractiveObject) aTest = TheAISContext()->SelectedInteractive();
+  Handle(AIS_Plane) aPlane = Handle(AIS_Plane)::DownCast (aTest);
+  if (aPlane.IsNull())
+  {
+    Message::SendFail ("Error: Selected shape is not a plane.");
+    return 1;
   }
-  // on le downcast
-  Handle(AIS_Plane) PlaneB =(Handle(AIS_Plane)::DownCast (theIOB));
 
-  // Fermeture du contexte local.
-  TheAISContext()->CloseLocalContext(myCurrentIndex);
-
-  // on le display & bind
-  TheAISContext()->Display(PlaneB );
-  GetMapOfAIS().Bind ( PlaneB ,argv[1]);
+  VDisplayAISObject (argv[1], aPlane);
 
   return 0;
 }
@@ -536,16 +898,16 @@ static int VAxisBuilder(Draw_Interpretor& di, Standard_Integer argc, const char*
   // Declarations
   Standard_Boolean HasArg;
   TCollection_AsciiString name;
-  Standard_Integer MyCurrentIndex;
 
   // Verification
-  if (argc<2 || argc>8 ) {di<<" Syntaxe error"<<"\n";return 1;}
+  if (argc<2 || argc>8 ) {di<<" Syntaxe error\n";return 1;}
   if (argc==8) HasArg=Standard_True;
   else HasArg=Standard_False;
 
   name=argv[1];
-  // Fermeture des contextes
-  TheAISContext()->CloseAllContexts();
+
+  TopTools_ListOfShape aShapes;
+  ViewerTest::GetSelectedShapes (aShapes);
 
   // Cas ou il y a des arguments
   // Purpose: Teste le constructeur AIS_Axis::AIS_Axis(x: Line from Geom)
@@ -560,7 +922,7 @@ static int VAxisBuilder(Draw_Interpretor& di, Standard_Integer argc, const char*
     Handle(Geom_Line) myLine=new Geom_Line (p1 ,myVect );
     Handle(AIS_Axis) TheAxis=new AIS_Axis (myLine );
     GetMapOfAIS().Bind (TheAxis,name);
-    TheAISContext()->Display(TheAxis);
+    TheAISContext()->Display(TheAxis, Standard_True);
   }
 
   // Pas d'arguments
@@ -568,71 +930,42 @@ static int VAxisBuilder(Draw_Interpretor& di, Standard_Integer argc, const char*
     // fonction vaxis
     // Purpose: Teste le constructeur AIS_Axis::AIS_Axis (x:Axis1Placement from Geom)
     if ( !strcasecmp(argv[0], "vaxis")) {
-      TheAISContext()->OpenLocalContext();
-      MyCurrentIndex=TheAISContext()->IndexOfCurrentLocal();
-
-      // Active le mode edge et le mode vertex
-      TheAISContext()->ActivateStandardMode(AIS_Shape::SelectionType(1) );
-      TheAISContext()->ActivateStandardMode(AIS_Shape::SelectionType(2) );
-      di<<" Select an edge or a vertex."<<"\n";
-
-      // Boucle d'attente waitpick.
-      Standard_Integer argcc = 5;
-      const char *buff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-      const char **argvv = (const char **) buff;
-      while (ViewerMainLoop( argcc, argvv) ) { }
-      // fin de la boucle
-
-      // recuperation de la shape.
-      TopoDS_Shape ShapeA;
-      for(TheAISContext()->InitSelected() ;TheAISContext()->MoreSelected() ;TheAISContext()->NextSelected() ) {
-        ShapeA = TheAISContext()->SelectedShape();
-      }
-      // recuperation de l'AIS_InteractiveObject
-      //Handle(AIS_InteractiveObject) myAISio=TheAISContext()->Current();
-      // down cast en AIS_Point si sig et type
-      // AIS_Point -> Geom_Pnt ....
-
-      if (ShapeA.ShapeType()==TopAbs_VERTEX) {
-        // on desactive le mode edge
-        TheAISContext()->DeactivateStandardMode(AIS_Shape::SelectionType(2) );
-        di<<" Select a different vertex."<<"\n";
-
-        TopoDS_Shape ShapeB;
-        do {
-          // Boucle d'attente waitpick.
-          Standard_Integer argccc = 5;
-          const char *bufff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-          const char **argvvv = (const char **) bufff;
-          while (ViewerMainLoop( argccc, argvvv) ) { }
-          // fin de la boucle
-          for(TheAISContext()->InitSelected() ;TheAISContext()->MoreSelected() ;TheAISContext()->NextSelected() ) {
-            ShapeB = TheAISContext()->SelectedShape();
-          }
-
+      if (aShapes.Extent() != 2 && aShapes.Extent() != 1)
+      {
+        Message::SendFail ("Error: Wrong number of selected shapes.");
+        return 1;
+      }
 
-        } while(ShapeB.IsSame(ShapeA) );
+      const TopoDS_Shape& aShapeA = aShapes.First();
+      if (aShapeA.ShapeType() == TopAbs_VERTEX)
+      {
+        if (aShapes.Extent() != 2)
+        {
+          Message::SendFail ("Error: Wrong number of selected shapes.");
+          return 1;
+        }
 
-        // Fermeture du context local
-        TheAISContext()->CloseLocalContext(MyCurrentIndex);
+        const TopoDS_Shape& aShapeB = aShapes.Last();
+        if (aShapeB.ShapeType() != TopAbs_VERTEX)
+        {
+          Message::SendFail ("Syntax error: You should select two vertices or one edge.");
+          return 1;
+        }
 
         // Construction de l'axe
-        gp_Pnt   A=BRep_Tool::Pnt(TopoDS::Vertex(ShapeA)  );
-        gp_Pnt   B=BRep_Tool::Pnt(TopoDS::Vertex(ShapeB)  );
-        gp_Vec   V (A,B);
-        gp_Dir   D (V);
+        gp_Pnt A = BRep_Tool::Pnt (TopoDS::Vertex (aShapeA));
+        gp_Pnt B = BRep_Tool::Pnt (TopoDS::Vertex (aShapeB));
+        gp_Vec V (A,B);
+        gp_Dir D (V);
         Handle(Geom_Axis1Placement) OrigineAndVect=new Geom_Axis1Placement (A,D);
         Handle(AIS_Axis) TheAxis=new AIS_Axis (OrigineAndVect);
         GetMapOfAIS().Bind (TheAxis,name);
-        TheAISContext()->Display(TheAxis);
-      }
-      else {
-        // Un unique edge (ShapeA) a ete picke
-        // Fermeture du context local
-        TheAISContext()->CloseLocalContext(MyCurrentIndex);
-        // Constuction de l'axe
-        TopoDS_Edge    ed =TopoDS::Edge(ShapeA);
-        TopoDS_Vertex  Va,Vb;
+        TheAISContext()->Display (TheAxis, Standard_True);
+      }
+      else
+      {
+        TopoDS_Edge    ed =TopoDS::Edge (aShapeA);
+        TopoDS_Vertex  Va,Vb;
         TopExp::Vertices(ed,Va,Vb );
         gp_Pnt A=BRep_Tool::Pnt(Va);
         gp_Pnt B=BRep_Tool::Pnt(Vb);
@@ -641,56 +974,32 @@ static int VAxisBuilder(Draw_Interpretor& di, Standard_Integer argc, const char*
         Handle(Geom_Axis1Placement) OrigineAndVect=new Geom_Axis1Placement (A,D);
         Handle(AIS_Axis) TheAxis=new AIS_Axis (OrigineAndVect);
         GetMapOfAIS().Bind (TheAxis,name);
-        TheAISContext()->Display(TheAxis);
+        TheAISContext()->Display (TheAxis, Standard_True);
       }
 
     }
 
     // Fonction axispara
     // Purpose: Teste le constructeur AIS_Axis::AIS_Axis(x: Axis2Placement from Geom, y: TypeOfAxis from AIS)
-    else if ( !strcasecmp(argv[0], "vaxispara")) {
-
-      TheAISContext()->OpenLocalContext();
-      MyCurrentIndex=TheAISContext()->IndexOfCurrentLocal();
-
-      // Active le mode edge
-      TheAISContext()->ActivateStandardMode(AIS_Shape::SelectionType(2) );
-      di<<" Select an edge."<<"\n";
-
-      // Boucle d'attente waitpick.
-      Standard_Integer argcc = 5;
-      const char *buff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-      const char **argvv = (const char **) buff;
-      while (ViewerMainLoop( argcc, argvv) ) { }
-      // fin de la boucle
-
-      TopoDS_Shape ShapeA;
-      for(TheAISContext()->InitSelected() ;TheAISContext()->MoreSelected() ;TheAISContext()->NextSelected() ) {
-        ShapeA = TheAISContext()->SelectedShape();
-      }
-      // Active le mode vertex et deactive edges
-      TheAISContext()->DeactivateStandardMode(AIS_Shape::SelectionType(2) );
-      TheAISContext()->ActivateStandardMode(AIS_Shape::SelectionType(1) );
-      di<<" Select a vertex."<<"\n";
-
-      // Boucle d'attente waitpick.
-      Standard_Integer argccc = 5;
-      const char *bufff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-      const char **argvvv = (const char **) bufff;
-      while (ViewerMainLoop( argccc, argvvv) ) { }
-      // fin de la boucle
-
-      // On peut choisir un pnt sur l'edge
-      TopoDS_Shape ShapeB;
-      for(TheAISContext()->InitSelected() ;TheAISContext()->MoreSelected() ;TheAISContext()->NextSelected() ) {
-        ShapeB = TheAISContext()->SelectedShape();
-      }
-      // Fermeture du context local
-      TheAISContext()->CloseLocalContext(MyCurrentIndex);
+    else if ( !strcasecmp(argv[0], "vaxispara"))
+    {
+      if (aShapes.Extent() != 2)
+      {
+        Message::SendFail ("Error: Wrong number of selected shapes.");
+        return 1;
+      }
 
-      // Construction de l'axe
-      TopoDS_Edge    ed=TopoDS::Edge(ShapeA) ;
-      gp_Pnt B=BRep_Tool::Pnt(TopoDS::Vertex(ShapeB) );
+      const TopoDS_Shape& aShapeA = aShapes.First();
+      const TopoDS_Shape& aShapeB = aShapes.Last();
+      if (!(aShapeA.ShapeType() == TopAbs_EDGE
+         && aShapeB.ShapeType() == TopAbs_VERTEX))
+      {
+        Message::SendFail ("Syntax error: You should select face and then vertex.");
+        return 1;
+      }
+
+      TopoDS_Edge    ed=TopoDS::Edge (aShapeA);
+      gp_Pnt B=BRep_Tool::Pnt(TopoDS::Vertex(aShapeB));
       TopoDS_Vertex  Va,Vc;
       TopExp::Vertices(ed,Va,Vc );
       gp_Pnt A=BRep_Tool::Pnt(Va);
@@ -700,53 +1009,31 @@ static int VAxisBuilder(Draw_Interpretor& di, Standard_Integer argc, const char*
       Handle(Geom_Axis1Placement) OrigineAndVect=new Geom_Axis1Placement (B,D);
       Handle(AIS_Axis) TheAxis=new AIS_Axis (OrigineAndVect);
       GetMapOfAIS().Bind (TheAxis,name);
-      TheAISContext()->Display(TheAxis);
+      TheAISContext()->Display (TheAxis, Standard_True);
 
     }
 
     // Fonction axisortho
-    else  {
-      TheAISContext()->OpenLocalContext();
-      MyCurrentIndex=TheAISContext()->IndexOfCurrentLocal();
-
-      // Active le mode edge
-      TheAISContext()->ActivateStandardMode(AIS_Shape::SelectionType(2) );
-      di<<" Select an edge."<<"\n";
-
-      // Boucle d'attente waitpick.
-      Standard_Integer argcc = 5;
-      const char *buff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-      const char **argvv = (const char **) buff;
-      while (ViewerMainLoop( argcc, argvv) ) { }
-      // fin de la boucle
-
-      TopoDS_Shape ShapeA;
-      for(TheAISContext()->InitSelected() ;TheAISContext()->MoreSelected() ;TheAISContext()->NextSelected() ) {
-        ShapeA = TheAISContext()->SelectedShape();
-      }
-      // Active le mode vertex et deactive edges
-      TheAISContext()->DeactivateStandardMode(AIS_Shape::SelectionType(2) );
-      TheAISContext()->ActivateStandardMode(AIS_Shape::SelectionType(1) );
-      di<<" Slect a vertex."<<"\n";
-
-      // Boucle d'attente waitpick.
-      Standard_Integer argccc = 5;
-      const char *bufff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-      const char **argvvv = (const char **) bufff;
-      while (ViewerMainLoop( argccc, argvvv) ) { }
-      // fin de la boucle
-
-      // On peut choisir un pnt sur l'edge
-      TopoDS_Shape ShapeB;
-      for(TheAISContext()->InitSelected() ;TheAISContext()->MoreSelected() ;TheAISContext()->NextSelected() ) {
-        ShapeB = TheAISContext()->SelectedShape();
-      }
-      // Fermeture du context local
-      TheAISContext()->CloseLocalContext(MyCurrentIndex);
+    else
+    {
+      if (aShapes.Extent() != 2)
+      {
+        Message::SendFail ("Error: Wrong number of selected shapes.");
+        return 1;
+      }
+
+      const TopoDS_Shape& aShapeA = aShapes.First();
+      const TopoDS_Shape& aShapeB = aShapes.Last();
+      if (!(aShapeA.ShapeType() == TopAbs_EDGE
+         && aShapeB.ShapeType() == TopAbs_VERTEX))
+      {
+        Message::SendFail ("Syntax error: You should select face and then vertex.");
+        return 1;
+      }
 
       // Construction de l'axe
-      TopoDS_Edge    ed=TopoDS::Edge(ShapeA) ;
-      gp_Pnt B=BRep_Tool::Pnt(TopoDS::Vertex(ShapeB) );
+      TopoDS_Edge    ed=TopoDS::Edge(aShapeA) ;
+      gp_Pnt B=BRep_Tool::Pnt(TopoDS::Vertex(aShapeB) );
       TopoDS_Vertex  Va,Vc;
       TopExp::Vertices(ed,Va,Vc );
       gp_Pnt A=BRep_Tool::Pnt(Va);
@@ -757,7 +1044,7 @@ static int VAxisBuilder(Draw_Interpretor& di, Standard_Integer argc, const char*
       Handle(Geom_Axis1Placement) OrigineAndVect=new Geom_Axis1Placement (B,D);
       Handle(AIS_Axis) TheAxis=new AIS_Axis (OrigineAndVect);
       GetMapOfAIS().Bind (TheAxis,name);
-      TheAISContext()->Display(TheAxis);
+      TheAISContext()->Display (TheAxis, Standard_True);
 
     }
 
@@ -775,8 +1062,7 @@ static int VAxisBuilder(Draw_Interpretor& di, Standard_Integer argc, const char*
 
 //==============================================================================
 //function : VPointBuilder
-//purpose  : Build an AIS_Point from coordinates or with a selected vertex or edge
-//Draw arg : vpoint PoinName [Xa] [Ya] [Za]
+//purpose  :
 //==============================================================================
 #include <TopoDS_Edge.hxx>
 #include <TopoDS_Vertex.hxx>
@@ -784,88 +1070,105 @@ static int VAxisBuilder(Draw_Interpretor& di, Standard_Integer argc, const char*
 #include <AIS_Point.hxx>
 #include <Geom_CartesianPoint.hxx>
 
-static int VPointBuilder(Draw_Interpretor& di, Standard_Integer argc, const char** argv)
+static int VPointBuilder(Draw_Interpretor& ,
+                         Standard_Integer theArgNb,
+                         const char** theArgVec)
 {
-  // Declarations
-  Standard_Boolean HasArg;
-  TCollection_AsciiString name;
-  Standard_Integer myCurrentIndex;
-
-  // Verification
-  if (argc<2 || argc>5 ) {di<<" Syntaxe error"<<"\n";return 1;}
-  if (argc==5) HasArg=Standard_True;
-  else HasArg=Standard_False;
-
-  name=argv[1];
-  // Fermeture des contextes
-  TheAISContext()->CloseAllContexts();
-
-  // Il y a des arguments: teste l'unique constructeur AIS_Pnt::AIS_Pnt(Point from Geom)
-  if (HasArg) {
-    Standard_Real thecoord[3];
-    for(Standard_Integer i=0;i<=2;i++)
-      thecoord[i]=Draw::Atof(argv[2+i]);
-    Handle(Geom_CartesianPoint )  myGeomPoint= new Geom_CartesianPoint (thecoord[0],thecoord[1],thecoord[2]);
-    Handle(AIS_Point)  myAISPoint=new AIS_Point(myGeomPoint );
-    GetMapOfAIS().Bind (myAISPoint,name);
-    TheAISContext()->Display(myAISPoint);
+  TCollection_AsciiString aName;
+  gp_Pnt aPnt (RealLast(), 0.0, 0.0);
+  bool is2d = false, isNoSel = false;
+  for (Standard_Integer anArgIter = 1; anArgIter < theArgNb; ++anArgIter)
+  {
+    TCollection_AsciiString anArg (theArgVec[anArgIter]);
+    anArg.LowerCase();
+    if (anArg == "-2d")
+    {
+      is2d = true;
+    }
+    else if (anArg == "-nosel"
+          || anArg == "-noselection")
+    {
+      isNoSel = true;
+    }
+    else if (aName.IsEmpty())
+    {
+      aName = theArgVec[anArgIter];
+    }
+    else if (aPnt.X() == RealLast()
+          && anArgIter + 1 < theArgNb
+          && Draw::ParseReal (theArgVec[anArgIter + 0], aPnt.ChangeCoord().ChangeCoord (1))
+          && Draw::ParseReal (theArgVec[anArgIter + 1], aPnt.ChangeCoord().ChangeCoord (2)))
+    {
+      if (anArgIter + 2 < theArgNb
+       && TCollection_AsciiString (theArgVec[anArgIter + 2]) != "-2d"
+       && Draw::ParseReal (theArgVec[anArgIter + 2], aPnt.ChangeCoord().ChangeCoord (3)))
+      {
+        anArgIter += 2;
+      }
+      else
+      {
+        anArgIter += 1;
+      }
+    }
+    else
+    {
+      Message::SendFail() << "Syntax error at argument '" << anArg << "'\n";
+      return 1;
+    }
   }
 
-  // Il n'a pas d'arguments
-  else {
-    TheAISContext()->OpenLocalContext();
-    myCurrentIndex=TheAISContext()->IndexOfCurrentLocal();
-
-    // Active le mode Vertex et Edges
-    TheAISContext()->ActivateStandardMode (AIS_Shape::SelectionType(1) );
-    TheAISContext()->ActivateStandardMode (AIS_Shape::SelectionType(2) );
-    di<<" Select a vertex or an edge(build the middle)"<<"\n";
-
-    // Boucle d'attente waitpick.
-    Standard_Integer argcc = 5;
-    const char *buff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-    const char **argvv = (const char **) buff;
-    while (ViewerMainLoop( argcc, argvv) ) { }
-    // fin de la boucle
-
-    TopoDS_Shape ShapeA;
-    for (TheAISContext()->InitSelected() ;TheAISContext()->MoreSelected() ;TheAISContext()->NextSelected() ) {
-      ShapeA= TheAISContext()->SelectedShape();
-    }
-
-    if (ShapeA.ShapeType()==TopAbs_VERTEX ) {
-      // Un vertex a ete selectionne
-      // Fermeture du context local
-      TheAISContext()->CloseLocalContext(myCurrentIndex);
-
-      // Construction du point
-      gp_Pnt A=BRep_Tool::Pnt(TopoDS::Vertex(ShapeA ) );
-      Handle(Geom_CartesianPoint) myGeomPoint= new Geom_CartesianPoint (A );
-      Handle(AIS_Point)  myAISPoint = new AIS_Point  (myGeomPoint );
-      GetMapOfAIS().Bind(myAISPoint,name);
-      TheAISContext()->Display(myAISPoint);
-    }
-    else {
-      // Un Edge a ete selectionne
-      // Fermeture du context local
-      TheAISContext()->CloseLocalContext(myCurrentIndex);
-
-      // Construction du point milieu de l'edge
-      TopoDS_Edge myEdge=TopoDS::Edge(ShapeA);
-      TopoDS_Vertex myVertexA,myVertexB;
-      TopExp::Vertices (myEdge ,myVertexA ,myVertexB );
-      gp_Pnt A=BRep_Tool::Pnt(myVertexA );
-      gp_Pnt B=BRep_Tool::Pnt(myVertexB );
-      // M est le milieu de [AB]
-      Handle(Geom_CartesianPoint) myGeomPointM= new Geom_CartesianPoint ( (A.X()+B.X())/2  , (A.Y()+B.Y())/2  , (A.Z()+B.Z())/2  );
-      Handle(AIS_Point)  myAISPointM = new AIS_Point  (myGeomPointM );
-      GetMapOfAIS().Bind(myAISPointM,name);
-      TheAISContext()->Display(myAISPointM);
+  if (aPnt.X() == RealLast())
+  {
+    TopTools_ListOfShape aShapes;
+    ViewerTest::GetSelectedShapes (aShapes);
+    TopoDS_Shape aShapeA;
+    if (aShapes.Extent() == 1)
+    {
+      aShapeA = aShapes.First();
+    }
+    switch (!aShapeA.IsNull() ? aShapeA.ShapeType() : TopAbs_SHAPE)
+    {
+      case TopAbs_VERTEX:
+      {
+        aPnt = BRep_Tool::Pnt (TopoDS::Vertex (aShapeA));
+        break;
+      }
+      case TopAbs_EDGE: // edge middle point
+      {
+        const TopoDS_Edge& anEdge = TopoDS::Edge (aShapeA);
+        TopoDS_Vertex aVertPair[2];
+        TopExp::Vertices (anEdge, aVertPair[0], aVertPair[1]);
+        const gp_Pnt A = BRep_Tool::Pnt (aVertPair[0]);
+        const gp_Pnt B = BRep_Tool::Pnt (aVertPair[1]);
+        aPnt = (A.XYZ() + B.XYZ()) / 2;
+        break;
+      }
+      default:
+      {
+        Message::SendFail() << "Error: Wrong number of selected shapes.\n"
+                            << "\tYou should select one edge or vertex.";
+        return 1;
+      }
     }
+  }
 
+  if (is2d)
+  {
+    aPnt.SetY (-aPnt.Y());
+  }
+  Handle(Geom_CartesianPoint ) aGeomPoint = new Geom_CartesianPoint (aPnt);
+  Handle(AIS_Point) aPointPrs = new AIS_Point (aGeomPoint);
+  if (is2d)
+  {
+    aPointPrs->SetTransformPersistence (new Graphic3d_TransformPers (Graphic3d_TMF_2d, Aspect_TOTP_LEFT_UPPER));
+    aPointPrs->SetZLayer (Graphic3d_ZLayerId_TopOSD);
+  }
+  ViewerTest::Display (aName, aPointPrs);
+  if (isNoSel)
+  {
+    ViewerTest::GetAISContext()->Deactivate (aPointPrs);
   }
   return 0;
-
 }
 
 //==============================================================================
@@ -895,12 +1198,11 @@ static Standard_Integer VPlaneBuilder (Draw_Interpretor& /*di*/,
   // Declarations
   Standard_Boolean hasArg;
   TCollection_AsciiString aName;
-  Standard_Integer aCurrentIndex;
 
   // Verification
   if (argc<2 || argc>6 )
   {
-    std::cout<<" Syntax error\n";
+    Message::SendFail ("Syntax error: wrong number of arguments");
     return 1;
   }
   if (argc == 6 || argc==5 || argc==4)
@@ -909,20 +1211,16 @@ static Standard_Integer VPlaneBuilder (Draw_Interpretor& /*di*/,
     hasArg=Standard_False;
 
   aName=argv[1];
-  // Close all contexts
-  TheAISContext()->CloseAllContexts();
 
   // There are some arguments
   if (hasArg)
   {
-    if (!GetMapOfAIS().IsBound2(argv[2] ))
+    Handle(AIS_InteractiveObject) aShapeA;
+    if (!GetMapOfAIS().Find2 (argv[2], aShapeA))
     {
-      std::cout<<"vplane: error 1st name doesn't exist in the GetMapOfAIS()\n";
+      Message::SendFail ("Syntax error: 1st name is not displayed");
       return 1;
     }
-    // Get shape from map
-    Handle(AIS_InteractiveObject) aShapeA =
-      Handle(AIS_InteractiveObject)::DownCast (GetMapOfAIS().Find2(argv[2] ));
 
     // The first argument is an AIS_Point
     if (!aShapeA.IsNull() &&
@@ -930,35 +1228,31 @@ static Standard_Integer VPlaneBuilder (Draw_Interpretor& /*di*/,
         aShapeA->Signature()==1)
     {
         // The second argument must also be an AIS_Point
-        if (argc<5 || !GetMapOfAIS().IsBound2(argv[3]))
+        Handle(AIS_InteractiveObject) aShapeB;
+        if (argc<5 || !GetMapOfAIS().Find2 (argv[3], aShapeB))
         {
-          std::cout<<"vplane: error 2nd name doesn't exist in the GetMapOfAIS()\n";
+          Message::SendFail ("Syntax error: 2nd name is not displayed");
           return 1;
         }
-        // Get shape from map
-        Handle(AIS_InteractiveObject) aShapeB =
-          Handle(AIS_InteractiveObject)::DownCast (GetMapOfAIS().Find2(argv[3]));
         // If B is not an AIS_Point
         if (aShapeB.IsNull() ||
           (!(aShapeB->Type()==AIS_KOI_Datum && aShapeB->Signature()==1)))
         {
-          std::cout<<"vplane: error 2nd object is expected to be an AIS_Point.\n";
+          Message::SendFail ("Syntax error: 2nd object is expected to be an AIS_Point");
           return 1;
         }
         // The third object is an AIS_Point
-        if (!GetMapOfAIS().IsBound2(argv[4]) ) 
+        Handle(AIS_InteractiveObject) aShapeC;
+        if (!GetMapOfAIS().Find2(argv[4], aShapeC)) 
         {
-          std::cout<<"vplane: error 3d name doesn't exist in the GetMapOfAIS().\n";
+          Message::SendFail ("Syntax error: 3d name is not displayed");
           return 1; 
         }
-        // Get shape from map
-        Handle(AIS_InteractiveObject) aShapeC =
-          Handle(AIS_InteractiveObject)::DownCast (GetMapOfAIS().Find2(argv[4]));
         // If C is not an AIS_Point
         if (aShapeC.IsNull() ||
           (!(aShapeC->Type()==AIS_KOI_Datum && aShapeC->Signature()==1)))
         {
-          std::cout<<"vplane: error 3d object is expected to be an AIS_Point.\n";
+          Message::SendFail ("Syntax error: 3d object is expected to be an AIS_Point");
           return 1;
         }
 
@@ -983,21 +1277,24 @@ static Standard_Integer VPlaneBuilder (Draw_Interpretor& /*di*/,
            Abs(aCartPointB->Z()-aCartPointA->Z())<=Precision::Confusion())
         {
           // B=A
-          std::cout<<"vplane error: same points"<<"\n";return 1;
+          Message::SendFail ("Error: same points");
+          return 1;
         }
         if(Abs(aCartPointC->X()-aCartPointA->X())<=Precision::Confusion() &&
            Abs(aCartPointC->Y()-aCartPointA->Y())<=Precision::Confusion() &&
            Abs(aCartPointC->Z()-aCartPointA->Z())<=Precision::Confusion())
         {
           // C=A
-          std::cout<<"vplane error: same points"<<"\n";return 1;
+          Message::SendFail ("Error: same points");
+          return 1;
         }
         if(Abs(aCartPointC->X()-aCartPointB->X())<=Precision::Confusion() &&
            Abs(aCartPointC->Y()-aCartPointB->Y())<=Precision::Confusion() &&
            Abs(aCartPointC->Z()-aCartPointB->Z())<=Precision::Confusion())
         {
           // C=B
-          std::cout<<"vplane error: same points"<<"\n";return 1;
+          Message::SendFail ("Error: same points");
+          return 1;
         }
 
         gp_Pnt A = aCartPointA->Pnt();
@@ -1014,11 +1311,10 @@ static Standard_Integer VPlaneBuilder (Draw_Interpretor& /*di*/,
           Standard_Integer aType = Draw::Atoi (argv[5]);
           if (aType != 0 && aType != 1)
           {
-            std::cout << "vplane error: wrong type of sensitivity!\n"
-                      << "Should be one of the following values:\n"
-                      << "0 - Interior\n"
-                      << "1 - Boundary"
-                      << std::endl;
+            Message::SendFail("Syntax error: wrong type of sensitivity.\n"
+                              "Should be one of the following values:\n"
+                              "0 - Interior\n"
+                              "1 - Boundary");
             return 1;
           }
           else
@@ -1026,26 +1322,24 @@ static Standard_Integer VPlaneBuilder (Draw_Interpretor& /*di*/,
             anAISPlane->SetTypeOfSensitivity (Select3D_TypeOfSensitivity (aType));
           }
         }
-        TheAISContext()->Display(anAISPlane);
+        TheAISContext()->Display (anAISPlane, Standard_True);
       }
 
       // The first argument is an AIS_Axis
       // Creation of a plane orthogonal to the axis through a point
     else if (aShapeA->Type()==AIS_KOI_Datum && aShapeA->Signature()==2 ) {
       // The second argument should be an AIS_Point
-      if (argc!=4 || !GetMapOfAIS().IsBound2(argv[3] ) )
+      Handle(AIS_InteractiveObject) aShapeB;
+      if (argc!=4 || !GetMapOfAIS().Find2 (argv[3], aShapeB))
       {
-        std::cout<<"vplane: error 2d name doesn't exist in the GetMapOfAIS()\n";
+        Message::SendFail ("Syntax error: 2d name is not displayed");
         return 1;
       }
-      // Get shape from map
-      Handle(AIS_InteractiveObject) aShapeB =
-        Handle(AIS_InteractiveObject)::DownCast (GetMapOfAIS().Find2(argv[3]));
       // If B is not an AIS_Point
       if (aShapeB.IsNull() ||
         (!(aShapeB->Type()==AIS_KOI_Datum && aShapeB->Signature()==1)))
       {
-        std::cout<<"vplane: error 2d object is expected to be an AIS_Point\n";
+        Message::SendFail ("Syntax error: 2d object is expected to be an AIS_Point");
         return 1;
       }
 
@@ -1072,11 +1366,10 @@ static Standard_Integer VPlaneBuilder (Draw_Interpretor& /*di*/,
         Standard_Integer aType = Draw::Atoi (argv[4]);
         if (aType != 0 && aType != 1)
         {
-          std::cout << "vplane error: wrong type of sensitivity!\n"
-                    << "Should be one of the following values:\n"
-                    << "0 - Interior\n"
-                    << "1 - Boundary"
-                    << std::endl;
+          Message::SendFail ("Syntax error: wrong type of sensitivity!\n"
+                             "Should be one of the following values:\n"
+                             "0 - Interior\n"
+                             "1 - Boundary");
           return 1;
         }
         else
@@ -1084,7 +1377,7 @@ static Standard_Integer VPlaneBuilder (Draw_Interpretor& /*di*/,
           anAISPlane->SetTypeOfSensitivity (Select3D_TypeOfSensitivity (aType));
         }
       }
-      TheAISContext()->Display(anAISPlane);
+      TheAISContext()->Display (anAISPlane, Standard_True);
 
     }
     // The first argumnet is an AIS_Plane
@@ -1092,19 +1385,17 @@ static Standard_Integer VPlaneBuilder (Draw_Interpretor& /*di*/,
     else if (aShapeA->Type()==AIS_KOI_Datum && aShapeA->Signature()==7)
     {
       // The second argument should be an AIS_Point
-      if (argc!=4 || !GetMapOfAIS().IsBound2(argv[3]))
+      Handle(AIS_InteractiveObject) aShapeB;
+      if (argc!=4 || !GetMapOfAIS().Find2 (argv[3], aShapeB))
       {
-        std::cout<<"vplane: error 2d name doesn't exist in the GetMapOfAIS()\n";
+        Message::SendFail ("Syntax error: 2d name is not displayed");
         return 1;
       }
-      // Get shape from map
-      Handle(AIS_InteractiveObject) aShapeB =
-        Handle(AIS_InteractiveObject)::DownCast (GetMapOfAIS().Find2(argv[3]));
       // B should be an AIS_Point
       if (aShapeB.IsNull() ||
          (!(aShapeB->Type()==AIS_KOI_Datum && aShapeB->Signature()==1)))
       {
-        std::cout<<"vplane: error 2d object is expected to be an AIS_Point\n";
+        Message::SendFail ("Syntax error: 2d object is expected to be an AIS_Point");
         return 1;
       }
 
@@ -1127,11 +1418,10 @@ static Standard_Integer VPlaneBuilder (Draw_Interpretor& /*di*/,
         Standard_Integer aType = Draw::Atoi (argv[4]);
         if (aType != 0 && aType != 1)
         {
-          std::cout << "vplane error: wrong type of sensitivity!\n"
-                    << "Should be one of the following values:\n"
-                    << "0 - Interior\n"
-                    << "1 - Boundary"
-                    << std::endl;
+          Message::SendFail ("Syntax error: wrong type of sensitivity!\n"
+                             "Should be one of the following values:\n"
+                             "0 - Interior\n"
+                             "1 - Boundary");
           return 1;
         }
         else
@@ -1139,115 +1429,44 @@ static Standard_Integer VPlaneBuilder (Draw_Interpretor& /*di*/,
           anAISPlane->SetTypeOfSensitivity (Select3D_TypeOfSensitivity (aType));
         }
       }
-      TheAISContext()->Display(anAISPlane);
+      TheAISContext()->Display (anAISPlane, Standard_True);
     }
     // Error
     else
     {
-      std::cout<<"vplane: error 1st object is not an AIS\n";
+      Message::SendFail ("Syntax error: 1st object is not an AIS");
       return 1;
     }
   }
   // There are no arguments
   else 
   {
+    TopTools_ListOfShape aShapes;
+    ViewerTest::GetSelectedShapes (aShapes);
+
     // Function vplane
     // Test the constructor AIS_Plane::AIS_Plane(Geom_Plane, Standard_Boolean )
     if (!strcasecmp(argv[0], "vplane"))
     {
-      TheAISContext()->OpenLocalContext();
-      aCurrentIndex=TheAISContext()->IndexOfCurrentLocal();
-
-      // Active modes Vertex, Edge and Face
-      TheAISContext()->ActivateStandardMode (AIS_Shape::SelectionType(1));
-      TheAISContext()->ActivateStandardMode (AIS_Shape::SelectionType(2));
-      TheAISContext()->ActivateStandardMode (AIS_Shape::SelectionType(4));
-      std::cout<<"Select a vertex, a face or an edge\n";
-
-      // Wait for picking
-      Standard_Integer argcc = 5;
-      const char *buff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-      const char **argvv = (const char **) buff;
-      while (ViewerMainLoop( argcc, argvv) ) { }
-      // end of the loop
-
-      TopoDS_Shape aShapeA;
-      for (TheAISContext()->InitSelected();
-           TheAISContext()->MoreSelected();
-           TheAISContext()->NextSelected())
+      if (aShapes.Extent() < 1 || aShapes.Extent() > 3)
       {
-        aShapeA = TheAISContext()->SelectedShape();
+        Message::SendFail() << "Error: Wront number of selected shapes.\n"
+                            << "\tYou should one of variant: face, edge and vertex or three vertices.";
+        return 1;
       }
 
-      // aShapeA is a Vertex
-      if (aShapeA.ShapeType()==TopAbs_VERTEX )
+      const TopoDS_Shape& aShapeA = aShapes.First();
+      if (aShapeA.ShapeType() == TopAbs_VERTEX)
       {
-        TheAISContext()->DeactivateStandardMode (AIS_Shape::SelectionType(4));
-        std::cout<<" Select an edge or a different vertex\n";
-
-        // Wait for picking
-        Standard_Integer argccc = 5;
-        const char *bufff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-        const char **argvvv = (const char **) bufff;
-        while (ViewerMainLoop( argccc, argvvv) ) { }
-        // end of the loop
-
-        TopoDS_Shape aShapeB;
-        for (TheAISContext()->InitSelected();
-          TheAISContext()->MoreSelected();
-          TheAISContext()->NextSelected())
-        {
-          aShapeB = TheAISContext()->SelectedShape();
-        }
-        // aShapeB is a Vertex
-        if (aShapeB.ShapeType()==TopAbs_VERTEX)
+        if (aShapes.Extent() == 2)
         {
-          // A and B are the same
-          if (aShapeB.IsSame(aShapeA))
-          {
-            std::cout<<" vplane: error, same points selected\n";
-            return 1;
-          }
-          TheAISContext()->DeactivateStandardMode (AIS_Shape::SelectionType(2));
-          std::cout<<" Select a different vertex\n";
-
-          // Wait for picking
-          Standard_Integer argcccc = 5;
-          const char *buffff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-          const char **argvvvv = (const char **) buffff;
-          while (ViewerMainLoop( argcccc, argvvvv) ) { }
-          // end of the loop
-
-          TopoDS_Shape aShapeC;
-          for (TheAISContext()->InitSelected();
-               TheAISContext()->MoreSelected();
-               TheAISContext()->NextSelected())
-          {
-            aShapeC = TheAISContext()->SelectedShape();
-          }
-          // aShapeC is the same as A or B
-          if (aShapeC.IsSame(aShapeA)||aShapeC.IsSame(aShapeB))
+          const TopoDS_Shape& aShapeB = aShapes.Last();
+          if (aShapeB.ShapeType() != TopAbs_EDGE)
           {
-            std::cout<<" vplane: error, same points selected\n";
+            Message::SendFail ("Syntax error: Together with vertex should be edge.");
             return 1;
           }
 
-          // Close the local context
-          TheAISContext()->CloseLocalContext(aCurrentIndex);
-
-          // Construction of plane
-          gp_Pnt A = BRep_Tool::Pnt(TopoDS::Vertex(aShapeA));
-          gp_Pnt B = BRep_Tool::Pnt(TopoDS::Vertex(aShapeB));
-          gp_Pnt C = BRep_Tool::Pnt(TopoDS::Vertex(aShapeC));
-          GC_MakePlane MkPlane(A, B, C);
-          Handle(Geom_Plane) aGeomPlane = MkPlane.Value();
-          Handle(AIS_Plane) anAISPlane = new AIS_Plane (aGeomPlane);
-          GetMapOfAIS().Bind (anAISPlane, aName);
-          TheAISContext()->Display(anAISPlane);
-        }
-        // ShapeB is an edge
-        else
-        {
           // Verify that the vertex is not on the edge ShapeB
           TopoDS_Edge anEdgeB = TopoDS::Edge(aShapeB);
           TopoDS_Vertex aVertA = TopoDS::Vertex(aShapeA);
@@ -1256,14 +1475,11 @@ static Standard_Integer VPlaneBuilder (Draw_Interpretor& /*di*/,
           if (OrthoProj.SquareDistance(1)<Precision::Approximation())
           {
             // The vertex is on the edge
-            std::cout<<" vplane: error point is on the edge\n";
+            Message::SendFail ("Error: point is on the edge");
             return 1;
           }
           else
           {
-            // Close the local context
-            TheAISContext()->CloseLocalContext(aCurrentIndex);
-            // Construction of plane
             gp_Pnt A = BRep_Tool::Pnt(aVertA);
             TopoDS_Vertex aVBa, aVBb;
             TopExp::Vertices(anEdgeB ,aVBa ,aVBb);
@@ -1273,32 +1489,56 @@ static Standard_Integer VPlaneBuilder (Draw_Interpretor& /*di*/,
             Handle(Geom_Plane) aGeomPlane = MkPlane.Value();
             Handle(AIS_Plane) anAISPlane = new AIS_Plane (aGeomPlane);
             GetMapOfAIS().Bind (anAISPlane, aName);
-            TheAISContext()->Display(anAISPlane);
+            TheAISContext()->Display (anAISPlane, Standard_True);
+          }
+        }
+        else if (aShapes.Extent() == 3)
+        {
+          TopTools_ListOfShape::Iterator anIter (aShapes);
+
+          anIter.Next();
+          const TopoDS_Shape& aShapeB = anIter.Value();
+
+          anIter.Next();
+          const TopoDS_Shape& aShapeC = anIter.Value();
+
+          if (!(aShapeB.ShapeType() == TopAbs_VERTEX
+             && aShapeC.ShapeType() == TopAbs_VERTEX))
+          {
+            Message::SendFail ("Syntax error: You should one of variant: face, edge and vertex or three vertices.");
+            return 1;
           }
+
+          gp_Pnt A = BRep_Tool::Pnt(TopoDS::Vertex(aShapeA));
+          gp_Pnt B = BRep_Tool::Pnt(TopoDS::Vertex(aShapeB));
+          gp_Pnt C = BRep_Tool::Pnt(TopoDS::Vertex(aShapeC));
+          GC_MakePlane MkPlane(A, B, C);
+          Handle(Geom_Plane) aGeomPlane = MkPlane.Value();
+          Handle(AIS_Plane) anAISPlane = new AIS_Plane (aGeomPlane);
+          GetMapOfAIS().Bind (anAISPlane, aName);
+          TheAISContext()->Display (anAISPlane, Standard_True);
+        }
+        else
+        {
+          Message::SendFail ("Syntax error: You should one of variant: face, edge and vertex or three vertices.");
+          return 1;
         }
       }
-      // aShapeA is an edge
-      else if (aShapeA.ShapeType()==TopAbs_EDGE)
+      else if (aShapeA.ShapeType() == TopAbs_EDGE)
       {
-        TheAISContext()->DeactivateStandardMode (AIS_Shape::SelectionType(4));
-        TheAISContext()->DeactivateStandardMode (AIS_Shape::SelectionType(2));
-        std::cout<<" Select a vertex that don't belong to the edge\n";
-
-        // Wait for picking
-        Standard_Integer argccc = 5;
-        const char *bufff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-        const char **argvvv = (const char **) bufff;
-        while (ViewerMainLoop( argccc, argvvv) ) { }
-        // end of the loop
+        if (aShapes.Extent() != 2)
+        {
+          Message::SendFail ("Error: wrong number of selected shapes.");
+          return 1;
+        }
 
-        TopoDS_Shape aShapeB;
-        for (TheAISContext()->InitSelected();
-             TheAISContext()->MoreSelected();
-             TheAISContext()->NextSelected())
+        const TopoDS_Shape& aShapeB = aShapes.Last();
+        if (aShapeB.ShapeType() != TopAbs_VERTEX)
         {
-          aShapeB = TheAISContext()->SelectedShape();
+          Message::SendFail ("Syntax error: Together with edge should be vertex.");
+          return 1;
         }
-        // aShapeB should be a Vertex
+
         // Check that the vertex aShapeB is not on the edge
         TopoDS_Edge anEdgeA = TopoDS::Edge(aShapeA);
         TopoDS_Vertex aVertB = TopoDS::Vertex(aShapeB);
@@ -1307,32 +1547,23 @@ static Standard_Integer VPlaneBuilder (Draw_Interpretor& /*di*/,
         if (OrthoProj.SquareDistance(1)<Precision::Approximation())
         {
           // The vertex is on the edge
-          std::cout<<" vplane: error point is on the edge\n";
+          Message::SendFail ("Error point is on the edge");
           return 1;
         }
-        else
-        {
-          // Close the local context
-          TheAISContext()->CloseLocalContext(aCurrentIndex);
-          // Construction of plane
-          gp_Pnt B = BRep_Tool::Pnt(aVertB);
-          TopoDS_Vertex aVAa, aVAb;
-          TopExp::Vertices(anEdgeA, aVAa, aVAb);
-          gp_Pnt Aa = BRep_Tool::Pnt(aVAa);
-          gp_Pnt Ab = BRep_Tool::Pnt(aVAb);
-          GC_MakePlane MkPlane (B,Aa,Ab);
-          Handle(Geom_Plane) aGeomPlane = MkPlane.Value();
-          Handle(AIS_Plane) anAISPlane = new AIS_Plane (aGeomPlane);
-          GetMapOfAIS().Bind (anAISPlane ,aName);
-          TheAISContext()->Display(anAISPlane);
-        }
+
+        gp_Pnt B = BRep_Tool::Pnt(aVertB);
+        TopoDS_Vertex aVAa, aVAb;
+        TopExp::Vertices(anEdgeA, aVAa, aVAb);
+        gp_Pnt Aa = BRep_Tool::Pnt(aVAa);
+        gp_Pnt Ab = BRep_Tool::Pnt(aVAb);
+        GC_MakePlane MkPlane (B,Aa,Ab);
+        Handle(Geom_Plane) aGeomPlane = MkPlane.Value();
+        Handle(AIS_Plane) anAISPlane = new AIS_Plane (aGeomPlane);
+        GetMapOfAIS().Bind (anAISPlane ,aName);
+        TheAISContext()->Display (anAISPlane, Standard_True);
       }
-      // aShapeA is a Face
-      else
+      else if (aShapeA.ShapeType() == TopAbs_FACE)
       {
-        // Close the local context: nothing to select
-        TheAISContext()->CloseLocalContext(aCurrentIndex);
-        // Construction of plane
         TopoDS_Face aFace = TopoDS::Face(aShapeA);
         BRepAdaptor_Surface aSurface (aFace, Standard_False);
         if (aSurface.GetType()==GeomAbs_Plane)
@@ -1341,14 +1572,19 @@ static Standard_Integer VPlaneBuilder (Draw_Interpretor& /*di*/,
           Handle(Geom_Plane) aGeomPlane = new Geom_Plane(aPlane);
           Handle(AIS_Plane) anAISPlane = new AIS_Plane(aGeomPlane);
           GetMapOfAIS().Bind (anAISPlane, aName);
-          TheAISContext()->Display(anAISPlane);
+          TheAISContext()->Display (anAISPlane, Standard_True);
         }
         else
         {
-          std::cout<<" vplane: error\n";
+          Message::SendFail ("Error: surface is not Plane");
           return 1;
         }
       }
+      else
+      {
+        Message::SendFail ("Syntax error: You should one of variant: face, edge and vertex or three vertices");
+        return 1;
+      }
     }
 
     // Function vPlanePara
@@ -1356,120 +1592,44 @@ static Standard_Integer VPlaneBuilder (Draw_Interpretor& /*di*/,
     // test the constructor AIS_Plane::AIS_Plane(Geom_Plane,gp_Pnt)
     else if (!strcasecmp(argv[0], "vplanepara"))
     {
-      TheAISContext()->OpenLocalContext();
-      aCurrentIndex = TheAISContext()->IndexOfCurrentLocal();
-
-      // Activate modes Vertex and Face
-      TheAISContext()->ActivateStandardMode (AIS_Shape::SelectionType(1));
-      TheAISContext()->ActivateStandardMode (AIS_Shape::SelectionType(4));
-      std::cout<<" Select a vertex or a face\n";
-
-      // Wait for picking
-      Standard_Integer argcc = 5;
-      const char *buff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-      const char **argvv = (const char **) buff;
-      while (ViewerMainLoop( argcc, argvv) ) { }
-      // end of the loop
-
-      TopoDS_Shape aShapeA;
-      for (TheAISContext()->InitSelected();
-           TheAISContext()->MoreSelected();
-           TheAISContext()->NextSelected())
+      if (aShapes.Extent() != 2)
       {
-        aShapeA = TheAISContext()->SelectedShape();
+        Message::SendFail ("Error: Wrong number of selected shapes.");
+        return 1;
       }
 
-      if (aShapeA.ShapeType()==TopAbs_VERTEX )
+      const TopoDS_Shape* aShapeA = &aShapes.First();
+      const TopoDS_Shape* aShapeB = &aShapes.Last();
+      if (aShapeA->ShapeType() != TopAbs_VERTEX)
       {
-        // aShapeA is a vertex
-        // Deactivate the mode Vertex
-        TheAISContext()->DeactivateStandardMode (AIS_Shape::SelectionType(1));
-        std::cout<<" Select a face\n";
-
-        // Wait for picking
-        Standard_Integer argccc = 5;
-        const char *bufff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-        const char **argvvv = (const char **) bufff;
-        while (ViewerMainLoop( argccc, argvvv) ) { }
-        // end of the loop
-
-        TopoDS_Shape aShapeB;
-        for (TheAISContext()->InitSelected();
-             TheAISContext()->MoreSelected();
-             TheAISContext()->NextSelected())
-        {
-          // A vertex ShapeA can be on Face ShapeB
-          aShapeB = TheAISContext()->SelectedShape();
-        }
+        std::swap (aShapeA, aShapeB);
+      }
 
-        // Close the local context
-        TheAISContext()->CloseLocalContext(aCurrentIndex);
+      if (!(aShapeA->ShapeType() == TopAbs_VERTEX
+         && aShapeB->ShapeType() == TopAbs_FACE))
+      {
+        Message::SendFail ("Syntax error: you should select face and vertex.");
+        return 1;
+      }
 
-        // Construction of plane
-        gp_Pnt A = BRep_Tool::Pnt(TopoDS::Vertex(aShapeA));
+      gp_Pnt A = BRep_Tool::Pnt(TopoDS::Vertex(*aShapeA));
 
-        TopoDS_Face aFace = TopoDS::Face(aShapeB);
-        BRepAdaptor_Surface aSurface (aFace, Standard_False);
-        if (aSurface.GetType()==GeomAbs_Plane )
-        {
-          gp_Pln aPlane = aSurface.Plane();
-          // Construct a plane parallel to aGeomPlane through A
-          aPlane.SetLocation(A);
-          Handle(Geom_Plane) aGeomPlane = new Geom_Plane (aPlane);
-          Handle(AIS_Plane) aAISPlane = new AIS_Plane (aGeomPlane, A);
-          GetMapOfAIS().Bind (aAISPlane ,aName);
-          TheAISContext()->Display(aAISPlane);
-        }
-        else
-        {
-          std::cout<<" vplanepara: error\n";
-          return 1;
-        }
+      TopoDS_Face aFace = TopoDS::Face(*aShapeB);
+      BRepAdaptor_Surface aSurface (aFace, Standard_False);
+      if (aSurface.GetType() == GeomAbs_Plane)
+      {
+        gp_Pln aPlane = aSurface.Plane();
+        // Construct a plane parallel to aGeomPlane through A
+        aPlane.SetLocation(A);
+        Handle(Geom_Plane) aGeomPlane = new Geom_Plane (aPlane);
+        Handle(AIS_Plane) aAISPlane = new AIS_Plane (aGeomPlane, A);
+        GetMapOfAIS().Bind (aAISPlane ,aName);
+        TheAISContext()->Display (aAISPlane, Standard_True);
       }
       else
       {
-        // ShapeA is a Face
-        // Deactive the mode Face
-        TheAISContext()->DeactivateStandardMode (AIS_Shape::SelectionType(4));
-        std::cout<<" Select a vertex\n";
-
-        // Wait for picking
-        Standard_Integer argccc = 5;
-        const char *bufff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-        const char **argvvv = (const char **) bufff;
-        while (ViewerMainLoop( argccc, argvvv) ) { }
-        // end of the loop
-
-        TopoDS_Shape aShapeB;
-        for (TheAISContext()->InitSelected();
-             TheAISContext()->MoreSelected();
-             TheAISContext()->NextSelected())
-        {
-          // A vertex ShapeB can be on Face ShapeA
-          aShapeB = TheAISContext()->SelectedShape();
-        }
-        // Close the local context
-        TheAISContext()->CloseLocalContext(aCurrentIndex);
-
-        // Construction of plane
-        gp_Pnt B = BRep_Tool::Pnt(TopoDS::Vertex(aShapeB));
-
-        TopoDS_Face aFace=TopoDS::Face(aShapeA);
-        BRepAdaptor_Surface aSurface (aFace, Standard_False);
-        if (aSurface.GetType()==GeomAbs_Plane )
-        {
-          gp_Pln aPlane = aSurface.Plane();
-          aPlane.SetLocation(B);
-          Handle(Geom_Plane) aGeomPlane = new Geom_Plane (aPlane);
-          // Construct a plane parallel to aGeomPlane through B
-          Handle(AIS_Plane) anAISPlane = new AIS_Plane (aGeomPlane, B);
-          GetMapOfAIS().Bind (anAISPlane, aName);
-          TheAISContext()->Display(anAISPlane);
-        }
-        else
-        {
-          std::cout<<" vplanepara: error"<<"\n";return 1;
-        }
+        Message::SendFail ("Error: Builded surface is not a plane.");
+        return 1;
       }
     }
 
@@ -1478,165 +1638,70 @@ static Standard_Integer VPlaneBuilder (Draw_Interpretor& /*di*/,
     // test the constructor AIS_Plane::AIS_Plane(Geom_Plane,gp_Pnt,gp_Pnt,gp_Pnt)
     else
     {
-      TheAISContext()->OpenLocalContext();
-      aCurrentIndex = TheAISContext()->IndexOfCurrentLocal();
-
-      // Activate the modes Edge and Face
-      TheAISContext()->ActivateStandardMode (AIS_Shape::SelectionType(2));
-      TheAISContext()->ActivateStandardMode (AIS_Shape::SelectionType(4));
-      std::cout<<" Select a face and an edge coplanar\n";
+      if (aShapes.Extent() != 2)
+      {
+        Message::SendFail ("Error: wrong number of selected shapes.");
+        return 1;
+      }
 
-      // Wait for picking
-      Standard_Integer argcc = 5;
-      const char *buff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-      const char **argvv = (const char **) buff;
-      while (ViewerMainLoop( argcc, argvv) ) { }
-      // end of the loop
+      const TopoDS_Shape* aShapeA = &aShapes.First();
+      const TopoDS_Shape* aShapeB = &aShapes.Last();
 
-      TopoDS_Shape aShapeA;
-      for (TheAISContext()->InitSelected();
-           TheAISContext()->MoreSelected();
-           TheAISContext()->NextSelected())
+      if (aShapeA->ShapeType() != TopAbs_EDGE)
       {
-        aShapeA = TheAISContext()->SelectedShape();
+        std::swap (aShapeA, aShapeB);
       }
 
-      if (aShapeA.ShapeType()==TopAbs_EDGE )
+      if (!(aShapeA->ShapeType() == TopAbs_EDGE
+         && aShapeB->ShapeType() == TopAbs_FACE))
       {
-        // ShapeA is an edge, deactivate the mode Edge...
-        TheAISContext()->DeactivateStandardMode (AIS_Shape::SelectionType(2));
-        std::cout<<" Select a face\n";
-
-        // Wait for picking
-        Standard_Integer argccc = 5;
-        const char *bufff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-        const char **argvvv = (const char **) bufff;
-        while (ViewerMainLoop( argccc, argvvv) ) { }
-        // end of the loop
-
-        TopoDS_Shape aShapeB;
-        for (TheAISContext()->InitSelected();
-             TheAISContext()->MoreSelected();
-             TheAISContext()->NextSelected())
-        {
-          // Edge ShapeA can be on Face ShapeB
-          aShapeB = TheAISContext()->SelectedShape();
-        }
-
-        // Close the local context
-        TheAISContext()->CloseLocalContext(aCurrentIndex);
+        Message::SendFail ("Error: you should select edge and face.");
+        return 1;
+      }
 
-        // Construction of plane
-        TopoDS_Edge anEdgeA = TopoDS::Edge(aShapeA);
-        TopoDS_Vertex aVAa, aVAb;
-        TopExp::Vertices(anEdgeA, aVAa, aVAb);
-        gp_Pnt Aa = BRep_Tool::Pnt(aVAa);
-        gp_Pnt Ab = BRep_Tool::Pnt(aVAb);
-        gp_Vec ab (Aa,Ab);
-
-        gp_Dir Dab (ab);
-        // Creation of rotation axis
-        gp_Ax1 aRotAxis (Aa,Dab);
-
-        TopoDS_Face aFace = TopoDS::Face(aShapeB);
-        // The edge must be parallel to the face
-        BRepExtrema_ExtPF aHeightA (aVAa, aFace);
-        BRepExtrema_ExtPF aHeightB (aVAb, aFace);
-        // Compare to heights
-        if (fabs(sqrt(aHeightA.SquareDistance(1)) - sqrt(aHeightB.SquareDistance(1)))
-            >Precision::Confusion())
-        {
-          // the edge is not parallel to the face
-          std::cout<<" vplaneortho error: the edge is not parallel to the face\n";
-          return 1;
-        }
-        // the edge is OK
-        BRepAdaptor_Surface aSurface (aFace, Standard_False);
-        if (aSurface.GetType()==GeomAbs_Plane)
-        {
-          gp_Pln aPlane = aSurface.Plane();
-          // It rotates a half turn round the axis of rotation
-          aPlane.Rotate(aRotAxis , M_PI/2);
+      // Construction of plane
+      TopoDS_Edge anEdgeA = TopoDS::Edge(*aShapeA);
+      TopoDS_Vertex aVAa, aVAb;
+      TopExp::Vertices(anEdgeA, aVAa, aVAb);
+      gp_Pnt Aa = BRep_Tool::Pnt(aVAa);
+      gp_Pnt Ab = BRep_Tool::Pnt(aVAb);
+      gp_Vec ab (Aa,Ab);
+
+      gp_Dir Dab (ab);
+      // Creation of rotation axis
+      gp_Ax1 aRotAxis (Aa,Dab);
+
+      TopoDS_Face aFace = TopoDS::Face(*aShapeB);
+      // The edge must be parallel to the face
+      BRepExtrema_ExtPF aHeightA (aVAa, aFace);
+      BRepExtrema_ExtPF aHeightB (aVAb, aFace);
+      // Compare to heights
+      if (fabs(sqrt(aHeightA.SquareDistance(1)) - sqrt(aHeightB.SquareDistance(1)))
+          >Precision::Confusion())
+      {
+        // the edge is not parallel to the face
+        Message::SendFail ("Error: the edge is not parallel to the face");
+        return 1;
+      }
+      // the edge is OK
+      BRepAdaptor_Surface aSurface (aFace, Standard_False);
+      if (aSurface.GetType()==GeomAbs_Plane)
+      {
+        gp_Pln aPlane = aSurface.Plane();
+        // It rotates a half turn round the axis of rotation
+        aPlane.Rotate(aRotAxis , M_PI/2);
 
-          Handle(Geom_Plane) aGeomPlane = new Geom_Plane (aPlane);
-          // constructed aGeomPlane parallel to a plane containing the edge (center mid-edge)
-          gp_Pnt aMiddle ((Aa.X()+Ab.X() )/2 ,(Aa.Y()+Ab.Y() )/2 ,(Aa.Z()+Ab.Z() )/2 );
-          Handle(AIS_Plane) anAISPlane = new AIS_Plane (aGeomPlane, aMiddle);
-          GetMapOfAIS().Bind (anAISPlane, aName);
-          TheAISContext()->Display(anAISPlane);
-        }
-        else
-        {
-          std::cout<<" vplaneortho: error\n";
-          return 1;
-        }
+        Handle(Geom_Plane) aGeomPlane = new Geom_Plane (aPlane);
+        // constructed aGeomPlane parallel to a plane containing the edge (center mid-edge)
+        gp_Pnt aMiddle ((Aa.X()+Ab.X() )/2 ,(Aa.Y()+Ab.Y() )/2 ,(Aa.Z()+Ab.Z() )/2 );
+        Handle(AIS_Plane) anAISPlane = new AIS_Plane (aGeomPlane, aMiddle);
+        GetMapOfAIS().Bind (anAISPlane, aName);
+        TheAISContext()->Display (anAISPlane, Standard_True);
       }
       else
       {
-        // ShapeA is a Face, deactive the mode Face.
-        TheAISContext()->DeactivateStandardMode (AIS_Shape::SelectionType(4));
-        std::cout<<" Select an edge\n";
-
-        // Wait for picking
-        Standard_Integer argccc = 5;
-        const char *bufff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-        const char **argvvv = (const char **) bufff;
-        while (ViewerMainLoop( argccc, argvvv) ) { }
-        // end of the loop
-
-        TopoDS_Shape aShapeB;
-        for (TheAISContext()->InitSelected();
-             TheAISContext()->MoreSelected();
-             TheAISContext()->NextSelected())
-        {
-          // Edge ShapeB can be on Face ShapeA
-          aShapeB = TheAISContext()->SelectedShape();
-        }
-        // Close the local context
-        TheAISContext()->CloseLocalContext(aCurrentIndex);
-
-        // Construction of plane
-        TopoDS_Edge anEdgeB = TopoDS::Edge(aShapeB);
-        TopoDS_Vertex aVBa, aVBb;
-        TopExp::Vertices(anEdgeB, aVBa, aVBb);
-        gp_Pnt aBa = BRep_Tool::Pnt(aVBa);
-        gp_Pnt aBb = BRep_Tool::Pnt(aVBb);
-        gp_Vec ab (aBa,aBb);
-        gp_Dir Dab (ab);
-        // Creation of rotation axe
-        gp_Ax1 aRotAxis (aBa,Dab);
-
-        TopoDS_Face aFace = TopoDS::Face(aShapeA);
-        // The edge must be parallel to the face
-        BRepExtrema_ExtPF aHeightA (aVBa, aFace);
-        BRepExtrema_ExtPF aHeightB (aVBb, aFace);
-        // Comparing the two heights
-        if (fabs(sqrt(aHeightA.SquareDistance(1)) - sqrt(aHeightB.SquareDistance(1)))
-            >Precision::Confusion())
-        {
-          // the edge is not parallel to the face
-          std::cout<<" vplaneortho error: the edge is not parallel to the face\n";
-          return 1;
-        }
-        // The edge is OK
-        BRepAdaptor_Surface aSurface (aFace, Standard_False);
-        if (aSurface.GetType()==GeomAbs_Plane)
-        {
-          gp_Pln aPlane = aSurface.Plane();
-          // It rotates a half turn round the axis of rotation
-          aPlane.Rotate(aRotAxis , M_PI/2);
-          Handle(Geom_Plane) aGeomPlane = new Geom_Plane (aPlane);
-          // constructed aGeomPlane parallel to a plane containing the edge theGeomPlane (center mid-edge)
-          gp_Pnt aMiddle ((aBa.X()+aBb.X() )/2 , (aBa.Y()+aBb.Y() )/2 , (aBa.Z()+aBb.Z() )/2 );
-          Handle(AIS_Plane) anAISPlane = new AIS_Plane (aGeomPlane, aMiddle);
-          GetMapOfAIS().Bind (anAISPlane ,aName);
-          TheAISContext()->Display(anAISPlane);
-        }
-        else
-        {
-          std::cout<<" vplaneortho: error\n";
-          return 1;
-        }
+        Message::SendFail ("Error: surface is not Plane");
+        return 1;
       }
     }
   }
@@ -1652,15 +1717,13 @@ static int VChangePlane (Draw_Interpretor& /*theDi*/, Standard_Integer theArgsNb
   Handle(AIS_InteractiveContext) aContextAIS = ViewerTest::GetAISContext();
   if (aContextAIS.IsNull())
   {
-    std::cout << theArgVec[0] << "AIS context is not available.\n";
+    Message::SendFail ("Error: no active viewer.");
     return 1;
   }
 
   if (theArgsNb < 3 || theArgsNb > 11)
   {
-    std::cerr << theArgVec[0] 
-              << ": incorrect number of command arguments.\n"
-              << "Type help for more information.\n";
+    Message::SendFail ("Syntax error: wrong number of arguments.");
     return 1;
   }
 
@@ -1672,9 +1735,7 @@ static int VChangePlane (Draw_Interpretor& /*theDi*/, Standard_Integer theArgsNb
 
   if ( aPlane.IsNull() )
   {
-    std::cout << theArgVec[0] 
-              << ": there is no interactive plane with the given name."
-              << "Type help for more information.\n";
+    Message::SendFail() << "Syntax error: there is no interactive plane with the given name '" << aName << "'.";
     return 1;
   }
 
@@ -1767,11 +1828,8 @@ static int VChangePlane (Draw_Interpretor& /*theDi*/, Standard_Integer theArgsNb
 
 static int VLineBuilder(Draw_Interpretor& di, Standard_Integer argc, const char** argv)
 {
-  Standard_Integer myCurrentIndex;
   // Verifications
-  if (argc!=4 && argc!=8 && argc!=2 )  {di<<"vline error: number of arguments not correct "<<"\n";return 1; }
-  // Fermeture des contextes
-  TheAISContext()->CloseAllContexts();
+  if (argc!=4 && argc!=8 && argc!=2 )  {di<<"vline error: number of arguments not correct \n";return 1; }
 
   // On recupere les parametres
   Handle(AIS_InteractiveObject) theShapeA;
@@ -1780,22 +1838,20 @@ static int VLineBuilder(Draw_Interpretor& di, Standard_Integer argc, const char*
   // Parametres: AIS_Point AIS_Point
   // ===============================
   if (argc==4) {
-    theShapeA=
-      Handle(AIS_InteractiveObject)::DownCast (GetMapOfAIS().Find2(argv[2]));
+    GetMapOfAIS().Find2 (argv[2], theShapeA);
     // On verifie que c'est bien une AIS_Point
     if (!theShapeA.IsNull() &&
       theShapeA->Type()==AIS_KOI_Datum && theShapeA->Signature()==1) {
         // on recupere le deuxieme AIS_Point
-        theShapeB=
-          Handle(AIS_InteractiveObject)::DownCast (GetMapOfAIS().Find2(argv[3]));
-        if (theShapeA.IsNull() ||
+        GetMapOfAIS().Find2 (argv[3], theShapeB);
+        if (theShapeB.IsNull() ||
           (!(theShapeB->Type()==AIS_KOI_Datum && theShapeB->Signature()==1)))
         {
-          di <<"vline error: wrong type of 2de argument."<<"\n";
+          di <<"vline error: wrong type of 2de argument.\n";
           return 1;
         }
       }
-    else {di <<"vline error: wrong type of 1st argument."<<"\n";return 1; }
+    else {di <<"vline error: wrong type of 1st argument.\n";return 1; }
     // Les deux parametres sont du bon type. On verifie que les points ne sont pas confondus
     Handle(AIS_Point) theAISPointA= Handle(AIS_Point)::DownCast (theShapeA);
     Handle(AIS_Point) theAISPointB= Handle(AIS_Point)::DownCast (theShapeB);
@@ -1810,12 +1866,12 @@ static int VLineBuilder(Draw_Interpretor& di, Standard_Integer argc, const char*
 
     if (myCartPointB->X()==myCartPointA->X() && myCartPointB->Y()==myCartPointA->Y() && myCartPointB->Z()==myCartPointA->Z() ) {
       // B=A
-      di<<"vline error: same points"<<"\n";return 1;
+      di<<"vline error: same points\n";return 1;
     }
     // Les deux points sont OK...Construction de l'AIS_Line (en faite, le segment AB)
     Handle(AIS_Line) theAISLine= new AIS_Line(myCartPointA,myCartPointB );
     GetMapOfAIS().Bind(theAISLine,argv[1] );
-    TheAISContext()->Display(theAISLine );
+    TheAISContext()->Display (theAISLine, Standard_True);
 
   }
 
@@ -1836,74 +1892,43 @@ static int VLineBuilder(Draw_Interpretor& di, Standard_Integer argc, const char*
 
     Handle(AIS_Line) theAISLine= new AIS_Line(myCartPointA,myCartPointB );
     GetMapOfAIS().Bind(theAISLine,argv[1] );
-    TheAISContext()->Display(theAISLine );
+    TheAISContext()->Display (theAISLine, Standard_True);
 
   }
 
   // Pas de parametres: Selection dans le viewer.
   // ============================================
 
-  else {
-    TheAISContext()->OpenLocalContext();
-    myCurrentIndex=TheAISContext()->IndexOfCurrentLocal();
-
-    // Active le mode Vertex.
-    TheAISContext()->ActivateStandardMode (AIS_Shape::SelectionType(1) );
-    di<<" Select a vertex "<<"\n";
-
-    // Boucle d'attente waitpick.
-    Standard_Integer argcc = 5;
-    const char *buff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-    const char **argvv = (const char **) buff;
-    while (ViewerMainLoop( argcc, argvv) ) { }
-    // fin de la boucle
-
-    TopoDS_Shape ShapeA;
-    for(TheAISContext()->InitSelected() ;TheAISContext()->MoreSelected() ;TheAISContext()->NextSelected() ) {
-      ShapeA = TheAISContext()->SelectedShape();
+  else
+  {
+    TopTools_ListOfShape aShapes;
+    ViewerTest::GetSelectedShapes (aShapes);
+    if (aShapes.Extent() != 2)
+    {
+      Message::SendFail ("Error: wrong number of selected shapes.");
+      return 1;
     }
 
-    // ShapeA est un Vertex
-    if (ShapeA.ShapeType()==TopAbs_VERTEX ) {
-
-      di<<" Select a different vertex."<<"\n";
-
-      TopoDS_Shape ShapeB;
-      do {
-
-        // Boucle d'attente waitpick.
-        Standard_Integer argccc = 5;
-        const char *bufff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-        const char **argvvv = (const char **) bufff;
-        while (ViewerMainLoop( argccc, argvvv) ) { }
-        // fin de la boucle
-
-        for(TheAISContext()->InitSelected() ;TheAISContext()->MoreSelected() ;TheAISContext()->NextSelected() ) {
-          ShapeB = TheAISContext()->SelectedShape();
-        }
-
-
-      } while(ShapeB.IsSame(ShapeA) );
-
-      // Fermeture du context local
-      TheAISContext()->CloseLocalContext(myCurrentIndex);
+    const TopoDS_Shape& aShapeA = aShapes.First();
+    const TopoDS_Shape& aShapeB = aShapes.Last();
 
-      // Construction de la line
-      gp_Pnt   A=BRep_Tool::Pnt(TopoDS::Vertex(ShapeA)  );
-      gp_Pnt   B=BRep_Tool::Pnt(TopoDS::Vertex(ShapeB)  );
-
-      Handle(Geom_CartesianPoint ) myCartPointA=new Geom_CartesianPoint(A);
-      Handle(Geom_CartesianPoint ) myCartPointB=new Geom_CartesianPoint(B);
+    if (!(aShapeA.ShapeType() == TopAbs_VERTEX
+       && aShapeB.ShapeType() == TopAbs_VERTEX))
+    {
+      Message::SendFail ("Error: you should select two different vertex.");
+      return 1;
+    }
 
-      Handle(AIS_Line) theAISLine= new AIS_Line(myCartPointA,myCartPointB );
-      GetMapOfAIS().Bind(theAISLine,argv[1] );
-      TheAISContext()->Display(theAISLine );
+    // Construction de la line
+    gp_Pnt A = BRep_Tool::Pnt (TopoDS::Vertex (aShapeA));
+    gp_Pnt B = BRep_Tool::Pnt (TopoDS::Vertex (aShapeB));
 
-    }
-    else  {
-      di<<"vline error."<<"\n";
-    }
+    Handle(Geom_CartesianPoint ) myCartPointA=new Geom_CartesianPoint(A);
+    Handle(Geom_CartesianPoint ) myCartPointB=new Geom_CartesianPoint(B);
 
+    Handle(AIS_Line) theAISLine= new AIS_Line(myCartPointA,myCartPointB );
+    GetMapOfAIS().Bind(theAISLine,argv[1] );
+    TheAISContext()->Display (theAISLine, Standard_True);
   }
 
   return 0;
@@ -1932,7 +1957,7 @@ class FilledCircle : public AIS_InteractiveObject
 {
 public:
     // CASCADE RTTI
-    DEFINE_STANDARD_RTTI(FilledCircle, AIS_InteractiveObject); 
+    DEFINE_STANDARD_RTTI_INLINE(FilledCircle,AIS_InteractiveObject); 
 
     FilledCircle(gp_Pnt theCenter, Standard_Real theRadius);
     FilledCircle(Handle(Geom_Circle) theCircle);
@@ -1943,10 +1968,10 @@ private:
     // Virtual methods implementation
     void Compute (  const Handle(PrsMgr_PresentationManager3d)& thePresentationManager,
                   const Handle(Prs3d_Presentation)& thePresentation,
-                  const Standard_Integer theMode);
+                  const Standard_Integer theMode) Standard_OVERRIDE;
 
     void ComputeSelection (  const Handle(SelectMgr_Selection)& theSelection, 
-                           const Standard_Integer theMode);
+                           const Standard_Integer theMode) Standard_OVERRIDE;
 
 protected:
     Handle(Geom_Circle) myCircle;
@@ -2002,8 +2027,7 @@ void FilledCircle::ComputeSelection(const Handle(SelectMgr_Selection) &theSelect
                                     const Standard_Integer /*theMode*/)
 {
   Handle(SelectMgr_EntityOwner) anEntityOwner = new SelectMgr_EntityOwner(this);
-  Handle(Select3D_SensitiveCircle) aSensitiveCircle = new Select3D_SensitiveCircle(anEntityOwner, 
-      myCircle, myFilledStatus);
+  Handle(Select3D_SensitiveCircle) aSensitiveCircle = new Select3D_SensitiveCircle (anEntityOwner, myCircle->Circ(), myFilledStatus);
   theSelection->Add(aSensitiveCircle);
 }
 
@@ -2038,9 +2062,7 @@ void DisplayCircle (Handle (Geom_Circle) theGeomCircle,
   // and remove it from context
   if (GetMapOfAIS().IsBound2(theName)) 
   {
-    Handle(Standard_Transient) anObj = GetMapOfAIS().Find2(theName);
-    Handle(AIS_InteractiveObject) anInterObj = 
-         Handle(AIS_InteractiveObject)::DownCast(anObj);
+    Handle(AIS_InteractiveObject) anInterObj = GetMapOfAIS().Find2(theName);
     TheAISContext()->Remove(anInterObj, Standard_False);
     GetMapOfAIS().UnBind2(theName);
    }
@@ -2049,36 +2071,29 @@ void DisplayCircle (Handle (Geom_Circle) theGeomCircle,
    GetMapOfAIS().Bind(aCircle, theName);
 
    // Display the circle
-   TheAISContext()->Display(aCircle);
+   TheAISContext()->Display (aCircle, Standard_True);
   
 }
 
 static int VCircleBuilder(Draw_Interpretor& /*di*/, Standard_Integer argc, const char** argv)
 {
-  Standard_Integer myCurrentIndex;
   // Verification of the arguments
   if (argc>6 || argc<2) 
   { 
-    std::cout << "vcircle error: expect 4 arguments.\n"; 
-    return 1; // TCL_ERROR 
+    Message::SendFail ("Syntax error: wrong number of arguments");
+    return 1;
   }
-  TheAISContext()->CloseAllContexts();
 
   // There are all arguments
   if (argc == 6) 
   {
     // Get arguments
     TCollection_AsciiString aName(argv[1]);
-    Standard_Boolean isFilled = (Standard_Boolean)Draw::Atoi(argv[5]);
-
-    Handle(AIS_InteractiveObject) theShapeA;
-    Handle(AIS_InteractiveObject) theShapeB;
-
-    theShapeA =
-      Handle(AIS_InteractiveObject)::DownCast(GetMapOfAIS().Find2(argv[2]));
-    theShapeB =
-      Handle(AIS_InteractiveObject)::DownCast(GetMapOfAIS().Find2(argv[3]));
+    Standard_Boolean isFilled = Draw::Atoi(argv[5]) != 0;
 
+    Handle(AIS_InteractiveObject) theShapeA, theShapeB;
+    GetMapOfAIS().Find2 (argv[2], theShapeA);
+    GetMapOfAIS().Find2 (argv[3], theShapeB);
 
     // Arguments: AIS_Point AIS_Point AIS_Point
     // ========================================
@@ -2087,17 +2102,17 @@ static int VCircleBuilder(Draw_Interpretor& /*di*/, Standard_Integer argc, const
     {
       if (theShapeB->Type()!=AIS_KOI_Datum || theShapeB->Signature()!=1 ) 
       {
-        std::cout << "vcircle error: 2d argument is unexpected to be a point.\n";
-        return 1; // TCL_ERROR 
+        Message::SendFail ("Error: 2d argument is unexpected to be a point");
+        return 1;
       }
       // The third object must be a point
-      Handle(AIS_InteractiveObject) theShapeC =
-        Handle(AIS_InteractiveObject)::DownCast(GetMapOfAIS().Find2(argv[4]));
+      Handle(AIS_InteractiveObject) theShapeC;
+      GetMapOfAIS().Find2 (argv[4], theShapeC);
       if (theShapeC.IsNull() ||
         theShapeC->Type()!=AIS_KOI_Datum || theShapeC->Signature()!=1 ) 
       {
-        std::cout << "vcircle error: 3d argument is unexpected to be a point.\n";
-        return 1; // TCL_ERROR 
+        Message::SendFail ("Error: 3d argument is unexpected to be a point");
+        return 1;
       }
         // tag
         // Verify that the three points are different
@@ -2122,24 +2137,24 @@ static int VCircleBuilder(Draw_Interpretor& /*di*/, Standard_Integer argc, const
             Abs(myCartPointA->Y()-myCartPointB->Y()) <= Precision::Confusion() && 
             Abs(myCartPointA->Z()-myCartPointB->Z()) <= Precision::Confusion() ) 
         {
-          std::cout << "vcircle error: Same points.\n"; 
-          return 1; // TCL_ERROR 
+          Message::SendFail ("Error: Same points");
+          return 1;
         }
         // Test A=C
         if (Abs(myCartPointA->X()-myCartPointC->X()) <= Precision::Confusion() &&
             Abs(myCartPointA->Y()-myCartPointC->Y()) <= Precision::Confusion() && 
             Abs(myCartPointA->Z()-myCartPointC->Z()) <= Precision::Confusion() ) 
         {
-          std::cout << "vcircle error: Same points.\n"; 
-          return 1; // TCL_ERROR 
+          Message::SendFail ("Error: Same points");
+          return 1;
         }
         // Test B=C
         if (Abs(myCartPointB->X()-myCartPointC->X()) <= Precision::Confusion() && 
             Abs(myCartPointB->Y()-myCartPointC->Y()) <= Precision::Confusion() && 
             Abs(myCartPointB->Z()-myCartPointC->Z()) <= Precision::Confusion() ) 
         {
-          std::cout << "vcircle error: Same points.\n"; 
-          return 1;// TCL_ERROR 
+          Message::SendFail ("Error: Same points");
+          return 1;
         }
         // Construction of the circle
         GC_MakeCircle Cir = GC_MakeCircle (myCartPointA->Pnt(), 
@@ -2149,12 +2164,12 @@ static int VCircleBuilder(Draw_Interpretor& /*di*/, Standard_Integer argc, const
         {
           theGeomCircle = Cir.Value();
         }
-        catch (StdFail_NotDone)
+        catch (StdFail_NotDone const&)
         {
-          std::cout << "vcircle error: can't create circle\n";
-          return -1; // TCL_ERROR
+          Message::SendFail ("Error: can't create circle");
+          return -1;
         }
-        
+
         DisplayCircle(theGeomCircle, aName, isFilled);
     }
 
@@ -2166,14 +2181,14 @@ static int VCircleBuilder(Draw_Interpretor& /*di*/, Standard_Integer argc, const
       if (theShapeB->Type() != AIS_KOI_Datum || 
         theShapeB->Signature() != 1 ) 
       {
-        std::cout << "vcircle error: 2d element is a unexpected to be a point.\n"; 
-        return 1; // TCL_ERROR 
+        Message::SendFail ("Error: 2d element is a unexpected to be a point");
+        return 1;
       }
       // Check that the radius is >= 0
       if (Draw::Atof(argv[4]) <= 0 ) 
       {
-        std::cout << "vcircle error: the radius must be >=0.\n"; 
-        return 1; // TCL_ERROR 
+        Message::SendFail ("Syntax error: the radius must be >=0");
+        return 1;
       }
 
       // Recover the normal to the plane
@@ -2196,10 +2211,10 @@ static int VCircleBuilder(Draw_Interpretor& /*di*/, Standard_Integer argc, const
       {
         theGeomCircle = Cir.Value();
       }
-      catch (StdFail_NotDone)
+      catch (StdFail_NotDone const&)
       {
-        std::cout << "vcircle error: can't create circle\n";
-        return -1; // TCL_ERROR
+        Message::SendFail ("Error: can't create circle");
+        return -1;
       }
 
       DisplayCircle(theGeomCircle, aName, isFilled);
@@ -2209,8 +2224,8 @@ static int VCircleBuilder(Draw_Interpretor& /*di*/, Standard_Integer argc, const
     // Error
     else
     {
-      std::cout << "vcircle error: 1st argument is a unexpected type.\n"; 
-      return 1; // TCL_ERROR 
+      Message::SendFail ("Error: 1st argument has an unexpected type");
+      return 1;
     }
 
   }
@@ -2221,85 +2236,40 @@ static int VCircleBuilder(Draw_Interpretor& /*di*/, Standard_Integer argc, const
     // Get the name of the circle 
     TCollection_AsciiString aName(argv[1]);
 
-    TheAISContext()->OpenLocalContext();
-    myCurrentIndex = TheAISContext()->IndexOfCurrentLocal();
-
-    // Activate selection mode for vertices and faces
-    TheAISContext()->ActivateStandardMode (AIS_Shape::SelectionType(1) );
-    TheAISContext()->ActivateStandardMode (AIS_Shape::SelectionType(4) );
-    std::cout << " Select a vertex or a face\n";
-
-    // Wait for picking
-    Standard_Integer argcc = 5;
-    const char *buff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-    const char **argvv = (const char **) buff;
-    while (ViewerMainLoop( argcc, argvv) ) { }
-    // end of the loop
-
-    TopoDS_Shape ShapeA;
-    for(TheAISContext()->InitSelected(); 
-      TheAISContext()->MoreSelected(); 
-      TheAISContext()->NextSelected() ) 
+    TopTools_ListOfShape aShapes;
+    ViewerTest::GetSelectedShapes (aShapes);
+    if (aShapes.Extent() != 3 && aShapes.Extent() != 2)
     {
-      ShapeA = TheAISContext()->SelectedShape();
+      Message::SendFail ("Error: Wrong number of selected shapes.");
+      return 1;
     }
 
-    // ShapeA is a Vertex
-    if (ShapeA.ShapeType() == TopAbs_VERTEX ) 
+    const TopoDS_Shape& aShapeA = aShapes.First();
+    if (aShapeA.ShapeType() == TopAbs_VERTEX ) 
     {
-      TheAISContext()->DeactivateStandardMode (AIS_Shape::SelectionType(4) );
-      std::cout << " Select a different vertex\n";
-
-      TopoDS_Shape ShapeB;
-      do 
+      if (aShapes.Extent() != 3)
       {
-        // Wait for picking
-        Standard_Integer argccc = 5;
-        const char *bufff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-        const char **argvvv = (const char **) bufff;
-        while (ViewerMainLoop( argccc, argvvv) ) { }
-        // end of the loop
+        Message::SendFail ("Error: wrong number of selected shapes.");
+        return 1;
+      }
 
-        for(TheAISContext()->InitSelected(); 
-          TheAISContext()->MoreSelected(); 
-          TheAISContext()->NextSelected() ) 
-        {
-          ShapeB = TheAISContext()->SelectedShape();
-        }
-      } while(ShapeB.IsSame(ShapeA) );
+      TopTools_ListOfShape::Iterator anIter (aShapes);
 
-      // Selection of ShapeC
-      std::cout << " Select the last vertex\n";
-      TopoDS_Shape ShapeC;
-      do 
-      {
-        // Wait for picking
-        Standard_Integer argcccc = 5;
-        const char *buffff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-        const char **argvvvv = (const char **) buffff;
-        while (ViewerMainLoop( argcccc, argvvvv) ) { }
-        // end of the loop
+      anIter.Next();
+      const TopoDS_Shape& aShapeB = anIter.Value();
 
-        for(TheAISContext()->InitSelected(); 
-          TheAISContext()->MoreSelected(); 
-          TheAISContext()->NextSelected() ) 
-        {
-          ShapeC = TheAISContext()->SelectedShape();
-        }
-      } while(ShapeC.IsSame(ShapeA) || ShapeC.IsSame(ShapeB) );
+      anIter.Next();
+      const TopoDS_Shape& aShapeC = anIter.Value();
       
       // Get isFilled
       Standard_Boolean isFilled;
       std::cout << "Enter filled status (0 or 1)\n";
-      cin >> isFilled;
-
-      // Close the local context
-      TheAISContext()->CloseLocalContext(myCurrentIndex);
+      std::cin >> isFilled;
 
       // Construction of the circle
-      gp_Pnt A = BRep_Tool::Pnt(TopoDS::Vertex(ShapeA));
-      gp_Pnt B = BRep_Tool::Pnt(TopoDS::Vertex(ShapeB));
-      gp_Pnt C = BRep_Tool::Pnt(TopoDS::Vertex(ShapeC));
+      gp_Pnt A = BRep_Tool::Pnt (TopoDS::Vertex (aShapeA));
+      gp_Pnt B = BRep_Tool::Pnt (TopoDS::Vertex (aShapeB));
+      gp_Pnt C = BRep_Tool::Pnt (TopoDS::Vertex (aShapeC));
 
       GC_MakeCircle Cir = GC_MakeCircle (A, B, C);
       Handle (Geom_Circle) theGeomCircle;
@@ -2307,55 +2277,34 @@ static int VCircleBuilder(Draw_Interpretor& /*di*/, Standard_Integer argc, const
       {
         theGeomCircle = Cir.Value();
       }
-      catch (StdFail_NotDone)
+      catch (StdFail_NotDone const&)
       {
-        std::cout << "vcircle error: can't create circle\n";
-        return -1; // TCL_ERROR
+        Message::SendFail ("Error: can't create circle");
+        return -1;
       }
 
       DisplayCircle(theGeomCircle, aName, isFilled);
 
     }
-    // Shape is a face
-    else
+    else if (aShapeA.ShapeType() == TopAbs_FACE)
     {
-      std::cout << " Select a vertex (in your face)\n";
-      TheAISContext()->DeactivateStandardMode (AIS_Shape::SelectionType(4) );
-
-      TopoDS_Shape ShapeB;
-      // Wait for picking
-      Standard_Integer argccc = 5;
-      const char *bufff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-      const char **argvvv = (const char **) bufff;
-      while (ViewerMainLoop( argccc, argvvv) ) { }
-      // end of the loop
-
-      for(TheAISContext()->InitSelected(); 
-        TheAISContext()->MoreSelected(); 
-        TheAISContext()->NextSelected() ) 
-      {
-        ShapeB = TheAISContext()->SelectedShape();
-      }
+      const TopoDS_Shape& aShapeB = aShapes.Last();
 
       // Recover the radius 
       Standard_Real theRad;
       do 
       {
         std::cout << " Enter the value of the radius:\n";
-        cin >> theRad;
+        std::cin >> theRad;
       } while (theRad <= 0);
       
       // Get filled status
       Standard_Boolean isFilled;
       std::cout << "Enter filled status (0 or 1)\n";
-      cin >> isFilled;
-
-      // Close the local context
-      TheAISContext()->CloseLocalContext(myCurrentIndex);
-      // Construction of the circle
+      std::cin >> isFilled;
 
       // Recover the normal to the plane. tag
-      TopoDS_Face myFace = TopoDS::Face(ShapeA);
+      TopoDS_Face myFace = TopoDS::Face(aShapeA);
       BRepAdaptor_Surface mySurface (myFace, Standard_False);
       gp_Pln myPlane = mySurface.Plane();
       Handle(Geom_Plane) theGeomPlane = new Geom_Plane (myPlane);
@@ -2364,7 +2313,7 @@ static int VCircleBuilder(Draw_Interpretor& /*di*/, Standard_Integer argc, const
       gp_Dir theDir = thegpAxe.Direction();
 
       // Recover the center
-      gp_Pnt theCenter = BRep_Tool::Pnt(TopoDS::Vertex(ShapeB));
+      gp_Pnt theCenter = BRep_Tool::Pnt (TopoDS::Vertex (aShapeB));
 
       // Construct the circle
       GC_MakeCircle Cir = GC_MakeCircle (theCenter, theDir ,theRad);
@@ -2373,16 +2322,19 @@ static int VCircleBuilder(Draw_Interpretor& /*di*/, Standard_Integer argc, const
       {
         theGeomCircle = Cir.Value();
       }
-      catch (StdFail_NotDone)
+      catch (StdFail_NotDone const&)
       {
-        std::cout << "vcircle error: can't create circle\n";
-        return -1; // TCL_ERROR
+        Message::SendFail ("Error: can't create circle");
+        return -1;
       }
 
       DisplayCircle(theGeomCircle, aName, isFilled);
-      
     }
-
+    else
+    {
+      Message::SendFail ("Error: You should select face and vertex or three vertices.");
+      return 1;
+    }
   }
 
   return 0;
@@ -2399,13 +2351,13 @@ static int VDrawText (Draw_Interpretor& theDI,
   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
   if (theArgsNb < 3)
   {
-    std::cout << "Error: wrong number of arguments! See usage:\n";
+    Message::SendFail ("Syntax error: wrong number of arguments. See usage:");
     theDI.PrintHelp (theArgVec[0]);
     return 1;
   }
   else if (aContext.IsNull())
   {
-    std::cout << "Error: no active view!\n";
+    Message::SendFail ("Error: no active viewer");
     return 1;
   }
 
@@ -2415,23 +2367,24 @@ static int VDrawText (Draw_Interpretor& theDI,
   Handle(AIS_TextLabel)      aTextPrs;
   ViewerTest_AutoUpdater     anAutoUpdater (aContext, ViewerTest::CurrentView());
 
+  Standard_Boolean isNewPrs = Standard_False;
   if (GetMapOfAIS().IsBound2 (aName))
   {
-    aTextPrs  = Handle(AIS_TextLabel)::DownCast (GetMapOfAIS().Find2 (aName));
+    aTextPrs = Handle(AIS_TextLabel)::DownCast (GetMapOfAIS().Find2 (aName));
   }
-  else
+
+  if (aTextPrs.IsNull())
   {
+    isNewPrs = Standard_True;
     aTextPrs = new AIS_TextLabel();
     aTextPrs->SetFont ("Courier");
   }
 
   aTextPrs->SetText (aText);
 
-  Graphic3d_TransModeFlags aTrsfPersFlags = Graphic3d_TMF_None;
-  gp_Pnt aTPPosition;
+  Handle(Graphic3d_TransformPers) aTrsfPers;
   Aspect_TypeOfDisplayText aDisplayType = Aspect_TODT_NORMAL;
 
-
   Standard_Boolean aHasPlane = Standard_False;
   gp_Dir           aNormal;
   gp_Dir           aDirection;
@@ -2451,7 +2404,7 @@ static int VDrawText (Draw_Interpretor& theDI,
     {
       if (anArgIt + 3 >= theArgsNb)
       {
-        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
+        Message::SendFail() << "Error: wrong number of values for parameter '" << aParam << "'";
         return 1;
       }
 
@@ -2462,48 +2415,23 @@ static int VDrawText (Draw_Interpretor& theDI,
     }
     else if (aParam == "-color")
     {
-      if (anArgIt + 1 >= theArgsNb)
-      {
-        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
-        return 1;
-      }
-
-      TCollection_AsciiString aColor (theArgVec[anArgIt + 1]);
-      Quantity_NameOfColor aNameOfColor = Quantity_NOC_BLACK;
-      if (Quantity_Color::ColorFromName (aColor.ToCString(), aNameOfColor))
-      {
-        anArgIt += 1;
-        aTextPrs->SetColor (aNameOfColor);
-        continue;
-      }
-      else if (anArgIt + 3 >= theArgsNb)
-      {
-        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
-        return 1;
-      }
-
-      TCollection_AsciiString aGreen (theArgVec[anArgIt + 2]);
-      TCollection_AsciiString aBlue  (theArgVec[anArgIt + 3]);
-      if (!aColor.IsRealValue()
-       || !aGreen.IsRealValue()
-       || !aBlue.IsRealValue())
+      Quantity_Color aColor;
+      Standard_Integer aNbParsed = ViewerTest::ParseColor (theArgsNb - anArgIt - 1,
+                                                           theArgVec + anArgIt + 1,
+                                                           aColor);
+      if (aNbParsed == 0)
       {
-        std::cout << "Error: wrong syntax at '" << aParam.ToCString() << "'.\n";
+        Message::SendFail() << "Syntax error at '" << aParam << "'";
         return 1;
       }
-
-      const Graphic3d_Vec3d anRGB (aColor.RealValue(),
-                                   aGreen.RealValue(),
-                                   aBlue.RealValue());
-
-      aTextPrs->SetColor (Quantity_Color (anRGB.r(), anRGB.g(), anRGB.b(), Quantity_TOC_RGB));
-      anArgIt += 3;
+      anArgIt += aNbParsed;
+      aTextPrs->SetColor (aColor);
     }
     else if (aParam == "-halign")
     {
       if (++anArgIt >= theArgsNb)
       {
-        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
+        Message::SendFail() << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'";
         return 1;
       }
 
@@ -2523,7 +2451,7 @@ static int VDrawText (Draw_Interpretor& theDI,
       }
       else
       {
-        std::cout << "Error: wrong syntax at '" << aParam.ToCString() << "'.\n";
+        Message::SendFail() << "Syntax error at '" << aParam << "'";
         return 1;
       }
     }
@@ -2531,7 +2459,7 @@ static int VDrawText (Draw_Interpretor& theDI,
     {
       if (++anArgIt >= theArgsNb)
       {
-        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
+        Message::SendFail() << "Syntax error: wrong number of values for parameter '" << aParam << "'";
         return 1;
       }
 
@@ -2555,7 +2483,7 @@ static int VDrawText (Draw_Interpretor& theDI,
       }
       else
       {
-        std::cout << "Error: wrong syntax at '" << aParam.ToCString() << "'.\n";
+        Message::SendFail() << "Syntax error at '" << aParam << "'";
         return 1;
       }
     }
@@ -2563,7 +2491,7 @@ static int VDrawText (Draw_Interpretor& theDI,
     {
       if (++anArgIt >= theArgsNb)
       {
-        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
+        Message::SendFail() << "Syntax error: wrong number of values for parameter '" << aParam << "'";
         return 1;
       }
 
@@ -2573,7 +2501,7 @@ static int VDrawText (Draw_Interpretor& theDI,
     {
       if (++anArgIt >= theArgsNb)
       {
-        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
+        Message::SendFail() << "Syntax error: wrong number of values for parameter '" << aParam << "'";
         return 1;
       }
 
@@ -2583,7 +2511,7 @@ static int VDrawText (Draw_Interpretor& theDI,
     {
       if (++anArgIt >= theArgsNb)
       {
-        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
+        Message::SendFail() << "Syntax error: wrong number of values for parameter '" << aParam << "'";
         return 1;
       }
 
@@ -2593,34 +2521,25 @@ static int VDrawText (Draw_Interpretor& theDI,
     {
       if (++anArgIt >= theArgsNb)
       {
-        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
+        Message::SendFail() << "Syntax error: wrong number of values for parameter '" << aParam << "'";
         return 1;
       }
 
       TCollection_AsciiString anOption (theArgVec[anArgIt]);
       anOption.LowerCase();
-      if (anOption.IsEqual ("regular"))
-      {
-        aTextPrs->SetFontAspect (Font_FA_Regular);
-      }
-      else if (anOption.IsEqual ("bold"))
+      Font_FontAspect aFontAspect = Font_FA_Undefined;
+      if (!parseFontStyle (anOption, aFontAspect))
       {
-        aTextPrs->SetFontAspect (Font_FA_Bold);
-      }
-      else if (anOption.IsEqual ("italic"))
-      {
-        aTextPrs->SetFontAspect (Font_FA_Italic);
-      }
-      else if (anOption.IsEqual ("bolditalic"))
-      {
-        aTextPrs->SetFontAspect (Font_FA_BoldItalic);
+        Message::SendFail() << "Syntax error: unknown font aspect '" << anOption << "'";
+        return 1;
       }
+      aTextPrs->SetFontAspect (aFontAspect);
     }
     else if (aParam == "-font")
     {
       if (++anArgIt >= theArgsNb)
       {
-        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
+        Message::SendFail() << "Syntax error: wrong number of values for parameter '" << aParam << "'";
         return 1;
       }
 
@@ -2630,7 +2549,7 @@ static int VDrawText (Draw_Interpretor& theDI,
     {
       if (anArgIt + 6 >= theArgsNb)
       {
-        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
+        Message::SendFail() << "Syntax error: wrong number of values for parameter '" << aParam << "'";
         return 1;
       }
 
@@ -2646,12 +2565,25 @@ static int VDrawText (Draw_Interpretor& theDI,
 
       aHasPlane = Standard_True;
     }
+    else if (aParam == "-flipping")
+    {
+      aTextPrs->SetFlipping (Standard_True);
+    }
+    else if (aParam == "-ownanchor")
+    {
+      if (++anArgIt >= theArgsNb)
+      {
+        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
+        return 1;
+      }
+      aTextPrs->SetOwnAnchorPoint (Draw::Atoi (theArgVec[anArgIt]) == 1);
+    }
     else if (aParam == "-disptype"
           || aParam == "-displaytype")
     {
       if (++anArgIt >= theArgsNb)
       {
-        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
+        Message::SendFail() << "Syntax error: wrong number of values for parameter '" << aParam << "'";
         return 1;
       }
       TCollection_AsciiString aType (theArgVec[anArgIt]);
@@ -2666,62 +2598,39 @@ static int VDrawText (Draw_Interpretor& theDI,
         aDisplayType = Aspect_TODT_DIMENSION;
       else if (aType == "normal")
         aDisplayType = Aspect_TODT_NORMAL;
+      else if (aType == "shadow")
+        aDisplayType = Aspect_TODT_SHADOW;
       else
       {
-        std::cout << "Error: wrong display type '" << aType << "'.\n";
+        Message::SendFail() << "Syntax error: wrong display type '" << aType << "'";
         return 1;
       }
     }
     else if (aParam == "-subcolor"
           || aParam == "-subtitlecolor")
     {
-      if (anArgIt + 1 >= theArgsNb)
-      {
-        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
-        return 1;
-      }
-
-      TCollection_AsciiString aColor (theArgVec[anArgIt + 1]);
-      Quantity_NameOfColor aNameOfColor = Quantity_NOC_BLACK;
-      if (Quantity_Color::ColorFromName (aColor.ToCString(), aNameOfColor))
-      {
-        anArgIt += 1;
-        aTextPrs->SetColorSubTitle (aNameOfColor);
-        continue;
-      }
-      else if (anArgIt + 3 >= theArgsNb)
-      {
-        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
-        return 1;
-      }
-
-      TCollection_AsciiString aGreen (theArgVec[anArgIt + 2]);
-      TCollection_AsciiString aBlue  (theArgVec[anArgIt + 3]);
-      if (!aColor.IsRealValue()
-       || !aGreen.IsRealValue()
-       || !aBlue.IsRealValue())
+      Quantity_Color aColor;
+      Standard_Integer aNbParsed = ViewerTest::ParseColor (theArgsNb - anArgIt - 1,
+                                                           theArgVec + anArgIt + 1,
+                                                           aColor);
+      if (aNbParsed == 0)
       {
-        std::cout << "Error: wrong syntax at '" << aParam.ToCString() << "'.\n";
+        Message::SendFail() << "Syntax error at '" << aParam << "'";
         return 1;
       }
-
-      const Graphic3d_Vec3d anRGB (aColor.RealValue(),
-                                   aGreen.RealValue(),
-                                   aBlue.RealValue());
-
-      aTextPrs->SetColorSubTitle (Quantity_Color (anRGB.r(), anRGB.g(), anRGB.b(), Quantity_TOC_RGB));
-      anArgIt += 3;
+      anArgIt += aNbParsed;
+      aTextPrs->SetColorSubTitle (aColor);
     }
     else if (aParam == "-2d")
     {
-      aTrsfPersFlags = Graphic3d_TMF_2d;
+      aTrsfPers = new Graphic3d_TransformPers (Graphic3d_TMF_2d);
     }
     else if (aParam == "-trsfperspos"
           || aParam == "-perspos")
     {
       if (anArgIt + 2 >= theArgsNb)
       {
-        std::cerr << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
+        Message::SendFail() << "Error: wrong number of values for parameter '" << aParam << "'.";
         return 1;
       }
 
@@ -2731,7 +2640,7 @@ static int VDrawText (Draw_Interpretor& theDI,
       if (!aX.IsIntegerValue()
        || !aY.IsIntegerValue())
       {
-        std::cerr << "Error: wrong syntax at '" << aParam << "'.\n";
+        Message::SendFail() << "Error: wrong syntax at '" << aParam << "'.";
         return 1;
       }
       if (anArgIt + 1 < theArgsNb)
@@ -2743,11 +2652,12 @@ static int VDrawText (Draw_Interpretor& theDI,
           ++anArgIt;
         }
       }
-      aTPPosition.SetCoord (aX.IntegerValue(), aY.IntegerValue(), aZ.IntegerValue());
+
+      aTrsfPers = Graphic3d_TransformPers::FromDeprecatedParams (Graphic3d_TMF_2d, gp_Pnt (aX.IntegerValue(), aY.IntegerValue(), aZ.IntegerValue()));
     }
     else
     {
-      std::cout << "Error: unknown argument '" << aParam << "'\n";
+      Message::SendFail() << "Syntax error: unknown argument '" << aParam << "'";
       return 1;
     }
   }
@@ -2757,22 +2667,30 @@ static int VDrawText (Draw_Interpretor& theDI,
     aTextPrs->SetOrientation3D (gp_Ax2 (aPos, aNormal, aDirection));
   }
 
-  if (aTrsfPersFlags != Graphic3d_TMF_None)
+  aTextPrs->SetDisplayType (aDisplayType);
+
+  if (!aTrsfPers.IsNull())
   {
-    aTextPrs->SetTransformPersistence (aTrsfPersFlags, aTPPosition);
-    aTextPrs->SetDisplayType (aDisplayType);
+    aContext->SetTransformPersistence (aTextPrs, aTrsfPers);
     aTextPrs->SetZLayer(Graphic3d_ZLayerId_TopOSD);
     if (aTextPrs->Position().Z() != 0)
     {
       aTextPrs->SetPosition (gp_Pnt(aTextPrs->Position().X(), aTextPrs->Position().Y(), 0));
     }
   }
-  else if (aTrsfPersFlags != aTextPrs->TransformPersistence().Flags)
+  else if (!aTextPrs->TransformPersistence().IsNull())
+  {
+    aContext->SetTransformPersistence (aTextPrs, Handle(Graphic3d_TransformPers)());
+  }
+
+  if (isNewPrs)
+  {
+    ViewerTest::Display (aName, aTextPrs, Standard_False);
+  }
+  else
   {
-    aTextPrs->SetTransformPersistence (aTrsfPersFlags);
-    aTextPrs->SetDisplayType (Aspect_TODT_NORMAL);
+    aContext->Redisplay (aTextPrs, Standard_False, Standard_True);
   }
-  ViewerTest::Display (aName, aTextPrs, Standard_False);
   return 0;
 }
 
@@ -2804,7 +2722,6 @@ static int VDrawText (Draw_Interpretor& theDI,
 #include <TopoDS_Shape.hxx>
 #include <TopExp_Explorer.hxx>
 #include <TopAbs.hxx>
-#include <StdSelect_ShapeTypeFilter.hxx>
 #include <AIS_InteractiveObject.hxx>
 
 
@@ -3048,13 +2965,13 @@ static int VDrawSphere (Draw_Interpretor& /*di*/, Standard_Integer argc, const c
   Handle(AIS_InteractiveContext) aContextAIS = ViewerTest::GetAISContext();
   if (aContextAIS.IsNull())
   {
-    std::cout << "Call vinit before!\n";
+    Message::SendFail ("Error: no active viewer");
     return 1;
   }
   else if (argc < 3)
   {
-    std::cout << "Use: " << argv[0]
-              << " shapeName Fineness [X=0.0 Y=0.0 Z=0.0] [Radius=100.0] [ToShowEdges=0]\n";
+    Message::SendFail() << "Syntax error: wrong number of arguments.\n"
+                        << "Use: " << argv[0] << " shapeName Fineness [X=0.0 Y=0.0 Z=0.0] [Radius=100.0] [ToShowEdges=0]";
     return 1;
   }
 
@@ -3082,20 +2999,13 @@ static int VDrawSphere (Draw_Interpretor& /*di*/, Standard_Integer argc, const c
 
   // stupid initialization of Green color in RGBA space as integer
   // probably wrong for big-endian CPUs
-  Standard_Integer aRed    = 0;
-  Standard_Integer aGreen  = 255;
-  Standard_Integer aBlue   = 0;
-  Standard_Integer anAlpha = 0; // not used
-  Standard_Integer aColorInt = aRed;
-  aColorInt += aGreen  << 8;
-  aColorInt += aBlue   << 16;
-  aColorInt += anAlpha << 24;
+  const Graphic3d_Vec4ub aColor (0, 255, 0, 0);
 
   // setup colors array per vertex
   Handle(TColStd_HArray1OfInteger) aColorArray = new TColStd_HArray1OfInteger (1, aNumberPoints);
   for (Standard_Integer aNodeId = 1; aNodeId <= aNumberPoints; ++aNodeId)
   {
-    aColorArray->SetValue (aNodeId, aColorInt);
+    aColorArray->SetValue (aNodeId, *reinterpret_cast<const Standard_Integer*> (aColor.GetData()));
   }
   aShape->SetColors (aColorArray);
 
@@ -3123,8 +3033,8 @@ static int VDrawSphere (Draw_Interpretor& /*di*/, Standard_Integer argc, const c
 
   // Setting material properties, very important for desirable visual result!
   Graphic3d_MaterialAspect aMat (Graphic3d_NOM_PLASTIC);
-  aMat.SetAmbient (0.2);
-  aMat.SetSpecular (0.5);
+  aMat.SetAmbientColor (Quantity_Color (Graphic3d_Vec3 (0.04f)));
+  aMat.SetSpecularColor(Quantity_Color (Graphic3d_Vec3 (0.50f)));
   Handle(Graphic3d_AspectFillArea3d) anAspect
     = new Graphic3d_AspectFillArea3d (Aspect_IS_SOLID,
                                       Quantity_NOC_RED,
@@ -3134,14 +3044,7 @@ static int VDrawSphere (Draw_Interpretor& /*di*/, Standard_Integer argc, const c
                                       aMat,
                                       aMat);
   Handle(Prs3d_ShadingAspect) aShAsp = new Prs3d_ShadingAspect();
-  if (toShowEdges)
-  {
-    anAspect->SetEdgeOn();
-  }
-  else
-  {
-    anAspect->SetEdgeOff();
-  }
+  anAspect->SetDrawEdges (toShowEdges);
   aShAsp->SetAspect (anAspect);
   aShape->Attributes()->SetShadingAspect (aShAsp);
 
@@ -3154,79 +3057,23 @@ static int VDrawSphere (Draw_Interpretor& /*di*/, Standard_Integer argc, const c
 //purpose  :
 //=============================================================================
 
-static int VComputeHLR (Draw_Interpretor& di,
-                        Standard_Integer argc,
-                        const char** argv)
+static int VComputeHLR (Draw_Interpretor& ,
+                        Standard_Integer theArgNb,
+                        const char** theArgVec)
 {
-  Handle(AIS_InteractiveContext) aContextAIS = ViewerTest::GetAISContext ();
-
-  if (aContextAIS.IsNull ())
-  {
-    di << "Please call vinit before\n";
-    return 1;
-  }
-
-  if ( argc != 3 &&  argc != 12 )
-  {
-    di << "Usage: " << argv[0] << " ShapeName HlrName "
-       << "[ eye_x eye_y eye_z dir_x dir_y dir_z upx upy upz ]" << "\n"
-       << "                    ShapeName - name of the initial shape\n"
-       << "                    HlrName - result hlr object from initial shape\n"
-       << "                    eye, dir are eye position and look direction\n"
-       << "                    up is the look up direction vector\n"
-       << "                    Use vtop to see projected hlr shape\n";
-    return 1;
-  }
-
-  // shape and new object name
-  TCollection_AsciiString aShapeName (argv[1]);
-  TCollection_AsciiString aHlrName (argv[2]);
-
-  TopoDS_Shape aSh = DBRep::Get (argv[1]);
-  if (aSh.IsNull()) 
-  {
-    BRep_Builder aBrepBuilder;
-    BRepTools::Read (aSh, argv[1], aBrepBuilder);
-    if (aSh.IsNull ())
-    {
-      di << "No shape with name " << argv[1] << " found\n";
-      return 1;
-    }
-  }
-
-  if (GetMapOfAIS ().IsBound2 (aHlrName))
-  {
-    di << "Presentable object with name " << argv[2] << " already exists\n";
-    return 1;
-  }
-
-  // close local context
-  if (aContextAIS->HasOpenedContext ())
-    aContextAIS->CloseLocalContext ();
-
-  Handle(HLRBRep_PolyAlgo) aPolyAlgo = new HLRBRep_PolyAlgo();
-  HLRBRep_PolyHLRToShape aHLRToShape;
-
+  TCollection_AsciiString aShapeName, aHlrName;
+  TopoDS_Shape aSh;
   gp_Pnt anEye;
   gp_Dir aDir;
   gp_Ax2 aProjAx;
-  if (argc == 9)
-  {
-    gp_Dir anUp;
-
-    anEye.SetCoord (Draw::Atof (argv[3]), Draw::Atof (argv[4]), Draw::Atof (argv[5]));
-    aDir.SetCoord (Draw::Atof (argv[6]), Draw::Atof (argv[7]), Draw::Atof (argv[8]));
-    anUp.SetCoord (Draw::Atof (argv[9]), Draw::Atof (argv[10]), Draw::Atof (argv[11]));
-    aProjAx.SetLocation (anEye);
-    aProjAx.SetDirection (aDir);
-    aProjAx.SetYDirection (anUp);
-  }
-  else
+  bool hasViewDirArg = false;
+  Prs3d_TypeOfHLR anAlgoType = Prs3d_TOH_PolyAlgo;
+  bool toShowCNEdges = false, toShowHiddenEdges = false;
+  int aNbIsolines = 0;
+  if (Handle(V3d_Viewer) aViewer = ViewerTest::GetViewerFromContext())
   {
     gp_Dir aRight;
-
-    Handle(V3d_Viewer) aViewer = ViewerTest::GetViewerFromContext();
-    Handle(V3d_View)   aView   = ViewerTest::CurrentView();
+    Handle(V3d_View) aView = ViewerTest::CurrentView();
     Standard_Integer aWidth, aHeight;
     Standard_Real aCentX, aCentY, aCentZ, aDirX, aDirY, aDirZ;
     Standard_Real aRightX, aRightY, aRightZ;
@@ -3235,7 +3082,6 @@ static int VComputeHLR (Draw_Interpretor& di,
     aView->ConvertWithProj (aWidth, aHeight/2, 
                             aRightX, aRightY, aRightZ,
                             aDirX, aDirY, aDirZ);
-
     aView->ConvertWithProj (aWidth/2, aHeight/2, 
                             aCentX, aCentY, aCentZ,
                             aDirX, aDirY, aDirZ);
@@ -3247,39 +3093,212 @@ static int VComputeHLR (Draw_Interpretor& di,
     aProjAx.SetDirection (aDir);
     aProjAx.SetXDirection (aRight);
   }
+  for (Standard_Integer anArgIter = 1; anArgIter < theArgNb; ++anArgIter)
+  {
+    TCollection_AsciiString anArgCase (theArgVec[anArgIter]);
+    anArgCase.LowerCase();
+    if (anArgIter + 1 < theArgNb
+     && (anArgCase == "-algotype"
+      || anArgCase == "-algo"
+      || anArgCase == "-type"))
+    {
+      TCollection_AsciiString anArgNext (theArgVec[++anArgIter]);
+      anArgNext.LowerCase();
+      if (anArgNext == "polyalgo")
+      {
+        anAlgoType = Prs3d_TOH_PolyAlgo;
+      }
+      else if (anArgNext == "algo")
+      {
+        anAlgoType = Prs3d_TOH_Algo;
+      }
+      else
+      {
+        Message::SendFail() << "Syntax error: unknown algo type '" << anArgNext << "'";
+        return 1;
+      }
+    }
+    else if (anArgCase == "-showhiddenedges"
+          || anArgCase == "-hiddenedges"
+          || anArgCase == "-hidden")
+    {
+      toShowHiddenEdges = true;
+      if (anArgIter + 1 < theArgNb
+       && ViewerTest::ParseOnOff (theArgVec[anArgIter + 1], toShowHiddenEdges))
+      {
+        ++anArgIter;
+      }
+    }
+    else if (anArgCase == "-showtangentedges"
+          || anArgCase == "-tangentedges"
+          || anArgCase == "-tangent")
+    {
+      toShowCNEdges = true;
+      if (anArgIter + 1 < theArgNb
+       && ViewerTest::ParseOnOff (theArgVec[anArgIter + 1], toShowCNEdges))
+      {
+        ++anArgIter;
+      }
+    }
+    else if (anArgIter + 1 < theArgNb
+          && (anArgCase == "-nbiso"
+           || anArgCase == "-nbisolines"))
+    {
+      aNbIsolines = Draw::Atoi (theArgVec[++anArgIter]);
+    }
+    else if (aSh.IsNull())
+    {
+      aSh = DBRep::Get (theArgVec[anArgIter]);
+      aShapeName = theArgVec[anArgIter];
+      if (aSh.IsNull())
+      {
+        BRep_Builder aBrepBuilder;
+        BRepTools::Read (aSh, theArgVec[anArgIter], aBrepBuilder);
+        if (aSh.IsNull())
+        {
+          Message::SendFail() << "Syntax error: no shape with name " << theArgVec[anArgIter] << " found";
+          return 1;
+        }
+      }
+    }
+    else if (aHlrName.IsEmpty())
+    {
+      aHlrName = theArgVec[anArgIter];
+    }
+    else if (!hasViewDirArg
+          && anArgIter + 8 < theArgNb)
+    {
+      hasViewDirArg = true;
+      gp_Dir anUp;
+      anEye.SetCoord (Draw::Atof (theArgVec[anArgIter + 0]), Draw::Atof (theArgVec[anArgIter + 1]), Draw::Atof (theArgVec[anArgIter + 2]));
+      aDir .SetCoord (Draw::Atof (theArgVec[anArgIter + 3]), Draw::Atof (theArgVec[anArgIter + 4]), Draw::Atof (theArgVec[anArgIter + 5]));
+      anUp .SetCoord (Draw::Atof (theArgVec[anArgIter + 6]), Draw::Atof (theArgVec[anArgIter + 7]), Draw::Atof (theArgVec[anArgIter + 8]));
+      aProjAx.SetLocation (anEye);
+      aProjAx.SetDirection (aDir);
+      aProjAx.SetYDirection (anUp);
+      anArgIter += 8;
+    }
+    else
+    {
+      Message::SendFail() << "Syntax error: unknown argument '" << theArgVec[anArgIter] << "'";
+      return 1;
+    }
+  }
 
-  HLRAlgo_Projector aProjector (aProjAx);
-  aPolyAlgo->Projector (aProjector);
-  aPolyAlgo->Load (aSh);
-  aPolyAlgo->Update ();
+  if (aHlrName.IsEmpty() || aSh.IsNull()
+   || (ViewerTest::GetAISContext().IsNull() && hasViewDirArg))
+  {
+    Message::SendFail ("Syntax error: wrong number of arguments");
+    return 1;
+  }
 
-  aHLRToShape.Update (aPolyAlgo);
+  HLRAlgo_Projector aProjector (aProjAx);
+  TopoDS_Shape aVisible[6];
+  TopoDS_Shape aHidden[6];
+  if (anAlgoType == Prs3d_TOH_PolyAlgo)
+  {
+    Handle(HLRBRep_PolyAlgo) aPolyAlgo = new HLRBRep_PolyAlgo();
+    aPolyAlgo->Projector (aProjector);
+    aPolyAlgo->Load (aSh);
+    aPolyAlgo->Update();
 
-  // make hlr shape from input shape
-  TopoDS_Compound aHlrShape;
-  BRep_Builder aBuilder;
-  aBuilder.MakeCompound (aHlrShape);
+    HLRBRep_PolyHLRToShape aHLRToShape;
+    aHLRToShape.Update (aPolyAlgo);
 
-  TopoDS_Shape aCompound = aHLRToShape.VCompound();
-  if (!aCompound.IsNull ())
+    aVisible[HLRBRep_Sharp]   = aHLRToShape.VCompound();
+    aVisible[HLRBRep_OutLine] = aHLRToShape.OutLineVCompound(); // extract visible outlines
+    aVisible[HLRBRep_Rg1Line] = aHLRToShape.Rg1LineVCompound();
+    if (toShowCNEdges)
+    {
+      aVisible[HLRBRep_RgNLine] = aHLRToShape.RgNLineVCompound();
+    }
+    if (toShowHiddenEdges)
+    {
+      aHidden[HLRBRep_Sharp]   = aHLRToShape.HCompound();
+      aHidden[HLRBRep_OutLine] = aHLRToShape.OutLineHCompound();
+      aHidden[HLRBRep_Rg1Line] = aHLRToShape.Rg1LineHCompound();
+      if (toShowCNEdges)
+      {
+        aHidden[HLRBRep_RgNLine] = aHLRToShape.RgNLineHCompound();
+      }
+    }
+  }
+  else
   {
-    aBuilder.Add (aHlrShape, aCompound);
+    Handle(HLRBRep_Algo) aHlrAlgo = new HLRBRep_Algo();
+    aHlrAlgo->Add (aSh, aNbIsolines);
+    aHlrAlgo->Projector (aProjector);
+    aHlrAlgo->Update();
+    aHlrAlgo->Hide();
+
+    HLRBRep_HLRToShape aHLRToShape (aHlrAlgo);
+    aVisible[HLRBRep_Sharp]   = aHLRToShape.VCompound();
+    aVisible[HLRBRep_OutLine] = aHLRToShape.OutLineVCompound();
+    aVisible[HLRBRep_Rg1Line] = aHLRToShape.Rg1LineVCompound();
+    if (toShowCNEdges)
+    {
+      aVisible[HLRBRep_RgNLine] = aHLRToShape.RgNLineVCompound();
+    }
+    aVisible[HLRBRep_IsoLine] = aHLRToShape.IsoLineVCompound();
+
+    if (toShowHiddenEdges)
+    {
+      aHidden[HLRBRep_Sharp]   = aHLRToShape.HCompound();
+      aHidden[HLRBRep_OutLine] = aHLRToShape.OutLineHCompound();
+      aHidden[HLRBRep_Rg1Line] = aHLRToShape.Rg1LineHCompound();
+      if (toShowCNEdges)
+      {
+        aHidden[HLRBRep_RgNLine] = aHLRToShape.RgNLineHCompound();
+      }
+      aHidden[HLRBRep_IsoLine] = aHLRToShape.IsoLineHCompound();
+    }
+    // extract 3d
+    //aVisible[HLRBRep_Sharp]   = aHLRToShape.CompoundOfEdges (HLRBRep_Sharp, Standard_True, Standard_True);
+    //aVisible[HLRBRep_OutLine] = aHLRToShape.OutLineVCompound3d();
   }
-  
-  // extract visible outlines
-  aCompound = aHLRToShape.OutLineVCompound();
-  if (!aCompound.IsNull ())
+
+  TopoDS_Compound aCompRes, aCompVis, aCompHid;
+  BRep_Builder aBuilder;
+  aBuilder.MakeCompound (aCompVis);
+  aBuilder.MakeCompound (aCompHid);
+  aBuilder.MakeCompound (aCompRes);
+  for (int aTypeIter = 0; aTypeIter < 6; ++aTypeIter)
   {
-    aBuilder.Add (aHlrShape, aCompound);
+    if (!aVisible[aTypeIter].IsNull())
+    {
+      aBuilder.Add (aCompVis, aVisible[aTypeIter]);
+    }
+    if (!aHidden[aTypeIter].IsNull())
+    {
+      aBuilder.Add (aCompHid, aHidden[aTypeIter]);
+    }
   }
+  aBuilder.Add (aCompRes, aCompVis);
+  aBuilder.Add (aCompRes, aCompHid);
 
   // create an AIS shape and display it
-  Handle(AIS_Shape) anObject = new AIS_Shape (aHlrShape);
-  GetMapOfAIS().Bind (anObject, aHlrName);
-  aContextAIS->Display (anObject);
-
-  aContextAIS->UpdateCurrentViewer ();
+  if (!ViewerTest::GetAISContext().IsNull())
+  {
+    Handle(AIS_ColoredShape) anObject = new AIS_ColoredShape (aCompRes);
+    if (toShowHiddenEdges)
+    {
+      Handle(Prs3d_LineAspect) aLineAspect = new Prs3d_LineAspect (Quantity_Color (Quantity_NOC_RED), Aspect_TOL_DASH, 1.0f);
+      for (int aTypeIter = 0; aTypeIter < 6; ++aTypeIter)
+      {
+        if (!aHidden[aTypeIter].IsNull())
+        {
+          Handle(AIS_ColoredDrawer) aDrawer = anObject->CustomAspects (aHidden[aTypeIter]);
+          aDrawer->SetLineAspect (aLineAspect);
+          aDrawer->SetWireAspect (aLineAspect);
+          aDrawer->SetFreeBoundaryAspect (aLineAspect);
+          aDrawer->SetUnFreeBoundaryAspect (aLineAspect);
+        }
+      }
+    }
+    ViewerTest::Display (aHlrName, anObject, true);
+  }
 
+  DBRep::Set (aHlrName.ToCString(), aCompRes);
   return 0;
 }
 
@@ -3291,86 +3310,146 @@ class MyPArrayObject : public AIS_InteractiveObject
 
 public:
 
-  MyPArrayObject (Handle(TColStd_HArray1OfAsciiString) theArrayDescription,
-                  Handle(Graphic3d_AspectMarker3d) theMarkerAspect = NULL)
+  MyPArrayObject (const Handle(Graphic3d_ArrayOfPrimitives)& thePArray) : myPArray (thePArray) {}
+
+  MyPArrayObject (Graphic3d_TypeOfPrimitiveArray thePrimType,
+                  const Handle(TColStd_HArray1OfAsciiString)& theDesc,
+                  const Handle(Graphic3d_AspectMarker3d)& theMarkerAspect)
   {
-    myArrayDescription = theArrayDescription;
-    myMarkerAspect = theMarkerAspect;
+    Init (thePrimType, theDesc, theMarkerAspect, Standard_False);
   }
 
-  DEFINE_STANDARD_RTTI(MyPArrayObject, AIS_InteractiveObject);
+  //! Initialize the array from specified description.
+  Standard_Boolean Init (Graphic3d_TypeOfPrimitiveArray thePrimType,
+                         const Handle(TColStd_HArray1OfAsciiString)& theDesc,
+                         const Handle(Graphic3d_AspectMarker3d)& theMarkerAspect,
+                         Standard_Boolean theToPatch);
+
+  DEFINE_STANDARD_RTTI_INLINE(MyPArrayObject,AIS_InteractiveObject);
+
+  virtual Standard_Boolean AcceptDisplayMode (const Standard_Integer theMode) const Standard_OVERRIDE { return theMode == 0; }
+
+  //! Sets color to this interactive object
+  //! @param theColor the color to be set
+  virtual void SetColor (const Quantity_Color& theColor) Standard_OVERRIDE;
 
 private:
 
   void Compute (const Handle(PrsMgr_PresentationManager3d)& aPresentationManager,
                 const Handle(Prs3d_Presentation)& aPresentation,
-                const Standard_Integer aMode);
+                const Standard_Integer aMode) Standard_OVERRIDE;
 
   void ComputeSelection (const Handle(SelectMgr_Selection)& theSelection,
-                         const Standard_Integer /*theMode*/);
+                         const Standard_Integer /*theMode*/) Standard_OVERRIDE;
 
   bool CheckInputCommand (const TCollection_AsciiString theCommand,
-                          const Handle(TColStd_HArray1OfAsciiString) theArgsArray,
+                          const Handle(TColStd_HArray1OfAsciiString)& theArgsArray,
                           Standard_Integer &theArgIndex,
                           Standard_Integer theArgCount,
                           Standard_Integer theMaxArgs);
 
+  //! Sets color for the shading aspect of the drawer used in this interactive object
+  //! @param theColor the color to be set
+  void setColorForShadingAspect(const Quantity_Color& theColor);
+
+  //! Replaces shading aspect from myDrawer->Link() with the own shading aspect of myDrawer for this interactive object
+  void replaceShadingAspect();
+
 protected:
 
-  Handle(TColStd_HArray1OfAsciiString) myArrayDescription;
   Handle(Graphic3d_AspectMarker3d) myMarkerAspect;
+  Handle(Graphic3d_ArrayOfPrimitives) myPArray;
 
 };
 
-
 void MyPArrayObject::Compute (const Handle(PrsMgr_PresentationManager3d)& /*aPresentationManager*/,
-                              const Handle(Prs3d_Presentation)& aPresentation,
-                              const Standard_Integer /*aMode*/)
+                              const Handle(Prs3d_Presentation)& thePrs,
+                              const Standard_Integer theMode)
+{
+  if (myPArray.IsNull() || theMode != 0)
+  {
+    return;
+  }
+
+  Handle(Graphic3d_Group) aGroup = thePrs->NewGroup();
+  if (!myMarkerAspect.IsNull())
+  {
+    aGroup->SetGroupPrimitivesAspect (myMarkerAspect);
+  }
+  else
+  {
+    aGroup->SetGroupPrimitivesAspect (myDrawer->ShadingAspect()->Aspect());
+  }
+  aGroup->AddPrimitiveArray (myPArray);
+}
+
+Standard_Boolean MyPArrayObject::Init (Graphic3d_TypeOfPrimitiveArray thePrimType,
+                                       const Handle(TColStd_HArray1OfAsciiString)& theDesc,
+                                       const Handle(Graphic3d_AspectMarker3d)& theMarkerAspect,
+                                       Standard_Boolean theToPatch)
 {
+  myMarkerAspect = theMarkerAspect;
+  if (!theToPatch)
+  {
+    myPArray.Nullify();
+  }
 
   // Parsing array description
   Standard_Integer aVertexNum = 0, aBoundNum = 0, aEdgeNum = 0;
-  Standard_Boolean hasVColors, hasBColors, hasNormals, hasTexels;
-  hasVColors = hasNormals = hasBColors = hasTexels = Standard_False;
-
-  Standard_Integer anArgIndex = 0;
-  Standard_Integer anArgsCount = myArrayDescription->Length();
-  TCollection_AsciiString anArrayType = myArrayDescription->Value (anArgIndex++);
+  Graphic3d_ArrayFlags anArrayFlags = Graphic3d_ArrayFlags_None;
 
+  const Standard_Integer anArgsCount = theDesc->Length();
   TCollection_AsciiString aCommand;
-  while (anArgIndex < anArgsCount)
+  for (Standard_Integer anArgIndex = theDesc->Lower(); anArgIndex <= theDesc->Upper(); )
   {
-    aCommand = myArrayDescription->Value (anArgIndex);
+    aCommand = theDesc->Value (anArgIndex);
     aCommand.LowerCase();
 
+    if (CheckInputCommand ("-deinterleaved", theDesc, anArgIndex, 0, anArgsCount))
+    {
+      anArrayFlags |= Graphic3d_ArrayFlags_AttribsDeinterleaved;
+    }
+    else if (CheckInputCommand ("-mutable", theDesc, anArgIndex, 0, anArgsCount))
+    {
+      anArrayFlags |= Graphic3d_ArrayFlags_AttribsMutable;
+      anArrayFlags |= Graphic3d_ArrayFlags_IndexesMutable;
+    }
     // vertex command
-    if (CheckInputCommand ("v", myArrayDescription, anArgIndex, 3, anArgsCount))
+    else if (CheckInputCommand ("v", theDesc, anArgIndex, 3, anArgsCount))
     {
       // vertex has a normal or normal with color or texel
-      if (CheckInputCommand ("n", myArrayDescription, anArgIndex, 3, anArgsCount))
-        hasNormals = Standard_True;
+      if (CheckInputCommand ("n", theDesc, anArgIndex, 3, anArgsCount))
+      {
+        anArrayFlags = anArrayFlags | Graphic3d_ArrayFlags_VertexNormal;
+      }
 
       // vertex has a color
-      if (CheckInputCommand ("c", myArrayDescription, anArgIndex, 3, anArgsCount))
-        hasVColors = Standard_True;
+      if (CheckInputCommand ("c", theDesc, anArgIndex, 3, anArgsCount))
+      {
+        anArrayFlags = anArrayFlags | Graphic3d_ArrayFlags_VertexColor;
+      }
 
       // vertex has a texel
-      if (CheckInputCommand ("t", myArrayDescription, anArgIndex, 2, anArgsCount))
-        hasTexels = Standard_True;
+      if (CheckInputCommand ("t", theDesc, anArgIndex, 2, anArgsCount))
+      {
+        anArrayFlags = anArrayFlags | Graphic3d_ArrayFlags_VertexTexel;
+      }
 
       aVertexNum++;
     }
     // bound command
-    else if (CheckInputCommand ("b", myArrayDescription, anArgIndex, 1, anArgsCount))
+    else if (CheckInputCommand ("b", theDesc, anArgIndex, 1, anArgsCount))
     {
       // bound has color
-      if (CheckInputCommand ("c", myArrayDescription, anArgIndex, 3, anArgsCount))
-        hasBColors = Standard_True;
+      if (CheckInputCommand ("c", theDesc, anArgIndex, 3, anArgsCount))
+      {
+        anArrayFlags = anArrayFlags | Graphic3d_ArrayFlags_BoundColor;
+      }
 
       aBoundNum++;
     }
     // edge command
-    else if (CheckInputCommand ("e", myArrayDescription, anArgIndex, 1, anArgsCount))
+    else if (CheckInputCommand ("e", theDesc, anArgIndex, 1, anArgsCount))
     {
       aEdgeNum++;
     }
@@ -3379,132 +3458,191 @@ void MyPArrayObject::Compute (const Handle(PrsMgr_PresentationManager3d)& /*aPre
       anArgIndex++;
   }
 
-  Handle(Graphic3d_ArrayOfPrimitives) anArray;
-  if (anArrayType == "points")
+  if (myPArray.IsNull())
   {
-    anArray = new Graphic3d_ArrayOfPoints (aVertexNum);
+    myPArray = Graphic3d_ArrayOfPrimitives::CreateArray (thePrimType, aVertexNum, aBoundNum, aEdgeNum, anArrayFlags);
   }
-  else if (anArrayType == "segments")
-    anArray = new Graphic3d_ArrayOfSegments (aVertexNum, aEdgeNum, hasVColors);
-  else if (anArrayType == "polylines")
-    anArray = new Graphic3d_ArrayOfPolylines (aVertexNum, aBoundNum, aEdgeNum,
-                                              hasVColors, hasBColors);
-  else if (anArrayType == "triangles")
-    anArray = new Graphic3d_ArrayOfTriangles (aVertexNum, aEdgeNum, hasNormals,
-                                              hasVColors, hasTexels);
-  else if (anArrayType == "trianglefans")
-    anArray = new Graphic3d_ArrayOfTriangleFans (aVertexNum, aBoundNum,
-                                                 hasNormals, hasVColors,
-                                                 hasBColors, hasTexels);
-  else if (anArrayType == "trianglestrips")
-    anArray = new Graphic3d_ArrayOfTriangleStrips (aVertexNum, aBoundNum,
-                                                   hasNormals, hasVColors,
-                                                   hasBColors, hasTexels);
-  else if (anArrayType == "quads")
-    anArray = new Graphic3d_ArrayOfQuadrangles (aVertexNum, aEdgeNum,
-                                                hasNormals, hasVColors,
-                                                hasTexels);
-  else if (anArrayType == "quadstrips")
-    anArray = new Graphic3d_ArrayOfQuadrangleStrips (aVertexNum, aBoundNum,
-                                                     hasNormals, hasVColors,
-                                                     hasBColors, hasTexels);
-  else if (anArrayType == "polygons")
-    anArray = new Graphic3d_ArrayOfPolygons (aVertexNum, aBoundNum, aEdgeNum,
-                                             hasNormals, hasVColors, hasBColors,
-                                             hasTexels);
+  else
+  {
+    if (myPArray->Type() != thePrimType
+    ||  aVertexNum > myPArray->VertexNumberAllocated()
+    ||  aEdgeNum   > myPArray->EdgeNumberAllocated()
+    ||  aBoundNum  > myPArray->BoundNumberAllocated()
+    || !myPArray->Attributes()->IsMutable()
+    || (!myPArray->Indices().IsNull() && !myPArray->Indices()->IsMutable()))
+    {
+      Message::SendFail ("Syntax error: array cannot be patched");
+      return Standard_False;
+    }
 
-  anArgIndex = 1;
-  while (anArgIndex < anArgsCount)
+    myPArray->Attributes()->NbElements = aVertexNum;
+    if (Handle(Graphic3d_AttribBuffer) anAttribs = Handle(Graphic3d_AttribBuffer)::DownCast (myPArray->Attributes()))
+    {
+      anAttribs->Invalidate (0, aVertexNum - 1);
+    }
+    if (!myPArray->Indices().IsNull())
+    {
+      myPArray->Indices()->NbElements = aEdgeNum;
+    }
+    if (!myPArray->Bounds().IsNull())
+    {
+      myPArray->Bounds()->NbBounds = aBoundNum;
+    }
+  }
+
+  Standard_Integer aVertIndex = 0;
+  for (Standard_Integer anArgIndex = theDesc->Lower(); anArgIndex <= theDesc->Upper(); )
   {
-    aCommand = myArrayDescription->Value (anArgIndex);
+    aCommand = theDesc->Value (anArgIndex);
     aCommand.LowerCase();
-    if (!aCommand.IsAscii())
+    if (!aCommand.IsAscii()
+      || aCommand.IsEmpty())
+    {
       break;
+    }
 
+    // skip beautifiers (syntax is not actually validated)
+    if (aCommand == "-deinterleaved"
+     || aCommand == "-mutable"
+     || aCommand.Value (1) == '('
+     || aCommand.Value (1) == ')'
+     || aCommand.Value (1) == ',')
+    {
+      ++anArgIndex;
+    }
     // vertex command
-    if (CheckInputCommand ("v", myArrayDescription, anArgIndex, 3, anArgsCount))
+    else if (CheckInputCommand ("v", theDesc, anArgIndex, 3, anArgsCount))
     {
-      anArray->AddVertex (myArrayDescription->Value (anArgIndex - 3).RealValue(),
-                          myArrayDescription->Value (anArgIndex - 2).RealValue(),
-                          myArrayDescription->Value (anArgIndex - 1).RealValue());
-      const Standard_Integer aVertIndex = anArray->VertexNumber();
+      const Graphic3d_Vec3 aVert ((float )theDesc->Value (anArgIndex - 3).RealValue(),
+                                  (float )theDesc->Value (anArgIndex - 2).RealValue(),
+                                  (float )theDesc->Value (anArgIndex - 1).RealValue());
+      if ((anArrayFlags & Graphic3d_ArrayFlags_AttribsDeinterleaved) != 0
+       || (anArrayFlags & Graphic3d_ArrayFlags_AttribsMutable) != 0)
+      {
+        ++aVertIndex;
+        myPArray->SetVertice (aVertIndex, aVert.x(), aVert.y(), aVert.z());
+      }
+      else
+      {
+        aVertIndex = myPArray->AddVertex (aVert);
+      }
 
       // vertex has a normal or normal with color or texel
-      if (CheckInputCommand ("n", myArrayDescription, anArgIndex, 3, anArgsCount))
-        anArray->SetVertexNormal (aVertIndex,
-                                  myArrayDescription->Value (anArgIndex - 3).RealValue(),
-                                  myArrayDescription->Value (anArgIndex - 2).RealValue(),
-                                  myArrayDescription->Value (anArgIndex - 1).RealValue());
-      
-      if (CheckInputCommand ("c", myArrayDescription, anArgIndex, 3, anArgsCount))
-        anArray->SetVertexColor (aVertIndex,
-                                 myArrayDescription->Value (anArgIndex - 3).RealValue(),
-                                 myArrayDescription->Value (anArgIndex - 2).RealValue(),
-                                 myArrayDescription->Value (anArgIndex - 1).RealValue());
+      if (CheckInputCommand ("n", theDesc, anArgIndex, 3, anArgsCount))
+      {
+        const Graphic3d_Vec3 aNorm ((float )theDesc->Value (anArgIndex - 3).RealValue(),
+                                    (float )theDesc->Value (anArgIndex - 2).RealValue(),
+                                    (float )theDesc->Value (anArgIndex - 1).RealValue());
+        myPArray->SetVertexNormal (aVertIndex, aNorm.x(), aNorm.y(), aNorm.z());
+      }
       
-      if (CheckInputCommand ("t", myArrayDescription, anArgIndex, 2, anArgsCount))
-        anArray->SetVertexTexel (aVertIndex,
-                                 myArrayDescription->Value (anArgIndex - 2).RealValue(),
-                                 myArrayDescription->Value (anArgIndex - 1).RealValue());
+      if (CheckInputCommand ("c", theDesc, anArgIndex, 3, anArgsCount))
+      {
+        const Graphic3d_Vec3d aCol (theDesc->Value (anArgIndex - 3).RealValue(),
+                                    theDesc->Value (anArgIndex - 2).RealValue(),
+                                    theDesc->Value (anArgIndex - 1).RealValue());
+        myPArray->SetVertexColor (aVertIndex, aCol.r(), aCol.g(), aCol.b());
+      }
+      if (CheckInputCommand ("t", theDesc, anArgIndex, 2, anArgsCount))
+      {
+        const Graphic3d_Vec2 aTex ((float )theDesc->Value (anArgIndex - 2).RealValue(),
+                                   (float )theDesc->Value (anArgIndex - 1).RealValue());
+        myPArray->SetVertexTexel (aVertIndex, aTex.x(), aTex.y());
+      }
     }
     // bounds command
-    else if (CheckInputCommand ("b", myArrayDescription, anArgIndex, 1, anArgsCount))
+    else if (CheckInputCommand ("b", theDesc, anArgIndex, 1, anArgsCount))
     {
-      Standard_Integer aVertCount = myArrayDescription->Value (anArgIndex - 1).IntegerValue();
+      Standard_Integer aVertCount = theDesc->Value (anArgIndex - 1).IntegerValue();
 
-      if (CheckInputCommand ("c", myArrayDescription, anArgIndex, 3, anArgsCount))
-        anArray->AddBound (aVertCount,
-                           myArrayDescription->Value (anArgIndex - 3).RealValue(),
-                           myArrayDescription->Value (anArgIndex - 2).RealValue(),
-                           myArrayDescription->Value (anArgIndex - 1).RealValue());
+      if (CheckInputCommand ("c", theDesc, anArgIndex, 3, anArgsCount))
+        myPArray->AddBound (aVertCount,
+                            theDesc->Value (anArgIndex - 3).RealValue(),
+                            theDesc->Value (anArgIndex - 2).RealValue(),
+                            theDesc->Value (anArgIndex - 1).RealValue());
 
       else
-        anArray->AddBound (aVertCount);
+        myPArray->AddBound (aVertCount);
     }
     // edge command
-    else if (CheckInputCommand ("e", myArrayDescription, anArgIndex, 1, anArgsCount))
+    else if (CheckInputCommand ("e", theDesc, anArgIndex, 1, anArgsCount))
     {
-      const Standard_Integer aVertIndex = myArrayDescription->Value (anArgIndex - 1).IntegerValue();
-      anArray->AddEdge (aVertIndex);
+      const Standard_Integer anEdge = theDesc->Value (anArgIndex - 1).IntegerValue();
+      myPArray->AddEdge (anEdge);
     }
     // unknown command
     else
-      anArgIndex++;
+    {
+      Message::SendFail() << "Syntax error: unknown argument '" << theDesc->Value(anArgIndex) << "'";
+      return Standard_False;
+    }
   }
+  return Standard_True;
+}
 
-  aPresentation->Clear();
-  if (!myMarkerAspect.IsNull())
+//=======================================================================
+// function : SetColor
+// purpose  :
+//=======================================================================
+void MyPArrayObject::SetColor (const Quantity_Color& theColor)
+{
+  AIS_InteractiveObject::SetColor (theColor);
+  setColorForShadingAspect (theColor);
+  if (myMarkerAspect)
   {
-    Prs3d_Root::CurrentGroup (aPresentation)->SetGroupPrimitivesAspect (myMarkerAspect);
+    myMarkerAspect->SetColor (theColor);
   }
-  Prs3d_Root::CurrentGroup (aPresentation)->AddPrimitiveArray (anArray);
+  SynchronizeAspects();
 }
 
 void MyPArrayObject::ComputeSelection (const Handle(SelectMgr_Selection)& theSelection,
-                                       const Standard_Integer /*theMode*/)
+                                       const Standard_Integer theMode)
 {
-  Handle(SelectMgr_EntityOwner) anEntityOwner = new SelectMgr_EntityOwner (this);
+  if (theMode != 0
+   || myPArray.IsNull())
+  {
+    return;
+  }
 
-  Standard_Integer anArgIndex = 1;
-  while (anArgIndex < myArrayDescription->Length())
+  Handle(SelectMgr_EntityOwner) anOwner = new SelectMgr_EntityOwner (this);
+  if (Handle(Graphic3d_ArrayOfTriangles) aTris = Handle(Graphic3d_ArrayOfTriangles)::DownCast (myPArray))
   {
-    if (CheckInputCommand ("v", myArrayDescription, anArgIndex, 3, myArrayDescription->Length()))
+    Handle(Select3D_SensitivePrimitiveArray) aSensitive = new Select3D_SensitivePrimitiveArray (anOwner);
+    aSensitive->InitTriangulation (myPArray->Attributes(), myPArray->Indices(), TopLoc_Location(), true);
+    theSelection->Add (aSensitive);
+  }
+  else if (Handle(Graphic3d_ArrayOfSegments) aSegs = Handle(Graphic3d_ArrayOfSegments)::DownCast (myPArray))
+  {
+    if (aSegs->EdgeNumber() > 0)
     {
-      gp_Pnt aPoint (myArrayDescription->Value (anArgIndex - 3).RealValue(),
-                     myArrayDescription->Value (anArgIndex - 2).RealValue(),
-                     myArrayDescription->Value (anArgIndex - 1).RealValue());
-      Handle(Select3D_SensitivePoint) aSensetivePoint = new Select3D_SensitivePoint (anEntityOwner, aPoint);
-      theSelection->Add (aSensetivePoint);
+      for (Standard_Integer aPntIter = 1; aPntIter <= aSegs->EdgeNumber(); aPntIter += 2)
+      {
+        Handle(Select3D_SensitiveSegment) aSeg = new Select3D_SensitiveSegment (anOwner, aSegs->Vertice (aSegs->Edge (aPntIter)), aSegs->Vertice (aSegs->Edge (aPntIter + 1)));
+        aSeg->SetSensitivityFactor (4);
+        theSelection->Add (aSeg);
+      }
     }
     else
     {
-      anArgIndex++;
+      for (Standard_Integer aPntIter = 1; aPntIter <= aSegs->VertexNumber(); aPntIter += 2)
+      {
+        Handle(Select3D_SensitiveSegment) aSeg = new Select3D_SensitiveSegment (anOwner, aSegs->Vertice (aPntIter), aSegs->Vertice (aPntIter + 1));
+        aSeg->SetSensitivityFactor (4);
+        theSelection->Add (aSeg);
+      }
     }
   }
+  else
+  {
+    Handle(Select3D_SensitivePrimitiveArray) aSensitive = new Select3D_SensitivePrimitiveArray (anOwner);
+    aSensitive->SetSensitivityFactor (8);
+    aSensitive->InitPoints (myPArray->Attributes(), myPArray->Indices(), TopLoc_Location(), true);
+    theSelection->Add (aSensitive);
+  }
 }
 
 bool MyPArrayObject::CheckInputCommand (const TCollection_AsciiString theCommand,
-                                       const Handle(TColStd_HArray1OfAsciiString) theArgsArray,
+                                       const Handle(TColStd_HArray1OfAsciiString)& theArgsArray,
                                        Standard_Integer &theArgIndex,
                                        Standard_Integer theArgCount,
                                        Standard_Integer theMaxArgs)
@@ -3533,6 +3671,34 @@ bool MyPArrayObject::CheckInputCommand (const TCollection_AsciiString theCommand
   return true;
 }
 
+//=======================================================================
+// function : setColorForShadingAspect
+// purpose  :
+//=======================================================================
+void MyPArrayObject::setColorForShadingAspect (const Quantity_Color& theColor)
+{
+  if (myDrawer->SetupOwnShadingAspect())
+  {
+    replaceShadingAspect();
+  }
+  myDrawer->ShadingAspect()->SetColor (theColor);
+}
+
+//=======================================================================
+// function : replaceShadingAspect
+// purpose  :
+//=======================================================================
+void MyPArrayObject::replaceShadingAspect()
+{
+  if (!myDrawer->Link())
+  {
+    return;
+  }
+  Graphic3d_MapOfAspectsToAspects anAspectReplacementMap;
+  anAspectReplacementMap.Bind (myDrawer->Link()->ShadingAspect()->Aspect(), myDrawer->ShadingAspect()->Aspect());
+  replaceAspects (anAspectReplacementMap);
+}
+
 //=============================================================================
 //function : VDrawPArray
 //purpose  : Draws primitives array from list of vertexes, bounds, edges
@@ -3543,55 +3709,116 @@ static int VDrawPArray (Draw_Interpretor& di, Standard_Integer argc, const char*
   Handle(AIS_InteractiveContext) aContextAIS = ViewerTest::GetAISContext();
   if (aContextAIS.IsNull())
   {
-    di << "Call vinit before!\n";
+    Message::SendFail ("Error: no active Viewer");
     return 1;
   }
   else if (argc < 3)
   {
-    di << "Use: " << argv[0] << " Name TypeOfArray"
-       << " [vertex] ... [bounds] ... [edges]\n"
-       << "  TypeOfArray={ points | segments | polylines | triangles |\n"
-       << "                trianglefans | trianglestrips | quads |\n"
-       << "                quadstrips | polygons }\n"
-       << "  vertex={ 'v' x y z [normal={ 'n' nx ny nz }] [color={ 'c' r g b }]"
-       << " [texel={ 't' tx ty }] } \n"
-       << "  bounds={ 'b' verticies_count [color={ 'c' r g b }] }\n"
-       << "  edges={ 'e' vertex_id }\n";
+    Message::SendFail ("Syntax error: wrong number of arguments");
     return 1;
   }
 
   // read the arguments
-  Standard_Integer aArgIndex = 1;
-  TCollection_AsciiString aName (argv[aArgIndex++]);
-  TCollection_AsciiString anArrayType (argv[aArgIndex++]);
+  Standard_Integer anArgIndex = 1;
+  TCollection_AsciiString aName (argv[anArgIndex++]);
+  TCollection_AsciiString anArrayType (argv[anArgIndex++]);
+  anArrayType.LowerCase();
+  Handle(MyPArrayObject) aPObject;
+  if (anArrayType == "-shape")
+  {
+    Standard_CString aShapeName = argv[anArgIndex++];
+    TopoDS_Shape aShape = DBRep::Get (aShapeName);
+    Handle(Graphic3d_ArrayOfPrimitives) aTris = StdPrs_ShadedShape::FillTriangles (aShape);
+    if (aShape.IsNull())
+    {
+      Message::SendFail() << "Syntax error: shape '" << aShapeName << "' is not found";
+      return 1;
+    }
+    else if (aTris.IsNull())
+    {
+      Message::SendFail() << "Syntax error: shape '" << aShapeName << "' is not triangulated";
+      return 1;
+    }
 
-  Standard_Boolean hasVertex = Standard_False;
+    aPObject = new MyPArrayObject (aTris);
+    ViewerTest::Display (aName, aPObject);
+    return 0;
+  }
+  else if (anArrayType == "-patch"
+        || anArrayType == "-modify"
+        || anArrayType == "-edit")
+  {
+    if (argc >= 3)
+    {
+      anArrayType = argv[anArgIndex++];
+      anArrayType.LowerCase();
+    }
 
-  Handle(TColStd_HArray1OfAsciiString) anArgsArray = new TColStd_HArray1OfAsciiString (0, argc - 2);
-  anArgsArray->SetValue (0, anArrayType);
+    if (GetMapOfAIS().IsBound2 (aName))
+    {
+      aPObject = Handle(MyPArrayObject)::DownCast (GetMapOfAIS().Find2 (aName));
+    }
+    if (aPObject.IsNull())
+    {
+      Message::SendFail() << "Syntax error: object '" << aName << "' cannot be found";
+      return 1;
+    }
+  }
 
-  if (anArrayType != "points"         &&
-      anArrayType != "segments"       &&
-      anArrayType != "polylines"      &&
-      anArrayType != "triangles"      &&
-      anArrayType != "trianglefans"   &&
-      anArrayType != "trianglestrips" &&
-      anArrayType != "quads"          &&
-      anArrayType != "quadstrips"     &&
-      anArrayType != "polygons")
+  Standard_Boolean hasVertex = Standard_False;
+
+  Graphic3d_TypeOfPrimitiveArray aPrimType = Graphic3d_TOPA_UNDEFINED;
+  if (anArrayType == "points")
+  {
+    aPrimType = Graphic3d_TOPA_POINTS;
+  }
+  else if (anArrayType == "segments")
   {
-    di << "Unexpected type of primitives array\n";
+    aPrimType = Graphic3d_TOPA_SEGMENTS;
+  }
+  else if (anArrayType == "polylines")
+  {
+    aPrimType = Graphic3d_TOPA_POLYLINES;
+  }
+  else if (anArrayType == "triangles")
+  {
+    aPrimType = Graphic3d_TOPA_TRIANGLES;
+  }
+  else if (anArrayType == "trianglefans")
+  {
+    aPrimType = Graphic3d_TOPA_TRIANGLEFANS;
+  }
+  else if (anArrayType == "trianglestrips")
+  {
+    aPrimType = Graphic3d_TOPA_TRIANGLESTRIPS;
+  }
+  else if (anArrayType == "quads")
+  {
+    aPrimType = Graphic3d_TOPA_QUADRANGLES;
+  }
+  else if (anArrayType == "quadstrips")
+  {
+    aPrimType = Graphic3d_TOPA_QUADRANGLESTRIPS;
+  }
+  else if (anArrayType == "polygons")
+  {
+    aPrimType = Graphic3d_TOPA_POLYGONS;
+  }
+  if (aPrimType == Graphic3d_TOPA_UNDEFINED)
+  {
+    Message::SendFail ("Syntax error: unexpected type of primitives array");
     return 1;
   }
 
-  TCollection_AsciiString aCommand;
-  for (Standard_Integer anArgIndex = 3; anArgIndex < argc; anArgIndex++)
+  Standard_Integer aLowerArg = anArgIndex;
+  Handle(TColStd_HArray1OfAsciiString) anArgsArray = new TColStd_HArray1OfAsciiString (0, argc - 3);
+  for (; anArgIndex < argc; ++anArgIndex)
   {
-    aCommand = argv[anArgIndex];
+    TCollection_AsciiString aCommand (argv[anArgIndex]);
     aCommand.LowerCase();
     if (!aCommand.IsAscii())
     {
-      di << "Unexpected argument: #" << aArgIndex - 1 << " , "
+      di << "Unexpected argument: #" << anArgIndex - 1 << " , "
          << "should be an array element: 'v', 'b', 'e' \n";
       break;
     }
@@ -3601,7 +3828,7 @@ static int VDrawPArray (Draw_Interpretor& di, Standard_Integer argc, const char*
       hasVertex = Standard_True;
     }
 
-    anArgsArray->SetValue (anArgIndex - 2, aCommand);
+    anArgsArray->SetValue (anArgIndex - aLowerArg, aCommand);
   }
 
   if (!hasVertex)
@@ -3611,18 +3838,59 @@ static int VDrawPArray (Draw_Interpretor& di, Standard_Integer argc, const char*
   }
 
   Handle(Graphic3d_AspectMarker3d)    anAspPoints;
-  if (anArrayType == "points")
+  if (aPrimType == Graphic3d_TOPA_POINTS)
   {
     anAspPoints = new Graphic3d_AspectMarker3d (Aspect_TOM_POINT, Quantity_NOC_YELLOW, 1.0f);
   }
 
   // create primitives array object
-  Handle(MyPArrayObject) aPObject = new MyPArrayObject (anArgsArray, anAspPoints);
+  if (aPObject.IsNull())
+  {
+    // register the object in map
+    aPObject = new MyPArrayObject (aPrimType, anArgsArray, anAspPoints);
+    VDisplayAISObject (aName, aPObject);
+  }
+  else
+  {
+    aPObject->Init (aPrimType, anArgsArray, anAspPoints, Standard_True);
+    ViewerTest::CurrentView()->Redraw();
+  }
+  return 0;
+}
 
-  // register the object in map
-  VDisplayAISObject (aName, aPObject);
+namespace
+{
+  //! Auxiliary function for parsing translation vector - either 2D or 3D.
+  static Standard_Integer parseTranslationVec (Standard_Integer theArgNb,
+                                               const char**     theArgVec,
+                                               gp_Vec&          theVec)
+  {
+    if (theArgNb < 2)
+    {
+      return 0;
+    }
 
-  return 0;
+    TCollection_AsciiString anX (theArgVec[0]);
+    TCollection_AsciiString anY (theArgVec[1]);
+    if (!anX.IsRealValue()
+     || !anY.IsRealValue())
+    {
+      return 0;
+    }
+
+    theVec.SetX (anX.RealValue());
+    theVec.SetY (anY.RealValue());
+    if (theArgNb >= 3)
+    {
+      TCollection_AsciiString anZ (theArgVec[2]);
+      if (anZ.IsRealValue())
+      {
+        theVec.SetZ (anZ.RealValue());
+        return 3;
+      }
+    }
+    return 2;
+  }
 }
 
 //=======================================================================
@@ -3630,7 +3898,7 @@ static int VDrawPArray (Draw_Interpretor& di, Standard_Integer argc, const char*
 //purpose  : Change location of AIS interactive object
 //=======================================================================
 
-static Standard_Integer VSetLocation (Draw_Interpretor& /*di*/,
+static Standard_Integer VSetLocation (Draw_Interpretor& theDI,
                                       Standard_Integer  theArgNb,
                                       const char**      theArgVec)
 {
@@ -3638,256 +3906,386 @@ static Standard_Integer VSetLocation (Draw_Interpretor& /*di*/,
   ViewerTest_AutoUpdater anUpdateTool (aContext, ViewerTest::CurrentView());
   if (aContext.IsNull())
   {
-    std::cout << "Error: no active view!\n";
+    Message::SendFail ("Error: no active viewer");
     return 1;
   }
 
-  TCollection_AsciiString aName;
-  gp_Vec aLocVec;
-  Standard_Boolean isSetLoc = Standard_False;
-
-  Standard_Integer anArgIter = 1;
-  for (; anArgIter < theArgNb; ++anArgIter)
+  Standard_Boolean toPrintInfo = Standard_True;
+  Handle(AIS_InteractiveObject) anObj;
+  TCollection_AsciiString aCmdName (theArgVec[0]);
+  aCmdName.LowerCase();
+  for (Standard_Integer anArgIter = 1; anArgIter < theArgNb; ++anArgIter)
   {
-    Standard_CString anArg = theArgVec[anArgIter];
-    if (anUpdateTool.parseRedrawMode (theArgVec[anArgIter]))
+    TCollection_AsciiString anArg = theArgVec[anArgIter];
+    anArg.LowerCase();
+    if (anUpdateTool.parseRedrawMode (anArg))
     {
       continue;
     }
-    else if (aName.IsEmpty())
+    else if (anObj.IsNull())
     {
-      aName = anArg;
+      const TCollection_AsciiString aName (theArgVec[anArgIter]);
+      GetMapOfAIS().Find2 (aName, anObj);
+      if (anObj.IsNull())
+      {
+        Message::SendFail() << "Error: object '" << aName << "' is not displayed";
+        return 1;
+      }
     }
-    else if (!isSetLoc)
+    else if (anArg == "-reset")
+    {
+      toPrintInfo = Standard_False;
+      aContext->SetLocation (anObj, gp_Trsf());
+    }
+    else if (anArg == "-copyfrom"
+          || anArg == "-copy")
     {
-      isSetLoc = Standard_True;
       if (anArgIter + 1 >= theArgNb)
       {
-        std::cout << "Error: syntax error at '" << anArg << "'\n";
+        Message::SendFail() << "Syntax error at '" << anArg << "'";
         return 1;
       }
-      aLocVec.SetX (Draw::Atof (theArgVec[anArgIter++]));
-      aLocVec.SetY (Draw::Atof (theArgVec[anArgIter]));
-      if (anArgIter + 1 < theArgNb)
+
+      const TCollection_AsciiString aName2 (theArgVec[anArgIter + 1]);
+      Handle(AIS_InteractiveObject) anObj2;
+      GetMapOfAIS().Find2 (aName2, anObj2);
+      if (anObj2.IsNull())
       {
-        aLocVec.SetZ (Draw::Atof (theArgVec[++anArgIter]));
+        Message::SendFail() << "Error: object '" << aName2 << "' is not displayed";
+        return 1;
       }
+
+      ++anArgIter;
+      aContext->SetLocation (anObj, anObj2->LocalTransformation());
     }
-    else
+    else if (anArg == "-rotate")
     {
-      std::cout << "Error: unknown argument '" << anArg << "'\n";
-      return 1;
-    }
-  }
-
-  // find object
-  const ViewerTest_DoubleMapOfInteractiveAndName& aMap = GetMapOfAIS();
-  Handle(AIS_InteractiveObject) anIObj;
-  if (aMap.IsBound2 (aName))
-  {
-    anIObj = Handle(AIS_InteractiveObject)::DownCast (aMap.Find2 (aName));
-  }
-  if (anIObj.IsNull())
-  {
-    std::cout << "Error: object '" << aName << "' is not displayed!\n";
-    return 1;
-  }
+      toPrintInfo = Standard_False;
+      if (anArgIter + 7 >= theArgNb)
+      {
+        Message::SendFail() << "Syntax error at '" << anArg << "'";
+        return 1;
+      }
 
-  gp_Trsf aTrsf;
-  aTrsf.SetTranslation (aLocVec);
-  TopLoc_Location aLocation (aTrsf);
-  aContext->SetLocation (anIObj, aLocation);
-  return 0;
-}
+      gp_Trsf aTrsf;
+      aTrsf.SetRotation (gp_Ax1 (gp_Pnt (Draw::Atof (theArgVec[anArgIter + 1]),
+                                         Draw::Atof (theArgVec[anArgIter + 2]),
+                                         Draw::Atof (theArgVec[anArgIter + 3])),
+                                 gp_Vec (Draw::Atof (theArgVec[anArgIter + 4]),
+                                         Draw::Atof (theArgVec[anArgIter + 5]),
+                                         Draw::Atof (theArgVec[anArgIter + 6]))),
+                                         Draw::Atof (theArgVec[anArgIter + 7]) * (M_PI / 180.0));
+      anArgIter += 7;
 
-//=======================================================================
-//function : TransformPresentation
-//purpose  : Change transformation of AIS interactive object
-//=======================================================================
-static Standard_Integer LocalTransformPresentation (Draw_Interpretor& /*theDi*/,
-                                                    Standard_Integer theArgNb,
-                                                    const char** theArgVec)
-{
-  if (theArgNb <= 1)
-  {
-    std::cout << "Error: too few arguments.\n";
-    return 1;
-  }
-
-  Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
-  ViewerTest_AutoUpdater anUpdateTool(aContext, ViewerTest::CurrentView());
-  if (aContext.IsNull())
-  {
-    std::cout << "Error: no active view!\n";
-    return 1;
-  }
+      aTrsf = anObj->LocalTransformation() * aTrsf;
+      aContext->SetLocation (anObj, aTrsf);
+    }
+    else if (anArg == "-translate")
+    {
+      toPrintInfo = Standard_False;
+      gp_Vec aLocVec;
+      Standard_Integer aNbParsed = parseTranslationVec (theArgNb - anArgIter - 1, theArgVec + anArgIter + 1, aLocVec);
+      anArgIter += aNbParsed;
+      if (aNbParsed == 0)
+      {
+        Message::SendFail() << "Syntax error at '" << anArg << "'";
+        return 1;
+      }
 
-  gp_Trsf aTrsf;
-  Standard_Integer aLast = theArgNb;
-  const char* aName = theArgVec[0];
+      gp_Trsf aTrsf;
+      aTrsf.SetTranslationPart (aLocVec);
+      aTrsf = anObj->LocalTransformation() * aTrsf;
+      aContext->SetLocation (anObj, aTrsf);
+    }
+    else if (anArg == "-scale"
+          || anArg == "-setscale")
+    {
+      toPrintInfo = Standard_False;
+      gp_XYZ aScaleLoc;
+      Standard_Real aScale = 1.0;
+      Standard_Boolean toPrintScale = Standard_True;
+      Standard_Boolean hasScaleLoc  = Standard_False;
+      if (anArgIter + 4 < theArgNb)
+      {
+        TCollection_AsciiString aScaleArgs[4] =
+        {
+          TCollection_AsciiString (theArgVec[anArgIter + 1]),
+          TCollection_AsciiString (theArgVec[anArgIter + 2]),
+          TCollection_AsciiString (theArgVec[anArgIter + 3]),
+          TCollection_AsciiString (theArgVec[anArgIter + 4])
+        };
+        Standard_Integer aScaleArgIter = 0;
+        for (; aScaleArgIter < 4; ++aScaleArgIter)
+        {
+          if (!aScaleArgs[aScaleArgIter].IsRealValue())
+          {
+            break;
+          }
+        }
+        if (aScaleArgIter == 4)
+        {
+          aScaleLoc.SetCoord (aScaleArgs[0].RealValue(), aScaleArgs[1].RealValue(), aScaleArgs[2].RealValue());
+          aScale = aScaleArgs[3].RealValue();
+          anArgIter += 4;
+          toPrintScale = Standard_False;
+          hasScaleLoc  = Standard_True;
+        }
+        else if (aScaleArgIter >= 1)
+        {
+          aScale = aScaleArgs[0].RealValue();
+          ++anArgIter;
+          toPrintScale = Standard_False;
+        }
+      }
+      else if (anArgIter + 1 < theArgNb)
+      {
+        TCollection_AsciiString aScaleArg (theArgVec[anArgIter + 1]);
+        if (aScaleArg.IsRealValue())
+        {
+          aScale = aScaleArg.RealValue();
+          ++anArgIter;
+          toPrintScale = Standard_False;
+        }
+      }
 
-  Standard_Boolean isReset = Standard_False;
-  Standard_Boolean isMove = Standard_False;
+      if (toPrintScale)
+      {
+        if (anArg == "-setscale")
+        {
+          Message::SendFail() << "Syntax error at '" << anArg << "'";
+          return 1;
+        }
 
-  // Prefix 'vloc'
-  aName += 4;
+        char aText[1024];
+        Sprintf (aText, "%g ", anObj->LocalTransformation().ScaleFactor());
+        theDI << aText;
+        continue;
+      }
 
-  if (!strcmp (aName, "reset"))
-  {
-    isReset = Standard_True;
-  }
-  else if (!strcmp (aName, "move"))
-  {
-    if (theArgNb < 3)
+      if (anArg == "-setscale")
+      {
+        gp_Trsf aTrsf = anObj->LocalTransformation();
+        if (hasScaleLoc)
+        {
+          aTrsf.SetScale (aScaleLoc, aScale);
+        }
+        else
+        {
+          aTrsf.SetScaleFactor (aScale);
+        }
+        aContext->SetLocation (anObj, aTrsf);
+      }
+      else
+      {
+        gp_Trsf aTrsf;
+        if (hasScaleLoc)
+        {
+          aTrsf.SetScale (aScaleLoc, aScale);
+          aTrsf = anObj->LocalTransformation() * aTrsf;
+        }
+        else
+        {
+          aTrsf = anObj->LocalTransformation();
+          aTrsf.SetScaleFactor (aTrsf.ScaleFactor() * aScale);
+        }
+        aContext->SetLocation (anObj, aTrsf);
+      }
+    }
+    else if (anArg == "-mirror")
     {
-      std::cout << "Error: too few arguments.\n";
-      return 1;
+      toPrintInfo = Standard_False;
+      if (anArgIter + 6 >= theArgNb)
+      {
+        Message::SendFail() << "Syntax error at '" << anArg << "'";
+        return 1;
+      }
+
+      gp_Trsf aTrsf;
+      aTrsf.SetMirror (gp_Ax2 (gp_Pnt (Draw::Atof(theArgVec[theArgNb - 6]),
+                                       Draw::Atof(theArgVec[theArgNb - 5]),
+                                       Draw::Atof(theArgVec[theArgNb - 4])),
+                               gp_Vec (Draw::Atof(theArgVec[theArgNb - 3]),
+                                       Draw::Atof(theArgVec[theArgNb - 2]),
+                                       Draw::Atof(theArgVec[theArgNb - 1]))));
+      anArgIter += 6;
+      aTrsf = anObj->LocalTransformation() * aTrsf;
+      aContext->SetLocation (anObj, aTrsf);
     }
+    else if (anArg == "-setrotation"
+          || anArg == "-rotation")
+    {
+      toPrintInfo = Standard_False;
+      if (anArgIter + 4 < theArgNb)
+      {
+        TCollection_AsciiString aQuatArgs[4] =
+        {
+          TCollection_AsciiString (theArgVec[anArgIter + 1]),
+          TCollection_AsciiString (theArgVec[anArgIter + 2]),
+          TCollection_AsciiString (theArgVec[anArgIter + 3]),
+          TCollection_AsciiString (theArgVec[anArgIter + 4])
+        };
+        Standard_Integer aQuatArgIter = 0;
+        for (; aQuatArgIter < 4; ++aQuatArgIter)
+        {
+          if (!aQuatArgs[aQuatArgIter].IsRealValue())
+          {
+            break;
+          }
+        }
 
-    const ViewerTest_DoubleMapOfInteractiveAndName& aMap = GetMapOfAIS();
+        if (aQuatArgIter == 4)
+        {
+          anArgIter += 4;
+          const gp_Quaternion aQuat (aQuatArgs[0].RealValue(),
+                                     aQuatArgs[1].RealValue(),
+                                     aQuatArgs[2].RealValue(),
+                                     aQuatArgs[3].RealValue());
+          gp_Trsf aTrsf = anObj->LocalTransformation();
+          aTrsf.SetRotation (aQuat);
+          aContext->SetLocation (anObj, aTrsf);
+          continue;
+        }
+        else if (anArg == "-setrotation")
+        {
+          Message::SendFail() << "Syntax error at '" << anArg << "'";
+          return 1;
+        }
+      }
 
-    Handle(AIS_InteractiveObject) anIObj;
-    if (aMap.IsBound2 (theArgVec[theArgNb - 1]))
+      char aText[1024];
+      const gp_Quaternion aQuat = anObj->LocalTransformation().GetRotation();
+      Sprintf (aText, "%g %g %g %g ", aQuat.X(), aQuat.Y(), aQuat.Z(), aQuat.W());
+      theDI << aText;
+    }
+    else if (anArg == "-setlocation"
+          || anArg == "-location")
     {
-      anIObj = Handle(AIS_InteractiveObject)::DownCast (aMap.Find2 (theArgVec[theArgNb - 1]));
+      toPrintInfo = Standard_False;
+      gp_Vec aLocVec;
+      Standard_Integer aNbParsed = parseTranslationVec (theArgNb - anArgIter - 1, theArgVec + anArgIter + 1, aLocVec);
+      anArgIter += aNbParsed;
+      if (aNbParsed != 0)
+      {
+        gp_Trsf aTrsf = anObj->LocalTransformation();
+        aTrsf.SetTranslationPart (aLocVec);
+        aContext->SetLocation (anObj, aTrsf);
+      }
+      else if (anArg == "-setlocation")
+      {
+        Message::SendFail() << "Syntax error at '" << anArg << "'";
+        return 1;
+      }
+
+      char aText[1024];
+      const gp_XYZ aLoc = anObj->LocalTransformation().TranslationPart();
+      Sprintf (aText, "%g %g %g ", aLoc.X(), aLoc.Y(), aLoc.Z());
+      theDI << aText;
     }
+    else if (aCmdName == "vsetlocation")
+    {
+      // compatibility with old syntax
+      gp_Vec aLocVec;
+      Standard_Integer aNbParsed = parseTranslationVec (theArgNb - anArgIter, theArgVec + anArgIter, aLocVec);
+      if (aNbParsed == 0)
+      {
+        Message::SendFail() << "Syntax error at '" << anArg << "'";
+        return 1;
+      }
+      anArgIter = anArgIter + aNbParsed - 1;
 
-    if (anIObj.IsNull())
+      gp_Trsf aTrsf;
+      aTrsf.SetTranslationPart (aLocVec);
+      aContext->SetLocation (anObj, aTrsf);
+      toPrintInfo = Standard_False;
+    }
+    else
     {
-      std::cout << "Error: object '" << theArgVec[theArgNb - 1] << "' is not displayed!\n";
+      Message::SendFail() << "Error: unknown argument '" << anArg << "'";
       return 1;
     }
-
-    isMove = Standard_True;
-
-    aTrsf = anIObj->Transformation();
-    aLast = theArgNb - 1;
   }
-  else if (!strcmp (aName, "translate"))
+
+  if (anObj.IsNull())
   {
-    if (theArgNb < 5)
-    {
-      std::cout << "Error: too few arguments.\n";
-      return 1;
-    }
-    aTrsf.SetTranslation (gp_Vec (Draw::Atof (theArgVec[theArgNb - 3]),
-                                  Draw::Atof (theArgVec[theArgNb - 2]),
-                                  Draw::Atof (theArgVec[theArgNb - 1])));
-    aLast = theArgNb - 3;
+    Message::SendFail ("Syntax error - wrong number of arguments");
+    return 1;
   }
-  else if (!strcmp (aName, "rotate"))
+  else if (!toPrintInfo)
   {
-    if (theArgNb < 9)
-    {
-      std::cout << "Error: too few arguments.\n";
-      return 1;
-    }
+    return 0;
+  }
 
-    aTrsf.SetRotation (
-      gp_Ax1 (gp_Pnt (Draw::Atof (theArgVec[theArgNb - 7]),
-                      Draw::Atof (theArgVec[theArgNb - 6]),
-                      Draw::Atof (theArgVec[theArgNb - 5])),
-              gp_Vec (Draw::Atof (theArgVec[theArgNb - 4]),
-                      Draw::Atof (theArgVec[theArgNb - 3]),
-                      Draw::Atof (theArgVec[theArgNb - 2]))),
-      Draw::Atof (theArgVec[theArgNb - 1]) * (M_PI / 180.0));
+  const gp_Trsf       aTrsf = anObj->LocalTransformation();
+  const gp_XYZ        aLoc  = aTrsf.TranslationPart();
+  const gp_Quaternion aRot  = aTrsf.GetRotation();
+  char aText[4096];
+  Sprintf (aText, "Location: %g %g %g\n"
+                  "Rotation: %g %g %g %g\n"
+                  "Scale:    %g\n",
+                  aLoc.X(), aLoc.Y(), aLoc.Z(),
+                  aRot.X(), aRot.Y(), aRot.Z(), aRot.W(),
+                  aTrsf.ScaleFactor());
+  theDI << aText;
+  return 0;
+}
 
-    aLast = theArgNb - 7;
+//! Find displayed object.
+static Handle(AIS_InteractiveObject) findConnectedObject (const TCollection_AsciiString& theName)
+{
+  Handle(AIS_InteractiveObject) aPrs;
+  if (!GetMapOfAIS().Find2 (theName, aPrs))
+  {
+    return Handle(AIS_InteractiveObject)();
   }
-  else if (!strcmp (aName, "mirror"))
+  if (Handle(AIS_ConnectedInteractive) aConnected = Handle(AIS_ConnectedInteractive)::DownCast (aPrs))
   {
-    if (theArgNb < 8)
-    {
-      std::cout << "Error: too few arguments.\n";
-      return 1;
-    }
-
-    aTrsf.SetMirror (gp_Ax2 (gp_Pnt (Draw::Atof(theArgVec[theArgNb - 6]),
-                                     Draw::Atof(theArgVec[theArgNb - 5]),
-                                     Draw::Atof(theArgVec[theArgNb - 4])),
-                             gp_Vec (Draw::Atof(theArgVec[theArgNb - 3]),
-                                     Draw::Atof(theArgVec[theArgNb - 2]),
-                                     Draw::Atof(theArgVec[theArgNb - 1]))));
-    aLast = theArgNb - 6;
+    return aConnected;
   }
-  else if (!strcmp (aName, "scale"))
+  else if (Handle(AIS_MultipleConnectedInteractive) aMultiCon = Handle(AIS_MultipleConnectedInteractive)::DownCast (aPrs))
   {
-    if (theArgNb < 6)
-    {
-      std::cout << "Error: too few arguments.\n";
-      return 1;
-    }
-
-    aTrsf.SetScale (gp_Pnt (Draw::Atof(theArgVec[theArgNb - 4]),
-                            Draw::Atof(theArgVec[theArgNb - 3]),
-                            Draw::Atof(theArgVec[theArgNb - 2])),
-                    Draw::Atof(theArgVec[theArgNb - 1]));
-    aLast = theArgNb - 4;
+    return aMultiCon;
   }
 
-  for (Standard_Integer anIdx = 1; anIdx < aLast; anIdx++)
+  // replace already displayed object with connected one
+  TheAISContext()->Remove (aPrs, false);
+  Handle(AIS_ConnectedInteractive) aConnected = new AIS_ConnectedInteractive();
+  if (aPrs->HasDisplayMode())
   {
-    // find object
-    const ViewerTest_DoubleMapOfInteractiveAndName& aMap = GetMapOfAIS();
-    Handle(AIS_InteractiveObject) anIObj;
-    if (aMap.IsBound2 (theArgVec[anIdx]))
-    {
-      anIObj = Handle(AIS_InteractiveObject)::DownCast (aMap.Find2 (theArgVec[anIdx]));
-    }
-    if (anIObj.IsNull())
-    {
-      std::cout << "Error: object '" << theArgVec[anIdx] << "' is not displayed!\n";
-      return 1;
-    }
-    
-    if (isReset)
-    {
-      // aTrsf already identity
-    }
-    else if (isMove)
-    {
-      aTrsf = anIObj->LocalTransformation() * anIObj->Transformation().Inverted() * aTrsf;
-    }
-    else
-    {
-      aTrsf = anIObj->LocalTransformation() * aTrsf;
-    }
-
-    TopLoc_Location aLocation (aTrsf);
-    aContext->SetLocation (anIObj, aLocation);
+    aConnected->SetDisplayMode (aPrs->DisplayMode());
   }
-
-  return 0;
+  aConnected->Connect (aPrs, aPrs->LocalTransformationGeom());
+  if (!aPrs->TransformPersistence().IsNull())
+  {
+    aConnected->SetTransformPersistence (aPrs->TransformPersistence());
+  }
+  ViewerTest::Display (theName, aConnected, false);
+  return aConnected;
 }
 
 //===============================================================================================
 //function : VConnect
-//purpose  : Creates and displays AIS_ConnectedInteractive object from input object and location 
-//Draw arg : vconnect name Xo Yo Zo object1 object2 ... [color=NAME]
+//purpose  : Creates and displays AIS_ConnectedInteractive object from input object and location
 //===============================================================================================
-
-static Standard_Integer VConnect (Draw_Interpretor& /*di*/, 
-                                  Standard_Integer argc, 
-                                  const char ** argv) 
+static Standard_Integer VConnect (Draw_Interpretor& /*di*/,
+                                  Standard_Integer argc,
+                                  const char ** argv)
 {
-  // Check the viewer
   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
   if (aContext.IsNull())
   {
-    std::cout << "vconnect error : call vinit before\n";
-    return 1; // TCL_ERROR
+    Message::SendFail ("Error: no active viewer");
+    return 1;
   }
-  // Check argumnets 
   if (argc < 6)
   {
-    std::cout << "vconnect error: expect at least 5 arguments\n";
-    return 1; // TCL_ERROR
+    Message::SendFail ("Syntax error: expect at least 5 arguments");
+    return 1;
   }
 
   // Get values
   Standard_Integer anArgIter = 1;
-  TCollection_AsciiString aName (argv[anArgIter++]);
-  Handle(AIS_MultipleConnectedInteractive) anOriginObject;
+  const TCollection_AsciiString aName (argv[anArgIter++]);
+  Handle(AIS_MultipleConnectedInteractive) aMultiConObject;
   TCollection_AsciiString aColorString (argv[argc-1]);
   Standard_CString aColorName = "";
   Standard_Boolean hasColor = Standard_False;
@@ -3897,114 +4295,84 @@ static Standard_Integer VConnect (Draw_Interpretor& /*di*/,
     aColorString.Remove (1, 6);
     aColorName = aColorString.ToCString();
   }
-  Handle(AIS_InteractiveObject) anObject;
 
-  // AIS_MultipleConnectedInteractive
   const Standard_Integer aNbShapes = hasColor ? (argc - 1) : argc;
   for (Standard_Integer i = 5; i < aNbShapes; ++i)
   {
     TCollection_AsciiString anOriginObjectName (argv[i]);
+    Handle(AIS_InteractiveObject) anObject;
     if (aName.IsEqual (anOriginObjectName))
     {
-      std::cout << "vconnect error: equal names for connected objects\n";
+      Message::SendFail ("Syntax error: equal names for connected objects");
       continue;
     }
-    if (GetMapOfAIS().IsBound2 (anOriginObjectName))
-    {
-      Handle(Standard_Transient) anObj = GetMapOfAIS().Find2 (anOriginObjectName);
-      anObject = Handle(AIS_InteractiveObject)::DownCast(anObj);
-      if (anObject.IsNull())
-      {
-        std::cout << "Object " << anOriginObjectName << " is used for non AIS viewer\n";
-        continue;
-      }
-    }
-    else
+
+    anObject = findConnectedObject (anOriginObjectName);
+    if (anObject.IsNull())
     {
-      Standard_CString aOriginName = anOriginObjectName.ToCString();
-      TopoDS_Shape aTDShape = DBRep::Get (aOriginName);
+      TopoDS_Shape aTDShape = DBRep::Get (anOriginObjectName);
       if (aTDShape.IsNull())
       {
-        std::cout << "vconnect error: object " << anOriginObjectName << " doesn't exist\n";
-        continue;
+        Message::SendFail() << "Syntax error: object " << anOriginObjectName << " doesn't exist";
+        return 1;
       }
-      anObject = new AIS_Shape (aTDShape);
+      Handle(AIS_Shape) aShapePrs = new AIS_Shape (aTDShape);
+      Handle(AIS_ConnectedInteractive) aConnectedOrig = new AIS_ConnectedInteractive();
+      aConnectedOrig->Connect (aShapePrs);
+      anObject = aConnectedOrig;
+
       aContext->Load (anObject);
       anObject->SetColor (ViewerTest::GetColorFromName (aColorName));
     }
 
-    if (anOriginObject.IsNull())
+    if (aMultiConObject.IsNull())
     {
-      anOriginObject = new AIS_MultipleConnectedInteractive();
+      aMultiConObject = new AIS_MultipleConnectedInteractive();
     }
 
-    anOriginObject->Connect (anObject);
+    aMultiConObject->Connect (anObject);
   }
-  if (anOriginObject.IsNull())
+  if (aMultiConObject.IsNull())
   {
-    std::cout << "vconect error : can't connect input objects\n";
-    return 1; // TCL_ERROR
+    Message::SendFail ("Syntax error: can't connect input objects");
+    return 1;
   }
 
-  // Get location data
-  Standard_Real aXo = Draw::Atof (argv[anArgIter++]);
-  Standard_Real aYo = Draw::Atof (argv[anArgIter++]);
-  Standard_Real aZo = Draw::Atof (argv[anArgIter++]);
-
   // Create transformation
-  gp_Vec aTranslation (aXo, aYo, aZo);
-
   gp_Trsf aTrsf; 
-  aTrsf.SetTranslationPart (aTranslation);
-  TopLoc_Location aLocation (aTrsf);
-
-  anOriginObject->SetLocalTransformation (aTrsf);
-
-  // Check if there is another object with given name
-  // and remove it from context
-  if(GetMapOfAIS().IsBound2(aName))
-  {
-    Handle(AIS_InteractiveObject) anObj = 
-      Handle(AIS_InteractiveObject)::DownCast(GetMapOfAIS().Find2(aName));
-    TheAISContext()->Remove(anObj, Standard_False);
-    GetMapOfAIS().UnBind2(aName);
-  }
-
-  // Bind connected object to its name
-  GetMapOfAIS().Bind (anOriginObject, aName);
+  aTrsf.SetTranslationPart (gp_Vec (Draw::Atof (argv[anArgIter + 0]),
+                                    Draw::Atof (argv[anArgIter + 1]),
+                                    Draw::Atof (argv[anArgIter + 2])));
+  TopLoc_Location aLocation (aTrsf);
+  anArgIter += 3;
 
-  // Display connected object
-  TheAISContext()->Display (anOriginObject);
+  aMultiConObject->SetLocalTransformation (aTrsf);
 
+  ViewerTest::Display (aName, aMultiConObject, true);
   return 0;
 }
 
 //===============================================================================================
 //function : VConnectTo
 //purpose  : Creates and displays AIS_ConnectedInteractive object from input object and location 
-//Draw arg : vconnectto name Xo Yo Zo object [-nodisplay|-noupdate|-update]
 //===============================================================================================
-
-static Standard_Integer VConnectTo (Draw_Interpretor& /*di*/, 
-                                    Standard_Integer argc, 
-                                    const char ** argv) 
+static Standard_Integer VConnectTo (Draw_Interpretor& /*di*/,
+                                    Standard_Integer argc,
+                                    const char ** argv)
 {
-  // Check the viewer
   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
   ViewerTest_AutoUpdater anUpdateTool (aContext, ViewerTest::CurrentView());
   if (aContext.IsNull())
   {
-    std::cout << "vconnect error : call vinit before\n";
-    return 1; // TCL_ERROR
+    Message::SendFail ("Error: no active viewer");
+    return 1;
   }
-  // Check argumnets 
   if (argc != 6 && argc != 7)
   {
-    std::cout << "vconnect error: expect at least 5 arguments\n";
-    return 1; // TCL_ERROR
+    Message::SendFail ("Syntax error: expect at least 5 arguments");
+    return 1;
   }
 
-  // Get values
   Standard_Integer anArgIter = 1;
   TCollection_AsciiString aName (argv[anArgIter++]);
   Handle(AIS_InteractiveObject) anOriginObject;
@@ -4012,78 +4380,61 @@ static Standard_Integer VConnectTo (Draw_Interpretor& /*di*/,
   TCollection_AsciiString anOriginObjectName(argv[5]);
   if (aName.IsEqual (anOriginObjectName))
   {
-    std::cout << "vconnect error: equal names for connected objects\n"; 
-    return 1; // TCL_ERROR
-  }
-  if (GetMapOfAIS().IsBound2 (anOriginObjectName))
-  {
-    Handle(Standard_Transient) anObj = GetMapOfAIS().Find2 (anOriginObjectName);
-    anOriginObject = Handle(AIS_InteractiveObject)::DownCast(anObj);
-    if (anOriginObject.IsNull())
-    {
-      std::cout << "Object " << anOriginObjectName << " is used for non AIS viewer\n";
-      return 1; // TCL_ERROR
-    }
+    Message::SendFail ("Syntax error: equal names for connected objects");
+    return 1;
   }
-  else
+  anOriginObject = findConnectedObject (anOriginObjectName);
+  if (anOriginObject.IsNull())
   {
-    Standard_CString aOriginName = anOriginObjectName.ToCString();
-    TopoDS_Shape aTDShape = DBRep::Get (aOriginName);
+    TopoDS_Shape aTDShape = DBRep::Get (anOriginObjectName);
     if (aTDShape.IsNull())
     {
-      std::cout << "vconnect error: object " << anOriginObjectName << " doesn't exist\n";
-      return 1; // TCL_ERROR
+      Message::SendFail() << "Syntax error: object " << anOriginObjectName << " doesn't exist";
+      return 1;
     }
-    anOriginObject = new AIS_Shape (aTDShape);
-    GetMapOfAIS().Bind (anOriginObject, anOriginObjectName);
-  }
-  // Get location data
-  Standard_Real aXo = Draw::Atof (argv[anArgIter++]);
-  Standard_Real aYo = Draw::Atof (argv[anArgIter++]);
-  Standard_Real aZo = Draw::Atof (argv[anArgIter++]);
-
-  // Create transformation
-  gp_Vec aTranslation (aXo, aYo, aZo);
-
-  gp_Trsf aTrsf; 
-  aTrsf.SetTranslationPart (aTranslation);
-  Handle(AIS_ConnectedInteractive) aConnected;
-
-  aConnected = new AIS_ConnectedInteractive();
 
-  aConnected->Connect (anOriginObject, aTrsf);
+    Handle(AIS_Shape) aShapePrs = new AIS_Shape (aTDShape);
+    Handle(AIS_ConnectedInteractive) aConnectedOrig = new AIS_ConnectedInteractive();
+    aConnectedOrig->Connect (aShapePrs);
 
-  // Check if there is another object with given name
-  // and remove it from context
-  if(GetMapOfAIS().IsBound2(aName))
-  {
-    Handle(AIS_InteractiveObject) anObj = 
-      Handle(AIS_InteractiveObject)::DownCast(GetMapOfAIS().Find2(aName));
-    TheAISContext()->Remove(anObj, Standard_False);
-    GetMapOfAIS().UnBind2(aName);
+    anOriginObject = aConnectedOrig;
+    GetMapOfAIS().Bind (aConnectedOrig, anOriginObjectName);
   }
 
-  // Bind connected object to its name
-  GetMapOfAIS().Bind (aConnected, aName);
+  // Create transformation
+  gp_Trsf aTrsf;
+  aTrsf.SetTranslationPart (gp_Vec (Draw::Atof (argv[anArgIter + 0]),
+                                    Draw::Atof (argv[anArgIter + 1]),
+                                    Draw::Atof (argv[anArgIter + 2])));
+  anArgIter += 3;
 
+  Handle(AIS_ConnectedInteractive) aConnected = new AIS_ConnectedInteractive();
+  aConnected->Connect (anOriginObject, aTrsf);
   if (argc == 7)
   {
     TCollection_AsciiString anArg = argv[6];
     anArg.LowerCase();
     if (anArg == "-nodisplay")
+    {
+      // bind connected object without displaying it
+      Handle(AIS_InteractiveObject) anObj;
+      if (GetMapOfAIS().Find2 (aName, anObj))
+      {
+        TheAISContext()->Remove (anObj, false);
+        GetMapOfAIS().UnBind2 (aName);
+      }
+      GetMapOfAIS().Bind (aConnected, aName);
       return 0;
+    }
 
     if (!anUpdateTool.parseRedrawMode (anArg))
     {
-      std::cout << "Warning! Unknown argument '" << anArg << "' passed, -nodisplay|-noupdate|-update expected at this point.\n";
+      Message::SendFail() << "Syntax error: unknown argument '" << anArg << "'";
+      return 1;
     }
   }
 
-  // Display connected object
-  TheAISContext()->Display (aConnected, Standard_False);
-
+  ViewerTest::Display (aName, aConnected, false);
   return 0;
 }
 
@@ -4098,13 +4449,13 @@ static Standard_Integer VDisconnect (Draw_Interpretor& di,
   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
   if (aContext.IsNull())
   {
-    std::cout << argv[0] << "ERROR : use 'vinit' command before " << "\n";
+    Message::SendFail( "Error: no active viewer");
     return 1;
   }
   
   if (argc != 3)
   {
-    std::cout << "ERROR : Usage : " << argv[0] << " name object" << "\n";
+    Message::SendFail() << "Syntax error: wrong number of arguments.\nUsage: " << argv[0] << " name object";
     return 1;
   }
 
@@ -4117,19 +4468,19 @@ static Standard_Integer VDisconnect (Draw_Interpretor& di,
   Handle(AIS_MultipleConnectedInteractive) anAssembly;
   if (!aMap.IsBound2 (aName) )
   {
-    std::cout << "Use 'vdisplay' before" << "\n";
+    Message::SendFail ("Error: no active viewer");
     return 1;
   }
 
   anAssembly = Handle(AIS_MultipleConnectedInteractive)::DownCast (aMap.Find2 (aName));
   if (anAssembly.IsNull())
   {
-    di << "Not an assembly" << "\n";
+    di << "Not an assembly\n";
     return 1;
   }
 
   Handle(AIS_InteractiveObject) anIObj;
-  if (!aMap.IsBound2 (anObject))
+  if (!aMap.Find2 (anObject, anIObj))
   {
     // try to interpret second argument as child number
     if (anObjectNumber > 0 && anObjectNumber <= anAssembly->Children().Size())
@@ -4147,20 +4498,13 @@ static Standard_Integer VDisconnect (Draw_Interpretor& di,
     }
     else
     {
-      std::cout << "Use 'vdisplay' before" << "\n";
+      Message::SendFail ("Error: no active viewer");
       return 1;
     }    
   }
 
-  // if object was found by name
-  if (anIObj.IsNull())
-  {
-    anIObj = Handle(AIS_InteractiveObject)::DownCast (aMap.Find2 (anObject));
-  }
-
   aContext->Disconnect (anAssembly, anIObj);
   aContext->UpdateCurrentViewer();
-
   return 0;
 }
 
@@ -4168,62 +4512,57 @@ static Standard_Integer VDisconnect (Draw_Interpretor& di,
 //function : VAddConnected
 //purpose  :
 //=======================================================================
-static Standard_Integer VAddConnected (Draw_Interpretor& di,
+static Standard_Integer VAddConnected (Draw_Interpretor& ,
                                        Standard_Integer argc,
                                        const char ** argv)
 {
   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
   if (aContext.IsNull())
   {
-    std::cout << argv[0] << "error : use 'vinit' command before " << "\n";
+    Message::SendFail ("Error: no active viewer");
     return 1;
   }
-  
+
   if (argc != 6)
   {
-    std::cout << argv[0] << " error: expect 5 arguments\n";
+    Message::SendFail ("Syntax error: expect 5 arguments");
     return 1;
   }
 
-  TCollection_AsciiString aName (argv[1]);
-  TCollection_AsciiString anObject (argv[5]);
-  Standard_Real aX = Draw::Atof (argv[2]);
-  Standard_Real aY = Draw::Atof (argv[3]);
-  Standard_Real aZ = Draw::Atof (argv[4]);
+  const TCollection_AsciiString aName (argv[1]);
+  const Standard_Real aX = Draw::Atof (argv[2]);
+  const Standard_Real aY = Draw::Atof (argv[3]);
+  const Standard_Real aZ = Draw::Atof (argv[4]);
+  const TCollection_AsciiString anObjectName (argv[5]);
 
   // find object
   ViewerTest_DoubleMapOfInteractiveAndName& aMap = GetMapOfAIS();
   Handle(AIS_MultipleConnectedInteractive) anAssembly;
-  if (!aMap.IsBound2 (aName) )
   {
-    std::cout << "Use 'vdisplay' before" << "\n";
-    return 1;
+    Handle(AIS_InteractiveObject) aPrs;
+    aMap.Find2 (aName, aPrs);
+    anAssembly = Handle(AIS_MultipleConnectedInteractive)::DownCast (aPrs);
+    if (anAssembly.IsNull())
+    {
+      Message::SendFail() << "Syntax error: '" << aName << "' is not an assembly";
+      return 1;
+    }
   }
 
-  anAssembly = Handle(AIS_MultipleConnectedInteractive)::DownCast (aMap.Find2 (aName));
-  if (anAssembly.IsNull())
+  Handle(AIS_InteractiveObject) anIObj = findConnectedObject (anObjectName);
+  if (anIObj.IsNull())
   {
-    di << "Not an assembly" << "\n";
+    Message::SendFail() << "Syntax error: '" << anObjectName << "' is not displayed";
     return 1;
   }
 
-  Handle(AIS_InteractiveObject) anIObj;
-  if (!aMap.IsBound2 (anObject))
-  {
-      std::cout << "Use 'vdisplay' before" << "\n";
-      return 1; 
-  }
-
-  anIObj = Handle(AIS_InteractiveObject)::DownCast (aMap.Find2 (anObject));
-
   gp_Trsf aTrsf;
   aTrsf.SetTranslation (gp_Vec (aX, aY, aZ));
  
   anAssembly->Connect (anIObj, aTrsf);
-  TheAISContext()->Display (anAssembly);
+  TheAISContext()->Display (anAssembly, Standard_False);
   TheAISContext()->RecomputeSelectionOnly (anAssembly);
   aContext->UpdateCurrentViewer();
-
   return 0;
 }
 
@@ -4238,13 +4577,13 @@ static Standard_Integer VListConnected (Draw_Interpretor& /*di*/,
   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
   if (aContext.IsNull())
   {
-    std::cout << argv[0] << "ERROR : use 'vinit' command before " << "\n";
+    Message::SendFail ("Error: no active viewer");
     return 1;
   }
   
   if (argc != 2)
   {
-    std::cout << "ERROR : Usage : " << argv[0] << " name" << "\n";
+    Message::SendFail() << "Syntax error: wrong number of arguments.\nUsage: " << argv[0] << " name";
     return 1;
   }
 
@@ -4255,14 +4594,14 @@ static Standard_Integer VListConnected (Draw_Interpretor& /*di*/,
   Handle(AIS_MultipleConnectedInteractive) anAssembly;
   if (!aMap.IsBound2 (aName) )
   {
-    std::cout << "Use 'vdisplay' before" << "\n";
+    Message::SendFail ("Error: no active viewer");
     return 1;
   }
 
   anAssembly = Handle(AIS_MultipleConnectedInteractive)::DownCast (aMap.Find2 (aName));
   if (anAssembly.IsNull())
   {
-    std::cout << "Not an assembly" << "\n";
+    Message::SendFail ("Syntax error: Not an assembly");
     return 1;
   }
 
@@ -4271,9 +4610,10 @@ static Standard_Integer VListConnected (Draw_Interpretor& /*di*/,
   Standard_Integer aCounter = 1;
   for (PrsMgr_ListOfPresentableObjectsIter anIter (anAssembly->Children()); anIter.More(); anIter.Next())
   {
-    if (GetMapOfAIS().IsBound1 (anIter.Value()))
+    Handle(AIS_InteractiveObject) anObj = Handle(AIS_InteractiveObject)::DownCast (anIter.Value());
+    if (GetMapOfAIS().IsBound1 (anObj))
     {
-      TCollection_AsciiString aCuurrentName = GetMapOfAIS().Find1 (anIter.Value());
+      TCollection_AsciiString aCuurrentName = GetMapOfAIS().Find1 (anObj);
       std::cout << aCounter << ")  " << aCuurrentName << "    (" << anIter.Value()->DynamicType()->Name() << ")";
     }
 
@@ -4292,509 +4632,364 @@ static Standard_Integer VListConnected (Draw_Interpretor& /*di*/,
   return 0;
 }
 
-namespace
-{
-  //! Checks if theMode is already turned on for theObj.
-  static Standard_Boolean InList (const Handle(AIS_InteractiveContext)& theAISContext,
-                                  const Handle(AIS_InteractiveObject)&  theObj,
-                                  const Standard_Integer                theMode)
-  {
-    TColStd_ListOfInteger anActiveModes;
-    theAISContext->ActivatedModes (theObj, anActiveModes);
-    for (TColStd_ListIteratorOfListOfInteger aModeIt (anActiveModes); aModeIt.More(); aModeIt.Next())
-    {
-      if (aModeIt.Value() == theMode)
-      {
-        return Standard_True;
-      }
-    }
-    return Standard_False;
-  }
-};
-
-//===============================================================================================
-//function : VSetSelectionMode
-//purpose  : Sets input selection mode for input object or for all displayed objects 
-//Draw arg : vselmode [object] mode On/Off (1/0)
-//===============================================================================================
-static Standard_Integer VSetSelectionMode (Draw_Interpretor& /*di*/,
-                                           Standard_Integer  theArgc,
-                                           const char**      theArgv)
+//=======================================================================
+//function : VChild
+//purpose  :
+//=======================================================================
+static Standard_Integer VChild (Draw_Interpretor& ,
+                                Standard_Integer theNbArgs,
+                                const char** theArgVec)
 {
-  // Check errors
-  Handle(AIS_InteractiveContext) anAISContext = ViewerTest::GetAISContext();
-  if (anAISContext.IsNull())
-  {
-    std::cerr << "Call vinit before!" << std::endl;
-    return 1;
-  }
-
-  // Check the arguments
-  if (theArgc < 3 && theArgc > 5)
+  Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
+  if (aContext.IsNull())
   {
-    std::cerr << "vselmode error : expects at least 2 arguments.\n"
-              << "Type help "<< theArgv[0] <<" for more information." << std::endl;
+    Message::SendFail ("Error: no active viewer");
     return 1;
   }
 
-  TCollection_AsciiString aLastArg (theArgv[theArgc - 1]);
-  aLastArg.LowerCase();
-  Standard_Boolean isToOpenLocalCtx = aLastArg == "-local";
-
-  // get objects to change selection mode
-  AIS_ListOfInteractive aTargetIOs;
-  Standard_Integer anArgNb = isToOpenLocalCtx ? theArgc - 1 : theArgc;
-  if (anArgNb == 3)
-  {
-    anAISContext->DisplayedObjects (aTargetIOs);
-  }
-  else
+  int toAdd = -1;
+  Handle(AIS_InteractiveObject) aParent;
+  bool hasActions = false;
+  int toInheritTrsf = -1;
+  ViewerTest_AutoUpdater anUpdateTool (aContext, ViewerTest::CurrentView());
+  for (Standard_Integer anArgIter = 1; anArgIter < theNbArgs; ++anArgIter)
   {
-    // Check if there is an object with given name in context
-    const TCollection_AsciiString aNameIO (theArgv[1]);
-    if (GetMapOfAIS().IsBound2 (aNameIO))
+    TCollection_AsciiString anArg (theArgVec[anArgIter]);
+    anArg.LowerCase();
+    if (anUpdateTool.parseRedrawMode (anArg))
     {
-      Handle(AIS_InteractiveObject) anIO = Handle(AIS_InteractiveObject)::DownCast (GetMapOfAIS().Find2 (aNameIO));
-      if (anIO.IsNull())
-      {
-        std::cerr << "vselmode error : object name is used for non AIS viewer" << std::endl;
-        return 1;
-      }
-      aTargetIOs.Append (anIO);
+      continue;
     }
-  }
-
-  const Standard_Integer aSelectionMode = Draw::Atoi (anArgNb == 3 ? theArgv[1] : theArgv[2]);
-  const Standard_Boolean toTurnOn       = Draw::Atoi (anArgNb == 3 ? theArgv[2] : theArgv[3]);
-  if (aSelectionMode == 0 && anAISContext->HasOpenedContext())
-  {
-    anAISContext->CloseLocalContext();
-  }
-
-  if (aSelectionMode == 0)
-  {
-    if (toTurnOn)
+    else if (anArg == "-add")
     {
-      for (AIS_ListIteratorOfListOfInteractive aTargetIt (aTargetIOs); aTargetIt.More(); aTargetIt.Next())
-      {
-        const Handle(AIS_InteractiveObject)& anIO = aTargetIt.Value();
-        TColStd_ListOfInteger anActiveModes;
-        anAISContext->ActivatedModes (anIO, anActiveModes);
-        if (!anActiveModes.IsEmpty())
-        {
-          anAISContext->Deactivate (anIO);
-        }
-        if (!InList (anAISContext, anIO, aSelectionMode))
-        {
-          anAISContext->Activate (anIO);
-        }
-      }
+      toAdd = 1;
+      continue;
     }
-    else
+    else if (anArg == "-remove")
+    {
+      toAdd = 0;
+      continue;
+    }
+    else if (anArg == "-inheritparenttrsf"
+      || anArg == "-inheritparentloc"
+      || anArg == "-inheritparentlocation"
+      || anArg == "-inheritparent"
+      || anArg == "-noinheritparenttrsf"
+      || anArg == "-noinheritparentloc"
+      || anArg == "-noinheritparentlocation"
+      || anArg == "-noinheritparent"
+      || anArg == "-ignoreparenttrsf"
+      || anArg == "-ignoreparentloc"
+      || anArg == "-ignoreparentlocation"
+      || anArg == "-ignoreparent")
     {
-      for (AIS_ListIteratorOfListOfInteractive aTargetIt (aTargetIOs); aTargetIt.More(); aTargetIt.Next())
+      bool aVal = true;
+      if (anArgIter + 1 < theNbArgs
+        && ViewerTest::ParseOnOff(theArgVec[anArgIter + 1], aVal))
       {
-        const Handle(AIS_InteractiveObject)& anIO = aTargetIt.Value();
-        if (InList (anAISContext, anIO, aSelectionMode))
-        {
-          anAISContext->Deactivate (anIO);
-        }
+        ++anArgIter;
+      }
+      if (anArg.StartsWith("-no")
+        || anArg.StartsWith("-ignore"))
+      {
+        aVal = !aVal;
       }
+      toInheritTrsf = aVal ? 1 : 0;
+      continue;
     }
-  }
 
-  if (aSelectionMode != 0 && toTurnOn) // Turn on specified mode
-  {
-    if (!anAISContext->HasOpenedContext() && isToOpenLocalCtx)
+    Handle(AIS_InteractiveObject) aChild;
+    if (!GetMapOfAIS().Find2 (theArgVec[anArgIter], aChild))
     {
-      anAISContext->OpenLocalContext (Standard_False);
+      Message::SendFail() << "Syntax error: object '" << theArgVec[anArgIter] << "' is not found";
+      return 1;
     }
 
-    for (AIS_ListIteratorOfListOfInteractive aTargetIt (aTargetIOs); aTargetIt.More(); aTargetIt.Next())
+    if (aParent.IsNull())
+    {
+      aParent = aChild;
+    }
+    else if (toAdd == -1)
+    {
+      Message::SendFail ("Syntax error: no action specified");
+      return 1;
+    }
+    else
     {
-      const Handle(AIS_InteractiveObject)& anIO = aTargetIt.Value();
-      if (InList (anAISContext, anIO, 0))
+      hasActions = true;
+      if (toAdd == 1)
       {
-        anAISContext->Deactivate (anIO, 0);
+        if(toInheritTrsf == 0)
+          aParent->AddChildWithCurrentTransformation(aChild);
+        else
+          aParent->AddChild (aChild);
       }
-      if (!InList (anAISContext, anIO, aSelectionMode))
+      else
       {
-        anAISContext->Load (anIO, -1, Standard_True);
-        anAISContext->Activate (anIO, aSelectionMode);
+        if (toInheritTrsf == 0)
+          aParent->RemoveChildWithRestoreTransformation(aChild);
+        else
+          aParent->RemoveChild (aChild);
       }
     }
   }
-
-  if (aSelectionMode != 0 && !toTurnOn) // Turn off specified mode
+  if (!hasActions)
   {
-    for (AIS_ListIteratorOfListOfInteractive aTargetIt (aTargetIOs); aTargetIt.More(); aTargetIt.Next())
-    {
-      const Handle(AIS_InteractiveObject)& anIO = aTargetIt.Value();
-      if (InList (anAISContext, anIO, aSelectionMode))
-      {
-        anAISContext->Deactivate (anIO, aSelectionMode);
-      }
-    }
+    Message::SendFail ("Syntax error: not enough arguments");
+    return 1;
   }
-
   return 0;
 }
 
-//===============================================================================================
-//function : VSelectionNext
-//purpose  : 
-//===============================================================================================
-static Standard_Integer VSelectionNext(Draw_Interpretor& /*theDI*/,
-                                 Standard_Integer /*theArgsNb*/,
-                                 const char** /*theArgVec*/)
+//=======================================================================
+//function : VParent
+//purpose  :
+//=======================================================================
+static Standard_Integer VParent(Draw_Interpretor&,
+  Standard_Integer theNbArgs,
+  const char** theArgVec)
 {
-  // Check errors
-  Handle(AIS_InteractiveContext) anAISContext = ViewerTest::GetAISContext();
-  Handle(V3d_View) aView = ViewerTest::CurrentView();
-
-  if (anAISContext.IsNull())
+  Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
+  if (aContext.IsNull())
   {
-    std::cerr << "Call vinit before!" << std::endl;
+    Message::SendFail ("Error: no active viewer");
     return 1;
   }
 
-  anAISContext->HilightNextDetected(aView);
-  return 0;
-}
-
-//===============================================================================================
-//function : VSelectionPrevious
-//purpose  : 
-//===============================================================================================
-static Standard_Integer VSelectionPrevious(Draw_Interpretor& /*theDI*/,
-                                 Standard_Integer /*theArgsNb*/,
-                                 const char** /*theArgVec*/)
-{
-  // Check errors
-  Handle(AIS_InteractiveContext) anAISContext = ViewerTest::GetAISContext();
-  Handle(V3d_View) aView = ViewerTest::CurrentView();
-
-  if (anAISContext.IsNull())
+  if (theNbArgs < 2 )
   {
-    std::cerr << "Call vinit before!" << std::endl;
+    Message::SendFail ("Syntax error: wrong number of arguments");
     return 1;
   }
 
-  anAISContext->HilightPreviousDetected(aView);
-  return 0;
-}
-
-
-//==========================================================================
-//class   : Triangle 
-//purpose : creates Triangle based on AIS_InteractiveObject. 
-//          This class was implemented for testing Select3D_SensitiveTriangle
-//===========================================================================
-
-class Triangle: public AIS_InteractiveObject 
-{
-public: 
-  // CASCADE RTTI
-  DEFINE_STANDARD_RTTI(Triangle, AIS_InteractiveObject);
-  Triangle (const gp_Pnt& theP1, 
-            const gp_Pnt& theP2, 
-            const gp_Pnt& theP3);
-protected:
-  void Compute (  const Handle(PrsMgr_PresentationManager3d)& thePresentationManager,
-                  const Handle(Prs3d_Presentation)& thePresentation,
-                  const Standard_Integer theMode);
-
-  void ComputeSelection (  const Handle(SelectMgr_Selection)& theSelection, 
-                           const Standard_Integer theMode);
-private: 
-  gp_Pnt myPoint1;
-  gp_Pnt myPoint2;
-  gp_Pnt myPoint3;
-};
-
-
-Triangle::Triangle (const gp_Pnt& theP1,
-                    const gp_Pnt& theP2,
-                    const gp_Pnt& theP3)
-{
-  myPoint1 = theP1;
-  myPoint2 = theP2;
-  myPoint3 = theP3;
-}
-
-void Triangle::Compute(const Handle(PrsMgr_PresentationManager3d)& /*thePresentationManager*/,
-                       const Handle(Prs3d_Presentation)& thePresentation,
-                       const Standard_Integer /*theMode*/)
-{
-  thePresentation->Clear();
-
-  BRepBuilderAPI_MakeEdge anEdgeMaker1(myPoint1, myPoint2),
-                          anEdgeMaker2(myPoint2, myPoint3),
-                          anEdgeMaker3(myPoint3, myPoint1);
-
-  TopoDS_Edge anEdge1 = anEdgeMaker1.Edge(),
-              anEdge2 = anEdgeMaker2.Edge(),
-              anEdge3 = anEdgeMaker3.Edge();
-  if(anEdge1.IsNull() || anEdge2.IsNull() || anEdge3.IsNull())
-    return;
-
-  BRepBuilderAPI_MakeWire aWireMaker(anEdge1, anEdge2, anEdge3);
-  TopoDS_Wire aWire = aWireMaker.Wire();
-  if(aWire.IsNull()) return;
-
-  BRepBuilderAPI_MakeFace aFaceMaker(aWire);
-  TopoDS_Face aFace = aFaceMaker.Face();
-  if(aFace.IsNull()) return;
-
-  StdPrs_ShadedShape::Add(thePresentation, aFace, myDrawer);
-}
-
-void Triangle::ComputeSelection(const Handle(SelectMgr_Selection)& theSelection, 
-                                const Standard_Integer /*theMode*/)
-{
-  Handle(SelectMgr_EntityOwner) anEntityOwner = new SelectMgr_EntityOwner(this);
-  Handle(Select3D_SensitiveTriangle) aSensTriangle = 
-    new Select3D_SensitiveTriangle(anEntityOwner, myPoint1, myPoint2, myPoint3);
-  theSelection->Add(aSensTriangle);
-}
-
-//===========================================================================
-//function : VTriangle 
-//Draw arg : vtriangle Name PointName PointName PointName
-//purpose  : creates and displays Triangle
-//===========================================================================
-
-//function: IsPoint
-//purpose : checks if the object with theName is AIS_Point, 
-//          if yes initialize thePoint from MapOfAIS
-Standard_Boolean IsPoint (const TCollection_AsciiString& theName,
-                          Handle(AIS_Point)& thePoint)
-{
-  Handle(AIS_InteractiveObject) anObject = 
-    Handle(AIS_InteractiveObject)::DownCast(GetMapOfAIS().Find2(theName));
-  if(anObject.IsNull() || 
-     anObject->Type() != AIS_KOI_Datum || 
-     anObject->Signature() != 1)
+  TCollection_AsciiString aName(theArgVec[1]);
+  Handle(AIS_InteractiveObject) aParent;
+  if (!GetMapOfAIS().Find2(theArgVec[1], aParent))
   {
-    return Standard_False;
+    Message::SendFail() << "Syntax error: object '" << theArgVec[1] << "' is not found";
+    return 1;
   }
-  thePoint = Handle(AIS_Point)::DownCast(anObject);
-  if(thePoint.IsNull())
-    return Standard_False;
-  return Standard_True;
-}
 
-//function: IsMatch
-//purpose: checks if thePoint1 is equal to thePoint2
-Standard_Boolean IsMatch (const Handle(Geom_CartesianPoint)& thePoint1,
-                          const Handle(Geom_CartesianPoint)& thePoint2)
-{
-  if(Abs(thePoint1->X()-thePoint2->X()) <= Precision::Confusion() &&
-     Abs(thePoint1->Y()-thePoint2->Y()) <= Precision::Confusion() &&
-     Abs(thePoint1->Z()-thePoint2->Z()) <= Precision::Confusion())
+  ViewerTest_AutoUpdater anUpdateTool(aContext, ViewerTest::CurrentView());
+  for (Standard_Integer anArgIter = 2; anArgIter < theNbArgs; ++anArgIter)
   {
-    return Standard_True;
+    TCollection_AsciiString anArg(theArgVec[anArgIter]);
+    anArg.LowerCase();
+    if (anArg == "-ignorevisu")
+      aParent->SetPropagateVisualState(Standard_False);
   }
-  return Standard_False;
+  return 0;
 }
 
-static Standard_Integer VTriangle (Draw_Interpretor& /*di*/,
-                                   Standard_Integer argc,
-                                   const char ** argv)
+//===============================================================================================
+//function : VSetSelectionMode
+//purpose  : vselmode
+//===============================================================================================
+static Standard_Integer VSetSelectionMode (Draw_Interpretor& /*di*/,
+                                           Standard_Integer  theNbArgs,
+                                           const char**      theArgv)
 {
-  // Check arguments
-  if (argc != 5)
+  // Check errors
+  Handle(AIS_InteractiveContext) anAISContext = ViewerTest::GetAISContext();
+  if (anAISContext.IsNull())
   {
-    std::cout<<"vtriangle error: expects 4 argumnets\n";
-    return 1; // TCL_ERROR
+    Message::SendFail ("Error: no active Viewer");
+    return 1;
   }
 
-  TheAISContext()->CloseAllContexts();
-
-  // Get and check values
-  TCollection_AsciiString aName(argv[1]);
-
-  Handle(AIS_Point) aPoint1, aPoint2, aPoint3;
-  if (!IsPoint(argv[2], aPoint1))
+  NCollection_Sequence<TCollection_AsciiString> anObjNames;
+  Standard_Integer aSelectionMode = -1;
+  Standard_Boolean toTurnOn = Standard_True;
+  AIS_SelectionModesConcurrency aSelModeConcurrency = AIS_SelectionModesConcurrency_GlobalOrLocal;
+  for (Standard_Integer anArgIter = 1; anArgIter < theNbArgs; ++anArgIter)
   {
-    std::cout<<"vtriangle error: the 2nd argument must be a point\n";
-    return 1; // TCL_ERROR
+    TCollection_AsciiString anArgCase (theArgv[anArgIter]);
+    anArgCase.LowerCase();
+    if (anArgCase == "-set"
+     || anArgCase == "-replace"
+     || anArgCase == "-single"
+     || anArgCase == "-exclusive")
+    {
+      aSelModeConcurrency = AIS_SelectionModesConcurrency_Single;
+    }
+    else if (anArgCase == "-add"
+          || anArgCase == "-combine"
+          || anArgCase == "-combination"
+          || anArgCase == "-multiple")
+    {
+      aSelModeConcurrency = AIS_SelectionModesConcurrency_Multiple;
+    }
+    else if (anArgCase == "-globalorlocal"
+          || anArgCase == "-localorglobal")
+    {
+      aSelModeConcurrency = AIS_SelectionModesConcurrency_GlobalOrLocal;
+    }
+    else
+    {
+      anObjNames.Append (theArgv[anArgIter]);
+    }
   }
-  if (!IsPoint(argv[3], aPoint2))
+  if (anObjNames.Size() < 2
+  || !ViewerTest::ParseOnOff (anObjNames.Last().ToCString(), toTurnOn))
   {
-    std::cout<<"vtriangle error: the 3d argument must be a point\n";
-    return 1; // TCL_ERROR
+    Message::SendFail ("Syntax error: wrong number of arguments");
+    return 1;
   }
-  if (!IsPoint(argv[4], aPoint3))
+  anObjNames.Remove (anObjNames.Upper());
   {
-    std::cout<<"vtriangle error: the 4th argument must be a point\n";
-    return 1; // TCL_ERROR
+    const TCollection_AsciiString aSelModeString = anObjNames.Last();
+    anObjNames.Remove (anObjNames.Upper());
+    TopAbs_ShapeEnum aShapeType = TopAbs_SHAPE;
+    if (aSelModeString.IsIntegerValue())
+    {
+      aSelectionMode = aSelModeString.IntegerValue();
+    }
+    else if (TopAbs::ShapeTypeFromString (aSelModeString.ToCString(), aShapeType))
+    {
+      aSelectionMode = AIS_Shape::SelectionMode (aShapeType);
+    }
+    else
+    {
+      Message::SendFail() << "Syntax error: unknown selection mode '" << aSelModeString  << "'";
+      return 1;
+    }
   }
 
-  // Check that points are different
-  Handle(Geom_CartesianPoint) aCartPoint1 = 
-    Handle(Geom_CartesianPoint)::DownCast(aPoint1->Component());
-  Handle(Geom_CartesianPoint) aCartPoint2 = 
-    Handle(Geom_CartesianPoint)::DownCast(aPoint2->Component());
-  // Test aPoint1 = aPoint2
-  if (IsMatch(aCartPoint1, aCartPoint2))
-  {
-    std::cout<<"vtriangle error: the 1st and the 2nd points are equal\n";
-    return 1; // TCL_ERROR
-  }
-  // Test aPoint2 = aPoint3
-  Handle(Geom_CartesianPoint) aCartPoint3 = 
-    Handle(Geom_CartesianPoint)::DownCast(aPoint3->Component());
-  if (IsMatch(aCartPoint2, aCartPoint3))
+  AIS_ListOfInteractive aTargetIOs;
+  for (NCollection_Sequence<TCollection_AsciiString>::Iterator anObjIter (anObjNames); anObjIter.More(); anObjIter.Next())
   {
-    std::cout<<"vtriangle error: the 2nd and the 3d points are equal\n";
-    return 1; // TCL_ERROR
+    const TCollection_AsciiString& aNameIO = anObjIter.Value();
+    Handle(AIS_InteractiveObject) anIO;
+    GetMapOfAIS().Find2 (aNameIO, anIO);
+    if (anIO.IsNull())
+    {
+      Message::SendFail() << "Syntax error: undefined presentable object " << aNameIO;
+      return 1;
+    }
+    aTargetIOs.Append (anIO);
   }
-  // Test aPoint3 = aPoint1
-  if (IsMatch(aCartPoint1, aCartPoint3))
+  if (aTargetIOs.IsEmpty())
   {
-    std::cout<<"vtriangle error: the 1st and the 3d points are equal\n";
-    return 1; // TCL_ERROR
+    anAISContext->DisplayedObjects (aTargetIOs);
   }
 
-  // Create triangle
-  Handle(Triangle) aTriangle = new Triangle(aCartPoint1->Pnt(),
-                                            aCartPoint2->Pnt(),
-                                            aCartPoint3->Pnt());
-
-  // Check if there is an object with given name
-  // and remove it from context
-  if (GetMapOfAIS().IsBound2(aName))
+  for (AIS_ListIteratorOfListOfInteractive aTargetIt (aTargetIOs); aTargetIt.More(); aTargetIt.Next())
   {
-    Handle(Standard_Transient) anObj = GetMapOfAIS().Find2(aName);
-    Handle(AIS_InteractiveObject) anInterObj = 
-         Handle(AIS_InteractiveObject)::DownCast(anObj);
-    TheAISContext()->Remove(anInterObj, Standard_False);
-    GetMapOfAIS().UnBind2(aName);
+    const Handle(AIS_InteractiveObject)& anIO = aTargetIt.Value();
+    anAISContext->SetSelectionModeActive (anIO, aSelectionMode, toTurnOn, aSelModeConcurrency);
   }
-
-  // Bind triangle to its name
-  GetMapOfAIS().Bind(aTriangle, aName);
-
-  // Display triangle
-  TheAISContext()->Display(aTriangle);
   return 0;
 }
 
-//class  : SegmentObject
-//purpose: creates segment based on AIS_InteractiveObject.
-//         This class was implemented for testing Select3D_SensitiveCurve
-
-class SegmentObject: public AIS_InteractiveObject
+//===============================================================================================
+//function : VSelectionNext
+//purpose  : 
+//===============================================================================================
+static Standard_Integer VSelectionNext(Draw_Interpretor& /*theDI*/,
+                                 Standard_Integer /*theArgsNb*/,
+                                 const char** /*theArgVec*/)
 {
-public:
-  // CASCADE RTTI
-  DEFINE_STANDARD_RTTI(SegmentObject, AIS_InteractiveObject); 
-  SegmentObject (const gp_Pnt& thePnt1, const gp_Pnt& thePnt2);
-protected:
-  void Compute (const Handle(PrsMgr_PresentationManager3d)& thePresentationManager,
-                const Handle(Prs3d_Presentation)& thePresentation,
-                const Standard_Integer theMode);
-
-  void ComputeSelection (const Handle(SelectMgr_Selection)& theSelection, 
-                         const Standard_Integer theMode);
-private:
-  gp_Pnt myPoint1;
-  gp_Pnt myPoint2;
-};
-
+  // Check errors
+  Handle(AIS_InteractiveContext) anAISContext = ViewerTest::GetAISContext();
+  Handle(V3d_View) aView = ViewerTest::CurrentView();
 
-SegmentObject::SegmentObject (const gp_Pnt& thePnt1, const gp_Pnt& thePnt2)
-{
-  myPoint1 = thePnt1;
-  myPoint2 = thePnt2;
-}
+  if (anAISContext.IsNull())
+  {
+    Message::SendFail ("Error: no active viewer");
+    return 1;
+  }
 
-void SegmentObject::Compute (const Handle(PrsMgr_PresentationManager3d) &/*thePresentationManager*/,
-                             const Handle(Prs3d_Presentation) &thePresentation,
-                             const Standard_Integer /*theMode*/)
-{
-  thePresentation->Clear();
-  BRepBuilderAPI_MakeEdge anEdgeMaker(myPoint1, myPoint2);
-  TopoDS_Edge anEdge = anEdgeMaker.Edge();
-  if (anEdge.IsNull())
-    return;
-  BRepAdaptor_Curve aCurveAdaptor(anEdge);
-  StdPrs_Curve::Add(thePresentation, aCurveAdaptor, myDrawer);
+  anAISContext->HilightNextDetected (aView);
+  return 0;
 }
 
-void SegmentObject::ComputeSelection (const Handle(SelectMgr_Selection) &theSelection,
-                                      const Standard_Integer /*theMode*/)
+//===============================================================================================
+//function : VSelectionPrevious
+//purpose  : 
+//===============================================================================================
+static Standard_Integer VSelectionPrevious(Draw_Interpretor& /*theDI*/,
+                                 Standard_Integer /*theArgsNb*/,
+                                 const char** /*theArgVec*/)
 {
-  Handle(SelectMgr_EntityOwner) anOwner = new SelectMgr_EntityOwner(this);
-  Handle(TColgp_HArray1OfPnt) anArray = new TColgp_HArray1OfPnt(1, 2);
-  anArray->SetValue(1, myPoint1);
-  anArray->SetValue(2, myPoint2);
-  Handle(Select3D_SensitiveCurve) aSensCurve = 
-    new Select3D_SensitiveCurve(anOwner, anArray);
-  theSelection->Add(aSensCurve);
-}
+  // Check errors
+  Handle(AIS_InteractiveContext) anAISContext = ViewerTest::GetAISContext();
+  Handle(V3d_View) aView = ViewerTest::CurrentView();
 
-//=======================================================================
-//function  : VSegment
-//Draw args : vsegment Name PointName PointName
-//purpose   : creates and displays Segment
-//=======================================================================
-static Standard_Integer VSegment (Draw_Interpretor& /*di*/,
-                                  Standard_Integer argc,
-                                  const char ** argv)
-{
-  // Check arguments
-  if(argc!=4)
+  if (anAISContext.IsNull())
   {
-    std::cout<<"vsegment error: expects 3 arguments\n";
-    return 1; // TCL_ERROR
+    Message::SendFail ("Error: no active viewer");
+    return 1;
   }
 
-  TheAISContext()->CloseAllContexts();
+  anAISContext->HilightPreviousDetected (aView);
+  return 0;
+}
 
-  // Get and check arguments
-  TCollection_AsciiString aName(argv[1]);
-  Handle(AIS_Point) aPoint1, aPoint2;
-  if (!IsPoint(argv[2], aPoint1))
+//===========================================================================
+//function : VTriangle 
+//Draw arg : vtriangle Name PointName PointName PointName
+//purpose  : creates and displays Triangle
+//===========================================================================
+static Standard_Integer VTriangle (Draw_Interpretor& /*di*/,
+                                   Standard_Integer argc,
+                                   const char ** argv)
+{
+  const Standard_Boolean isTri = TCollection_AsciiString (argv[0]) == "vtriangle";
+  Handle(Graphic3d_ArrayOfPrimitives) aPrims;
+  if (isTri)
   {
-    std::cout<<"vsegment error: the 2nd argument should be a point\n";
-    return 1; // TCL_ERROR
+    aPrims = new Graphic3d_ArrayOfTriangles (3);
   }
-  if (!IsPoint(argv[3], aPoint2))
+  else
   {
-    std::cout<<"vsegment error: the 3d argument should be a point\n";
-    return 1; // TCL_ERROR
+    aPrims = new Graphic3d_ArrayOfSegments (2);
   }
-  //Check that points are different
-  Handle(Geom_CartesianPoint) aCartPoint1 = 
-    Handle(Geom_CartesianPoint)::DownCast(aPoint1->Component());
-  Handle(Geom_CartesianPoint) aCartPoint2 = 
-    Handle(Geom_CartesianPoint)::DownCast(aPoint2->Component());
-  if(IsMatch(aCartPoint1, aCartPoint2))
+
+  if (argc != (2 + aPrims->VertexNumberAllocated()))
   {
-    std::cout<<"vsegment error: equal points\n";
-    return 1; // TCL_ERROR
+    Message::SendFail ("Syntax error: wrong number of arguments");
+    return 1;
   }
-  
-  // Create segment
-  Handle(SegmentObject) aSegment = new SegmentObject(aCartPoint1->Pnt(), aCartPoint2->Pnt());
-  // Check if there is an object with given name
-  // and remove it from context
-  if (GetMapOfAIS().IsBound2(aName))
+
+  gp_Pnt aPnts[3];
+  for (Standard_Integer aPntIter = 0; aPntIter < aPrims->VertexNumberAllocated(); ++aPntIter)
   {
-    Handle(Standard_Transient) anObj = GetMapOfAIS().Find2(aName);
-    Handle(AIS_InteractiveObject) anInterObj = 
-         Handle(AIS_InteractiveObject)::DownCast(anObj);
-    TheAISContext()->Remove(anInterObj, Standard_False);
-    GetMapOfAIS().UnBind2(aName);
-  }
+    const TCollection_AsciiString aName (argv[2 + aPntIter]);
+    if (Handle(AIS_Point) aPntPrs = Handle(AIS_Point)::DownCast (GetMapOfAIS().IsBound2 (aName) ? GetMapOfAIS().Find2 (aName) : NULL))
+    {
+      aPnts[aPntIter] = aPntPrs->Component()->Pnt();
+    }
+    else
+    {
+      TopoDS_Shape aShape = DBRep::Get (argv[2 + aPntIter]);
+      if (aShape.IsNull()
+       || aShape.ShapeType() != TopAbs_VERTEX)
+      {
+        Message::SendFail() << "Syntax error: argument " << aName << " must be a point";
+        return 1;
+      }
+      aPnts[aPntIter] = BRep_Tool::Pnt (TopoDS::Vertex (aShape));
+    }
 
-  // Bind segment to its name
-  GetMapOfAIS().Bind(aSegment, aName);
+    for (Standard_Integer aPnt2Iter = 0; aPnt2Iter < aPntIter; ++aPnt2Iter)
+    {
+      if (aPnts[aPnt2Iter].IsEqual (aPnts[aPntIter], Precision::Confusion()))
+      {
+        Message::SendFail ("Syntax error: points should not be equal");
+        return 1;
+      }
+    }
+
+    aPrims->AddVertex (aPnts[aPntIter]);
+  }
 
-  // Display segment
-  TheAISContext()->Display(aSegment);
+  Handle(AIS_InteractiveObject) aPrs = new MyPArrayObject (aPrims);
+  if (!isTri)
+  {
+    aPrs->Attributes()->SetupOwnShadingAspect();
+    aPrs->Attributes()->ShadingAspect()->Aspect()->SetColor (aPrs->Attributes()->LineAspect()->Aspect()->Color());
+  }
+  ViewerTest::Display (argv[1], aPrs);
   return 0;
 }
 
@@ -4810,7 +5005,7 @@ static Standard_Integer VObjZLayer (Draw_Interpretor& di,
   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
   if (aContext.IsNull())
   {
-    di << argv[0] << "Call 'vinit' before!\n";
+    Message::SendFail ("Error: no active viewer");
     return 1;
   }
 
@@ -4832,20 +5027,11 @@ static Standard_Integer VObjZLayer (Draw_Interpretor& di,
 
   // find object
   TCollection_AsciiString aName (argv[2]);
-  ViewerTest_DoubleMapOfInteractiveAndName& aMap = GetMapOfAIS();
-  if (!aMap.IsBound2 (aName))
-  {
-    di << "Use 'vdisplay' before" << "\n";
-    return 1;
-  }
-
-  // find interactive object
-  Handle(Standard_Transient) anObj = GetMapOfAIS().Find2 (aName);
-  Handle(AIS_InteractiveObject) anInterObj =
-    Handle(AIS_InteractiveObject)::DownCast (anObj);
+  Handle(AIS_InteractiveObject) anInterObj;
+  GetMapOfAIS().Find2 (aName, anInterObj);
   if (anInterObj.IsNull())
   {
-    di << "Not an AIS interactive object!\n";
+    Message::SendFail() << "Syntax error: object '" << aName << "' is not displayed";
     return 1;
   }
 
@@ -4874,14 +5060,15 @@ static Standard_Integer VPolygonOffset(Draw_Interpretor& /*di*/,
   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
   if (aContext.IsNull())
   {
-    std::cout << argv[0] << " Call 'vinit' before!\n";
+    Message::SendFail ("Error: no active viewer");
     return 1;
   }
 
   if (argc > 2 && argc != 5)
   {
-    std::cout << "Usage : " << argv[0] << " [object [mode factor units]] - sets/gets polygon offset parameters for an object,"
-      "without arguments prints the default values" << std::endl;
+    Message::SendFail() << "Syntax error: wrong number of arguments.\n"
+                           "Usage: " << argv[0] << " [object [mode factor units]] - sets/gets polygon offset parameters for an object,"
+                           "without arguments prints the default values";
     return 1;
   }
 
@@ -4890,19 +5077,10 @@ static Standard_Integer VPolygonOffset(Draw_Interpretor& /*di*/,
   if (argc >= 2)
   {
     TCollection_AsciiString aName (argv[1]);
-    ViewerTest_DoubleMapOfInteractiveAndName& aMap = GetMapOfAIS();
-    if (!aMap.IsBound2 (aName))
-    {
-      std::cout << "Use 'vdisplay' before" << std::endl;
-      return 1;
-    }
-
-    // find interactive object
-    Handle(Standard_Transient) anObj = GetMapOfAIS().Find2 (aName);
-    anInterObj = Handle(AIS_InteractiveObject)::DownCast (anObj);
-    if (anInterObj.IsNull())
+    if (!GetMapOfAIS().Find2 (aName, anInterObj)
+      || anInterObj.IsNull())
     {
-      std::cout << "Not an AIS interactive object!" << std::endl;
+      Message::SendFail() << "Syntax error: object '" << aName << "' is not displayed";
       return 1;
     }
   }
@@ -4945,125 +5123,7 @@ static Standard_Integer VPolygonOffset(Draw_Interpretor& /*di*/,
   return 0;
 }
 
-//=======================================================================
-//function : VShowFaceBoundaries
-//purpose  : Set face boundaries drawing on/off for ais object
-//=======================================================================
-static Standard_Integer VShowFaceBoundary (Draw_Interpretor& /*di*/,
-                                           Standard_Integer argc,
-                                           const char ** argv)
-{
-  Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext ();
-  if (aContext.IsNull ())
-  {
-    std::cout << argv[0] << " Call 'vinit' before!\n";
-    return 1;
-  }
-
-  if ((argc != 3 && argc < 6) || argc > 8)
-  {
-    std::cout << "Usage :\n " << argv[0]
-              << " ObjectName isOn [R G B [LineWidth [LineStyle]]]\n"
-              << "   ObjectName - name of AIS interactive object. \n"
-              << "                if ObjectName = \"\", then set as default\n"
-              << "                settings for all newly displayed objects\n"
-              << "   isOn       - flag indicating whether the boundaries\n"
-              << "                should be turned on or off (can be set\n"
-              << "                to 0 (off) or 1 (on)).\n"
-              << "   R, G, B    - red, green and blue components of boundary\n"
-              << "                color in range (0 - 255).\n"
-              << "                (default is (0, 0, 0)\n"
-              << "   LineWidth  - line width\n"
-              << "                (default is 1)\n"
-              << "   LineStyle  - line fill style :\n"
-              << "                 0 - solid  \n"
-              << "                 1 - dashed \n"
-              << "                 2 - dot    \n"
-              << "                 3 - dashdot\n"
-              << "                 (default is solid)";
-    return 1;
-  }
-
-  TCollection_AsciiString aName (argv[1]);
-
-  Quantity_Parameter aRed      = 0.0;
-  Quantity_Parameter aGreen    = 0.0;
-  Quantity_Parameter aBlue     = 0.0;
-  Standard_Real      aWidth    = 1.0;
-  Aspect_TypeOfLine  aLineType = Aspect_TOL_SOLID;
-  
-  // find object
-  Handle(AIS_InteractiveObject) anInterObj;
-
-  // if name is empty - apply attributes for default aspect
-  if (!aName.IsEmpty ())
-  {
-    ViewerTest_DoubleMapOfInteractiveAndName& aMap = GetMapOfAIS ();
-    if (!aMap.IsBound2 (aName))
-    {
-      std::cout << "Use 'vdisplay' on " << aName << " before" << std::endl;
-      return 1;
-    }
-
-    // find interactive object
-    Handle(Standard_Transient) anObj = GetMapOfAIS ().Find2 (aName);
-    anInterObj = Handle(AIS_InteractiveObject)::DownCast (anObj);
-    if (anInterObj.IsNull ())
-    {
-      std::cout << "Not an AIS interactive object!" << std::endl;
-      return 1;
-    }
-  }
-  
-  const Handle(Prs3d_Drawer)& aDrawer = (aName.IsEmpty ()) ?
-    TheAISContext ()->DefaultDrawer () : anInterObj->Attributes ();
-
-  // turn boundaries on/off
-  Standard_Boolean isBoundaryDraw = (Draw::Atoi (argv[2]) == 1);
-  aDrawer->SetFaceBoundaryDraw (isBoundaryDraw);
-  
-  // set boundary line color
-  if (argc >= 6)
-  {
-    // Text color
-    aRed   = Draw::Atof (argv[3])/255.;
-    aGreen = Draw::Atof (argv[4])/255.;
-    aBlue  = Draw::Atof (argv[5])/255.;
-  }
-
-  // set line width
-  if (argc >= 7)
-  {
-    aWidth = (Standard_Real)Draw::Atof (argv[6]);
-  }
-
-  // select appropriate line type
-  if (argc == 8)
-  {
-    switch (Draw::Atoi (argv[7]))
-    {
-      case 1: aLineType = Aspect_TOL_DASH;    break;
-      case 2: aLineType = Aspect_TOL_DOT;     break;
-      case 3: aLineType = Aspect_TOL_DOTDASH; break;
-      default:
-        aLineType = Aspect_TOL_SOLID;
-    }
-  }
-
-  Quantity_Color aColor (aRed, aGreen, aBlue, Quantity_TOC_RGB);
-
-  Handle(Prs3d_LineAspect) aBoundaryAspect = 
-    new Prs3d_LineAspect (aColor, aLineType, aWidth);
-
-  aDrawer->SetFaceBoundaryAspect (aBoundaryAspect);
-
-  TheAISContext()->Redisplay (anInterObj);
-  
-  return 0;
-}
-
 // This class is used for testing markers.
-
 class ViewerTest_MarkersArrayObject : public AIS_InteractiveObject
 {
 
@@ -5078,16 +5138,16 @@ public:
     myMarkerAspect = theMarkerAspect;
   }
 
-  DEFINE_STANDARD_RTTI(MyPArrayObject, AIS_InteractiveObject);
+  DEFINE_STANDARD_RTTI_INLINE(ViewerTest_MarkersArrayObject,AIS_InteractiveObject);
 
 private:
 
   void Compute (const Handle(PrsMgr_PresentationManager3d)& aPresentationManager,
                 const Handle(Prs3d_Presentation)& aPresentation,
-                const Standard_Integer aMode);
+                const Standard_Integer aMode) Standard_OVERRIDE;
 
   void ComputeSelection (const Handle(SelectMgr_Selection)& theSelection,
-                         const Standard_Integer /*theMode*/);
+                         const Standard_Integer /*theMode*/) Standard_OVERRIDE;
 
 protected:
 
@@ -5170,14 +5230,13 @@ static Standard_Integer VMarkersTest (Draw_Interpretor&,
   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
   if (aContext.IsNull())
   {
-    std::cerr << "Call 'vinit' before!\n";
+    Message::SendFail ("Error: no active viewer");
     return 1;
   }
 
   if (theArgNb < 5)
   {
-    std::cerr << "Usage :\n " << theArgVec[0]
-              << "name X Y Z [PointsOnSide=10] [MarkerType=0] [Scale=1.0] [FileName=ImageFile]\n";
+    Message::SendFail ("Syntax error: wrong number of arguments");
     return 1;
   }
 
@@ -5214,7 +5273,7 @@ static Standard_Integer VMarkersTest (Draw_Interpretor&,
     }
     else
     {
-      std::cerr << "Wrong argument: " << anArg << "\n";
+      Message::SendFail() << "Syntax error: wrong argument '" << anArg << "'";
       return 1;
     }
   }
@@ -5228,16 +5287,16 @@ static Standard_Integer VMarkersTest (Draw_Interpretor&,
     anImage = new Image_AlienPixMap();
     if (!anImage->Load (aFileName))
     {
-      std::cerr << "Could not load image from file '" << aFileName << "'!\n";
+      Message::SendFail() << "Error: could not load image from file '" << aFileName << "'!";
       return 1;
     }
-    if (anImage->Format() == Image_PixMap::ImgGray)
+    if (anImage->Format() == Image_Format_Gray)
     {
-      anImage->SetFormat (Image_PixMap::ImgAlpha);
+      anImage->SetFormat (Image_Format_Alpha);
     }
-    else if (anImage->Format() == Image_PixMap::ImgGrayF)
+    else if (anImage->Format() == Image_Format_GrayF)
     {
-      anImage->SetFormat (Image_PixMap::ImgAlphaF);
+      anImage->SetFormat (Image_Format_AlphaF);
     }
     anAspect = new Graphic3d_AspectMarker3d (anImage);
   }
@@ -5252,49 +5311,6 @@ static Standard_Integer VMarkersTest (Draw_Interpretor&,
   return 0;
 }
 
-//! Auxiliary function to parse font aspect style argument
-static Standard_Boolean parseFontStyle (const TCollection_AsciiString& theArg,
-                                        Font_FontAspect&               theAspect)
-{
-  if (theArg == "regular"
-   || *theArg.ToCString() == 'r')
-  {
-    theAspect = Font_FA_Regular;
-    return Standard_True;
-  }
-  else if (theArg == "bolditalic")
-  {
-    theAspect = Font_FA_BoldItalic;
-    return Standard_True;
-  }
-  else if (theArg == "bold"
-        || *theArg.ToCString() == 'b')
-  {
-    theAspect = Font_FA_Bold;
-    return Standard_True;
-  }
-  else if (theArg == "italic"
-        || *theArg.ToCString() == 'i')
-  {
-    theAspect = Font_FA_Italic;
-    return Standard_True;
-  }
-  return Standard_False;
-}
-
-//! Auxiliary function
-static TCollection_AsciiString fontStyleString (const Font_FontAspect theAspect)
-{
-  switch (theAspect)
-  {
-    case Font_FA_Regular:    return "regular";
-    case Font_FA_BoldItalic: return "bolditalic";
-    case Font_FA_Bold:       return "bold";
-    case Font_FA_Italic:     return "italic";
-    default:                 return "undefined";
-  }
-}
-
 //=======================================================================
 //function : TextToBrep
 //purpose  : Tool for conversion text to occt-shapes
@@ -5306,7 +5322,7 @@ static int TextToBRep (Draw_Interpretor& /*theDI*/,
   // Check arguments
   if (theArgNb < 3)
   {
-    std::cerr << "Error: " << theArgVec[0] << " - invalid syntax\n";
+    Message::SendFail() << "Error: " << theArgVec[0] << " - invalid syntax";
     return 1;
   }
 
@@ -5326,7 +5342,7 @@ static int TextToBRep (Draw_Interpretor& /*theDI*/,
 
   Graphic3d_HorizontalTextAlignment aHJustification = Graphic3d_HTA_LEFT;
   Graphic3d_VerticalTextAlignment   aVJustification = Graphic3d_VTA_BOTTOM;
-
+  Font_StrictLevel aStrictLevel = Font_StrictLevel_Any;
   for (; anArgIt < theArgNb; ++anArgIt)
   {
     TCollection_AsciiString aParam (theArgVec[anArgIt]);
@@ -5337,7 +5353,7 @@ static int TextToBRep (Draw_Interpretor& /*theDI*/,
     {
       if (anArgIt + 3 >= theArgNb)
       {
-        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
+        Message::SendFail() << "Error: wrong number of values for parameter '" << aParam << "'";
         return 1;
       }
 
@@ -5349,7 +5365,7 @@ static int TextToBRep (Draw_Interpretor& /*theDI*/,
     {
       if (++anArgIt >= theArgNb)
       {
-        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
+        Message::SendFail() << "Error: wrong number of values for parameter '" << aParam << "'";
         return 1;
       }
 
@@ -5369,7 +5385,7 @@ static int TextToBRep (Draw_Interpretor& /*theDI*/,
       }
       else
       {
-        std::cout << "Error: wrong syntax at '" << aParam.ToCString() << "'.\n";
+        Message::SendFail() << "Error: wrong syntax at '" << aParam << "'";
         return 1;
       }
     }
@@ -5377,7 +5393,7 @@ static int TextToBRep (Draw_Interpretor& /*theDI*/,
     {
       if (++anArgIt >= theArgNb)
       {
-        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
+        Message::SendFail() << "Error: wrong number of values for parameter '" << aParam << "'";
         return 1;
       }
 
@@ -5401,7 +5417,7 @@ static int TextToBRep (Draw_Interpretor& /*theDI*/,
       }
       else
       {
-        std::cout << "Error: wrong syntax at '" << aParam.ToCString() << "'.\n";
+        Message::SendFail() << "Error: wrong syntax at '" << aParam << "'";
         return 1;
       }
     }
@@ -5409,7 +5425,7 @@ static int TextToBRep (Draw_Interpretor& /*theDI*/,
     {
       if (++anArgIt >= theArgNb)
       {
-        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
+        Message::SendFail() << "Error: wrong number of values for parameter '" << aParam << "'";
         return 1;
       }
 
@@ -5419,32 +5435,15 @@ static int TextToBRep (Draw_Interpretor& /*theDI*/,
     {
       if (++anArgIt >= theArgNb)
       {
-        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
+        Message::SendFail() << "Error: wrong number of values for parameter '" << aParam << "'";
         return 1;
       }
 
       TCollection_AsciiString anOption (theArgVec[anArgIt]);
       anOption.LowerCase();
-
-      if (anOption.IsEqual ("regular"))
-      {
-        aFontAspect = Font_FA_Regular;
-      }
-      else if (anOption.IsEqual ("bold"))
+      if (!parseFontStyle (anOption, aFontAspect))
       {
-        aFontAspect = Font_FA_Bold;
-      }
-      else if (anOption.IsEqual ("italic"))
-      {
-        aFontAspect = Font_FA_Italic;
-      }
-      else if (anOption.IsEqual ("bolditalic"))
-      {
-        aFontAspect = Font_FA_BoldItalic;
-      }
-      else
-      {
-        std::cout << "Error: wrong syntax at '" << aParam.ToCString() << "'.\n";
+        Message::SendFail() << "Error: unknown font aspect '" << anOption << "'";
         return 1;
       }
     }
@@ -5452,17 +5451,23 @@ static int TextToBRep (Draw_Interpretor& /*theDI*/,
     {
       if (++anArgIt >= theArgNb)
       {
-        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
+        Message::SendFail() << "Error: wrong number of values for parameter '" << aParam << "'";
         return 1;
       }
 
       aFontName = theArgVec[anArgIt];
     }
+    else if (aParam == "-strict")
+    {
+      anArgIt += parseFontStrictLevel (theArgNb  - anArgIt - 1,
+                                       theArgVec + anArgIt + 1,
+                                       aStrictLevel);
+    }
     else if (aParam == "-composite")
     {
       if (++anArgIt >= theArgNb)
       {
-        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
+        Message::SendFail() << "Error: wrong number of values for parameter '" << aParam << "'";
         return 1;
       }
 
@@ -5472,7 +5477,7 @@ static int TextToBRep (Draw_Interpretor& /*theDI*/,
     {
       if (anArgIt + 6 >= theArgNb)
       {
-        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
+        Message::SendFail() << "Error: wrong number of values for parameter '" << aParam << "'";
         return 1;
       }
 
@@ -5488,14 +5493,14 @@ static int TextToBRep (Draw_Interpretor& /*theDI*/,
     }
     else
     {
-      std::cerr << "Warning! Unknown argument '" << aParam << "'\n";
+      Message::SendFail() << "Warning! Unknown argument '" << aParam << "'";
     }
   }
 
   aFont.SetCompositeCurveMode (anIsCompositeCurve);
-  if (!aFont.Init (aFontName.ToCString(), aFontAspect, aTextHeight))
+  if (!aFont.FindAndInit (aFontName.ToCString(), aFontAspect, aTextHeight, aStrictLevel))
   {
-    std::cerr << "Font initialization error\n";
+    Message::SendFail ("Error: unable to load Font");
     return 1;
   }
 
@@ -5510,48 +5515,58 @@ static int TextToBRep (Draw_Interpretor& /*theDI*/,
 //function : VFont
 //purpose  : Font management
 //=======================================================================
+struct FontComparator
+{
+  bool operator() (const Handle(Font_SystemFont)& theFontA,
+                   const Handle(Font_SystemFont)& theFontB)
+  {
+    return theFontA->FontKey().IsLess (theFontB->FontKey());
+  }
+};
 
 static int VFont (Draw_Interpretor& theDI,
                   Standard_Integer  theArgNb,
                   const char**      theArgVec)
 {
   Handle(Font_FontMgr) aMgr = Font_FontMgr::GetInstance();
-  if (theArgNb < 2)
-  {
-    // just print the list of available fonts
-    Standard_Boolean isFirst = Standard_True;
-    for (Font_NListOfSystemFont::Iterator anIter (aMgr->GetAvailableFonts());
-         anIter.More(); anIter.Next())
-    {
-      const Handle(Font_SystemFont)& aFont = anIter.Value();
-      if (!isFirst)
-      {
-        theDI << "\n";
-      }
-
-      theDI << aFont->FontName()->String()
-            << " " << fontStyleString (aFont->FontAspect())
-            << " " << aFont->FontPath()->String();
-      isFirst = Standard_False;
-    }
-    return 0;
-  }
-
+  bool toPrintList = theArgNb < 2, toPrintNames = false;
+  Font_StrictLevel aStrictLevel = Font_StrictLevel_Any;
   for (Standard_Integer anArgIter = 1; anArgIter < theArgNb; ++anArgIter)
   {
     const TCollection_AsciiString anArg (theArgVec[anArgIter]);
     TCollection_AsciiString anArgCase (anArg);
     anArgCase.LowerCase();
-    if (anArgCase == "find")
+    if (anArgCase == "-strict")
     {
-      if (++anArgIter >= theArgNb)
-      {
-        std::cerr << "Wrong syntax at argument '" << anArg.ToCString() << "'!\n";
-        return 1;
-      }
-
-      Standard_CString aFontName   = theArgVec[anArgIter];
-      Font_FontAspect  aFontAspect = Font_FA_Undefined;
+      anArgIter += parseFontStrictLevel (theArgNb  - anArgIter - 1,
+                                         theArgVec + anArgIter + 1,
+                                         aStrictLevel);
+    }
+    else if (anArgCase == "-clear")
+    {
+      aMgr->ClearFontDataBase();
+    }
+    else if (anArgCase == "-init")
+    {
+      aMgr->InitFontDataBase();
+    }
+    else if (anArgCase == "-list")
+    {
+      toPrintList = true;
+    }
+    else if (anArgCase == "-names")
+    {
+      toPrintList = true;
+      toPrintNames = true;
+    }
+    else if (anArgIter + 1 < theArgNb
+          && (anArgCase == "-find"
+           || anArgCase == "-findinfo"
+           || anArgCase == "-findall"
+           || anArgCase == "find"))
+    {
+      const TCollection_AsciiString aFontName (theArgVec[++anArgIter]);
+      Font_FontAspect aFontAspect = Font_FA_Undefined;
       if (++anArgIter < theArgNb)
       {
         anArgCase = theArgVec[anArgIter];
@@ -5561,267 +5576,204 @@ static int VFont (Draw_Interpretor& theDI,
           --anArgIter;
         }
       }
-      Handle(Font_SystemFont) aFont = aMgr->FindFont (new TCollection_HAsciiString (aFontName), aFontAspect, -1);
-      if (aFont.IsNull())
+
+      const bool toFindAll   = (anArgCase == "-findall");
+      const bool toPrintInfo = (anArgCase == "-findinfo");
+      TCollection_AsciiString aResult;
+      if (toFindAll
+       || aFontName.Search ("*") != -1)
       {
-        std::cerr << "Error: font '" << aFontName << "' is not found!\n";
-        continue;
+        const Font_NListOfSystemFont aFonts = aMgr->GetAvailableFonts();
+        std::vector<Handle(Font_SystemFont)> aFontsSorted;
+        aFontsSorted.reserve (aFonts.Size());
+        for (Font_NListOfSystemFont::Iterator aFontIter (aFonts); aFontIter.More(); aFontIter.Next())
+        {
+          aFontsSorted.push_back (aFontIter.Value());
+        }
+        std::stable_sort (aFontsSorted.begin(), aFontsSorted.end(), FontComparator());
+        for (std::vector<Handle(Font_SystemFont)>::iterator aFontIter = aFontsSorted.begin(); aFontIter != aFontsSorted.end(); ++aFontIter)
+        {
+          const Handle(Font_SystemFont)& aFont = *aFontIter;
+          const TCollection_AsciiString aCheck = TCollection_AsciiString ("string match -nocase \"") + aFontName + "\" \"" + aFont->FontName() + "\"";
+          if (theDI.Eval (aCheck.ToCString()) == 0
+          && *theDI.Result() != '1')
+          {
+            theDI.Reset();
+            continue;
+          }
+
+          theDI.Reset();
+          if (!aResult.IsEmpty())
+          {
+            aResult += "\n";
+          }
+
+          aResult += toPrintInfo ? aFont->ToString() : aFont->FontName();
+          if (!toFindAll)
+          {
+            break;
+          }
+        }
+      }
+      else if (Handle(Font_SystemFont) aFont = aMgr->FindFont (aFontName, aStrictLevel, aFontAspect))
+      {
+        aResult = toPrintInfo ? aFont->ToString() : aFont->FontName();
       }
 
-      theDI << aFont->FontName()->String()
-            << " " << fontStyleString (aFont->FontAspect())
-            << " " << aFont->FontPath()->String();
-    }
-    else if (anArgCase == "add"
-          || anArgCase == "register")
-    {
-      if (++anArgIter >= theArgNb)
+      if (!aResult.IsEmpty())
       {
-        std::cerr << "Wrong syntax at argument '" << anArg.ToCString() << "'!\n";
-        return 1;
+        theDI << aResult;
+      }
+      else
+      {
+        Message::SendFail() << "Error: font '" << aFontName << "' is not found";
       }
-      Standard_CString aFontPath   = theArgVec[anArgIter];
-      Standard_CString aFontName   = NULL;
+    }
+    else if (anArgIter + 1 < theArgNb
+          && (anArgCase == "-add"
+           || anArgCase == "add"
+           || anArgCase == "-register"
+           || anArgCase == "register"))
+    {
+      ++anArgIter;
+      Standard_CString aFontPath = theArgVec[anArgIter++];
+      TCollection_AsciiString aFontName;
       Font_FontAspect  aFontAspect = Font_FA_Undefined;
-      if (++anArgIter < theArgNb)
+      Standard_Integer isSingelStroke = -1;
+      for (; anArgIter < theArgNb; ++anArgIter)
       {
-        if (!parseFontStyle (anArgCase, aFontAspect))
+        anArgCase = theArgVec[anArgIter];
+        anArgCase.LowerCase();
+        if (aFontAspect == Font_FontAspect_UNDEFINED
+         && parseFontStyle (anArgCase, aFontAspect))
+        {
+          continue;
+        }
+        else if (anArgCase == "singlestroke"
+              || anArgCase == "singleline"
+              || anArgCase == "oneline")
+        {
+          isSingelStroke = 1;
+        }
+        else if (aFontName.IsEmpty())
         {
           aFontName = theArgVec[anArgIter];
         }
-        if (++anArgIter < theArgNb)
+        else
         {
-          anArgCase = theArgVec[anArgIter];
-          anArgCase.LowerCase();
-          if (!parseFontStyle (anArgCase, aFontAspect))
-          {
-            --anArgIter;
-          }
+          --anArgIter;
+          break;
         }
       }
 
       Handle(Font_SystemFont) aFont = aMgr->CheckFont (aFontPath);
       if (aFont.IsNull())
       {
-        std::cerr << "Error: font '" << aFontPath << "' is not found!\n";
+        Message::SendFail() << "Error: font '" << aFontPath << "' is not found!";
         continue;
       }
 
-      if (aFontAspect != Font_FA_Undefined
-       || aFontName   != NULL)
+      if (aFontAspect != Font_FontAspect_UNDEFINED
+      || !aFontName.IsEmpty())
       {
-        if (aFontAspect == Font_FA_Undefined)
+        TCollection_AsciiString aName = aFont->FontName();
+        if (!aFontName.IsEmpty())
+        {
+          aName = aFontName;
+        }
+        Handle(Font_SystemFont) aFont2 = new Font_SystemFont (aName);
+        if (aFontAspect != Font_FontAspect_UNDEFINED)
         {
-          aFontAspect = aFont->FontAspect();
+          aFont2->SetFontPath (aFontAspect, aFontPath, 0);
         }
-        Handle(TCollection_HAsciiString) aName = aFont->FontName();
-        if (aFontName != NULL)
+        else
         {
-          aName = new TCollection_HAsciiString (aFontName);
+          for (int anAspectIter = 0; anAspectIter < Font_FontAspect_NB; ++anAspectIter)
+          {
+            aFont2->SetFontPath ((Font_FontAspect )anAspectIter,
+                                 aFont->FontPath ((Font_FontAspect )anAspectIter),
+                                 aFont->FontFaceId ((Font_FontAspect )anAspectIter));
+          }
         }
-        aFont = new Font_SystemFont (aName, aFontAspect, new TCollection_HAsciiString (aFontPath));
+        aFont = aFont2;
+      }
+      if (isSingelStroke != -1)
+      {
+        aFont->SetSingleStrokeFont (isSingelStroke == 1);
       }
 
       aMgr->RegisterFont (aFont, Standard_True);
-      theDI << aFont->FontName()->String()
-            << " " << fontStyleString (aFont->FontAspect())
-            << " " << aFont->FontPath()->String();
+      theDI << aFont->ToString();
+    }
+    else if (anArgCase == "-verbose"
+          || anArgCase == "-trace")
+    {
+      bool toEnable = true;
+      if (anArgIter + 1 < theArgNb
+       && ViewerTest::ParseOnOff (theArgVec[anArgIter + 1], toEnable))
+      {
+        ++anArgIter;
+      }
+      aMgr->SetTraceAliases (toEnable);
+    }
+    else if (anArgCase == "-unicodefallback"
+          || anArgCase == "-fallback"
+          || anArgCase == "-touseunicodesubsetfallback")
+    {
+      bool toEnable = true;
+      if (anArgIter + 1 < theArgNb
+       && ViewerTest::ParseOnOff (theArgVec[anArgIter + 1], toEnable))
+      {
+        ++anArgIter;
+      }
+      Font_FontMgr::ToUseUnicodeSubsetFallback() = toEnable;
     }
     else
     {
-      std::cerr << "Warning! Unknown argument '" << anArg.ToCString() << "'\n";
+      Message::SendFail() << "Warning! Unknown argument '" << anArg << "'";
     }
   }
 
-  return 0;
-}
-
-//=======================================================================
-//function : VSetEdgeType
-//purpose  : Edges type management
-//=======================================================================
-
-static int VSetEdgeType (Draw_Interpretor& theDI,
-                         Standard_Integer  theArgNum,
-                         const char**      theArgs)
-{
-  if (theArgNum < 4 || theArgNum > 9)
-  {
-    theDI << theArgs[0] << " error: wrong number of parameters. Type 'help "
-          << theArgs[0] << "' for more information.\n";
-    return 1;
-  }
-
-  Standard_Boolean isForceRedisplay = Standard_False;
-
-  // Get shape name
-  TCollection_AsciiString aName(theArgs[1]);
-  if (!GetMapOfAIS().IsBound2 (aName))
-  {
-    theDI <<  theArgs[0] << " error: wrong object name.\n";
-    return 1;
-  }
-  
-  Handle(AIS_InteractiveObject) anObject = 
-    Handle(AIS_InteractiveObject)::DownCast(GetMapOfAIS().Find2(aName));
-  
-  // Enable trianle edge mode
-  anObject->Attributes()->ShadingAspect()->Aspect()->SetEdgeOn();
-
-  // Parse parameters
-  for (Standard_Integer anIt = 2; anIt < theArgNum; ++anIt)
+  if (toPrintList)
   {
-    TCollection_AsciiString aParam ((theArgs[anIt]));
-    if (aParam.Value (1) == '-' && !aParam.IsRealValue())
+    // just print the list of available fonts
+    Standard_Boolean isFirst = Standard_True;
+    const Font_NListOfSystemFont aFonts = aMgr->GetAvailableFonts();
+    std::vector<Handle(Font_SystemFont)> aFontsSorted;
+    aFontsSorted.reserve (aFonts.Size());
+    for (Font_NListOfSystemFont::Iterator aFontIter (aFonts); aFontIter.More(); aFontIter.Next())
     {
-      if (aParam.IsEqual ("-type"))
-      {
-        if (theArgNum <= anIt + 1)
-        {
-          theDI <<  theArgs[0] << " error: wrong number of values for parameter '"
-                << aParam.ToCString() << "'.\n";
-          return 1;
-        }
-
-        TCollection_AsciiString aType = theArgs[++anIt];
-        aType.UpperCase();
+      aFontsSorted.push_back (aFontIter.Value());
+    }
+    std::stable_sort (aFontsSorted.begin(), aFontsSorted.end(), FontComparator());
+    for (std::vector<Handle(Font_SystemFont)>::iterator aFontIter = aFontsSorted.begin(); aFontIter != aFontsSorted.end(); ++aFontIter)
+    {
+      const Handle(Font_SystemFont)& aFont = *aFontIter;
 
-        if (aType.IsEqual ("SOLID"))
-        {
-          anObject->Attributes()->ShadingAspect()->Aspect()->SetEdgeLineType(Aspect_TOL_SOLID);
-        }
-        else if (aType.IsEqual ("DASH"))
-        {
-          anObject->Attributes()->ShadingAspect()->Aspect()->SetEdgeLineType(Aspect_TOL_DASH);
-        }
-        else if (aType.IsEqual ("DOT"))
-        {
-          anObject->Attributes()->ShadingAspect()->Aspect()->SetEdgeLineType(Aspect_TOL_DOT);
-        }
-        else if (aType.IsEqual ("DOTDASH"))
-        {
-          anObject->Attributes()->ShadingAspect()->Aspect()->SetEdgeLineType(Aspect_TOL_DOTDASH);
-        }
-        else
-        {
-          theDI <<  theArgs[0] << " error: wrong line type: '" << aType.ToCString() << "'.\n";
-          return 1;
-        }
-        
-      }
-      else if (aParam.IsEqual ("-color"))
+      if (toPrintNames)
       {
-        if (theArgNum <= anIt + 3)
+        if (!isFirst)
         {
-          theDI <<  theArgs[0] << " error: wrong number of values for parameter '"
-                << aParam.ToCString() << "'.\n";
-          return 1;
+          theDI << "\n";
         }
-
-        Quantity_Parameter aR = Draw::Atof(theArgs[++anIt]);
-        Quantity_Parameter aG = Draw::Atof(theArgs[++anIt]);
-        Quantity_Parameter aB = Draw::Atof(theArgs[++anIt]);
-        Quantity_Color aColor = Quantity_Color (aR > 1 ? aR / 255.0 : aR,
-                                                aG > 1 ? aG / 255.0 : aG,
-                                                aB > 1 ? aB / 255.0 : aB,
-                                                Quantity_TOC_RGB);
-
-        anObject->Attributes()->ShadingAspect()->Aspect()->SetEdgeColor (aColor);
-      }
-      else if (aParam.IsEqual ("-force"))
-      {
-        isForceRedisplay = Standard_True;
+        theDI << "\"" << aFont->FontName() << "\"";
       }
       else
       {
-        theDI <<  theArgs[0] << " error: unknown parameter '"
-              << aParam.ToCString() << "'.\n";
-        return 1;
+        if (!isFirst)
+        {
+          theDI << "\n";
+        }
+        theDI << aFont->ToString();
       }
+      isFirst = Standard_False;
     }
+    return 0;
   }
 
-  // Update shape presentation as aspect parameters were changed
-  if (isForceRedisplay)
-  {
-    ViewerTest::GetAISContext()->Redisplay (anObject);
-  }
-  else
-  {
-    anObject->SetAspect (anObject->Attributes()->ShadingAspect());
-  }
-
-  //Update view
-  ViewerTest::CurrentView()->Redraw();
-
-  return 0;
-}
-
-//=======================================================================
-//function : VUnsetEdgeType
-//purpose  : Unsets edges visibility in shading mode
-//=======================================================================
-
-static int VUnsetEdgeType (Draw_Interpretor& theDI,
-                         Standard_Integer  theArgNum,
-                         const char**      theArgs)
-{
-  if (theArgNum != 2 && theArgNum != 3)
-  {
-    theDI << theArgs[0] << " error: wrong number of parameters. Type 'help "
-          << theArgs[0] << "' for more information.\n";
-    return 1;
-  }
-
-  Standard_Boolean isForceRedisplay = Standard_False;
-
-  // Get shape name
-  TCollection_AsciiString aName (theArgs[1]);
-  if (!GetMapOfAIS().IsBound2 (aName))
-  {
-    theDI <<  theArgs[0] << " error: wrong object name.\n";
-    return 1;
-  }
-
-  Handle(AIS_InteractiveObject) anObject = 
-    Handle(AIS_InteractiveObject)::DownCast (GetMapOfAIS().Find2(aName));
-
-  // Enable trianle edge mode
-  anObject->Attributes()->ShadingAspect()->Aspect()->SetEdgeOff();
-
-  // Parse parameters
-  if (theArgNum == 3)
-  {
-    TCollection_AsciiString aParam ((theArgs[2]));
-    if (aParam.IsEqual ("-force"))
-    {
-      isForceRedisplay = Standard_True;
-    }
-    else
-    {
-       theDI <<  theArgs[0] << " error: unknown parameter '"
-              << aParam.ToCString() << "'.\n";
-       return 1;
-    }
-  }
-
-  // Update shape presentation as aspect parameters were changed
-  if (isForceRedisplay)
-  {
-    ViewerTest::GetAISContext()->Redisplay (anObject);
-  }
-  else
-  {
-    anObject->SetAspect (anObject->Attributes()->ShadingAspect());
-  }
-
-  //Update view
-  ViewerTest::CurrentView()->Redraw();
-
   return 0;
 }
 
-
 //=======================================================================
 //function : VVertexMode
 //purpose  : Switches vertex display mode for AIS_Shape or displays the current value
@@ -5834,7 +5786,7 @@ static int VVertexMode (Draw_Interpretor& theDI,
   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
   if (aContext.IsNull())
   {
-    std::cout << "Error: no view available, call 'vinit' before!" << std::endl;
+    Message::SendFail ("Error: no active viewer");
     return 1;
   }
 
@@ -5852,8 +5804,8 @@ static int VVertexMode (Draw_Interpretor& theDI,
   {
     if (theArgNum == 2)
     {
-      std::cout << "Error: '-set' option not followed by the mode and optional object name(s)" << std::endl;
-      std::cout << "Type 'help vvertexmode' for usage hints" << std::endl;
+      Message::SendFail ("Error: '-set' option not followed by the mode and optional object name(s)\n"
+                         "Type 'help vvertexmode' for usage hints");
       return 1;
     }
 
@@ -5879,12 +5831,11 @@ static int VVertexMode (Draw_Interpretor& theDI,
     for (Standard_Integer aCount = 3; aCount < theArgNum; aCount++)
     {
       TCollection_AsciiString aName (theArgs[aCount]);
-      if (!GetMapOfAIS().IsBound2 (aName))
+      if (!GetMapOfAIS().Find2 (aName, anObject))
       {
         theDI << "Warning: wrong object name ignored - " << theArgs[0] << "\n";
         continue;
       }
-      anObject = Handle(AIS_InteractiveObject)::DownCast (GetMapOfAIS().Find2(aName));
       anObjs.Append (anObject);
     }
 
@@ -5902,16 +5853,15 @@ static int VVertexMode (Draw_Interpretor& theDI,
     return 0;
   }
 
-  if (theArgNum > 2)
+  Handle(AIS_InteractiveObject) anObject;
+  if (theArgNum > 2
+  || !GetMapOfAIS().Find2 (aParam, anObject))
   {
-    std::cout << "Error: invalid number of arguments" << std::endl;
-    std::cout << "Type 'help vvertexmode' for usage hints" << std::endl;
+    Message::SendFail ("Syntax error: invalid number of arguments");
     return 1;
   }
 
   // One argument (object name) --> print the current vertex draw mode for the object
-  Handle(AIS_InteractiveObject) anObject =
-    Handle(AIS_InteractiveObject)::DownCast (GetMapOfAIS().Find2 (aParam));
   Prs3d_VertexDrawMode aCurrMode = anObject->Attributes()->VertexDrawMode();
   theDI <<  "Object's vertex draw mode: " << (aCurrMode == Prs3d_VDM_Isolated ? "'isolated'" : "'all'") << "\n";
   return 0;
@@ -5928,7 +5878,7 @@ static Standard_Integer VPointCloud (Draw_Interpretor& theDI,
   Handle(AIS_InteractiveContext) anAISContext = ViewerTest::GetAISContext();
   if (anAISContext.IsNull())
   {
-    std::cerr << "Error: no active view!\n";
+    Message::SendFail ("Error: no active view!");
     return 1;
   }
 
@@ -5958,7 +5908,7 @@ static Standard_Integer VPointCloud (Draw_Interpretor& theDI,
     case 2  : aCmd = CloudForShape; break;
     case 7  : aCmd = CloudSphere; break;
     default :
-      std::cout << "Error: wrong number of arguments! See usage:\n";
+      Message::SendFail ("Syntax error: wrong number of arguments! See usage:");
       theDI.PrintHelp (theArgs[0]);
       return 1;
   }
@@ -5967,6 +5917,7 @@ static Standard_Integer VPointCloud (Draw_Interpretor& theDI,
   Standard_Boolean toRandColors = Standard_False;
   Standard_Boolean hasNormals   = Standard_True;
   Standard_Boolean isSetArgNorm = Standard_False;
+  Standard_Boolean hasUV        = Standard_False;
   for (Standard_Integer anArgIter = 1; anArgIter < theArgNum; ++anArgIter)
   {
     Standard_CString anArg = theArgs[anArgIter];
@@ -5977,7 +5928,7 @@ static Standard_Integer VPointCloud (Draw_Interpretor& theDI,
     {
       if (isSetArgNorm && hasNormals)
       {
-        std::cout << "Error: wrong syntax - normals can not be enabled with colors at the same time\n";
+        Message::SendFail ("Syntax error: normals can not be enabled with colors at the same time");
         return 1;
       }
       toRandColors = Standard_True;
@@ -5988,7 +5939,7 @@ static Standard_Integer VPointCloud (Draw_Interpretor& theDI,
     {
       if (toRandColors)
       {
-        std::cout << "Error: wrong syntax - normals can not be enabled with colors at the same time\n";
+        Message::SendFail ("Syntax error: normals can not be enabled with colors at the same time");
         return 1;
       }
       isSetArgNorm = Standard_True;
@@ -6000,9 +5951,27 @@ static Standard_Integer VPointCloud (Draw_Interpretor& theDI,
       isSetArgNorm = Standard_True;
       hasNormals   = Standard_False;
     }
+    else if (aFlag == "-uv"
+          || aFlag == "-texels")
+    {
+      hasUV = Standard_True;
+    }
   }
 
   Standard_CString aName = theArgs[1];
+  Graphic3d_ArrayFlags aFlags = Graphic3d_ArrayFlags_None;
+  if (hasNormals)
+  {
+    aFlags |= Graphic3d_ArrayFlags_VertexNormal;
+  }
+  if (toRandColors)
+  {
+    aFlags |= Graphic3d_ArrayFlags_VertexColor;
+  }
+  if (hasUV)
+  {
+    aFlags |= Graphic3d_ArrayFlags_VertexTexel;
+  }
 
   // generate arbitrary set of points
   Handle(Graphic3d_ArrayOfPoints) anArrayPoints;
@@ -6013,7 +5982,7 @@ static Standard_Integer VPointCloud (Draw_Interpretor& theDI,
 
     if (aShape.IsNull())
     {
-      std::cout << "Error: no shape with name '" << aShapeName << "' found\n";
+      Message::SendFail() << "Error: no shape with name '" << aShapeName << "' found";
       return 1;
     }
 
@@ -6031,11 +6000,11 @@ static Standard_Integer VPointCloud (Draw_Interpretor& theDI,
     }
     if (aNbPoints < 3)
     {
-      std::cout << "Error: shape should be triangulated!\n";
+      Message::SendFail ("Error: shape should be triangulated");
       return 1;
     }
 
-    anArrayPoints = new Graphic3d_ArrayOfPoints (aNbPoints, toRandColors, hasNormals);
+    anArrayPoints = new Graphic3d_ArrayOfPoints (aNbPoints, aFlags);
     for (TopExp_Explorer aFaceIt (aShape, TopAbs_FACE); aFaceIt.More(); aFaceIt.Next())
     {
       const TopoDS_Face& aFace = TopoDS::Face (aFaceIt.Current());
@@ -6081,6 +6050,11 @@ static Standard_Integer VPointCloud (Draw_Interpretor& theDI,
         {
           anArrayPoints->SetVertexNormal (anIndexOfPoint, aNormals (aNodeIter));
         }
+        if (hasUV
+         && aTriangulation->HasUVNodes())
+        {
+          anArrayPoints->SetVertexTexel (anIndexOfPoint, aTriangulation->UVNode (aNodeIter));
+        }
       }
     }
   }
@@ -6096,7 +6070,7 @@ static Standard_Integer VPointCloud (Draw_Interpretor& theDI,
     aDistribution.LowerCase();
     if ( aDistribution != "surface" && aDistribution != "volume" )
     {
-      std::cout << "Error: wrong arguments! See usage:\n";
+      Message::SendFail ("Syntax error: wrong arguments. See usage:");
       theDI.PrintHelp (theArgs[0]);
       return 1;
     }
@@ -6104,7 +6078,7 @@ static Standard_Integer VPointCloud (Draw_Interpretor& theDI,
 
     gp_Pnt aCenter(aCenterX, aCenterY, aCenterZ);
 
-    anArrayPoints = new Graphic3d_ArrayOfPoints (aNbPoints, toRandColors, hasNormals);
+    anArrayPoints = new Graphic3d_ArrayOfPoints (aNbPoints, aFlags);
     for (Standard_Integer aPntIt = 0; aPntIt < aNbPoints; ++aPntIt)
     {
       Standard_Real anAlpha   = (Standard_Real (rand() % 2000) / 1000.0) * M_PI;
@@ -6129,6 +6103,11 @@ static Standard_Integer VPointCloud (Draw_Interpretor& theDI,
       {
         anArrayPoints->SetVertexNormal (anIndexOfPoint, aDir);
       }
+      if (hasUV)
+      {
+        anArrayPoints->SetVertexTexel (anIndexOfPoint, gp_Pnt2d (anAlpha / 2.0 * M_PI,
+                                                                 aBeta   / 2.0 * M_PI));
+      }
     }
   }
 
@@ -6152,7 +6131,7 @@ static int VPriority (Draw_Interpretor& theDI,
   ViewerTest_AutoUpdater anUpdateTool (aContext, ViewerTest::CurrentView());
   if (aContext.IsNull())
   {
-    std::cout << "Error: no view available, call 'vinit' before!" << std::endl;
+    Message::SendFail ("Error: no active viewer");
     return 1;
   }
 
@@ -6165,8 +6144,8 @@ static int VPriority (Draw_Interpretor& theDI,
     --aNbArgs;
     if (aPriority < 0 || aPriority > 10)
     {
-      std::cout << "Error: the specified display priority value '" << aLastArg
-                << "' is outside the valid range [0..10]" << std::endl;
+      Message::SendFail() << "Syntax error: the specified display priority value '" << aLastArg
+                          << "' is outside the valid range [0..10]";
       return 1;
     }
   }
@@ -6177,7 +6156,7 @@ static int VPriority (Draw_Interpretor& theDI,
 
   if (aNbArgs < 2)
   {
-    std::cout << "Error: wrong number of arguments! See usage:\n";
+    Message::SendFail ("Syntax error: wrong number of arguments! See usage:");
     theDI.PrintHelp (theArgs[0]);
     return 1;
   }
@@ -6191,14 +6170,10 @@ static int VPriority (Draw_Interpretor& theDI,
 
     TCollection_AsciiString aName (theArgs[anArgIter]);
     Handle(AIS_InteractiveObject) anIObj;
-    if (GetMapOfAIS().IsBound2 (aName))
-    {
-      anIObj = Handle(AIS_InteractiveObject)::DownCast (GetMapOfAIS().Find2 (aName));
-    }
-
+    GetMapOfAIS().Find2 (aName, anIObj);
     if (anIObj.IsNull())
     {
-      std::cout << "Error: the object '" << theArgs[1] << "' is not displayed" << std::endl;
+      Message::SendFail() << "Error: the object '" << theArgs[1] << "' is not displayed";
       return 1;
     }
 
@@ -6214,6 +6189,217 @@ static int VPriority (Draw_Interpretor& theDI,
   return 0;
 }
 
+//! Auxiliary class for command vnormals.
+class MyShapeWithNormals : public AIS_Shape
+{
+  DEFINE_STANDARD_RTTI_INLINE(MyShapeWithNormals, AIS_Shape);
+public:
+
+  Standard_Real    NormalLength;
+  Standard_Integer NbAlongU;
+  Standard_Integer NbAlongV;
+  Standard_Boolean ToUseMesh;
+  Standard_Boolean ToOrient;
+
+public:
+
+  //! Main constructor.
+  MyShapeWithNormals (const TopoDS_Shape& theShape)
+  : AIS_Shape   (theShape),
+    NormalLength(10),
+    NbAlongU  (1),
+    NbAlongV  (1),
+    ToUseMesh (Standard_False),
+    ToOrient  (Standard_False) {}
+
+protected:
+
+  //! Comnpute presentation.
+  virtual void Compute (const Handle(PrsMgr_PresentationManager3d)& thePrsMgr,
+                        const Handle(Prs3d_Presentation)&           thePrs,
+                        const Standard_Integer                      theMode) Standard_OVERRIDE
+  {
+    AIS_Shape::Compute (thePrsMgr, thePrs, theMode);
+
+    NCollection_DataMap<TopoDS_Face, NCollection_Vector<std::pair<gp_Pnt, gp_Pnt> > > aNormalMap;
+    if (ToUseMesh)
+    {
+      DBRep_DrawableShape::addMeshNormals (aNormalMap, myshape, NormalLength);
+    }
+    else
+    {
+      DBRep_DrawableShape::addSurfaceNormals (aNormalMap, myshape, NormalLength, NbAlongU, NbAlongV);
+    }
+
+    Handle(Graphic3d_Group) aPrsGroup = Prs3d_Root::NewGroup (thePrs);
+    aPrsGroup->SetGroupPrimitivesAspect (myDrawer->ArrowAspect()->Aspect());
+
+    const Standard_Real aArrowAngle  = myDrawer->ArrowAspect()->Angle();
+    const Standard_Real aArrowLength = myDrawer->ArrowAspect()->Length();
+    for (NCollection_DataMap<TopoDS_Face, NCollection_Vector<std::pair<gp_Pnt, gp_Pnt> > >::Iterator aFaceIt (aNormalMap);
+         aFaceIt.More(); aFaceIt.Next())
+    {
+      const Standard_Boolean toReverse = ToOrient && aFaceIt.Key().Orientation() == TopAbs_REVERSED;
+      Handle(Graphic3d_ArrayOfSegments) aSegments = new Graphic3d_ArrayOfSegments (2 * aFaceIt.Value().Size());
+      for (NCollection_Vector<std::pair<gp_Pnt, gp_Pnt> >::Iterator aPntIt (aFaceIt.Value()); aPntIt.More(); aPntIt.Next())
+      {
+        std::pair<gp_Pnt, gp_Pnt> aPair = aPntIt.Value();
+        if (toReverse)
+        {
+          const gp_Vec aDir = aPair.first.XYZ() - aPair.second.XYZ();
+          aPair.second = aPair.first.XYZ() + aDir.XYZ();
+        }
+
+        aSegments->AddVertex (aPair.first);
+        aSegments->AddVertex (aPair.second);
+        Prs3d_Arrow::Draw (aPrsGroup, aPair.second, gp_Vec(aPair.first, aPair.second), aArrowAngle, aArrowLength);
+      }
+
+      aPrsGroup->AddPrimitiveArray (aSegments);
+    }
+  }
+
+};
+
+//=======================================================================
+//function : VNormals
+//purpose  : Displays/Hides normals calculated on shape geometry or retrieved from triangulation
+//=======================================================================
+static int VNormals (Draw_Interpretor& theDI,
+                     Standard_Integer  theArgNum,
+                     const char**      theArgs)
+{
+  Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
+  if (aContext.IsNull())
+  {
+    Message::SendFail ("Error: no active viewer");
+    return 1;
+  }
+  else if (theArgNum < 2)
+  {
+    Message::SendFail ("Syntax error: wrong number of arguments. See usage:");
+    theDI.PrintHelp (theArgs[0]);
+    return 1;
+  }
+
+  Standard_Integer anArgIter = 1;
+  Standard_CString aShapeName = theArgs[anArgIter++];
+  TopoDS_Shape     aShape     = DBRep::Get (aShapeName);
+  Standard_Boolean isOn = Standard_True;
+  if (aShape.IsNull())
+  {
+    Message::SendFail() << "Error: shape with name '" << aShapeName << "' is not found";
+    return 1;
+  }
+
+  ViewerTest_DoubleMapOfInteractiveAndName& aMap = GetMapOfAIS();
+  Handle(MyShapeWithNormals) aShapePrs;
+  if (aMap.IsBound2 (aShapeName))
+  {
+    aShapePrs = Handle(MyShapeWithNormals)::DownCast (aMap.Find2 (aShapeName));
+  }
+
+  Standard_Boolean isUseMesh = Standard_False;
+  Standard_Real    aLength = 10.0;
+  Standard_Integer aNbAlongU = 1, aNbAlongV = 1;
+  Standard_Boolean isOriented = Standard_False;
+  for (; anArgIter < theArgNum; ++anArgIter)
+  {
+    TCollection_AsciiString aParam (theArgs[anArgIter]);
+    aParam.LowerCase();
+    if (anArgIter == 2
+     && ViewerTest::ParseOnOff (aParam.ToCString(), isOn))
+    {
+      continue;
+    }
+    else if (aParam == "-usemesh"
+          || aParam == "-mesh")
+    {
+      isUseMesh = Standard_True;
+    }
+    else if (aParam == "-length"
+          || aParam == "-len")
+    {
+      ++anArgIter;
+      aLength = anArgIter < theArgNum ? Draw::Atof (theArgs[anArgIter]) : 0.0;
+      if (Abs (aLength) <= gp::Resolution())
+      {
+        Message::SendFail ("Syntax error: length should not be zero");
+        return 1;
+      }
+    }
+    else if (aParam == "-orient"
+          || aParam == "-oriented")
+    {
+      isOriented = Standard_True;
+      if (anArgIter + 1 < theArgNum
+        && ViewerTest::ParseOnOff (theArgs[anArgIter + 1], isOriented))
+      {
+        ++anArgIter;
+      }
+    }
+    else if (aParam == "-nbalongu"
+          || aParam == "-nbu")
+    {
+      ++anArgIter;
+      aNbAlongU = anArgIter < theArgNum ? Draw::Atoi (theArgs[anArgIter]) : 0;
+      if (aNbAlongU < 1)
+      {
+        Message::SendFail ("Syntax error: NbAlongU should be >=1");
+        return 1;
+      }
+    }
+    else if (aParam == "-nbalongv"
+          || aParam == "-nbv")
+    {
+      ++anArgIter;
+      aNbAlongV = anArgIter < theArgNum ? Draw::Atoi (theArgs[anArgIter]) : 0;
+      if (aNbAlongV < 1)
+      {
+        Message::SendFail ("Syntax error: NbAlongV should be >=1");
+        return 1;
+      }
+    }
+    else if (aParam == "-nbalong"
+          || aParam == "-nbuv")
+    {
+      ++anArgIter;
+      aNbAlongU = anArgIter < theArgNum ? Draw::Atoi (theArgs[anArgIter]) : 0;
+      aNbAlongV = aNbAlongU;
+      if (aNbAlongU < 1)
+      {
+        Message::SendFail ("Syntax error: NbAlong should be >=1");
+        return 1;
+      }
+    }
+    else
+    {
+      Message::SendFail() << "Syntax error: unknown argument '" << aParam << "'";
+      return 1;
+    }
+  }
+
+  if (isOn)
+  {
+    if (aShapePrs.IsNull())
+    {
+      aShapePrs = new MyShapeWithNormals (aShape);
+    }
+    aShapePrs->ToUseMesh    = isUseMesh;
+    aShapePrs->ToOrient     = isOriented;
+    aShapePrs->NormalLength = aLength;
+    aShapePrs->NbAlongU     = aNbAlongU;
+    aShapePrs->NbAlongV     = aNbAlongV;
+    VDisplayAISObject (aShapeName, aShapePrs);
+  }
+  else if (!aShapePrs.IsNull())
+  {
+    VDisplayAISObject (aShapeName, new AIS_Shape (aShape));
+  }
+
+  return 0;
+}
+
 //=======================================================================
 //function : ObjectsCommands
 //purpose  :
@@ -6222,10 +6408,50 @@ static int VPriority (Draw_Interpretor& theDI,
 void ViewerTest::ObjectCommands(Draw_Interpretor& theCommands)
 {
   const char *group ="AISObjects";
-  theCommands.Add("vtrihedron",
-    "vtrihedron         : vtrihedron name [Xo] [Yo] [Zo] [Zu] [Zv] [Zw] [Xu] [Xv] [Xw] "
-    "\n\t\t: Creates a new *AIS_Trihedron* object. If no argument is set, the default trihedron (0XYZ) is created.",
-    __FILE__,VTrihedron,group);
+
+  theCommands.Add ("vtrihedron",
+                   "vtrihedron : vtrihedron name"
+                   "\n\t\t: [-dispMode {wireframe|shading} ]"
+                   "\n\t\t: [-origin x y z ]"
+                   "\n\t\t: [-zaxis u v w -xaxis u v w ]"
+                   "\n\t\t: [-drawAxes {X|Y|Z|XY|YZ|XZ|XYZ}]"
+                   "\n\t\t: [-hideLabels {on|off}]"
+                   "\n\t\t: [-hideArrows {on|off}]"
+                   "\n\t\t: [-label {XAxis|YAxis|ZAxis} value]"
+                   "\n\t\t: [-attribute {XAxisLength|YAxisLength|ZAxisLength"
+                   "\n\t\t:             |TubeRadiusPercent|ConeRadiusPercent"
+                   "\n\t\t:             |ConeLengthPercent|OriginRadiusPercent"
+                   "\n\t\t:             |ShadingNumberOfFacettes} value]"
+                   "\n\t\t: [-color {Origin|XAxis|YAxis|ZAxis|XOYAxis|YOZAxis"
+                   "\n\t\t:         |XOZAxis|Whole} {r g b | colorName}]"
+                   "\n\t\t: [-textColor {r g b | colorName}]"
+                   "\n\t\t: [-arrowColor {r g b | colorName}]"
+                   "\n\t\t: [-priority {Origin|XAxis|YAxis|ZAxis|XArrow"
+                   "\n\t\t:            |YArrow|ZArrow|XOYAxis|YOZAxis"
+                   "\n\t\t:            |XOZAxis|Whole} value]"
+                   "\n\t\t:"
+                   "\n\t\t: Creates a new *AIS_Trihedron* object or changes parameters of "
+                   "\n\t\t: existing trihedron. If no argument is set,"
+                   "\n\t\t: the default trihedron (0XYZ) is created."
+                   "\n\t\t: -dispMode mode of visualization: wf - wireframe,"
+                   "\n\t\t:                                  sh - shading."
+                   "\n\t\t:               Default value is wireframe."
+                   "\n\t\t: -origin allows to set trihedron location."
+                   "\n\t\t: -zaxis/-xaxis allows to set trihedron X and Z"
+                   "\n\t\t:               directions. The directions should"
+                   "\n\t\t:               be orthogonal. Y direction is calculated."
+                   "\n\t\t: -drawAxes allows to set what axes are drawn in the"
+                   "\n\t\t:           trihedron, default state is XYZ"
+                   "\n\t\t: -hideLabels allows to show/hide trihedron labels"
+                   "\n\t\t: -hideArrows allows to show/hide trihedron arrows"
+                   "\n\t\t: -label allows to change default X/Y/Z titles of axes"
+                   "\n\t\t: -attribute sets parameters of trihedron"
+                   "\n\t\t: -color sets color properties of parts of trihedron"
+                   "\n\t\t: -textColor sets color properties of trihedron labels"
+                   "\n\t\t: -arrowColor sets color properties of trihedron arrows"
+                   "\n\t\t: -priority allows to change default selection priority"
+                   "\n\t\t: of trihedron components",
+                   __FILE__,VTrihedron,group);
 
   theCommands.Add("vtri2d",
     "vtri2d Name"
@@ -6260,9 +6486,11 @@ void ViewerTest::ObjectCommands(Draw_Interpretor& theCommands)
     __FILE__,VAxisBuilder,group);
 
   theCommands.Add("vpoint",
-    "vpoint  PointName [Xa] [Ya] [Za] "
-    "\n\t\t: Creates a point from coordinates. If the values are not defined,"
-    "\n\t\t: a point is created by interactive selection of a vertice or an edge (in the center of the edge).",
+    "vpoint name [X Y [Z]] [-2d] [-nosel]"
+    "\n\t\t: Creates a point from coordinates."
+    "\n\t\t: If the values are not defined, a point is created from selected vertex or edge (center)."
+    "\n\t\t:  -2d    defines on-screen 2D point from top-left window corner"
+    "\n\t\t:  -nosel creates non-selectable presentation",
     __FILE__,VPointBuilder,group);
 
   theCommands.Add("vplane",
@@ -6317,17 +6545,19 @@ void ViewerTest::ObjectCommands(Draw_Interpretor& theCommands)
                    "\n\t\t: [-angle angle=0]"
                    "\n\t\t: [-zoom {0|1}=0]"
                    "\n\t\t: [-height height=16]"
-                   "\n\t\t: [-aspect {regular|bold|italic|bolditalic}=regular]"
+                   "\n\t\t: [-aspect {regular|bold|italic|boldItalic}=regular]"
                    "\n\t\t: [-font font=Times]"
                    "\n\t\t: [-2d]"
                    "\n\t\t: [-perspos {X Y Z}=0 0 0], where"
                    "\n\t\t X and Y define the coordinate origin in 2d space relative to the view window"
                    "\n\t\t Example: X=0 Y=0 is center, X=1 Y=1 is upper right corner etc..."
                    "\n\t\t Z coordinate defines the gap from border of view window (except center position)."
-                   "\n\t\t: [-disptype {blend|decal|subtitle|dimension|normal}=normal}"
+                   "\n\t\t: [-disptype {blend|decal|shadow|subtitle|dimension|normal}=normal}"
                    "\n\t\t: [-subcolor {R G B|name}=white]"
                    "\n\t\t: [-noupdate]"
                    "\n\t\t: [-plane NormX NormY NormZ DirX DirY DirZ]"
+                   "\n\t\t: [-flipping]"
+                   "\n\t\t: [-ownanchor {0|1}=1]"
                    "\n\t\t: Display text label at specified position.",
     __FILE__, VDrawText, group);
 
@@ -6335,18 +6565,70 @@ void ViewerTest::ObjectCommands(Draw_Interpretor& theCommands)
     "vdrawsphere: vdrawsphere shapeName Fineness [X=0.0 Y=0.0 Z=0.0] [Radius=100.0] [ToShowEdges=0] [ToPrintInfo=1]\n",
     __FILE__,VDrawSphere,group);
 
+  theCommands.Add ("vlocation",
+                "vlocation name"
+      "\n\t\t:   [-reset]"
+      "\n\t\t:   [-copyFrom otherName]"
+      "\n\t\t:   [-translate X Y [Z]]"
+      "\n\t\t:   [-rotate x y z dx dy dz angle]"
+      "\n\t\t:   [-scale [X Y Z] scale]"
+      "\n\t\t:   [-mirror x y z dx dy dz]"
+      "\n\t\t:   [-setLocation X Y [Z]]"
+      "\n\t\t:   [-setRotation QX QY QZ QW]"
+      "\n\t\t:   [-setScale [X Y Z] scale]"
+      "\n\t\t:   [-inheritParentTrsf {on|off}]"
+      "\n\t\t: Object local transformation management:"
+      "\n\t\t:   -reset       reset transformation to identity"
+      "\n\t\t:   -translate   translate object"
+      "\n\t\t:   -rotate      applies rotation to local transformation"
+      "\n\t\t:   -scale       applies scale    to local transformation"
+      "\n\t\t:   -mirror      applies mirror   to local transformation"
+      "\n\t\t:   -setLocation assign object location"
+      "\n\t\t:   -setRotation assign object rotation (quaternion)"
+      "\n\t\t:   -setScale    assign object scale factor"
+      "\n\t\t:   -inheritParentTrsf option to inherit parent"
+      "\n\t\t:                transformation or not (ON by default)",
+        __FILE__, VSetLocation, group);
   theCommands.Add ("vsetlocation",
-                   "vsetlocation [-noupdate|-update] name x y z"
-                   "\n\t\t: Set new location for an interactive object.",
+                   "alias for vlocation",
         __FILE__, VSetLocation, group);
-
-  theCommands.Add (
-    "vcomputehlr",
-    "vcomputehlr: shape hlrname [ eyex eyey eyez lookx looky lookz ]",
+  theCommands.Add ("vchild",
+                   "vchild parent [-add] [-remove] [-ignoreParentTrsf {0|1}] child1 [child2] [...]"
+      "\n\t\t: Command for testing low-level presentation connections."
+      "\n\t\t: vconnect command should be used instead.",
+        __FILE__, VChild, group);
+  theCommands.Add("vparent",
+    "vparent parent [-ignoreVisu]"
+    "\n\t\t: Command for testing object properties as parent in the hierarchy."
+    "\n\t\t: Arguments:"
+    "\n\t\t:   -ignoreVisu do not propagate the visual state (display/erase/color) to children objects",
+    __FILE__, VParent, group);
+  theCommands.Add ("vcomputehlr",
+                "vcomputehlr shapeInput hlrResult [-algoType {algo|polyAlgo}=polyAlgo]"
+      "\n\t\t:   [eyeX eyeY eyeZ dirX dirY dirZ upX upY upZ]"
+      "\n\t\t:   [-showTangentEdges {on|off}=off] [-nbIsolines N=0] [-showHiddenEdges {on|off}=off]"
+      "\n\t\t: Arguments:"
+      "\n\t\t:  shapeInput - name of the initial shape"
+      "\n\t\t:  hlrResult - result HLR object from initial shape"
+      "\n\t\t:  eye, dir are eye position and look direction"
+      "\n\t\t:  up is the look up direction vector"
+      "\n\t\t:  -algoType HLR algorithm to use"
+      "\n\t\t:  -showTangentEdges include tangent edges"
+      "\n\t\t:  -nbIsolines include isolines"
+      "\n\t\t:  -showHiddenEdges include hidden edges"
+      "\n\t\t: Use vtop to see projected HLR shape.",
     __FILE__, VComputeHLR, group);
 
   theCommands.Add("vdrawparray",
-    "vdrawparray : vdrawparray Name TypeOfArray [vertex = { 'v' x y z [vertex_normal = { 'n' x y z }] [vertex_color = { 'c' r g b }] ] ... [bound = { 'b' vertex_count [bound_color = { 'c' r g b }] ] ... [edge = { 'e' vertex_id ]",
+                "vdrawparray name TypeOfArray={points|segments|polylines|triangles"
+      "\n\t\t:                                |trianglefans|trianglestrips|quads|quadstrips|polygons}"
+      "\n\t\t:              [-deinterleaved|-mutable]"
+      "\n\t\t:              [vertex={'v' x y z [normal={'n' nx ny nz}] [color={'c' r g b}] [texel={'t' tx ty}]]"
+      "\n\t\t:              [bound= {'b' nbVertices [bound_color={'c' r g b}]]"
+      "\n\t\t:              [edge=  {'e' vertexId]"
+      "\n\t\t:              [-shape shapeName] [-patch]"
+      "\n\t\t: Commands create an Interactive Object for specified Primitive Array definition (Graphic3d_ArrayOfPrimitives)"
+      "\n\t\t: with the main purpose is covering various combinations by tests",
     __FILE__,VDrawPArray,group);
 
   theCommands.Add("vconnect", 
@@ -6377,24 +6659,19 @@ void ViewerTest::ObjectCommands(Draw_Interpretor& theCommands)
 
 
   theCommands.Add("vselmode", 
-    "vselmode : [object] mode_number is_turned_on=(1|0)\n"
-    "  switches selection mode for the determined object or\n"
-    "  for all objects in context.\n"
-    "  mode_number is non-negative integer that has different\n"
-    "    meaning for different interactive object classes.\n"
-    "    For shapes the following mode_number values are allowed:\n"
-    "      0 - shape\n"
-    "      1 - vertex\n"
-    "      2 - edge\n"
-    "      3 - wire\n"
-    "      4 - face\n"
-    "      5 - shell\n"
-    "      6 - solid\n"
-    "      7 - compsolid\n"
-    "      8 - compound\n"
-    "  is_turned_on is:\n"
-    "    1 if mode is to be switched on\n"
-    "    0 if mode is to be switched off\n", 
+                "vselmode [object] selectionMode {on|off}"
+      "\n\t\t:            [{-add|-set|-globalOrLocal}=-globalOrLocal]"
+      "\n\t\t: Switches selection mode for the specified object or for all objects in context."
+      "\n\t\t: Selection mode is either an integer number specific to Interactive Object,"
+      "\n\t\t: or sub-shape type in case of AIS_Shape:"
+      "\n\t\t:   Shape, Vertex, Edge, Wire, Face, Shell, Solid, CompSolid, Compound"
+      "\n\t\t: The integer mode 0 (Shape in case of AIS_Shape) is reserved for selecting object as whole."
+      "\n\t\t: Additional options:"
+      "\n\t\t:  -add           already activated selection modes will be left activated"
+      "\n\t\t:  -set           already activated selection modes will be deactivated"
+      "\n\t\t:  -globalOrLocal (default) if new mode is Global selection mode,"
+      "\n\t\t:                 then active local selection modes will be deactivated"
+      "\n\t\t:                 and the samthen active local selection modes will be deactivated",
     __FILE__, VSetSelectionMode, group);
 
   theCommands.Add("vselnext",
@@ -6413,7 +6690,7 @@ void ViewerTest::ObjectCommands(Draw_Interpretor& theCommands)
   theCommands.Add("vsegment",
     "vsegment Name PointName PointName"
     "\n\t\t: Creates and displays a segment from named points.", 
-    __FILE__, VSegment,group);
+    __FILE__, VTriangle,group);
 
   theCommands.Add("vobjzlayer",
     "vobjzlayer : set/get object [layerid] - set or get z layer id for the interactive object",
@@ -6423,12 +6700,6 @@ void ViewerTest::ObjectCommands(Draw_Interpretor& theCommands)
     "vpolygonoffset : [object [mode factor units]] - sets/gets polygon offset parameters for an object, without arguments prints the default values",
     __FILE__, VPolygonOffset, group);
 
-  theCommands.Add ("vshowfaceboundary",
-    "vshowfaceboundary : ObjectName isOn (1/0) [R G B [LineWidth [LineStyle]]]"
-    "- turns on/off drawing of face boundaries for ais object "
-    "and defines boundary line style.",
-    __FILE__, VShowFaceBoundary, group);
-
   theCommands.Add ("vmarkerstest",
                    "vmarkerstest: name X Y Z [PointsOnSide=10] [MarkerType=0] [Scale=1.0] [FileName=ImageFile]\n",
                    __FILE__, VMarkersTest, group);
@@ -6439,27 +6710,21 @@ void ViewerTest::ObjectCommands(Draw_Interpretor& theCommands)
                    "\n\t\t: [-halign {left|center|right}=left]"
                    "\n\t\t: [-valign {top|center|bottom|topfirstline}=bottom}]"
                    "\n\t\t: [-height height=16]"
-                   "\n\t\t: [-aspect {regular|bold|italic|bolditalic}=regular]"
-                   "\n\t\t: [-font font=Courier]"
+                   "\n\t\t: [-aspect {regular|bold|italic|boldItalic}=regular]"
+                   "\n\t\t: [-font font=Courier] [-strict {strict|aliases|any}=any]"
                    "\n\t\t: [-composite {on|off}=off]"
                    "\n\t\t: [-plane NormX NormY NormZ DirX DirY DirZ]",
                    __FILE__, TextToBRep, group);
   theCommands.Add ("vfont",
-                            "vfont [add pathToFont [fontName] [regular,bold,italic,bolditalic=undefined]]"
-                   "\n\t\t:        [find fontName [regular,bold,italic,bolditalic=undefined]]",
+                            "vfont [-add pathToFont [fontName] [regular,bold,italic,boldItalic=undefined] [singleStroke]]"
+                   "\n\t\t:        [-strict {any|aliases|strict}] [-find fontName [regular,bold,italic,boldItalic=undefined]] [-verbose {on|off}]"
+                   "\n\t\t:        [-findAll fontNameMask] [-findInfo fontName]"
+                   "\n\t\t:        [-unicodeFallback {on|off}]"
+                   "\n\t\t:        [-clear] [-init] [-list] [-names]"
+                   "\n\t\t: Work with font registry - register font, list available fonts, find font."
+                   "\n\t\t: -findAll  is same as -find, but can print more than one font when mask is passed."
+                   "\n\t\t: -findInfo is same as -find, but prints complete font information instead of family name.",
                    __FILE__, VFont, group);
-  
-  theCommands.Add ("vsetedgetype",
-                   "vsetedgetype usage:\n"
-                   "vsetedgetype ShapeName [-force] [-type {solid, dash, dot}] [-color R G B] "
-                   "\n\t\t:        Sets edges type and color for input shape",
-                   __FILE__, VSetEdgeType, group);
-
-  theCommands.Add ("vunsetedgetype",
-                   "vunsetedgetype usage:\n"
-                   "vunsetedgetype ShapeName [-force]"
-                   "\n\t\t:        Unsets edges type and color for input shape",
-                   __FILE__, VUnsetEdgeType, group);
 
   theCommands.Add ("vvertexmode",
                    "vvertexmode [name | -set {isolated | all | inherited} [name1 name2 ...]]\n"
@@ -6470,12 +6735,12 @@ void ViewerTest::ObjectCommands(Draw_Interpretor& theCommands)
                    __FILE__, VVertexMode, group);
 
   theCommands.Add ("vpointcloud",
-                   "vpointcloud name shape [-randColor] [-normals] [-noNormals]"
+                   "vpointcloud name shape [-randColor] [-normals] [-noNormals] [-uv]"
                    "\n\t\t: Create an interactive object for arbitary set of points"
                    "\n\t\t: from triangulated shape."
                    "\n"
                    "vpointcloud name x y z r npts {surface|volume}\n"
-                   "            ... [-randColor] [-normals] [-noNormals]"
+                   "            ... [-randColor] [-normals] [-noNormals] [-uv]"
                    "\n\t\t: Create arbitrary set of points (npts) randomly distributed"
                    "\n\t\t: on spheric surface or within spheric volume (x y z r)."
                    "\n\t\t:"
@@ -6486,38 +6751,15 @@ void ViewerTest::ObjectCommands(Draw_Interpretor& theCommands)
                    "\n",
                    __FILE__, VPointCloud, group);
 
-  theCommands.Add("vlocreset",
-    "vlocreset name1 name2 ...\n\t\t  remove object local transformation",
-    __FILE__,
-    LocalTransformPresentation, group);
-
-  theCommands.Add("vlocmove",
-    "vlocmove name1 name2 ... name\n\t\t  set local transform to match transform of 'name'",
-    __FILE__,
-    LocalTransformPresentation, group);
-
-  theCommands.Add("vloctranslate",
-    "vloctranslate name1 name2 ... dx dy dz\n\t\t  applies translation to local transformation",
-    __FILE__,
-    LocalTransformPresentation, group);
-
-  theCommands.Add("vlocrotate",
-    "vlocrotate name1 name2 ... x y z dx dy dz angle\n\t\t  applies rotation to local transformation",
-    __FILE__,
-    LocalTransformPresentation, group);
-
-  theCommands.Add("vlocmirror",
-    "vlocmirror name x y z dx dy dz\n\t\t  applies mirror to local transformation",
-    __FILE__,
-    LocalTransformPresentation, group);
-
-  theCommands.Add("vlocscale",
-    "vlocscale name x y z scale\n\t\t  applies scale to local transformation",
-    __FILE__,
-    LocalTransformPresentation, group);
-
   theCommands.Add("vpriority",
     "vpriority [-noupdate|-update] name [value]\n\t\t  prints or sets the display priority for an object",
     __FILE__,
     VPriority, group);
+
+  theCommands.Add ("vnormals",
+                   "vnormals usage:\n"
+                   "vnormals Shape [{on|off}=on] [-length {10}] [-nbAlongU {1}] [-nbAlongV {1}] [-nbAlong {1}]"
+                   "\n\t\t:        [-useMesh] [-oriented {0}1}=0]"
+                   "\n\t\t:  Displays/Hides normals calculated on shape geometry or retrieved from triangulation",
+                   __FILE__, VNormals, group);
 }