Imports System.IO
Imports EgtUILib
Imports EgtWPFLib

Public Class ProjectMgrUC
   ' Riferimenti a pagine (condivisi tra tutte le istanze della classe)
   Private Shared m_MainWindow As MainWindow = DirectCast(Application.Current.MainWindow, MainWindow)
   Private Shared m_CurrProjPage As CurrentProjectPageUC
   Private Shared m_CurrMachine As CurrentMachine
   Private Shared m_CurrNcComm As CNCommunication
   Friend Shared m_VeinMatchingWnd As VeinMatchingWindow = Nothing
   ' usato per scrivere i comadi di movimento test lavorazione
   Friend m_CN As CN_generico

   Private Sub ProjectMgrUC_Initialized(sender As Object, e As EventArgs) Handles Me.Initialized
      ' Imposto i messaggi letti dal file dei messaggi
      NewBtn.ToolTip = EgtMsg(MSG_CADCUTPAGEUC + 3)
      LoadBtn.ToolTip = EgtMsg(MSG_CADCUTPAGEUC + 4)
      SaveBtn.ToolTip = EgtMsg(MSG_CADCUTPAGEUC + 5)
      SaveNameBtn.ToolTip = EgtMsg(MSG_CADCUTPAGEUC + 6)
      CSVBtn.ToolTip = EgtMsg(MSG_CADCUTPAGEUC + 8)
      VeinMatchingBtn.ToolTip = EgtMsg(MSG_CADCUTPAGEUC + 9)

      RegisterBtn.Content = "REG"                              'Shape Registration
      ResetCutBtn.Content = EgtMsg(MSG_NESTPAGEUC + 6)         'Reset
      SimulateBtn.ToolTip = EgtMsg(MSG_CADCUTPAGEUC + 1)       'Simulate - Simula
      If m_MainWindow.GetKeyOption(MainWindow.KEY_OPT.OFFICE_TYPE) Then
         WorkBtn.ToolTip = EgtMsg(MSG_CADCUTPAGEUC + 10)       'Export - Esporta
      Else
         WorkBtn.ToolTip = EgtMsg(MSG_CADCUTPAGEUC + 2)        'Work - Lavora
      End If
      TestBtn.ToolTip = EgtMsg(90255)                          'Test
   End Sub

   Private Sub ProjectMgrUC_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
      ' Impostazioni
      SetReference()

      ' Se richiesto carico finestra per VeinMatching e ultimo intarsio
      If m_MainWindow.GetKeyOption(MainWindow.KEY_OPT.MAN_PHOTO) And
         GetPrivateProfileInt(S_VEINMATCHING, K_VEINMA_ENABLE, 0, m_MainWindow.GetIniFile()) <> 0 And
         IsNothing(m_VeinMatchingWnd) Then
         ' Finestra
         m_VeinMatchingWnd = New VeinMatchingWindow
         m_VeinMatchingWnd.Owner = m_MainWindow
         m_VeinMatchingWnd.Show()
         m_VeinMatchingWnd.Hide()
         VeinMatching.m_nVeinCtx = GetVeinMatchingContext()
         EgtSetCurrentContext(m_CurrProjPage.CurrentProjectScene.GetCtx())
         m_VeinMatchingWnd.AdjustPosition()
         ' Ultimo intarsio
         VeinMatching.Open(m_MainWindow.GetVeinMatchingDir() & "\Inlay.vme")
      End If
   End Sub

   Public Sub SetReference()
      m_CurrProjPage = m_MainWindow.m_CurrentProjectPageUC
      m_CurrMachine = m_MainWindow.m_CurrentMachine
      m_CurrNcComm = m_MainWindow.m_CNCommunication
   End Sub

   Private Sub NewBtn_Click(sender As Object, e As RoutedEventArgs) Handles NewBtn.Click
      EgtSetCurrentContext(m_CurrProjPage.CurrentProjectScene.GetCtx())
      m_CurrProjPage.m_SceneButtons.MeasureBtn.IsChecked = False
      ' Se progetto modificato, chiedo se salvarlo
      If EgtGetModified() Then
         Dim SaveCurrProj As New EgtMsgBox(m_MainWindow, "", EgtMsg(MSG_EGTMSGBOX + 1), EgtMsgBox.Buttons.YES_NO_CANCEL, EgtMsgBox.Icons.NULL)
         Select Case SaveCurrProj.m_nPressedBtn
            Case 0    ' Annulla
               Return
            Case 1    ' Si
               m_CurrProjPage.SaveNamedProject()
               m_CurrProjPage.SaveProject()
            Case 2    ' No
               ' Non devo fare alcunchè
         End Select
      End If
      ' Gestione stato FastGrid
      m_MainWindow.m_CadCutPageUC.m_FastGridSlabManager.OnPreNewProject()
      ' Cancello progetto salvato con nome da file ini
      WritePrivateProfileString(S_GENERAL, K_LASTNAMEPROJ, "", m_MainWindow.GetIniFile())
      ' Se ci sono pezzi in parcheggio, chiedo se conservarli
      Dim bRetainParkedParts As Boolean = False
      If EgtGetFirstPart() <> GDB_ID.NULL Then
         ' Conservare i pezzi in parcheggio ?
         Dim RetainParkedParts As New EgtMsgBox(m_MainWindow, "", EgtMsg(91118), EgtMsgBox.Buttons.YES_NO_CANCEL, EgtMsgBox.Icons.NULL)
         Select Case RetainParkedParts.m_nPressedBtn
            Case 0    ' Annulla
               Return
            Case 1    ' Si
               bRetainParkedParts = True
            Case 2    ' No
               ' Non devo fare alcunchè
         End Select
      End If
      ' Scelta tavola della macchina
      Dim nTabInd As Integer = ChooseTable()
      ' Creo nuovo progetto
      m_CurrProjPage.NewProject(nTabInd, bRetainParkedParts)
      ' Gestione stato FastGrid
      m_MainWindow.m_CadCutPageUC.m_FastGridSlabManager.OnPostNewProject()
      EgtZoom(ZM.ALL)
   End Sub

   Friend Function ChooseTable() As Integer
      Dim nTabInd As Integer = 0
      Select Case GetTableCount()
         Case 3
            ' Tavolo da usare ?
            Dim TableToUse As New EgtMsgBox(m_MainWindow, "", EgtMsg(91111), EgtMsgBox.Buttons.ONE_TWO_THREE, EgtMsgBox.Icons.NULL)
            Select Case TableToUse.m_nPressedBtn
               Case 1    ' 1
                  nTabInd = 1
               Case 2    ' 2
                  nTabInd = 2
               Case 0    ' 3
                  nTabInd = 3
            End Select
         Case 2
            ' Tavolo da usare ?
            Dim TableToUse As New EgtMsgBox(m_MainWindow, "", EgtMsg(91111), EgtMsgBox.Buttons.ONE_TWO, EgtMsgBox.Icons.NULL)
            Select Case TableToUse.m_nPressedBtn
               Case 1    ' 1
                  nTabInd = 1
               Case 0    ' 2
                  nTabInd = 2
            End Select
         Case Else
            nTabInd = 1
      End Select
      Return nTabInd
   End Function

   Friend Function ChangeTable() As Integer
      Dim nRes As Integer = 0
      ' se non abilitato esco dalla pagina
      If GetPrivateProfileInt(S_TABLE, K_CHANGETABWD, 0, m_MainWindow.GetMachIniFile()) = 0 Then
         Return nRes
      End If
      Select Case GetTableCount()
         Case 2
            ' Vuoi cambiare tavola?
            Dim TableToUse As New EgtMsgBox(m_MainWindow, "", String.Format(EgtMsg(90968)), EgtMsgBox.Buttons.OK_CANCEL, EgtMsgBox.Icons.NULL)
            nRes = TableToUse.m_nPressedBtn
         Case Else
            ' negli altri casi (3 tavole o una tavola non fare nulla)
      End Select
      Return nRes
   End Function

   Private Sub LoadBtn_Click(sender As Object, e As RoutedEventArgs) Handles LoadBtn.Click
      EgtSetCurrentContext(m_CurrProjPage.CurrentProjectScene.GetCtx())
      m_CurrProjPage.m_SceneButtons.MeasureBtn.IsChecked = False
      ' Cancello eventuali messaggi
      m_CurrProjPage.ClearMessage()
      ' Se progetto modificato, chiedo se salvarlo
      If EgtGetModified() Then
         Dim SaveCurrProj As New EgtMsgBox(m_MainWindow, "", EgtMsg(MSG_EGTMSGBOX + 1), EgtMsgBox.Buttons.YES_NO_CANCEL, EgtMsgBox.Icons.NULL)
         Select Case SaveCurrProj.m_nPressedBtn
            Case 0    ' Annulla
               Return
            Case 1    ' Si
               m_CurrProjPage.SaveNamedProject()
               m_CurrProjPage.SaveProject()
            Case 2    ' No
               ' Non devo fare alcunchè
         End Select
      End If
      ' Imposto la pagina attualmente attiva come Previous
      m_MainWindow.m_PrevActivePage = m_MainWindow.m_ActivePage
      ' Passo alla pagina di apertura con preview
      m_MainWindow.MainWindowGrid.Children.Remove(m_MainWindow.m_CurrentProjectPageUC)
      m_MainWindow.MainWindowGrid.Children.Add(m_MainWindow.m_OpenPage)
      m_MainWindow.m_ActivePage = MainWindow.Pages.Open
   End Sub

   Friend Sub PostLoad(ByVal sCurrDir As String, sCurrFile As String)

      EgtSetCurrentContext(m_CurrProjPage.CurrentProjectScene.GetCtx())
      If Not m_CurrProjPage.LoadProject(sCurrDir & "\" & sCurrFile) Then
         m_CurrProjPage.NewProject()
         m_CurrProjPage.m_MruFiles.Remove(sCurrDir & "\" & sCurrFile)
      Else
         ' Verifico se file salvato con nome guardando il nome della cartella in cui si trova
         Dim sSaveNameDir As String = String.Empty
         GetPrivateProfileString(S_GENERAL, K_SAVENAMEDIR, "", sSaveNameDir, m_MainWindow.GetIniFile())
         If sCurrDir = sSaveNameDir Then
            WritePrivateProfileString(S_GENERAL, K_LASTNAMEPROJ, sCurrFile.Substring(0, sCurrFile.Length - 4), m_MainWindow.GetIniFile())
            ' Salvo equivalente con indice
            m_CurrProjPage.SetNextProjectIndex()
            m_CurrProjPage.SaveProject()
         Else
            WritePrivateProfileString(S_GENERAL, K_LASTNAMEPROJ, String.Empty, m_MainWindow.GetIniFile())
         End If
         ' Salvo path di carico del progetto
         If sCurrDir <> m_MainWindow.GetSaveDir() And sCurrDir <> sSaveNameDir Then
            m_CurrProjPage.SetLoadPath(sCurrDir & "\" & sCurrFile)
         End If
         m_CurrProjPage.m_MruFiles.Add(sCurrDir & "\" & sCurrFile)
      End If
      ' Verifico se andare nel CadCut o nel FrameCut
      Dim nPrjType As Integer = m_CurrProjPage.GetCurrentProjectType()
      If nPrjType = CurrentProjectPageUC.PRJ_TYPE.FLATS And
         m_MainWindow.m_PrevActivePage <> MainWindow.Pages.CadCut Then
         m_CurrProjPage.CurrentProjectPageGrid.Children.Remove(m_MainWindow.m_FrameCutPageUC)
         m_CurrProjPage.CurrentProjectPageGrid.Children.Add(m_MainWindow.m_CadCutPageUC)
         m_MainWindow.m_ActivePage = MainWindow.Pages.CadCut
         m_MainWindow.FrameCutBtn.IsChecked = False
         m_MainWindow.CadCutBtn.IsChecked = True
      ElseIf nPrjType = CurrentProjectPageUC.PRJ_TYPE.FRAMES And
             m_MainWindow.m_PrevActivePage <> MainWindow.Pages.FrameCut Then
         m_CurrProjPage.CurrentProjectPageGrid.Children.Remove(m_MainWindow.m_CadCutPageUC)
         m_CurrProjPage.CurrentProjectPageGrid.Children.Add(m_MainWindow.m_FrameCutPageUC)
         m_MainWindow.m_ActivePage = MainWindow.Pages.FrameCut
         m_MainWindow.CadCutBtn.IsChecked = False
         m_MainWindow.FrameCutBtn.IsChecked = True
      Else
         m_MainWindow.m_ActivePage = m_MainWindow.m_PrevActivePage
      End If
      EgtZoom(ZM.ALL)
   End Sub

   Private Sub SaveBtn_Click(sender As Object, e As RoutedEventArgs) Handles SaveBtn.Click
      EgtSetCurrentContext(m_CurrProjPage.CurrentProjectScene.GetCtx())
      ' Salvataggio con nome (solo se nome definito)
      m_CurrProjPage.SaveNamedProject()
      ' Salvataggio con numero ciclico
      m_CurrProjPage.SaveProject()
      ' Se cornici, ripristino visualizzazione lavorazioni
      If m_MainWindow.m_ActivePage = MainWindow.Pages.FrameCut Then
         ShowAllCurrPhaseMachinings()
      End If
      EgtDraw()
   End Sub

   Private Sub SaveNameBtn_Click(sender As Object, e As RoutedEventArgs) Handles SaveNameBtn.Click
      EgtSetCurrentContext(m_CurrProjPage.CurrentProjectScene.GetCtx())
      Dim MySaveNameWD As New SaveNameWD(m_MainWindow, SaveNameWD.SAVE_TYPE.PRJ_NAMED)
      MySaveNameWD.ShowDialog()
   End Sub

   Private Sub CSVBtn_Click(sender As Object, e As RoutedEventArgs) Handles CSVBtn.Click
      EgtSetCurrentContext(m_CurrProjPage.CurrentProjectScene.GetCtx())
      m_CurrProjPage.m_SceneButtons.MeasureBtn.IsChecked = False
      m_MainWindow.m_CadCutPageUC.CadCutPageGrid.Children.Remove(m_MainWindow.m_CadCutPageUC.m_NestPage)
      m_MainWindow.m_CadCutPageUC.CadCutPageGrid.Children.Add(m_MainWindow.m_CadCutPageUC.m_CSVPage)
      m_MainWindow.m_ActivePage = MainWindow.Pages.CSV
      m_MainWindow.m_PrevActivePage = MainWindow.Pages.CadCut
   End Sub

   Private Sub ResetCutBtn_Click(sender As Object, e As RoutedEventArgs) Handles ResetCutBtn.Click
      EgtSetCurrentContext(m_CurrProjPage.CurrentProjectScene.GetCtx())
      ' Cancello eventuali messaggi
      m_CurrProjPage.ClearMessage()
      ' Ricalcolo tutte le lavorazioni
      Dim nWarn As Integer = 0
      ResetAllMachinings(nWarn)
      If nWarn = 1 Then m_CurrProjPage.SetWarningMessage(EgtMsg(MSG_SPLITPAGEUC + 11)) ' Lama troppo grande per utilizzo ventosa
      ' Aggiorno visualizzazione
      EgtDraw()
   End Sub

   Private Sub SimulateBtn_Click(sender As Object, e As RoutedEventArgs) Handles SimulateBtn.Click
      EgtSetCurrentContext(m_CurrProjPage.CurrentProjectScene.GetCtx())
      m_CurrProjPage.m_SceneButtons.MeasureBtn.IsChecked = False
      m_CurrProjPage.CurrProjGrid.Visibility = Windows.Visibility.Hidden
      If m_MainWindow.m_ActivePage = MainWindow.Pages.CadCut Then
         m_CurrProjPage.CurrentProjectPageGrid.Children.Remove(m_MainWindow.m_CadCutPageUC)
         m_MainWindow.m_PrevActivePage = MainWindow.Pages.CadCut
      Else
         m_CurrProjPage.CurrentProjectPageGrid.Children.Remove(m_MainWindow.m_FrameCutPageUC)
         m_MainWindow.m_PrevActivePage = MainWindow.Pages.FrameCut
      End If
      m_CurrProjPage.CurrentProjectPageGrid.Children.Add(m_MainWindow.m_SimulationPage)
      m_MainWindow.m_ActivePage = MainWindow.Pages.Simulation
   End Sub

   Private Sub WorkBtn_Click(sender As Object, e As RoutedEventArgs) Handles WorkBtn.Click
#If TRIAL Then
      m_CurrProjPage.SetWarningMessage("Trial Version")
#Else
      ' se sono in modalità Test allora eseguo solo il posizionamento della lama
      If m_MainWindow.m_CadCutPageUC.m_NestPage.m_bSelectCurv Then
         ' Verifico non sia versione Ufficio
         If m_MainWindow.GetKeyOption(MainWindow.KEY_OPT.OFFICE_TYPE) Then
            m_CurrProjPage.SetWarningMessage("Office Version")
            Return
         End If

         '------------------- Ricavo punto medio di posizionamento ----------------------------
         ' Spessore grezzo
         Dim m_ptRawMax, m_ptRawMin As Point3d
         If Not GetRawBox(m_ptRawMin, m_ptRawMax) Then Return
         Dim dRawHeight As Double = m_ptRawMax.z - m_ptRawMin.z
         ' Recupero spessore lama corrente
         Dim sSaw As String = m_MainWindow.m_CurrentMachine.sCurrSaw
         EgtTdbSetCurrTool(sSaw)
         Dim dThick As Double = 0
         EgtTdbGetCurrToolParam(MCH_TP.THICK, dThick)
         Dim dDiam As Double = 0
         EgtTdbGetCurrToolParam(MCH_TP.DIAM, dDiam)
         'recupero il lato selezionato 
         Dim nIdSelected As Integer = m_MainWindow.m_CadCutPageUC.m_NestPage.m_CurrSelectedCurv
         If nIdSelected = -1 Then Return
         ' recupero gli estremi del latovda tagliare
         Dim ptStart As Point3d
         EgtStartPoint(nIdSelected, GDB_ID.ROOT, ptStart)
         Dim ptEnd As Point3d
         EgtEndPoint(nIdSelected, GDB_ID.ROOT, ptEnd)
         Dim vtDirLine As Vector3d = ptEnd - ptStart
         ' calcolo il versore perpendicolare alla linea di taglio (diretto verso l'interno del pezzo)
         Dim vtDirT As Vector3d = vtDirLine
         vtDirT.Normalize()
         vtDirT.Rotate(Vector3d.Z_AX, 90)

         ' Calcolo punto di posizionamemto (punto medio)
         Dim ptMid, m_ptTabOri As Point3d

         If Not EgtGetTableRef(1, m_ptTabOri) Then Return
         ptMid.x = (ptEnd.x + ptStart.x) / 2
         ptMid.y = (ptEnd.y + ptStart.y) / 2
         ptMid.z = (ptEnd.z + ptStart.z) / 2 + dDiam / 2
         ptMid -= vtDirT * dThick

         '--------------------------- Imposto la posizione della macchina ----------------------------
         ' Recupero la posizione macchina
         Dim dL1, dL2, dL3, dR1, dR2 As Double
         If Not m_MainWindow.m_CNCommunication.GetAxesPositions(dL1, dL2, dL3, dR1, dR2) Then Return
         ' Imposto la lama corrente
         If Not EgtSetCalcTool(sSaw, "H1", 1) Then Return

         ' calcolo la posizione degli assi rotanti C, B
         Dim nStat As Integer
         Dim dC1, dB1, dC2, dB2 As Double
         EgtGetCalcAngles(vtDirT, Vector3d.Z_AX(), nStat, dC1, dB1, dC2, dB2)
         ' calcolo la posizione degli assi lineari X, Y, Z
         Dim dX, dY, dZ As Double
         EgtGetCalcPositions(ptMid, dC1, dB1, nStat, dX, dY, dZ)

         ' verifica assi lineari
         EgtVerifyOutstroke(dX, dY, dZ, dC1, dB1, nStat)
         If nStat <> 0 Then
            vtDirT = -vtDirT
            ptMid -= vtDirT * dThick
            EgtGetCalcAngles(vtDirT, Vector3d.Z_AX(), nStat, dC1, dB1, dC2, dB2)
            ' calcolo la posizione degli assi lineari X, Y, Z ( correggere il punto ptMid.z sommando il raggio utensile)
            EgtGetCalcPositions(ptMid, dC1, dB1, nStat, dX, dY, dZ)
         End If

         '--------------------------- Comunico i movimenti in origine macchina al CN ----------------------------------------
         Dim ptMachine As Point3d = New Point3d(dX, dY, dZ)
         ExecuteCommandCNC(ptMachine, dC1, dB1)
         Return
      End If
      ' ---------------------------- Fine modalità test --------------------------------------------

      Dim bOk As Boolean = True
      EgtSetCurrentContext(m_CurrProjPage.CurrentProjectScene.GetCtx())
      ' Elimino eventuale attrezzaggio da OmagOFFICE
      EgtEraseCurrSetup()
      ' Verifico l'attrezzaggio degli utensili utilizzati
      Dim sMissingTools As String = String.Empty
      If Not VerifySetup(sMissingTools) Then
         m_CurrProjPage.SetErrorMessage(EgtMsg(90322) & " " & sMissingTools)  'Mancano gli utensili : ... 
         Return
      End If
      ' Costringo ad aggiornare UI
      UpdateUI()
      ' Aggiorno flag per lavaggio
      m_CurrProjPage.UpdateWashingFlag()
      ' Aggiorno flag per tastatura per tagli con angolo di fianco
      m_CurrProjPage.UpdateSideAngCutProbeFlag()
      ' Se pezzi piani e non c'è ordine delle lavorazioni, ricalcolo tutto e ne faccio uno automatico
      Dim nPrjType As Integer = m_CurrProjPage.GetCurrentProjectType()
      Dim bDirectCut As Boolean = (GetDirectCutPart() <> GDB_ID.NULL)
      If nPrjType = CurrentProjectPageUC.PRJ_TYPE.FLATS And
         Not bDirectCut And
         Not m_CurrProjPage.GetOrderMachiningFlag() Then
         ResetAllMachinings()
         bOk = SortAllMachinings()
         If bOk Then
            m_CurrProjPage.SetOrderMachiningFlag()
            Dim bModif As Boolean = TestAllMachiningsForStrict()
            If bModif Then
               m_CurrProjPage.SetWarningMessage(EgtMsg(90321))     'Ridotte alcune lavorazioni per evitare interferenze
            Else
               m_CurrProjPage.SetInfoMessage(EgtMsg(90399))        'Aggiornate tutte le lavorazioni
            End If
            EgtDraw()
         End If
      End If
      ' Costringo ad aggiornare UI
      UpdateUI()
      ' Disabilito impostazione modificato
      EgtDisableModified()
      ' Aggiorno le lavorazioni
      bOk = UpdateAllMachiningsToolpaths() And bOk
      ' Aggiorno posizionamento ventose sui pezzi per eventuali tagli da sotto con lama
      bOk = UpdateVacuumsForDrip() And bOk
      ' Costringo ad aggiornare UI
      UpdateUI()
      ' Inserisco indice di progetto
      m_CurrProjPage.SetProjectIndexFlag()
      ' Inserisco il materiale
      m_CurrProjPage.SetProjectMaterial()
      ' Salvo il progetto con le lavorazioni
      Dim sMchPath As String = m_MainWindow.GetTempDir() & "\MachProj.nge"
      m_CurrProjPage.SaveFile(sMchPath)
      ' Costringo ad aggiornare UI
      UpdateUI()
      ' Se modalità Ufficio, copio il progetto ed esco
      If m_MainWindow.GetKeyOption(MainWindow.KEY_OPT.OFFICE_TYPE) Then
         ' Ripristino come fase corrente quella iniziale
         EgtSetCurrPhase(1)
         ' Chiedo il nome del file esportato
         Dim MySaveNameWD As New SaveNameWD(m_MainWindow, SaveNameWD.SAVE_TYPE.PRJ_COPY)
         MySaveNameWD.ShowDialog()
         Return
      End If
      ' Se presente ripartenza, ne chiedo conferma
      Dim nPhaseRestart As Integer = m_CurrProjPage.GetProjectNcRestart()
      If nPhaseRestart <> 0 Then
         ' Confermi ripartenza dalla fase NNN ?
         Dim AskNcRestart As New EgtMsgBox(m_MainWindow, "", String.Format(EgtMsg(90326), nPhaseRestart),
                                        EgtMsgBox.Buttons.YES_NO_CANCEL, EgtMsgBox.Icons.NULL, 2)
         Select Case AskNcRestart.m_nPressedBtn
            Case 1         ' YES
            Case 2         ' NO
               EgtEnableModified()
               m_CurrProjPage.ResetProjectNcRestart()
               nPhaseRestart = 0
               EgtDisableModified()
            Case Else      ' CANCEL
               Return
         End Select
      End If
      ' Se abilitate, eseguo le stime
      If GetPrivateProfileInt(S_MACH_ESTIMATIONS, K_ENABLEEST, 0, m_MainWindow.GetMachIniFile()) <> 0 Then
         EgtEstimate(m_MainWindow.GetTempDir() & "\MachProj.html", "OmagCut ver." & m_MainWindow.GetVersion())
      End If
      ' Genero file CNC (lancio anche se errore in precedenza)
      Dim sCncPath As String = m_MainWindow.GetCncDir() & "\CadCut" & m_CurrMachine.sIsoFileExt
      bOk = EgtGenerate(sCncPath, "OmagCut ver." & m_MainWindow.GetVersion()) And bOk
      ' Costringo ad aggiornare UI
      UpdateUI()
      ' Ripristino come fase corrente quella iniziale
      EgtSetCurrPhase(1)
      ' Se nesting di pezzi piani, nascondo tutte le lavorazioni
      If m_MainWindow.m_ActivePage = MainWindow.Pages.CadCut Then
         HideAllMachinings()
      Else
         ShowAllCurrPhaseMachinings()
      End If
      ' Abilito impostazione modificato
      EgtEnableModified()
      ' Se errore in generazione, segnalo l'errore ed esco
      If Not bOk Then
         m_CurrProjPage.SetErrorMessage(EgtMsg(90314))       'Errore nella generazione del programma CN
         Return
      End If
      ' Costringo ad aggiornare UI
      UpdateUI()
      ' Se macchina normale
      If Not (m_CurrMachine.bProdLine Or m_CurrMachine.bDemo) Then
         ' Download programma (eventuali errori sono segnalati dalla funzione)
         If m_CurrNcComm.SendProgram(sCncPath, 900) Then
            ' copio il progetto corrente come progetto in lavorazione
            Dim sWrkPath As String = m_MainWindow.GetTempDir() & "\" & "WorkProj.nge"
            My.Computer.FileSystem.CopyFile(sMchPath, sWrkPath, True)
            ' se abilitato e non è restart, lancio eventuale lua post-trasmissione
            If m_MainWindow.GetKeyOption(MainWindow.KEY_OPT.SIMPLESTATISTICS) And nPhaseRestart = 0 Then
               m_MainWindow.ExecSentProgScript(False)
            End If
         End If

         '------------------- INIZIO Avvio il Ciclo-Start-------------------------
         If GetPrivateProfileInt(S_GENERAL, K_STARTPROGRAM, 0, m_MainWindow.GetIniFile()) <> 0 Then
            Dim MyCicloStartWD As New CicloStartWD(m_MainWindow)
            MyCicloStartWD.ShowDialog()
         End If
         '------------------- FINE Avvio il Ciclo-Start-------------------------

         ' Altrimenti linea di produzione
      Else
         ' Verifico non sia già stato trasmesso
         Dim bAlreadySent As Boolean = (m_CurrProjPage.GetProjectNcProgSent() <> 0)
         If bAlreadySent Then
            ' Gestione possibilità sia nuovo progetto
            Dim bIsNew As Boolean = False
            If m_CurrMachine.bAskNewOnResend Then
               ' Programma già trasmesso, è una nuova lastra ?
               Dim AskNew As New EgtMsgBox(m_MainWindow, "", EgtMsg(90330),
                                           EgtMsgBox.Buttons.YES_NO_CANCEL, EgtMsgBox.Icons.NULL, 2)
               ' Se annullo
               If AskNew.m_nPressedBtn = 0 Then
                  Return
                  ' Se altrimenti nuovo progetto
               ElseIf AskNew.m_nPressedBtn = 1 Then
                  ' Incremento indice
                  m_CurrProjPage.SetNextProjectIndex()
                  ' Rimuovo flag di progetto già scaricato
                  EgtRemoveInfo(EgtGetFirstNameInGroup(GDB_ID.ROOT, NAME_PROJMARK), INFO_UNLOADSAVED)
                  ' Rimuovo flag di Ok sui pezzi
                  Dim nRawId As Integer = CamAuto.GetCurrentRaw()
                  Dim nPartId As Integer = EgtGetFirstPartInRawPart(nRawId)
                  While nPartId <> GDB_ID.NULL
                     EgtRemoveInfo(nPartId, INFO_PARTOK)
                     Dim nRegId = EgtGetFirstNameInGroup(nPartId, NAME_REGION)
                     ' Cerco prima regione nel layer
                     Dim nId As Integer = EgtGetFirstInGroup(nRegId)
                     While nId <> GDB_ID.NULL
                        If EgtGetType(nId) = GDB_TY.SRF_FRGN Then
                           EgtSetColor(nId, New Color3d(0, 255, 255, 25))     ' Aqua
                           Exit While
                        End If
                        nId = EgtGetNext(nId)
                     End While
                     nPartId = EgtGetNextPartInRawPart(nPartId)
                  End While
                  ' Eventuale gestione dati lastra
                  Dim bSlabId As Boolean = (Not m_CurrMachine.bHasRawBarCodeReader And
                                            GetPrivateProfileInt(S_RAWPART, K_SLABID, 0, m_MainWindow.GetIniFile()) <> 0)
                  If bSlabId Then
                     Dim sBlock As String = ""
                     GetPrivateProfileString(S_RAWPART, K_BLOCKNAME, "", sBlock, m_MainWindow.GetIniFile())
                     Dim nSlabNbr As Integer = GetPrivateProfileInt(S_RAWPART, K_SLABNBR, 0, m_MainWindow.GetIniFile())
                     nSlabNbr += 1
                     Dim sSlabNbr As String = nSlabNbr.ToString()
                     WritePrivateProfileString(S_RAWPART, K_SLABNBR, sSlabNbr, m_MainWindow.GetIniFile())
                     Utility.SetBlockAndSlabNbr(sBlock, sSlabNbr)
                  End If
                  ' Salvo il progetto
                  m_CurrProjPage.SaveProject()
                  ' Rigenero il file CNC
                  EgtGenerate(sCncPath, "OmagCut ver." & m_MainWindow.GetVersion())
                  EgtDisableModified()
                  ' Ripristino come fase corrente quella iniziale
                  EgtSetCurrPhase(1)
                  ' Se nesting di pezzi piani, nascondo tutte le lavorazioni
                  If m_MainWindow.m_ActivePage = MainWindow.Pages.CadCut Then
                     HideAllMachinings()
                  Else
                     ShowAllCurrPhaseMachinings()
                  End If
                  EgtEnableModified()
                  EgtDraw()
                  ' Dichiaro che il progetto è nuovo
                  bAlreadySent = False
               End If
            End If
            If bAlreadySent Then
               ' Programma già trasmesso, vuoi ritrasmetterlo ?
               Dim AskTransm As New EgtMsgBox(m_MainWindow, "", EgtMsg(90319),
                                              EgtMsgBox.Buttons.YES_NO_CANCEL, EgtMsgBox.Icons.NULL, 2)
               If AskTransm.m_nPressedBtn <> 1 Then Return
            End If
         End If

         ' Se non collegato alla macchina
         If Not m_MainWindow.m_bNCLink Then
            ' salvo il progetto corrente incrementando il valore del progetto
            m_CurrProjPage.SetWarningMessage(EgtMsg(90316))        'Non connesso alla macchina
            ' copio il progetto corrente come progetto in lavorazione
            Dim sWrkPath As String = m_MainWindow.GetTempDir() & "\" & "WorkProj.nge"
            My.Computer.FileSystem.CopyFile(sMchPath, sWrkPath, True)
            ' Dichiaro part program inviato
            m_CurrProjPage.SetProjectNcProgSent(1)
            ' Salvo il progetto
            m_CurrProjPage.SaveProject()
            ' lancio eventuale lua post-trasmissione
            m_MainWindow.ExecSentProgScript(False, bAlreadySent)
            ' se in versione demo (per linea di produzione) salvo il file corrente incrementando la numerazione
            Return
         End If

         ' Leggo variabile relativa al programma 1 (standard E80021)
         m_CurrNcComm.m_CN.n_DReadELS_handle = 0
         m_CurrNcComm.m_CN.ReadEls_Add_Parameter(m_CurrMachine.sVarProg1, 1)
         Dim nVarProg1 As Integer = 99
         For I As Integer = 0 To 10
            System.Threading.Thread.Sleep(50)
            If m_CurrNcComm.m_CN.n_DReadELS_handle = 1 Then
               nVarProg1 = CInt(m_CurrNcComm.m_CN.d_DReadELS_value)
               Exit For
            End If
         Next
         ' Leggo variabile relativa al programma 2 (standard E80022)
         m_CurrNcComm.m_CN.n_DReadELS_handle = 0
         m_CurrNcComm.m_CN.ReadEls_Add_Parameter(m_CurrMachine.sVarProg2, 1)
         Dim nVarProg2 As Integer = 99
         For I As Integer = 0 To 10
            System.Threading.Thread.Sleep(50)
            If m_CurrNcComm.m_CN.n_DReadELS_handle = 1 Then
               nVarProg2 = CInt(m_CurrNcComm.m_CN.d_DReadELS_value)
               Exit For
            End If
         Next
         ' Leggo eventuale variabile per lavorazione con 2 tavole in parallelo (standard E80027)
         Dim nVarProgTwins As Integer = 1
         If Not String.IsNullOrWhiteSpace(m_CurrMachine.sVarProgTwins) Then
            m_CurrNcComm.m_CN.n_DReadELS_handle = 0
            m_CurrNcComm.m_CN.ReadEls_Add_Parameter(m_CurrMachine.sVarProgTwins, 1)
            For I As Integer = 0 To 10
               System.Threading.Thread.Sleep(50)
               If m_CurrNcComm.m_CN.n_DReadELS_handle = 1 Then
                  nVarProgTwins = CInt(m_CurrNcComm.m_CN.d_DReadELS_value)
                  Exit For
               End If
            Next
         End If
         ' Verifico se posso scrivere nell'area 1
         If nVarProg1 = 0 And (nVarProg2 <> 1 Or nVarProgTwins = 2) Then
            m_CurrNcComm.SetProgramMainOrSub(False)
            If m_CurrNcComm.SendProgram(sCncPath, m_CurrMachine.nProg1, False) Then
               ' Dichiaro part program inviato
               m_CurrProjPage.SetProjectNcProgSent(1)
               ' Copio il progetto corrente come progetto in lavorazione
               Dim sWrkPath As String = m_MainWindow.GetTempDir() & "\" & "WorkProj1.nge"
               My.Computer.FileSystem.CopyFile(sMchPath, sWrkPath, True)
               ' Salvo il progetto
               m_CurrProjPage.SaveProject()
               ' Dichiaro programma inviato
               m_CurrNcComm.m_CN.DVariables_WriteVariables2(m_CurrMachine.sVarProg1, "1")
               ' lancio eventuale lua post-trasmissione
               m_MainWindow.ExecSentProgScript(False, bAlreadySent)
            End If
            m_CurrNcComm.SetProgramMainOrSub(True)
            ' Altrimenti verifico se posso scrivere nell'area 2
         ElseIf nVarProg2 = 0 And (nVarProg1 <> 1 Or nVarProgTwins = 2) Then
            m_CurrNcComm.SetProgramMainOrSub(False)
            If m_CurrNcComm.SendProgram(sCncPath, m_CurrMachine.nProg2, False) Then
               ' Dichiaro part program inviato
               m_CurrProjPage.SetProjectNcProgSent(2)
               ' Copio il progetto corrente come progetto in lavorazione
               Dim sWrkPath As String = m_MainWindow.GetTempDir() & "\" & "WorkProj2.nge"
               My.Computer.FileSystem.CopyFile(sMchPath, sWrkPath, True)
               ' Salvo il progetto
               m_CurrProjPage.SaveProject()
               ' Dichiaro programma inviato
               m_CurrNcComm.m_CN.DVariables_WriteVariables2(m_CurrMachine.sVarProg2, "1")
               ' lancio eventuale lua post-trasmissione
               m_MainWindow.ExecSentProgScript(False, bAlreadySent)
            End If
            m_CurrNcComm.SetProgramMainOrSub(True)
            ' Altrimenti aree di memoria non disponibili
         Else
            m_CurrProjPage.SetErrorMessage(EgtMsg(90318))       'La macchina non accetta il programma CN
         End If

      End If
#End If
   End Sub

   ' ------------------------------------------------ GENERA COMANDI CNC MOVIMENTO ------------------------------------------------
   Private Sub ExecuteCommandCNC(ptMid As Point3d, dAngC As Double, dAngB As Double)

      Dim CmdString As String = String.Empty
      If Not EgtLuaExecFile(m_MainWindow.m_CurrentMachine.sMachDir() & "\DirectCmd\TestWork.lua") Then
         Return
      End If

      '----------- DATI MOVIMENTO -----------
      ' imposto avanzamneto in rapido (non deve essere impostata feed e speed)
      EgtLuaSetGlobBoolVar("CMD.G0", True)

      '----------- POSIZINE MACCHINA -----------
      ' Leggo gli assi rispetto allo 0 macchina
      m_CurrNcComm.m_CN.set_OP_OM(0)

      System.Threading.Thread.Sleep(100)
      Dim dL1o, dL2o, dL3o As Double
      m_CurrNcComm.GetLinearAxesPositions(dL1o, dL2o, dL3o)
      Dim dR1, dR2 As Double
      m_CurrNcComm.GetRotaryAxesPositions(dR1, dR2)
      EgtLuaSetGlobNumVar("CMD.L1o", dL1o)
      EgtLuaSetGlobNumVar("CMD.L2o", dL2o)
      EgtLuaSetGlobNumVar("CMD.L3o", dL3o)
      EgtLuaSetGlobNumVar("CMD.R1", dR1)
      EgtLuaSetGlobNumVar("CMD.R2", dR2)

      ' Recupero spessore lama corrente
      Dim sSaw As String = m_MainWindow.m_CurrentMachine.sCurrSaw
      EgtTdbSetCurrTool(sSaw)
      Dim dThick As Double = 0
      EgtTdbGetCurrToolParam(MCH_TP.THICK, dThick)
      EgtLuaSetGlobNumVar("CMD.SAWTH", dThick)

      '----------- ASSEGNO POSIZIONE DI ARRIVO MACCHINA -----------
      ' Assegno valore ad ogni asse da muovere (in zero macchina)
      EgtLuaSetGlobNumVar("CMD.X_AXISMOVE", ptMid.x)
      EgtLuaSetGlobNumVar("CMD.Y_AXISMOVE", ptMid.y)
      EgtLuaSetGlobNumVar("CMD.Z_AXISMOVE", ptMid.z)
      ' imposto gli angoli 
      EgtLuaSetGlobNumVar("CMD.C_ANGMOVE", dAngC)
      EgtLuaSetGlobNumVar("CMD.B_ANGMOVE", dAngB)

      ' Calcolo stringa di comando risultante
      EgtLuaCallFunction("CmdString")
      EgtLuaGetGlobStringVar("CMD.CMDSTRING", CmdString)

      ' Reset lua
      EgtLuaResetGlobVar("CmdString")
      EgtLuaResetGlobVar("CMD")
      ' Log del comando
      EgtOutLog("CmdString=" & CmdString)

      ' Reset lua
      EgtLuaResetGlobVar("CMD")
      ' Modifico stringa per inserire i newline ( in questo caso non c'è bisogno perchè tutto sulla stessa linea)
      CmdString = CmdString.Replace("<br/>", Environment.NewLine)
      ' Creo file...
      Dim FilePath As String = m_MainWindow.GetCncDir() & "\TestWork" & m_MainWindow.m_CurrentMachine.sIsoFileExt
      ' ...e ci scrivo
      Dim Writer As New IO.StreamWriter(FilePath, False)
      Writer.Write(CmdString)
      Writer.Close()
      ' Verifico se sono connesso alla macchina prima di continuare
      If Not m_MainWindow.m_bNCLink Then
         m_CurrProjPage.SetWarningMessage(EgtMsg(90316))        'Non connesso alla macchina
         Return
      End If
      ' Mando file al CN
      If Not m_MainWindow.m_CNCommunication.SendProgram(FilePath, 900) Then
         Return
      End If
      m_MainWindow.m_CurrentProjectPageUC.ClearMessage()
      EgtOutLog("TestWork : sent NC program")
      ' Aspetto e lo avvio
      System.Threading.Thread.Sleep(300)
      m_MainWindow.m_CNCommunication.m_CN.DGeneralFunctions_CycleStart()

   End Sub

   ' ------------------------------------------------ GENERA COMANDI CNC MOVIMENTO ------------------------------------------------

   Private Sub TestBtn_Click(sender As Object, e As RoutedEventArgs) Handles TestBtn.Click
      If TestBtn.IsChecked Then
         m_MainWindow.m_CadCutPageUC.m_NestPage.m_bSelectCurv = True
         ' deseleziono tutto
         EgtDeselectAll()
      Else
         m_MainWindow.m_CadCutPageUC.m_NestPage.m_bSelectCurv = False
         EgtDeselectObj(m_MainWindow.m_CadCutPageUC.m_NestPage.m_CurrSelectedCurv)
         EgtDeselectObj(m_MainWindow.m_CadCutPageUC.m_NestPage.m_CurrSelectedSawCurv)
      End If
      ' aggiorno il disegno
      EgtDraw()
   End Sub

   Private Sub VeinMatchingBtn_Click(sender As Object, e As RoutedEventArgs) Handles VeinMatchingBtn.Click
      If VeinMatchingBtn.IsChecked Then
         VeinMatchingShow()
      Else
         VeinMatchingHide()
      End If
   End Sub

   Friend Function GetVeinMatchingContext() As Integer
      If IsNothing(m_VeinMatchingWnd) Then Return 0
      Return m_VeinMatchingWnd.VeinMatchingScene.GetCtx()
   End Function

   Friend Sub VeinMatchingShow()
      ' Se non già creata, non devo fare alcunchè
      If IsNothing(m_VeinMatchingWnd) Then Return
      ' Esecuzione
      m_VeinMatchingWnd.Show()
      EgtSetCurrentContext(m_CurrProjPage.CurrentProjectScene.GetCtx())
      VeinMatchingBtn.IsChecked = True
   End Sub

   Friend Sub VeinMatchingHide()
      ' Se non già creata, non devo fare alcunchè
      If IsNothing(m_VeinMatchingWnd) Then Return
      ' Esecuzione
      m_VeinMatchingWnd.Hide()
      EgtSetCurrentContext(m_CurrProjPage.CurrentProjectScene.GetCtx())
      VeinMatchingBtn.IsChecked = False
   End Sub

   Private Sub RegisterBtn_Checked(sender As Object, e As RoutedEventArgs) Handles RegisterBtn.Checked
      EgtSetCurrentContext(m_CurrProjPage.CurrentProjectScene.GetCtx())
      m_CurrProjPage.m_SceneButtons.MeasureBtn.IsChecked = False
      ' Nascondo bottoni ProjectMgrUC
      NewBtn.Visibility = Windows.Visibility.Hidden
      LoadBtn.Visibility = Windows.Visibility.Hidden
      SaveBtn.Visibility = Windows.Visibility.Hidden
      SaveNameBtn.Visibility = Windows.Visibility.Hidden
      CSVBtn.Visibility = Windows.Visibility.Hidden
      VeinMatchingBtn.Visibility = Windows.Visibility.Hidden
      ResetCutBtn.Visibility = Windows.Visibility.Hidden
      SimulateBtn.Visibility = Windows.Visibility.Hidden
      WorkBtn.Visibility = Windows.Visibility.Hidden
      ' Nascondo bottoni CadCutPageUC
      m_MainWindow.m_CadCutPageUC.PhotoBtn.Visibility = Windows.Visibility.Hidden
      m_MainWindow.m_CadCutPageUC.RawPartBtn.Visibility = Windows.Visibility.Hidden
      m_MainWindow.m_CadCutPageUC.DrawBtn.Visibility = Windows.Visibility.Hidden
      m_MainWindow.m_CadCutPageUC.ImportBtn.Visibility = Windows.Visibility.Hidden
      m_MainWindow.m_CadCutPageUC.SplitBtn.Visibility = Windows.Visibility.Hidden
      ' Nascondo bottoni nesting
      m_MainWindow.m_CadCutPageUC.m_NestPage.m_bRegister = True
      m_MainWindow.m_CadCutPageUC.m_NestPage.MaximizeMoveBtn.IsEnabled = False
      m_MainWindow.m_CadCutPageUC.m_NestPage.MagneticPiecesBtn.IsEnabled = False
      m_MainWindow.m_CadCutPageUC.m_NestPage.InsertPartBtn.Visibility = Windows.Visibility.Hidden
      m_MainWindow.m_CadCutPageUC.m_NestPage.StorePartBtn.Visibility = Windows.Visibility.Hidden
      m_MainWindow.m_CadCutPageUC.m_NestPage.RemovePartBtn.Visibility = Windows.Visibility.Hidden
      m_MainWindow.m_CadCutPageUC.m_NestPage.SelectAllBtn.Visibility = Windows.Visibility.Hidden
      m_MainWindow.m_CadCutPageUC.m_NestPage.DeselectAllBtn.Visibility = Windows.Visibility.Hidden
      ' Deseleziono tutto
      EgtDeselectAll()
      ' Se c'è la foto devo sistemare
      If m_CurrProjPage.GetPhoto() <> GDB_ID.NULL Then
         ' Salvo il riferimento della texture originale di ogni grezzo
         Dim nRawId As Integer = EgtGetFirstRawPart()
         While nRawId <> GDB_ID.NULL
            Dim nSolidId As Integer = EgtGetFirstNameInGroup(nRawId, NAME_RAW_SOLID)
            ' Recupero il riferimento originale e lo salvo nelle info
            Dim refTxr As New Frame3d
            EgtGetTextureFrame(nSolidId, GDB_ID.ROOT, refTxr)
            EgtSetInfo(nSolidId, "OriTxrRef", refTxr)
            ' Passo al successivo
            nRawId = EgtGetNextRawPart(nRawId)
         End While
         ' Modifiche sull'unico grezzo della prima fase 
         Dim nSolId = EgtGetFirstNameInGroup(m_CurrProjPage.m_nRawId, NAME_RAW_SOLID)
         ' Disabilito la texture sul grezzo
         EgtRemoveTextureData(nSolId)
         ' Sistemo il colore
         Dim Col As Color3d
         EgtGetCalcColor(nSolId, Col)
         Col.A = 20
         EgtSetColor(nSolId, Col, True)
         ' Visualizzo la foto
         m_MainWindow.m_CurrentProjectPageUC.ShowPhoto(True)
         ' Aggiorno visualizzazione
         EgtDraw()
      End If
      ' Visualizzo step adatti alla scelta fatta
      m_MainWindow.m_CadCutPageUC.m_NestPage.UpdateStepsOnUI()
      ' Cancello eventuali messaggi di errore/avvertimento
      m_CurrProjPage.ClearMessage()
   End Sub

   Private Sub RegisterBtn_Unchecked(sender As Object, e As RoutedEventArgs) Handles RegisterBtn.Unchecked
      EgtSetCurrentContext(m_CurrProjPage.CurrentProjectScene.GetCtx())
      m_CurrProjPage.m_SceneButtons.MeasureBtn.IsChecked = False
      ' Visualizzo bottoni ProjectMgrUC
      NewBtn.Visibility = Windows.Visibility.Visible
      LoadBtn.Visibility = Windows.Visibility.Visible
      SaveBtn.Visibility = Windows.Visibility.Visible
      SaveNameBtn.Visibility = Windows.Visibility.Visible
      If m_MainWindow.GetKeyOption(MainWindow.KEY_OPT.CSV_AUTO) Or
         m_MainWindow.GetKeyOption(MainWindow.KEY_OPT.CSV_SIMPLE) Then
         CSVBtn.Visibility = Windows.Visibility.Visible
      End If
      If m_MainWindow.GetKeyOption(MainWindow.KEY_OPT.MAN_PHOTO) And
         GetPrivateProfileInt(S_VEINMATCHING, K_VEINMA_ENABLE, 0, m_MainWindow.GetIniFile()) <> 0 Then
         VeinMatchingBtn.Visibility = Windows.Visibility.Visible
      End If
      ResetCutBtn.Visibility = Windows.Visibility.Visible
      SimulateBtn.Visibility = Windows.Visibility.Visible
      WorkBtn.Visibility = Windows.Visibility.Visible
      ' Visualizzo bottoni CadCutPageUC
      m_MainWindow.m_CadCutPageUC.PhotoBtn.Visibility = Windows.Visibility.Visible
      m_MainWindow.m_CadCutPageUC.RawPartBtn.Visibility = Windows.Visibility.Visible
      m_MainWindow.m_CadCutPageUC.DrawBtn.Visibility = Windows.Visibility.Visible
      m_MainWindow.m_CadCutPageUC.ImportBtn.Visibility = Windows.Visibility.Visible
      m_MainWindow.m_CadCutPageUC.SplitBtn.Visibility = Windows.Visibility.Visible
      ' Visualizzo bottoni nesting
      m_MainWindow.m_CadCutPageUC.m_NestPage.m_bRegister = False
      m_MainWindow.m_CadCutPageUC.m_NestPage.MaximizeMoveBtn.IsEnabled = True
      m_MainWindow.m_CadCutPageUC.m_NestPage.MagneticPiecesBtn.IsEnabled = True
      m_MainWindow.m_CadCutPageUC.m_NestPage.InsertPartBtn.Visibility = Windows.Visibility.Visible
      m_MainWindow.m_CadCutPageUC.m_NestPage.StorePartBtn.Visibility = Windows.Visibility.Visible
      m_MainWindow.m_CadCutPageUC.m_NestPage.RemovePartBtn.Visibility = Windows.Visibility.Visible
      m_MainWindow.m_CadCutPageUC.m_NestPage.SelectAllBtn.Visibility = Windows.Visibility.Visible
      m_MainWindow.m_CadCutPageUC.m_NestPage.DeselectAllBtn.Visibility = Windows.Visibility.Visible
      ' Se c'è la foto devo sistemare
      If m_CurrProjPage.GetPhoto() <> GDB_ID.NULL Then
         ' Recupero il riferimento originale del primo grezzo
         Dim nSolId = EgtGetFirstNameInGroup(m_CurrProjPage.m_nRawId, NAME_RAW_SOLID)
         Dim refOri1Txr As New Frame3d
         EgtGetInfo(nSolId, "OriTxrRef", refOri1Txr)
         ' Recupero il nome della texture dalla foto
         Dim sTxrName As String = String.Empty
         EgtGetTextureName(m_CurrProjPage.GetPhoto(), sTxrName)
         ' Recupero il riferimento della texture dalla foto
         Dim refPhTxr As New Frame3d
         m_CurrProjPage.GetPhotoTextureRef(refPhTxr)
         ' Inserisco la texture su tutti i grezzi
         Dim nRawId As Integer = EgtGetFirstRawPart()
         While nRawId <> GDB_ID.NULL
            Dim nSolidId = EgtGetFirstNameInGroup(nRawId, NAME_RAW_SOLID)
            ' Recupero il riferimento della texture originale
            Dim refOriTxr As New Frame3d
            EgtGetInfo(nSolidId, "OriTxrRef", refOriTxr)
            Dim vtMove As Vector3d = refOriTxr.Orig() - refOri1Txr.Orig()
            ' Carico la texture della foto sul grezzo
            EgtSetTextureName(nSolidId, sTxrName)
            ' Carico il nuovo riferimento della texture della foto sul grezzo
            Dim refTxr As New Frame3d(refPhTxr)
            refTxr.Move(vtMove)
            EgtSetTextureFrame(nSolidId, refTxr, GDB_RT.GLOB)
            ' Passo al successivo
            nRawId = EgtGetNextRawPart(nRawId)
         End While
         ' Modifiche sull'unico grezzo della prima fase 
         ' Sistemo il colore
         Dim colWhite As New Color3d(255, 255, 255, 100)
         EgtSetColor(nSolId, colWhite)
         ' Anche per il contorno
         Dim nOutlineId = EgtGetFirstNameInGroup(m_CurrProjPage.m_nRawId, NAME_RAW_OUTLINE)
         EgtSetColor(nOutlineId, colWhite)
         EgtSetStatus(nOutlineId, GDB_ST.OFF)
         ' Nascondo la foto
         m_MainWindow.m_CurrentProjectPageUC.ShowPhoto(False)
         ' Aggiorno visualizzazione
         EgtDraw()
      End If
      ' Visualizzo step adatti alla scelta fatta
      m_MainWindow.m_CadCutPageUC.m_NestPage.UpdateStepsOnUI()
      ' Cancello eventuali messaggi di errore/avvertimento
      m_CurrProjPage.ClearMessage()
   End Sub

End Class
