Imports System.Collections.ObjectModel
Imports System.ComponentModel
Imports EgtUILib

Public Class SplitPageUC

   ' Riferimento alla MainWindow
   Private m_MainWindow As MainWindow = DirectCast(Application.Current.MainWindow, MainWindow)
   Private WithEvents m_CurrProjPage As CurrentProjectPageUC
   ' Flag di pagina attiva
   Private m_bActive As Boolean = False
   ' Tipo movimento dei grezzi (manuale o con testa ventosa)
   Private m_bByHand As Boolean = True
   ' Abilitazione movimento finale pezzi su tavola ausiliaria
   Private m_bEnableOnAuxTab As Boolean = False
   ' Stato
   Private m_nCurrPhase As Integer = 0
   Private m_MachiningList As New List(Of SplitMach)

   ' numero di lavorazioni di tipo lama
   Private m_nCountSawing As Integer = 0
   ' numero di lavprazioni di tipo waterjet
   Private m_nCountWaterjetting As Integer = 0
   ' altri tipi di lavorazioni (Foro/Fresa)
   Private m_nCountOtherMachining As Integer = 0
   ' verifico che le lavorazioni selezionate siano omogenee (con lo stesso utensile)
   Private m_bAreHomogeneous As Boolean = False

   Private m_ItemList As New ObservableCollection(Of NameIdLsBxItem)
   'Private m_CurrInd As Integer = -1
   'Private m_CurrItems As New List(Of NameIdLsBxItem)
   Private m_CurrFirstInd As Integer = -1
   Private m_CurrLastInd As Integer = -1
   Friend m_bShow As Boolean = False
   Private m_bModified As Boolean = False
   Private m_nNbrGrpId As Integer = GDB_ID.NULL
   Private m_bToNext As Boolean = False
   Friend m_bOnAuxTab As Boolean = False
   ' Drag
   Private m_nDragInd As Integer = -1
   Private m_nDragType As Integer = 0           '0=niente, 1=attacco, 2=uscita
   Private m_ptDragPrev As Point3d
   Private m_bDragging As Boolean = False
   ' Selected cut
   Private m_nSelected As Integer = GDB_ID.NULL

   Private Sub SplitPageUC_Initialized(sender As Object, e As EventArgs)
      PrevBtn.IsEnabled = False
      ' Collego lista di oggetti a ListBox
      MachiningLsBx.ItemsSource = m_ItemList
      ' Assegno testi
      OnOffBtn.ToolTip = EgtMsg(MSG_SPLITPAGEUC + 1)         ' On/Off
      AllOnBtn.ToolTip = EgtMsg(MSG_SPLITPAGEUC + 2)         ' Tutti On
      AllOffBtn.ToolTip = EgtMsg(MSG_SPLITPAGEUC + 3)        ' Tutti Off
      CutBtn.ToolTip = EgtMsg(MSG_SPLITPAGEUC + 4)           ' Allunga/Accorcia
      CutStartBtn.ToolTip = EgtMsg(MSG_SPLITPAGEUC + 5)      ' Inizio Allunga/Accorcia
      CutEndBtn.ToolTip = EgtMsg(MSG_SPLITPAGEUC + 6)        ' Fine Allunga/Accorcia
      OutCenStartBtn.ToolTip = EgtMsg(MSG_SPLITPAGEUC + 7)   ' Inizio Centro/Fuori
      OutCenEndBtn.ToolTip = EgtMsg(MSG_SPLITPAGEUC + 12)    ' Fine Centro/Fuori
      ModifStartBtn.ToolTip = EgtMsg(MSG_SPLITPAGEUC + 33)   ' Inizio Modif.
      ModifEndBtn.ToolTip = EgtMsg(MSG_SPLITPAGEUC + 34)     ' Fine Modif.
      InvertBtn.ToolTip = EgtMsg(MSG_SPLITPAGEUC + 36)       ' Inverti
      PauseBtn.ToolTip = EgtMsg(MSG_SPLITPAGEUC + 31)        ' Pausa On/Off
      AllOutStartBtn.ToolTip = EgtMsg(MSG_SPLITPAGEUC + 8)   ' Inizi Tutti Fuori
      AllCenStartBtn.ToolTip = EgtMsg(MSG_SPLITPAGEUC + 9)   ' Inizi Tutti Centro
      AllOutEndBtn.ToolTip = EgtMsg(MSG_SPLITPAGEUC + 13)    ' Fine Tutti Fuori
      AllCenEndBtn.ToolTip = EgtMsg(MSG_SPLITPAGEUC + 14)    ' Fine Tutti Centro
      AllExtendBtn.ToolTip = EgtMsg(MSG_SPLITPAGEUC + 15)    ' Allunga Tutti
      AllReduceBtn.ToolTip = EgtMsg(MSG_SPLITPAGEUC + 16)    ' Accorc. Tutti
      ModifyBtn.Content = EgtMsg(MSG_SPLITPAGEUC + 17)       ' Modifica
      AutoBtn.Content = EgtMsg(MSG_SPLITPAGEUC + 18)         ' Auto
      RestartBtn.Content = EgtMsg(MSG_SPLITPAGEUC + 19)      ' Restart
   End Sub

   Private Sub SplitPageUC_Loaded(sender As Object, e As EventArgs) Handles Me.Loaded
      m_bActive = True
      m_CurrProjPage = m_MainWindow.m_CurrentProjectPageUC
      m_nDragInd = -1
      m_nDragType = 0
      ' Leggo tipo movimento grezzi
      m_bByHand = (EgtGetHeadId(VACUUM_HEAD) = GDB_ID.NULL Or
                  Not m_MainWindow.GetKeyOption(MainWindow.KEY_OPT.AUTO_MANIP) Or
                  (GetPrivateProfileInt(S_RAWMOVE, K_PERPENDICULAR, 0, m_MainWindow.GetIniFile()) <> 0))
      ' Se movimento con ventosa, verifico se lama troppo grande
      If Not m_bByHand And Not m_MainWindow.m_CurrentMachine.IsVacuumMovePossible() Then
         m_bByHand = True
         m_MainWindow.m_CurrentProjectPageUC.SetWarningMessage(EgtMsg(MSG_SPLITPAGEUC + 11))    ' Lama troppo grande per utilizzo ventosa
      End If
      ' Verifico se abilitato spostamento finale pezzi e se macchina lo consente
      m_bEnableOnAuxTab = Not m_bByHand AndAlso
                          m_MainWindow.GetKeyOption(MainWindow.KEY_OPT.MOVE_PARTS) AndAlso
                          EgtGetTableId(AUX_TAB) <> GDB_ID.NULL
      ' Nascondo eventuali pezzi in parcheggio
      HideParkedParts()
      ' Nascondo eventuale contorno da foto
      m_MainWindow.m_CurrentProjectPageUC.ShowContour(False)
      ' Deseleziono pezzi
      EgtDeselectAll()
      EgtZoom(ZM.ALL)
      ' Elimino eventuali pretagli su uscite
      RemoveAllExitPreCuts()
      ' Se non sono in sola visualizzazione, faccio ordine automatico delle lavorazioni
      If Not m_bShow Then
         If m_MainWindow.m_CurrentMachine.WaterJettingActive Then ResetAllMachinings()
         If SortAllMachinings() Then m_MainWindow.m_CurrentProjectPageUC.SetOrderMachiningFlag()
         If m_MainWindow.m_CurrentMachine.WaterJettingActive Then
            Dim bModif As Boolean = TestAllMachiningsForStrict()
            If bModif Then m_MainWindow.m_CurrentProjectPageUC.SetWarningMessage(EgtMsg(90321)) 'Ridotte alcune lavorazioni per evitare interferenze
         End If
      End If
      ' Disabilito impostazione modificato
      EgtDisableModified()
      ' Creo gruppo per numeri identificativi di lavorazione (colore default grigio)
      m_nNbrGrpId = EgtCreateGroup(GDB_ID.ROOT)
      EgtSetColor(m_nNbrGrpId, COL_MCH_DIS_NUMBER)
      EgtSetStatus(m_nNbrGrpId, GDB_ST.SEL)
      EgtSetLevel(m_nNbrGrpId, GDB_LV.TEMP)
      ' Recupero l'indice della fase corrente
      m_nCurrPhase = EgtGetCurrPhase()
      ' Visualizzo solo anteprime di lavorazioni della fase
      ShowOnePhaseMachiningPreview(m_nCurrPhase)
      ' Preparo la lista delle lavorazioni
      CalculateSplitMachList(m_nCurrPhase, m_MachiningList)
      ' azzero i contatori delle lavorazioni
      m_nCountSawing = 0
      m_nCountWaterjetting = 0
      m_nCountOtherMachining = 0
      ' Aggiorno visualizzazione delle lavorazioni
      For nI As Integer = 0 To m_MachiningList.Count() - 1
         ' sistemo colore
         ColorMachining(m_MachiningList(nI))
         ' assegno numerazione
         NumberDirectionMachining(nI)
         ' conto il numero di tipi di lavorazioni
         CountMachiningType(m_MachiningList(nI), m_nCountSawing, m_nCountWaterjetting, m_nCountOtherMachining)
      Next
      ' Preparo la lista degli Item
      ShowMachiningList()
      ' Aggiorno visualizzazione
      EgtDraw()
      ' Abilito impostazione modificato
      EgtEnableModified()
      ' Nessun item corrente
      m_CurrFirstInd = -1
      m_CurrLastInd = -1
      ' Reset flag di modifica
      m_bModified = False
      ' Reset flag tipo uscita
      m_bToNext = False
      ' Abilitazione bottoni
      EnableButtons()
      ' Se sola visualizzazione, segnalazione di eventuale fase di restart
      If m_bShow Then
         Dim nPhaseRestart As Integer = m_MainWindow.m_CurrentProjectPageUC.GetProjectNcRestart()
         If nPhaseRestart = m_nCurrPhase Then
            m_MainWindow.m_CurrentProjectPageUC.SetInfoMessage(EgtMsg(MSG_SPLITPAGEUC + 19) & " (" & m_nCurrPhase.ToString() & ")")
         Else
            m_MainWindow.m_CurrentProjectPageUC.ClearMessage()
         End If
      End If
   End Sub

   Private Sub ShowMachiningList()
      m_ItemList.Clear()
      For i As Integer = 1 To m_MachiningList.Count()
         Dim Mach As SplitMach = m_MachiningList(i - 1)
         If Mach.m_nType = MCH_OY.SAWING Then            ' Taglio
            Dim sText As String = String.Empty
            If Math.Abs(Mach.m_dSideAng) < EPS_ANG_SMALL Then
               sText = EgtMsg(90791) & " " & i.ToString()
               If Mach.m_sLay = NAME_ONPATH Then AddTopText(sText)
            Else
               sText = EgtMsg(90791) & " " & i.ToString() & "  " & DoubleToString(Mach.m_dSideAng, 2) & "°"
            End If
            If Mach.m_bPause Then AddPauseText(sText)
            m_ItemList.Add(New NameIdLsBxItem(sText, i - 1, Mach.m_bEnabled, MCH_OY.SAWING))
         ElseIf Mach.m_nType = MCH_OY.DRILLING Then       ' Foratura
            Dim sText As String = EgtMsg(90792) & " " & i.ToString()
            If Mach.m_bPause Then AddPauseText(sText)
            m_ItemList.Add(New NameIdLsBxItem(sText, i - 1, Mach.m_bEnabled, MCH_OY.DRILLING))
         ElseIf Mach.m_nType = MCH_OY.MILLING Then        ' Fresatura
            Dim sText As String = EgtMsg(90793) & " " & i.ToString()
            If Mach.m_sLay = NAME_ONPATH Then AddTopText(sText)
            If Mach.m_bPause Then AddPauseText(sText)
            m_ItemList.Add(New NameIdLsBxItem(sText, i - 1, Mach.m_bEnabled, MCH_OY.MILLING))
         ElseIf Mach.m_nType = MCH_OY.POCKETING Then      ' Svuotatura
            Dim sText As String = EgtMsg(90796) & " " & i.ToString()
            If Mach.m_bPause Then AddPauseText(sText)
            m_ItemList.Add(New NameIdLsBxItem(sText, i - 1, Mach.m_bEnabled, MCH_OY.POCKETING))
         ElseIf Mach.m_nType = MCH_OY.WATERJETTING Then   ' Waterjet
            Dim sText As String = EgtMsg(90797) & " " & i.ToString()
            If Mach.m_bPause Then AddPauseText(sText)
            m_ItemList.Add(New NameIdLsBxItem(sText, i - 1, Mach.m_bEnabled, MCH_OY.WATERJETTING))
         End If
      Next
   End Sub

   Private Sub OnMyMouseDownScene(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles m_CurrProjPage.OnMouseDownScene
      ' Verifico di essere il gestore attivo e non in modalità sola visualizzazione
      If Not m_bActive OrElse m_bShow Then Return
      ' Si può selezionare solo con il tasto sinistro e se stato NULL
      If e.Button <> Windows.Forms.MouseButtons.Left Or
         Not m_CurrProjPage.CurrentProjectScene.IsStatusNull() Then
         Return
      End If
      ' Reset drag
      m_nDragInd = -1
      m_nDragType = 0
      ' Reset selection interface
      m_nSelected = GDB_ID.NULL
      ' Verifico se selezionato estremo di taglio con lama
      EgtSetObjFilterForSelWin(False, True, False, False, False)
      Dim nSel As Integer
      EgtSelect(e.Location, Scene.DIM_SEL, Scene.DIM_SEL, nSel)
      Dim nId As Integer = EgtGetFirstObjInSelWin()
      While nId <> GDB_ID.NULL
         ' Verifico sia un attacco o uscita di taglio con lama
         Dim nType As Integer = 0
         Dim sName As String = ""
         EgtGetName(nId, sName)
         If String.Compare(sName, NAME_PV_PRECUT) = 0 Then
            nType = 1
         ElseIf String.Compare(sName, NAME_PV_POSTCUT) = 0 Then
            nType = 2
         ElseIf String.Compare(sName, NAME_PV_CUT) = 0 Then
            nType = 3
         End If
         If nType = 1 Or nType = 2 Then
            Dim nPvId As Integer = EgtGetParent(EgtGetParent(nId))
            Dim nMchId As Integer = GDB_ID.NULL
            If EgtGetInfo(nPvId, "MId", nMchId) Then
               For nInd As Integer = 0 To m_MachiningList.Count() - 1
                  If m_MachiningList(nInd).m_nId = nMchId Then
                     m_nDragInd = nInd
                     m_nDragType = nType
                  End If
                  For nJ As Integer = 0 To m_MachiningList(nInd).m_vOthId.Count() - 1
                     If m_MachiningList(nInd).m_vOthId(nJ) = nMchId Then
                        m_nDragInd = nInd
                        m_nDragType = nType
                        Exit For
                     End If
                  Next
                  If m_nDragInd >= 0 Then
                     ' Assegno l'id dell'elemnto selezionato
                     m_nSelected = m_nDragInd
                     Exit For
                  End If
               Next
            End If
            If m_nDragInd >= 0 Then
               ' Assegno l'id dell'elemnto selezionato
               m_nSelected = m_nDragInd
               Exit While
            End If
         ElseIf nType = 3 Then
            Dim nPvId As Integer = EgtGetParent(EgtGetParent(nId))
            Dim nMchId As Integer = GDB_ID.NULL
            If EgtGetInfo(nPvId, "MId", nMchId) Then
               For nInd As Integer = 0 To m_MachiningList.Count() - 1
                  If m_MachiningList(nInd).m_nId = nMchId Then
                     m_nSelected = nInd
                  End If
                  For nJ As Integer = 0 To m_MachiningList(nInd).m_vOthId.Count() - 1
                     If m_MachiningList(nInd).m_vOthId(nJ) = nMchId Then
                        m_nSelected = nInd
                        Exit For
                     End If
                  Next
                  If m_nSelected >= 0 Then Exit For
               Next
            End If
            If m_nSelected >= 0 Then Exit While
         End If
         nId = EgtGetNextObjInSelWin()
      End While
      ' Sistemazioni per drag
      If m_nSelected >= 0 AndAlso EgtUnProjectPoint(e.Location, m_ptDragPrev) Then
         MachiningLsBx.SelectedIndex = m_nSelected
      Else
         m_nDragInd = -1
         m_nDragType = 0
         m_nSelected = GDB_ID.NULL
      End If
   End Sub

   Private Sub OnMyMouseMoveScene(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles m_CurrProjPage.OnMouseMoveScene
      ' Verifico di essere il gestore attivo e non in modalità sola visualizzazione
      If Not m_bActive OrElse m_bShow Then Return
      ' Se drag non abilitato o in corso
      If m_nDragInd = -1L Or m_bDragging Then Return
      m_bDragging = True
      Dim nOperId As Integer = m_MachiningList(m_nDragInd).m_nId
      ' Ricavo il punto corrente in coordinate mondo
      Dim ptCurr As Point3d
      EgtUnProjectPoint(e.Location, ptCurr)
      ' Ricavo il vettore di movimento e la variazione di lunghezza
      Dim vtMove As Vector3d = ptCurr - m_ptDragPrev
      Dim dDelta = vtMove * m_MachiningList(m_nDragInd).m_vtDir
      If m_nDragType = 1 Then
         Dim dOrigUsal As Double = 0
         Dim dUsal As Double
         ' ----------------------- REPEAT -----------------------
         Do
            dDelta = -dDelta
            ' Leggo il valore salvato nella geometria
            EgtGetInfo(nOperId, INFO_MCH_USER_SAL, dOrigUsal)
            dUsal = dOrigUsal + dDelta
            ' Se c'è limite alla lunghezza libera
            If m_MachiningList(m_nDragInd).m_dStartFreeLen < FREELEN_INF Then
               ' Recupero sicurezza in corner interno
               Dim dCornerSafety As Double = Math.Max(GetPrivateProfileDouble(S_MACH_NEST, K_MACH_SAFE_LEN_INTCORNER, 1, m_MainWindow.GetMachIniFile()), 10 * EPS_SMALL)
               ' Recupero lunghezza baffo del taglio
               Dim nPvId As Integer = GDB_ID.NULL
               EgtGetInfo(EgtGetFirstNameInGroup(nOperId, NAME_PREVIEW), INFO_PV_ONPART_ID, nPvId)
               Dim dDT As Double = 0
               EgtGetInfo(EgtGetFirstGroupInGroup(nPvId), "DT", dDT)
               dUsal = Math.Min(dUsal, m_MachiningList(m_nDragInd).m_dStartFreeLen - dDT - dCornerSafety)
            End If
            ' Modifica della lavorazione
            EgtSetCurrMachining(nOperId)
            Dim dAddLen As Double = 0
            EgtGetMachiningParam(MCH_MP.STARTADDLEN, dAddLen)

            If dAddLen - dOrigUsal < -10 * EPS_SMALL Then
               m_bDragging = False
               Return
            End If
            EgtSetMachiningParam(MCH_MP.STARTADDLEN, dAddLen + dUsal - dOrigUsal)
            EgtSetInfo(nOperId, INFO_MCH_USER_SAL, dUsal)
         Loop Until UpdateMachiningPreview(m_MachiningList(m_nDragInd).m_nId, True)
         ' ----------------------- REPEAT (solo se il segmento scompare) -----------------------
      Else
         Dim dOrigUeal As Double = 0
         Dim dUeal As Double
         dDelta = -dDelta
         Do
            dDelta = -dDelta
            ' Leggo il valore salvato nella geometria
            EgtGetInfo(nOperId, INFO_MCH_USER_EAL, dOrigUeal)
            dUeal = dOrigUeal + dDelta
            ' Se c'è limite alla lunghezza libera
            If m_MachiningList(m_nDragInd).m_dEndFreeLen < FREELEN_INF Then
               ' Recupero sicurezza in corner interno
               Dim dCornerSafety As Double = Math.Max(GetPrivateProfileDouble(S_MACH_NEST, K_MACH_SAFE_LEN_INTCORNER, 1, m_MainWindow.GetMachIniFile()), 10 * EPS_SMALL)
               ' Recupero lunghezza baffo del taglio
               Dim nPvId As Integer = GDB_ID.NULL
               EgtGetInfo(EgtGetFirstNameInGroup(nOperId, NAME_PREVIEW), INFO_PV_ONPART_ID, nPvId)
               Dim dDT As Double = 0
               EgtGetInfo(EgtGetFirstGroupInGroup(nPvId), "DT", dDT)
               dUeal = Math.Min(dUeal, m_MachiningList(m_nDragInd).m_dEndFreeLen - dDT - dCornerSafety)
            End If
            ' Modifica della lavorazione
            EgtSetCurrMachining(nOperId)
            Dim dAddLen As Double = 0
            EgtGetMachiningParam(MCH_MP.ENDADDLEN, dAddLen)

            If dAddLen - dOrigUeal < -10 * EPS_SMALL Then
               m_bDragging = False
               Return
            End If
            EgtSetMachiningParam(MCH_MP.ENDADDLEN, dAddLen + dUeal - dOrigUeal)
            EgtSetInfo(nOperId, INFO_MCH_USER_EAL, dUeal)
         Loop Until UpdateMachiningPreview(m_MachiningList(m_nDragInd).m_nId, True)
      End If
      ' verifico interferenza
      EgtVerifyMachining(m_MachiningList(m_nDragInd).m_nId, m_MachiningList(m_nDragInd).m_nInterf)
      ColorMachining(m_MachiningList(m_nDragInd))
      ColorNumberArrow(m_nDragInd)
      ' Aggiorno visualizzazione
      EgtDraw()
      m_bModified = True
      ' Aggiorno punto e stato di drag
      m_ptDragPrev = ptCurr
      m_bDragging = False
   End Sub

   Private Sub OnMyMouseUpScene(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles m_CurrProjPage.OnMouseUpScene
      ' Verifico di essere il gestore attivo e non in modalità sola visualizzazione
      If Not m_bActive OrElse m_bShow Then Return
      ' Se drag in corso
      If m_nDragInd >= 0 Then
         m_nDragInd = -1
      End If
   End Sub

   Private Sub AddPauseText(ByRef sName As String)
      sName &= "  " & EgtMsg(MSG_SPLITPAGEUC + 32) ' Pausa
   End Sub

   Private Sub AddTopText(ByRef sName As String)
      sName &= "  Top"
   End Sub

   Private Sub RemovePauseText(ByRef sName As String)
      sName = sName.Replace(EgtMsg(MSG_SPLITPAGEUC + 32), "")
      sName = sName.TrimEnd()
   End Sub

   Private Sub MachiningLsBx_SelectionChanged(sender As Object, e As SelectionChangedEventArgs) Handles MachiningLsBx.SelectionChanged
      If MachiningLsBx.SelectedItems.Count = 0 Then Return
      If MachiningLsBx.SelectedItems.Count = 1 Then m_bAreHomogeneous = True
      ' creo lista ordinata dei selezionati
      Dim ItemList As New List(Of NameIdLsBxItem)
      For Each Item As NameIdLsBxItem In MachiningLsBx.SelectedItems
         ItemList.Add(Item)
      Next

      ' verifico che le lavorazioni siano dello stesso tipo
      VerifyHomogenousMachining(ItemList)

      ItemList.Sort(Function(x, y) Comparer(Of Integer).Default.Compare(m_ItemList.IndexOf(x), m_ItemList.IndexOf(y)))

      If VerifyContinuity(ItemList) Then
         MoveUpBtn.IsEnabled = True
         MoveDownBtn.IsEnabled = True
      Else
         MoveUpBtn.IsEnabled = False
         MoveDownBtn.IsEnabled = False
      End If

      GetCurrSelection()

      '' verifico che siano contigui
      'Dim bContigus As Boolean = False
      'Dim OrdIndex = 0
      'OrdIndex = MachiningLsBx.SelectedItems(MachiningLsBx.SelectedItems.Count - 1).Ind
      '' recupero l'indice dell'ultimo elemento selezionato
      'Dim LastSel As NameIdLsBxItem = MachiningLsBx.SelectedItems(MachiningLsBx.SelectedItems.Count - 1)
      'If MachiningLsBx.SelectedItems.Count = 1 Then
      '   bContigus = True
      'Else
      '   For Each Item As NameIdLsBxItem In ItemList
      '      If Item.Ind = LastSel.Ind + 1 Or Item.Ind = LastSel.Ind - 1 Then
      '         bContigus = True
      '      End If
      '   Next
      'End If
      '' se non contiguo, elimino dai selezionati il primo(che è l'ultimo ad essere stato selezionato)
      'If Not bContigus Then
      '   ItemList.Remove(LastSel)
      '   MachiningLsBx.SelectedItems.RemoveAt(MachiningLsBx.SelectedItems.Count - 1)
      'End If

      ' resetto marcatura lavorazioni
      If m_CurrFirstInd > -1 Then
         For Index As Integer = m_CurrFirstInd To m_CurrLastInd
            MarkMachining(m_ItemList(Index).Ind, False)
         Next
      End If
      ' resetto indici
      m_CurrFirstInd = -1
      m_CurrLastInd = -1
      ' marco lavorazioni selezionate
      For Each Item As NameIdLsBxItem In ItemList
         MarkMachining(Item.Ind, True)
      Next
      m_CurrFirstInd = m_ItemList.IndexOf(ItemList(0))
      m_CurrLastInd = m_ItemList.IndexOf(ItemList(ItemList.Count - 1))
      EgtDraw()
   End Sub

   Private Sub MoveUpBtn_Click(sender As Object, e As RoutedEventArgs) Handles MoveUpBtn.Click
      MoveItem(-1)
   End Sub

   Private Sub MoveDownBtn_Click(sender As Object, e As RoutedEventArgs) Handles MoveDownBtn.Click
      MoveItem(1)
   End Sub

   Private Sub MoveItem(direction As Integer)
      ' Checking selected item
      If m_CurrFirstInd = -1 OrElse MachiningLsBx.SelectedIndex < 0 Then
         Return
      End If

      ' Se la direzione è giù
      If direction = 1 And m_CurrLastInd < m_ItemList.Count - 1 Then
         ' sposto il successivo prima di tutti i selezionati
         m_ItemList.Move(m_CurrLastInd + 1, m_CurrFirstInd)
         MoveMachining(m_CurrLastInd + 1, m_CurrFirstInd)
         ' aggiorno gli indici degli elementi coinvolti nello spostamento (selezionati e non)
         For index As Integer = m_CurrLastInd + 1 To m_CurrFirstInd Step -1
            m_ItemList(index).Ind = index
         Next
         m_CurrFirstInd += 1
         m_CurrLastInd += 1
      ElseIf direction = -1 And m_CurrFirstInd > 0 Then
         ' sposto il precedente dopo tutti i selezionati
         m_ItemList.Move(m_CurrFirstInd - 1, m_CurrLastInd)
         MoveMachining(m_CurrFirstInd - 1, m_CurrLastInd)
         ' aggiorno gli indici degli elementi coinvolti nello spostamento (selezionati e non)
         For index As Integer = m_CurrFirstInd - 1 To m_CurrLastInd
            m_ItemList(index).Ind = index
         Next
         m_CurrFirstInd -= 1
         m_CurrLastInd -= 1
      End If

      ' Imposto flag di modifica
      m_bModified = True
   End Sub

   Private Sub MoveMachining(oldIndex As Integer, newIndex As Integer)
      Dim item As SplitMach = m_MachiningList(oldIndex)
      m_MachiningList.RemoveAt(oldIndex)
      m_MachiningList.Insert(newIndex, item)
   End Sub

   Private Sub OnOffBtn_Click(sender As Object, e As RoutedEventArgs) Handles OnOffBtn.Click
      If m_CurrFirstInd = -1 Then Return
      For Index As Integer = m_CurrFirstInd To m_CurrLastInd
         If Not m_ItemList(Index).IsSelected Then
            Continue For
         End If
         Dim nI As Integer = m_ItemList(Index).Ind
         If m_MachiningList(nI).m_bEnabled Then
            m_MachiningList(nI).m_bEnabled = False
            m_ItemList(Index).bIsActive = False
         Else
            m_MachiningList(nI).m_bEnabled = True
            m_ItemList(Index).bIsActive = True
         End If
         ColorMachining(m_MachiningList(nI))
         ColorNumberArrow(nI)
      Next
      EgtDraw()
      ' Imposto flag di modifica
      m_bModified = True

      ' recupero l'elenco degli elementi selezionati
      Dim ItemList As New List(Of NameIdLsBxItem)
      For Each Item As NameIdLsBxItem In MachiningLsBx.SelectedItems
         ItemList.Add(Item)
      Next

      VerifyHomogenousMachining(ItemList)
   End Sub

   Private Sub AllOnBtn_Click(sender As Object, e As RoutedEventArgs) Handles AllOnBtn.Click
      For nI As Integer = 0 To m_MachiningList.Count() - 1
         If Not m_MachiningList(nI).m_bEnabled Then
            m_MachiningList(nI).m_bEnabled = True
            m_ItemList(nI).bIsActive = True
            ColorMachining(m_MachiningList(nI))
            ColorNumberArrow(nI)
         End If
      Next
      EgtDraw()
      ' Imposto flag di modifica
      m_bModified = True
      ' Abilitazione bottone Next
      EnableButtons()
   End Sub

   Private Sub AllOffBtn_Click(sender As Object, e As RoutedEventArgs) Handles AllOffBtn.Click
      For nI As Integer = 0 To m_MachiningList.Count() - 1
         If m_MachiningList(nI).m_bEnabled Then
            m_MachiningList(nI).m_bEnabled = False
            m_ItemList(nI).bIsActive = False
            ColorMachining(m_MachiningList(nI))
            ColorNumberArrow(nI)
         End If
      Next
      EgtDraw()
      ' Imposto flag di modifica
      m_bModified = True
      ' Abilitazione bottone Next
      EnableButtons()
   End Sub

   Private Sub CutBtn_Click(sender As Object, e As RoutedEventArgs) Handles CutBtn.Click
      If m_CurrFirstInd = -1 Then Return
      Dim bGenModif As Boolean = False
      For Index As Integer = m_CurrFirstInd To m_CurrLastInd
         If Not m_ItemList(Index).IsSelected Then
            Continue For
         End If
         Dim nI As Integer = m_ItemList(Index).Ind
         ' Provo ad entrambi gli estremi
         Dim bModif As Boolean = AdjustBothCuts(nI)
         ' Provo all'inizio
         If Not bModif Then bModif = AdjustStartCut(nI)
         ' Provo alla fine
         If Not bModif Then bModif = AdjustEndCut(nI)
         ' Se modificato qualcosa
         If bModif Then
            bGenModif = True
         End If
      Next
      ' Se modificato qualcosa
      If bGenModif Then
         EgtDraw()
         m_bModified = True
      End If
      ' Aggiono abilitazione bottoni
      EnableButtons()
   End Sub

   Private Sub CutEndBtn_Click(sender As Object, e As RoutedEventArgs) Handles CutEndBtn.Click
      If m_CurrFirstInd = -1 Then Return
      Dim bGenModif As Boolean = False
      For Index As Integer = m_CurrFirstInd To m_CurrLastInd
         If Not m_ItemList(Index).IsSelected Then
            Continue For
         End If
         Dim nI As Integer = m_ItemList(Index).Ind
         ' Eseguo
         If AdjustEndCut(nI) Then
            bGenModif = True
         End If
      Next
      ' Se modificato qualcosa
      If bGenModif Then
         EgtDraw()
         m_bModified = True
      End If
      ' Aggiono abilitazione bottoni
      EnableButtons()
   End Sub

   Private Sub CutStartBtn_Click(sender As Object, e As RoutedEventArgs) Handles CutStartBtn.Click
      If m_CurrFirstInd = -1 Then Return
      Dim bGenModif As Boolean = False
      For Index As Integer = m_CurrFirstInd To m_CurrLastInd
         If Not m_ItemList(Index).IsSelected Then
            Continue For
         End If
         Dim nI As Integer = m_ItemList(Index).Ind
         ' Eseguo
         If AdjustStartCut(nI) Then
            bGenModif = True
         End If
      Next
      ' Se modificato qualcosa
      If bGenModif Then
         EgtDraw()
         m_bModified = True
      End If
      ' Aggiono abilitazione bottoni
      EnableButtons()
   End Sub

   Private Function AdjustBothCuts(nI As Integer,
                                   Optional bAllForced As Boolean = False,
                                   Optional bAccForced As Boolean = False) As Boolean
      ' Verifico che entrambi gli estremi siano allungabili
      If Not (m_MachiningList(nI).m_bCanStartAll And m_MachiningList(nI).m_bCanEndAll) Then Return False
      ' Eseguo allungamento o riporto allo standard
      EgtSetCurrMachining(m_MachiningList(nI).m_nId)
      Dim nLiPrev As Integer
      EgtGetMachiningParam(MCH_MP.LEADINTYPE, nLiPrev)
      Dim nLoPrev As Integer
      EgtGetMachiningParam(MCH_MP.LEADOUTTYPE, nLoPrev)
      If (m_MachiningList(nI).m_bStartAll Or m_MachiningList(nI).m_bEndAll) And Not bAllForced Then
         ' accorcio
         If nLiPrev = MCH_SAW_LI.EXT_OUT Then
            EgtSetMachiningParam(MCH_MP.LEADINTYPE, MCH_SAW_LI.OUT)
         Else
            EgtSetMachiningParam(MCH_MP.LEADINTYPE, MCH_SAW_LI.CENT)
         End If
         If nLoPrev = MCH_SAW_LO.EXT_OUT Then
            EgtSetMachiningParam(MCH_MP.LEADOUTTYPE, MCH_SAW_LO.OUT)
         Else
            EgtSetMachiningParam(MCH_MP.LEADOUTTYPE, MCH_SAW_LO.CENT)
         End If
         UpdateMachiningPreview(m_MachiningList(nI).m_nId, True)
         m_MachiningList(nI).m_bStartAll = False
         m_MachiningList(nI).m_bEndAll = False
      ElseIf m_MachiningList(nI).m_bEnabled And Not bAccForced Then
         ' allungo
         If nLiPrev = MCH_SAW_LI.OUT Then
            EgtSetMachiningParam(MCH_MP.LEADINTYPE, MCH_SAW_LI.EXT_OUT)
         Else
            EgtSetMachiningParam(MCH_MP.LEADINTYPE, MCH_SAW_LI.EXT_CENT)
         End If
         If nLoPrev = MCH_SAW_LO.OUT Then
            EgtSetMachiningParam(MCH_MP.LEADOUTTYPE, MCH_SAW_LO.EXT_OUT)
         Else
            EgtSetMachiningParam(MCH_MP.LEADOUTTYPE, MCH_SAW_LO.EXT_CENT)
         End If
         UpdateMachiningPreview(m_MachiningList(nI).m_nId, True)
         m_MachiningList(nI).m_bStartAll = True
         m_MachiningList(nI).m_bEndAll = True
      End If
      ColorMachining(m_MachiningList(nI))
      Return True
   End Function

   Private Function AdjustStartCut(nI As Integer,
                                   Optional bAllForced As Boolean = False,
                                   Optional bAccForced As Boolean = False) As Boolean
      ' Verifico che l'estremo iniziale sia allungabile
      If Not m_MachiningList(nI).m_bCanStartAll Then Return False
      ' Eseguo allungamento o riporto allo standard
      EgtSetCurrMachining(m_MachiningList(nI).m_nId)
      Dim nLiPrev As Integer
      EgtGetMachiningParam(MCH_MP.LEADINTYPE, nLiPrev)
      If m_MachiningList(nI).m_bStartAll And Not bAllForced Then
         ' accorcio
         If nLiPrev = MCH_SAW_LI.EXT_OUT Then
            EgtSetMachiningParam(MCH_MP.LEADINTYPE, MCH_SAW_LI.OUT)
         Else
            EgtSetMachiningParam(MCH_MP.LEADINTYPE, MCH_SAW_LI.CENT)
         End If
         UpdateMachiningPreview(m_MachiningList(nI).m_nId, True)
         m_MachiningList(nI).m_bStartAll = False
      ElseIf m_MachiningList(nI).m_bEnabled And Not bAccForced Then
         ' allungo
         If nLiPrev = MCH_SAW_LI.OUT Then
            EgtSetMachiningParam(MCH_MP.LEADINTYPE, MCH_SAW_LI.EXT_OUT)
         Else
            EgtSetMachiningParam(MCH_MP.LEADINTYPE, MCH_SAW_LI.EXT_CENT)
         End If
         UpdateMachiningPreview(m_MachiningList(nI).m_nId, True)
         m_MachiningList(nI).m_bStartAll = True
      End If
      ColorMachining(m_MachiningList(nI))
      Return True
   End Function

   Private Function AdjustEndCut(nI As Integer,
                                 Optional bAllForced As Boolean = False,
                                 Optional bAccForced As Boolean = False) As Boolean
      ' Verifico che l'estremo finale sia allungabile
      If Not m_MachiningList(nI).m_bCanEndAll Then Return False
      ' Eseguo allungamento o riporto allo standard
      EgtSetCurrMachining(m_MachiningList(nI).m_nId)
      Dim nLoPrev As Integer
      EgtGetMachiningParam(MCH_MP.LEADOUTTYPE, nLoPrev)
      If m_MachiningList(nI).m_bEndAll And Not bAllForced Then
         ' accorcio
         If nLoPrev = MCH_SAW_LO.EXT_OUT Then
            EgtSetMachiningParam(MCH_MP.LEADOUTTYPE, MCH_SAW_LO.OUT)
         Else
            EgtSetMachiningParam(MCH_MP.LEADOUTTYPE, MCH_SAW_LO.CENT)
         End If
         m_MachiningList(nI).m_bEndAll = False
      ElseIf m_MachiningList(nI).m_bEnabled And Not bAccForced Then
         ' allungo
         If nLoPrev = MCH_SAW_LO.OUT Then
            EgtSetMachiningParam(MCH_MP.LEADOUTTYPE, MCH_SAW_LO.EXT_OUT)
         Else
            EgtSetMachiningParam(MCH_MP.LEADOUTTYPE, MCH_SAW_LO.EXT_CENT)
         End If
         m_MachiningList(nI).m_bEndAll = True
      End If
      UpdateMachiningPreview(m_MachiningList(nI).m_nId, True)
      ColorMachining(m_MachiningList(nI))
      Return True
   End Function

   Private Sub OutCenStartBtn_Click(sender As Object, e As RoutedEventArgs) Handles OutCenStartBtn.Click
      If m_CurrFirstInd = -1 Then Return
      Dim bGenModif As Boolean = False
      For Index As Integer = m_CurrFirstInd To m_CurrLastInd
         If Not m_ItemList(Index).IsSelected Then
            Continue For
         End If
         Dim nI As Integer = m_ItemList(Index).Ind
         If m_MachiningList(nI).m_sLay = NAME_OUTLOOP Then
            EgtSetCurrMachining(m_MachiningList(nI).m_nId)
            Dim nLiPrev As Integer
            EgtGetMachiningParam(MCH_MP.LEADINTYPE, nLiPrev)
            If nLiPrev = MCH_SAW_LI.OUT Then
               ' accorcio
               EgtSetMachiningParam(MCH_MP.LEADINTYPE, MCH_SAW_LI.CENT)
               UpdateMachiningPreview(m_MachiningList(nI).m_nId, True)
               ModifyOtherLeadIn(nI, MCH_SAW_LI.CENT)
               ' ri-verifico interferenza
               EgtVerifyMachining(m_MachiningList(nI).m_nId, m_MachiningList(nI).m_nInterf)
            ElseIf nLiPrev = MCH_SAW_LI.EXT_OUT Then
               ' accorcio
               EgtSetMachiningParam(MCH_MP.LEADINTYPE, MCH_SAW_LI.EXT_CENT)
               UpdateMachiningPreview(m_MachiningList(nI).m_nId, True)
               ModifyOtherLeadIn(nI, MCH_SAW_LI.CENT)
            ElseIf nLiPrev = MCH_SAW_LI.CENT Then
               ' allungo
               EgtSetMachiningParam(MCH_MP.LEADINTYPE, MCH_SAW_LI.OUT)
               UpdateMachiningPreview(m_MachiningList(nI).m_nId, True)
               ModifyOtherLeadIn(nI, MCH_SAW_LI.OUT)
               ' ri-verifico interferenza
               EgtVerifyMachining(m_MachiningList(nI).m_nId, m_MachiningList(nI).m_nInterf)
            ElseIf nLiPrev = MCH_SAW_LI.EXT_CENT Then
               ' allungo
               EgtSetMachiningParam(MCH_MP.LEADINTYPE, MCH_SAW_LI.EXT_OUT)
               UpdateMachiningPreview(m_MachiningList(nI).m_nId, True)
               ModifyOtherLeadIn(nI, MCH_SAW_LI.OUT)
            End If
            ColorMachining(m_MachiningList(nI))
            ColorNumberArrow(nI)
            bGenModif = True
         End If
      Next
      ' Se modificato qualcosa
      If bGenModif Then
         EgtDraw()
         m_bModified = True
      End If
   End Sub

   Private Sub AllOutStartBtn_Click(sender As Object, e As RoutedEventArgs) Handles AllOutStartBtn.Click
      For nI As Integer = 0 To m_MachiningList.Count() - 1
         EgtSetCurrMachining(m_MachiningList(nI).m_nId)
         Dim nLiPrev As Integer
         EgtGetMachiningParam(MCH_MP.LEADINTYPE, nLiPrev)
         If nLiPrev = MCH_SAW_LI.CENT Then
            ' allungo
            EgtSetMachiningParam(MCH_MP.LEADINTYPE, MCH_SAW_LI.OUT)
            UpdateMachiningPreview(m_MachiningList(nI).m_nId, True)
            ModifyOtherLeadIn(nI, MCH_SAW_LI.OUT)
            ' ri-verifico interferenza
            EgtVerifyMachining(m_MachiningList(nI).m_nId, m_MachiningList(nI).m_nInterf)
         ElseIf nLiPrev = MCH_SAW_LI.EXT_CENT Then
            ' allungo
            EgtSetMachiningParam(MCH_MP.LEADINTYPE, MCH_SAW_LI.EXT_OUT)
            UpdateMachiningPreview(m_MachiningList(nI).m_nId, True)
            ModifyOtherLeadIn(nI, MCH_SAW_LI.OUT)
         End If
         ColorMachining(m_MachiningList(nI))
         ColorNumberArrow(nI)
      Next
      EgtDraw()
      ' Imposto flag di modifica
      m_bModified = True
   End Sub

   Private Sub AllCenStartBtn_Click(sender As Object, e As RoutedEventArgs) Handles AllCenStartBtn.Click
      For nI As Integer = 0 To m_MachiningList.Count() - 1
         EgtSetCurrMachining(m_MachiningList(nI).m_nId)
         Dim nLiPrev As Integer
         EgtGetMachiningParam(MCH_MP.LEADINTYPE, nLiPrev)
         If nLiPrev = MCH_SAW_LI.OUT Then
            ' accorcio
            EgtSetMachiningParam(MCH_MP.LEADINTYPE, MCH_SAW_LI.CENT)
            UpdateMachiningPreview(m_MachiningList(nI).m_nId, True)
            ModifyOtherLeadIn(nI, MCH_SAW_LI.CENT)
            ' ri-verifico interferenza
            EgtVerifyMachining(m_MachiningList(nI).m_nId, m_MachiningList(nI).m_nInterf)
         ElseIf nLiPrev = MCH_SAW_LI.EXT_OUT Then
            ' accorcio
            EgtSetMachiningParam(MCH_MP.LEADINTYPE, MCH_SAW_LI.EXT_CENT)
            UpdateMachiningPreview(m_MachiningList(nI).m_nId, True)
            ModifyOtherLeadIn(nI, MCH_SAW_LI.CENT)
         End If
         ColorMachining(m_MachiningList(nI))
         ColorNumberArrow(nI)
      Next
      EgtDraw()
      ' Imposto flag di modifica
      m_bModified = True
   End Sub

   Private Sub OutCenEndBtn_Click(sender As Object, e As RoutedEventArgs) Handles OutCenEndBtn.Click
      If m_CurrFirstInd = -1 Then Return
      Dim bGenModif As Boolean = False
      For Index As Integer = m_CurrFirstInd To m_CurrLastInd
         If Not m_ItemList(Index).IsSelected Then
            Continue For
         End If
         Dim nI As Integer = m_ItemList(Index).Ind
         If m_MachiningList(nI).m_sLay = NAME_OUTLOOP Then
            EgtSetCurrMachining(m_MachiningList(nI).m_nId)
            Dim nLoPrev As Integer
            EgtGetMachiningParam(MCH_MP.LEADOUTTYPE, nLoPrev)
            If nLoPrev = MCH_SAW_LO.OUT Then
               ' accorcio
               EgtSetMachiningParam(MCH_MP.LEADOUTTYPE, MCH_SAW_LO.CENT)
               UpdateMachiningPreview(m_MachiningList(nI).m_nId, True)
               ModifyOtherLeadOut(nI, MCH_SAW_LO.CENT)
               ' ri-verifico interferenza
               EgtVerifyMachining(m_MachiningList(nI).m_nId, m_MachiningList(nI).m_nInterf)
            ElseIf nLoPrev = MCH_SAW_LO.EXT_OUT Then
               ' accorcio
               EgtSetMachiningParam(MCH_MP.LEADOUTTYPE, MCH_SAW_LO.EXT_CENT)
               UpdateMachiningPreview(m_MachiningList(nI).m_nId, True)
               ModifyOtherLeadOut(nI, MCH_SAW_LO.CENT)
            ElseIf nLoPrev = MCH_SAW_LO.CENT Then
               ' allungo
               EgtSetMachiningParam(MCH_MP.LEADOUTTYPE, MCH_SAW_LO.OUT)
               UpdateMachiningPreview(m_MachiningList(nI).m_nId, True)
               ModifyOtherLeadOut(nI, MCH_SAW_LO.OUT)
               ' ri-verifico interferenza
               EgtVerifyMachining(m_MachiningList(nI).m_nId, m_MachiningList(nI).m_nInterf)
            ElseIf nLoPrev = MCH_SAW_LO.EXT_CENT Then
               ' allungo
               EgtSetMachiningParam(MCH_MP.LEADOUTTYPE, MCH_SAW_LO.EXT_OUT)
               UpdateMachiningPreview(m_MachiningList(nI).m_nId, True)
               ModifyOtherLeadOut(nI, MCH_SAW_LO.OUT)
            End If
            ColorMachining(m_MachiningList(nI))
            ColorNumberArrow(nI)
            bGenModif = True
         End If
      Next
      ' Se modificato qualcosa
      If bGenModif Then
         EgtDraw()
         m_bModified = True
      End If
   End Sub

   Private Sub AllOutEndBtn_Click(sender As Object, e As RoutedEventArgs) Handles AllOutEndBtn.Click
      For nI As Integer = 0 To m_MachiningList.Count() - 1
         EgtSetCurrMachining(m_MachiningList(nI).m_nId)
         Dim nLoPrev As Integer
         EgtGetMachiningParam(MCH_MP.LEADOUTTYPE, nLoPrev)
         If nLoPrev = MCH_SAW_LO.CENT Then
            ' allungo
            EgtSetMachiningParam(MCH_MP.LEADOUTTYPE, MCH_SAW_LO.OUT)
            UpdateMachiningPreview(m_MachiningList(nI).m_nId, True)
            ModifyOtherLeadOut(nI, MCH_SAW_LO.OUT)
            ' ri-verifico interferenza
            EgtVerifyMachining(m_MachiningList(nI).m_nId, m_MachiningList(nI).m_nInterf)
         ElseIf nLoPrev = MCH_SAW_LO.EXT_CENT Then
            ' allungo
            EgtSetMachiningParam(MCH_MP.LEADOUTTYPE, MCH_SAW_LO.EXT_OUT)
            UpdateMachiningPreview(m_MachiningList(nI).m_nId, True)
            ModifyOtherLeadOut(nI, MCH_SAW_LO.OUT)
         End If
         ColorMachining(m_MachiningList(nI))
         ColorNumberArrow(nI)
      Next
      EgtDraw()
      ' Imposto flag di modifica
      m_bModified = True
   End Sub

   Private Sub AllCenEndBtn_Click(sender As Object, e As RoutedEventArgs) Handles AllCenEndBtn.Click
      For nI As Integer = 0 To m_MachiningList.Count() - 1
         EgtSetCurrMachining(m_MachiningList(nI).m_nId)
         Dim nLoPrev As Integer
         EgtGetMachiningParam(MCH_MP.LEADOUTTYPE, nLoPrev)
         If nLoPrev = MCH_SAW_LO.OUT Then
            ' accorcio
            EgtSetMachiningParam(MCH_MP.LEADOUTTYPE, MCH_SAW_LO.CENT)
            UpdateMachiningPreview(m_MachiningList(nI).m_nId, True)
            ModifyOtherLeadOut(nI, MCH_SAW_LO.CENT)
            ' ri-verifico interferenza
            EgtVerifyMachining(m_MachiningList(nI).m_nId, m_MachiningList(nI).m_nInterf)
         ElseIf nLoPrev = MCH_SAW_LO.EXT_OUT Then
            ' accorcio
            EgtSetMachiningParam(MCH_MP.LEADOUTTYPE, MCH_SAW_LO.EXT_CENT)
            UpdateMachiningPreview(m_MachiningList(nI).m_nId, True)
            ModifyOtherLeadOut(nI, MCH_SAW_LO.CENT)
         End If
         ColorMachining(m_MachiningList(nI))
         ColorNumberArrow(nI)
      Next
      EgtDraw()
      ' Imposto flag di modifica
      m_bModified = True
   End Sub

   Private Sub AllExtendBtn_Click(sender As Object, e As RoutedEventArgs) Handles AllExtendBtn.Click
      Dim bModif As Boolean = False
      For nI As Integer = 0 To m_MachiningList.Count() - 1
         ' Provo ad entrambi gli estremi
         Dim bOneModif As Boolean = AdjustBothCuts(nI, True, False)
         ' Provo all'inizio
         If Not bOneModif Then bOneModif = AdjustStartCut(nI, True, False)
         ' Provo alla fine
         If Not bOneModif Then bOneModif = AdjustEndCut(nI, True, False)
         ' Aggiorno flag globale
         If bOneModif Then bModif = True
      Next
      ' Se modificato qualcosa
      If bModif Then
         EgtDraw()
         m_bModified = True
      End If
      ' Abilitazione bottone Next
      EnableButtons()
   End Sub

   Private Sub AllReduceBtn_Click(sender As Object, e As RoutedEventArgs) Handles AllReduceBtn.Click
      Dim bModif As Boolean = False
      For nI As Integer = 0 To m_MachiningList.Count() - 1
         ' Provo ad entrambi gli estremi
         Dim bOneModif As Boolean = AdjustBothCuts(nI, False, True)
         ' Provo all'inizio
         If Not bOneModif Then bOneModif = AdjustStartCut(nI, False, True)
         ' Provo alla fine
         If Not bOneModif Then bOneModif = AdjustEndCut(nI, False, True)
         ' Aggiorno flag globale
         If bOneModif Then bModif = True
      Next
      ' Se modificato qualcosa
      If bModif Then
         EgtDraw()
         m_bModified = True
      End If
      ' Abilitazione bottone Next
      EnableButtons()
   End Sub

   Private Sub ModifStartBtn_Click(sender As Object, e As RoutedEventArgs) Handles ModifStartBtn.Click
      ' abilito la finestra per inserire i valori solo per il primo elemento della lista (di default tutti gli altri oggetti assumono lo stesso valore)
      Dim bFirstInd As Boolean = True
      Dim bFirstMill As Boolean = True
      Dim bFirstWJ As Boolean = True
      ' elenco delle variabili : MCH_MY.SAWING/MCH_MY.MILLING
      Dim dUsal As Double = 0

      ' elenco delle variabili : MCH_MY.WATERJETTING
      Dim dWJAddLen As Double = 0
      Dim bWJLiHole As Boolean = True
      Dim nWJTangDist As Double = 0
      Dim nWJPerpDist As Double = 0
      Dim nWJLeadInType As Integer = 0

      ' Recupero la lavorazione corrente
      If m_CurrFirstInd = -1 Then Return
      Dim bGenModif As Boolean = False
      For Index As Integer = m_CurrFirstInd To m_CurrLastInd
         If Not m_ItemList(Index).IsSelected Then
            Continue For
         End If
         Dim nI As Integer = m_ItemList(Index).Ind
         Dim nOperId As Integer = m_MachiningList(nI).m_nId
         Dim nMachiningType As Integer = EgtGetOperationType(nOperId)
         ' Se taglio con lama
         If nMachiningType = MCH_MY.SAWING And
            (m_MachiningList(nI).m_bIsLine Or m_MachiningList(nI).m_dPrevAng > FL_ARC_ANG_MIN Or m_MachiningList(nI).m_sLay = NAME_ONPATH) Then
            ' leggo il valore salvato nella geometria
            Dim dOrigUsal As Double = 0
            EgtGetInfo(nOperId, INFO_MCH_USER_SAL, dOrigUsal)

            ' ------------------ INIZIO PREPARAZIONE TASTIERINO VIRTUALE ------------------
            If bFirstInd Then
               ' Dialogo richiesta valore
               Dim ValWnd As New EditValueWD(m_MainWindow, "SAW: " & EgtMsg(MSG_SPLITPAGEUC + 35))      ' Allungamento
               ValWnd.SetVal(dOrigUsal)
               If Not ValWnd.ShowDialog() Then Return
               ' carico il valore letto dal testierino virtuale
               dUsal = ValWnd.GetVal()
               ' comunico che ho letto il primo dato
               bFirstInd = False
            End If
            ' ------------------ FINE PREPARAZIONE TASTIERINO VIRTUALE ------------------
            Dim bRepeat As Boolean = False
            Do
               ' Se c'è limite alla lunghezza libera
               If m_MachiningList(nI).m_dStartFreeLen < FREELEN_INF Then
                  ' Recupero sicurezza in corner interno
                  Dim dCornerSafety As Double = Math.Max(GetPrivateProfileDouble(S_MACH_NEST, K_MACH_SAFE_LEN_INTCORNER, 1, m_MainWindow.GetMachIniFile()), 10 * EPS_SMALL)
                  ' Recupero lunghezza baffo del taglio
                  Dim nPvId As Integer = GDB_ID.NULL
                  EgtGetInfo(EgtGetFirstNameInGroup(nOperId, NAME_PREVIEW), INFO_PV_ONPART_ID, nPvId)
                  Dim dDT As Double = 0
                  EgtGetInfo(EgtGetFirstGroupInGroup(nPvId), "DT", dDT)
                  dUsal = Math.Min(dUsal, m_MachiningList(nI).m_dStartFreeLen - dDT - dCornerSafety)
               End If
               ' Modifica della lavorazione
               EgtSetCurrMachining(nOperId)
               Dim dAddLen As Double = 0
               EgtGetMachiningParam(MCH_MP.STARTADDLEN, dAddLen)
               ' verifico che non sia sull'angolo interno (altrimenti vieto la modifica)
               If dAddLen - dOrigUsal < -10 * EPS_SMALL Then
                  Return
               End If
               EgtSetMachiningParam(MCH_MP.STARTADDLEN, dAddLen + dUsal - dOrigUsal)
               EgtSetInfo(nOperId, INFO_MCH_USER_SAL, dUsal)
               bRepeat = Not UpdateMachiningPreview(m_MachiningList(nI).m_nId, True)
               If bRepeat Then
                  EgtSetMachiningParam(MCH_MP.STARTADDLEN, dOrigUsal)
                  EgtSetInfo(nOperId, INFO_MCH_USER_SAL, dOrigUsal)
                  dUsal = dOrigUsal
               End If
            Loop Until Not bRepeat

            ' verifico interferenza
            EgtVerifyMachining(m_MachiningList(nI).m_nId, m_MachiningList(nI).m_nInterf)
            ColorMachining(m_MachiningList(nI))
            ColorNumberArrow(nI)
            bGenModif = True

            ' se altrimenti fresatura sopra
         ElseIf nMachiningType = MCH_MY.MILLING And m_MachiningList(nI).m_sLay = NAME_ONPATH Then

            ' leggo il valore salvato nella geometria
            Dim dOrigUsal As Double = 0
            EgtGetInfo(nOperId, INFO_MCH_USER_SAL, dOrigUsal)
            If bFirstMill Then
               ' ------------------ INIZIO PREPARAZIONE TASTIERINO VIRTUALE ------------------
               ' Dialogo richiesta valore
               Dim ValWnd As New EditValueWD(m_MainWindow, "MILL: " & EgtMsg(MSG_SPLITPAGEUC + 35))      ' Allungamento
               ValWnd.SetVal(dOrigUsal)
               If Not ValWnd.ShowDialog() Then Return
               ' carico il valore letto dal testierino virtuale
               dUsal = ValWnd.GetVal()
               ' comunico che ho letto il primo dato
               bFirstMill = False
            End If
            ' ------------------ FINE PREPARAZIONE TASTIERINO VIRTUALE ------------------

            ' Modifica della lavorazione
            EgtSetCurrMachining(nOperId)
            Dim dAddLen As Double = 0
            EgtGetMachiningParam(MCH_MP.STARTADDLEN, dAddLen)
            EgtSetMachiningParam(MCH_MP.STARTADDLEN, dAddLen + dUsal - dOrigUsal)
            EgtSetInfo(nOperId, INFO_MCH_USER_SAL, dUsal)
            UpdateMachiningPreview(m_MachiningList(nI).m_nId, True)
            bGenModif = True

            ' se altrimenti getto d'acqua
         ElseIf nMachiningType = MCH_MY.WATERJETTING Then

            ' ------------------ INIZIO PREPARAZIONE TASTIERINO VIRTUALE ------------------
            If bFirstWJ Then
               ' Recupero i valori attuali della lavorazione
               Dim bOriginalIsLeadIn As Boolean = True
               Dim dOriginalAddLen As Double = 0
               Dim bOriginalLiHole As Boolean = True
               Dim nOriginalTangDist As Double = 0
               Dim nOriginalPerpDist As Double = 0
               Dim nOriginalLeadInType As Integer = 0
               EgtSetCurrMachining(nOperId)
               EgtGetMachiningParam(MCH_MP.STARTADDLEN, dOriginalAddLen)
               EgtGetMachiningParam(MCH_MP.LIHOLE, bOriginalLiHole)
               EgtGetMachiningParam(MCH_MP.LITANG, nOriginalTangDist)
               EgtGetMachiningParam(MCH_MP.LIPERP, nOriginalPerpDist)
               EgtGetMachiningParam(MCH_MP.LEADINTYPE, nOriginalLeadInType)
               ' Dialogo richiesta valori
               Dim ModifStartWnd As New ModifStartEndWD(m_MainWindow, "WJ: " & EgtMsg(MSG_SPLITPAGEUC + 33), bOriginalIsLeadIn, nOperId)      ' Inizio Modif.
               ModifStartWnd.SetElongation(dOriginalAddLen)
               ModifStartWnd.SetHole(bOriginalLiHole)
               ModifStartWnd.SetLiTangDist(nOriginalTangDist)
               ModifStartWnd.SetLiPerpDist(nOriginalPerpDist)
               ModifStartWnd.SetLeadInType(nOriginalLeadInType)
               If Not ModifStartWnd.ShowDialog() Then Return

               ' carico il valore letto dal testierino virtuale
               dWJAddLen = ModifStartWnd.GetElongation()
               bWJLiHole = ModifStartWnd.GetHole()
               nWJTangDist = ModifStartWnd.GetLiTangDist()
               nWJPerpDist = ModifStartWnd.GetLiPerpDist()
               nWJLeadInType = ModifStartWnd.GetLeadInType().Id
               ' comunico che ho letto il primo dato
               bFirstWJ = False
            End If
            ' ------------------ INIZIO PREPARAZIONE TASTIERINO VIRTUALE ------------------

            ' Modifica della lavorazione
            EgtSetCurrMachining(nOperId)
            EgtSetMachiningParam(MCH_MP.LIHOLE, bWJLiHole)
            EgtSetMachiningParam(MCH_MP.STARTADDLEN, dWJAddLen)
            EgtSetMachiningParam(MCH_MP.LEADINTYPE, nWJLeadInType)
            EgtSetMachiningParam(MCH_MP.LITANG, nWJTangDist)
            EgtSetMachiningParam(MCH_MP.LIPERP, nWJPerpDist)

            UpdateMachiningPreview(m_MachiningList(nI).m_nId, True)

            ' verifico interferenza
            EgtVerifyMachining(m_MachiningList(nI).m_nId, m_MachiningList(nI).m_nInterf)
            ColorMachining(m_MachiningList(nI))
            ColorNumberArrow(nI)
            bGenModif = True
         End If
      Next
      ' Se modificato qualcosa
      If bGenModif Then
         EgtDraw()
         m_bModified = True
      End If
   End Sub

   Private Sub ModifEndBtn_Click(sender As Object, e As RoutedEventArgs) Handles ModifEndBtn.Click
      ' abilito la finestra per inserire i valori solo per il primo elemento della lista (di default tutti gli altri oggetti assumono lo stesso valore)
      Dim bFirstInd As Boolean = True
      Dim bFirstMill As Boolean = True
      Dim bFirstWJ As Boolean = True
      ' elenco delle variabili : MCH_MY.SAWING/MCH_MY.MILLING
      Dim dUeal As Double = 0

      ' Recupero i valori attuali della lavorazione
      Dim dWJAddLen As Double = 0
      Dim WJLeadOutType As Integer = 0
      Dim nWJTangDist As Double = 0
      Dim nWJPerpDist As Double = 0

      ' Recupero la lavorazione corrente
      If m_CurrFirstInd = -1 Then Return
      Dim bGenModif As Boolean = False
      For Index As Integer = m_CurrFirstInd To m_CurrLastInd
         If Not m_ItemList(Index).IsSelected Then
            Continue For
         End If
         Dim nI As Integer = m_ItemList(Index).Ind
         Dim nOperId As Integer = m_MachiningList(nI).m_nId
         Dim nMachiningType As Integer = EgtGetOperationType(nOperId)
         ' Se taglio con lama
         If nMachiningType = MCH_MY.SAWING And
            (m_MachiningList(nI).m_bIsLine Or m_MachiningList(nI).m_dNextAng > FL_ARC_ANG_MIN Or m_MachiningList(nI).m_sLay = NAME_ONPATH) Then

            Dim dOrigUeal As Double = 0
            EgtGetInfo(nOperId, INFO_MCH_USER_EAL, dOrigUeal)

            ' ------------------ INIZIO PREPARAZIONE TASTIERINO VIRTUALE ------------------
            If bFirstInd Then
               ' Dialogo richiesta valore
               Dim ValWnd As New EditValueWD(m_MainWindow, "SAW: " & EgtMsg(MSG_SPLITPAGEUC + 35))      ' Allungamento
               ValWnd.SetVal(dOrigUeal)
               If Not ValWnd.ShowDialog() Then Return
               dUeal = ValWnd.GetVal()
               bFirstInd = False
            End If
            ' ------------------ FINE PREPARAZIONE TASTIERINO VIRTUALE ------------------
            Dim bRepeat As Boolean = False
            Do
               ' Se c'è limite alla lunghezza libera
               If m_MachiningList(nI).m_dEndFreeLen < FREELEN_INF Then
                  ' Recupero sicurezza in corner interno
                  Dim dCornerSafety As Double = Math.Max(GetPrivateProfileDouble(S_MACH_NEST, K_MACH_SAFE_LEN_INTCORNER, 1, m_MainWindow.GetMachIniFile()), 10 * EPS_SMALL)
                  ' Recupero lunghezza baffo del taglio
                  Dim nPvId As Integer = GDB_ID.NULL
                  EgtGetInfo(EgtGetFirstNameInGroup(nOperId, NAME_PREVIEW), INFO_PV_ONPART_ID, nPvId)
                  Dim dDT As Double = 0
                  EgtGetInfo(EgtGetFirstGroupInGroup(nPvId), "DT", dDT)
                  dUeal = Math.Min(dUeal, m_MachiningList(nI).m_dEndFreeLen - dDT - dCornerSafety)
               End If

               ' Modifica della lavorazione
               EgtSetCurrMachining(nOperId)
               Dim dAddLen As Double = 0
               EgtGetMachiningParam(MCH_MP.ENDADDLEN, dAddLen)
               If dAddLen - dOrigUeal < -10 * EPS_SMALL Then
                  Return
               End If
               EgtSetMachiningParam(MCH_MP.ENDADDLEN, dAddLen + dUeal - dOrigUeal)
               EgtSetInfo(nOperId, INFO_MCH_USER_EAL, dUeal)
               UpdateMachiningPreview(m_MachiningList(nI).m_nId, True)
               bRepeat = Not UpdateMachiningPreview(m_MachiningList(nI).m_nId, True)
               If bRepeat Then
                  EgtSetMachiningParam(MCH_MP.ENDADDLEN, dOrigUeal)
                  EgtSetInfo(nOperId, INFO_MCH_USER_EAL, dOrigUeal)
                  dUeal = dOrigUeal
               End If
            Loop Until Not bRepeat

            ' verifico interferenza
            EgtVerifyMachining(m_MachiningList(nI).m_nId, m_MachiningList(nI).m_nInterf)
            ColorMachining(m_MachiningList(nI))
            ColorNumberArrow(nI)
            bGenModif = True
            ' se altrimenti fresatura sopra
         ElseIf nMachiningType = MCH_MY.MILLING And m_MachiningList(nI).m_sLay = NAME_ONPATH Then

            Dim dOrigUeal As Double = 0
            EgtGetInfo(nOperId, INFO_MCH_USER_EAL, dOrigUeal)
            ' ------------------ INIZIO PREPARAZIONE TASTIERINO VIRTUALE ------------------
            If bFirstMill Then
               ' Dialogo richiesta valore
               Dim ValWnd As New EditValueWD(m_MainWindow, "MILL: " & EgtMsg(MSG_SPLITPAGEUC + 35))      ' Allungamento
               ValWnd.SetVal(dOrigUeal)
               If Not ValWnd.ShowDialog() Then Return
               dUeal = ValWnd.GetVal()
               bFirstMill = False
            End If
            ' ------------------ FINE PREPARAZIONE TASTIERINO VIRTUALE ------------------
            ' Modifica della lavorazione
            EgtSetCurrMachining(nOperId)
            Dim dAddLen As Double = 0
            EgtGetMachiningParam(MCH_MP.ENDADDLEN, dAddLen)
            EgtSetMachiningParam(MCH_MP.ENDADDLEN, dAddLen + dUeal - dOrigUeal)
            EgtSetInfo(nOperId, INFO_MCH_USER_EAL, dUeal)
            UpdateMachiningPreview(m_MachiningList(nI).m_nId, True)
            bGenModif = True
            ' se altrimenti getto d'acqua
         ElseIf nMachiningType = MCH_MY.WATERJETTING Then

            If bFirstWJ Then
               ' Recupero i valori attuali della lavorazione
               Dim dAddLen As Double = 0
               Dim LeadOutType As Integer = 0
               Dim nTangDist As Double = 0
               Dim nPerpDist As Double = 0
               EgtSetCurrMachining(nOperId)
               EgtGetMachiningParam(MCH_MP.ENDADDLEN, dAddLen)
               EgtGetMachiningParam(MCH_MP.LEADOUTTYPE, LeadOutType)
               EgtGetMachiningParam(MCH_MP.LOTANG, nTangDist)
               EgtGetMachiningParam(MCH_MP.LOPERP, nPerpDist)
               ' Dialogo richiesta valore
               Dim ModifStartWnd As New ModifStartEndWD(m_MainWindow, "WJ: " & EgtMsg(MSG_SPLITPAGEUC + 34), False, nOperId)      ' Fine Modif.
               ModifStartWnd.SetElongation(dAddLen)
               ModifStartWnd.SetLeadOutType(LeadOutType)
               ModifStartWnd.SetLoTangDist(nTangDist)
               ModifStartWnd.SetLoPerpDist(nPerpDist)
               If Not ModifStartWnd.ShowDialog() Then Return
               dWJAddLen = ModifStartWnd.GetElongation()
               WJLeadOutType = ModifStartWnd.GetLeadOutType().Id
               nWJTangDist = ModifStartWnd.GetLoTangDist()
               nWJPerpDist = ModifStartWnd.GetLoPerpDist()
               bFirstWJ = False
            End If

            ' Modifica della lavorazione
            EgtSetCurrMachining(nOperId)
            EgtSetMachiningParam(MCH_MP.ENDADDLEN, dWJAddLen)
            EgtSetMachiningParam(MCH_MP.LEADOUTTYPE, WJLeadOutType)
            EgtSetMachiningParam(MCH_MP.LOTANG, nWJTangDist)
            EgtSetMachiningParam(MCH_MP.LOPERP, nWJPerpDist)
            UpdateMachiningPreview(m_MachiningList(nI).m_nId, True)

            ' verifico interferenza
            EgtVerifyMachining(m_MachiningList(nI).m_nId, m_MachiningList(nI).m_nInterf)
            ColorMachining(m_MachiningList(nI))
            ColorNumberArrow(nI)
            bGenModif = True
         End If
      Next
      ' Se modificato qualcosa
      If bGenModif Then
         EgtDraw()
         m_bModified = True
      End If
   End Sub

   Private Sub InvertBtn_Click(sender As Object, e As RoutedEventArgs) Handles InvertBtn.Click
      If m_CurrFirstInd = -1 Then Return
      For Index As Integer = m_CurrFirstInd To m_CurrLastInd
         If Not m_ItemList(Index).IsSelected Then
            Continue For
         End If
         Dim nI As Integer = m_ItemList(Index).Ind
         ' Si possono invertire solo i tagli di lama
         If m_MachiningList(nI).m_nType <> MCH_OY.SAWING Then Continue For
         ' Non si possono invertire i tagli di lama inclinati
         If Math.Abs(m_MachiningList(nI).m_dSideAng) > 0.1 Then Continue For
         ' Se abilitata inversione automatica e quindi non invertito
         If m_MachiningList(nI).m_bEnableInvert Then
            ' Inverto e disabilito inversione automatica
            If CamAuto.InvertVerticalCut(m_MachiningList(nI).m_nId) Then
               m_MachiningList(nI).m_bInvert = True
               m_MachiningList(nI).m_vtDir = -m_MachiningList(nI).m_vtDir
               m_MachiningList(nI).m_bEnableInvert = False
               SwapStartEndData(nI)
               ResetEnableInvert(m_MachiningList(nI).m_nEntId)
               EgtErase(m_MachiningList(nI).m_nArrId)
               NumberDirectionMachining(nI, False)
               EgtDraw()
            End If
            ' se altrimenti disabilitata inversione automatica e invertito
         ElseIf m_MachiningList(nI).m_bInvert Then
            ' Tolgo inversione e lascio disabilitazione inv. autom.
            If CamAuto.InvertVerticalCut(m_MachiningList(nI).m_nId) Then
               m_MachiningList(nI).m_bInvert = False
               m_MachiningList(nI).m_vtDir = -m_MachiningList(nI).m_vtDir
               SwapStartEndData(nI)
               EgtErase(m_MachiningList(nI).m_nArrId)
               NumberDirectionMachining(nI, False)
               EgtDraw()
            End If
            ' altrimenti disabilitata inversione automatica e non invertito
         Else
            ' Abilito inversione automatica e lascio non invertito
            m_MachiningList(nI).m_bEnableInvert = True
            SetEnableInvert(m_MachiningList(nI).m_nEntId)
            EgtErase(m_MachiningList(nI).m_nArrId)
            NumberDirectionMachining(nI, False)
            EgtDraw()
         End If
      Next
   End Sub

   Private Sub PauseBtn_Click(sender As Object, e As RoutedEventArgs) Handles PauseBtn.Click
      If m_CurrFirstInd = -1 Then Return
      Dim bGenModif As Boolean = False
      For Index As Integer = m_CurrFirstInd To m_CurrLastInd
         If Not m_ItemList(Index).IsSelected Then
            Continue For
         End If
         Dim nI As Integer = m_ItemList(Index).Ind
         Dim nOperId As Integer = m_MachiningList(nI).m_nId
         If GetPause(nOperId) Then
            ResetPause(nOperId)
            m_MachiningList(nI).m_bPause = False
            RemovePauseText(m_ItemList(Index).Name)
         Else
            SetPause(nOperId)
            m_MachiningList(nI).m_bPause = True
            AddPauseText(m_ItemList(Index).Name)
         End If
      Next
   End Sub

   Private Sub PrevBtn_Click(sender As Object, e As RoutedEventArgs) Handles PrevBtn.Click
      ' Dichiaro solo visualizzazione
      m_bShow = True
      ' Esco 
      ExitSplit(False)
      ' Torno alla fase precedente
      EgtSetCurrPhase(EgtGetCurrPhase() - 1)
      ' Reimposto la precedente
      SplitPageUC_Loaded(Nothing, Nothing)
   End Sub

   Private Sub NextBtn_Click(sender As Object, e As RoutedEventArgs) Handles NextBtn.Click
      m_bToNext = True
      m_MainWindow.m_CadCutPageUC.CadCutPageGrid.Children.Remove(m_MainWindow.m_CadCutPageUC.m_SplitPage)
      m_MainWindow.m_CadCutPageUC.CadCutPageGrid.Children.Add(m_MainWindow.m_CadCutPageUC.m_MoveRawPartPage)
      m_MainWindow.m_CadCutPageUC.m_CadCutMode = CadCutPageUC.CadCutModes.MoveRawPart
   End Sub

   Private Sub AutoBtn_Click(sender As Object, e As RoutedEventArgs) Handles AutoBtn.Click
      ' Con movimento manuale, non disponibile movimento automatico
      If m_bByHand Then Return
      ' Elimino evidenziazione e numerazione
      RemoveMarkAndNumbers()
      ' Calcolo automatico
      Dim bFinished As Boolean = False
      Dim bOk As Boolean = CalculateOnePhaseSplitAuto(bFinished)
      If Not bOk Then
         m_MainWindow.m_CurrentProjectPageUC.SetWarningMessage(EgtMsg(90350))     'Calcolo automatico non riuscito
      End If
      m_bModified = True
      ' Ricarico
      SplitPageUC_Loaded(Nothing, Nothing)
   End Sub

   Private Sub RestartBtn_Click(sender As Object, e As RoutedEventArgs) Handles RestartBtn.Click
      ' Se fase corrente è la prima, imposto partenza normale
      If m_nCurrPhase = 1 Then
         m_MainWindow.m_CurrentProjectPageUC.ResetProjectNcRestart()
         ' Altrimenti, imposto la ripartenza dalla fase corrente
      Else
         m_MainWindow.m_CurrentProjectPageUC.SetProjectNcRestart(m_nCurrPhase)
         m_MainWindow.m_CurrentProjectPageUC.SetInfoMessage(EgtMsg(MSG_SPLITPAGEUC + 19) & " (" & m_nCurrPhase.ToString() & ")")
      End If
   End Sub

   Private Sub ModifyBtn_Click(sender As Object, e As RoutedEventArgs) Handles ModifyBtn.Click
      ' Dichiaro non più solo visualizzazione
      m_bShow = False
      ' Rimuovo eventuale restart
      m_MainWindow.m_CurrentProjectPageUC.ResetProjectNcRestart()
      ' Elimino le fasi successive alla corrente
      While EgtGetPhaseCount() > m_nCurrPhase
         RemoveLastPhase()
      End While
      ' Aggiorno le lavorazioni (eliminato sort per lasciare ordine immutato)
      If m_MainWindow.m_CurrentMachine.WaterJettingActive Then ResetAllMachinings()
      m_MainWindow.m_CurrentProjectPageUC.SetOrderMachiningFlag()
      If m_MainWindow.m_CurrentMachine.WaterJettingActive Then
         Dim bModif As Boolean = TestAllMachiningsForStrict()
         If bModif Then m_MainWindow.m_CurrentProjectPageUC.SetWarningMessage(EgtMsg(90321)) 'Ridotte alcune lavorazioni per evitare interferenze
      End If
      ' Visualizzo solo anteprime di lavorazioni della fase
      ShowOnePhaseMachiningPreview(m_nCurrPhase)
      ' Nascondo gli eventuali percorsi di lavorazione
      HideAllMachinings()
      ' Preparo la lista delle lavorazioni e le disabilito
      CalculateSplitMachList(m_nCurrPhase, m_MachiningList)
      m_nCountSawing = 0
      m_nCountWaterjetting = 0
      m_nCountOtherMachining = 0
      For nI As Integer = 0 To m_MachiningList.Count() - 1
         m_MachiningList(nI).m_bEnabled = False
         ' conto il numero di tipi di lavorazioni
         CountMachiningType(m_MachiningList(nI), m_nCountSawing, m_nCountWaterjetting, m_nCountOtherMachining)
      Next
      ' Aggiorno visualizzazione delle lavorazioni
      EgtEmptyGroup(m_nNbrGrpId)
      For nI As Integer = 0 To m_MachiningList.Count() - 1
         ' sistemo colore
         ColorMachining(m_MachiningList(nI))
         ' assegno numerazione
         NumberDirectionMachining(nI)
      Next
      ' Preparo la lista degli Item
      ShowMachiningList()
      ' Aggiorno visualizzazione
      EgtDraw()
      ' Aggiono abilitazione bottoni
      EnableButtons()
   End Sub

   Private Sub SplitPageUC_Unloaded(sender As Object, e As EventArgs) Handles Me.Unloaded
      m_bActive = False
      m_MainWindow.m_CurrentProjectPageUC.ClearMessage()
      ExitSplit(Not m_bToNext)
      EgtDraw()
   End Sub

   Friend Sub ExitSplit(Optional bTrueExit As Boolean = True)
      ' Rimuovo evidenziazione e numeri
      RemoveMarkAndNumbers()
      ' Ripristino colori lavorazioni
      EgtDisableModified()
      For i As Integer = 0 To m_MachiningList.Count() - 1
         ColorMachining(m_MachiningList(i), True)
      Next
      EgtEnableModified()
      ' se modificato salvo ordine e stato delle lavorazioni
      If m_bModified Then
         ' Al primo posto deve rimanere la disposizione della fase
         Dim nFirstOperId As Integer = EgtGetPhaseDisposition(m_nCurrPhase)
         For i As Integer = m_ItemList.Count() - 1 To 0 Step -1
            Dim nI As Integer = m_ItemList(i).Ind
            Dim nMchId As Integer = m_MachiningList(nI).m_nId
            EgtRelocate(nMchId, nFirstOperId, GDB_POS.AFTER)
            If m_MachiningList(nI).m_bEnabled Then
               EgtSetOperationMode(m_MachiningList(nI).m_nId, True)
               EgtRemoveInfo(m_MachiningList(nI).m_nId, INFO_MCH_USER_OFF)
            Else
               EgtSetOperationMode(m_MachiningList(nI).m_nId, False)
               EgtSetInfo(m_MachiningList(nI).m_nId, INFO_MCH_USER_OFF, True)
            End If
         Next
         ' dichiaro ordine salvato
         m_MainWindow.m_CurrentProjectPageUC.SetOrderMachiningFlag()
      End If
      ' Affondamento ridotto
      Dim dReducedDepth As Double = GetPrivateProfileDouble(S_MACH_NEST, K_MACH_REDUCEDDEPTH, 1, m_MainWindow.GetMachIniFile())
      ' Restringo o rialzo lavorazioni abilitate ma con interferenza
      Dim bModified As Boolean = False
      For Each Mach As SplitMach In m_MachiningList
         If Mach.m_bEnabled And Mach.m_nInterf <> FMI_TYPE.NONE Then
            If AdjustMachining(Mach.m_nId, Mach.m_nInterf, dReducedDepth) Then
               bModified = True
            End If
         End If
      Next
      If bTrueExit Then
         ' ritorno a fase 1
         EgtSetCurrPhase(1)
         ' Ripristino visualizzazione preview lavorazioni
         ShowAllPhasesMachiningPreview()
      End If
      If bModified Then
         m_MainWindow.m_CurrentProjectPageUC.SetWarningMessage(EgtMsg(90321))     'Ridotte alcune lavorazioni per evitare interferenze
      End If
   End Sub

   Friend Function GetDisabledCutsCount() As Integer
      ' Determino il numero di tagli disabilitati
      Dim nCount As Integer = 0
      For nI As Integer = 0 To m_MachiningList.Count() - 1
         If Not m_MachiningList(nI).m_bEnabled Then
            nCount += 1
         End If
      Next
      Return nCount
   End Function

   Friend Function GetSplitCutsCount() As Integer
      ' Determino il numero di tagli passanti almeno da un lato
      Dim nCount As Integer = 0
      For nI As Integer = 0 To m_MachiningList.Count() - 1
         If m_MachiningList(nI).m_bEnabled And
            (m_MachiningList(nI).m_bStartAll Or m_MachiningList(nI).m_bEndAll) Then
            nCount += 1
         End If
      Next
      Return nCount
   End Function

   Friend Sub GetSplitCuts(ByRef Cuts() As Integer)
      ' Determino l'elenco dei tagli passanti almeno da un lato
      Dim MyCuts As New List(Of Integer)
      For nI As Integer = 0 To m_MachiningList.Count() - 1
         If m_MachiningList(nI).m_bEnabled And
            (m_MachiningList(nI).m_bStartAll Or m_MachiningList(nI).m_bEndAll) Then
            MyCuts.Add(m_MachiningList(nI).m_nId)
         End If
      Next
      Cuts = MyCuts.ToArray()
   End Sub

   Friend Sub GetEnabledCuts(ByRef Cuts() As Integer)
      ' Determino l'elenco dei tagli abilitati
      Dim MyCuts As New List(Of Integer)
      For nI As Integer = 0 To m_MachiningList.Count() - 1
         If m_MachiningList(nI).m_bEnabled And
            ( m_MachiningList(nI).m_sLay = NAME_OUTLOOP Or m_MachiningList(nI).m_sLay = NAME_INLOOP) Then
            MyCuts.Add(m_MachiningList(nI).m_nId)
         End If
      Next
      Cuts = MyCuts.ToArray()
   End Sub

   Private Sub EnableButtons()
      ' Per bottone PREV
      PrevBtn.IsEnabled = (m_nCurrPhase > 1)
      ' Per bottone NEXT
      ' Se abilitato manipolatore e non è con waterjet
      If ( m_MainWindow.GetKeyOption(MainWindow.KEY_OPT.MAN_MANIP) Or
           m_MainWindow.GetKeyOption(MainWindow.KEY_OPT.AUTO_MANIP)) And
           Not m_MainWindow.m_CurrentMachine.bWaterJetting Then
         ' Se in modifica
         If Not m_bShow Then
            ' Se allontanamento perpendicolare
            If m_bByHand Then
               m_bOnAuxTab = False
               ' Ci deve essere almeno 1 taglio disabilitato e 1 e 1 solo passante
               NextBtn.IsEnabled = (GetDisabledCutsCount() > 0 And GetSplitCutsCount() = 1)
            ' Altrimenti
            Else
               ' movimento standard sulla tavola (almeno un taglio disabilitato)
               Dim bStdTab As Boolean = (GetDisabledCutsCount() > 0)
               ' movimento su tavola di scarico
               m_bOnAuxTab = Not bStdTab AndAlso (m_nCurrPhase = EgtGetPhaseCount() And m_bEnableOnAuxTab)
               ' movimento finale sulla tavola
               Dim bFinalMoveTab As Boolean = m_MainWindow.m_CurrentMachine.bRawFinalMove
               ' Deve essere permesso almeno un tipo di movimento
               NextBtn.IsEnabled = bStdTab Or m_bOnAuxTab Or bFinalMoveTab
            End If
         ' altrimenti sto solo visualizzando
         Else
            ' movimento su tavola di scarico
            m_bOnAuxTab = (m_nCurrPhase = EgtGetPhaseCount() - 1 And m_bEnableOnAuxTab And EgtGetOperationType(EgtGetLastOperation()) = MCH_OY.DISP)
            ' Non deve essere l'ultima fase
            NextBtn.IsEnabled = (m_nCurrPhase < EgtGetPhaseCount())
         End If
      Else
         NextBtn.IsEnabled = False
      End If
      ' Per bottone MODIFY
      ModifyBtn.IsEnabled = m_bShow
      ' Per bottone AUTO
      AutoBtn.Visibility = If(m_bShow, Windows.Visibility.Hidden, Windows.Visibility.Visible)
      AutoBtn.IsEnabled = Not m_bShow And ((GetDisabledCutsCount() > 0 Or m_nCurrPhase = 1) And Not m_bByHand)
      ' Per bottone RESTART
      RestartBtn.Visibility = If(m_bShow, Windows.Visibility.Visible, Windows.Visibility.Hidden)
      RestartBtn.IsEnabled = m_bShow And m_MainWindow.m_CurrentMachine.bEnableRestart
      ' Altri bottoni
      MoveUpBtn.IsEnabled = Not m_bShow
      MoveDownBtn.IsEnabled = Not m_bShow
      OnOffBtn.IsEnabled = Not m_bShow
      AllOnBtn.IsEnabled = Not m_bShow
      AllOffBtn.IsEnabled = Not m_bShow
      CutBtn.IsEnabled = Not m_bShow
      CutStartBtn.IsEnabled = Not m_bShow
      CutEndBtn.IsEnabled = Not m_bShow
      OutCenStartBtn.IsEnabled = Not m_bShow
      AllOutStartBtn.IsEnabled = Not m_bShow
      AllCenStartBtn.IsEnabled = Not m_bShow
      OutCenEndBtn.IsEnabled = Not m_bShow
      AllOutEndBtn.IsEnabled = Not m_bShow
      AllCenEndBtn.IsEnabled = Not m_bShow
      AllExtendBtn.IsEnabled = Not m_bShow
      AllReduceBtn.IsEnabled = Not m_bShow
      ModifStartBtn.IsEnabled = Not m_bShow
      ModifEndBtn.IsEnabled = Not m_bShow
      InvertBtn.IsEnabled = Not m_bShow
      PauseBtn.IsEnabled = Not m_bShow And m_MainWindow.m_CurrentMachine.bEnablePause

      ' nascondo i comandi che non devono essere visualizzati in funzione delle lavorazioni attive
      If m_nCountSawing = 0 And (m_nCountWaterjetting > 0 Or m_nCountOtherMachining) Then
         VisibilityButtonFromMachinig(MCH_OY.WATERJETTING)
      Else
         VisibilityButtonFromMachinig(MCH_OY.SAWING)
      End If

   End Sub

   Private Sub VerifyHomogenousMachining(ItemList As List(Of NameIdLsBxItem))
      If IsNothing(ItemList) OrElse ItemList.Count = 0 Then
         m_MainWindow.m_CurrentProjectPageUC.ClearMessage()
         Return
      End If
      Dim nSawing As Integer = 0
      Dim nWaterjetting As Integer = 0
      Dim nOtherMachining As Integer = 0
      ' conto il numero di tipi di lavprazioni
      For Each Item As NameIdLsBxItem In ItemList
         If Item.Type = MCH_OY.SAWING Then
            nSawing += 1
         ElseIf Item.Type = MCH_OY.WATERJETTING Then
            nWaterjetting += 1
         Else
            nOtherMachining += 1
         End If
      Next
      ' verifico se le lavorazioni sono omeogenee
      If nSawing > 0 And (nWaterjetting > 0 Or nOtherMachining > 0) Then
         m_bAreHomogeneous = False
         VisibilityButtonFromMachinig(MCH_OY.SAWING)
      ElseIf nSawing = 0 And nOtherMachining > 0 And nWaterjetting > 0 Then
         m_bAreHomogeneous = False
         VisibilityButtonFromMachinig(MCH_OY.WATERJETTING)
      Else
         VisibilityButtonFromMachinig(ItemList(0).Type)
         m_bAreHomogeneous = True
      End If
      ' eventualmente stampo messaggio
      If Not m_bAreHomogeneous Then
         m_MainWindow.m_CurrentProjectPageUC.ClearMessage()
         m_MainWindow.m_CurrentProjectPageUC.SetWarningMessage("Lavorazioni non omogenee")
      Else
         m_MainWindow.m_CurrentProjectPageUC.ClearMessage()
      End If
   End Sub

   Private Function VerifyContinuity(ItemList As List(Of NameIdLsBxItem)) As Boolean
      If ItemList.Count < 2 Then Return True
      Dim bContigus As Boolean = False
      For Index As Integer = 0 To ItemList.Count - 2
         If ItemList(Index).Ind = ItemList(Index + 1).Ind + 1 Or ItemList(Index).Ind = ItemList(Index + 1).Ind - 1 Then
            bContigus = True
         Else
            bContigus = False
            Exit For
         End If
      Next
      Return bContigus
   End Function

   Private Sub GetCurrSelection()
      For Each Item As NameIdLsBxItem In m_ItemList
         Item.IsSelected = False
      Next
      ' recupero il numero di elementi selezionati
      Dim nCount As Integer = MachiningLsBx.SelectedItems.Count
      For Index As Integer = 0 To nCount - 1
         Dim Local_ItemTemplate As NameIdLsBxItem = MachiningLsBx.SelectedItems(Index)
         For Each Item As NameIdLsBxItem In m_ItemList
            If Item.Ind = Local_ItemTemplate.Ind Then
               Item.IsSelected = True
               Exit For
            End If
         Next
      Next
   End Sub

   Private Sub VisibilityButtonFromMachinig(ByVal Type As Integer)
      If Type <> MCH_OY.SAWING Then
         CutBtn.Visibility = Visibility.Hidden
         CutStartBtn.Visibility = Visibility.Hidden
         CutEndBtn.Visibility = Visibility.Hidden

         OutCenStartBtn.Visibility = Visibility.Hidden
         OutCenEndBtn.Visibility = Visibility.Hidden
         InvertBtn.Visibility = Visibility.Hidden
         PauseBtn.Visibility = Visibility.Hidden
         AllOutStartBtn.Visibility = Visibility.Hidden
         AllCenStartBtn.Visibility = Visibility.Hidden
         AllOutEndBtn.Visibility = Visibility.Hidden
         AllCenEndBtn.Visibility = Visibility.Hidden
         AllExtendBtn.Visibility = Visibility.Hidden
         AllReduceBtn.Visibility = Visibility.Hidden
      Else
         CutBtn.Visibility = Visibility.Visible
         CutStartBtn.Visibility = Visibility.Visible
         CutEndBtn.Visibility = Visibility.Visible

         OutCenStartBtn.Visibility = Visibility.Visible
         OutCenEndBtn.Visibility = Visibility.Visible
         InvertBtn.Visibility = Visibility.Visible
         PauseBtn.Visibility = Visibility.Visible
         AllOutStartBtn.Visibility = Visibility.Visible
         AllCenStartBtn.Visibility = Visibility.Visible
         AllOutEndBtn.Visibility = Visibility.Visible
         AllCenEndBtn.Visibility = Visibility.Visible
         AllExtendBtn.Visibility = Visibility.Visible
         AllReduceBtn.Visibility = Visibility.Visible
      End If
   End Sub

   Private Function ModifyOtherLeadIn(nI As Integer, nLiOthType As Integer) As Boolean
      ' Modifico l'attacco delle lavorazioni inglobate
      For Each nMchId As Integer In m_MachiningList(nI).m_vOthId
         EgtSetCurrMachining(nMchId)
         EgtSetMachiningParam(MCH_MP.LEADINTYPE, nLiOthType)
      Next
      Return True
   End Function

   Private Function ModifyOtherLeadOut(nI As Integer, nLoOthType As Integer) As Boolean
      ' Modifico l'uscita delle lavorazioni inglobate
      For Each nMchId As Integer In m_MachiningList(nI).m_vOthId
         EgtSetCurrMachining(nMchId)
         EgtSetMachiningParam(MCH_MP.LEADOUTTYPE, nLoOthType)
      Next
      Return True
   End Function

   Private Sub NumberDirectionMachining( nI As Integer, Optional bNumber As Boolean = True)
      EgtDisableModified()
      ' Determino se seconda lavorazione
      Dim sName As String = String.Empty
      EgtGetName(m_MachiningList(nI).m_nId, sName)
      Dim b2ndLav As Boolean = sName.Contains("_") Or sName.Contains("Drip")
      ' Ingombro complessivo della lavorazione
      Dim ptMin, ptMax As Point3d
      If Not BoxFromMachining(nI, ptMin, ptMax) Then Return
      ' Metto il numero nel centro
      Dim dRadXY = Point3d.DistXY(ptMin, ptMax)
      Dim dHtxt As Double = 50
      Dim dRat As Double = 0.75
      If dRadXY < 200 Then
         dHtxt = 40
         dRat = 0.6
      ElseIf dRadXY < 25 Then
         dHtxt = 25
         dRat = 0.5
      End If
      Dim vtXY As Vector3d = ptMax - ptMin
      vtXY.Normalize()
      Dim ptCen As Point3d = Point3d.Media(ptMin, ptMax) + vtXY * If(Not b2ndLav, -0.8, 0.8) * dHtxt
      ptCen.z = ptMax.z + 1
      If bNumber Then
         Dim nNbrId As Integer = EgtCreateTextAdv( m_nNbrGrpId, ptCen, 0, (nI + 1).ToString(), "",
                                                   300, False, dHtxt, dRat, 0, INS_POS.MC)
         m_MachiningList(nI).m_nNbrId = nNbrId
         ' Aggiungo a numero info con identificativo della lavorazione e viceversa
         EgtSetInfo( nNbrId, "MId", m_MachiningList(nI).m_nId)
         EgtSetInfo( m_MachiningList(nI).m_nId, "NbrId", nNbrId)
      End If
      ' Se taglio con lama, metto la direzione accanto al numero
      If m_MachiningList(nI).m_nType = MCH_OY.SAWING Then
         Dim ptStart As New Point3d( ptCen + m_MachiningList(nI).m_vtDir * dHtxt)
         Dim vtDir As New Vector3d( m_MachiningList(nI).m_vtDir) 
         Dim bTwin As Boolean = ( Not m_MachiningList(nI).m_bEnableInvert  OrElse  Math.Abs( m_MachiningList(nI).m_dSideAng) > 0.1) 
         Dim nArrId As Integer = AddMachiningDirection( ptStart, vtDir, dHtxt, bTwin)
         m_MachiningList(nI).m_nArrId = nArrId
         ' Aggiungo a freccia info con identificativo della lavorazione e viceversa
         EgtSetInfo( nArrId, "MId", m_MachiningList(nI).m_nId)
         EgtSetInfo( m_MachiningList(nI).m_nId, "ArrId", nArrId)
      Else
         m_MachiningList(nI).m_nArrId = GDB_ID.NULL
      End If
      ' Assegno colore a numero e freccia
      ColorNumberArrow( nI)
      EgtEnableModified()
   End Sub

   Private Function BoxFromMachining(nI As Integer, ByRef ptMin As Point3d, ByRef ptMax As Point3d) As Boolean
      If nI < 0 Then Return False
      ' Lavorazione principale
      If Not BoxFromSingleMachining(m_MachiningList(nI).m_nId, ptMin, ptMax) Then
         Return False
      End If
      ' Eventuali lavorazioni inglobate
      For Each nId As Integer In m_MachiningList(nI).m_vOthId
         Dim ptMchMin, ptMchMax As Point3d
         If BoxFromSingleMachining(nId, ptMchMin, ptMchMax) Then
            ptMin.x = Math.Min(ptMin.x, ptMchMin.x)
            ptMin.y = Math.Min(ptMin.y, ptMchMin.y)
            ptMin.z = Math.Min(ptMin.z, ptMchMin.z)
            ptMax.x = Math.Max(ptMax.x, ptMchMax.x)
            ptMax.y = Math.Max(ptMax.y, ptMchMax.y)
            ptMax.z = Math.Max(ptMax.z, ptMchMax.z)
         End If
      Next
      Return True
   End Function

   Private Function BoxFromSingleMachining(nOperId As Integer, ByRef ptMin As Point3d, ByRef ptMax As Point3d) As Boolean
      ' Recupero il preview della lavorazione
      Dim nPvId As Integer = GDB_ID.NULL
      EgtGetInfo(EgtGetFirstNameInGroup(nOperId, NAME_PREVIEW), INFO_PV_ONPART_ID, nPvId)
      Return EgtGetBBoxGlob(nPvId, GDB_BB.STANDARD, ptMin, ptMax)
   End Function

   Private Function AddMachiningDirection( ptStart As Point3d, vtDir As Vector3d, dLen As Double, bTwin As Boolean) As Integer
      Dim dArrX As Double = dLen * Math.Cos( 30 * Math.PI / 180)
      Dim dArrY As Double = dLen * Math.Sin( 30 * Math.PI / 180)
      Dim nTmpId As Integer = EgtCreateLine( m_nNbrGrpId, Point3d.ORIG() + dArrY * Vector3d.Y_AX(), Point3d.ORIG() + dArrX * Vector3d.X_AX())
      Dim nCrvId As Integer = EgtCreateCurveCompo( m_nNbrGrpId, nTmpId, True)
      EgtAddCurveCompoLine( nCrvId, Point3d.ORIG() - dArrY * Vector3d.Y_AX())
      If bTwin Then
         EgtAddCurveCompoLine( nCrvId, Point3d.ORIG() + 2 * dArrX * Vector3d.X_AX())
         EgtCloseCurveCompo( nCrvId)
      End If
      Dim frLoc As New Frame3d( ptStart, vtDir, Vector3d.Z_AX() ^ vtDir, Vector3d.Z_AX())
      EgtTransform( nCrvId, frLoc)
      Return nCrvId
   End Function

   Private Sub MarkMachining(nI As Integer, bMark As Boolean)
      If nI < 0 Then Return
      Dim nOperId As Integer = m_MachiningList(nI).m_nId
      ' Evidenzio la lavorazione principale
      MarkSingleMachining(nOperId, bMark)
      ' Evidenzio l'eventuale numero della lavorazione
      MarkNumberArrow(nI, bMark)
      ' Marco anche le lavorazioni inglobate
      For Each nId As Integer In m_MachiningList(nI).m_vOthId
         MarkSingleMachining(nId, bMark)
      Next
   End Sub

   Private Sub MarkSingleMachining(nOperId As Integer, bMark As Boolean)
      Dim nPvId As Integer = GDB_ID.NULL
      If EgtGetInfo(EgtGetFirstNameInGroup(nOperId, NAME_PREVIEW), INFO_PV_ONPART_ID, nPvId) Then
         If bMark Then
            EgtSetMark(nPvId)
         Else
            EgtResetMark(nPvId)
         End If
      End If
   End Sub

   Private Sub MarkNumberArrow(nI As Integer, bMark As Boolean)
      If nI < 0 Then Return
      Dim nNbrId As Integer = m_MachiningList(nI).m_nNbrId
      Dim nArrId As Integer = m_MachiningList( nI).m_nArrId
      If bMark Then
         EgtSetMark( nNbrId)
         EgtSetMark( nArrId)
      Else
         EgtResetMark( nNbrId)
         EgtResetMark( nArrId)
      End If
   End Sub

   Private Sub ColorNumberArrow( nI As Integer)
      If nI < 0 Then Return
      Dim nNbrId As Integer = m_MachiningList( nI).m_nNbrId
      Dim nArrId As Integer = m_MachiningList( nI).m_nArrId
      If m_MachiningList( nI).m_bEnabled Then
         If m_MachiningList( nI).m_nInterf = FMI_TYPE.NONE Then
            EgtSetColor( nNbrId, COL_MCH_FREE)
            EgtSetColor( nArrId, COL_MCH_FREE)
         Else
            EgtSetColor( nNbrId, COL_MCH_INTERF)
            EgtSetColor( nArrId, COL_MCH_INTERF)
         End If
      Else
         If m_MachiningList( nI).m_nInterf = FMI_TYPE.NONE Then
            EgtResetColor( nNbrId)
            EgtResetColor( nArrId)
         ElseIf Not m_MachiningList( nI).m_bEnabled Then
            EgtSetColor( nNbrId, COL_MCH_DIS_INTERF)
            EgtSetColor( nArrId, COL_MCH_DIS_INTERF)
         End If
      End If
   End Sub

   Private Sub RemoveMarkAndNumbers()
      EgtDisableModified()
      ' cancello evidenziazione
      If m_CurrFirstInd >= 0 Then
         For Index As Integer = m_CurrFirstInd To m_CurrLastInd
            If Not m_ItemList(Index).IsSelected Then
               Continue For
            End If
            MarkMachining(m_ItemList(Index).Ind, False)
         Next
         m_CurrFirstInd = -1
         m_CurrLastInd = -1
      End If
      ' cancello gruppo di numerazione e ripristino colori lavorazioni
      EgtErase(m_nNbrGrpId)
      For i As Integer = 0 To m_MachiningList.Count() - 1
         ColorMachining(m_MachiningList(i), True)
      Next
      EgtEnableModified()
   End Sub

   Private Sub SwapStartEndData( nI As Integer)
      ' Swap angoli precedente e successivo
      Dim dAng As Double = m_MachiningList( nI).m_dPrevAng
      m_MachiningList( nI).m_dPrevAng = m_MachiningList( nI).m_dNextAng
      m_MachiningList( nI).m_dNextAng = dAng
      ' Swap lunghezze libere
      Dim dFreeLen As Double = m_MachiningList( nI).m_dStartFreeLen
      m_MachiningList( nI).m_dStartFreeLen = m_MachiningList( nI).m_dEndFreeLen
      m_MachiningList( nI).m_dEndFreeLen = dFreeLen
      ' Swap stato di allungamento
      Dim bAll As Boolean = m_MachiningList( nI).m_bStartAll
      m_MachiningList( nI).m_bStartAll = m_MachiningList( nI).m_bEndAll
      m_MachiningList( nI).m_bEndAll = bAll
      ' Swap possibilità di allungamento
      Dim bCanAll As Boolean = m_MachiningList( nI).m_bCanStartAll
      m_MachiningList( nI).m_bCanStartAll = m_MachiningList( nI).m_bCanEndAll
      m_MachiningList( nI).m_bCanEndAll = bCanAll
      ' Swap stato interferenza
      if ( m_MachiningList( nI).m_nInterf And FMI_TYPE.LI) <> 0  And  ( m_MachiningList( nI).m_nInterf And FMI_TYPE.LO) = 0 Then
         m_MachiningList( nI).m_nInterf -= FMI_TYPE.LI
         m_MachiningList( nI).m_nInterf += FMI_TYPE.LO
      ElseIf ( m_MachiningList( nI).m_nInterf And FMI_TYPE.LI) = 0  And  ( m_MachiningList( nI).m_nInterf And FMI_TYPE.LO) <> 0 Then
         m_MachiningList( nI).m_nInterf += FMI_TYPE.LI
         m_MachiningList( nI).m_nInterf -= FMI_TYPE.LO
      End If
      ' Swap Allungamento Utente 
      Dim dOrigUsal As Double = 0
      EgtGetInfo( m_MachiningList( nI).m_nId, INFO_MCH_USER_SAL, dOrigUsal)
      Dim dOrigUeal As Double = 0
      EgtGetInfo( m_MachiningList( nI).m_nId, INFO_MCH_USER_EAL, dOrigUeal)
      EgtSetInfo( m_MachiningList( nI).m_nId, INFO_MCH_USER_SAL, dOrigUeal)
      EgtSetInfo( m_MachiningList( nI).m_nId, INFO_MCH_USER_EAL, dOrigUsal)
   End Sub

   '-----------------------------------------------------------------------------------------------
   Private Class NameIdLsBxItem
      Implements INotifyPropertyChanged

      Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged

      Private m_nInd As Integer
      Private m_sName As String
      Private m_bIsActive As Boolean
      Private m_nType As Integer

      Private m_IsSelected As Boolean

      Public Property Ind As Integer
         Get
            Return m_nInd
         End Get
         Set(value As Integer)
            m_nInd = value
         End Set
      End Property

      Public Property Name As String
         Get
            Return m_sName
         End Get
         Set(value As String)
         If value <> m_sName Then
            m_sName = value
                  NotifyPropertyChanged("Name")
         End If
         End Set
      End Property

      Public Property bIsActive As Boolean
         Get
            Return m_bIsActive
         End Get
         Set(value As Boolean)
         If value <> m_bIsActive Then
            m_bIsActive = value
            NotifyPropertyChanged("bIsActive")
         End If
         End Set
      End Property

      Public Property Type As Integer
         Get
            Return m_nType
         End Get
         Set(value As Integer)
            m_nType = value
         End Set
      End Property

      Public Property IsSelected As Boolean
         Get
            Return m_IsSelected
         End Get
         Set(value As Boolean)
            m_IsSelected = value
         End Set
      End Property

      Sub New(Name As String, Ind As Integer, bIsActive As Boolean, nType As Integer)
         Me.m_sName = Name
         Me.m_nInd = Ind
         Me.m_bIsActive = bIsActive
         Me.m_nType = nType
      End Sub

      Public Sub NotifyPropertyChanged(propName As String)
         RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propName))
      End Sub

   End Class

End Class
