//Written by Tolik
unit U_ReindexMaster;

interface

uses
  Windows, U_LNG, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, RzButton, RzRadChk, ExtCtrls, RzPanel, RzRadGrp, ComCtrls,
  StdCtrls, RzLabel, Mask, RzEdit, RzSpnEdt, DrawObjects, siComp, siLngLnk,
  RzCmboBx, RzLstBox, RzTreeVw, Spin, Math, cxLookAndFeelPainters,
  cxButtons, cxGraphics, cxLookAndFeels, Menus;

  var CurrIndex, CurrComponIndex: Integer;
      IndexList, ComponentIndexList: Array of Integer;
type
  TF_ReindexMaster = class(TForm)
    MarkDirection: TRzRadioGroup;
    BeginIndexNum: TRzSpinEdit;
    RzLabel1: TRzLabel;
    siLangLinked1: TsiLangLinked;
    RzRadioGroup1: TRzRadioGroup;
    ReindexOnCompon: TRzRadioButton;
    RzRadioGroup2: TRzRadioGroup;
    ReindexByType: TRzRadioButton;
    ReindexTotal: TRzRadioButton;
    ComponTypeTree: TRzCheckTree;
    RzLabel2: TRzLabel;
    BeginClockDirection: TRzComboBox;
    RzRadioGroup3: TRzRadioGroup;
    PointObjectsReindex: TRzRadioButton;
    LineObjectsReindex: TRzRadioButton;
    Point_IndexType: TRzRadioGroup;
    ReindexOnCabinets: TRzCheckBox;
    ReindexOnObj: TRzRadioButton;
    Label1: TLabel;
    BeginComponIndexNum: TRzSpinEdit;
    DropIndexCounter: TCheckBox;
    IndexOnlyHigh: TRzCheckBox;
    IndexComplectOnly: TRzCheckBox;
    Line_IndexType: TRzCheckGroup;
    IndexChannelByKabinet: TRzCheckBox;
    MarkDIrection_L: TRzRadioGroup;
    BeginIndexNumL: TRzSpinEdit;
    Reindex_Order: TRzRadioGroup;
    IndexOnlyHigh_L: TRzCheckBox;
    CheckRaises: TRzCheckBox;
    Button_Choice: TcxButton;
    Button_Cancel: TcxButton;
    procedure FormKeyPress(Sender: TObject; var Key: Char);
    procedure FormKeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure Button_ChoiceClick(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure pClick(Sender: TObject);
    procedure lClick(Sender: TObject);
    procedure wwwClick(Sender: TObject);
    procedure zfdClick(Sender: TObject);
    procedure ReindexByTypeClick(Sender: TObject);
    procedure ReindexTotalClick(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure DefineCadSelectionIndexTypes(aComponTypes: string; var ComponTypeList: TStringList);
    procedure IndexOnlyHighClick(Sender: TObject);
    procedure MarkDirectionChanging(Sender: TObject; NewIndex: Integer;
      var AllowChange: Boolean);
    procedure LineObjectsReindexClick(Sender: TObject);
    procedure PointObjectsReindexClick(Sender: TObject);
    procedure ReindexOnObjClick(Sender: TObject);
    procedure ReindexOnComponClick(Sender: TObject);
    procedure SaveCheckedTreeList;
    procedure LoadCheckedTreeList;
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure Point_IndexTypeChanging(Sender: TObject; NewIndex: Integer;
      var AllowChange: Boolean);
    procedure ReindexOnCabinetsClick(Sender: TObject);
    procedure IndexComplectOnlyClick(Sender: TObject);
    procedure IndexOnlyHigh_LClick(Sender: TObject);
    procedure CheckRaisesClick(Sender: TObject);
    procedure IndexChannelByKabinetClick(Sender: TObject);
    procedure Button_CancelClick(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  Published

  end;

var
  F_ReindexMaster: TF_ReindexMaster;
  CheckTreeList: TStringList;
  ComponTypes: TStringList;
  FiguresList: TList;

implementation 

uses U_CAD, U_Common, Unit_DM_SCS, USCS_Main, U_BaseCommon, U_BaseConstants,
  U_ChoiceConnectSide, U_SCSClasses, U_MAIN, U_Constants, U_ESCadClasess, U_SCSComponent, U_SCSLists;

{$R *.dfm}
 type MyPointerArray = array [1..4] of Pointer;
procedure TF_ReindexMaster.FormKeyPress(Sender: TObject; var Key: Char);
begin
  case Key of
    #27: begin
           Key := #0;
           Close;
         end;
  end;
end;

procedure TF_ReindexMaster.FormKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
  case Key of
    27: begin
           Key := 0;
           Close;
         end;
  end;
end;


Procedure TF_ReindexMaster.SaveCheckedTreeList;
  var i: Integer;
      Node: TTreeNode;
      s: string;
  begin
    CheckTreeList.Clear;
    for i := 0 to ComponTypeTree.Items.Count - 1 do
    begin
      Node := ComponTypeTree.Items[i];
      if Node.AbsoluteIndex <> 0 then
      begin
        if ComponTypeTree.ItemState[Node.AbsoluteIndex] = csChecked then
        begin
          s := Node.Text;
          CheckTreeList.Add(s);
        end;
      end;
    end;
  end;

  Procedure TF_ReindexMaster.LoadCheckedTreeList;
  var i, j: Integer;
      Node: TTreeNode;
      s: string;
      NodeFound: Boolean;
  begin
    NodeFound := False;
    if CheckTreeList.Count > 0 then
    begin
      // Uncheck All
      for i := 0 to ComponTypeTree.Items.Count - 1 do
      begin
        Node := ComponTypeTree.Items[i];
        ComponTypeTree.ItemState[Node.AbsoluteIndex] := csUnchecked;
      end;
      // Check Saved 
      for i := 0 to ComponTypeTree.Items.Count - 1 do
      begin
        Node := ComponTypeTree.Items[i];
        if Node.AbsoluteIndex <> 0 then
        begin
          s := node.Text;
          if CheckTreeList.IndexOf(s) <> -1 then
            ComponTypeTree.ItemState[Node.AbsoluteIndex] := csChecked;
        end;
      end;
    end;
  end;

procedure DefinePointFigures;
var i, j, k:Integer;
  aCad: TF_CAD;
  Figure: TFigure;
begin
  aCad := GetListByID(F_ProjMan.GSCSBase.CurrProject.CurrList.SCSID);
  if aCad <> Nil then
  begin
    if FiguresList <> nil then
      FiguresList.Clear
    else
      FiguresList := TList.Create;
    if F_ReindexMaster.PointObjectsReindex.Checked then
    begin
      // All Selected Points
      for i := 0 to aCad.PCad.Selection.Count - 1 do
      begin
        Figure := TFigure(aCad.PCad.Selection[i]);
        if CheckFigureByClassName(Figure, cTConnectorObject) then
        begin
          if TConnectorObject(Figure).ConnectorType = ct_NB then
          begin
            FiguresList.Add(Figure);
          end;
        end;
      end;
    end;
  end;
end;

procedure DefineLineFigures;
var i, j, k:Integer;
    aCad: TF_CAD;
    Figure: TFigure;
begin
  aCad := GetListByID(F_ProjMan.GSCSBase.CurrProject.CurrList.SCSID);
  if aCad <> Nil then
  begin
    if FiguresList = nil then
      FiguresList := TList.Create
    else
      FiguresList.Clear;

    for i := 0 to aCad.PCad.Selection.Count - 1 do
    begin
      Figure := TFigure(aCad.PCad.Selection[i]);
      if CheckFigureByClassName(Figure, cTOrthoLine) then
      begin
        FiguresList.Add(Figure);
        //если учитывать С/П, то их нужно еще поискать
        if (F_ReindexMaster.CheckRaises.Visible and F_ReindexMaster.CheckRaises.Checked) then
        begin
          // первый коннектор трассы
          if TConnectorObject(TOrthoLine(Figure).JoinConnector1).JoinedOrtholinesList.Count > 0 then
          begin
            for j := 0 to TConnectorObject(TOrthoLine(Figure).JoinConnector1).JoinedOrtholinesList.Count - 1 do
            begin
              if TOrthoLine(TConnectorObject(TOrthoLine(Figure).JoinConnector1).JoinedOrtholinesList[j]).FIsRaiseUpDown then
              begin
                if FiguresList.IndexOf(TFigure(TConnectorObject(TOrthoLine(Figure).JoinConnector1).JoinedOrtholinesList[j])) = -1 then
                  FiguresList.Add(TFigure(TConnectorObject(TOrthoLine(Figure).JoinConnector1).JoinedOrtholinesList[j]));
              end;
            end;
          end;
          // смотрим на соединителе к первому коннектору (если есть)
          for j := 0 to TConnectorObject(TOrthoLine(Figure).JoinConnector1).JoinedConnectorsList.Count - 1 do
          begin
            for k := 0 to TConnectorObject(TConnectorObject(TOrthoLine(Figure).JoinConnector1).JoinedConnectorsList[k]).JoinedOrtholinesList.Count - 1 do
            begin
              if TOrthoLine(TConnectorObject(TConnectorObject(TOrthoLine(Figure).JoinConnector1).JoinedConnectorsList[k]).JoinedOrtholinesList[k]).FIsRaiseUpDown then
              begin
                if FiguresList.IndexOf(TFigure(TConnectorObject(TConnectorObject(TOrthoLine(Figure).JoinConnector1).JoinedConnectorsList[k]).JoinedOrtholinesList[k])) = -1 then
                  FiguresList.Add(TFigure(TConnectorObject(TConnectorObject(TOrthoLine(Figure).JoinConnector1).JoinedConnectorsList[k]).JoinedOrtholinesList[k]))
              end;
            end;
          end;
          //второй коннектор трассы
          if TConnectorObject(TOrthoLine(Figure).JoinConnector2).JoinedOrtholinesList.Count > 0 then
          begin
            for j := 0 to TConnectorObject(TOrthoLine(Figure).JoinConnector2).JoinedOrtholinesList.Count - 1 do
            begin
              if TOrthoLine(TConnectorObject(TOrthoLine(Figure).JoinConnector2).JoinedOrtholinesList[j]).FIsRaiseUpDown then
              begin
                if FiguresList.IndexOf(TFigure(TConnectorObject(TOrthoLine(Figure).JoinConnector2).JoinedOrtholinesList[j])) = -1 then
                  FiguresList.Add(TFigure(TConnectorObject(TOrthoLine(Figure).JoinConnector2).JoinedOrtholinesList[j]));
              end;
            end;
          end;
          // смотрим на соединителе ко второму коннектору (если есть)
          for j := 0 to TConnectorObject(TOrthoLine(Figure).JoinConnector1).JoinedConnectorsList.Count - 1 do
          begin
            for k := 0 to TConnectorObject(TConnectorObject(TOrthoLine(Figure).JoinConnector1).JoinedConnectorsList[k]).JoinedOrtholinesList.Count - 1 do
            begin
              if TOrthoLine(TConnectorObject(TConnectorObject(TOrthoLine(Figure).JoinConnector1).JoinedConnectorsList[k]).JoinedOrtholinesList[k]).FIsRaiseUpDown then
              begin
                if FiguresList.IndexOf(TFigure(TConnectorObject(TConnectorObject(TOrthoLine(Figure).JoinConnector1).JoinedConnectorsList[k]).JoinedOrtholinesList[k])) = -1 then
                  FiguresList.Add(TFigure(TConnectorObject(TConnectorObject(TOrthoLine(Figure).JoinConnector1).JoinedConnectorsList[k]).JoinedOrtholinesList[k]))
              end;
            end;
          end;
          //
        end;
      end;
    end;
  end;
end;
Procedure TF_ReindexMaster.Button_ChoiceClick(Sender: TObject);
Var CabinetList, {FiguresList,} TmpFiguresList, PassedFiguresList, TempList: TList;
    Figure, TmpFigure: TFigure;
    aCad: TF_CAD;
    aList: TSCSList;
    i, j, k, IndexNum, CurrComponIndex{, CurrIndex}, ActLayer: Integer;
    SelectedMode: string;
    SCSComponent: TSCSComponent;
    SortAgain: Boolean;
    SortFiguresCount, Counter: Integer;
    SCSCatalog, Cabinet, currCabinet: TSCSCatalog;
    SprComponentType: TNBComponentType;

    Node: TTreeNode;
    CurrCheckType: String;

    TracesList, CableList, ChannelList: TList; // трассы, кабели, каб каналы
    CableNames, ChannelNames: TList; // трассы, кабели, каб каналы (NamePlural Lists) на всякий, а вдруг не совпадет где-нибудь
    TraceFigures: TList; // трассы (фигуры на КАДе)


  Function CheckFigureInList(aList: TList; AFigure: TFigure): Boolean;
  Var i: Integer;
  Begin
    Result := false;
    if AList.Count > 0 then
    begin
      for i := 0 to aList.Count - 1 do
      begin
        if TFigure(aList[i]).ID = aFigure.ID then
        begin
          Result := true;
          break;
        end;
      end;
    end;
  End;

  Procedure DropTypeCounters(var IndexList: array of Integer; DropToUser: Boolean);
  var i: Integer;
  begin
    if Length(IndexList) > 0 then
    begin
      if DropToUser then
      begin
        for i := 0 to Length(IndexList) - 1 do
        begin
          IndexList[i] := StrToInt(BeginIndexNum.Text);
        end;
      end
      else
      begin
        for i := 0 to Length(IndexList) - 1 do
        begin
          IndexList[i] := 1;
        end;
      end;
    end;
  end;

  Function GetTopList(ComponList: TSCSComponents): TSCSComponents;
  Var i:Integer;
  Begin
    Result := TSCSComponents.Create(False);
    if ComponList.Count > 0 then
    begin
      for i := 0 to ComponList.Count - 1 do
      begin
        if ComponList[i].IsTop then
        begin
          if ((not IndexComplectOnly.Enabled) or ((IndexComplectOnly.Enabled) and (IndexComplectOnly.Checked = false))) then
          begin
            if ComponTypes.IndexOf(ComponList[i].ComponentType.NamePlural) <> -1 then
              Result.Add(ComponList[i]);
          end
          else
            Result.Add(ComponList[i]);
        end;
      end;
    end;
    // Tolik 13/05/2019 --
   { if Result.Count = 0 then
      Result := nil;}
   //
  End;

  Procedure ChangeFiguresCaptions(aCatalogList: TSCSCatalogs);
  var i, j: Integer;
      Figure: TFigure;
      Catalog: TSCSCatalog;
  begin
    for i := 0 to aCatalogList.Count - 1 do
    begin
      Figure := nil;
      Catalog := aCatalogList[i];
      for j := 0 to aCad.PCad.Selection.Count - 1 do
      begin
        Figure := aCad.PCad.Selection[j];
        if Figure.Id = Catalog.SCSID then
        begin
          TConnectorObject(Figure).FIndex := Catalog.MarkID;
          TConnectorObject(Figure).FIsNameChanged := True;
          if TConnectorObject(Figure).ConnectorType <> ct_Clear then
            SetConnNameInCaptionOnCAD(TConnectorObject(Figure));
          break;
        end;
      end;
    end;
  end;

  procedure RemComponByParent(ACompon: TSCSComponent);
  var i: Integer;
      currCompon: TSCSComponent;
      currCabinet, ResultCabinet, Catalog : TSCSCatalog;
      currComponIndexList: Array of Integer;
  begin
    if ACompon <> nil then
    begin
      currComponIndex := StrToInt(BeginComponIndexNum.Text);
      if ReindexByType.Checked and BeginComponIndexNum.Enabled then
      begin
        SetLength(currComponIndexList, ComponTypes.Count);
        for i := 0 to (Length(currComponIndexList) - 1)  do
          currComponIndexList[i] := StrToInt(BeginComponIndexNum.Text);
      end;

      for i := 0 to ACompon.ChildComplects.Count - 1 do
      begin
        currCompon := ACompon.ChildComplects[i];
        if ComponTypes.IndexOf(currCompon.ComponentType.NamePlural) <> -1 then
        begin
          Catalog := currCompon.GetFirstParentCatalog;
          if Catalog <> nil then
          begin
            CurrCabinet := Catalog.GetParentCatalogByItemType(itRoom);
            if ReindexByType.Checked then
              //currComponIndex := ComponentIndexList[ComponTypes.IndexOF(currCompon.ComponentType.NamePlural)];
              currComponIndex := currComponIndexList[ComponTypes.IndexOF(currCompon.ComponentType.NamePlural)];
            currCompon.MarkID := currComponIndex;
            Inc(CurrComponIndex);
            if ReindexByType.Checked then
              //ComponentIndexList[ComponTypes.IndexOF(currCompon.ComponentType.NamePlural)] := currComponIndex;
              currComponIndexList[ComponTypes.IndexOF(currCompon.ComponentType.NamePlural)] := currComponIndex;
            ApplyChangeComponMarkID(currCompon, true, false, nil);
            TF_Main(GCadForm).F_ChoiceConnectSide.DefineObjectSignature(Catalog);
            ResultCabinet := Catalog.GetParentCatalogByItemType(itRoom);
            if ((CurrCabinet <> nil) and (ResultCabinet <> nil)) then
            begin
              if  currCabinet <> ResultCabinet then
              begin
                if currCabinet.ChildCatalogs.IndexOf(Catalog) <> - 1 then
                begin
                   MoveObjectToRoomInPM(GCadForm.FCADListID, Catalog.SCSID, currCabinet.SCSID);
                end;
              end;
            end;
          end;
        end;
        if currCompon.ChildComplects.Count > 0 then
          RemComponByParent(currCompon);
      end;
    end;
  end;

  procedure RemComponByTop(aComponent: TSCSComponent);
  var i, j: Integer;
      currCabinet, ResultCabinet, Catalog : TSCSCatalog;
      currCompon: TSCSComponent;
      PassedList, ComponList: TSCSComponents;
  begin
    if aComponent <> nil then
    begin
      //currComponIndex := StrToInt(BeginComponIndexNum.Text);}
      currCompon := aComponent;
      if ComponTypes.IndexOf(currCompon.ComponentType.NamePlural) <> -1 then
      begin
        if not AComponent.IsTop then
        begin
          Catalog := currCompon.GetFirstParentCatalog;
          if Catalog <> nil then
          begin
            CurrCabinet := Catalog.GetParentCatalogByItemType(itRoom);
            if ReindexByType.Checked then
              currComponIndex := ComponentIndexList[ComponTypes.IndexOF(currCompon.ComponentType.NamePlural)];
            currCompon.MarkID := currComponIndex;
            Inc(currComponIndex);
            if ReindexByType.Checked then
              ComponentIndexList[ComponTypes.IndexOF(currCompon.ComponentType.NamePlural)] := currComponIndex;
            ApplyChangeComponMarkID(currCompon, true, false, nil);
            TF_Main(GCadForm).F_ChoiceConnectSide.DefineObjectSignature(Catalog);
            ResultCabinet := Catalog.GetParentCatalogByItemType(itRoom);
            if ((CurrCabinet <> nil) and (ResultCabinet <> nil)) then
            begin
              if  currCabinet <> ResultCabinet then
               begin
                if currCabinet.ChildCatalogs.IndexOf(Catalog) <> - 1 then
                begin
                   MoveObjectToRoomInPM(GCadForm.FCADListID, Catalog.SCSID, currCabinet.SCSID);
                end;
              end;
            end;
          end;
        end;
      end;
      if currCompon.ChildComplects.Count > 0 then
      begin
        for i := 0 to currCompon.ChildComplects.Count - 1 do
        begin
          RemComponByTop(currCompon.ChildComplects[i]);
        end;
      end;
    end;
  end;

  procedure GetAllComponsFromCompon(SCSCompon: TSCSComponent; Var ComponList: TSCSComponents);
  var currCompon: TSCSComponent;
    i: Integer;
  begin
    if ComponTypes.IndexOf(SCSCompon.ComponentType.NamePlural) <> -1 then
      ComponList.Add(SCSCompon);
    for i := 0 to SCSCompon.ChildComplects.Count - 1 do
    begin
      currCompon := SCSCompon.ChildComplects[i];
      if currCompon.ChildComplects.Count = 0 then
      begin
        if ComponTypes.IndexOf(currCompon.ComponentType.NamePlural) <> -1 then
          ComponList.Add(currCompon);
      end
      else
      begin
        GetAllComponsFromCompon(currCompon, ComponList);
      end;
    end;
  end;

  Procedure RemarkList(aTmpFiguresList: TList);
  Var i, j, k: Integer;
    aTmpFigure: TFigure;
    Component: TSCSComponent;
    Catalog: TSCSCatalog;
    CatalogList: TSCSCatalogs;
    ComponList, PassedList: TSCSComponents;
  Begin
    try
      ComponList := Nil;
      CatalogList := Nil;
      if aTmpFiguresList.Count > 0 then
      begin
        for i := 0 to aTmpFiguresList.Count - 1 do
        begin
          Figure := TFigure(aTmpFiguresList[i]);
          ShowObjectInPM(Figure.ID, Figure.Name, False);
        end;
        CatalogList := TSCSCatalogs.Create(false);
        // Define Catalog List by Selected Types
        for i := 0 to aTmpFiguresList.Count - 1 do
        begin
          aTmpFigure := TFigure(aTmpFiguresList[i]);
          Catalog := F_ProjMan.GSCSBase.CurrProject.CurrList.GetCatalogFromReferencesBySCSID(aTmpFigure.ID);
          if Catalog <> nil then
          begin
            if CatalogList.IndexOf(Catalog) = -1 then
            begin
              for j := 0 to Catalog.SCSComponents.Count - 1 do
              begin
                Component := Catalog.SCSComponents[j];
                if Component.IsTop then
                begin
                  if ComponTypes.IndexOf(Component.ComponentType.NamePlural) <> -1 then
                    CatalogList.Add(Catalog);
                Break;
                end;
              end;
            end;
          end;
        end;
        // Reindex Catalogs Only (means the objects!!!)
        if ReindexOnObj.Checked then
        begin
          // Index by SelectedMode (by Type Or Total)
          if ComponTypes.Count > 0 then
          begin
            for i := 0 to CatalogList.Count - 1 do
            begin
              Catalog := CatalogList[i];
              for j := 0 to Catalog.SCSComponents.Count - 1 do
              begin
                Component := Catalog.SCSComponents[j];
                if Component.IsTop then
                begin
                  if ComponTypes.IndexOf(Component.ComponentType.NamePlural) <> - 1 then
                  begin
                    if ReindexByType.Checked then
                      currIndex := IndexList[ComponTypes.IndexOf(Component.ComponentType.NamePlural)];
                    Catalog.MarkID := currIndex;
                    Inc(CurrIndex);
                    Catalog.NameMark :=  TF_MAIN(Catalog.ActiveForm).MakeNameMarkCatalog(Catalog.ID, false, qmMemory);
                    if Assigned(Catalog.TreeViewNode) then
                      Catalog.TreeViewNode.Text := Catalog.GetNameForVisible(true);
                    if ReindexByType.Checked then
                      IndexList[ComponTypes.IndexOf(Component.ComponentType.NamePlural)] := currIndex;
                  end;
                  Break;
                end;
              end;
            end;
          end;
        end
        else
        // ==================================================================================================================
        // Components Reindex
        if ReindexOnCompon.Checked then
        begin
          ComponList := TSCSComponents.Create(false);
          if ((IndexOnlyHigh.Checked) or ((not IndexOnlyHigh.Checked) and (Point_IndexType.Buttons[0].Checked = False))) then
          begin
            for i := 0 to CatalogList.Count - 1 do
            begin
              //Index Top Components
              Catalog := CatalogList[i];
              for k := 0 to Catalog.SCSComponents.Count - 1 do
              begin
                Component := Catalog.SCSComponents[k];
                ComponList.Add(Component);
                if ((not IndexComplectOnly.Enabled) or ((IndexComplectOnly.Enabled) and (IndexComplectOnly.Checked = false))) then
                begin
                  currCabinet := Catalog.GetParentCatalogByItemType(itRoom);
                  if ReindexByType.Checked then
                    currIndex := IndexList[ComponTypes.IndexOf(Component.ComponentType.NamePlural)];
                  Component.MarkID := CurrIndex;
                  Inc(currIndex);
                  ApplyChangeComponMarkID(Component, true, false, nil);
                  TF_Main(GCadForm).F_ChoiceConnectSide.DefineObjectSignature(Catalog);
                  if ReindexByType.Checked then
                    IndexList[ComponTypes.IndexOf(Component.ComponentType.NamePlural)] := currIndex;

                  if currCabinet <> nil then
                  begin
                    if currCabinet.ChildCatalogs.IndexOf(Catalog)  = -1 then
                    begin
                      MoveObjectToRoomInPM(GCadForm.FCADListID, Catalog.SCSID, currCabinet.SCSID);
                    end;
                  end;
                end;
              end;

              if not IndexOnlyHigh.Checked then
              begin
                if Point_IndexType.Buttons[1].Checked then
                begin
                  for j := 0 to ComponList.Count - 1 do
                  begin
                    RemComponByParent(ComponList[j]);
                  end;
                end
                else
                if Point_IndexType.Buttons[2].Checked then
                begin
                  for j := 0 to ComponList.Count - 1 do
                  begin
                    currComponIndex := StrToInt(BeginComponIndexNum.Text);
                    if ReindexByType.Checked then
                    begin
                      for k := 0 to Length(ComponentIndexList) - 1 do
                        ComponentIndexList[k] := StrToInt(BeginComponIndexNum.Text);
                    end;
                    RemComponByTop(ComponList[j]);
                  end;
                end;
              end;
              ComponList.Clear;
            end;
          end
          else
          if ((IndexOnlyHigh.Checked = False) and (Point_IndexType.Buttons[0].Checked = True)) then
          begin
            // Get Compons from Catalog by User Selected Types
            for i := 0 to CatalogList.Count - 1 do
            begin
              Catalog := CatalogList[i];
              for k := 0 to Catalog.SCSComponents.Count - 1 do
              begin
               { for j := 0 to Catalog.ComponentReferences.Count - 1 do
                begin
                  if ComponTypes.IndexOf(Catalog.ComponentReferences[j].ComponentType.NamePlural) <> -1 then
                    ComponList.Add(Catalog.ComponentReferences[j]);
                end; }
                ComponList.Clear;
                GetAllComponsFromCompon(Catalog.SCSComponents[k], ComponList);
                for j := 0 to ComponList.Count - 1 do
                begin
                  Component := ComponList[j];
                  if ( (not Component.IsTop) or ((Component.IsTop) and ((not IndexComplectOnly.Enabled) or ((IndexComplectOnly.Enabled) and (IndexComplectOnly.Checked = false)))) ) then
                  begin
                    currCabinet := Catalog.GetParentCatalogByItemType(itRoom);
                    if ReindexByType.Checked then
                        currIndex := IndexList[ComponTypes.IndexOf(Component.ComponentType.NamePlural)];
                    Component.MarkID := CurrIndex;
                    Inc(currIndex);
                    ApplyChangeComponMarkID(Component, true, false, nil);
                    TF_Main(GCadForm).F_ChoiceConnectSide.DefineObjectSignature(Catalog);
                    if ReindexByType.Checked then
                      IndexList[ComponTypes.IndexOf(Component.ComponentType.NamePlural)] := currIndex;

                    if currCabinet <> nil then
                    begin
                      if currCabinet.ChildCatalogs.IndexOf(Catalog)  = -1 then
                      begin
                        MoveObjectToRoomInPM(GCadForm.FCADListID, Catalog.SCSID, currCabinet.SCSID);
                      end;
                    end;
                  end;
                end;
              end;
            end;
          end;
        end;
        ChangeFiguresCaptions(TSCSCatalogs(CatalogList));
        if aCad <> nil then
            RefreshCad(aCad.PCad);
      end;
    finally
      // Tolik 13/05/2019 --
      if ComponList <> nil then
        ComponList.Free;
      if CatalogList <> nil then
        CatalogList.Free;
      //
    end;
  End;

  procedure Mark_byCreationOrder;
  var i, j, k: Integer;
      Figure: TFigure;
      CatalogList: TSCSCatalogs;
      Compon: TSCSComponent;
      currCabinet, Catalog: TSCSCatalog;
      ComponList: TSCSComponents;
  begin
    if FiguresList.Count > 0 then
    // Sort Figures By Creation Order
    begin
      for i := 0 to FiguresList.Count - 1 do
      begin
        Figure := TFigure(FiguresList[i]);
        ShowObjectInPM(Figure.ID, Figure.Name, False);
      end;
      if FiguresList.Count > 1 then
      begin
        SortAgain := True;
        while SortAgain do
        begin
          SortAgain := False;
          for i := 0 to FiguresList.Count - 2 do
          begin
            if TFigure(FiguresList[i]).ID > TFigure(FiguresList[i + 1]).ID then
            begin
              SortAgain := True;
              Figure := TFigure(FiguresList[i + 1]);
              FiguresList[i + 1] := FiguresList[i];
              FiguresList[i] := Figure;
            end;
          end;
        end;
      end;  

      CatalogList := TSCSCatalogs.Create(False);
      for i := 0 to FiguresList.Count - 1 do
      begin
        Figure := TFigure(FiguresList[i]);
        Catalog := F_ProjMan.GSCSBase.CurrProject.CurrList.GetCatalogFromReferencesBySCSID(Figure.ID);
        if Catalog <> nil then
        begin
          //for j := 0 to Catalog.SCSComponents.Count - 1 do
          for j := 0 to Catalog.ComponentReferences.Count - 1 do
          begin
           // Compon := Catalog.SCSComponents[j];
            Compon := Catalog.ComponentReferences[j];
           { if Compon.IsTop then
            begin}
              if ComponTypes.IndexOf(Compon.ComponentType.NamePlural) <> -1 then
              begin
                CatalogList.Add(Catalog);
                break;
              end;
           // end;
          end;
        end;
      end;

      if CatalogList.Count > 0 then
      begin
        if CatalogList.Count > 1 then
        begin
          //sort CatalogList by Creation Order
          SortAgain := true;
          while SortAgain do
          begin
            SortAgain := False;
            for i := 0 to CatalogList.Count - 2 do
            begin
              if CatalogList[i].SCSID > CatalogList[i + 1].SCSID then
              begin
                Catalog := CatalogList[i];
                CatalogList[i] := CatalogList[i + 1];
                CatalogList[i + 1] := Catalog;
                SortAgain := True;
              end;
            end;
          end;
        end;

        if ReindexOnObj.Checked then
        begin
          for i := 0 to CatalogList.Count - 1 do
          begin
            Catalog := CatalogList[i];
            for j := 0 to Catalog.SCSComponents.Count - 1 do
            begin
              Compon := Catalog.SCSComponents[j];
              if Compon.IsTop then
              begin
                if ComponTypes.IndexOf(Compon.ComponentType.NamePlural) <> - 1 then
                begin
                  if ReindexByType.Checked then
                    currIndex := IndexList[ComponTypes.IndexOf(Compon.ComponentType.NamePlural)];
                  Catalog.MarkID := currIndex;
                  Inc(CurrIndex);
                  Catalog.NameMark :=  TF_MAIN(Catalog.ActiveForm).MakeNameMarkCatalog(Catalog.ID, false, qmMemory);
                  if Assigned(Catalog.TreeViewNode) then
                    Catalog.TreeViewNode.Text := Catalog.GetNameForVisible(true);
                  if ReindexByType.Checked then
                    IndexList[ComponTypes.IndexOf(Compon.ComponentType.NamePlural)] := currIndex;
                  SetIndexToFigure(Catalog.ListID, Catalog.SCSID, Catalog.MarkID);
                end;
                Break;
              end;
            end;
          end;

          //RefreshCad(GCadForm.PCAD);
        end
        else
        if ReindexOnCompon.Checked then
        begin
          // Tolik 13/05/2019 --
          //ComponList := TSCSComponents.Create(false);
          ComponList := Nil;
          //
          if ((IndexOnlyHigh.Checked) or ((not IndexOnlyHigh.Checked) and (Point_IndexType.Buttons[0].Checked = False))) then
          begin
            for i := 0 to CatalogList.Count - 1 do
            begin
              ComponList := GetTopList(CatalogList[i].SCSComponents);
              if ComponList.Count > 0 then
              begin
                // Sort List by Creation Order
                if ComponList.Count > 1 then
                begin
                  SortAgain := true;
                  while SortAgain do
                  begin
                    SortAgain := false;
                    for j := 0 to ComponList.Count - 2 do
                    begin
                      if ComponList[j].ID > ComponList[j + 1].ID then
                      begin
                        SortAgain := True;
                        Compon := ComponList[j];
                        ComponList[j] := ComponList[j + 1];
                        ComponList[j + 1] := Compon;
                      end;
                    end;
                  end;
                end;
              end;
              //Index Top Components
              Catalog := CatalogList[i];
              if ((not IndexComplectOnly.Enabled) or ((IndexComplectOnly.Enabled) and (IndexComplectOnly.Checked = false))) then
              begin
                for j := 0 to ComponList.Count - 1 do
                begin
                  Compon := ComponList[j];
                  currCabinet := Catalog.GetParentCatalogByItemType(itRoom);
                  if ReindexByType.Checked then
                      currIndex := IndexList[ComponTypes.IndexOf(Compon.ComponentType.NamePlural)];
                  Compon.MarkID := CurrIndex;
                  Inc(currIndex);
                  ApplyChangeComponMarkID(Compon, true, false, nil);
                  TF_Main(GCadForm).F_ChoiceConnectSide.DefineObjectSignature(Catalog);
                  if ReindexByType.Checked then
                    IndexList[ComponTypes.IndexOf(Compon.ComponentType.NamePlural)] := currIndex;

                  if currCabinet <> nil then
                  begin
                    if currCabinet.ChildCatalogs.IndexOf(Catalog)  = -1 then
                    begin
                      MoveObjectToRoomInPM(GCadForm.FCADListID, Catalog.SCSID, currCabinet.SCSID);
                    end;
                  end;
                end;
              end;

              if not IndexOnlyHigh.Checked then
              begin
                if Point_IndexType.Buttons[1].Checked then
                begin
                  for j := 0 to ComponList.Count - 1 do
                  begin
                    RemComponByParent(ComponList[j]);
                  end;
                end
                else
                if Point_IndexType.Buttons[2].Checked then
                begin
                  for j := 0 to ComponList.Count - 1 do
                  begin
                    currComponIndex := StrToInt(BeginComponIndexNum.Text);
                    if ReindexByType.Checked then
                    begin
                      for k := 0 to Length(ComponentIndexList) - 1 do
                        ComponentIndexList[k] := StrToInt(BeginComponIndexNum.Text);
                    end;
                    RemComponByTop(ComponList[j]);
                  end;
                end;
              end;
              FreeAndNil(ComponList); // Tolik 13/05/2019 - -
            end;
          end
          else
          if ((IndexOnlyHigh.Checked = False) and (Point_IndexType.Buttons[0].Checked = True)) then
          begin
            // Get Compons from Catalog by User Selected Types
            ComponList := TSCSComponents.Create(False); // Tolik 13/05/2019 --
            for i := 0 to CatalogList.Count - 1 do
            begin
              ComponList.Clear;
              Catalog := CatalogList[i];
              for j := 0 to Catalog.ComponentReferences.Count - 1 do
              begin
                if ComponTypes.IndexOf(Catalog.ComponentReferences[j].ComponentType.NamePlural) <> -1 then
                  ComponList.Add(Catalog.ComponentReferences[j]);
              end;

              if ComponList.Count > 0 then
              begin
                if ComponList.Count > 1 then
                begin
                  //Sort Compons by creation Order
                  SortAgain := True;
                  while SortAgain do
                  begin
                    SortAgain := false;
                    for j := 0 to ComponList.Count - 2 do
                    begin
                      if ComponList[j].ID > ComponList[j + 1].ID then
                      begin
                        SortAgain := True;
                        Compon := ComponList[j];
                        ComponList[j] := ComponList[ j + 1];
                        ComponList[j + 1] := Compon;
                      end;
                    end;
                  end;
                end;
              end;

              for j := 0 to ComponList.Count - 1 do
              begin
                Compon := ComponList[j];
                if ( (not Compon.IsTop) or ((Compon.IsTop) and ((not IndexComplectOnly.Enabled) or ((IndexComplectOnly.Enabled) and (IndexComplectOnly.Checked = false)))) ) then
                begin
                  currCabinet := Catalog.GetParentCatalogByItemType(itRoom);
                  if ReindexByType.Checked then
                      currIndex := IndexList[ComponTypes.IndexOf(Compon.ComponentType.NamePlural)];
                  Compon.MarkID := CurrIndex;
                  Inc(currIndex);
                  ApplyChangeComponMarkID(Compon, true, false, nil);
                  TF_Main(GCadForm).F_ChoiceConnectSide.DefineObjectSignature(Catalog);
                  if ReindexByType.Checked then
                    IndexList[ComponTypes.IndexOf(Compon.ComponentType.NamePlural)] := currIndex;

                  if currCabinet <> nil then
                  begin
                    if currCabinet.ChildCatalogs.IndexOf(Catalog)  = -1 then
                    begin
                      MoveObjectToRoomInPM(GCadForm.FCADListID, Catalog.SCSID, currCabinet.SCSID);
                    end;
                  end;
                end;
              end;
            end;
          end;
        end;
      end;
    end;
    ChangeFiguresCaptions(CatalogList);
    if ComponList <> nil then
      ComponList.Free;
    CatalogList.free; // Tolik 13/05/2019 --
    //RemarkList(FiguresList);
    if aCad <> nil then
      RefreshCad(aCad.PCad);
  end;

  Procedure RemComponList(aList: TSCSComponents);
  var i: Integer;
    Component: TSCSComponent;
    currCabinet, ResultCabinet, Catalog : TSCSCatalog;
    Marked: Boolean;

  begin
    if aList.Count > 0 then
    begin
      for i := 0 to aList.Count - 1 do
      begin
        Marked := False;
        Component := aList[i];
        Catalog := Component.GetFirstParentCatalog;
        if Catalog <> nil then
        begin
          Marked := false;
          CurrCabinet := Catalog.GetParentCatalogByItemType(itRoom);
          if ReindexByType.Checked then
          begin
            // Top Components
            if Component.IsTop then
            begin
              if ((not IndexComplectOnly.Enabled) or ((IndexComplectOnly.Enabled) and (IndexComplectOnly.Checked = false))) then
              begin
                CurrIndex := IndexList[ComponTypes.IndexOF(Component.ComponentType.NamePlural)];
                Component.MarkID := currIndex;
                Inc(CurrIndex);
                Marked := True;
              end;
            end
            else
            // Child Components
            begin
              if ((not IndexOnlyHigh.Enabled) or ((IndexOnlyHigh.Enabled) and (IndexOnlyHigh.Checked = false))) then
              {begin
                CurrComponIndex := ComponentIndexList[ComponTypes.IndexOF(Component.ComponentType.NamePlural)];
                Component.MarkId := CurrComponIndex;
                INC(CurrComponIndex);
              end;
              begin }
                CurrIndex := IndexList[ComponTypes.IndexOF(Component.ComponentType.NamePlural)];
                Component.MarkID := currIndex;
                Inc(CurrIndex);
                Marked := True;
              
            end;
          end
          else
          begin
            if Component.IsTop then
            begin
              if ((not IndexComplectOnly.Enabled) or ((IndexComplectOnly.Enabled) and (IndexComplectOnly.Checked = false))) then
              begin
                Component.MarkID := currIndex;
                Inc(CurrIndex);
                Marked := True;
              end;
            end
            else
            begin
              if ((not IndexOnlyHigh.Enabled) or ((IndexOnlyHigh.Enabled) and (IndexOnlyHigh.Checked = false))) then
              begin
                Component.MarkID := currIndex;
                Inc(CurrIndex);
                Marked := True;
              end;
            end;
          end;
          if Marked then
          begin
            ApplyChangeComponMarkID(Component, true, false, nil);
            TF_Main(GCadForm).F_ChoiceConnectSide.DefineObjectSignature(Catalog);
            if ReindexByType.Checked then
              IndexList[ComponTypes.IndexOF(Component.ComponentType.NamePlural)] := CurrIndex;
            //check if Cabinet changed
            ResultCabinet := Catalog.GetParentCatalogByItemType(itRoom);
            if ((CurrCabinet <> nil) and (ResultCabinet <> nil)) then
            begin
              if  currCabinet <> ResultCabinet then
              begin
                if currCabinet.ChildCatalogs.IndexOf(Catalog) <> - 1 then
                begin
                   MoveObjectToRoomInPM(GCadForm.FCADListID, Catalog.SCSID, currCabinet.SCSID);
                end;
              end;
            end;
          end;
        end;
      end;
    end;
  end;

  Function GetTopComponList(aCatalogList: TSCSCatalogs): TSCSComponents;
  Var i, j: Integer;
      Catalog: TSCSCatalog;
  Begin
    Result := TSCSComponents.Create(false);
    for i := 0 to aCatalogList.Count - 1 do
    begin
      Catalog := aCatalogList[i];
      for j := 0 to Catalog.SCSComponents.Count - 1 do
      begin
        Result.Add(Catalog.SCSComponents[j]);
      end;
    end;
  End;

  // Mark by ProjMan Order
  Procedure Mark_byPMOrder;
  Var i, j, k, l: Integer;
    Figure: TFigure;
    Catalog, Catalog1: TSCSCatalog;
    currList: TSCSList;
    TempCatalogList, CatalogList: TSCSCatalogs;
    Component: TSCSComponent;
    Node, RoomNode: TTreeNode;
    {CurrIndex,} currTopIndex : Integer;
    ComponList: TSCSComponents;
    currCabinet, ResultCabinet: TSCSCatalog;
    currIndexArray: Array of Integer;
    QueryMode: TQueryMode;
    //gForm: TForm;

    procedure GetAllComponsFromCompon(SCSCompon: TSCSComponent);
    var currCompon: TSCSComponent;
      i: Integer;
    begin
      if ComponTypes.IndexOf(SCSCompon.ComponentType.NamePlural) <> -1 then
        ComponList.Add(SCSCompon);
      for i := 0 to SCSCompon.ChildComplects.Count - 1 do
      begin
        currCompon := SCSCompon.ChildComplects[i];
        if currCompon.ChildComplects.Count = 0 then
        begin
          if ComponTypes.IndexOf(currCompon.ComponentType.NamePlural) <> -1 then
            ComponList.Add(currCompon);
        end
        else
        begin
          GetAllComponsFromCompon(currCompon);
        end;
      end;
    end;

    Procedure GetCatalogListFromTreeNode(aNode: TTreeNode);
    var i: Integer;
        Catalog: TSCSCatalog;
        ChildNode: TTreeNode;
    begin
      if aNode <> nil then
      begin
        Catalog := F_ProjMan.GSCSBase.CurrProject.CurrList.GetCatalogFromReferences(PObjectData(aNode.Data).ObjectID);
        if Catalog <> nil then
        begin
          // Catalog
          if (TempCatalogList.IndexOf(Catalog) <> -1) and  (CatalogList.IndexOf(Catalog) = - 1) then
            CatalogList.Add(Catalog);
        end;
        {if aNode.Count = 0 then
        begin
          Catalog := F_ProjMan.GSCSBase.CurrProject.CurrList.GetCatalogFromReferences(PObjectData(aNode.Data).ObjectID);
          if Catalog <> nil then
          begin
            // Catalog
            if (TempCatalogList.IndexOf(Catalog) <> -1) and  (CatalogList.IndexOf(Catalog) = - 1) then
              CatalogList.Add(Catalog);
          end;
        end
        else }
        if aNode.Count > 0 then
        begin
          for i := 0 to aNode.Count - 1 do
          begin
            ChildNode := aNode.Item[i];
            if ChildNode <> nil then
              GetCatalogListFromTreeNode(ChildNode);
          end;
        end;
      end;
    end;

  Begin
    //GetCurrList
    //gForm := F_ReindexMaster;
    ComponList := nil;
    CurrList := F_ProjMan.GSCSBase.CurrProject.CurrList;
    if CurrList <> nil then
    begin
      TempCatalogList := TSCSCatalogs.Create(false);
      CatalogList := TSCSCatalogs.Create(false);
      //CurrIndex :=  StrToInt(BeginIndexNum.Text);
      // AllCatalogList
      for i := 0 to FiguresList.Count - 1 do
      begin
        Figure := TFigure(FiguresList[i]);
        Catalog := F_ProjMan.GSCSBase.CurrProject.CurrList.GetCatalogFromReferencesBySCSID(Figure.ID);
        // Check to take by Selected Types Only
        if (Catalog <> nil) and (TempCatalogList.IndexOf(Catalog) = -1) then
        begin
          for j := 0 to Catalog.ComponentReferences.Count - 1 do
          begin
            Component := Catalog.ComponentReferences[j];
            if ComponTypes.IndexOf(Component.ComponentType.NamePlural) <> -1 then
            begin
              TempCatalogList.Add(Catalog);
              Break;
            end;
          end;
        end;
      end;
      // Get CatalogList by PM Order on Selected Figures
      for i := 0 to FiguresList.Count - 1 do
      begin
        Figure := TFigure(FiguresList[i]);
        ShowObjectInPM(Figure.ID, Figure.Name, False);
      end;

      //if CurrList.TreeViewNode.Count > 0 then
      if F_ProjMan.GSCSBase.CurrProject.CurrList.TreeViewNode.Count > 0 then
      begin
        //j := CurrList.TreeViewNode.Count - 1;
        j := F_ProjMan.GSCSBase.CurrProject.CurrList.TreeViewNode.Count - 1;
        for i := 0 to j do
        begin
          //Node := currList.TreeViewNode.Item[i];
          Node := F_ProjMan.GSCSBase.CurrProject.CurrList.TreeViewNode.Item[i];
          if Node <> nil then
            GetCatalogListFromTreeNode(Node);
          {begin
            Catalog := F_ProjMan.GSCSBase.CurrProject.CurrList.GetCatalogFromReferences(PObjectData(Node.Data).ObjectID);
            //Catalog :=  F_ProjMan.GSCSBase.CurrProject.CurrList.GetCatalogFromReferencesBySCSID(PObjectData(Node.Data).ObjectID);
            if Catalog <> nil then
            begin
              // Catalog
              if Catalog.ItemType <> itRoom then
              begin
                if (TempCatalogList.IndexOf(Catalog) <> -1) and  (CatalogList.IndexOf(Catalog) = - 1) then
                  CatalogList.Add(Catalog);
              end
              else
              // if Room
              begin
                for k := 0 to Node.Count - 1 do
                begin
                  RoomNode := Node.Item[k];
                  //Catalog := F_ProjMan.GSCSBase.CurrProject.CurrList.GetCatalogFromReferencesBySCSID(PObjectData(RoomNode.Data).ObjectID);
                  Catalog := F_ProjMan.GSCSBase.CurrProject.CurrList.GetCatalogFromReferences(PObjectData(RoomNode.Data).ObjectID);
                  if Catalog <> nil then
                  begin
                    if (TempCatalogList.IndexOf(Catalog) <> -1) and  (CatalogList.IndexOf(Catalog) = - 1) then
                      CatalogList.Add(Catalog);
                  end;
                end;
              end;
            end;
          end;}
        end;
      end;
      // if Objects
      if ReindexOnObj.Checked then
      begin
        if CatalogList.Count > 0 then
        // Reindexing
        begin
          for i := 0 to CatalogList.Count - 1 do
          begin
            Catalog := CatalogList[i];
            Component := Catalog.GetFirstComponent;
            if ComponTypes.IndexOf(Component.ComponentType.NamePlural) <> -1 then
            begin
              if ReindexByType.Checked then
                currIndex := IndexList[ComponTypes.IndexOf(Component.ComponentType.NamePlural)];
              Catalog.MarkID := currIndex;
              Inc(CurrIndex);
              Catalog.NameMark :=  TF_MAIN(Catalog.ActiveForm).MakeNameMarkCatalog(Catalog.ID, false, qmMemory);
              if Assigned(Catalog.TreeViewNode) then
                Catalog.TreeViewNode.Text := Catalog.GetNameForVisible(true);
              if ReindexByType.Checked then
                IndexList[ComponTypes.IndexOf(Component.ComponentType.NamePlural)] := currIndex;
            end;
          end;
        end;
      end
      else
      if ReindexOnCompon.Checked then
      begin
        ComponList := TSCSComponents.Create(false);
        if not IndexOnlyHigh.Checked then
        begin
          // Reindex with Components
          if Point_IndexType.ItemIndex = 0 then
          begin
            // Build componList
            for i := 0 to CatalogList.Count - 1 do
            begin
              Catalog := CatalogList[i];
              // not Only Top Components(All)
              for j := 0 to Catalog.SCSComponents.Count - 1 do
              begin
                Component := Catalog.SCSComponents[j];
                GetAllComponsFromCompon(Component);
              end;
            end;
            // Reindex
            RemComponList(ComponList);
          end
          else
          // Reindex by Parent
          if Point_IndexType.ItemIndex = 1 then
          begin
            FreeAndNil(ComponList);
            ComponList := GetTopComponList(CatalogList);
            RemComponList(ComponList);
            for i := 0 to ComponList.Count - 1 do
            begin
              Component := ComponList[i];
              RemComponByParent(Component);
            end;
          end
          else
          //Reindex by Top
          if Point_IndexType.ItemIndex = 2 then
          begin
            FreeAndNil(ComponList);
            ComponList := GetTopComponList(CatalogList);
            RemComponList(ComponList);
            for i := 0 to ComponList.Count - 1 do
            begin
              Component := ComponList[i];
              currComponIndex := StrToInt(BeginComponIndexNum.Text);
              {if ((DropIndexCounter.Enabled and (not DropIndexCounter.Checked)) or (DropIndexCounter.Enabled = false)) then
              begin
                if ReindexByType.Checked and BeginComponIndexNum.Enabled then
                begin
                  for j := 0 to Length(ComponentIndexList) - 1 do
                    ComponentIndexList[j] := StrToInt(BeginComponIndexNum.Text);
                end;
              end; }
              currComponIndex := StrToInt(BeginComponIndexNum.Text);
              if ReindexByType.Checked then
              begin
                for k := 0 to Length(ComponentIndexList) - 1 do
                  ComponentIndexList[k] := StrToInt(BeginComponIndexNum.Text);
              end;
              for j := 0 to Component.ChildComplects.Count - 1 do
              begin
                RemComponByTop(Component.ChildComplects[j]);
              end;
            end;
          end;
        end
        else
        begin
          for i := 0 to CatalogList.Count - 1 do
          begin
            Catalog := CatalogList[i];
            // only Top components
            for j := 0 to Catalog.SCSComponents.Count - 1 do
            begin
              Component := Catalog.SCSComponents[j];
              if (Component.IsTop) and (ComponTypes.IndexOf(Component.ComponentType.NamePlural) <> -1) then
                ComponList.Add(Component);
            end;
          end;
          // Reindex
          RemComponList(ComponList);
        end;
      end;
    end;
    ChangeFiguresCaptions(CatalogList);
    if ComponList <> nil then
      FreeAndNil(ComponList);
  End;

  procedure RemarkSelectionHL;
  var i: Integer;
  begin
    if TmpFiguresList = nil then
      TmpFiguresList := TList.Create;
    // drop counters
    if FiguresList.Count > 0 then
    begin
      if FiguresList.Count > 1 then
      begin
        SortAgain := True;
        // Сортировка по высоте
        while SortAgain do
        begin
          SortAgain := false;
          for i := 0 to FiguresList.Count - 2 do
          begin
            if TFigure(FiguresList[i]).ap1.y > TFigure(FiguresList[i+1]).ap1.y then
            begin
              Figure := TFigure(FiguresList[i]);
              FiguresList[i] := FiguresList[i+1];
              FiguresList[i+1] := Figure;
              SortAgain := true;
            end;
          end;
        end;
        SortFiguresCount := FiguresList.Count;
        PassedFiguresList := TList.Create;
        Counter := 0;
        While Counter <> SortFiguresCount do
        begin
          TmpFigure := nil;
          for i := 0 to FiguresList.Count - 1 do
          begin
            Figure := TFigure(FiguresList[i]);
            if PassedFiguresList.IndexOf(Figure) = -1 then
            begin
              if TmpFigure = nil then
              begin
                TmpFigure := FiguresList[i];
                TmpFiguresList.Add(TmpFigure);
                PassedFiguresList.Add(TmpFigure);
                Inc(Counter);
              end
              else
              begin
                if Abs(TmpFigure.ap1.y - TFigure(FiguresList[i]).ap1.y) <= 10 then
                begin
                  TmpFiguresList.Add(TFigure(FiguresList[i]));
                  PassedFiguresList.Add(TFigure(FiguresList[i]));
                  Inc(Counter);
                end
                else
                  Break;
              end;
            end;
          end;
          //sort tmpList
          if TmpFiguresList.Count > 1 then
          begin
            SortAgain := True;
            while SortAgain do
            begin
              SortAgain := False;
              for i := 0 to TmpFiguresList.Count - 2 do
              begin
                if TFigure(TmpFiguresList[i]).ap1.x > TFigure(TmpFiguresList[i + 1]).ap1.x then
                begin
                  Figure := TFigure(TmpFiguresList[i]);
                  TmpFiguresList[i] := TmpFiguresList[i + 1];
                  TmpFiguresList[i + 1] := Figure;
                  SortAgain := true;
                end;
              end;
            end;
          end;
          // remark
          RemarkList(TmpFiguresList);
          TmpFiguresList.Clear;
        end;
      end
      else
      begin
        TmpFiguresList.Add(FiguresList[0]);
        RemarkList(TmpFiguresList);
        TmpFiguresList.Clear;
      end;
      if not GProjectChanged then // Tolik 28/08/2019 --
        SetProjectChanged(True);
      if aCad <> nil then
        RefreshCad(aCad.PCad);
    end;
  end;

  procedure RemarkSelectionLH;
  var i: Integer;
  begin
    if FiguresList.Count > 0 then
    begin
      if FiguresList.Count > 1 then
      begin
        SortAgain := True;
        while SortAgain do
        begin
          SortAgain := false;
          for i := 0 to FiguresList.Count - 2 do
          begin
            if TFigure(FiguresList[i]).ap1.x > TFigure(FiguresList[i+1]).ap1.x then
            begin
              Figure := TFigure(FiguresList[i]);
              FiguresList[i] := FiguresList[i+1];
              FiguresList[i+1] := Figure;
              SortAgain := true;
            end;
          end;
        end;
        SortFiguresCount := FiguresList.Count;
        PassedFiguresList := TList.Create;
        if TmpFiguresList = nil then
          TmpFiguresList := TList.Create;
        Counter := 0;
        While Counter <> SortFiguresCount do
        begin
          TmpFigure := nil;
          for i := 0 to FiguresList.Count - 1 do
          begin
            Figure := TFigure(FiguresList[i]);
            if PassedFiguresList.IndexOf(Figure) = -1 then
            begin
              if TmpFigure = nil then
              begin
                TmpFigure := FiguresList[i];
                TmpFiguresList.Add(TmpFigure);
                PassedFiguresList.Add(TmpFigure);
                Inc(Counter);
              end
              else
              begin
                if Abs(TmpFigure.ap1.x - TFigure(FiguresList[i]).ap1.x) <= 10 then
                begin
                  TmpFiguresList.Add(TFigure(FiguresList[i]));
                  PassedFiguresList.Add(TFigure(FiguresList[i]));
                  Inc(Counter);
                end
                else
                  Break;
              end;
            end;
          end;
          //sort tmpList
          if TmpFiguresList.Count > 1 then
          begin
            SortAgain := True;
            while SortAgain do
            begin
              SortAgain := False;
              for i := 0 to TmpFiguresList.Count - 2 do
              begin
                if TFigure(TmpFiguresList[i]).ap1.y > TFigure(TmpFiguresList[i + 1]).ap1.y then
                begin
                  Figure := TFigure(TmpFiguresList[i]);
                  TmpFiguresList[i] := TmpFiguresList[i + 1];
                  TmpFiguresList[i + 1] := Figure;
                  SortAgain := true;
                end;
              end;
            end;
          end;
        end;
      end;
      // remark
      if TmpFiguresList = nil then
      begin
          TmpFiguresList := TList.Create;
        TmpFiguresList.Add(FiguresList[0]);
      end;
      RemarkList(TmpFiguresList);
      TmpFiguresList.Clear;
      if not GProjectChanged then // Tolik 28/08/2019 --
        SetProjectChanged(True);
      if aCad <> nil then
        RefreshCad(aCad.PCad);
    end;
  end;

  Procedure SortListByZCoord(SortingList: TList);
  Var i: Integer;
  Begin
    SortAgain := true;
    while SortAgain do
    begin
      SortAgain := false;
      for i := 0 to SortingList.Count - 2 do
      begin
        Figure := TFigure(SortingList[i]);
        TmpFigure := TFigure(SortingList[i+1]);
        if ((Figure.ap1.x = TmpFigure.ap1.x) and (Figure.ap1.y = TmpFigure.ap1.y)) then
        begin
          if TConnectorObject(Figure).ActualZOrder[1] > TConnectorObject(TmpFigure).ActualZOrder[1] then
          begin
            SortingList[i] := TmpFigure;
            SortingList[i + 1] := Figure;
            SortAgain := True;
            Break;
          end;
        end;
      end;
    end;
  End;

  Procedure RemarkSelectionByNearest;
  Var i, DistArrayLength: Integer;
      DistList: array of Double;
      tmpFigure, BeginFigure: TFigure;
      tmpValue: Double;

    Function FindNearestFigure: TFigure;
    Var i: Integer;
        currFigure: TFigure;
        currValue: Double;
    Begin
      Result := nil;
      DistArrayLength:= 0;
      if TmpFiguresList <> nil then
        TmpFiguresList.Clear;
      SetLength(DistList,0);
      for i := 0 to FiguresList.Count - 1 do
      begin
        currFigure := TFigure(FiguresList[i]);
        if CheckFigureInList(PassedFiguresList, currFigure) = false then
        begin
          Inc(DistArrayLength);
          SetLength(DistList, DistArrayLength);
          currFigure := FiguresList[i];
          DistList[DistArrayLength - 1] := Sqrt( Sqr(TFigure(currFigure).ap1.x - TFigure(TmpFigure).ap1.x) +
                                                 Sqr(TFigure(currFigure).ap1.y - TFigure(TmpFigure).ap1.y) +
                                                 Sqr(TConnectorObject(currFigure).ActualZOrder[1] - TConnectorObject(TmpFigure).ActualZOrder[1])
                                               );
          TmpFiguresList.Add(currFigure);
        end;
      end;
      // sort lists
      SortAgain := True;
      while SortAgain do
      begin
        SortAgain := false;
        for i := 0 to DistArrayLength - 2 do
        begin
          if DistList[i] > DistList[i + 1] then
          begin
            currFigure := TFigure(TmpFiguresList[i]);
            TmpFiguresList[i] := TmpFiguresList[i + 1];
            TmpFiguresList[i + 1] := currFigure;
            currValue := DistList[i];
            DistList[i] := DistList[i + 1];
            DistList[i + 1] := currValue;
            SortAgain := True;
          end;
        end;
      end;
      Result := TmpFiguresList[0];
    End;

  Begin
    if FiguresList.Count > 0 then
    begin
      // drop counters
      if FiguresList.Count > 1 then
      begin
        SetLength(DistList,0);
        // Look for nearest to system coord zero point
        // buid array of distances
        for i := 0 to FiguresList.Count - 1 do
        begin
          TmpFigure := TFigure(FiguresList[i]);
          SetLength(DistList, Length(DistList) + 1);
          DistList[Length(DistList) - 1] := Sqrt(Sqr(TmpFigure.ap1.x) +Sqr(TmpFigure.ap1.y) +
                                             Sqr(TConnectorObject(TmpFigure).ActualZOrder[1]) );
        end;
        // sort by min dist (both array and List)
        SortAgain := True;
        DistArrayLength := Length(DistList);
        while SortAgain do
        begin
          SortAgain := false;
          for i := 0 to DistArrayLength - 2  do
          begin
            if DistList[i] > DistList[i + 1] then
            begin
              tmpValue := DistList[i];
              DistList[i] := DistList[i + 1];
              DistList[i + 1] := tmpValue;
              tmpFigure := TFigure(FiguresList[i]);
              FiguresList[i] := FiguresList[i+1];
              FiguresList[i+1] := tmpFigure;
              SortAgain := true;
            end;
          end;
        end;
      end;
      SetLength(DistList,0);

      SortFiguresCount := FiguresList.Count;
      PassedFiguresList := TList.Create;
      if TmpFiguresList = nil then
        TmpFiguresList := TList.Create;

      Counter := 0;
      //begin Figure
      TmpFigure := TFigure(FiguresList[0]);
      PassedFiguresList.Add(TFigure(TmpFigure));
      Inc(Counter);
      While Counter <> SortFiguresCount do
      begin
        TmpFigure := FindNearestFigure;
        if TmpFigure <> nil then
        begin
          PassedFiguresList.Add(TFigure(TmpFigure));
          Inc(Counter);
        end;
      end;
      // remark
      RemarkList(PassedFiguresList);
      SetLength(DistList,0);
      if not GProjectChanged then // Tolik 28/08/2019 --
        SetProjectChanged(True);
      if aCad <> nil then
        RefreshCad(aCad.PCad);
    end;
  End;

  Procedure RemarkSelectionByClock;
  Var i, BeginDirection: integer;
      aCad: TF_CAD;
      LeftPosition, RightPosition, TopPosition, BottomPosition: Double;
      FiguresCount: Integer;
      CenterX, CenterY: Double;
      LeftTopFigures, RightTopFigures, LeftDownFigures, RightDownFigures, PassedFiguresList: TList;
      ProcNames: MyPointerArray;
      ProcName: Pointer;
      CurrDirectionIndex: Integer;
      ProcList: TStringList;
  Begin
    if FiguresList.Count > 0 then
    begin
      // Variables Init
      FiguresCount := FiguresList.Count - 1;
      LeftPosition := 0;
      RightPosition := 0;
      TopPosition := 0;
      BottomPosition := 0;
      CenterX := 0;
      CenterY := 0;
      LeftTopFigures := TList.Create;
      RightTopFigures := TList.Create;
      LeftDownFigures := TList.Create;
      RightDownFigures := TList.Create;
      PassedFiguresList := TList.Create;
      ProcList := nil;
      // Define Positions
      Figure := TFigure(FiguresList[0]);
      LeftPosition := Figure.ap1.x;
      RightPosition := Figure.ap1.x;
      TopPosition := Figure.ap1.y;
      BottomPosition := Figure.ap1.y;

      for i := 1 to FiguresCount do
      begin
        Figure := TFigure(FiguresList[i]);
        if LeftPosition > Figure.ap1.x then
          LeftPosition := Figure.ap1.x;
        if RightPosition < Figure.ap1.x then
          RightPosition := Figure.ap1.x;
        if TopPosition < Figure.ap1.y then
          TopPosition := Figure.ap1.y;
        if BottomPosition > Figure.ap1.y then
          BottomPosition := Figure.ap1.y;
      end;
      // Define ReindexCoordCenter
      CenterX := (LeftPosition + RightPosition)/2;
      CenterY := (TopPosition + BottomPosition)/2;
      // Define Figures Lists by Kvadrants
      for i := 0 to FiguresCount do
      begin
        Figure := FiguresList[i];
        if PassedFiguresList.IndexOf(Figure) = -1 then
        begin
          if (Figure.ap1.x <= CenterX) and (Figure.ap1.y <= CenterY) then
            LeftTopFigures.Add(Figure)
          else
          if (Figure.ap1.x > CenterX) and (Figure.ap1.y < CenterY) then
            RightTopFigures.Add(Figure)
          else
          if (Figure.ap1.x > CenterX) and (Figure.ap1.y > CenterY) then
            RightDownFigures.Add(Figure)
          else
          if (Figure.ap1.x < CenterX) and (Figure.ap1.y > CenterY) then
            LeftDownFigures.Add(Figure);
          PassedFiguresList.Add(Figure);
        end;
      end;
      //Sorting not Empty Lists (by XY first)
      if LeftTopFigures.Count > 1 then
      begin
        // X
        SortAgain := True;
        while SortAgain do
        begin
          SortAgain := False;
          for i := 0 to LeftTopFigures.Count - 2 do
          begin
            Figure := TFigure(LeftTopFigures[i]);
            TmpFigure := TFigure(LeftTopFigures[i+1]);
            if (Figure.ap1.x > TmpFigure.ap1.x)  then
            begin
              LeftTopFigures[i] := TmpFigure;
              LeftTopFigures[i+1] := Figure;
              SortAgain := True;
              Break;
            end;
          end;
        end;
        // Y ( Down --> Up )
        SortAgain := True;
        while SortAgain do
        begin
          SortAgain := False;
          for i := 0 to LeftTopFigures.Count - 2 do
          begin
            Figure := TFigure(LeftTopFigures[i]);
            TmpFigure := TFigure(LeftTopFigures[i+1]);
            if Figure.ap1.x = TmpFigure.ap1.x then
            begin
              if (Figure.ap1.y < TmpFigure.ap1.y) then
              begin
                LeftTopFigures[i] := TmpFigure;
                LeftTopFigures[i+1] := Figure;
                SortAgain := True;
                Break;
              end;
            end;
          end;
        end;
        SortListByZCoord(LeftTopFigures);
      end;

      if RightTopFigures.Count > 1 then
      begin
        // Y
        SortAgain := True;
        while SortAgain do
        begin
          SortAgain := False;
          for i := 0 to RightTopFigures.Count - 2 do
          begin
            Figure := TFigure(RightTopFigures[i]);
            TmpFigure := TFigure(RightTopFigures[i+1]);
            if (Figure.ap1.x > TmpFigure.ap1.x) then
            begin
              RightTopFigures[i] := TmpFigure;
              RightTopFigures[i+1] := Figure;
              SortAgain := True;
              break;
            end;
          end;
        end;
        // X
        SortAgain := True;
        while SortAgain do
        begin
          SortAgain := False;
          for i := 0 to RightTopFigures.Count - 2 do
          begin
            Figure := TFigure(RightTopFigures[i]);
            TmpFigure := TFigure(RightTopFigures[i+1]);
            if (Figure.ap1.x = TmpFigure.ap1.x) then
            begin
              if (Figure.ap1.y > TmpFigure.ap1.y) then
              begin
                RightTopFigures[i] := TmpFigure;
                RightTopFigures[i+1] := Figure;
                SortAgain := True;
                break;
              end;
            end;
          end;
        end;
        SortListByZCoord(RightTopFigures);
      end;

      if RightDownFigures.Count > 1 then
      begin
        // X
        SortAgain := True;
        while SortAgain do
        begin
          SortAgain := False;
          for i := 0 to RightDownFigures.Count - 2 do
          begin
            Figure := TFigure(RightDownFigures[i]);
            TmpFigure := TFigure(RightDownFigures[i+1]);
            if (Figure.ap1.x < TmpFigure.ap1.x) then
            begin
              RightDownFigures[i] := TmpFigure;
              RightDownFigures[i+1] := Figure;
              SortAgain := True;
            end;
          end;
        end;
        // Y
        SortAgain := True;
        while SortAgain do
        begin
          SortAgain := False;
          for i := 0 to RightDownFigures.Count - 2 do
          begin
            Figure := TFigure(RightDownFigures[i]);
            TmpFigure := TFigure(RightDownFigures[i+1]);
            if (Figure.ap1.x = TmpFigure.ap1.x) then
            begin
              if (Figure.ap1.y > TmpFigure.ap1.y) then
              begin
                RightDownFigures[i] := TmpFigure;
                RightDownFigures[i+1] := Figure;
                SortAgain := True;
                break;
              end;
            end;
          end;
        end;
        SortListByZCoord(RightDownFigures);
      end;

      if LeftDownFigures.Count > 1 then
      begin
        SortAgain := True;
        while SortAgain do
        begin
          SortAgain := False;
          for i := 0 to LeftDownFigures.Count - 2 do
          begin
            Figure := TFigure(LeftDownFigures[i]);
            TmpFigure := TFigure(LeftDownFigures[i+1]);
            if (Figure.ap1.y < TmpFigure.ap1.y) then
            begin
              LeftDownFigures[i] := TmpFigure;
              LeftDownFigures[i+1] := Figure;
              SortAgain := True;
            end;
          end;
        end;
        // X
        SortAgain := True;
        while SortAgain do
        begin
          SortAgain := False;
          for i := 0 to LeftDownFigures.Count - 2 do
          begin
            Figure := TFigure(LeftDownFigures[i]);
            TmpFigure := TFigure(LeftDownFigures[i+1]);
            if (Figure.ap1.y = TmpFigure.ap1.y) then
            begin
              if (Figure.ap1.x < TmpFigure.ap1.x) then
              begin
                LeftDownFigures[i] := TmpFigure;
                LeftDownFigures[i+1] := Figure;
                SortAgain := True;
                break;
              end;
            end;
          end;
        end;
        SortListByZCoord(LeftDownFigures);
      end;

      ProcList := TStringList.Create;
      BeginDirection := BeginClockDirection.ItemIndex + 1;
      ProcNames[1] :=  Pointer(LeftTopFigures);
      ProcNames[2] :=  Pointer(RightTopFigures);
      ProcNames[3] :=  Pointer(RightDownFigures);
      ProcNames[4] :=  Pointer(LeftDownFigures);

      for i := 1 to 4 do
      begin
        if TList(ProcNames[BeginDirection]).Count > 0 then
          RemarkList(TList(ProcNames[BeginDirection]));
        Inc(BeginDirection);
        if BeginDirection > 4 then
          BeginDirection := 1;
      end;
      // Tolik 13/05/2019 --
      LeftTopFigures.Free;
      RightTopFigures.Free;
      LeftDownFigures.Free;
      RightDownFigures.Free;
      PassedFiguresList.Free;
      //
    end;
  End;
  // сортировка трасс по выбранному режиму индексации
  procedure SortLineFiguresByMode(var FiguresList: TList);
  var i: Integer;
      Figure: TFigure;
      x1, x2 : Double;
      SortAgain : Boolean;
      CanChange: Boolean;
  begin
    if FiguresList.Count > 1 then
    begin
      begin
        SortAgain := True;
        // Слева - направо (по оси Х)
        while SortAgain do
        begin
          SortAgain := False;
          for i := 0 to FiguresList.Count - 2 do
          begin
            // координата с/п на плоскости - по любому коннектору
            if TOrthoLine(FiguresList[i]).FIsRaiseUpDown then
              x1 := TConnectorObject(TOrthoLine(FiguresList[i]).JoinConnector1).ActualPoints[1].x
            else
              // координата трассы - по её средине
              x1 := (TConnectorObject(TOrthoLine(FiguresList[i]).JoinConnector1).ActualPoints[1].x + TConnectorObject(TOrthoLine(FiguresList[i]).JoinConnector2).ActualPoints[1].x)/2;

            if TOrthoLine(FiguresList[i + 1]).FIsRaiseUpDown then
              x2 := TConnectorObject(TOrthoLine(FiguresList[i + 1]).JoinConnector1).ActualPoints[1].x
            else
              x2 := (TConnectorObject(TOrthoLine(FiguresList[i + 1]).JoinConnector1).ActualPoints[1].x + TConnectorObject(TOrthoLine(FiguresList[i + 1]).JoinConnector2).ActualPoints[1].x)/2;
            if x1 > x2 then
            begin
              Figure := TFigure(FiguresList[i]);
              FiguresList[i] := FiguresList[i + 1];
              FiguresList[i + 1] := Figure;
              SortAgain := True;
            end;
          end;
        end;

        // сверху - вниз или снизу вверх (если "лево" - одинаковое, смотрим, кто выше по ОСИ У,
        // НО!! учитываем, что игрек идет сверху вниз - кто МЕНЬШЕ, тот ВЫШЕ)
        SortAgain := True;
        while SortAgain do
        begin
          SortAgain := False;
          CanChange := False;
          for i := 0 to FiguresList.Count - 2 do
          begin
            if TOrthoLine(FiguresList[i]).FIsRaiseUpDown then
              x1 := TConnectorObject(TOrthoLine(FiguresList[i]).JoinConnector1).ActualPoints[1].x
            else
              x1 := (TConnectorObject(TOrthoLine(FiguresList[i]).JoinConnector1).ActualPoints[1].x + TConnectorObject(TOrthoLine(FiguresList[i]).JoinConnector2).ActualPoints[1].x)/2;
            if TOrthoLine(FiguresList[i + 1]).FIsRaiseUpDown then
              x2 := TConnectorObject(TOrthoLine(FiguresList[i + 1]).JoinConnector1).ActualPoints[1].x
            else
              x2 := (TConnectorObject(TOrthoLine(FiguresList[i + 1]).JoinConnector1).ActualPoints[1].x + TConnectorObject(TOrthoLine(FiguresList[i + 1]).JoinConnector2).ActualPoints[1].x)/2;
            if x1 = x2 then
            begin
              //x1 := Min(TConnectorObject(TOrthoLine(FiguresList[i]).JoinConnector1).ActualPoints[1].y, TConnectorObject(TOrthoLine(FiguresList[i]).JoinConnector2).ActualPoints[1].y);
              //x2 := Min(TConnectorObject(TOrthoLine(FiguresList[i + 1]).JoinConnector1).ActualPoints[1].y, TConnectorObject(TOrthoLine(FiguresList[i + 1]).JoinConnector2).ActualPoints[1].y);
              if TOrthoLine(FiguresList[i]).FIsRaiseUpDown then
                x1 := TConnectorObject(TOrthoLine(FiguresList[i]).JoinConnector1).ActualPoints[1].y
              else
                x1 := (TConnectorObject(TOrthoLine(FiguresList[i]).JoinConnector1).ActualPoints[1].y + TConnectorObject(TOrthoLine(FiguresList[i]).JoinConnector2).ActualPoints[1].y)/2;
              if TOrthoLine(FiguresList[i + 1]).FIsRaiseUpDown then
                x2 := TConnectorObject(TOrthoLine(FiguresList[i + 1]).JoinConnector1).ActualPoints[1].y
              else
                x2 := (TConnectorObject(TOrthoLine(FiguresList[i + 1]).JoinConnector1).ActualPoints[1].y + TConnectorObject(TOrthoLine(FiguresList[i + 1]).JoinConnector2).ActualPoints[1].y)/2;
              if ((F_ReindexMaster.MarkDIrection_L.ItemIndex = 0) and (x1 > x2 )) then
                CanChange := True
              else
                if ((F_ReindexMaster.MarkDIrection_L.ItemIndex = 1) and (x1 < x2 )) then
                  CanChange := True;
              if CanChange then
              begin
                Figure := TFigure(FiguresList[i]);
                FiguresList[i] := FiguresList[i + 1];
                FiguresList[i + 1] := Figure;
                SortAgain := True;
              end;
            end;
          end;
        end;
      end;
    end;
  end;

  Procedure SortTracesbyCreationOrder;
  var i: Integer;
      currTrace: TSCSCatalog;
      SortAgain: Boolean;
  Begin
    if TracesList <> nil then
    begin
      if TracesList.Count > 1 then
      begin
        SortAgain := True;
        while SortAgain do
        begin
          SortAgain := False;
          for i := 0 to TracesList.Count - 2 do
          begin
            if TSCSCatalog(TracesList[i]).ID > TSCSCatalog(TracesList[i+1]).ID then
            begin
              if not SortAgain then
                SortAgain := True;
              currTrace := TSCSCatalog(TracesList[i]);
              TracesList[i] := TracesList[i+1];
              TracesList[i+1] := currTrace;
            end;
          end;
        end;
      end;
    end;
  End;

  procedure SortLineComponentsByReindex_Order(var LineComponList: TList);
  var i: Integer;
      currComponent: TSCScomponent;
      SortAgain: Boolean;

  begin
    if LineComponList <> nil then
    begin
      if LineComponList.Count > 1 then
      begin
        SortAgain := True;
        if F_ReindexMaster.Reindex_Order.ItemIndex = 0 then
        begin
          while SortAgain do
          begin
            SortAgain := False;
            for i := 0 to LineComponList.Count - 2 do
            begin
              if TSCSComponent(LineComponList[i]).ID > TSCSComponent(LineComponList[i + 1]).ID then
              begin
                SortAgain := True;
                currComponent := TSCSComponent(LineComponList[i]);
                LineComponList[i] := LineComponList[i + 1];
                LineComponList[i + 1] := currComponent;
              end;
            end;
          end;
        end
        else
          if  F_ReindexMaster.Reindex_Order.ItemIndex = 1 then
          begin
            while SortAgain do
            begin
              SortAgain := False;
              for i := 0 to LineComponList.Count - 2 do
              begin
                if TSCSComponent(LineComponList[i]).CompRelSortID > TSCSComponent(LineComponList[i + 1]).CompRelSortID then
                begin
                  SortAgain := True;
                  currComponent := TSCSComponent(LineComponList[i]);
                  LineComponList[i] := LineComponList[i + 1];
                  LineComponList[i + 1] := currComponent;
                end;
              end;
            end;
          end;
      end;
    end;
  end;




  // слева - направо, сверху - вниз (или снизу вверх)
  procedure RemarkLineSelection;
  var i, j, k, l, NewIndex: Integer;
      SCSComponent, PartCompon: TSCSComponent;
      WholeComponList: TSCSComponents;
      SCSCatalog: TSCSCatalog;
      CabinetList, PassedComponList, CurrComponList: TList;
      Cabinet: TSCSCatalog;
      Figure: TFigure;
      CurrFigList, TempComponList, CabinetComponList: TList;
      ComponentTypeList: TStringList;
      IndexCounterList: TIntList;

      procedure RemarkLineComponList(var ComponList, PassedComponList: TList; var counter: Integer; isCable: Boolean = false);
      var i, j: Integer;
          SCSComponent, PartCompon: TSCSComponent;
      begin
        if ComponList.Count > 0 then
        begin
          for i := 0 to ComponList.Count - 1 do
          begin
            SCSComponent := TSCSComponent(ComponList[i]);
            if PassedComponList.IndexOf(SCSComponent) = -1 then
            begin
              SCSComponent.MarkID := counter;
              Inc(counter);
              SCSComponent.SaveComponent;
              PassedComponList.Add(SCSComponent);
              ApplyChangeComponMarkID(SCSComponent, true, false, nil);
              if isCable then
              begin
                SCSComponent.LoadWholeComponent(false);
                for j := 0 to SCSComponent.WholeComponent.Count - 1 do
                begin
                  if SCSComponent.WholeComponent[j] <> SCSComponent.ID then
                  begin
                    PartCompon := TF_Main(F_ProjMan).GSCSBase.CurrProject.GetComponentFromReferences(SCSComponent.WholeComponent[j]);
                    if Assigned(PartCompon) then
                    begin
                      if PassedComponList.IndexOf(PartCompon)  = -1 then
                      begin
                        PartCompon.MarkID := SCSComponent.MarkID;
                        PartCompon.SaveComponent;
                        ApplyChangeComponMarkID(PartCompon, true, True, nil {WholeComponList});
                        PassedComponList.Add(PartCompon);
                      end;
                    end;
                  end;
                end;
              end;
            end;
          end;
        end;
      end;
  begin
    IndexCounterList := nil;
    ComponentTypeList := TStringList.Create;
    PassedComponList := TList.Create;
     // Компоненты одного каталога
    TempComponList := TList.Create;
    CurrIndex := StrToInt(F_ReindexMaster.BeginIndexNumL.Text);
    // Traces
    if TracesList.Count > 0 then
    begin
      for i := 0 to TracesList.Count - 1 do
      begin
        SCSCatalog := TSCSCatalog(TracesList[i]); //F_ProjMan.GSCSBase.CurrProject.CurrList.GetCatalogFromReferencesBySCSID(TOrthoLine(Figure).ID);
        if Assigned(SCSCatalog) then
        begin
          SCSCatalog.MarkID := CurrIndex;
          Inc(CurrIndex);
          SCSCatalog.Save;
          ReDefineObjectComponsNameMarks(SCSCatalog);
          if Assigned(SCSCatalog.TreeViewNode) then
            SCSCatalog.TreeViewNode.Text := SCSCatalog.GetNameForVisible(true);
        end;
      end;
    end;
    //Cables
    if CableList.Count > 0 then
    begin
      PassedComponList := TList.Create;
      TempComponList := TList.Create;
      //WholeComponList := TSCSComponents.Create(false);
      // если индексация по типам
      if F_ReindexMaster.ReindexByType.Checked then
      begin
        for i := 0 to CableList.Count - 1 do
        begin
          SCSComponent := TSCSComponent(CableList[i]);
          if ComponentTypeList.IndexOf(SCSComponent.ComponentType.GUID) = -1 then
            ComponentTypeList.Add(SCSComponent.ComponentType.GUID);
        end;
        if ComponentTypeList.Count > 0 then
        begin
          //индексим по типам кабеля
          for i := 0 to ComponentTypeList.Count - 1 do
          begin
            //сброс начального индекса в заданное значение
            CurrIndex := StrToInt(F_ReindexMaster.BeginIndexNumL.Text);
            for j := 0 to CableList.Count - 1 do
            begin
              SCSComponent := CableList[j];
              if PassedComponList.IndexOf(SCSComponent) = -1 then
              begin
                SCSCatalog := SCSComponent.GetFirstParentCatalog;
                if SCSCatalog <> nil then
                begin
                  TempComponList.Clear;
                  // отбираем все кабели на текущей трассе (по текущему имени множественного числа)
                  for k := 0 to SCSCatalog.ComponentReferences.Count - 1 do
                  begin
                    if TSCSComponent(SCSCatalog.ComponentReferences[k]).ComponentType.GUID = ComponentTypeList[i] then
                      TempComponList.Add(TSCSComponent(SCSCatalog.ComponentReferences[k]));
                  end;
                  // сортируем в зависимости от порядка индексации
                  if TempComponList.Count > 1 then
                    SortLineComponentsByReindex_Order(TempComponList);

                  RemarkLineComponList(TempComponList, PassedComponList, CurrIndex, True);
                end;
              end;
            end;
          end;
        end;
      end
      else
      begin
        // индексация сквозная (не по типам, весь кабель подряд)
        for i := 0 to CableList.Count - 1 do
        begin
          SCSComponent := TSCSComponent(CableList[i]);
          if PassedComponList.IndexOf(SCScomponent) = -1 then
          begin
            SCSCatalog := SCSComponent.GetFirstParentCatalog;
            if SCSCatalog <> nil then
            begin
              TempComponList.Clear;
              // все кабели трассы, попавшие в список
              for j := 0 to SCSCatalog.ComponentReferences.Count - 1 do
              begin
                SCSComponent := TSCSComponent(SCSCatalog.ComponentReferences[j]);
                if CableList.IndexOf(SCSComponent) <> -1 then
                TempComponList.Add(SCSComponent);
              end;
              // сортанем согласно порядка сортировки (либо по МП либо в порядке создания)
              if TempComponList.Count > 1 then
                SortLineComponentsByReindex_Order(TempComponList);
              RemarkLineComponList(TempComponList, PassedComponList, CurrIndex, True);
            end;
          end;
        end;
        if TempComponList <> nil then
          FreeAndNil(TempComponList);
      end;
    end;
    //Cable Channels
    if ChannelList.Count > 0 then
    begin
      CabinetList := nil;
      //PassedComponList := nil;
      CurrComponList := nil;
      CurrFigList := nil; // фигуры кабинета
      TempComponList := TList.Create; // компоненты одного каталога
      CabinetComponList := nil; // компоненты одного кабинета (отсортированные)
      if ComponentTypeList.Count > 0 then
        ComponentTypeList.Clear;
      if PassedComponList.Count > 0 then
        PassedComponList.Clear;
      // Список кабинетов
      CabinetList := TList.Create;
      if  F_ReindexMaster.IndexChannelByKabinet.Checked then
      begin
        for i := 0 to ChannelList.Count - 1 do
        begin
          SCSComponent := TSCSComponent(ChannelList[i]);
          SCSCatalog := SCSComponent.GetFirstParentCatalog;
          Cabinet := SCSCatalog.GetParentCatalogByItemType(itRoom);
          if Cabinet <> nil then
          begin
            if CabinetList.IndexOf(Cabinet) = -1 then
              CabinetList.Add(Cabinet)
          end;
        end;
      end;
      // Если индексировать по типам - Определяем список типов Ложемента (трубы,гофры и т.п., всего, что "не кабель")
      if F_ReindexMaster.ReindexByType.Checked then
      begin
        for i := 0 to ChannelList.Count - 1 do
        begin
          if ComponentTypeList.IndexOf(TSCSComponent(ChannelList[i]).ComponentType.GUID) = -1 then
            ComponentTypeList.Add(TSCSComponent(ChannelList[i]).ComponentType.GUID);
        end;
        // Если индексировать кабканал по кабинетам, и  по типам, то
        // строим список порядковых индексов для каждого типа каб канала
        if (F_ReindexMaster.IndexChannelByKabinet.Checked and F_ReindexMaster.ReindexByType.Checked) then
        begin
          IndexCounterList := TIntList.Create;
          for i := 0 to ComponentTypeList.Count - 1 do
            IndexCounterList.Add(StrToInt(F_ReindexMaster.BeginIndexNumL.Text));
        end;
      end;

      // Если не по кабинетам или кабинетов совсем нет (кроме виртуального) - тогда тотальный реиндекс согласно
      // порядку сортировки трасс и порядку индексации компонент
      if (not F_ReindexMaster.IndexChannelByKabinet.Checked) or (CabinetList.Count = 0) then
      begin
        // индексация по типам
        if F_ReindexMaster.ReindexByType.Checked then
        begin
          for j := 0 to ComponentTypeList.Count - 1 do
          begin
            // сбрасываем счетчик для каждого типа компонент
            CurrIndex := StrToInt(F_ReindexMaster.BeginIndexNumL.Text);
            for i := 0 to ChannelList.Count - 1 do
            begin
              SCSComponent := TSCSComponent(ChannelList[i]);
              if SCSComponent.ComponentType.GUID = ComponentTypeList[j] then
              begin
                if PassedComponList.IndexOf(SCSComponent) = -1 then
                begin
                  SCSCatalog := SCSComponent.GetFirstParentCatalog;
                  if SCSCatalog <> nil then
                  begin
                    if TempComponList.Count > 0 then
                      TempComponList.Clear;
                    // собираем из каталога компоненты текущего типа по списку
                    for k := 0 to SCSCatalog.ComponentReferences.Count - 1 do
                    begin
                      SCSComponent := SCSCatalog.ComponentReferences[k];
                      if ((SCSComponent.ComponentType.GUID = ComponentTypeList[j]) and
                          (PassedComponList.IndexOf(SCSComponent)= -1)) then
                       TempComponList.Add(SCSComponent);
                    end;
                    // сортировка
                    if TempComponList.Count > 1 then
                      SortLineComponentsByReindex_Order(TempComponList);
                     // переиндексация (все, что попалось на трассе заданного типа)
                    RemarkLineComponList(TempComponList, PassedComponList, CurrIndex);
                  end;
                end;
              end;
            end;
          end;
        end
        else
        // индексация сквозная
        begin
          for i := 0 to ChannelList.Count - 1 do
          begin
            SCSComponent := TSCSComponent(ChannelList[i]);
            if PassedComponList.IndexOf(SCSComponent)  = -1 then
            begin
              SCSCatalog := SCSComponent.GetFirstParentCatalog;
              if SCSCatalog <> nil then
              begin
                if TempComponList.Count > 0 then
                  TempComponList.Clear;
                for j := 0 to SCSCatalog.ComponentReferences.Count - 1 do
                begin
                  SCSComponent := SCSCatalog.ComponentReferences[j];
                  if ((PassedComponList.IndexOf(SCSComponent) = -1) and (ChannelList.IndexOf(SCSComponent) <> - 1)) then
                    TempComponList.Add(SCSComponent);
                end;
                // сортанем
                if TempComponList.Count > 1 then
                  SortLineComponentsByReindex_Order(TempComponList);
                // перемаркируем (индексируем)
                RemarkLineComponList(TempComponList, PassedComponList, CurrIndex);
              end;
            end;
          end;
        end;
      end
      else
      // Индексировать по кабинетам
      begin
        // если что-то из выбранного попало в кабинеты,
        // индексируем по кабинетам
        if CabinetList.Count > 0 then
        begin
          // Компоненты текущего кабинета
          CurrComponList := TList.Create;
          // Список фигур кабинета
          CurrFigList := TList.Create;
          // компоненты одного кабинета(отсортированные)
          CabinetComponList := TList.Create;
          // Строим список для индескации
          for i := 0 to CabinetList.Count - 1 do
          begin
            // кабинет
            Cabinet := TSCSCatalog(CabinetList[i]);
            // список компонент кабинета (из выбранных, если попали), сбрасываем - будем строить
            if CurrComponList.Count > 0 then
              CurrComponList.Clear;
            for j := 0 to ChannelList.Count - 1 do
            begin
              SCSComponent := TSCSComponent(ChannelList[j]);
              SCSCatalog := SCSComponent.GetFirstParentCatalog;
              if SCSCatalog <> nil then
              begin
                SCSCatalog := SCSCatalog.GetParentCatalogByItemType(itRoom);
                if SCSCatalog <> nil then
                begin
                  if SCSCatalog.ID = Cabinet.ID then
                  begin
                    CurrComponList.Add(SCSComponent);
                  end;
                end;
              end;
            end;
            // что-то попало в кабинет, сортируем список по параметрам индексации
            if CurrComponList.Count > 0 then
            begin
              if CurrFigList.Count > 0 then
                CurrFigList.Clear;
              if CabinetComponList.Count > 0 then
                CabinetComponList.Clear;
              // строим список фигур
              for j := 0 to CurrComponList.Count - 1 do
              begin
                SCSComponent := TSCSComponent(CurrComponList[j]);
                SCSCatalog := SCSComponent.GetFirstParentCatalog;
                if SCSCatalog <> nil then
                begin
                  for k := 0 to FiguresList.Count - 1 do
                  begin
                    if SCSCatalog.SCSID = TFigure(FiguresList[k]).ID then
                    begin
                      if currFigList.IndexOf(FiguresList[k]) = -1 then
                      begin
                        CurrFigList.Add(FiguresList[k]);
                        break;
                      end;
                    end;
                  end;
                end;
              end;
              // если есть фигуры в кабинете
              if CurrFigList.Count > 0 then
              begin
                // сортируем фигуры
                SortLineFiguresByMode(currFigList);
                // строим список компонент, согласно расположению фигур
                if CabinetComponList.Count > 0 then
                  CabinetComponList.Clear;
                for j := 0 to CurrFigList.Count - 1 do
                begin
                  Figure := TFigure(CurrFigList[j]);
                  SCSCatalog := F_ProjMan.GSCSBase.CurrProject.CurrList.GetCatalogFromReferencesBySCSID(Figure.ID);
                  if SCSCatalog <> nil then
                  begin
                    for k := 0 to SCSCatalog.ComponentReferences.Count - 1 do
                    begin
                      SCSComponent := SCSCatalog.ComponentReferences[k];
                      if SCSComponent.IsLine = biTrue then
                      begin
                        if CurrComponList.IndexOf(SCSComponent) <> -1 then
                          CabinetComponList.Add(SCSComponent);
                      end;
                    end;
                  end;
                end;
              end;
            end;
            if CabinetComponList.Count > 0 then
            begin
              // если сбрасывать счетчик - сбрасываем счетчик (индекс)
              if (F_ReindexMaster.DropIndexCounter.Enabled and (not F_ReindexMaster.DropIndexCounter.Checked)) then
                CurrIndex := StrToInt(F_ReindexMaster.BeginIndexNumL.Text);

              //если индексировать по типам
              if F_ReindexMaster.ReindexByType.Checked then
              begin
                if (F_ReindexMaster.DropIndexCounter.Enabled and (not F_ReindexMaster.DropIndexCounter.Checked)) then
                for l := 0 to IndexCounterList.Count - 1 do
                  IndexCounterList[l] := StrToInt(F_ReindexMaster.BeginIndexNumL.Text);
                for l := 0 to ComponentTypeList.Count - 1 do
                begin
                  //if (F_ReindexMaster.DropIndexCounter.Enabled and F_ReindexMaster.DropIndexCounter.Checked) then
                  CurrIndex := IndexCounterList[l];
                  for j := 0 to CabinetComponList.Count - 1 do
                  begin
                    SCSComponent := TSCSComponent(CabinetComponList[j]);
                    if ((PassedComponList.IndexOf(SCSComponent) = -1) and (SCSComponent.ComponentType.Guid = ComponentTypeList[l])) then
                    begin
                      SCSCatalog := SCSComponent.GetFirstParentCatalog;
                      if SCSCatalog <> nil then
                      begin
                        if TempComponList.Count > 0 then
                        TempComponList.Clear;
                        for k := 0 to SCSCatalog.ComponentReferences.Count - 1 do
                        begin
                          SCSComponent := SCSCatalog.ComponentReferences[k];
                          if ((PassedComponList.IndexOf(SCSComponent) = -1) and (SCSComponent.ComponentType.Guid = ComponentTypeList[l])) then
                            TempComponList.Add(SCSComponent);
                        end;
                        // сортировка
                        if TempComponList.Count > 1 then
                          SortLineComponentsByReindex_Order(TempComponList);

                        RemarkLineComponList(TempComponList, PassedComponList, CurrIndex);
                      end;
                    end;
                  end;
                  if (F_ReindexMaster.DropIndexCounter.Enabled and F_ReindexMaster.DropIndexCounter.Checked) then
                    IndexCounterList[l] := CurrIndex;
                end;
              end
              else
              //индексация покабинетная сквозная
              begin
                // если сбрасывать счетчик - сбрасываем счетчик (индекс)
                if (F_ReindexMaster.DropIndexCounter.Enabled and (not F_ReindexMaster.DropIndexCounter.Checked)) then
                  CurrIndex := StrToInt(F_ReindexMaster.BeginIndexNumL.Text);
                for j := 0 to CabinetComponList.Count - 1 do
                begin
                  SCSComponent := TSCSComponent(CabinetComponList[j]);
                  if (PassedComponList.IndexOf(SCSComponent) = -1) then
                  begin
                    SCSCatalog := SCSComponent.GetFirstParentCatalog;
                    if SCSCatalog <> nil then
                    begin
                      if TempComponList.Count > 0 then
                      TempComponList.Clear;
                      for k := 0 to SCSCatalog.ComponentReferences.Count - 1 do
                      begin
                        SCSComponent := SCSCatalog.ComponentReferences[k];
                        if ((PassedComponList.IndexOf(SCSComponent) = -1) and (CabinetComponList.IndexOf(SCSComponent) <> -1)) then
                          TempComponList.Add(SCSComponent);
                      end;
                      // сортировка
                      if TempComponList.Count > 1 then
                        SortLineComponentsByReindex_Order(TempComponList);

                      RemarkLineComponList(TempComponList, PassedComponList, CurrIndex);
                    end;
                  end;
                end;
              end;
            end;
          end;
          if PassedComponList.Count < ChannelList.Count then
          begin
            // все остальные, что просто лежат на листе, и не попадают ни в один кабинет

            //если индексация сквозная
            if not F_ReindexMaster.ReindexByType.Checked then
            begin
              // если сбрасывать счетчик - сбрасываем
              if (F_ReindexMaster.DropIndexCounter.Enabled and (not F_ReindexMaster.DropIndexCounter.Checked)) then
                    CurrIndex := StrToInt(F_ReindexMaster.BeginIndexNumL.Text);
              for j := 0 to ChannelList.Count - 1 do
              begin
                SCSComponent := TSCSComponent(ChannelList[j]);
                if PassedComponList.IndexOf(SCSComponent) = -1 then
                begin
                  SCSCatalog := SCSComponent.GetFirstParentCatalog;
                  if SCSCatalog <> nil then
                  begin
                    if TempComponList.Count > 0 then
                      TempComponList.Clear;
                    for k := 0 to SCSCatalog.ComponentReferences.Count - 1 do
                    begin
                      SCSComponent := TSCSComponent(SCSCatalog.ComponentReferences[k]);
                      if ((PassedComponList.IndexOf(SCSComponent) = -1) and (ChannelList.IndexOf(SCSComponent) <> - 1)) then
                        TempComponList.Add(SCSComponent);
                    end;
                    if TempComponList.Count > 1 then
                      SortLineComponentsByReindex_Order(TempComponList);

                    RemarkLineComponList(TempComponList, PassedComponList, CurrIndex);
                  end;
                end;
              end;
            end
            else
            // индексировать по типам
            begin
              // если индексировать по типам и сбрасывать счетчик, то сбросить все счетчики для типов компонент
              if F_ReindexMaster.ReindexByType.Checked and  (F_ReindexMaster.DropIndexCounter.Enabled) and
                 (not F_ReindexMaster.DropIndexCounter.Checked) then
              begin
                for j := 0 to IndexCounterList.Count - 1 do
                  IndexCounterList[j] := StrToInt(F_ReindexMaster.BeginIndexNumL.Text);
              end;
              for l := 0 to ComponentTypeList.Count - 1 do
              begin
                // если индексировать по типам, юзаем счетчик по заданному типу компонент
                if (F_ReindexMaster.ReindexByType.Checked) then
                  CurrIndex := IndexCounterList[l];

                for j := 0 to ChannelList.Count - 1 do
                begin
                  SCSComponent := TSCSComponent(ChannelList[j]);
                  if (PassedComponList.IndexOf(SCSComponent) = -1) and (SCSComponent.ComponentType.Guid = ComponentTypeList[l])  then
                  begin
                    SCSCatalog := SCSComponent.GetFirstParentCatalog;
                    if SCSCatalog <> nil then
                    begin
                      if TempComponList.Count > 0 then
                        TempComponList.Clear;
                      for k := 0 to SCSCatalog.ComponentReferences.Count - 1 do
                      begin
                        SCSComponent := TSCSComponent(SCSCatalog.ComponentReferences[k]);
                        if (PassedComponList.IndexOf(SCSComponent) = -1) and (ChannelList.IndexOf(SCSComponent) <> - 1) and
                            (SCSComponent.ComponentType.GUID = ComponentTypeList[l]) then
                          TempComponList.Add(SCSComponent);
                      end;
                      if TempComponList.Count > 1 then
                        SortLineComponentsByReindex_Order(TempComponList);

                      RemarkLineComponList(TempComponList, PassedComponList, CurrIndex);
                    end;
                  end;
                end;
              end;
            end;
          end;
        end;

        if CabinetList <> nil then
          FreeAndNil(CabinetList);
        if PassedComponList <> nil then
          FreeAndNil(PassedComponList);
        if CurrComponList <> nil then
          FreeAndNil(CurrComponList);
        if CurrFigList <> nil then
          FreeAndNil(CurrFigList);
        if TempComponList <> nil then
          FreeAndNil(TempComponList);
        if CabinetComponList <> nil then
          FreeAndNil(CabinetComponList);
        if ComponentTypeList <> nil then
          FreeAndNil(ComponentTypeList);
        if IndexCounterList <> nil then
          FreeAndNil(IndexCounterList);  
      end;
    end;

  end;


  Procedure ReMarkComponentsBySelectedMode(ReMarkMode: String);
  Begin
    if PointObjectsReindex.Checked then
    begin
      // for point Objects Only
      if ReMarkMode = 'Mark_byCreationOrder' then
        Mark_byCreationOrder
      else
      if ReMarkMode = 'Mark_byPMOrder' then
        Mark_byPMOrder
      else
      if ReMarkMode = 'Mark_HL' then
        RemarkSelectionHL
      else
      if ReMarkMode = 'Mark_LH' then
        RemarkSelectionLH
      else
      if ReMarkMode = 'Mark_ByNearest' then
        RemarkSelectionByNearest
      else
      if ReMarkMode = 'Mark_ByClock' then
        RemarkSelectionByClock;
    end
    else
      // for Objects (or components) Only
      if LineObjectsReindex.Checked then
      begin
          RemarkLineSelection;
      end;
  End;
  Procedure Define_Selected_Types(var ComponTypes: TStringList);
  var i: Integer;
  Begin
    // Define Selected Types (in Tree)
    if ComponTypes = nil then
      ComponTypes := TStringList.Create
    else
      ComponTypes.Clear;
    for i := 0 to ComponTypeTree.Items.Count - 1 do
    begin
      Node := ComponTypeTree.Items[i];
      if Node.AbsoluteIndex <> 0 then
      begin
        if ComponTypeTree.ItemState[Node.AbsoluteIndex] = csChecked then
          ComponTypes.Add(Node.Text);
      end;
    end;
  End;

  Procedure RemarkPointsByList;
  Var i,j,k : integer;
      RemarkMode: string;

  Begin
    RemarkMode := '';
   // ComponentIndexList := nil;
    currIndex := StrToInt(BeginIndexNum.Text);

    if BeginComponIndexNum.Enabled then
      CurrComponIndex := StrToInt(BeginComponIndexNum.Text)
    else
      CurrComponIndex := 1;

    // Define Remark Mode
    if FiguresList.Count > 0 then
    begin
      for j := 0 to MarkDirection.Items.Count - 1 do
      begin
        if MarkDirection.Buttons[j].Checked then
        begin
          ReMarkMode := MarkDirection.Buttons[j].Name;
          Break;
        end;
      end;
    end;
    // Init ComponTypes Indexes Arrays
    if ComponTypes.Count > 0 then
    begin
      SetLength(IndexList, 0);
      j := 0;
      for i := 0 to ComponTypes.Count - 1 do
      begin
        SetLength(IndexList, j + 1);
        IndexList[j] := StrToInt(BeginIndexNum.Text);
        Inc(j);
      end;
    end;
    if ReindexByType.Checked and BeginComponIndexNum.Enabled then
    begin
      SetLength(ComponentIndexList, 0);
      j := 0;
      for i := 0 to ComponTypes.Count - 1 do
      begin
        SetLength(ComponentIndexList, j + 1);
        ComponentIndexList[j] := StrToInt(BeginComponIndexNum.Text);
        Inc(j);
      end;
    end;

    if ReindexOnCabinets.Checked then
    begin
      // Define Cabinets List
      if CabinetList = nil then
        CabinetList := TList.Create
      else
        CabinetList.Clear;
      CabinetList.Add(GetVirtualCabinet);// Virtual Cabinet(ALL the Page) as First Cabinet

      for i := 0 to FiguresList.Count - 1 do
      begin
        Figure := TFigure(FiguresList[i]);
        // Figure in PM (Catalog)
        SCSCatalog := F_ProjMan.GSCSBase.CurrProject.CurrList.GetCatalogFromReferencesBySCSID(Figure.ID);
        if SCSCatalog <> nil then
        begin
          begin
            Cabinet := Nil;
            // Cabinet
            Cabinet := SCSCatalog.GetParentCatalogByItemType(itRoom);
            if Cabinet <> nil then
            begin
              if CabinetList.IndexOf(Cabinet) = -1 then
                CabinetList.Add(Cabinet);
            end;
          end;
        end;
      end;
      if CabinetList.Count > 1 then
      begin
        // Sort CabinetList by CabinetNumber (CabinetNumber = Cabinet.MarkID)
        if CabinetList.Count > 2 then
        begin
          sortAgain := true;
          while sortAgain do
          begin
            SortAgain := False;
            for i := 1 to CabinetList.Count - 2 do
            begin
              if TSCSCatalog(CabinetList[i]).MarkID > TSCSCatalog(CabinetList[i+1]).MarkID then
              begin
                SortAgain := True;
                Cabinet := TSCSCatalog(CabinetList[i]);
                CabinetList[i] := CabinetList[i+1];
                CabinetList[i+1] := Cabinet;
              end;
            end;
          end;
        end;
        // Remark By Cabinets
        // Invirtual Cabinet First
        FiguresList.Clear;
        for j := 0 to aCad.PCad.Selection.Count - 1 do
        begin
          Figure := TFigure(aCad.PCad.Selection[j]);
          if Figure <> nil then
          begin
            SCSCatalog := F_ProjMan.GSCSBase.CurrProject.CurrList.GetCatalogFromReferencesBySCSID(Figure.ID);
            if SCSCatalog <> nil then
            begin
              Cabinet := SCSCatalog.GetParentCatalogByItemType(itRoom);
              if Cabinet = nil then
                FiguresList.Add(Figure);
            end;
          end;
        end;
        if FiguresList.Count > 0 then
          ReMarkComponentsBySelectedMode(RemarkMode);

        for i := 1 to CabinetList.Count - 1 do
        begin
          FiguresList.Clear;
          Cabinet := TSCSCatalog(CabinetList[i]);
          // Drop Counters
          if (DropIndexCounter.Enabled and not DropIndexCounter.Checked) then
          begin
            currIndex := StrToInt(BeginIndexNum.Text);
            if BeginComponIndexNum.Enabled then
            begin
              currComponIndex := StrToInt(BeginComponIndexNum.Text);
              for j := 0 to Length(ComponentIndexList) - 1 do
              begin
                ComponentIndexList[j] := StrToInt(BeginComponIndexNum.Text);
              end;
            end;
            for j := 0 to Length(IndexList) - 1  do
            begin
              IndexList[j] := StrToInt(BeginIndexNum.Text);
            end;
          end;
          for j := 0 to aCad.PCad.Selection.Count - 1 do
          begin
            Figure := TFigure(aCad.PCad.Selection[j]);
            if Figure <> nil then
            begin
              SCSCatalog := F_ProjMan.GSCSBase.CurrProject.CurrList.GetCatalogFromReferencesBySCSID(Figure.ID);
              if SCSCatalog <> nil then
              begin
                currCabinet := SCSCatalog.GetParentCatalogByItemType(itRoom);
                if Cabinet = currCabinet then
                  FiguresList.Add(Figure);
              end;
            end;
          end;
          if FiguresList.Count > 0 then
          begin
            if ReindexByType.Checked and (not DropIndexCounter.Checked) then
            begin
              DropTypeCounters(IndexList, True);
              currIndex := StrToInt(BeginIndexNum.Text);
              if BeginComponIndexNum.Enabled then
                CurrComponIndex := StrToInt(BeginComponIndexNum.Text)
              else
                CurrComponIndex := 1;
            end;
            ReMarkComponentsBySelectedMode(RemarkMode);
          end;
        end;
      end
      else
        ReMarkComponentsBySelectedMode(RemarkMode);
    end
    else
      ReMarkComponentsBySelectedMode(RemarkMode);
  End;
  // Line Selection ======================================================================
  Procedure RemarkLinesByList;
  Var i: Integer;
      RemarkMode: string;

    procedure GetLinesBySelection;
    var i, j, k: Integer;
        SCSCatalog: TSCSCatalog;
        SCSComponent: TSCSComponent;
        SelectTraces, SelectRaises: Boolean;
        TempCableList, TempChannelList: TList;
        SortAgain: Boolean;
    begin
      try
        if ComponTypeTree.Items.Count > 0 then
        begin
          TempCableList := TList.Create;
          TempChannelList := TList.Create;
          SelectTraces := False;
          SelectRaises := False;
          if (F_ReindexMaster.CheckRaises.Visible and F_ReindexMaster.CheckRaises.Checked) then
            SelectRaises := True;
          if ComponTypes.IndexOf(cForm3D_Mes8_2)  <> -1 then
            SelectTraces := True;
          for i := 0 to FiguresList.Count - 1 do
          begin
            Figure := nil;
            Figure := TFigure(FiguresList[i]);
            if Figure <> nil then
            begin
              TraceFigures.Add(Figure); //
              SCSCatalog := nil;
              SCSCatalog := F_ProjMan.GSCSBase.CurrProject.CurrList.GetCatalogFromReferencesBySCSID(Figure.ID);
              if SCSCatalog <> nil then
              begin
                if SCSCatalog.IsLine = biTrue then // Trace or RaiseUpDown
                begin
                  if F_ReindexMaster.ReindexOnObj.Checked then
                  begin
                    if (TOrthoLine(Figure).FIsRaiseUpDown and SelectRaises) or ((not (TOrthoLine(Figure).FIsRaiseUpDown)) and SelectTraces) then
                      TracesList.Add(SCSCatalog); // Trace To List
                  end;
                  TempCableList.Clear;
                  TempChannelList.Clear;
                  if not ReindexOnObj.Checked then
                  begin
                    for j := 0 to SCSCatalog.ComponentReferences.Count - 1 do
                    begin
                      SCSComponent := nil;
                      SCSComponent := SCSCatalog.ComponentReferences[j]; // Cable or CableChannel
                      if SCSComponent <> nil then
                      begin
                        if SCSComponent.IsLine = biTrue then
                        begin
                          //Cable
                          if IsCableComponent(SCSComponent) then
                          begin
                            if ComponTypes.IndexOf(SCSComponent.ComponentType.NamePlural) <> -1 then
                            begin
                              if not IndexOnlyHigh.Checked then
                                TempCableList.Add(SCSComponent)
                              else
                              begin
                                if SCSComponent.IsTop then
                                  TempCableList.Add(SCSComponent);
                              end;
                            end;
                          end
                          else
                          //CableChannel
                          begin
                            if ComponTypes.IndexOf(SCSComponent.ComponentType.NamePlural) <> -1 then
                            begin
                              if not IndexOnlyHigh.Checked then
                                TempChannelList.Add(SCSComponent)
                              else
                              begin
                                if SCSComponent.IsTop then
                                  TempChannelList.Add(SCSComponent);
                              end;
                            end;
                          end;
                        end;
                      end;
                    end;
                    // Sort Lists By ReindexOnObj Order
                    SortLineComponentsByReindex_Order(TempCableList);
                    SortLineComponentsByReindex_Order(TempChannelList);
                    // add to CableList from Catalog
                    if TempCableList.Count > 0 then
                    begin
                      for j := 0 to TempCableList.Count - 1 do
                      begin
                        CableList.Add(TempCableList[j]);
                      end;
                    end;
                    // Add CableChannel from Catalog
                    if TempChannelList.Count > 0 then
                    begin
                      for j := 0 to TempChannelList.Count - 1 do
                      begin
                        ChannelList.Add(TempChannelList[j]);
                      end;
                    end;
                  end;
                end;
              end;
            end;
          end;
          // Delete Cables From List duplicated by Whole_ID
          if CableList.Count > 1 then
          begin
            j := 0;
            while j < CableList.Count do
            begin
              SCSComponent := TSCSComponent(CableList[j]);
              Inc(j);
              for i := (CableList.Count - 1) downto j do
              begin
                if TSCSComponent(CableList[i]).Whole_ID = SCSComponent.Whole_ID then
                  CableList.Delete(i);
              end;
            end;
          end;
        end;
      finally
        if TempCableList <> nil then
          FreeAndNil(TempCableList);
        if TempChannelList <> nil then
          FreeAndNil(TempChannelList);
      end;
    end;

  Begin
    if FiguresList.Count > 0 then
    begin
    {  TracesList, CableList, ChannelList: TList; // трассы, кабели, каб каналы
      CableNames, ChannelNames: TList; // трассы, кабели, каб каналы (NamePlural Lists) на всякий, а вдруг не совпадет где-нибудь}

      TracesList := TList.Create;
      CableList := TList.Create;
      ChannelList := TList.Create;
      TraceFigures := TList.Create;
      // Get remark Mode
      RemarkMode := '';
      if FiguresList.Count > 0 then
      begin
        for i := 0 to MarkDIrection_L.Items.Count - 1 do
        begin
          if MarkDIrection_L.Buttons[i].Checked then
          begin
            ReMarkMode := MarkDIrection_L.Buttons[i].Name;
            Break;
          end;
        end;
      end;

      SortLineFiguresByMode(FiguresList);
      GetLinesBySelection;
      ReMarkComponentsBySelectedMode(RemarkMode);
      //Toilk 13/05/2019 --
      TracesList.Free;
      CableList.Free;
      ChannelList.Free;
      TraceFigures.Free;
      //
    end;
    F_ReindexMaster.Close;
  End;

Begin
  // Если вдруг компонент для индексации нет - типы не определены, то - нах
  if not F_ReindexMaster.ComponTypeTree.Enabled then
    Exit;
  try
    try
      ActLayer := GCadForm.PCad.ActiveLayer;
      //ComponTypes := Nil; // Component Type List Selected on ComponTypeTree
      Define_Selected_Types(ComponTypes); // Check Tree Selection
      if ComponTypes.Count = 0 then
      // If No Component Types Selected - EXIT;
      EXIT;

      aCad := Nil;
      //FiguresList := Nil;
      CurrCheckType := '';
      CabinetList := Nil;
      TempList := TList.Create;
      TmpFiguresList := nil;
      //For Line Objects
      TracesList := nil; // traces
      CableList := nil; // cables
      ChannelList := nil; // cable Channels and other (pipes, cottugated pipes, tubes ect. )
      TraceFigures := nil;

      currIndex := StrToInt(BeginIndexNum.Text);
      //IndexList := Nil;
      //CheckTreeList := TStringList.Create;
      IndexNum := StrToInt(BeginIndexNum.Text);
      aCad := GetListByID(F_ProjMan.GSCSBase.CurrProject.CurrList.SCSID);
      if aCad <> Nil then
      begin
        if aCad.PCad.Selection.Count > 0 then
        begin
          //F_ReindexMaster.Hide;
          //Undo
          if GCadForm.FCanSaveForUndo then
            GCadForm.SaveForUndo(uat_None, True, False, 0);
          FiguresList := TList.Create;
          //TempList := TList.Create;

          Try
            BeginProgress;
            if PointObjectsReindex.Checked then
            begin
              DefinePointFigures;
              // Point Objects Reindex
              if FiguresList.Count > 0 then
                RemarkPointsByList;
            end
            else
            // Line Objects Reindex
            if LineObjectsReindex.Checked then
            begin
              DefineLineFigures;
              Define_Selected_Types(ComponTypes); 
              if FiguresList.Count > 0 then
                RemarkLinesByList;
            end;
          Finally
            EndProgress;
            if FiguresList <> nil then
              FreeAndNil(FiguresList);
            if ComponTypes <> nil then
              FreeAndNil(ComponTypes);
            if TracesList <> nil then
              FreeAndNil(TracesList);
            if CableList <> nil then
              FreeAndNil(CableList);
            if ChannelList <> nil then
              FreeAndNil(ChannelList);
            if TraceFigures <> nil then
              FreeAndNil(TraceFigures);
            // Tolik 13/05/2019 -*-
            TempList.free;
            //
              aCad.PCad.DeselectAll(ActLayer);
              aCad.Pcad.Refresh;
          End;
        end;
      end;
    except
      on E: Exception do
      begin
        addExceptionToLogEx('ReindexMaster', E.Message);
        //aCad.PCad.Selection.Clear;
        if FiguresList <> nil then
          FreeAndNil(FiguresList);
        if ComponTypes <> nil then
          FreeAndNil(ComponTypes);
        if TracesList <> nil then
          FreeAndNil(TracesList);
        if CableList <> nil then
          FreeAndNil(CableList);
        if ChannelList <> nil then
          FreeAndNil(ChannelList);
        if TraceFigures <> nil then
          FreeAndNil(TraceFigures);
        // Tolik 13/05/2019 -*-
        TempList.free;
        //
        aCad.PCad.DeselectAll(ActLayer);
        aCad.Pcad.Refresh;
      end;
    end;
  finally
    close;
  end;
End;

Procedure TF_ReindexMaster.FormCreate(Sender: TObject);
Begin
  try
    // Tolik 01/11/2019 --
    BeginComponIndexNum.Min := 0;
    BeginComponIndexNum.Max := 0;
    BeginIndexNum.Min := 0;
    BeginIndexNum.Max := 0;
    BeginIndexNumL.Min := 0;
    BeginIndexNumL.Max := 0;
    //
    Caption := Reindex_Master_Caption;
    MarkDirection.Buttons[0].Name := 'Mark_byCreationOrder';
    MarkDirection.Buttons[1].Name := 'Mark_byPMOrder';
    MarkDirection.Buttons[2].Name := 'Mark_HL';
    MarkDirection.Buttons[3].Name := 'Mark_LH';
    MarkDirection.Buttons[4].Name := 'Mark_ByNearest';
    MarkDirection.Buttons[5].Name := 'Mark_ByClock';

   { MarkDirection_L.Buttons[0].Name := 'Mark_byCreationOrder';
    MarkDirection_L.Buttons[1].Name := 'Mark_byPMOrder';
    }
    MarkDirection_L.Buttons[0].Name := 'Mark_HL';
    MarkDirection_L.Buttons[1].Name := 'Mark_LH';
   { MarkDirection_L.Buttons[4].Name := 'Mark_ByNearest';
    MarkDirection_L.Buttons[5].Name := 'Mark_ByClock';
    MarkDirection_L.Buttons[4].Enabled := False;
    }

    Point_IndexType.Buttons[0].Name := 'onCommponent';
    Point_IndexType.Buttons[1].Name := 'onParent';
    Point_IndexType.Buttons[2].Name := 'onTop';

    Point_IndexType.Visible := True;
    Line_IndexType.Visible := False;

    MarkDirection.Buttons[0].Checked := True;
    Point_IndexType.Buttons[0].Checked := True;

    ComponTypeTree.Enabled := True;
    BeginClockDirection.ItemIndex := 0;
    CheckTreeList := TStringList.Create;
    Reindex_Order.Visible := False;

    BeginIndexNumL.Visible := False;
    MarkDirection_L.Visible := False;
    ComponTypes := nil;
    FiguresList := nil;
    //DefineCadSelectionIndexTypes('PointObj');
    ReindexOnCabinets.Hint := hReindexMaster_Msg1;
    IndexChannelByKabinet.Hint := hReindexMaster_Msg1;
  except
    on E: Exception do addExceptionToLogEx('On_Form_Create_ReindexMaster', E.Message);
  end;
End;

procedure TF_ReindexMaster.pClick(Sender: TObject);
begin
  if not PointObjectsReindex.Checked then
  begin
    MarkDirection.Enabled := false;
    LineObjectsReindex.Checked := True;
  end
  else
  begin
    LineObjectsReindex.Checked := False;
    MarkDirection.Enabled := True;
  end;
end;

procedure TF_ReindexMaster.lClick(Sender: TObject);
begin
  if not  LineObjectsReindex.Checked then
  begin
    PointObjectsReindex.Checked := True;
    MarkDirection.Enabled := True;
  end
  else
  begin
    PointObjectsReindex.Checked := False;
    MarkDirection.Enabled := False;
  end;
end;

procedure TF_ReindexMaster.wwwClick(Sender: TObject);
begin
  if ReindexByType.Checked then
    ReindexTotal.Checked := False
  else
    ReindexTotal.Checked := True;
end;

procedure TF_ReindexMaster.zfdClick(Sender: TObject);
begin
  ReindexTotal.Checked := not ReindexByType.Checked;
end;

procedure TF_ReindexMaster.ReindexByTypeClick(Sender: TObject);
begin
  if not ReindexOnObj.Checked then
  begin
    IndexOnlyHigh.Enabled := True;
  end;
  ComponTypeTree.Enabled := True;
  if LineObjectsReindex.Checked = False then
    DefineCadSelectionIndexTypes('PointObj', ComponTypes)
  else
    DefineCadSelectionIndexTypes('LineObj', ComponTypes);
end;

procedure TF_ReindexMaster.ReindexTotalClick(Sender: TObject);
begin
  if LineObjectsReindex.Checked = False then
    DefineCadSelectionIndexTypes('PointObj', ComponTypes)
  else
    DefineCadSelectionIndexTypes('LineObj', ComponTypes);
end;

procedure TF_ReindexMaster.DefineCadSelectionIndexTypes(aComponTypes: string; var ComponTypeList: TStringList);
var  i, j, k: Integer;
//    ComponTypes: TStringList;
    ACad: TF_CAD;
    Figure: TFigure;
    SCSCatalog: TSCSCatalog;
    SCSComponent: TSCSComponent;
    RootNode, Node: TTreeNode;
    ComponType: TComponentType;
    Name: string;
begin
  try
    if F_ProjMan.GSCSBase.CurrProject.CurrList <> nil then
    begin
      if ComponTypeTree.Enabled = false then
        ComponTypeTree.Enabled := true;

    if ComponTypeTree.Items.Count > 0 then
      SaveCheckedTreeList;

     if ComponTypeList = nil then
       ComponTypeList := TStringList.Create
     else
       ComponTypeList.Clear;
      //ComponTypes := TStringList.Create;
      if FiguresList = nil then
        FiguresList := TList.Create
      else
        FiguresList.Clear;
      if aComponTypes = 'PointObj' then
      begin
        DefinePointFigures;
        //for i := 0 to ACad.PCad.Selection.Count - 1 do
        for i := 0 to FiguresList.Count - 1 do
        begin
          Figure := nil;
         // Figure := TFigure(aCad.PCad.Selection[i]);
          Figure := TFigure(FiguresList[i]);
          if Figure <> nil then
          begin
            SCSCatalog := nil;
            SCSCatalog := F_ProjMan.GSCSBase.CurrProject.CurrList.GetCatalogFromReferencesBySCSID(Figure.id);
            if SCSCatalog <> nil then
            begin
              for j := 0 to SCSCatalog.SCSComponents.Count - 1 do
              begin
                SCSComponent := nil;
                SCSComponent := SCSCatalog.SCSComponents[j];
                if SCSComponent <> nil then
                begin
                  if SCSComponent.IsTop and (SCSComponent.IsLine = biFalse) then
                  begin
                    // Top Components
                    if not IndexComplectOnly.Enabled or ((IndexComplectOnly.Enabled) and (not IndexComplectOnly.Checked)) then
                    begin
                      if ComponTypeList.IndexOf(SCSComponent.ComponentType.NamePlural) = -1 then
                      begin
                        ComponTypeList.Add(SCSComponent.ComponentType.NamePlural);
                      end;
                    end;
                    // Top Childs
                    if not (IndexOnlyHigh.Checked or ReindexOnObj.Checked) then
                    begin
                      for k := 0 to SCSComponent.ChildReferences.Count - 1 do
                      begin
                        if ComponTypeList.IndexOf(SCSComponent.ChildReferences[k].ComponentType.NamePlural) = -1 then
                          ComponTypeList.Add(SCSComponent.ChildReferences[k].ComponentType.NamePlural);
                      end;
                    end;
                  end;
                end;
              end;
            end;
          end;
        end;
      end;

      if aComponTypes = 'LineObj' then
      begin
        DefineLineFigures;
        for i := 0 to FiguresList.Count - 1 do
        begin
          Figure := nil;
         // Figure := TFigure(aCad.PCad.Selection[i]);
          Figure := TFigure(FiguresList[i]);
          if Figure <> nil then
          begin
            if CheckFigureByClassName(Figure, cTOrthoLine) then
            begin
              SCSCatalog := nil;
              SCSCatalog := F_ProjMan.GSCSBase.CurrProject.CurrList.GetCatalogFromReferencesBySCSID(Figure.id);
              if SCSCatalog <> nil then
              begin
                if SCSCatalog.IsLine = biTrue then
                begin
                  if ReindexOnObj.Checked then
                  begin
                    if TOrthoLine(Figure).FIsRaiseUpDown then
                    begin
                      if (ComponTypeList.IndexOf(cForm3D_Mes8_3) = -1) then
                        ComponTypeList.Add(cForm3D_Mes8_3);
                    end
                    else
                      if (ComponTypeList.IndexOf(cMasterCableCanalTracing_Msg22_5) = -1) then
                        ComponTypeList.Add(cMasterCableCanalTracing_Msg22_5);
                  end;
                  if not ReindexOnObj.Checked then
                  begin
                    for j := 0 to SCSCatalog.ComponentReferences.Count - 1 do
                    begin
                      SCSComponent := nil;
                      SCSComponent := SCSCatalog.ComponentReferences[j];
                      if SCSComponent <> nil then
                      begin
                        if SCSComponent.IsLine = biTrue then
                        begin
                          if ComponTypeList.IndexOf(SCSComponent.ComponentType.NamePlural) = -1 then
                          begin
                            if ((IndexOnlyHigh_L.Enabled) and (not IndexOnlyHigh_L.Checked)) then
                              ComponTypeList.Add(SCSComponent.ComponentType.NamePlural)
                            else
                              if SCSComponent.IsTop then
                                ComponTypeList.Add(SCSComponent.ComponentType.NamePlural);
                          end;
                        end;
                      end;
                    end;
                  end;
                end;
              end;
            end;  
          end;
        end;
      end;

      ComponTypeTree.Items.Clear;
      RootNode := ComponTypeTree.Items.Add( nil, cexdAll);
      if ComponTypeList.Count > 0 then
      begin
        for i := 0 to ComponTypeList.Count - 1 do
        begin
          Name := ComponTypeList[i];
          Node := ComponTypeTree.Items.AddChild( RootNode, Name);
        end;
      end;
      ComponTypeTree.DropTarget := RootNode;
      ComponTypeTree.DropTarget.Expand(false);
      if ComponTypeTree.Items.Count < 2 then
        ComponTypeTree.Enabled := False
      else
        ComponTypeTree.Enabled := True;
       // end;
      //end;
      if CheckTreeList.Count > 0 then
        LoadCheckedTreeList;
    end;
  finally
  end;
end;

procedure TF_ReindexMaster.FormShow(Sender: TObject);
begin
//  LoadCheckedTreeList;
  if LineObjectsReindex.Checked then
    DefineCadSelectionIndexTypes('LineObj', ComponTypes)
  else
    if PointObjectsReindex.Checked then
      DefineCadSelectionIndexTypes('PointObj', ComponTypes);

  if Point_IndexType.Buttons[0].Checked then
  begin
    BeginComponIndexNum.Enabled := False;
    Label1.Enabled := False;
  end
  else
  begin
    BeginComponIndexNum.Enabled := True;
    Label1.Enabled := True;
  end;

  DropIndexCounter.Enabled := ((F_ReindexMaster.ReindexOnCabinets.Checked and F_ReindexMaster.PointObjectsReindex.Checked) or
                              (F_ReindexMaster.IndexChannelByKabinet.Checked and F_ReindexMaster.LineObjectsReindex.Checked));

  if F_ProjMan.GSCSBase.CurrProject.CurrList.Setting.GroupListObjectsByType = True then
  begin
    F_ReindexMaster.ReindexOnCabinets.ShowHint := True;
    F_ReindexMaster.IndexChannelByKabinet.ShowHint := True;
    F_ReindexMaster.ReindexOnCabinets.Checked := False;
    F_ReindexMaster.IndexChannelByKabinet.Checked := False;

  end
  else
  begin
    F_ReindexMaster.ReindexOnCabinets.ShowHint := False;
    F_ReindexMaster.IndexChannelByKabinet.ShowHint := False;
  end;

  //IndexhReindexMaster_Msg1
end;

procedure TF_ReindexMaster.IndexOnlyHighClick(Sender: TObject);
begin
  if IndexOnlyHigh.Checked then
  begin
    Point_IndexType.Enabled := false;
    if IndexComplectOnly.Checked then
      IndexComplectOnly.Checked := False
    else
    begin
      if LineObjectsReindex.Checked = False then
      DefineCadSelectionIndexTypes('PointObj', ComponTypes)
      else
        DefineCadSelectionIndexTypes('LineObj', ComponTypes);
    end;
  end
  else
  begin
    if PointObjectsReindex.Checked then
      Point_IndexType.Enabled := true;
    if LineObjectsReindex.Checked = False then
      DefineCadSelectionIndexTypes('PointObj', ComponTypes)
    else
      DefineCadSelectionIndexTypes('LineObj', ComponTypes);
  end;
end;

procedure TF_ReindexMaster.MarkDirectionChanging(Sender: TObject;
  NewIndex: Integer; var AllowChange: Boolean);
begin
  if MarkDirection.Buttons[5].Checked then
  begin
    RzLabel2.Enabled := True;
    BeginClockDirection.Enabled := True;
  end
  else
  begin
    RzLabel2.Enabled := False;
    BeginClockDirection.Enabled := False;
  end;
end;

procedure TF_ReindexMaster.LineObjectsReindexClick(Sender: TObject);
begin
  MarkDirection.Visible := False;
  MarkDirection_L.Visible := True;
  //Point_IndexType.Enabled := False;
  Point_IndexType.Visible := False;
  Line_IndexType.Visible := True;
  DropIndexCounter.Enabled := False;
  Label1.Enabled := False;
  MarkDirection.Buttons[4].Enabled := False;
  BeginIndexNum.Visible := False;
  BeginIndexNumL.Visible := True;
  Reindex_Order.Visible := True;
  IndexOnlyHigh_L.Visible := True;
  IndexOnlyHigh_L.Enabled := not ReindexOnObj.Checked;
  IndexOnlyHigh.Visible := False;
  IndexComplectOnly.Visible := False;
  F_ReindexMaster.CheckRaises.Visible := True;
  F_ReindexMaster.DropIndexCounter.Enabled := (F_ReindexMaster.IndexChannelByKabinet.Visible and F_ReindexMaster.IndexChannelByKabinet.Checked);
  DefineCadSelectionIndexTypes('LineObj', ComponTypes);
end;

procedure TF_ReindexMaster.PointObjectsReindexClick(Sender: TObject);
begin
  Point_IndexType.Visible := True;
  Line_IndexType.Visible := False;
  MarkDirection.Buttons[4].Enabled := True;
  MarkDirection.Visible := True;
  MarkDIrection_L.Visible := False;
  if IndexOnlyHigh.Enabled and (not IndexOnlyHigh.Checked) then
  begin
    Point_IndexType.Enabled := True;
    if Point_IndexType.Buttons[0].Checked then
    begin
      BeginComponIndexNum.Enabled := False;
      Label1.Enabled := False;
    end
    else
    begin
      BeginComponIndexNum.Enabled := True;
      Label1.Enabled := True;
    end;
  end;

   DropIndexCounter.Enabled := (F_ReindexMaster.ReindexOnCabinets.Checked and  F_ReindexMaster.ReindexOnCabinets.Enabled and F_ReindexMaster.ReindexOnCabinets.Visible);




  BeginIndexNum.Visible := True;
  BeginIndexNumL.Visible := False;
  Reindex_Order.Visible := False;

  IndexOnlyHigh.Visible := True;
  IndexComplectOnly.Visible := True;
  IndexOnlyHigh_L.Visible := False;
  F_ReindexMaster.CheckRaises.Visible := False;
  DefineCadSelectionIndexTypes('PointObj', ComponTypes);
end;

procedure TF_ReindexMaster.ReindexOnObjClick(Sender: TObject);
begin
  IndexOnlyHigh.Enabled := False;
  IndexComplectOnly.Enabled := False;
  Point_IndexType.Enabled := False;
  BeginComponIndexNum.Enabled := False;
  Label1.Enabled := False;

  if LineObjectsReindex.Checked = False then
  begin
    F_ReindexMaster.CheckRaises.Visible := False;
    DefineCadSelectionIndexTypes('PointObj', ComponTypes);
  end
  else
  begin
    IndexOnlyHigh_L.Enabled := False;
    F_ReindexMaster.CheckRaises.Visible := True;
    DefineCadSelectionIndexTypes('LineObj', ComponTypes);
  end;
  ComponTypeTree.Enabled := True;
end;

procedure TF_ReindexMaster.ReindexOnComponClick(Sender: TObject);
begin
  IndexOnlyHigh.Enabled := True;
  IndexComplectOnly.Enabled := True;
  ComponTypeTree.Enabled := True;
  if LineObjectsReindex.Checked = False then
    DefineCadSelectionIndexTypes('PointObj', ComponTypes)
  else
  begin
    IndexOnlyHigh_L.Enabled := True;
    F_ReindexMaster.CheckRaises.Visible := True;
    DefineCadSelectionIndexTypes('LineObj', ComponTypes);
  end;
  if PointObjectsReindex.Checked and (not IndexOnlyHigh.Checked) then
    Point_IndexType.Enabled := True;
  if (IndexOnlyHigh.Checked = false) and (not Point_IndexType.Buttons[0].Checked) then
  begin
    BeginComponIndexNum.Enabled := True;
    Label1.Enabled := True;
  end;
end;

procedure TF_ReindexMaster.FormClose(Sender: TObject;
  var Action: TCloseAction);
begin
  if FiguresList <> nil then
    FreeAndNil(FiguresList);
  if ComponTypes <> nil then
    FreeAndNil(ComponTypes);  
  SaveCheckedTreeList;
end;

procedure TF_ReindexMaster.Point_IndexTypeChanging(Sender: TObject;
  NewIndex: Integer; var AllowChange: Boolean);
begin
  if Point_IndexType.Buttons[0].Checked then
  begin
    BeginComponIndexNum.Enabled := False;
    Label1.Enabled := False;
  end
  else
  begin
    BeginComponIndexNum.Enabled := True;
    Label1.Enabled := True;
  end;
end;

procedure TF_ReindexMaster.ReindexOnCabinetsClick(Sender: TObject);
begin
  if F_ProjMan.GSCSBase.CurrProject.CurrList.Setting.GroupListObjectsByType = True then
    F_ReindexMaster.ReindexOnCabinets.Checked := False;
    DropIndexCounter.Enabled := (F_ReindexMaster.ReindexOnCabinets.Checked and F_ReindexMaster.ReindexOnCabinets.Visible);
end;

procedure TF_ReindexMaster.IndexComplectOnlyClick(Sender: TObject);
begin
  if IndexComplectOnly.Checked then
  begin
    if IndexOnlyHigh.Checked then
      IndexOnlyHigh.State := cbUnchecked
    else
    begin
      if LineObjectsReindex.Checked = False then
        DefineCadSelectionIndexTypes('PointObj', ComponTypes)
      else
        DefineCadSelectionIndexTypes('LineObj', ComponTypes);
    end;
  end
  else
  begin
    if LineObjectsReindex.Checked = False then
      DefineCadSelectionIndexTypes('PointObj', ComponTypes)
    else
      DefineCadSelectionIndexTypes('LineObj', ComponTypes);
  end;
end;
procedure TF_ReindexMaster.IndexOnlyHigh_LClick(Sender: TObject);
begin
   if LineObjectsReindex.Checked = False then
      DefineCadSelectionIndexTypes('PointObj', ComponTypes)
    else
      DefineCadSelectionIndexTypes('LineObj', ComponTypes);
  //DefineCadSelectionIndexTypes('LineObj', ComponTypes);
end;

procedure TF_ReindexMaster.CheckRaisesClick(Sender: TObject);
begin
  DefineCadSelectionIndexTypes('LineObj', ComponTypes);
end;

procedure TF_ReindexMaster.IndexChannelByKabinetClick(Sender: TObject);
begin
  if F_ProjMan.GSCSBase.CurrProject.CurrList.Setting.GroupListObjectsByType = True then
    F_ReindexMaster.IndexChannelByKabinet.Checked := False;
    DropIndexCounter.Enabled := F_ReindexMaster.IndexChannelByKabinet.Checked;
end;

procedure TF_ReindexMaster.Button_CancelClick(Sender: TObject);
begin
  Exit;
end;



End.// yet
