Attribute VB_Name = "ModEuro"
Public thepath$        'percorso avvio programma
Public thepath1$       'percorso file di lavoro
Public oplevel%        'livello abilitazione operatore =0 user =1 superutente
Public isgrabbing%   'flag di grab in corso
Public Xsize%          'numero pixel X dell'immagine
Public Ysize%          'numero pixel Y dell'immagine
Public BufPixel()  As Byte 'Matrice contenente i pixel
Public Pmat(1 To 1000, 1 To 2) As Integer 'matrice con X e Y dei punti trovati
Public numpoints%  'numero massimo dei punti che posso trovare
Public laseron%      'Flag di raggio laser acceso
Public LaserX&        'Coordinata X del punto di sparo riferita allo schermo (in Pixel)
Public LaserY&        'Coordinata Y del punto di sparo riferita allo schermo (in Pixel)
Public RefX&           'Coordinata X del reference point di macchina 1 laser
Public RefY&           'Coordinata Y del reference point di macchina 1 laser
Public RefX1&              'Coordinata X del reference point di macchina 2 laser
Public RefY1&           'Coordinata Y del reference point di macchina 2 laser
Public RefZ&           'Coordinata X del reference point di macchina tavola
Public RefW&           'Coordinata Y del reference point di macchina tavola
Public mctype%      'Tipo di motion controller, 1 = Galil
Public downfile$      'Nome di file di download per il motion controller
Public iodev$           'Contiene le schede IO da gestire
Public stepxy!           'numero passi/mm asse x
Public stepzw!           'numero passi/mm asse z
Public stept!           'numero passi/mm asse focale
Public mult&           'fattore moltiplicazione in Jog
Public accmax$       'accelerazione max Jog
Public accmin$        'accelerazione min Jog
Public speedmaxxy&   'velocita' max Jog xy
Public speedmaxzw&   'velocita' max Jog zw
Public speedkey%   'tasto accelerazione Jog, =16 shift =17 Ctrl
Public pixelmm!       'numero Pixel/MM schermo
Public workdir$       'directory di salvataggio file di lavoro
Public lastfile$         'ultimo file aperto
Public pwd$            'password criptata
Public ver$              'versione attuale
Public jogging%      'se =1 sono in jogging xy se = 2 in jogging% zw
Public oldx&           'vecchia posizione cursore X prima di entrare in jog
Public oldy&           'vecchia posizione cursore Y prima di entrare in jog
Public term$              'terminatore di record
Public justloaded%  'se =1 ho appena avviato
Public statjog%       'stato del jog in corso: 0 ref macchina, 1 ref taglio, 2 corner 1, 3 corner 2
Public lang$            'linguaggio
Public CameraGapX& 'offset telecamere X
Public CameraGapY& 'offset telecamere Y
Public dispstep%     'visualizza posizioni in passi
Public pumpon%     'flag di pompa accesa
Public rfon%           'flag di RF qswitch acceso
Public wason!        'contaore
Public thecontrast& 'contrasto display
Public thebrightness& 'luminosita' display
Public lastfreq$       'ultimo valore di frequenza programmato
Public lastcurr$       'ultimo valore di corrente programmato
Public tableoutx$    'tavola fuori X
Public tableouty$    'tavola fuori Y
Public dtcurr&        'timer di ultimo valore di frequenza programmato
Public vuotoff%
Public asklamp%
Public loopingsafety%
Public exitsafety%
Public tin%
Public oldmsg$
Public dscalex#
Public dscaley#
Public thestrings$
Public flagpuntali%
Public fouraxes% 'se =1 uso 4 assi galil se no 2 (xy)
Public vacuum% 'se =1 c'e' il vuoto tavola, altrimenti no
Public doubletable% 'se =1 c'e' doppia tavola
Public doublecamera% 'se =1 c'e' doppia telecamera
Public steppixelx! 'numero di step motore per pixel x
Public steppixely! 'numero di step motore per pixel y
Public puntali% 'se =1 puntali alti se =0 bassi
Public dontprobe% 'se =1 non abbassa i puntali quando fermo
Public mancurr! 'ultimo valore di corrente impostato manualmente
Public manfreq! 'ultimo valore di frequenza impostato manualmente
Public flagwork% 'se =1 sono in esecuzione
Public reptext$ 'testo puro  cut report
Public reptextRTF$ 'testo RTF cut report
Public theguard% 'flag di scan guard chiuso
Public thefunctional% 'se l'ultimo taglio era funzionale
Public thefinalval! 'valore finale di res o volt
Public theiset! 'corrente settata sullo strumento
Public ilasmax! 'corrente di fondoscala laser
Public workexit%
Public currtrimnum% 'numero puntato dall'editor quando si edita la casella numero taglio
Public debugging% 'se =1 sono in debug
Public filelogging% 'se =1 salvo l'esecuzione tagli su file
Public thelogfile$  'C:\path\log.txt file in cui vengono salvati i dettagli di taglio
Public plc1% 'se =1 c'e' il plc n 1

Public blnTavolaCarico As Boolean     'Se true indica la tavola nella posizione di carico
Public sngTavolaCarico As Single      'Valore dell'encoder corrispondente alla posizione di carico
Public sngTavolaScarico As Single     'Valore dell'encoder corrispondente alla posizione di scarico

Declare Function timeGetTime Lib "winmm.dll" () As Long
Declare Function GetAsyncKeyState% Lib "user32" (ByVal vKey As Long)
Declare Function SetCursorPos& Lib "user32" (ByVal x As Long, ByVal y As Long)
Declare Function GetCursorPos& Lib "user32" (lpPoint As POINTAPI)
Declare Function SetWindowPos Lib "user32" (ByVal hwnd As Long, ByVal hWndInsertAfter As Long, ByVal x As Long, ByVal y As Long, ByVal cx As Long, ByVal cy As Long, ByVal wFlags As Long) As Long
Declare Function PortIn Lib "c:\winnt\system\portio.dll" (ByVal ad%) As Byte
Declare Sub PortOut Lib "c:\winnt\system\portio.dll" (ByVal ad%, ByVal tb As Byte)
Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (hpvDest As Any, hpvSource As Any, ByVal cbCopy As Long)

Type POINTAPI  '  8 Bytes
     x As Long
     y As Long
End Type
Public pt As POINTAPI

'------ SHUT DOWN
      'The ExitWindowsEx function either logs off, shuts down, or shuts 'down and restarts the system.
Declare Function ExitWindowsEx Lib "user32" (ByVal dwOptions As Long, ByVal dwReserved As Long) As Long
      'The GetLastError function returns the calling thread's last-error
      'code value. The last-error code is maintained on a per-thread basis.
      'Multiple threads do not overwrite each other's last-error code.
Declare Function GetLastError Lib "kernel32" () As Long
      'The GetVersion function returns the operating system in use.
Declare Function GetVersion Lib "kernel32" () As Long
      'The GetCurrentProcess function returns a pseudohandle for the
      'current process.
Declare Function GetCurrentProcess Lib "kernel32" () As Long
      'The OpenProcessToken function opens the access token associated with
      'a process.
Declare Function OpenProcessToken Lib "advapi32" (ByVal ProcessHandle As Long, ByVal DesiredAccess As Long, TokenHandle As Long) As Long
      'The LookupPrivilegeValue function retrieves the locally unique
      'identifier (LUID) used on a specified system to locally represent
      'the specified privilege name.
Declare Function LookupPrivilegeValue Lib "advapi32" Alias "LookupPrivilegeValueA" (ByVal lpSystemName As String, ByVal lpName As String, lpLuid As LUID) As Long
      'The AdjustTokenPrivileges function enables or disables privileges
      'in the specified access token. Enabling or disabling privileges
      'in an access token requires TOKEN_ADJUST_PRIVILEGES access.
Declare Function AdjustTokenPrivileges Lib "advapi32" (ByVal TokenHandle As Long, ByVal DisableAllPrivileges As Long, NewState As TOKEN_PRIVILEGES, ByVal BufferLength As Long, PreviousState As TOKEN_PRIVILEGES, ReturnLength As Long) As Long
Declare Sub SetLastError Lib "kernel32" (ByVal dwErrCode As Long)

Type LUID
        UsedPart As Long
        IgnoredForNowHigh32BitPart As Long
End Type

Private Type LUID_AND_ATTRIBUTES
         TheLuid As LUID
         Attributes As Long
End Type

Private Type TOKEN_PRIVILEGES
         PrivilegeCount As Long
         TheLuid As LUID
         Attributes As Long
End Type

Public Const EWX_SHUTDOWN As Long = 1
Public Const EWX_FORCE As Long = 4
Sub executu(cutn%, thetable%, execute%, cuterr%)
'esegue un taglio incondizionato
                            'attende che la tavola sia in posizione
                            Hasdone% = 0
                            cutrefx& = Val(TLasReferenceX$)
                            cutrefy& = Val(TLasReferenceY$)
                            cutrefx1& = Val(TLasReferenceX1$)
                            cutrefy1& = Val(TLasReferenceY1$)
                            cutrefz& = Val(TTabReferenceZ$)
                            cutrefw& = Val(TTabReferenceW$)
                            If doubletable% = 1 Then
                            Do
                                Call readdevice(0, 0, 10)
                                If execute% = 1 Then
                                    'If doubletable% = 1 Then
                                        If thetable% = 0 Then
                                            If d0.I_Tavola_A_NReady = 0 Then Exit Do
                                        Else
                                            If d0.I_Tavola_B_NReady = 0 Then Exit Do
                                        End If
                                    'End If
                                Else
                                    Exit Do
                                End If
                                DoEvents
                                ek% = GetAsyncKeyState%(27) 'esc key
                                If (Hasdone% = 2) Or (workexit% > 0) Or (ek% <> 0) Then
                                    'interruzione operatore
                                    cuterr% = 4
                                    'If ek% <> 0 Then SendKeys "{ESC}", 1
                                    If ek% <> 0 Then pressesc% = 1
                                    GoTo cutfailed
                                End If
                            
                            Loop
                            End If
                            If execute% = 1 Then
                                Call showstatus("Executing Trim")
                            Else
                                Call showstatus("Testing Trim")
                            End If
                            cuterr% = 0
                            thematrix$(4001) = Trim$(Str(cuterr%))
                            'esegue o testa (execute%=0) taglio singolo digitale con strumento K 2700
                            'cuterr%:=0 nessun errore, =1 gia' scattato =2 non scattato=3 vario=4 interrotto dall'utente
                            k% = cutn%
                            If k% <= UBound(TrimMatrix) Then
                                myrecord = TrimMatrix(k%)
                            Else
                                cuterr% = 3
                                GoTo cutfailed
                            End If
                            rnom2! = 0
                            rnom1! = 0
                            dcut% = 0
                            cutType% = Val(cleanval(myrecord.cutType))
                            usevision% = Val(cleanval(myrecord.vision))
                            Select Case cutType%
                            Case 6
                            Case Else
                                cuterr% = 3
                                GoTo cutfailed
                            End Select
                            gapx& = Val(cleanval(myrecord.startx))
                            gapy& = Val(cleanval(myrecord.starty))
                            deltax& = Val(cleanval(myrecord.stopx)) - Val(cleanval(myrecord.startx))
                            deltay& = Val(cleanval(myrecord.stopy)) - Val(cleanval(myrecord.starty))
                            'cutspeed& = mm2step#(Val(cleanval(myrecord.speed)), stepzw!)
                            cutspeed& = mm2step#(Val(cleanval(myrecord.speed)), stepxy!)
                                thecutdir$ = "0"
                                If Abs(deltay&) > Abs(deltax&) Then thecutdir$ = "1"
                                Select Case thecutdir$
                                Case "0"
                                    deltax1& = deltax&
                                    deltay1& = 0
                                    deltax2& = 0
                                    deltay2& = 0
                                Case Else
                                    deltax1& = 0
                                    deltay1& = deltay&
                                    deltax2& = 0
                                    deltay2& = 0
                                End Select
                            'posizionamento su step e inizio taglio
                            guard% = 0
                            If thetable% = 0 Then
                                ccutrefx& = cutrefx& + gapx&
                                ccutrefy& = cutrefy& + gapy&
                                ccutrefz& = cutrefz& + gapZ&
                                ccutrefw& = cutrefw& + gapW&
                            Else
                                ccutrefx& = cutrefx1& + gapx&
                                ccutrefy& = cutrefy1& + gapy&
                                ccutrefz& = cutrefz& + gapZ&
                                ccutrefw& = cutrefw& + gapW&
                            End If
                            Hasdone% = 0
                            Call gotoposxyzw(Trim(Str(ccutrefx&)), Trim(Str(ccutrefy&)), Trim(Str(ccutrefz&)), Trim(Str(ccutrefw&)))
                            Call setoutput(0, d0.O_Rele_Work_Standby)
                            thefreq! = Val(cleanval(myrecord.freq)) * 1000
                            lastfreq$ = Trim$(Str(thefreq!))
                            Call setfreqda(1, thefreq!)
                            thecurr! = myrecord.current
                            lastcurr$ = Trim$(Str(thecurr!))
                            Call setda(1, thecurr!, ilasmax!)
                            'controllo puntali
                            Call readdevice(0, 0, 10)
                            If FrmEuro.Imglampon.Visible = True Then
                                If FrmEuro.Lblfreq.Caption <> lastfreq$ Then FrmEuro.Lblfreq.Caption = lastfreq$
                                If FrmEuro.Lblcurr.Caption <> lastcurr$ Then FrmEuro.Lblcurr.Caption = lastcurr$
                            Else
                                If FrmEuro.Lblfreq.Caption <> "0" Then FrmEuro.Lblfreq.Caption = "0"
                                If FrmEuro.Lblcurr.Caption <> "0" Then FrmEuro.Lblcurr.Caption = "0"
                            End If
                            DoEvents
                            If d0.I_Puntali_Alti = 0 Then
                                puntali% = 0
                                  Else
                                puntali% = 1
                            End If
                            If flagpuntali% = 0 Then puntali% = 0
                            Do
                                DoEvents
                                If Hasdone% = 2 Or workexit% > 0 Then Exit Do
                            Loop While puntali% = 1
                            If Hasdone% = 2 Or workexit% > 0 Then
                                cuterr% = 4
                                GoTo cutfailed
                            End If
                            tcmd$ = "DX1=" + Str(deltax1&)
                            Debug.Print tcmd$
                            Call galilcmd(tcmd$, res$, ermsg$)
                            tcmd$ = "DY1=" + Str(deltay1&)
                            Debug.Print tcmd$
                            Call galilcmd(tcmd$, res$, ermsg$)
                            tcmd$ = "DX2=" + Str(deltax2&)
                            Debug.Print tcmd$
                            Call galilcmd(tcmd$, res$, ermsg$)
                            tcmd$ = "DY2=" + Str(deltay2&)
                            Debug.Print tcmd$
                            Call galilcmd(tcmd$, res$, ermsg$)
                            tcmd$ = "VSC=" + Str(cutspeed&)
                            Debug.Print tcmd$
                            Call galilcmd(tcmd$, res$, ermsg$)
                            theiset! = 0
                            donetest% = 0
                            Hasdone% = 0
                            'Call reset2700
                            Do
                                DoEvents
                                If Hasdone% = 2 Or workexit% > 0 Then
                                    cuterr% = 4
                                    GoTo cutfailed
                                End If
                            Loop While moving% > 0
                            If Hasdone% = 2 Or workexit% > 0 Then
                                'interruzione operatore
                                cuterr% = 4
                                GoTo cutfailed
                            End If
                            'comando di taglio galil
                            
                            'qui va messo il correttore di visione, se abilitato
                            
                            gapstepx& = 0
                            gapstepy& = 0
                            
                            ffnn$ = lastfile$
                            If ffnn$ = "\" Then ffnn$ = ""
                            visionfilename$ = thepath1$ + ffnn$ + Trim$(Str(cutn%)) + ".vis"
                            exf$ = Dir$(visionfilename$)
                            
                            If exf$ <> "" And usevision% = 1 Then
                            'il file di visione esiste
                                Call loadvision(visionfilename$)
                                thedimim& = 768& * 576&
                                ReDim myimage(1 To thedimim&) As Byte
                                FrmEuro.Digitizer.Halt
                                FrmEuro.Digitizer.Grab
                                FrmEuro.Buffer.Get myimage
                                thedimim& = Len(copystring$)
                                ReDim mytemplate(1 To thedimim&) As Byte
                                CopyMemory2 mytemplate(1), copystring$, thedimim&
                                Call findvision(found%, foundx&, foundy&)
                                If found% = 1 Then
                                    vgapx& = (foundx& - TempLeft)
                                    vgapy& = (foundy& - TempTop)
                                    gapstepx& = vgapx& * steppixelx!
                                    gapstepy& = vgapy& * steppixely!
                                    'visualizza rettangolo verde di found
                                    FrmEuro.Picfx1.Left = foundx& * Screen.TwipsPerPixelX
                                    FrmEuro.Picfx1.Top = foundy& * Screen.TwipsPerPixelY
                                    FrmEuro.Picfx1.Width = (TempRight - TempLeft) * Screen.TwipsPerPixelX
                                    FrmEuro.Picfy1.Left = FrmEuro.Picfx1.Left
                                    FrmEuro.Picfy1.Top = FrmEuro.Picfx1.Top
                                    FrmEuro.Picfy1.Height = (TempBottom - TempTop) * Screen.TwipsPerPixelY
                                    FrmEuro.Picfx2.Left = FrmEuro.Picfx1.Left
                                    FrmEuro.Picfx2.Width = FrmEuro.Picfx1.Width
                                    FrmEuro.Picfx2.Top = FrmEuro.Picfx1.Top + FrmEuro.Picfy1.Height
                                    FrmEuro.Picfy2.Top = FrmEuro.Picfy1.Top
                                    FrmEuro.Picfy2.Height = FrmEuro.Picfy1.Height
                                    FrmEuro.Picfy2.Left = FrmEuro.Picfy1.Left + FrmEuro.Picfx1.Width
                                    FrmEuro.Picfx1.Visible = True
                                    FrmEuro.Picfx2.Visible = True
                                    FrmEuro.Picfy1.Visible = True
                                    FrmEuro.Picfy2.Visible = True
                                    dddttt& = timeGetTime&
                                    Do
                                        DoEvents
                                        If timeGetTime& - dddttt& < 0 Then Exit Do
                                    Loop While (timeGetTime& - dddttt&) < 200
                                End If
                                Erase myimage
                                Erase mytemplate
                                copystring$ = ""
                                FrmEuro.Digitizer.GrabContinuous
                                DoEvents
                                FrmEuro.Picfx1.Visible = False
                                FrmEuro.Picfx2.Visible = False
                                FrmEuro.Picfy1.Visible = False
                                FrmEuro.Picfy2.Visible = False

                            End If
                            
                            If gapstepx& <> 0 Or gapstepy& <> 0 Then
                                'correzione spostamento
                                ccutrefx& = ccutrefx& + gapxstep&
                                ccutrefy& = ccutrefy& - gapstepy&
                                
                                Hasdone% = 0
                                Call gotoposxyzw(Str(ccutrefx&), Str(ccutrefy&), Str(ccutrefz&), Str(ccutrefw&))
                                Do
                                    DoEvents
                                    If Hasdone% = 2 Or workexit% > 0 Then
                                        cuterr% = 4
                                        GoTo cutfailed
                                    End If
                                Loop While moving% > 0
                            End If
                            
                            tcmd$ = "CDONE=0"
                            Debug.Print tcmd$
                            Call galilcmd(tcmd$, res$, ermsg$)
                            Call enablework
                            FrmEuro.Enabled = False
                            tcmd$ = "XQ#SCUT"
                            Debug.Print tcmd$
                            Call galilcmd(tcmd$, res$, ermsg$)
                            'attesa primo stop
                            tout% = 0
                            numseconds% = 20000 / cutspeed&
                            Hasdone% = 0
                            If dcut% = 0 Then tout% = 5
                            If uncond% = 1 Then tout% = -1
                            Call waitcut2700(numseconds%, tout%)
                            If Hasdone% = 2 Or workexit% > 0 Then
                                cuterr% = 4
                                GoTo cutfailed
                            End If
                            If tout% = 1 Then
                                'MsgBox ("Cut Timeout")
                                cuterr% = 2
                                GoTo cutfailed
                            End If
                            Exit Sub
cutfailed:
'E1=cuterr%
thematrix$(4001) = Trim$(Str(cuterr%))
'Call exitwork
    
End Sub



Sub updatefilelog(mr$)
mmr$ = mr$
If Right$(mr$, 2) = Chr$(13) + Chr$(10) Then
    mmr$ = Left$(mmr$, Len(mmr$) - 2)
End If
un% = FreeFile
Open thelogfile$ For Append As #un%
    Print #un%, mmr$
Close #un%
End Sub
Sub updatedebug(dstring$)
mdstring$ = dstring$
If Right$(mdstring$, 2) = Chr$(13) + Chr$(10) Then
    mdstring$ = Left$(mdstring$, Len(mdstring$) - 2)
End If
mdstring$ = mdstring$ + " " + Str(Int(Timer * 10) / 10) + Chr$(13) + Chr$(10)
un% = FreeFile
Open thepath$ + "debug.txt" For Append As #un%
    Print #un%, mdstring$;
Close #un%
End Sub

Sub puntaliup(checkok%)
checkok% = 0
If flagpuntali% Mod 2 = 0 Then checkok% = 1: Exit Sub
flagpuntali% = 2
Call resetoutput(0, d0.O_Rele_Puntali_Down)
Call readdevice(0, 0, 10)
If d0.I_Puntali_Alti = 1 Then puntali% = 1: checkok% = 1: flagpuntali% = 1: Exit Sub
ms& = 2000
dt1& = timeGetTime&()
Do
    DoEvents
    dt2& = timeGetTime&()
    dif& = dt2& - dt1&
    If dif& < 0 Then dt1& = timeGetTime&()
    Call readdevice(0, 0, 10)
    If d0.I_Puntali_Alti = 1 Then puntali% = 1: checkok% = 1: flagpuntali% = 1: Exit Sub
Loop While dif& < ms&
flagpuntali% = 1
End Sub
Sub checkscan(md%, proben%, card%, bank%)
Select Case proben%
Case 3, 6, 33, 38
    cn% = 1
Case 13, 24, 39, 40
    cn% = 2
Case 2, 8, 12, 36
    cn% = 3
Case 10, 11, 16, 20
    cn% = 4
Case 14, 17, 34, 37
    cn% = 5
Case 19, 29, 31, 32
    cn% = 6
Case 18, 26, 30, 35
    cn% = 7
Case 1, 21, 27, 28
    cn% = 8
Case 7, 9, 22, 23
    cn% = 9
Case 4, 5, 15, 25
    cn% = 10
Case Else
    card% = 0
    bank% = 0
    Exit Sub
End Select
Select Case md%
Case 1
    'scanner high
    Select Case proben%
    Case 1, 3, 8, 10, 15, 19, 23, 35, 37, 39
        'H1
        card% = 1
        bank% = 1
    Case 5, 7, 11, 12, 17, 21, 24, 26, 29, 33
        'H2
        card% = 1
        bank% = 4
    Case 9, 13, 20, 25, 28, 30, 32, 34, 36, 38
        'H3
        card% = 2
        bank% = 1
    Case Else
        bank% = 0
        card% = 0
    End Select
Case 2
    'scanner low
    Select Case proben%
    Case 1, 3, 8, 10, 15, 19, 23, 35, 37, 39
        'L1
        card% = 1
        bank% = 2
    Case 5, 7, 11, 12, 17, 21, 24, 26, 29, 33
        'L2
        card% = 2
        bank% = 2
    Case 2, 4, 6, 14, 16, 18, 22, 27, 31, 40
        'L3
        card% = 2
        bank% = 4
    Case Else
        card% = 0
        bank% = 0
    End Select
Case 3
    'scanner guard
    Select Case proben%
    Case 1, 3, 8, 10, 15, 19, 23, 35, 37, 39
        'G1
        card% = 1
        bank% = 3
    Case 5, 7, 11, 12, 17, 21, 24, 26, 29, 33
        'G2
        card% = 2
        bank% = 3
    Case Else
        bank% = 0
        card% = 0
    End Select
End Select
If bank% > 0 Then bank% = ((bank% - 1) * 10) + cn%
End Sub
Sub puntalidown(checkok%)
checkok% = 0
If dontprobe% = 1 Then dontprobe% = 0: checkok% = 1: Exit Sub
If flagpuntali% Mod 2 = 0 Then checkok% = 1: Exit Sub
flagpuntali% = 2
Call setoutput(0, d0.O_Rele_Puntali_Down)
Call Delay(500)
Call readdevice(0, 0, 10)
If d0.I_Puntali_Alti = 0 Then puntali% = 0: checkok% = 1
flagpuntali% = 1
End Sub

Sub savebmp(datamatrix() As Byte, filname$)
'crea un file BMP a 256 tonalita' di grigio
'l'header (1078 byte) contiene il numero complessivo
'di byte (pos 3) numero col (pos 20) numero righe (pos 24)
'numero di raw data (pos 36) e una lookup table di 256 x 4 byte
'le dimensioni vengono estratte dalla matrice che deve essere di byte.
'durante il salvataggio, viene invertito l'asse y per motivi di standard bmp
dt = Timer
SizeX& = UBound(datamatrix(), 1)
SizeY& = UBound(datamatrix(), 2)
'SizeX& = 768
'SizeY& = 576
raw& = SizeX& * SizeY&
nd& = 1078& + raw&
header$ = Chr$(66) + Chr$(77) + MKL$(nd&) + String$(4, Chr$(0))
header$ = header$ + Chr$(54) + Chr$(4) + String$(2, Chr$(0))
header$ = header$ + Chr$(40) + String$(3, Chr$(0))
header$ = header$ + MKL$(SizeX&) + MKL$(SizeY&) + Chr$(1)
header$ = header$ + Chr$(0) + Chr$(8) + String$(5, Chr$(0))
header$ = header$ + MKL$(raw&) + String$(16, 0)
For i% = 0 To 255
    h1$ = h1$ + String$(3, Chr$(i%)) + Chr$(0)
Next i%
header$ = header$ + h1$
un% = FreeFile
Open filname$ For Output As #un%
Print #un%, header$;
thestring$ = Space$(SizeX&)
For k% = SizeY& To 1 Step -1
    CopyMemory ByVal thestring$, datamatrix(1, k%), SizeX&
    Print #un%, thestring$;
Next k%
thestring$ = ""
'thestring1$ = Space$(SizeX& * SizeY&)
'CopyMemory ByVal thestring1$, ByVal Form1.Buffer.HostAddress, SizeX& * SizeY&
'Print #un%, thestring1$;

Close un%
Debug.Print Timer - dt
End Sub
Function MKL$(x As Long)
    temp$ = Space$(4)
    CopyMemory ByVal temp$, x&, 4
    MKL$ = temp$
End Function

      
      Sub AdjustToken()

      '********************************************************************
      '* This procedure sets the proper privileges to allow a log off or a
      '* shut down to occur under Windows NT.
      '********************************************************************

         Const TOKEN_ADJUST_PRIVILEGES = &H20
         Const TOKEN_QUERY = &H8
         Const SE_PRIVILEGE_ENABLED = &H2

         Dim hdlProcessHandle As Long
         Dim hdlTokenHandle As Long
         Dim tmpLuid As LUID
         Dim tkp As TOKEN_PRIVILEGES
         Dim tkpNewButIgnored As TOKEN_PRIVILEGES
         Dim lBufferNeeded As Long

         'Set the error code of the last thread to zero using the
         'SetLast Error function. Do this so that the GetLastError
         'function does not return a value other than zero for no
         'apparent reason.
         SetLastError 0

         'Use the GetCurrentProcess function to set the hdlProcessHandle
         'variable.
         hdlProcessHandle = GetCurrentProcess()

         If GetLastError <> 0 Then
            MsgBox "GetCurrentProcess error==" & GetLastError
         End If

         OpenProcessToken hdlProcessHandle, _
            (TOKEN_ADJUST_PRIVILEGES Or TOKEN_QUERY), hdlTokenHandle

         If GetLastError <> 0 Then
            MsgBox "OpenProcessToken error==" & GetLastError
         End If

         'Get the LUID for shutdown privilege
         LookupPrivilegeValue "", "SeShutdownPrivilege", tmpLuid

         If GetLastError <> 0 Then
            MsgBox "LookupPrivilegeValue error==" & GetLastError
         End If

         tkp.PrivilegeCount = 1    ' One privilege to set
         tkp.TheLuid = tmpLuid
         tkp.Attributes = SE_PRIVILEGE_ENABLED

         'Enable the shutdown privilege in the access token of this process
         AdjustTokenPrivileges hdlTokenHandle, _
                               False, _
                               tkp, _
                               Len(tkpNewButIgnored), _
                               tkpNewButIgnored, _
                               lBufferNeeded

         If GetLastError <> 0 Then
            MsgBox "AdjustTokenPrivileges error==" & GetLastError
         End If

      End Sub
Sub exitwork()
    flagdopsi% = 0
    FrmEuro.Lblpsi.Visible = False
    FrmEuro.Lblpsi.Caption = ""
    oldmsg$ = ""
    Call showstatus("")
    FrmEuro.Enabled = True
    'muove il tastatore in posizione sicura
    tcmd$ = "ST Z"
    Call galilcmd(tcmd$, res$, ermsg$)
    tcmd$ = "SP ,," + Str(10 * speedmaxzw&) + ","
    Call galilcmd(tcmd$, res$, ermsg$)
    Call Delay(100)
    tcmd$ = "PA ,,100,;BG Z"
    Call galilcmd(tcmd$, res$, ermsg$)

    flagwork% = 0
    Call PlcGotoPos(1, PlcMinPos$)
    FrmEuro.Timerwork.Enabled = False
    'If workexit% = 1 Then workexit% = 2: Call tableout
    'If workexit% = 0 Then Call rescontinue
End Sub
Sub updatereport(mr$, colr%)
    If debugging% = 1 Then
        Call updatedebug(mr$)
   End If
    If filelogging% = 1 Then
        Call updatefilelog(mr$)
    End If
    If flagdopsi% > 0 Then Exit Sub
    If Len(Frmrep.TxtReport.Text) > 30000 Then Frmrep.TxtReport.Text = ""
    Select Case colr%
    Case 0
        Frmrep.TxtReport.SelColor = RGB(0, 0, 0)
    Case 1
        Frmrep.TxtReport.SelColor = RGB(255, 0, 0)
    Case 2
        Frmrep.TxtReport.SelColor = RGB(0, 255, 0)
    End Select
    Frmrep.TxtReport.SelStart = 65535
    Frmrep.TxtReport.SelText = mr$ + Chr$(13) + Chr$(10)
    Frmrep.TxtReport.SelStart = 65535
    If Len(Frmrep.TxtReport.Text) > 30000 Then Frmrep.TxtReport.Text = Right$(Frmrep.TxtReport.Text, 20000)
    If UCase$(Screen.ActiveForm.Name) <> "FRMREP" Then
        Frmrep.Show
        Frmrep.SetFocus
    End If
End Sub
Sub execwork(testing%)
            'If flagdopsi% > 0 Then Exit Sub
            'muove il pallet in posizione sicura
            tcmd$ = "ST Z"
            Call galilcmd(tcmd$, res$, ermsg$)
            tcmd$ = "SP ,," + Str(10 * speedmaxzw&) + ","
            Call galilcmd(tcmd$, res$, ermsg$)
            Call Delay(100)
            tcmd$ = "PA ,,100,;BG Z"
            Call galilcmd(tcmd$, res$, ermsg$)
            
            Hasdone% = 0
            workexit% = 0
            pressesc% = 0
            FrmEuro.Enabled = False
            flagwork% = 1
            oldmsg$ = ""
            If debugging% = 1 Then
                    Call updatedebug("New Work Session")
            End If
            
            'hasdone%=1 terminato posizionamento
            'hasdone%=2 uscita con esc
            'hasdone%=3 errore interprete
            'hasdone%=4 accensione lampada
            'hasdone    %=5 uscita per allarme
            Call checkmachineon(ok%)
            If ok% = 0 Then
                Call exitwork
                Exit Sub
            End If
GoTo cutk
            If testing% = 0 Then
                If d0.I_Contaore_Laser_On = 0 Then
                    Call exitwork
                    MsgBox (mss$(24))
                    Exit Sub
                End If
                Call setoutput(0, d0.O_RF_On_12V)
            End If
cutk:
            If lastfile$ = "\" Then
                Call exitwork
                MsgBox (mss(25))
                Exit Sub
            End If
            Hasdone% = 0 '''
            Call checksafety
            'Call tablein(0)
            'Call Delay(250)
            'Call readdevice(0,0,12)
            'If d0.I_Pressione_Aria = 0 Then
                'Call exitwork
                'MsgBox (mss$(26))
                'Exit Sub
            'End If
            msg$ = mss$(27)
            Call showstatus(msg$)
            nstx% = Val(TNumStepZ$)
            nsty% = Val(TNumStepW$)
            If nstx% <= 0 Then nstx% = 1
            If nsty% <= 0 Then nsty% = 1
            cutrefx& = Val(TLasReferenceX$)
            cutrefy& = Val(TLasReferenceY$)
            cutrefx1& = Val(TLasReferenceX1$)
            cutrefy1& = Val(TLasReferenceY1$)
            cutrefz& = Val(TTabReferenceZ$)
            cutrefw& = Val(TTabReferenceW$)
            'Do
                'DoEvents
            'Loop While Hasdone% = 0
            'If Hasdone% = 2 Then
                'Call exitwork
                'msg$ = ""
                'Call showstatus(msg$)
                'Exit Sub
            'End If
            'tcmd$ = "CDONE=0"
            'Call galilcmd(tcmd$, res$, ermsg$)
            'Call enablework
            'FrmEuro.Enabled = False
            'mr$ = " "
            'Call updatereport(mr$, 0)
            'mr$ = Date$ + " " + Time$
            'Call updatereport(mr$, 0)
            'mr$ = " "
            'Call updatereport(mr$, 0)
            'Frmrep.Visible = True
            If psistring$ <> "" And Val(Uusepsi$) = 1 Then
                FrmEuro.Lblpsi.Caption = "Esc to quit the interpreter"
                FrmEuro.Lblpsi.Visible = True
                'analisi psi qui
                pcounter& = 0
                flagdopsi% = 1
                'Timerpsi.Enabled = True
                FrmEuro.txtinter.Text = psistring$
                ek% = GetAsyncKeyState%(27) 'esc key
                Do
                    DoEvents
                    opcounter& = pcounter&
                    Call psiliner("", pcounter&, 1, FrmEuro.txtinter)
                    ek% = GetAsyncKeyState%(27) 'esc key
                    If (ek% <> 0) Or (pressesc% = 1) Then
                        pressesc% = 0
                        pcounter& = -3
                    End If
                Loop While pcounter& >= 0
                Select Case pcounter&
                Case -1
                    thmsg$ = "Execution terminated"
                Case -2
                    thmsg$ = "Execution terminated for errors at line:" + Str(opcounter&)
                Case -3
                    thmsg$ = "Terminated by user"
                End Select
                Do
                    'attende la fine pressione tasto
                    ek% = GetAsyncKeyState%(27) 'esc key
                    DoEvents
                Loop While ek% <> 0
                MsgBox (thmsg$)
                flagdopsi% = 0
                Call exitwork
                Exit Sub
            Else
                Call exitwork
                Exit Sub
            End If
            Exit Sub
            For i% = 1 To nsty%
                mr$ = "STEP Y:" + Str(i%)
                Call updatereport(mr$, 0)
                gapW& = (1 - i%) * mm2step#(Val(TTabStepW$), stepzw!)
                For j% = 1 To nstx%
                        thekg% = 0
                        thekb% = 0
                        cutfail% = 0
                        mr$ = "STEP X:" + Str(j%)
                        Call updatereport(mr$, 0)
                        gapZ& = (j% - 1) * mm2step#(Val(TTabStepZ$), stepzw!)
                        thexecstring$ = Trim$(TTrimExe$)
                        If thexecstring$ <> "" Then thexecstring$ = thexecstring$ + ","
startcut:
                        Do While thexecstring$ <> ""
                            slope% = 0
                            uncond% = 0
                            funct% = 0
                            cm% = InStr(thexecstring$, ",")
                            If cm% > 0 Then
                                cutk$ = Trim$(Left$(thexecstring$, cm% - 1))
                                k% = Val(cutk$)
                            Else
                                Exit Do
                            End If
                            thexecstring$ = Mid$(thexecstring$, cm% + 1)
                            If k% <= UBound(TrimMatrix) Then
                                myrecord = TrimMatrix(k%)
                            Else
                                GoTo startcut
                            End If
                            rnom2! = 0
                            rnom1! = 0
                            dcut% = 0
                            cutType% = Val(cleanval(myrecord.cutType))
                            cutstep! = Val(cleanval(myrecord.serpstep))
                            funct% = Val(cleanval(myrecord.func))
                            thefunctional% = funct%
                            slope% = Val(cleanval(myrecord.slope))
                            Select Case cutType%
                            Case 0, 1
                                '0 doppio
                                '1 L
                                If cutType% = 0 Then
                                    mr$ = "CUT:" + Str(k%) + " (double cut)"
                                Else
                                    mr$ = "CUT:" + Str(k%) + " (L cut)"
                                End If
                                Call updatereport(mr$, 0)
                                If Trim$(cleanval(myrecord.reslabel)) <> "" Then
                                    mr$ = "LABEL: " + cleanval(myrecord.reslabel)
                                    Call updatereport(mr$, 0)
                                End If
                                Call updatereport(mr$, 0)
                                dcut% = 1
                                If funct% = 0 Then
                                    'taglio ohmico
                                    rnom2! = Val(cleanval(myrecord.ohmvalue))
                                    ornom2! = rnom2!
                                    Select Case Val(cleanval(myrecord.cutPre))
                                    Case Is <= 0, Is >= 100
                                        Case Else
                                        rnom2! = rnom2! - (Val(cleanval(myrecord.cutPre)) * rnom2!) / 100
                                    End Select
                                    Select Case Val(cleanval(myrecord.cut1St))
                                    Case Is <= 0, Is >= 100
                                        GoTo errh
                                    End Select
                                    rnom1! = (rnom2! * Val(cleanval(myrecord.cut1St))) / 100
                                    Select Case rnom1!
                                    Case 0, Is >= rnom2!
                                        GoTo errh
                                    End Select
                                Else
                                    'taglio funzionale
                                    vnom2! = Val(cleanval(myrecord.voltvalue))
                                    ovnom2! = vnom2!
                                    Select Case Val(cleanval(myrecord.cutPre))
                                    Case Is <= 0, Is >= 100
                                    Case Else
                                        vnom2! = vnom2! - (Val(cleanval(myrecord.cutPre)) * vnom2!) / 100
                                    End Select
                                    Select Case Val(cleanval(myrecord.cut1St))
                                    Case Is <= 0, Is >= 100
                                        GoTo errh
                                    End Select
                                    vnom1! = (vnom2! * Val(cleanval(myrecord.cut1St))) / 100
                                    Select Case vnom1!
                                    Case 0, Is >= vnom2!
                                        GoTo errh
                                    End Select
                                End If
                            'Case 1
                                'functional
                                'valori fittizi
                                'rnom1! = 100
                                'rnom2! = 0
                                'dcut% = 0
                                'funct% = 1
                            Case 2, 3
                                'mark
                                'valori fittizi
                                funct% = 0
                                thefunctional% = 0
                                rnom1! = 100
                                rnom2! = 0
                                Select Case Val(cleanval(myrecord.mark))
                                Case 1
                                    thekg% = Val(cutk$)
                                Case 2
                                    thekb% = Val(cutk$)
                                End Select
                                GoTo startcut
                            Case 4, 5
                                'serp o singolo
                                If cutType% = 4 Then
                                    mr$ = "CUT:" + Str(k%) + " (serp. cut)"
                                Else
                                    mr$ = "CUT:" + Str(k%) + " (unconditional cut)"
                                End If
                                Call updatereport(mr$, 0)
                                If Trim$(cleanval(myrecord.reslabel)) <> "" Then
                                    mr$ = "LABEL: " + cleanval(myrecord.reslabel)
                                    Call updatereport(mr$, 0)
                                End If
                                Call updatereport(mr$, 0)
                                dcut% = 0
                                If funct% = 0 Then
                                    'ohmico
                                    rnom2! = 0
                                    rnom1! = Val(cleanval(myrecord.ohmvalue))
                                    ornom1! = rnom1!
                                    Select Case Val(cleanval(myrecord.cutPre))
                                    Case Is <= 0, Is >= 100
                                    Case Else
                                        rnom1! = rnom1! - (Val(cleanval(myrecord.cutPre)) * rnom1!) / 100
                                    End Select
                                Else
                                    'funzionale
                                    vnom2! = 0
                                    vnom1! = Val(cleanval(myrecord.voltvalue))
                                    ovnom1! = vnom1!
                                    Select Case Val(cleanval(myrecord.cutPre))
                                    Case Is <= 0, Is >= 100
                                    Case Else
                                        vnom1! = vnom1! - (Val(cleanval(myrecord.cutPre)) * vnom1!) / 100
                                    End Select
                                End If
                            Case 6
                                'unconditional
                                'valori fittizi
                                mr$ = "CUT:" + Str(k%) + " (unconditional cut)"
                                Call updatereport(mr$, 0)
                                If Trim$(cleanval(myrecord.reslabel)) <> "" Then
                                    mr$ = "LABEL: " + cleanval(myrecord.reslabel)
                                    Call updatereport(mr$, 0)
                                End If
                                funct% = 0
                                thefunctional% = 0
                                rnom1! = 100
                                rnom2! = 0
                                dcut% = 0
                                uncond% = 1
                            End Select
                            If testing% = 1 And uncond% = 1 Then GoTo startcut
                            If funct% = 0 Then
                                If rnom1! = 0 And rnom2! = 0 Then GoTo errh
                            Else
                                If vnom1! = 0 And vnom2! = 0 Then GoTo errh
                            End If
                            gapx& = Val(cleanval(myrecord.startx))
                            gapy& = Val(cleanval(myrecord.starty))
                            deltax& = Val(cleanval(myrecord.stopx)) - Val(cleanval(myrecord.startx))
                            deltay& = Val(cleanval(myrecord.stopy)) - Val(cleanval(myrecord.starty))
                            If cutType% = 4 Then deltaz& = mm2step#(Val(cleanval(myrecord.serpstep)), stepxy!)
                            cutspeed& = mm2step#(Val(cleanval(myrecord.speed)), stepzw!)
                            If dcut% = 1 Then
                                Select Case UCase$(cleanval(myrecord.cutDir))
                                Case "0"
                                    deltax1& = deltax&
                                    deltay1& = 0
                                    deltax2& = 0
                                    deltay2& = deltay&
                                Case Else
                                    deltax1& = 0
                                    deltay1& = deltay&
                                    deltax2& = deltax&
                                    deltay2& = 0
                                End Select
                            Else
                                Select Case UCase$(cleanval(myrecord.cutDir))
                                Case "0"
                                    deltax1& = deltax&
                                    deltay1& = 0
                                    deltax2& = 0
                                    deltay2& = 0
                                Case Else
                                    deltax1& = 0
                                    deltay1& = deltay&
                                    deltax2& = 0
                                    deltay2& = 0
                                End Select
                                
                            End If
                            If cutType% = 4 Then
                                'serp
                                Select Case UCase$(cleanval(myrecord.cutDir))
                                Case "0"
                                    'serpx
                                    deltax1& = deltax&
                                    deltay1& = 0
                                    deltax2& = 0
                                    deltay2& = deltay&
                                    deltax3& = deltaz&
                                    deltay3& = 0
                                Case Else
                                    'serpy
                                    deltax1& = 0
                                    deltay1& = deltay&
                                    deltax2& = deltax&
                                    deltay2& = 0
                                    deltax3& = 0
                                    deltay3& = deltaz&
                                End Select
                            End If
                            'chiusura scanner
                            sch% = Val(cleanval(myrecord.scanh))
                            scl% = Val(cleanval(myrecord.scanl))
                            scg% = Val(cleanval(myrecord.scang))
                            guard% = 0
                            If scg% > 0 Then guard% = 1
                            Call closescan(sch%, scl%, scg%)
                            dtscan& = timeGetTime()
                            If sch% < 0 Then
                                mr$ = "Error on scanner high"
                                Call updatereport(mr$, 1)
                            End If
                            If scl% < 0 Then
                                mr$ = "Error on scanner low"
                                Call updatereport(mr$, 1)
                            End If
                            If scg% < 0 Then
                                mr$ = "Error on scanner guard"
                                Call updatereport(mr$, 1)
                            End If
                            'Call Delay(200)
                            'posizionamento su step e inizio taglio
                            ccutrefx& = cutrefx& + gapx&
                            ccutrefy& = cutrefy& + gapy&
                            ccutrefz& = cutrefz& + gapZ&
                            ccutrefw& = cutrefw& + gapW&
                            Hasdone% = 0
                            Call gotoposxyzw(Trim(Str(ccutrefx&)), Trim(Str(ccutrefy&)), Trim(Str(ccutrefz&)), Trim(Str(ccutrefw&)))
                            Call setoutput(0, d0.O_Rele_Work_Standby)
                            thefreq! = Val(cleanval(myrecord.freq)) * 1000
                            lastfreq$ = Trim$(Str(thefreq!))
                            Call setfreqda(1, thefreq!)
                            thecurr! = myrecord.current
                            lastcurr$ = Trim$(Str(thecurr!))
                            Call setda(1, thecurr!, ilasmax!)
                            'controllo puntali
                            Call readdevice(0, 0, 10)
                            If FrmEuro.Imglampon.Visible = True Then
                                If FrmEuro.Lblfreq.Caption <> lastfreq$ Then FrmEuro.Lblfreq.Caption = lastfreq$
                                If FrmEuro.Lblcurr.Caption <> lastcurr$ Then FrmEuro.Lblcurr.Caption = lastcurr$
                            Else
                                If FrmEuro.Lblfreq.Caption <> "0" Then FrmEuro.Lblfreq.Caption = "0"
                                If FrmEuro.Lblcurr.Caption <> "0" Then FrmEuro.Lblcurr.Caption = "0"
                            End If
                            DoEvents
                            If d0.I_Puntali_Alti = 0 Then
                                puntali% = 0
                                  Else
                                puntali% = 1
                            End If
                            If flagpuntali% = 0 Then puntali% = 0
                            Do
                                DoEvents
                                If Hasdone% = 2 Or workexit% > 0 Then Exit Do
                            Loop While puntali% = 1
                            If Hasdone% = 2 Or workexit% > 0 Then
                                Call exitwork
                                Exit Sub
                            End If
                            percentage! = Val(cleanval(myrecord.tolaccept))
                            tcmd$ = "DX1=" + Str(deltax1&)
                            Debug.Print tcmd$
                            Call galilcmd(tcmd$, res$, ermsg$)
                            tcmd$ = "DY1=" + Str(deltay1&)
                            Debug.Print tcmd$
                            Call galilcmd(tcmd$, res$, ermsg$)
                            tcmd$ = "DX2=" + Str(deltax2&)
                            Debug.Print tcmd$
                            Call galilcmd(tcmd$, res$, ermsg$)
                            tcmd$ = "DY2=" + Str(deltay2&)
                            Debug.Print tcmd$
                            Call galilcmd(tcmd$, res$, ermsg$)
                            If cutType% = 4 Then
                                'serp
                                tcmd$ = "DX3=" + Str(deltax3&)
                                Debug.Print tcmd$
                                Call galilcmd(tcmd$, res$, ermsg$)
                                tcmd$ = "DY3=" + Str(deltay3&)
                                Debug.Print tcmd$
                                Call galilcmd(tcmd$, res$, ermsg$)
                            End If
                            tcmd$ = "VSC=" + Str(cutspeed&)
                            Debug.Print tcmd$
                            Call galilcmd(tcmd$, res$, ermsg$)
                            theiset! = 0
                            donetest% = 0
                            Hasdone% = 0
                            Do
                                DoEvents
                                'If donetest% = 1 And moving% > 0 Then Stop
                                If Hasdone% = 2 Or workexit% > 0 Then
                                    Call exitwork
                                    Exit Sub
                                End If
                            
                            
                            If (timeGetTime() - dtscan& > 10) And donetest% = 0 Then
                            donetest% = 1
                            If funct% = 1 Then
                    
                                'taglio funzionale
                                thevoltval! = ovnom1!
                                'pretest volt
                                If vnom2! > 0 Then thevoltval! = ovnom2!
                                If uncond% = 0 Then
                                    perc1! = Val(cleanval(myrecord.tolcut))
                                    If slope% = 1 Then
                                        Call testvolt(percentage!, perc1!, guard%, thevoltval!, 1, 1, ok%)
                                    Else
                                        Call testvolt(percentage!, perc1!, guard%, thevoltval!, 2, 1, ok%)
                                    End If
                                    'se la resistenza e' gia' in tolleranza finale setta perc1! a 1 e non tara
                                    If testing% = 1 Then mustexit% = 1: Exit Do
                                    If perc1! = 1 Then: mustexit% = 1: Exit Do
                                Else
                                    ok% = 1
                                End If
                                If percentage! = 0 Then ok% = 1
                                If dcut% = 1 And ok% = 1 Then
                                    '1st cut su % diff valore di prestest e valore finale
                                    new1! = thevoltval! + ((vnom2! - thevoltval!) * Val(cleanval(myrecord.cut1St)) / 100)
                                    If new1! > 0 Then vnom1! = new1!
                                End If
                                If uncond% = 0 Then
                                    If ok% = 1 Then
                                        Call setcutv(dcut%, guard%, vnom1!, vnom2!, slope%)
                                    Else
                                        cutfail% = 1
                                        mustexit% = 1
                                        Exit Do
                                    End If
                                End If
                            Else
                                'pretest resistenza
                                theresval! = ornom1!
                                If rnom2! > 0 Then theresval! = ornom2!: dcut% = 1
                                If uncond% = 0 Then
                                    thefinalval! = 0
                                    perc1! = Val(cleanval(myrecord.tolcut))
                                    Call testres(percentage!, perc1!, guard%, theresval!, 1, 1, ok%)
                                    'se la resistenza e' gia' in tolleranza finale setta perc1! a 1 e non tara
                                    If testing% = 1 Then mustexit% = 1: Exit Do
                                    If perc1! = 1 Then: mustexit% = 1: Exit Do
                                Else
                                    ok% = 1
                                End If
                                If percentage! = 0 Then ok% = 1
                                If dcut% = 1 And ok% = 1 Then
                                    '1st cut su % diff valore di prestest e valore finale
                                    new1! = theresval! + ((rnom2! - theresval!) * Val(cleanval(myrecord.cut1St)) / 100)
                                    If new1! > 0 Then rnom1! = new1!
                                End If
                                If uncond% = 0 Then
                                    If ok% = 1 Then
                                        Call setcutr(dcut%, guard%, rnom1!, rnom2!)
                                    Else
                                        cutfail% = 1
                                        mustexit% = 1
                                        Exit Do
                                    End If
                                End If
                            End If
                            End If
                            Loop While moving% > 0 Or donetest% = 0
                            If mustexit% = 1 Then
                                mustexit% = 0
                                Hasdone% = 0
                                Do
                                    DoEvents
                                    If Hasdone% = 2 Or workexit% > 0 Then Exit Do
                                Loop While moving% > 0
                                GoTo startcut
                            End If
                            If Hasdone% = 2 Or workexit% > 0 Then
                                'interruzione operatore
                                Call exitwork
                                Exit Sub
                            End If
                            'comando di taglio galil
                            tcmd$ = "CDONE=0"
                            Debug.Print tcmd$
                            Call galilcmd(tcmd$, res$, ermsg$)
                            Call enablework
                            FrmEuro.Enabled = False
                            Select Case cutType%
                            Case 0
                                tcmd$ = "XQ#DCUT"
                            Case 1
                                tcmd$ = "XQ#LCUT"
                            Case 4
                                'serp
                                tcmd$ = "XQ#SERCUT"
                            Case 5, 6
                                tcmd$ = "XQ#SCUT"
                            End Select
                            Debug.Print tcmd$
                            Call galilcmd(tcmd$, res$, ermsg$)
                            'attesa primo stop
                            tout% = 0
                            numseconds% = 20000 / cutspeed&
                            Hasdone% = 0
                            If dcut% = 0 Then tout% = 5
                            If uncond% = 1 Then tout% = -1
                            Call waitcut(numseconds%, tout%)
                            If Hasdone% = 2 Or workexit% > 0 Then
                                Call exitwork
                                Exit Sub
                            End If
                            If tout% = 1 Then
                                MsgBox ("Cut Timeout")
                                Call exitwork
                                Exit Sub
                            End If
                            If dcut% = 1 Then
                                'taglio di tipo doppio
                                If funct% = 1 And slope% = 0 Then
                                    Call setsecondcut(0)
                                Else
                                    Call setsecondcut(1)
                                End If
                                'tout% = -5
                                tout% = 0
                                numseconds% = 20000 / cutspeed&
                                'Hasdone% = 0
                                Call waitcut(numseconds%, tout%)
                                If Hasdone% = 2 Or workexit% > 0 Then
                                    Call exitwork
                                    Exit Sub
                                End If
                                If tout% = 1 Then
                                    MsgBox ("Cut Timeout")
                                    Call exitwork
                                    Exit Sub
                                End If
                            End If
                            'test finale resistenza
                            percentage! = Val(cleanval(myrecord.tolcut))
                            If percentage! > 0 And uncond% = 0 Then
                                If funct% = 0 Then
                                    theresval! = ornom1!
                                    If rnom2! > 0 Then theresval! = ornom2!
                                        thefinalval! = 0
                                        Call testres(percentage!, 0, guard%, theresval!, 3, 1, ok%)
                                Else
                                    thevoltval! = ovnom1!
                                    If vnom2! > 0 Then thevoltval! = ovnom2!
                                    Call testvolt(percentage!, 0, guard%, thevoltval!, 3, 1, ok%)
                                End If
                                If ok% = 0 Then
                                    cutfail% = 1
                                    GoTo startcut
                                End If
                            End If
                        Loop
                        'se c'e' stato un errore marco nello step attuale
                        mk% = 0
                        If cutfail% = 1 And thekb% > 0 Then
                            myrecord = TrimMatrix(thekb%)
                            mk% = 1
                        End If
                        If cutfail% = 0 And thekg% > 0 Then
                                myrecord = TrimMatrix(thekg%)
                                mk% = 1
                        End If
                        If mk% = 1 And testing% = 0 Then
                            cutType% = Val(cleanval(myrecord.cutType))
                            gapx& = Val(cleanval(myrecord.startx))
                            gapy& = Val(cleanval(myrecord.starty))
                            deltax& = Val(cleanval(myrecord.stopx)) - Val(cleanval(myrecord.startx))
                            deltay& = Val(cleanval(myrecord.stopy)) - Val(cleanval(myrecord.starty))
                            cutspeed& = mm2step#(Val(cleanval(myrecord.speed)), stepzw!)
                            Select Case cutType%
                            Case "2"
                                    'marker circle
                                    rmc& = Sqr((deltax& * deltax&) + (deltay& * deltay&))
                            Case "3"
                                    'marker square
                                    deltax1& = deltax&
                                    deltay1& = 0
                                    deltax2& = 0
                                    deltay2& = deltay&
                            End Select
                            ccutrefx& = cutrefx& + gapx&
                            ccutrefy& = cutrefy& + gapy&
                            ccutrefz& = cutrefz& + gapZ&
                            ccutrefw& = cutrefw& + gapW&
                            Hasdone% = 0
                            Call gotoposxyzw(Trim(Str(ccutrefx&)), Trim(Str(ccutrefy&)), Trim(Str(ccutrefz&)), Trim(Str(ccutrefw&)))
                            Call setoutput(0, d0.O_Rele_Work_Standby)
                            thefreq! = Val(cleanval(myrecord.freq)) * 1000
                            lastfreq$ = Trim$(Str(thefreq!))
                            Call setfreqda(1, thefreq!)
                            thecurr! = myrecord.current
                            lastcurr$ = Trim$(Str(thecurr!))
                            tcmd$ = "VSC=" + Str(cutspeed&)
                            Debug.Print tcmd$
                            Call galilcmd(tcmd$, res$, ermsg$)
                            If cutType% = 2 Then
                                tcmd$ = "MRAGGIO=" + Trim$(Str(rmc&))
                                Debug.Print tcmd$
                                Call galilcmd(tcmd$, res$, ermsg$)
                            End If
                            If cutType% = 3 Then
                                tcmd$ = "DX1=" + Str(deltax1&)
                                Debug.Print tcmd$
                                Call galilcmd(tcmd$, res$, ermsg$)
                                tcmd$ = "DY1=" + Str(deltay1&)
                                Debug.Print tcmd$
                                Call galilcmd(tcmd$, res$, ermsg$)
                                tcmd$ = "DX2=" + Str(deltax2&)
                                Debug.Print tcmd$
                                Call galilcmd(tcmd$, res$, ermsg$)
                                tcmd$ = "DY2=" + Str(deltay2&)
                                Debug.Print tcmd$
                                Call galilcmd(tcmd$, res$, ermsg$)
                            End If
                            Do
                                DoEvents
                                If Hasdone% = 2 Or workexit% > 0 Then Exit Do
                            Loop While moving% > 0
                            If Hasdone% = 2 Or workexit% > 0 Then
                                Call exitwork
                                Exit Sub
                            End If
                            'comando di taglio galil
                            tcmd$ = "CDONE=0"
                            Debug.Print tcmd$
                            Call galilcmd(tcmd$, res$, ermsg$)
                            Call enablework
                            FrmEuro.Enabled = False
                            Select Case cutType%
                            Case 2
                                tcmd$ = "XQ#MARKC"
                            Case 3
                                tcmd$ = "XQ#MARKQ"
                            End Select
                            Debug.Print tcmd$
                            Call galilcmd(tcmd$, res$, ermsg$)
                            'attesa primo stop
                            tout% = -1
                            numseconds% = 20000 / cutspeed&
                            Hasdone% = 0
                            Call waitcut(numseconds%, tout%)
                            If Hasdone% = 2 Or workexit% > 0 Then
                                Call exitwork
                                Exit Sub
                            End If
                            If tout% = 1 Then
                                MsgBox ("Cut Timeout")
                                Call exitwork
                                Exit Sub
                            End If
                            
                        End If
                Next j%
            Next i%
            'fine ciclo
            Hasdone% = 0
            Call tableout
            Do
                DoEvents
            Loop While Hasdone% = 0
            Call exitwork
            Exit Sub
errh:
    MsgBox (mss$(30))
    If flagdopsi% = 0 Then FrmEuro.Enabled = True
End Sub




Sub jogxy()
If flagpuntali% = 2 Then Exit Sub
Call updateposxy
If moving% > 0 Then Exit Sub
Static enabler%
Static enabler1%
Static enabler2%
Static ocmd$
Static spxx&
Static spyy&
Static clk%
Static crk%
Static cuk%
Static cdk%
ths% = 15
dt& = timeGetTime()
a& = GetCursorPos&(pt)
thexx& = Screen.Width / (2 * Screen.TwipsPerPixelX)
theyy& = Screen.Height / (2 * Screen.TwipsPerPixelY)
dx& = pt.x - thexx&
dy& = theyy& - pt.y
'accelerazioni assi
accx$ = accmax$
accy$ = accmax$
spx& = Int((mult& * dx&) / (dt& - odt&))
spy& = Int((mult& * dy&) / (dt& - odt&))
Select Case spx&
Case Is < -speedmaxxy&
    spx& = -speedmaxxy&
Case Is > speedmaxxy&
    spx& = speedmaxxy&
End Select
Select Case spy&
Case Is < -speedmaxxy&
    spy& = -speedmaxxy&
Case Is > speedmaxxy&
    spy& = speedmaxxy&
End Select
ck% = GetAsyncKeyState%(speedkey%) 'ctrl key
lk% = GetAsyncKeyState%(&H25) 'left key
uk% = GetAsyncKeyState%(&H26) 'up key
rk% = GetAsyncKeyState%(&H27) 'right key
dk% = GetAsyncKeyState%(&H28) 'down key
esk% = GetAsyncKeyState%(27) 'escape key
enk% = GetAsyncKeyState%(13) 'enter key
lmk% = GetAsyncKeyState%(&H1) 'left mouse button
rmk% = GetAsyncKeyState%(&H2) 'right mouse button
shk% = GetAsyncKeyState%(&H10) 'shift key

Select Case shk%
Case 0
    enabler2% = enabler2% Or 1
Case Else
    If enabler2% = 1 Then
        'ho spinto shift
        enabler2% = 0
        If dispstep% = 0 Then
            dispstep% = 1
        Else
            dispstep% = 0
        End If
    End If
End Select

Select Case esk%
Case 0
    enabler% = enabler% Or 1
Case Else
    If enabler% = 15 Then
        'ho spinto esc
        escjog% = 1
        enabler% = 0
    End If
End Select

Select Case enk%
Case 0
    enabler% = enabler% Or 2
Case Else
    If enabler% = 15 Then
        getv% = 1
        escjog% = 1
        enabler% = 0
        'ho spinto enter
    End If
End Select
Select Case lmk%
Case 0
    enabler% = enabler% Or 4
Case Else
    If enabler% = 15 Then
        getv% = 1
        escjog% = 1
        enabler% = 0
        'ho spinto il tasto sinistro
    End If
End Select
Select Case rmk%
Case 0
    enabler% = enabler% Or 8
Case Else
    If enabler% = 15 Then
        getv% = 1
        escjog% = 1
        enabler% = 0
        'ho spinto il tasto destro
    End If
End Select
Select Case lk%
Case 0
    'non sto spigendo
    clk% = 0
    enabler1% = enabler1% Or 1
    If spxx& < 0 Then
        spxx& = 0
        kk% = 1
    End If
Case Else
    If enabler1% = 15 Then
        clk% = clk% + 1
        If lk% = 1 Then clk% = 1
        If clk% > ths% Then
            clk% = ths%
            spxx& = -speedmaxxy&
        Else
            spxx& = -(speedmaxxy& / ths%) * clk%
        End If
        'sto spingendo
        kk% = 1
        If ck% <> 0 Then
            acx% = 1
            spxx& = 2 * spxx&
        End If
    Else
        clk% = 0
    End If
End Select
Select Case rk%
Case 0
    'non sto spigendo
    crk% = 0
    enabler1% = enabler1% Or 2
    If spxx& > 0 Then
        spxx& = 0
        kk% = 1
    End If
Case Else
    If enabler1% = 15 Then
        'sto spingendo
        crk% = crk% + 1
        If rk% = 1 Then crk% = 1
        If crk% > ths% Then
            crk% = ths%
            spxx& = speedmaxxy&
        Else
            spxx& = (speedmaxxy& / ths%) * crk%
        End If
        kk% = 1
        If ck% <> 0 Then
            spxx& = 2 * spxx&
            acx% = 1
        End If
    Else
        crk% = 0
    End If
End Select
Select Case uk%
Case 0
    'non sto spigendo
    cuk% = 0
    enabler1% = enabler1% Or 4
    If spyy& > 0 Then
        spyy& = 0
        kk% = 1
    End If
Case Else
    If enabler1% = 15 Then
        'sto spingendo
        cuk% = cuk% + 1
        If uk% = 1 Then cuk% = 1
        If cuk% > ths% Then
            cuk% = ths%
            spyy& = speedmaxxy&
        Else
            spyy& = (speedmaxxy& / ths%) * cuk%
        End If
        kk% = 1
        If ck% <> 0 Then
            spyy& = 2 * spyy&
            acy% = 1
        End If
    Else
        cuk% = 0
    End If
End Select

Select Case dk%
Case 0
    'non sto spigendo
    cdk% = 0
    enabler1% = enabler1% Or 8
    If spyy& < 0 Then
        spyy& = 0
        kk% = 1
    End If
Case Else
    'sto spingendo
    If enabler1% = 15 Then
        cdk% = cdk% + 1
        If dk% = 1 Then cdk% = 1
        If cdk% > ths% Then
            cdk% = ths%
            spyy& = -speedmaxxy&
        Else
            spyy& = -(speedmaxxy& / ths%) * cdk%
        End If
        kk% = 1
        If ck% <> 0 Then
            spyy& = 2 * spyy&
            acy% = 1
        End If
    Else
        cdk% = 0
    End If
End Select
If kk% = 1 Then
    accx$ = accmin$
    If acx% = 1 Then accx$ = accmax$
    accy$ = accmin$
    If acy% = 1 Then accy$ = accmax$
    spx& = spxx&
    spy& = spyy&
End If
If odt& <> 0 And (spx& <> 0 Or spy& <> 0) Then
    tcmd$ = "JG " + Str$(spx&) + "," + Str$(spy&) + ";" + "BG XY"
Else
    tcmd$ = "ST XY;SP" + Str(speedmaxxy&) + "," + Str(speedmaxxy&)
End If
If escjog% = 1 Then tcmd$ = "ST XY;SP" + Str(speedmaxxy&) + "," + Str(speedmaxxy&) + ";AC " + accx$ + "," + accy$
tcmd$ = tcmd$ + ";AC" + accx$ + "," + accy$
If ocmd$ <> tcmd$ Then
    'Debug.Print tcmd$
    Call galilcmd(tcmd$, res$, ermsg$)
End If
ocmd$ = tcmd$
a& = SetCursorPos(thexx&, theyy&)
odt& = dt&
If escjog% = 1 Then
        If getv% = 1 Then
            Call galilcmd("TP XY", res$, ermsg$)
            cm% = InStr(res$, ",")
            If cm% > 0 Then
                thex& = Val(Trim$(Left$(res$, cm% - 1)))
                they& = Val(Trim$(Mid$(res$, cm% + 1)))
            End If
        End If
        Do
            esk% = GetAsyncKeyState%(27) 'escape key
            enk% = GetAsyncKeyState%(13) 'enter key
            lmk% = GetAsyncKeyState%(&H1) 'left mouse button
            rmk% = GetAsyncKeyState%(&H2) 'right mouse button
            tk% = esk% + enk% + lmk% + rmk%
            DoEvents
        Loop While tk% <> 0
        Call offjog
        enabler% = 0
        enabler1% = 0
        ocmd$ = ""
        Select Case statjog%
        Case -1
            'Jog
            statjog% = 0
        Case 0
            'ref. macchina 1
            If getv% = 1 Then
                RefX& = thex&
                RefY& = they&
                Call saveini
            End If
        Case 5
            'ref. macchina 2
            If getv% = 1 Then
                RefX1& = thex&
                RefY1& = they&
                Call saveini
            End If
            statjog% = 0
        Case 1, 4
            'ref. taglio 1
            If getv% = 1 Then
                TLasReferenceX$ = Trim(Str(thex&))
                Frmedit.txtRefX.Tag = TLasReferenceX$
                Frmedit.txtRefX = formatter$(step2mm#(thex&, stepxy!), 3, 2)
                TLasReferenceY$ = Trim(Str(they&))
                Frmedit.txtRefY.Tag = TLasReferenceY$
                Frmedit.txtRefY = formatter$(step2mm#(they&, stepxy!), 3, 2)
            End If
            If statjog% = 1 Then
                statjog% = 0
                Frmedit.ZOrder 0
                Frmedit.Show 1
            Else
                statjog% = 0
            End If
        Case 5, 6
            'ref. taglio 2
            If getv% = 1 Then
                TLasReferenceX1$ = Trim(Str(thex&))
                Frmedit.TxtRefX1.Tag = TLasReferenceX1$
                Frmedit.TxtRefX1 = formatter$(step2mm#(thex&, stepxy!), 3, 2)
                TLasReferenceY1$ = Trim(Str(they&))
                Frmedit.TxtRefY1.Tag = TLasReferenceY1$
                Frmedit.TxtRefY1 = formatter$(step2mm#(they&, stepxy!), 3, 2)
            End If
            If statjog% = 6 Then
                statjog% = 0
                Frmedit.ZOrder 0
                Frmedit.Show 1
            Else
                statjog% = 0
            End If
        Case 2
            'start cut
            If getv% = 1 Then
                gapx& = thex& - Val(Frmedit.txtRefX.Tag)
                gapy& = they& - Val(Frmedit.txtRefY.Tag)
                Frmedit.TxtCutStartX.Tag = Trim(Str(gapx&))
                Frmedit.txtCutStartY.Tag = Trim(Str(gapy&))
                Frmedit.TxtCutStartX = formatter$(step2mm#(gapx&, stepxy!), 3, 2)
                Frmedit.txtCutStartY = formatter$(step2mm#(gapy&, stepxy!), 3, 2)
                Frmedit.txtCutStopX.Tag = Trim(Str(gapx&))
                Frmedit.txtCutStopY.Tag = Trim(Str(gapy&))
                Frmedit.txtCutStopX = formatter$(step2mm#(gapx&, stepxy!), 3, 2)
                Frmedit.txtCutStopY = formatter$(step2mm#(gapy&, stepxy!), 3, 2)
                MsgBox ("Press enter to get the cut stop positon")
                If loopingsafety% = 1 Then Exit Sub
                Call checksafety
                statjog% = 3
                Frmedit.Visible = False
                jogging% = 1
                Call setjogpos
            Else
                statjog% = 0
                Frmedit.ZOrder 0
                Frmedit.Show 1
            End If
        Case 3
            'stop cut
            If getv% = 1 Then
                gapx& = thex& - Val(Frmedit.txtRefX.Tag)
                gapy& = they& - Val(Frmedit.txtRefY.Tag)
                Frmedit.txtCutStopX.Tag = Trim(Str(gapx&))
                Frmedit.txtCutStopY.Tag = Trim(Str(gapy&))
                Frmedit.txtCutStopX = formatter$(step2mm#(gapx&, stepxy!), 3, 2)
                Frmedit.txtCutStopY = formatter$(step2mm#(gapy&, stepxy!), 3, 2)
                diffx& = Abs(Val(Frmedit.txtCutStopX.Tag) - Val(Frmedit.TxtCutStartX.Tag))
                diffy& = Abs(Val(Frmedit.txtCutStopY.Tag) - Val(Frmedit.txtCutStartY.Tag))
                'If diffx& >= diffy& Then
                    'Frmedit.lstCutDir.ListIndex = 0
                'Else
                    'Frmedit.lstCutDir.ListIndex = 1
                'End If
            End If
            If Frmedit.txtCutStopX.Tag = Frmedit.TxtCutStartX.Tag And Frmedit.txtCutStopY.Tag = Frmedit.txtCutStartY.Tag Then
                MsgBox ("Warning: Start and Stop are the same point")
            End If
            statjog% = 0
            Frmedit.ZOrder 0
            Frmedit.Show 1
        End Select
 End If
End Sub
Sub jogzw()
Call updateposzw
If moving% > 0 Then Exit Sub
Static enabler%
Static enabler1%
Static enabler2%
Static enabler3%
Static ocmd$
Static spxx&
Static spyy&
Static clk%
Static crk%
Static cuk%
Static cdk%
Static dtpun& 'memorizza l'istante in cui azzero il jog
ths% = 15
dt& = timeGetTime()
a& = GetCursorPos&(pt)
thexx& = Screen.Width / (2 * Screen.TwipsPerPixelX)
theyy& = Screen.Height / (2 * Screen.TwipsPerPixelY)
dx& = pt.x - thexx&
dy& = theyy& - pt.y
'accelerazioni assi
accx$ = accmax$
accy$ = accmax$
spx& = Int((mult& * dx&) / (dt& - odt&))
spy& = Int((mult& * dy&) / (dt& - odt&))
Select Case spx&
Case Is < -speedmaxzw&
    spx& = -speedmaxzw&
Case Is > speedmaxzw&
    spx& = speedmaxzw&
End Select
Select Case spy&
Case Is < -speedmaxzw&
    spy& = -speedmaxzw&
Case Is > speedmaxzw&
    spy& = speedmaxzw&
End Select
ck% = GetAsyncKeyState%(speedkey%) 'ctrl key
lk% = GetAsyncKeyState%(&H25) 'left key
uk% = GetAsyncKeyState%(&H26) 'up key
rk% = GetAsyncKeyState%(&H27) 'right key
dk% = GetAsyncKeyState%(&H28) 'down key
esk% = GetAsyncKeyState%(27) 'escape key
enk% = GetAsyncKeyState%(13) 'enter key
lmk% = GetAsyncKeyState%(&H1) 'left mouse button
rmk% = GetAsyncKeyState%(&H2) 'right mouse button
shk% = GetAsyncKeyState%(&H10) 'shift key

Select Case shk%
Case 0
    enabler2% = enabler2% Or 1
Case Else
    If enabler2% = 1 Then
        'ho spinto shift
        enabler2% = 0
        If dispstep% = 0 Then
            dispstep% = 1
        Else
            dispstep% = 0
        End If
    End If
End Select

Select Case esk%
Case 0
    enabler% = enabler% Or 1
Case Else
    If enabler% = 7 Then
        'ho spinto esc
        escjog% = 1
        enabler% = 0
    End If
End Select

Select Case enk%
Case 0
    enabler% = enabler% Or 2
Case Else
    If enabler% = 7 Then
        getv% = 1
        escjog% = 1
        enabler% = 0
        'ho spinto enter
    End If
End Select
Select Case lmk%
Case 0
    enabler% = enabler% Or 4
Case Else
    If enabler% = 7 Then
        getv% = 1
        escjog% = 1
        enabler% = 0
        'ho spinto il tasto sinistro
    End If
End Select
'Select Case rmk%
'Case 0
    'enabler% = enabler% Or 8
'Case Else
    'If enabler% = 15 Then
        'getv% = 1
        'escjog% = 1
        'enabler% = 0
        ''ho spinto il tasto destro
    'End If
'End Select
Select Case lk%
Case 0
    'non sto spigendo
    clk% = 0
    enabler1% = enabler1% Or 1
    If spxx& > 0 Then
        spxx& = 0
        kk% = 1
    End If
Case Else
    If enabler1% = 15 Then
        clk% = clk% + 1
        If lk% = 1 Then clk% = 1
        If clk% > ths% Then
            clk% = ths%
            spxx& = speedmaxzw&
        Else
            spxx& = (speedmaxzw& / ths%) * clk%
        End If
        'sto spingendo
        kk% = 1
        If ck% <> 0 Then
            acx% = 1
            spxx& = 2 * spxx&
        End If
    Else
        clk% = 0
    End If
End Select
Select Case rk%
Case 0
    'non sto spigendo
    crk% = 0
    enabler1% = enabler1% Or 2
    If spxx& < 0 Then
        spxx& = 0
        kk% = 1
    End If
Case Else
    If enabler1% = 15 Then
        'sto spingendo
        crk% = crk% + 1
        If rk% = 1 Then crk% = 1
        If crk% > ths% Then
            crk% = ths%
            spxx& = -speedmaxzw&
        Else
            spxx& = (-speedmaxzw& / ths%) * crk%
        End If
        kk% = 1
        If ck% <> 0 Then
            spxx& = 2 * spxx&
            acx% = 1
        End If
    Else
        crk% = 0
    End If
End Select
Select Case uk%
Case 0
    'non sto spigendo
    cuk% = 0
    enabler1% = enabler1% Or 4
    If spyy& < 0 Then
        spyy& = 0
        kk% = 1
    End If
Case Else
    If enabler1% = 15 Then
        'sto spingendo
        cuk% = cuk% + 1
        If uk% = 1 Then cuk% = 1
        If cuk% > ths% Then
            cuk% = ths%
            spyy& = -speedmaxzw&
        Else
            spyy& = (-speedmaxzw& / ths%) * cuk%
        End If
        kk% = 1
        If ck% <> 0 Then
            spyy& = 2 * spyy&
            acy% = 1
        End If
    Else
        cuk% = 0
    End If
End Select

Select Case dk%
Case 0
    'non sto spigendo
    cdk% = 0
    enabler1% = enabler1% Or 8
    If spyy& > 0 Then
        spyy& = 0
        kk% = 1
    End If
Case Else
    'sto spingendo
    If enabler1% = 15 Then
        cdk% = cdk% + 1
        If dk% = 1 Then cdk% = 1
        If cdk% > ths% Then
            cdk% = ths%
            spyy& = speedmaxzw&
        Else
            spyy& = (speedmaxzw& / ths%) * cdk%
        End If
        kk% = 1
        If ck% <> 0 Then
            spyy& = 2 * spyy&
            acy% = 1
        End If
    Else
        cdk% = 0
    End If
End Select
If kk% = 1 Then
    accx$ = accmin$
    If acx% = 1 Then accx$ = accmax$
    accy$ = accmin$
    If acy% = 1 Then accy$ = accmax$
    spx& = spxx&
    spy& = spyy&
End If

Select Case rmk%
Case 0
    enabler3% = enabler3% Or 1
Case Else
    If enabler3% = 1 Then
        If flagpuntali% = 1 Then
            Call readdevice(0, 0, 10)
            If d0.I_Puntali_Alti = 1 Then
                spx& = 0
                spy& = 0
                Call puntalidown(checkok%)
            Else
                Call puntaliup(checkok%)
            End If
        End If
    End If
End Select

If odt& <> 0 And (spx& <> 0 Or spy& <> 0) Then
    If flagpuntali% = 1 Then
        dtpun& = -1
        Call readdevice(0, 0, 10)
        If d0.I_Puntali_Alti = 0 Then
            Call puntaliup(checkok%)
            If checkok% = 0 Then spx& = 0: spy& = 0
        End If
    End If
    tcmd$ = "JG ,," + Str$(spx&) + "," + Str$(spy&) + ";" + "BG ZW"
Else
    tcmd$ = "ST ZW;SP ,," + Str(speedmaxzw&) + "," + Str(speedmaxzw&)
    If flagpuntali% = 1 Then
        If d0.I_Puntali_Alti = 1 Then
            dtp& = timeGetTime&()
            If dtpun& = -1 Then
                dtpd& = 0
                dtpun& = dtp&
            Else
                dtpd& = dtp& - dtpun&
            End If
            If dtpd& > 500 Then
                Call galilcmd(tcmd$, res$, ermsg$)
                Call puntalidown(checkok%)
            End If
        Else
            dtpun& = -1
        End If
    End If
End If
If escjog% = 1 Then tcmd$ = "ST ZW;SP ,," + Str(speedmaxzw&) + "," + Str(speedmaxzw&) + ";AC ,," + accx$ + "," + accy$
tcmd$ = tcmd$ + ";AC ,," + accx$ + "," + accy$
If ocmd$ <> tcmd$ Then
    'Debug.Print tcmd$
    Call galilcmd(tcmd$, res$, ermsg$)
End If
ocmd$ = tcmd$
a& = SetCursorPos(thexx&, theyy&)
odt& = dt&
If escjog% = 1 Then
        If getv% = 1 Then
            Call galilcmd("TP ZW", res$, ermsg$)
            cm% = InStr(res$, ",")
            If cm% > 0 Then
                thex& = Val(Trim$(Left$(res$, cm% - 1)))
                they& = Val(Trim$(Mid$(res$, cm% + 1)))
            End If
        End If
        Do
            esk% = GetAsyncKeyState%(27) 'escape key
            enk% = GetAsyncKeyState%(13) 'enter key
            lmk% = GetAsyncKeyState%(&H1) 'left mouse button
            rmk% = GetAsyncKeyState%(&H2) 'right mouse button
            tk% = esk% + enk% + lmk% + rmk%
            DoEvents
        Loop While tk% <> 0
        Call offjog
        enabler% = 0
        enabler1% = 0
        ocmd$ = ""
        Select Case statjog%
        Case -1
            'Jog
            statjog% = 0
            Call switchcamera(0, 1)
        Case 0
            'ref. macchina
            If getv% = 1 Then
                RefZ& = thex&
                RefW& = they&
                Call saveini
            End If
            Call switchcamera(0, 1)
        Case 1
            'reference tavola per taglio
            If getv% = 1 Then
                TTabReferenceZ$ = Trim(Str(thex&))
                Frmedit.txtRefZ.Tag = TTabReferenceZ$
                Frmedit.txtRefZ = formatter$(step2mm#(thex&, stepzw!), 3, 2)
                TTabReferenceW$ = Trim(Str(they&))
                Frmedit.txtRefW.Tag = TTabReferenceW$
                Frmedit.txtRefW = formatter$(step2mm#(they&, stepzw!), 3, 2)
            End If
            Call switchcamera(0, 1)
            statjog% = 0
            Frmedit.ZOrder 0
            Frmedit.Show 1
        End Select
 End If
End Sub
Sub enablework()
    Do
        esk% = GetAsyncKeyState%(27) 'escape key
    Loop While esk% <> 0
    FrmEuro.Timerwork.Enabled = True
End Sub
Sub tableout()
    If loopingsafety% = 1 Then Exit Sub
    Call checksafety
    tin% = 0
    If doubletable% = 0 Then FrmEuro.Toolbar1.Buttons.Item(9).value = tbrUnpressed
    Call gotoposzw(tableoutx$, tableouty$)
    dontprobe% = 1
    vuotoff% = 1
    If doubletable% = 1 Then
        Call tableABout
    End If
End Sub
Sub tableABin()
lasttable% = 0
Call resetoutput(0, d0.O_Buono_A)
Call resetoutput(0, d0.O_Buono_B)
Call resetoutput(0, d0.O_Cattivo_A)
Call resetoutput(0, d0.O_Cattivo_B)
Call setoutput(0, d0.O_Selezione_Tavola_A)
Call setoutput(0, d0.O_Selezione_Tavola_B)
End Sub
Sub tableAin()
cutrefx& = Val(TLasReferenceX$)
cutrefy& = Val(TLasReferenceY$)
cutrefz& = Val(TTabReferenceZ$)
cutrefw& = Val(TTabReferenceW$)
Call gotoposxyzw(Str(cutrefx&), Str(cutrefy&), Str(gotoz&), Str(gotow&))
Do
    DoEvents
    esk% = GetAsyncKeyState%(27) 'escape key
    If esk% <> 0 Then ex% = 1: Exit Do
    Call readdevice(0, 0, 10)
    If d0.I_NScarto_Pezzo = 1 Then Exit Do
Loop
If ex% = 1 Then
    'SendKeys "{ESC}", 1
    pressesc% = 1
    Exit Sub
End If
lasttable% = 0
Call setoutput(0, d0.O_Selezione_Tavola_A)
Call resetoutput(0, d0.O_Selezione_Tavola_B)
Call resetoutput(0, d0.O_Buono_A)
Call resetoutput(0, d0.O_Cattivo_A)
End Sub
Sub tableAout()
Call resetoutput(0, d0.O_Selezione_Tavola_A)
End Sub
Sub tableBout()
Call resetoutput(0, d0.O_Selezione_Tavola_B)
End Sub

Sub tableBin()
cutrefx1& = Val(TLasReferenceX1$)
cutrefy1& = Val(TLasReferenceY1$)
cutrefz& = Val(TTabReferenceZ$)
cutrefw& = Val(TTabReferenceW$)
Call gotoposxyzw(Str(cutrefx1&), Str(cutref1y&), Str(gotoz&), Str(gotow&))
Do
    DoEvents
    esk% = GetAsyncKeyState%(27) 'escape key
    If esk% <> 0 Then ex% = 1: Exit Do
    Call readdevice(0, 0, 10)
    If d0.I_NScarto_Pezzo = 1 Then Exit Do
Loop
If ex% = 1 Then
    'SendKeys "{ESC}", 1
    pressesc% = 1
    Exit Sub
End If
lasttable% = 1
Call resetoutput(0, d0.O_Selezione_Tavola_A)
Call setoutput(0, d0.O_Selezione_Tavola_B)
Call resetoutput(0, d0.O_Buono_B)
Call resetoutput(0, d0.O_Cattivo_B)
End Sub

Sub tableABout()
Call resetoutput(0, d0.O_Selezione_Tavola_A)
Call resetoutput(0, d0.O_Selezione_Tavola_B)
End Sub

Sub tablein(go%)
    If loopingsafety% = 1 Then Exit Sub
    'Call checksafety
    tin% = 1
    If doubletable% = 0 Then FrmEuro.Toolbar1.Buttons.Item(9).value = tbrPressed
    Call resetoutput(0, d0.O_Chiamata_Operatore)
    Call vuoto(1)
    Call checksafety
    If TTabReferenceZ$ <> "" Then
        trx$ = TTabReferenceZ$
        try$ = TTabReferenceW$
    Else
        trx$ = Trim$(Str(RefZ&))
        try$ = Trim$(Str(RefW&))
    End If
    Call vuoto(1)
    If go% = 1 Then Call gotoposzw(trx$, try$)
    If doubletable% = 1 Then
        Call tableABin
    End If
End Sub
Sub puntaliupdown()
If FrmEuro.Imgmacon.Visible = False Then Exit Sub
If loopingsaffety% = 1 Then Exit Sub
Call checksafety
If flagpuntali% = 1 Then
        Call readdevice(0, 0, 10)
        If d0.I_Puntali_Alti = 1 Then
            Call puntalidown(checkok%)
        Else
            Call puntaliup(checkok%)
        End If
End If
End Sub
Sub setjogpos()

Select Case jogging%
Case Is = 1
    Select Case statjog%
    Case -1
        'jog laser senza acquisizione
        trx$ = ""
        try$ = ""
        trz$ = ""
        trw$ = ""
    Case 1, 4
        'acquisizione reference laser 1 per taglio
        If TTabReferenceZ$ <> "" Then
            trz$ = TTabReferenceZ$
            trw$ = TTabReferenceW$
        Else
            trz$ = Trim$(Str(RefZ&))
            trw$ = Trim$(Str(RefW&))
        End If
        If TLasReferenceX$ <> "" Then
            trx$ = TLasReferenceX$
            try$ = TLasReferenceY$
        Else
            trx$ = Trim$(Str(RefX&))
            try$ = Trim$(Str(RefY&))
        End If
    Case 6
        'acquisizione reference laser 2 per taglio
        If TTabReferenceZ$ <> "" Then
            trz$ = TTabReferenceZ$
            trw$ = TTabReferenceW$
        Else
            trz$ = Trim$(Str(RefZ&))
            trw$ = Trim$(Str(RefW&))
        End If
        If TLasReferenceX1$ <> "" Then
            trx$ = TLasReferenceX1$
            try$ = TLasReferenceY1$
        Else
            trx$ = Trim$(Str(RefX1&))
            try$ = Trim$(Str(RefY1&))
        End If
    Case 2
        'acquisizione start taglio
        val1x& = RefX&
        If TLasReferenceX$ <> "" Then val1x& = Val(TLasReferenceX$)
        val1y& = RefY&
        If TLasReferenceY$ <> "" Then val1y& = Val(TLasReferenceY$)
        If Frmedit.txtRefX.Tag <> "" Then val1x& = Val(Frmedit.txtRefX.Tag)
        If Frmedit.txtRefY.Tag <> "" Then val1y& = Val(Frmedit.txtRefY.Tag)
        val2x& = 0
        val2y& = 0
        If Frmedit.TxtCutStartX.Tag <> "" Then val2x& = Val(Frmedit.TxtCutStartX.Tag)
        If Frmedit.txtCutStartY.Tag <> "" Then val2y& = Val(Frmedit.txtCutStartY.Tag)
        trx$ = Trim$(Str$(val1x& + val2x&))
        try$ = Trim$(Str$(val1y& + val2y&))
    Case 3
        'acquisizione stop taglio
        val1x& = RefX&
        If TLasReferenceX$ <> "" Then val1x& = Val(TLasReferenceX$)
        val1y& = RefY&
        If TLasReferenceY$ <> "" Then val1y& = Val(TLasReferenceY$)
        val2x& = 0
        val2y& = 0
        If Frmedit.TxtCutStartX.Tag <> "" Then val2x& = Val(Frmedit.TxtCutStartX.Tag)
        If Frmedit.txtCutStartY.Tag <> "" Then val2y& = Val(Frmedit.txtCutStartY.Tag)
        If Frmedit.txtCutStopX.Tag <> "" Then val2x& = Val(Frmedit.txtCutStopX.Tag)
        If Frmedit.txtCutStopY.Tag <> "" Then val2y& = Val(Frmedit.txtCutStopY.Tag)
        trx$ = Trim$(Str$(val1x& + val2x&))
        try$ = Trim$(Str$(val1y& + val2y&))
    End Select
Case 2
    Select Case statjog%
    Case -1
        'jog tavola senza acquisizione
        trx$ = ""
        try$ = ""
        trz$ = ""
        trw$ = ""
    Case 1
        'acquisizione reference tavola per taglio
        trx$ = ""
        try$ = ""
        If TTabReferenceZ$ <> "" Then
            trz$ = TTabReferenceZ$
            trw$ = TTabReferenceW$
        Else
            trz$ = Trim$(Str(RefZ&))
            trw$ = Trim$(Str(RefW&))
        End If
    End Select
Case 3
    Select Case statjog%
    Case -1
        'jog tavola senza acquisizione
        val1x& = RefX&
        If TLasReferenceX$ <> "" Then val1x& = Val(TLasReferenceX$)
        val1y& = RefY&
        If TLasReferenceY$ <> "" Then val1y& = Val(TLasReferenceY$)
        If Frmedit.txtRefX.Tag <> "" Then val1x& = Val(Frmedit.txtRefX.Tag)
        If Frmedit.txtRefY.Tag <> "" Then val1y& = Val(Frmedit.txtRefY.Tag)
        trx$ = Trim$(Str$(val1x&))
        try$ = Trim$(Str$(val1y&))
        trz$ = ""
        trw$ = ""
        Call plcpuntaliup(1)
    End Select
End Select
Call onjog(trx$, try$, trz$, trw$)
End Sub
Sub tabclick()
With Frmedit
If .cmdsave.Enabled = False Then Exit Sub
Select Case .SSTabEdit.Tab
Case 0
        'reference
        .FramLasRef.Enabled = True
        .FramTabRef.Enabled = True
        .FramTrimNum.Enabled = False
        .FramCutType.Enabled = False
        .FramCutStart.Enabled = False
        .FramCutStop.Enabled = False
        .FramCutPar.Enabled = False
        .FramlasPar.Enabled = False
        .Frammark.Enabled = False
        .FramTrimBut.Enabled = False
        .FramTabStep.Enabled = False
        .FramExe.Enabled = False
        '.cmdGetTabRef.SetFocus
        .cmdGetLasRef.SetFocus
Case 1
        .FramLasRef.Enabled = False
        .FramTabRef.Enabled = False
        .FramTrimNum.Enabled = True
        .FramCutType.Enabled = True
        .FramCutStart.Enabled = True
        .FramCutStop.Enabled = True
        .FramCutPar.Enabled = True
        .FramlasPar.Enabled = True
        .Frammark.Enabled = True
        .FramTrimBut.Enabled = True
        .FramTabStep.Enabled = False
        .FramExe.Enabled = False
        'Call selectcase
        .cmdGetStart.SetFocus
Case 2
        .FramLasRef.Enabled = False
        .FramTabRef.Enabled = False
        .FramTrimNum.Enabled = False
        .FramCutType.Enabled = False
        .FramCutStart.Enabled = False
        .FramCutStop.Enabled = False
        .FramCutPar.Enabled = False
        .FramlasPar.Enabled = False
        .Frammark.Enabled = False
        .FramTrimBut.Enabled = False
        .FramTabStep.Enabled = True
        .FramExe.Enabled = False
        .txtNstepX.SetFocus
Case 3
        .FramLasRef.Enabled = False
        .FramTabRef.Enabled = False
        .FramTrimNum.Enabled = False
        .FramCutType.Enabled = False
        .FramCutStart.Enabled = False
        .FramCutStop.Enabled = False
        .FramCutPar.Enabled = False
        .FramlasPar.Enabled = False
        .Frammark.Enabled = False
        .FramTrimBut.Enabled = False
        .FramTabStep.Enabled = False
        .FramExe.Enabled = True
        .txtExe.SetFocus
End Select
End With
End Sub
Sub getitem(ByVal recstring$, numitem%, it$)
'data una stringa, ne estrae il campo di ordine numitem%, contando i separatori
'il valore trovato viene restituito in it$
st% = -2
cc% = 0
Do
    c% = InStr(st% + Len(term$), recstring$, term$)
    If c% > 0 Then cc% = cc% + 1
    If cc% = numitem% Then
        it$ = Mid$(recstring$, st% + Len(term$), c% - st% - Len(term$))
        Exit Sub
    End If
    st% = c%
Loop While c% > 0
End Sub
'Sub getrecord(tp$, nr%)
''dato un file (tp$) e un numero di record (nr%),
''preleva il record e lo mette in therecord
''se il numero di record e' sbagliato, restituisce un
''record nullo
'un% = FreeFile
'Open tp$ For Random As #un% Len = Len(therecord)
'Get un%, nr%, therecord
'Close #un%
'Exit Sub
'On Error GoTo errget
'errget:
'therecord.genfield = Space$(lenrecord%)
'Exit Sub
'End Sub

Sub frequencyon(frq&)
    Dim aa As Byte
    fq! = CInt(1193180 / frq&)
    ffqq% = fq!
    lowdiv% = ffqq% And &HFF
    highdiv% = ffqq% / 256
    ad% = &H43
    aa = &HB6
    Call PortOut(ad%, aa)
    ad% = &H42
    aa = lowdiv%
    Call PortOut(ad%, aa)
    aa = highdiv%
    Call PortOut(ad%, aa)
    ad% = &H61
    aa = PortIn(ad%)
    aa = aa Or 3         'turn on
    Call PortOut(ad%, aa)
End Sub
Sub checkaccess()
If oplevel% > 0 Then Exit Sub
If oplevel% = 0 And pwd$ = encdec$(Chr$(0)) Then oplevel% = 1: Exit Sub
'FrmEuro.Enabled = False
Frmpwda.Show 1
End Sub
Sub frequencyoff()
    ad% = &H61
    aa = PortIn(ad%)
    aa = aa And Not 3
    Call PortOut(ad%, aa)
End Sub
Sub jogz()
Call updateposz
If moving% > 0 Then Exit Sub
Static enabler%
Static enabler1%
Static enabler2%
Static enabler3%
Static ocmd$
Static spxx&
Static spyy&
Static clk%
Static crk%
Static cuk%
Static cdk%
Static dtpun& 'memorizza l'istante in cui azzero il jog
ths% = 15
dt& = timeGetTime()
a& = GetCursorPos&(pt)
thexx& = Screen.Width / (2 * Screen.TwipsPerPixelX)
theyy& = Screen.Height / (2 * Screen.TwipsPerPixelY)
dx& = pt.x - thexx&
dy& = theyy& - pt.y
'accelerazioni assi
accx$ = accmax$
accy$ = accmax$
spx& = Int((mult& * dx&) / (dt& - odt&))
spy& = Int((mult& * dy&) / (dt& - odt&))
Select Case spx&
Case Is < -speedmaxzw&
    spx& = -speedmaxzw&
Case Is > speedmaxzw&
    spx& = speedmaxzw&
End Select
Select Case spy&
Case Is < -speedmaxzw&
    spy& = -speedmaxzw&
Case Is > speedmaxzw&
    spy& = speedmaxzw&
End Select
ck% = GetAsyncKeyState%(speedkey%) 'ctrl key
lk% = GetAsyncKeyState%(&H27) 'left key
uk% = GetAsyncKeyState%(&H26) 'up key
rk% = GetAsyncKeyState%(&H25) 'right key
dk% = GetAsyncKeyState%(&H28) 'down key
esk% = GetAsyncKeyState%(27) 'escape key
enk% = GetAsyncKeyState%(13) 'enter key
lmk% = GetAsyncKeyState%(&H1) 'left mouse button
rmk% = GetAsyncKeyState%(&H2) 'right mouse button
shk% = GetAsyncKeyState%(&H10) 'shift key

Select Case shk%
Case 0
    enabler2% = enabler2% Or 1
Case Else
    If enabler2% = 1 Then
        'ho spinto shift
        enabler2% = 0
        If dispstep% = 0 Then
            dispstep% = 1
        Else
            dispstep% = 0
        End If
    End If
End Select

Select Case esk%
Case 0
    enabler% = enabler% Or 1
Case Else
    If enabler% = 7 Then
        'ho spinto esc
        escjog% = 1
        enabler% = 0
    End If
End Select

Select Case enk%
Case 0
    enabler% = enabler% Or 2
Case Else
    If enabler% = 7 Then
        getv% = 1
        escjog% = 1
        enabler% = 0
        'ho spinto enter
    End If
End Select
Select Case lmk%
Case 0
    enabler% = enabler% Or 4
Case Else
    If enabler% = 7 Then
        getv% = 1
        escjog% = 1
        enabler% = 0
        'ho spinto il tasto sinistro
    End If
End Select
'Select Case rmk%
'Case 0
    'enabler% = enabler% Or 8
'Case Else
    'If enabler% = 15 Then
        'getv% = 1
        'escjog% = 1
        'enabler% = 0
        ''ho spinto il tasto destro
    'End If
'End Select
Select Case lk%
Case 0
    'non sto spigendo
    clk% = 0
    enabler1% = enabler1% Or 1
    If spxx& > 0 Then
        spxx& = 0
        kk% = 1
    End If
Case Else
    If enabler1% = 15 Then
        clk% = clk% + 1
        If lk% = 1 Then clk% = 1
        If clk% > ths% Then
            clk% = ths%
            spxx& = speedmaxzw&
        Else
            spxx& = (speedmaxzw& / ths%) * clk%
        End If
        'sto spingendo
        kk% = 1
        If ck% <> 0 Then
            acx% = 1
            spxx& = 2 * spxx&
        End If
    Else
        clk% = 0
    End If
End Select
Select Case rk%
Case 0
    'non sto spigendo
    crk% = 0
    enabler1% = enabler1% Or 2
    If spxx& < 0 Then
        spxx& = 0
        kk% = 1
    End If
Case Else
    If enabler1% = 15 Then
        'sto spingendo
        crk% = crk% + 1
        If rk% = 1 Then crk% = 1
        If crk% > ths% Then
            crk% = ths%
            spxx& = -speedmaxzw&
        Else
            spxx& = (-speedmaxzw& / ths%) * crk%
        End If
        kk% = 1
        If ck% <> 0 Then
            spxx& = 2 * spxx&
            acx% = 1
        End If
    Else
        crk% = 0
    End If
End Select
Select Case uk%
Case 0
    'non sto spigendo
    cuk% = 0
    enabler1% = enabler1% Or 4
    If spyy& < 0 Then
        spyy& = 0
        kk% = 1
    End If
Case Else
    If enabler1% = 15 Then
        'sto spingendo
        cuk% = cuk% + 1
        If uk% = 1 Then cuk% = 1
        If cuk% > ths% Then
            cuk% = ths%
            spyy& = -speedmaxzw&
        Else
            spyy& = (-speedmaxzw& / ths%) * cuk%
        End If
        kk% = 1
        If ck% <> 0 Then
            spyy& = 2 * spyy&
            acy% = 1
        End If
    Else
        cuk% = 0
    End If
End Select

Select Case dk%
Case 0
    'non sto spigendo
    cdk% = 0
    enabler1% = enabler1% Or 8
    If spyy& > 0 Then
        spyy& = 0
        kk% = 1
    End If
Case Else
    'sto spingendo
    If enabler1% = 15 Then
        cdk% = cdk% + 1
        If dk% = 1 Then cdk% = 1
        If cdk% > ths% Then
            cdk% = ths%
            spyy& = speedmaxzw&
        Else
            spyy& = (speedmaxzw& / ths%) * cdk%
        End If
        kk% = 1
        If ck% <> 0 Then
            spyy& = 2 * spyy&
            acy% = 1
        End If
    Else
        cdk% = 0
    End If
End Select
If kk% = 1 Then
    accx$ = accmin$
    If acx% = 1 Then accx$ = accmax$
    accy$ = accmin$
    If acy% = 1 Then accy$ = accmax$
    spx& = spxx&
    spy& = spyy&
End If

Select Case rmk%
Case 0
    enabler3% = enabler3% Or 1
Case Else
    If enabler3% = 1 Then
        If flagpuntali% = 1 Then
            Call readdevice(0, 0, 10)
            If d0.I_Puntali_Alti = 1 Then
                spx& = 0
                spy& = 0
                Call puntalidown(checkok%)
            Else
                Call puntaliup(checkok%)
            End If
        End If
    End If
End Select

If odt& <> 0 And (spx& <> 0 Or spy& <> 0) Then
    If flagpuntali% = 1 Then
        dtpun& = -1
        Call readdevice(0, 0, 10)
        If d0.I_Puntali_Alti = 0 Then
            Call puntaliup(checkok%)
            If checkok% = 0 Then spx& = 0: spy& = 0
        End If
    End If
    'tcmd$ = "JG ,," + Str$(spx&) + "," + Str$(spy&) + ";" + "BG ZW"
    tcmd$ = "JG ,," + Str$(spx&) + ",;" + "BG Z"
Else
    tcmd$ = "ST ZW;SP ,," + Str(speedmaxzw&) + ","
    If flagpuntali% = 1 Then
        If d0.I_Puntali_Alti = 1 Then
            dtp& = timeGetTime&()
            If dtpun& = -1 Then
                dtpd& = 0
                dtpun& = dtp&
            Else
                dtpd& = dtp& - dtpun&
            End If
            If dtpd& > 500 Then
                Call galilcmd(tcmd$, res$, ermsg$)
                Call puntalidown(checkok%)
            End If
        Else
            dtpun& = -1
        End If
    End If
End If
If escjog% = 1 Then tcmd$ = "ST Z;SP ,," + Str(speedmaxzw&) + ",;AC ,," + accx$ + ","
tcmd$ = tcmd$ + ";AC ,," + accx$ + ","
If ocmd$ <> tcmd$ Then
    'Debug.Print tcmd$
    Call galilcmd(tcmd$, res$, ermsg$)
End If
ocmd$ = tcmd$
a& = SetCursorPos(thexx&, theyy&)
odt& = dt&
If escjog% = 1 Then
        If getv% = 1 Then
            Call galilcmd("TP ZW", res$, ermsg$)
            cm% = InStr(res$, ",")
            If cm% > 0 Then
                thex& = Val(Trim$(Left$(res$, cm% - 1)))
                they& = Val(Trim$(Mid$(res$, cm% + 1)))
            End If
        End If
        Do
            esk% = GetAsyncKeyState%(27) 'escape key
            enk% = GetAsyncKeyState%(13) 'enter key
            lmk% = GetAsyncKeyState%(&H1) 'left mouse button
            rmk% = GetAsyncKeyState%(&H2) 'right mouse button
            tk% = esk% + enk% + lmk% + rmk%
            DoEvents
        Loop While tk% <> 0
        Call offjog
        enabler% = 0
        enabler1% = 0
        ocmd$ = ""
        Select Case statjog%
        Case -1
            'Jog
            statjog% = 0
            Call switchcamera(0, 1)
        Case 0
            'ref. macchina
            If getv% = 1 Then
                RefZ& = thex&
                RefW& = they&
                Call saveini
            End If
            Call switchcamera(0, 1)
        Case 1
            'reference tavola per taglio
            If getv% = 1 Then
                TTabReferenceZ$ = Trim(Str(thex&))
                Frmedit.txtRefZ.Tag = TTabReferenceZ$
                Frmedit.txtRefZ = formatter$(step2mm#(thex&, stepzw!), 3, 2)
                TTabReferenceW$ = Trim(Str(they&))
                Frmedit.txtRefW.Tag = TTabReferenceW$
                Frmedit.txtRefW = formatter$(step2mm#(they&, stepzw!), 3, 2)
            End If
            Call switchcamera(0, 1)
            statjog% = 0
            Frmedit.ZOrder 0
            Frmedit.Show 1
        End Select
 End If

End Sub
Sub loadlanguage(curfrm As Form, lang$)
With curfrm
'carica le stringhe nella lingua stabilita dal file:
'nomeform.lang; per la codifica dell'informazione vedere
'anche il file stesso
Dim gencontr As Object
Set gencontr = Nothing
un% = FreeFile
thefile$ = thepath$ + .Name + "." + lang$
ex$ = Dir(thefile$)
ci% = -1
If ex$ <> "" Then
    'On Error GoTo errcontr
    Open thefile$ For Input As #un%
        While Not EOF(un%)
            Line Input #un%, cl$
            cl$ = LTrim$(cl$)
            Select Case Left$(cl$, 1)
            Case ")"
                'indice di array di controlli
                ci% = Val(Mid$(cl$, 2))
            Case "/"
                'identifica il nome di un controllo
                cmode% = 0
                ci% = -1
                If Trim(Mid$(cl$, 2)) = "" Then
                    Set gencontr = Nothing
                Else
                    Set gencontr = .Controls(Trim$(Mid$(cl$, 2)))
                End If
            Case "$"
                'scritta su un bottone o etichetta
                If ci% >= 0 Then
                    dn% = 0
                    If Not (gencontr Is Nothing) Then
                        If TypeOf gencontr Is Toolbar Then
                            gencontr.Buttons(ci%) = Mid$(cl$, 2)
                            dn% = 1
                        End If
                        If TypeOf gencontr Is SSTab Then
                            gencontr.TabCaption(ci%) = Mid$(cl$, 2)
                            dn% = 1
                        End If
                    End If
                    If dn% = 0 Then gencontr(ci%).Caption = Mid$(cl$, 2)
                Else
                    If gencontr Is Nothing Then
                        .Caption = Mid$(cl$, 2)
                    Else
                        gencontr.Caption = Mid$(cl$, 2)
                    End If
                End If
            Case "#"
                'tag, utile per i range
                cl1$ = Trim(Mid$(cl$, 2))
                Select Case Left$(cl1$, 1)
                Case "@"
                    'e'un range
                    cl$ = Mid$(cl1$, 2)
                    If ci% >= 0 Then
                        gencontr(ci%).Tag = gencontr(ci%).Tag + "@" + cl$ + "@"
                    Else
                        gencontr.Tag = gencontr.Tag + "@" + cl$ + "@"
                    End If
                Case Else
                    'e' un tag normale
                    If ci% >= 0 Then
                        gencontr.Tag(ci%) = gencontr.Tag(ci%) + cl$ + "#"
                    Else
                        gencontr.Tag = gencontr.Tag + cl$ + "#"
                    End If
                End Select
            Case "^"
                'scritta di help sul puntatore del mouse
                If ci% >= 0 Then
                    dn% = 0
                    If Not (gencontr Is Nothing) Then
                        If TypeOf gencontr Is Toolbar Then
                            Call SetTip(Trim$(Mid$(cl$, 2)), gencontr.Buttons(ci%))
                            dn% = 1
                        End If
                    End If
                    If dn% = 0 Then Call SetTip(Trim$(Mid$(cl$, 2)), gencontr(ci%))
                Else
                    Call SetTip(Trim$(Mid$(cl$, 2)), gencontr)
                End If
            Case "@"
                'testo di una casella di testo
                'quando necessario, va posto per ultimo nella lista dell'oggetto
                'in modo da scatenare l'evento change a cose fatte
                If ci% >= 0 Then
                    gencontr(ci%).Text = Mid$(cl$, 2)
                Else
                    gencontr.Text = Mid$(cl$, 2)
                End If
            End Select
        Wend
    Close #un%
End If
End With
Exit Sub
errcontr:
Resume Next
End Sub
Function getit$(nitem%, itst$, sp$)
'data una stringa, ne estrae un sottocampo delimitato
'dal carattere sp$, dal sottocampo estrae l'elemento nitem%
If sp$ <> "" Then
    s1% = InStr(itst$, sp$)
    If s1% > 0 Then
        s2% = InStr(s1% + 1, itst$, sp$)
        If s2% > 0 Then itst$ = Mid$(itst$, s1% + 1, s2% - s1% - 1)
    End If
End If
res$ = ""
itst1$ = Trim$(itst$)
If Left$(itst1$, 1) <> "^" Then itst$ = "^" + itst$
If Right$(itst1$, 1) <> "^" Then itst$ = itst$ + "^"
st% = 0
en% = 0

For i% = 1 To nitem%
    st% = InStr(st% + 1, itst$, "^")
    If st% <= 0 Then Exit For
Next i%
If st% > 0 Then
    en% = InStr(st% + 1, itst$, "^")
    If en% > 0 Then
        res$ = Mid$(itst$, st% + 1, en% - st% - 1)
    End If
End If
getit$ = res$
End Function

Sub SetTip(tip$, thctrl As Variant)
'setta il tooltip di un oggetto; per maggiore leggibilita' aggiunge spazi agli estremi
thctrl.ToolTipText = " " + Trim$(tip$) + " "
End Sub

Sub Main()
If App.PrevInstance = True Then End
thepath$ = App.Path
If Right$(thepath$, 1) <> "\" Then thepath$ = thepath$ + "\"
Call loadini
FrmEuro.Enabled = False
term$ = Chr$(13) + Chr$(10)
Xsize% = FrmEuro.Digitizer.SizeX
Ysize% = FrmEuro.Digitizer.SizeY
If Xsize% = 0 Then Xsize% = 768
If Ysize% = 0 Then Ysize% = 576
ReDim BufPixel(1 To Xsize%, 1 To Ysize%) As Byte
FrmEuro.Show
FrmEuro.Refresh
Call initdisplay
'Call loadini
FrmEuro.Digitizer.Contrast = thecontrast&
FrmEuro.Digitizer.Brightness = thebrightness&
Call loadstat
'password nulla
oplevel% = 0
If pwd$ = encdec$(Chr$(0)) Then
    oplevel% = 1
Else
    FrmEuro.mnuedacc.Visible = True
End If
If workdir$ = "" Then
    thepath1$ = thepath$
Else
    thepath1$ = workdir$
    If Left$(workdir$, 1) = "\" Then thepath1$ = thepath$ + Mid$(workdir$, 2)
End If
If Right$(thepath1$, 1) <> "\" Then
    thepath1$ = thepath1$ + "\"
End If
If LaserX& < 0 Then
    LaserX& = (FrmEuro.SSPanel1.Width / 2) / Screen.TwipsPerPixelX
End If
If LaserY& < 0 Then
    LaserY& = (Screen.Height - FrmEuro.SSPanel1.Height / 2) / Screen.TwipsPerPixelY
End If
If EditorX& < 0 Then
    EditorX& = (Screen.Width - Frmedit.Width) / 2
End If
If EditorY& < 0 Then
    EditorY& = (Screen.Height - Frmedit.Height) / 2
End If
Call movecross(LaserX&, LaserY&, RGB(255, 0, 0))
FrmEuro.Show
FrmEuro.Refresh
Call resetmachine
End Sub
Sub setfreqda(dn%, freq!)
freq! = Abs(freq!)
If freq! > 15000 Then freq! = 15000
If ioportmatrix(dn%) = -1 Then Exit Sub
If hiomatrix(dn%) = -1 Then Exit Sub
rt& = CInt(100000 / freq!)
ptiow.port = ioportmatrix(dn%) + 15
ptiow.ByteData = 62 'counter,write LSB MSB, modo 3
errcde = DRV_WritePortByte(hiomatrix(dn%), ptiow)
If errcde <> 0 Then GoTo errcode
lsb% = rt& And 255
msb% = Int(rt& / 256)
ptiow.port = ioportmatrix(dn%) + 12
ptiow.ByteData = lsb%
errcde = DRV_WritePortByte(hiomatrix(dn%), ptiow)
If errcde <> 0 Then GoTo errcode
ptiow.port = ioportmatrix(dn%) + 12
ptiow.ByteData = msb%
errcde = DRV_WritePortByte(hiomatrix(dn%), ptiow)
If errcde <> 0 Then GoTo errcode
ptiow.port = ioportmatrix(dn%) + 10
ptiow.ByteData = 2
errcde = DRV_WritePortByte(hiomatrix(dn%), ptiow)
If errcde <> 0 Then GoTo errcode
lastfreq$ = Trim$(Str$(freq!))
Exit Sub
errcode:
Call updatelog(mss$(33), 1)
End Sub
Sub lampon()
'accensione pompa e lampada
Call readdevice(0, 0, 10)
ad$ = ""
'verifica condizione di interlock laser
If d0.O_PasswordOK = 0 And d0.I_Blocco_Chiller = 0 Then ad$ = ad$ + ", Chiller"
If d0.I_Clickson_Laser = 0 Then ad$ = ad$ + ", Clickson"
If d0.I_Livello_Refrigerante = 0 Then ad$ = ad$ + ", Level"
If d0.O_PasswordOK = 0 And d0.I_Interlock_Qswitch = 0 Then ad$ = ad$ + ", QSwitch"
If d0.I_Termico_Pompa_Refrigerante = 0 Then ad$ = ad$ + ", Pump"
If ad$ <> "" Then
    ad$ = Mid$(ad$, 3)
    MsgBox (mss$(147) + "(" + ad$ + ")")
    Exit Sub
End If
msg$ = (mss$(34))
Call showstatus(msg$)
dtcurr& = timeGetTime&()
Hasdone% = 4
FrmEuro.Enabled = False
Call enablework
Call updatelog(mss$(35), 2)
If pumpon% = 1 Then
    'la pompa e' gia' accesa
    'controllo livello acqua e flusso
    Call updatelog(mss$(36), 2)
    Call checkpump(ok%)
    If ok% = 0 Then
        Call exitreset
        Exit Sub
    End If
Else
    Call updatelog(mss$(37), 2)
    Call updatelog(mss$(38), 2)
    If d0.I_Termico_Pompa_Refrigerante = 0 Then
        Call updatelog(mss$(39), 2)
        Call updatelog(mss$(40), 2)
        Call lampoff
        ermsg$ = mss$(41)
        Call alert(ermsg$, 1)
        Call exitreset
        Exit Sub
    End If
    Call updatelog(mss$(42), 2)
    Call setoutput(0, d0.O_Rele_Comm_Pompa_Ref)
    Call setoutput(0, d0.O_Abilitazione_Chiller)
    Call updatelog(mss$(43), 2)
    Call Delay(10000)
    Call checkpump(ok%)
    If ok% = 0 Then
        Call exitreset
        Exit Sub
    End If
    pumpon% = 1
End If
    Call updatelog(mss$(44), 2)
    If d0.I_Clickson_Laser = 0 Then
        Call updatelog(mss$(45), 2)
        ermsg$ = mss$(46)
        Call alert(ermsg$, 1)
        Call exitreset
        Exit Sub
    End If
    Call updatelog(mss$(47), 2)
    'Rf on
    Call updatelog(mss$(48), 2)
    Call setoutput(0, d0.O_RF_On_12V)
    Call updatelog(mss$(43), 2)
    rfon% = 0
    Call Delay(1000)
    rfon% = 1
    Call readdevice(0, 0, 10)
    'da 7 A
    Call updatelog(mss$(49), 2)
    Call setda(1, 7, ilasmax!)
    upc% = 2
    For i% = 1 To upc%
        If rfon% = 1 Then rfon% = -1
        Call updatelog(mss$(50) + Str(i%), 2)
        Call updatelog(mss$(51) + Str(i%), 2)
        Call setoutput(0, d0.O_Lamp_On)
        dtlamp& = timeGetTime&()
        tm% = 0
        Call updatelog(mss$(52), 2)
        Do
            DoEvents
            dif& = timeGetTime&() - dtlamp&
            If d0.I_Contaore_Laser_On = 1 Then
                oonn% = 1
                Exit Do
            End If
            If dif& > 10000 Then
                tm% = 1
                Exit Do
            End If
        Loop
        If rfon% = -1 And oonn% = 1 Then
            Call Delay(4000)
        End If
        rfon% = 1
        If tm% = 1 Then
            Call updatelog(mss$(53), 2)
            Call updatelog(mss$(54), 2)
            Call resetoutput(0, d0.O_Lamp_On)
            Call updatelog(mss$(55), 2)
            Call Delay(15000)
        Else
            Call updatelog(mss$(56) + Str(i%), 2)
            Exit For
        End If
        If Hasdone% = 2 Then
            Call exitreset
            Exit Sub
        End If
    Next i%
    If tm% = 1 Then
        Call updatelog(mss$(57), 2)
        ermsg$ = mss$(58) + Str$(upc%)
        Call alert(ermsg$, 2)
    End If
    If flagdopsi% = 0 Then FrmEuro.Enabled = True
    FrmEuro.Timerwork.Enabled = False
    Call hidelog
    Hasdone% = 0
    msg$ = ""
    Call showstatus(msg$)
End Sub
Sub pump_on()
enab% = FrmEuro.Enabled
FrmEuro.Enabled = False
Call updatelog(mss$(35), 2)
If pumpon% = 1 Then
    'la pompa e' gia' accesa
    'controllo livello acqua e flusso
    Call updatelog(mss$(36), 2)
    Call checkpump(ok%)
    If ok% = 0 Then
        Call hidelog
        FrmEuro.Enabled = enab%
        Exit Sub
    End If
Else
    Call updatelog(mss$(37), 2)
    Call updatelog(mss$(38), 2)
    If d0.I_Termico_Pompa_Refrigerante = 0 Then
        Call updatelog(mss$(39), 2)
        Call updatelog(mss$(40), 2)
        Call lampoff
        ermsg$ = mss$(41)
        Call alert(ermsg$, 1)
        Call exitreset
        FrmEuro.Enabled = enab%
        Exit Sub
    End If
    Call updatelog(mss$(42), 2)
    Call setoutput(0, d0.O_Rele_Comm_Pompa_Ref)
    Call setoutput(0, d0.O_Abilitazione_Chiller)
    Call updatelog(mss$(43), 2)
    Call Delay(10000)
    Call checkpump(ok%)
    If ok% = 0 Then
        Call exitreset
        FrmEuro.Enabled = enab%
        Exit Sub
    End If
    pumpon% = 1
End If
Call hidelog
FrmEuro.Enabled = enab%
End Sub
Sub loadstat()
    un% = FreeFile
    thefile$ = thepath$ + "stat.dat"
    Open thefile$ For Input As #un%
    While Not EOF(un%)
        Line Input #un%, cl$
        cl$ = Trim$(cl$)
        If Left$(cl$, 1) <> "'" And cl$ <> "" Then
            lc% = lc% + 1
            Select Case lc%
            Case 1
                'Contaore
                cm% = InStr(cl$, ",")
                If cm% > 0 Then
                    Mid$(cl$, cm%, 1) = "."
                End If
                wason! = Val(cl$)
            End Select
        End If
    Wend
    Close #un%
End Sub
Sub savestat()
un% = FreeFile
Open thepath$ + "Stat.dat" For Output As #un%
Print #un%, wason!
Close un%
End Sub
Sub lampoff()
    msg$ = (mss$(54))
    Call showstatus(msg$)
    'riduzione corrente
    If FrmEuro.Enabled = False Then disabled% = 1
    FrmEuro.Enabled = False
    Call updatelog(mss$(49), 2)
    Call setda(1, 7, ilasmax!)
    'stdby
    Call updatelog(mss$(59), 2)
    Call resetoutput(0, d0.O_Rele_Work_Standby)
    'lamp off
    Call updatelog(mss$(54), 2)
    Call resetoutput(0, d0.O_Lamp_On)
    'RF off
    Call updatelog(mss$(60), 2)
    Call resetoutput(0, d0.O_RF_On_12V)
    rfon% = 0
    If d0.I_Clickson_Laser = 1 Then
        'spengo la pompa
        Call updatelog(mss$(43), 2)
        Call Delay(10000)
        Call updatelog(mss$(40), 2)
        pumpon% = 0
        Call resetoutput(0, d0.O_Rele_Comm_Pompa_Ref)
        Call resetoutput(0, d0.O_Abilitazione_Chiller)
    End If
    If disabled% = 0 Then
        If flagdopsi% = 0 Then FrmEuro.Enabled = True
    End If
    Call hidelog
    msg$ = ""
    Call showstatus(msg$)
End Sub
Sub checkpump(ok%)
    ok% = 1
    Call updatelog(mss$(61), 2)
    Call readdevice(0, 0, 10)
    If d0.I_Livello_Refrigerante = 0 Then
        Call updatelog(mss$(62), 2)
        Call updatelog(mss$(40), 2)
        Call lampoff
        ermsg$ = mss$(63)
        Call alert(ermsg$, 1)
        ok% = 0
        Exit Sub
    Else
        Call updatelog(mss$(64), 2)
    End If
    'flusso
    Call updatelog(mss$(65), 2)
    Call readdevice(0, 0, 10)
    If d0.I_Flusso_Refrigerante = 0 Then
        Call updatelog(mss$(143), 2)
        Call updatelog(mss$(40), 2)
        Call lampoff
        ermsg$ = mss$(66)
        Call alert(ermsg$, 1)
        ok% = 0
        Exit Sub
    Else
        Call updatelog(mss$(67), 2)
    End If
End Sub
Sub machineoff()
Call readdevice(0, 0, 10)
If d0.I_Contaore_Laser_On = 1 Then
    Call lampoff
End If
Call readdevice(0, 0, 10)
If d0.I_Rele_Comm_Pompa_Refrigerante = 1 Then
    Call lampoff
End If
'fermo la Galil
Call updatelog(mss$(68), 2)
Call galilcmd("AB 1", res$, ermsg$)
Call galilcmd("ST XYZW", res$, ermsg$)
Call galilcmd("MO XYZW", res$, ermsg$)
'annullo tutti gli output
Call updatelog(mss$(69), 2)
Call setprt(0, 3, 255, 0)
Call setprt(0, 4, 255, 0)
Call setprt(0, 5, 255, 0)
Call setprt(0, 6, 255, 0)
Call updatelog(mss$(70), 2)
Call readdevice(0, 0, 10)
Call closedevices
FrmEuro.Timerpoll.Enabled = False
End Sub
Sub resetmachine()
If hiomatrix(1) = 0 Then
    For i% = 0 To 9
        hiomatrix(i%) = -1
        ioportmatrix(i%) = -1
    Next i%
    hDmc = -1
End If
FrmEuro.Enabled = False
a% = MsgBox(mss$(71), vbYesNo Or vbDefaultButton1, mss$(23))
If a% = 7 Then
    If flagdopsi% = 0 Then FrmEuro.Enabled = True
    Exit Sub
End If
justloaded% = 1
msg$ = mss$(72)
Call showstatus(msg$)
If pumpon% = 1 Then
    Call lampoff
End If
'Call closedevices
If iodev$ <> "" Then
    Call scanio
End If
If oplevel% = 2 Then
    Call updatelog(mss$(73), 2)
    Call setoutput(0, d0.O_PasswordOK)
Else
    Call updatelog(mss$(74), 2)
    Call resetoutput(0, d0.O_PasswordOK)
End If
Call readdevice(0, 0, 10)
Call updatelog(mss$(75), 2)
While d0.I_Rele_Emergenza = 0
    Call readdevice(0, 0, 10)
    Call updatelog(mss$(76), 2)
    ermsg$ = mss$(77)
    Call showerror(ermsg$, 0, ans%)
    If ans% = 2 Then
        Call exitreset
        Exit Sub
    End If
Wend
Call updatelog(mss$(78), 2)
Call updatelog(mss$(79), 2)
Call readdevice(0, 0, 10)
While d0.I_Alimentazione_24 = 0
    Call updatelog(mss$(80), 2)
    ermsg$ = mss$(81)
    Call showerror(ermsg$, 0, ans%)
    If ans% = 2 Then
        Call exitreset
        Exit Sub
    End If
    Call readdevice(0, 0, 10)
Wend
Call updatelog(mss$(82), 2)
Do
    Call updatelog(mss$(83), 2)
    Call readdevice(0, 0, 10)
    If d0.I_Switch_Portello_Ant_Open = 1 Then
        Call updatelog(mss$(84), 2)
        Call updatelog(mss$(85), 2)
        If d0.I_Chiave_Abilitazione_Laser = 1 Then
            Call updatelog(mss$(86), 2)
            Call checkaccess
            If oplevel% < 1 Then
                ermsg$ = mss$(87)
                Call showerror(ermsg$, 0, ans%)
                If ans% = 2 Then
                    Call exitreset
                    Exit Sub
                End If
            Else
                Exit Do
            End If
        Else
            Call updatelog(mss$(144), 2)
            ermsg$ = mss$(88)
            Call showerror(ermsg$, 0, ans%)
            If ans% = 2 Then
                Call exitreset
                Exit Sub
            End If
        End If
    Else
        Call updatelog(mss$(89), 2)
        Exit Do
    End If
Loop
If loopingsafety% = 1 Then Exit Sub
'Call checksafety
Call readdevice(0, 0, 10)
Do
    Call readdevice(0, 0, 10)
    Call updatelog(mss$(90), 2)
    If d0.I_Switch_Portello_Sup_Open = 1 Then
        Call updatelog(mss$(91), 2)
        Call updatelog(mss$(85), 2)
        If d0.I_Chiave_Abilitazione_Laser = 1 Then
            Call updatelog(mss$(86), 2)
            Call checkaccess
            If oplevel% < 1 Then
                ermsg$ = mss$(92)
                Call showerror(ermsg$, 0, ans%)
                If ans% = 2 Then
                    Call exitreset
                    Exit Sub
                End If
            Else
                Exit Do
            End If
        Else
            Call updatelog(mss$(144), 2)
            ermsg$ = mss$(93)
            Call showerror(ermsg$, 0, ans%)
            If ans% = 2 Then
                Call exitreset
                Exit Sub
            End If
        End If
    Else
        Call updatelog(mss$(94), 2)
        Exit Do
    End If
Loop
Call checksafety
Call readdevice(0, 0, 10)
Call updatelog(mss$(35), 2)
If pumpon% = 1 Then
    'la pompa e' accesa, devo controllare livello e flusso
    'livello
    Call updatelog(mss$(36), 2)
    Call checkpump(ok%)
    If ok% = 0 Then
        Call exitreset
        Exit Sub
    End If
Else
    Call updatelog(mss$(37), 2)
End If
'system on
Call updatelog(mss$(95), 2)
Call setoutput(0, d0.O_System_On)
'tensioni ausiliarie
Call updatelog(mss$(96), 2)
Call setoutput(0, d0.O_24V_Cond_A_O)
Call updatelog(mss$(97), 2)
Call setoutput(0, d0.O_24V_Cond_B_O)
Call updatelog(mss$(98), 2)
Call setoutput(0, d0.O_24V_Cond_C_I)
'illuminazione
Call updatelog(mss$(99), 2)
Call setoutput(0, d0.O_Rele_Illuminazione)
'attacco il vuoto per un attimo
If vacuum% = 1 Then
    Call updatelog(mss$(100), 2)
    'Call setoutput(0, d0.O_Rele_Vuoto_Tav_A)
    Call setoutput(0, d0.O_Cattivo_A)
    Call updatelog(mss$(101), 2)
    Call Delay(500)
    Call readdevice(0, 0, 10)
    Call updatelog(mss$(102), 2)
    If d0.I_Pressione_Aria = 0 Then
        Call updatelog(mss$(103), 2)
        Call updatelog(mss$(104), 2)
        'Call resetoutput(0, d0.O_Rele_Vuoto_Tav_A)
        Call resetoutput(0, d0.O_Cattivo_A)
    Else
        Call updatelog(mss$(105), 2)
    End If
End If
If mctype% > 0 Then
    Select Case mctype%
    Case 1
        Call opengalil
    End Select
End If
If doubletable% = 1 Then
    Call tableABout
End If
moving% = 2
FrmEuro.Timerpoll.Enabled = True
FrmEuro.TimerMove.Interval = 100
FrmEuro.TimerMove.Enabled = True
End Sub
Sub vuoto(st%)
If vacuum% = 0 Then Exit Sub
If st% = 0 Then
    'Call resetoutput(0, d0.O_Rele_Vuoto_Tav_A)
    Call resetoutput(0, d0.O_Cattivo_A)
Else
    Call readdevice(0, 0, 10)
    'If d0.O_Rele_Vuoto_Tav_A = 1 Then Exit Sub
    If d0.O_Cattivo_A = 1 Then Exit Sub
    'Call setoutput(0, d0.O_Rele_Vuoto_Tav_A)
    Call setoutput(0, d0.O_Cattivo_A)
    Call Delay(200)
End If
End Sub
Sub exitalert()
    workexit% = 1
    If FrmEuro.Timerwork.Enabled = True Then
        Hasdone% = 5
    End If
    If flagdopsi% = 0 Then FrmEuro.Enabled = True
    oldmsg$ = ""
    msg$ = ""
    Call showstatus(msg$)
End Sub
Sub Delay(ms&)
dt1& = timeGetTime&()
Do
    DoEvents
    dt2& = timeGetTime&()
    dif& = dt2& - dt1&
    If dif& < 0 Then dt1& = timeGetTime&()
Loop While dif& < ms&
End Sub
Sub checkmachineon(ok%)
ok% = 1
'Call readdevice(0,0,12)
'If d0.O_System_On = 0 Then
If FrmEuro.Imgmacon.Visible = False Then
    ok% = 0
    MsgBox (mss$(106))
End If
End Sub
Function mss$(md%)
mss$ = ""
fd2$ = Chr$(13) + Chr$(10)
fd1$ = fd2$ + Trim(Str(md%))
f1% = InStr(thestrings$, fd1$)
If f1% > 0 Then
    f2% = InStr(f1% + 1, thestrings$, fd2$)
    If f2% > 0 Then
        bg% = f1% + Len(fd1$)
        ln% = f2% - f1% - Len(fd1$)
        ttss$ = Mid$(thestrings$, bg%, ln%)
        bg% = 1
        Do
            sl% = InStr(ttss$, "/\")
            If sl% > 0 Then
                bg% = sl% + 1
                Mid$(ttss$, sl%, 2) = Chr$(13) + Chr$(10)
            End If
        Loop While sl% > 0
        mss$ = ttss$
    End If
End If
End Function
Sub alert(ermsg$, which%)
Call updatelog(ermsg$, 1)
If (which% And 1) = 1 Then Call setoutput(0, d0.O_Allarme_Macchina)
If (which% And 3) = 3 Then Call setoutput(0, d0.O_Chiamata_Operatore)
a% = MsgBox(ermsg$, vbOKOnly Or vbExclamation)
If (which% And 1) = 1 Then Call resetoutput(0, d0.O_Allarme_Macchina)
If (which% And 3) = 3 Then Call resetoutput(0, d0.O_Chiamata_Operatore)
Call hidelog
End Sub
Sub exitreset()
    Call updatelog(mss$(107), 2)
    FrmEuro.Timerwork.Enabled = False
    If flagdopsi% = 0 Then FrmEuro.Enabled = True
    Hasdone% = 0
    justloaded% = 0
    oldmsg$ = ""
    msg$ = ""
    Call showstatus(msg$)
End Sub
Sub closedevices()
For i% = 0 To 9
    If hiomatrix(i%) <> -1 Then
        a& = DRV_DeviceClose(hiomatrix(i%))
    End If
Next i%
With FrmEuro
    .Imgmacoff.Visible = True
    .Imgmacon.Visible = False
    .Imgpumpoff.Visible = True
    .Imgpumpon.Visible = False
    .Imglampoff.Visible = True
    .Imglampon.Visible = False
    .ImgRFoff.Visible = True
    .ImgRFon.Visible = False
    .Lblfreq.Caption = "0"
    .Lblcurr.Caption = "0"
    .Toolbar1.Buttons.Item(8).value = tbrUnpressed
    .Toolbar1.Buttons.Item(9).value = tbrUnpressed
    .Toolbar1.Buttons.Item(10).value = tbrUnpressed
    .Toolbar1.Buttons.Item(12).value = tbrUnpressed
    lastfreq$ = "0"
    lastcurr$ = "0"
End With
If mctype% > 0 Then
    Select Case mctype%
    Case 1
        'galil
        If hDmc > -1 Then a& = DMCClose(hDmc)
        hDmc = -1
    End Select
End If
For i% = 0 To 9
    hiomatrix(i%) = -1
    ioportmatrix(i%) = -1
Next i%
End Sub
Sub checksafety()
Static wrote%
ok% = 0
loopingsafety% = 1
wrote% = 0
exitsafety% = 0
    Do
        DoEvents
        Call readdevice(0, 0, 10)
        pa% = d0.I_Switch_Portello_Ant_Open
        ps% = d0.I_Switch_Portello_Sup_Open
        If pa% = 1 Or ps% = 1 Then
            If oplevel% > 0 And d0.I_Chiave_Abilitazione_Laser = 1 Then
                a% = MsgBox(mss$(108))
                Call readdevice(0, 0, 10)
                If oplevel% > 0 And d0.I_Chiave_Abilitazione_Laser = 1 Then ok% = 1
            Else
                wrote% = 1
                msg$ = (mss$(109))
                If pa% = 0 Then msg$ = (mss$(110))
                Call showstatus(msg$)
            End If
        Else
            ok% = 1
        End If
        If flagdopsi% = 1 Then
            ek% = GetAsyncKeyState%(27) 'esc key
            If ek% <> 0 Then
                pressesc% = 1
                Exit Do
            End If
        End If
    Loop While ok% = 0 And exitsafety% = 0
loopingsafety% = 0
If wrote% = 1 Then
    msg$ = ""
    Call showstatus(msg$)
End If
End Sub
Sub showstatus(msg$)
With FrmEuro
If msg$ = "" Then
    msg$ = oldmsg$
    oldmsg$ = ""
End If
If msg$ = "" Then
    oldmsg$ = ""
    .lblstatus.Visible = False
    .lblstatus.Caption = ""
    Exit Sub
End If
If msg$ = .lblstatus.Caption Then Exit Sub
If .lblstatus.Visible = True Then
    oldmsg$ = .lblstatus.Caption
    .lblstatus.Caption = msg$
Else
    .lblstatus.Caption = msg$
    .lblstatus.Top = .Toolbar1.Height
    .lblstatus.Left = 0
    .lblstatus.Height = .SSPanel1.Top - .TxtLog.Top
    .lblstatus.Width = .SSPanel1.Width
    .lblstatus.Visible = True
    .lblstatus.ZOrder 0
End If
End With
End Sub
Sub showstatus1(msg$)
With FrmEuro
If msg$ = "" Then
    '.Lblstatus1.Visible = False
    .Lblstatus1.Caption = ""
    Exit Sub
End If
If msg$ = .Lblstatus1.Caption Then Exit Sub
.Lblstatus1.Caption = msg$
'.Lblstatus1.Visible = True
End With
End Sub

Sub showerror(ermsg$, which%, ans%)
Select Case which%
Case 0
    ans% = MsgBox(ermsg$, vbRetryCancel Or vbExclamation, mss$(111))
End Select
End Sub
Sub onjog(posx$, posy$, posz$, posw$)
Do
    ck% = GetAsyncKeyState%(speedkey%) 'ctrl key
    pup% = GetAsyncKeyState%(&H21) 'left key
    pdn% = GetAsyncKeyState%(&H22) 'up key
    lk% = GetAsyncKeyState%(&H25) 'left key
    uk% = GetAsyncKeyState%(&H26) 'up key
    rk% = GetAsyncKeyState%(&H27) 'right key
    dk% = GetAsyncKeyState%(&H28) 'down key
    esk% = GetAsyncKeyState%(27) 'escape key
    enk% = GetAsyncKeyState%(13) 'enter key
    lmk% = GetAsyncKeyState%(&H1) 'left mouse button
    rmk% = GetAsyncKeyState%(&H2) 'right mouse button
    shk% = GetAsyncKeyState%(&H10) 'shift key
    tot% = pup% + pdn% + ck% + lk% + uk% + rk% + dk% + esk% + enk% + lmk% + rmk% + shk%
    DoEvents
Loop While tot% <> 0
msg$ = mss$(112)
Call showstatus(msg$)
dispstep% = 0
If jogging% = 1 Then Call switchcamera(0, 1)
FrmEuro.TimerJog.Enabled = True
FrmEuro.TimerJog.Tag = "A"
a& = GetCursorPos&(pt)
oldx& = pt.x
oldy& = pt.y
Call hidecursor
Call movecross(LaserX&, LaserY&, RGB(0, 255, 0))
tx& = Screen.Width / (2 * Screen.TwipsPerPixelX)
ty& = Screen.Height / (2 * Screen.TwipsPerPixelY)
a& = SetCursorPos(tx&, ty&)
If posx$ <> "" Or posz$ <> "" Then
    Select Case jogging%
    Case 1
        If posz$ <> "" Then
            Call gotoposxyzw(posx$, posy$, posz$, posw$)
        Else
            Call gotoposxy(posx$, posy$)
        End If
    Case 2
        If posx$ <> "" Then
            Call gotoposxyzw(posx$, posy$, posz$, posw$)
        Else
            Call gotoposzw(posz$, posw$)
        End If
    Case 3
        If posz$ <> "" Then
            Call gotoposxyzw(posx$, posy$, posz$, posw$)
        Else
            Call gotoposxy(posx$, posy$)
        End If
    End Select
End If
If FrmEuro.Enabled = True Then FrmEuro.Display.SetFocus
FrmEuro.Enabled = False
End Sub

Sub md(Button)
If FrmEuro.TimerCross.Enabled = True Then
    Select Case Button
    Case 2
    'tasto destro
        'Sparo laser
        If laseron% = 0 Then
            If d0.O_System_On = 0 Then
                Exit Sub
            End If
            If d0.I_Contaore_Laser_On = 0 Then
                Exit Sub
            End If
            Call movecross(pt.x, pt.y, RGB(0, 0, 255))
            Call setoutput(0, d0.O_Rele_Work_Standby)
            thefreq! = 1000
            If manfreq! <> 0 Then thefreq! = manfreq! * 1000
            Call setfreqda(1, thefreq!)
            thecurr! = 14
            If mancurr! <> 0 Then thecurr! = mancurr!
            lastcurr$ = Trim$(Str(thecurr!))
            Call setda(1, thecurr!, ilasmax!)
            Call galilcmd("SB8", res$, ermsg$)
            laseron% = 1
        End If
    Case 1
    'tasto sinistro
        'Memorizzo ed esco
        Call resetoutput(0, d0.O_Rele_Work_Standby)
        thefreq! = 1000
        Call setfreqda(1, thefreq!)
        thecurr! = 7
        Call setda(1, thecurr!, ilasmax!)
        Call galilcmd("CB8", res$, ermsg$)
        laseron% = 0
        a& = GetCursorPos&(pt)
        LaserX& = pt.x
        LaserY& = pt.y
        Call movecross(LaserX&, LaserY&, RGB(255, 0, 0))
        FrmEuro.TimerCross.Enabled = False
        If flagdopsi% = 0 Then FrmEuro.Enabled = True
        Call saveini
        a& = SetCursorPos(oldx&, oldy&)
        Call showcursor
    End Select
End If
End Sub
Function encdec$(epwd$)
    For i% = 1 To Len(epwd$)
        edpwd$ = edpwd$ + Chr$(Asc(Mid$(epwd$, i%, 1)) Xor &HAA)
    Next i%
    encdec$ = edpwd$
End Function
Sub mu(Button)
If FrmEuro.TimerCross.Enabled = True Then
    Select Case Button
    Case 2
        'arresto laser
        Call resetoutput(0, d0.O_Rele_Work_Standby)
        thefreq! = 1000
        Call setfreqda(1, thefreq!)
        thecurr! = 7
        Call setda(1, thecurr!, ilasmax!)
        Call galilcmd("CB8", res$, ermsg$)
        laseron% = 0
        Call movecross(pt.x, pt.y, RGB(0, 255, 0))
    End Select
End If
End Sub
Sub offjog()
oldmsg$ = ""
msg$ = ""
Call showstatus(msg$)
jogging% = 0
If flagdopsi% = 0 Then FrmEuro.Enabled = True
FrmEuro.TimerJog.Enabled = False
FrmEuro.Picpos.Visible = False
Call movecross(LaserX&, LaserY&, RGB(255, 0, 0))
a& = SetCursorPos(oldx&, oldy&)
Call showcursor
End Sub
Sub loadstrings()
un% = FreeFile
Open thepath$ + "\strings." + lang$ For Input As un%
ll& = LOF(un%)
thestrings$ = Input$(ll&, un%)
Close #un%
End Sub
Sub loadini()
'carica i parametri di macchina in ordine sequenziale;
'se l'ultimo parametro non viene trovato segnala un errore
On Error GoTo errfil
    intCounter = 0          'Contatore per verificare possibili errori tramite timer TimeOut
    LaserX& = -1
    LaserY& = -1
    EditorX& = -1
    EditorY& = -1
    RefX& = 0
    RefY& = 0
    RefX1& = 0
    RefY1& = 0
    mctype% = 1
    downfile$ = "N.DMC"
    iodev$ = "PCL-722,PCL-818,X,X,X,X,X,X,X,X"
    stepxy! = 2400
    stepzw! = 2400
    stept! = 800
    mult& = 3000
    accmax$ = "1000000"
    accmin$ = "5000"
    speedmaxxy& = 10000
    speedmaxzw& = 10000
    speedkey% = 16
    pixelmm! = 110
    workdir$ = "\WORK"
    lastfile$ = "\"
    pwd$ = encdec("test")
    ver$ = "1.0 Benning"
    lang$ = "ITA"
    GapCameraX& = 0
    GapCameraY& = 0
    thecontrast& = 128
    thebrightness& = 128
    tableoutx$ = "94000"
    tableouty$ = "94000"
    kad% = 0
    Scanad% = 0
    a23% = 0
    a27% = 0
    flagpuntali% = 0
    fouraxes% = 0
    vacuum% = 0
    doubletable% = 0
    doublecamera% = 0
    steppixely! = 13.7
    steppixelx! = 13.7
    plc1% = 0
    sngTavolaCarico = 0                  'Posizione encoder in carico
    sngTavolaScarico = 16000             'Posizione encoder in scarico
    blnTavolaCarico = True               'Indica che inizialmente la posizione è in carico
    AddressAgilent = 5                   'Indirizzo dell'Agilent 6634B
    un% = FreeFile
    thefile$ = thepath$ + "laser.ini"
    Open thefile$ For Input As #un%
    While Not EOF(un%)
        Line Input #un%, cl$
        cl$ = Trim$(cl$)
        If Left$(cl$, 1) <> "'" And cl$ <> "" Then
            lc% = lc% + 1
            Select Case lc%
            Case 1
                'Coordinata X croce laser
                LaserX& = Val(cl$)
            Case 2
                'Coordinata Y croce laser
                LaserY& = Val(cl$)
            Case 3
                'Coordinata X cartella editor
                EditorX& = Val(cl$)
            Case 4
                'Coordinata Y cartella editor
                EditorY& = Val(cl$)
            Case 5
                'Coordinata X Reference point 1 di macchina laser
                RefX& = Val(cl$)
            Case 6
                'Coordinata Y Reference point 1 di macchina laser
                RefY& = Val(cl$)
            Case 7
                'Coordinata X Reference point 1 di macchina laser
                RefX1& = Val(cl$)
            Case 8
                'Coordinata Y Reference point 1 di macchina laser
                RefY1& = Val(cl$)
            Case 9
                'Coordinata X Reference point di macchina tavola
                RefZ& = Val(cl$)
            Case 10
                'Coordinata Y Reference point di macchina tavola
                RefW& = Val(cl$)
            Case 11
                'tipo motion controller
                mctype% = Val(cl$)
            Case 12
                'download file
                downfile$ = cl$
            Case 13
                'tipo I/O controller
                iodev$ = cl$
            Case 14
                'passi per mm asse X
                stepxy! = Val(cl$)
            Case 15
                'passi per mm assi X/Y
                stepzw! = Val(cl$)
            Case 16
                'passi per mm assi Z/W
                stept! = Val(cl$)
            Case 17
                'fattore di moltiplicazione jog mouse
                mult& = Val(cl$)
            Case 18
                'accelerazione massima
                accmax$ = cl$
            Case 19
                'accelerazione minima
                accmin$ = cl$
            Case 20
                'velocita' massima xy
                speedmaxxy& = Val(cl$)
            Case 21
                'velocita' massima xy
                speedmaxzw& = Val(cl$)
            Case 22
                'codice di controllo tasto X 2 nel Jog (16 Shift, 17 Ctrl)
                speedkey% = Val(cl$)
            Case 23
                'numero pixel per mm
                pixelmm! = Val(cl$)
            Case 24
                'directory file di lavoro
                workdir$ = cl$
            Case 25
                'nome dell'ultimo file aperto
                lastfile$ = cl$
            Case 26
                'password criptata
                pwd$ = cl$
            Case 27
                'versione corrente
                ver$ = cl$
            Case 28
                'linguaggio
                lang$ = cl$
            Case 29
                'offset telecamere X
                GapCameraX& = Val(cl$)
            Case 30
                'offset telecamere Y
                GapCameraY& = Val(cl$)
            Case 31
                'contrasto display
                thecontrast& = Val(cl$)
            Case 32
                'luminosita'display
                thebrightness& = Val(cl$)
            Case 33
                'posizione tavola fuori x
                tableoutx$ = cl$
            Case 34
                'posizione tavola fuori y
                tableouty$ = cl$
            Case 35
                'indirizzo GPIB Source Meter Keithley
                'se =0 non c'e' il source meter
                kad% = Val(cl$)
            Case 36
                'indirizzo GPIB Scanner Keithley
                'se =0 non c'e' lo scanner
                Scanad% = Val(cl$)
            Case 37
                'indirizzo GPIB 2700
                'se =0 non c'e'
                a27% = Val(cl$)
            Case 38
                'indirizzo GPIB 230
                'se =0 non c'e'
                a23% = Val(cl$)
            Case 39
                'flag presenza puntali
                flagpuntali% = Val(cl$)
            Case 40
                ilasmax! = Val(cl$)
            Case 41
                'se =1 4 assi galil, altrimenti 2
                fouraxes% = Val(cl$)
            Case 42
                'se =1 c'e' il vuoto tavola, altrimenti no
                vacuum% = Val(cl$)
            Case 43
                'se =1 c'e' la doppia tavola con PLC
                doubletable% = Val(cl$)
            Case 44
                'se =1 c'e' la doppia telecamera
                doublecamera% = Val(cl$)
            Case 45
                'step per pixel x
                steppixelx! = Val(cl$)
            Case 46
                'step per pixel y
                steppixely! = Val(cl$)
            Case 47
                plc1% = Val(cl$)
                here% = 1
            Case 48
                'valore dell'encoder corrispondente alla posizione di carico
                sngTavolaCarico = Val(cl$)
            Case 49
                'valore dell'encoder corrispondente alla posizione di scarico
                sngTavolaScarico = Val(cl$)
            Case 50
                'Indirizzo dell'Agilent
                AddressAgilent = Val(cl$)
            End Select
        End If
    Wend
    Close #un%
    Call loadstrings
    Select Case here%
    Case 0
        Call updatelog(mss$(113), 1)
build:
        Call saveini
        Call loadini
    Case 1
        Call updatelog(mss$(114), 0)
    End Select
    If encdec(pwd$) = Chr$(0) Then oplevel% = 1
    Exit Sub
errfil:
Call updatelog(mss$(115) + Error$, 1)
Resume build
End Sub
Sub saveini()
'On Error GoTo errsave
    thefile$ = thepath$ + "laser.ini"
    thefile1$ = thepath$ + "laser.bak"
    un% = FreeFile
    Open thefile1$ For Output As #un%
    Close #un%
    Kill thefile1$
    Name thefile$ As thefile1$
    Open thefile1$ For Input As #un%
    un1% = FreeFile
    Open thefile$ For Output As #un1%
    While lc% < 47
        If ended% = 0 Then
            Line Input #un%, cl$
            If EOF(un%) Then
                 ended% = 1
            End If
        End If
        cl$ = Trim$(cl$)
        If ended% = 1 Then cl$ = "A"
        If Left$(cl$, 1) <> "'" And cl$ <> "" Then
            lc% = lc% + 1
            Select Case lc%
            Case 1
                'Coordinata X croce laser
                Print #un1%, LaserX&
            Case 2
                'Coordinata Y croce laser
                Print #un1%, LaserY&
            Case 3
                'Coordinata X cartella editor
                Print #un1%, EditorX&
            Case 4
                'Coordinata Y cartella editor
                Print #un1%, EditorY&
            Case 5
                'Coordinata X Reference point di macchina laser
                Print #un1%, RefX&
            Case 6
                'Coordinata Y Reference point di macchina laser
                Print #un1%, RefY&
            Case 7
                'Coordinata X Reference point di macchina laser
                Print #un1%, RefX1&
            Case 8
                'Coordinata Y Reference point di macchina laser
                Print #un1%, RefY1&
            Case 9
                'Coordinata Z Reference point di macchina tavola
                Print #un1%, RefZ&
            Case 10
                'Coordinata W Reference point di macchina tavola
                Print #un1%, RefW&
            Case 11
                'tipo motion controller
                Print #un1%, mctype%
            Case 12
                'download file
                Print #un1%, downfile$
            Case 13
                'tipo I/O controller
                Print #un1%, iodev$
            Case 14
                'passi per mm assi X/Y
                Print #un1%, stepxy!
            Case 15
                'passi per mm assi Z/W
                Print #un1%, stepzw!
            Case 16
                'passi per mm asse focale
                Print #un1%, stept!
            Case 17
                'fattore di moltiplicazione jog mouse
                Print #un1%, mult&
            Case 18
                'accelerazione massima
                Print #un1%, accmax$
            Case 19
                'accelerazione minima
                Print #un1%, accmin$
            Case 20
                'velocita' massima
                Print #un1%, speedmaxxy&
            Case 21
                'velocita' massima
                Print #un1%, speedmaxzw&
            Case 22
                'codice di controllo tasto X 2 nel Jog (16 Shift, 17 Ctrl)
                Print #un1%, speedkey%
            Case 23
                'numero pixel per mm
                Print #un1%, pixelmm!
            Case 24
                'directory salvataggio file di lavoro
                Print #un1%, workdir$
            Case 25
                'ultimo file di lavoro aperto
                Print #un1%, lastfile$
            Case 26
                'password criptata
                Print #un1%, pwd$
            Case 27
                'versione attuale
                Print #un1%, ver$
            Case 28
                Print #un1%, lang$
            Case 29
                Print #un1%, GapCameraX&
            Case 30
                Print #un1%, GapCameraY&
            Case 31
                Print #un1%, thecontrast&
            Case 32
                Print #un1%, thebrightness&
            Case 33
                Print #un1%, tableoutx$
            Case 34
                Print #un1%, tableouty$
            Case 35
                Print #un1%, kad%
            Case 36
                Print #un1%, Scanad%
            Case 37
                Print #un1%, a27%
            Case 38
                Print #un1%, a23%
            Case 39
                Print #un1%, flagpuntali%
            Case 40
                Print #un1%, ilasmax!
            Case 41
                Print #un1%, fouraxes%
            Case 42
                Print #un1%, vacuum%
            Case 43
                Print #un1%, doubletable%
            Case 44
                Print #un1%, doublecamera%
            Case 45
                Print #un1%, steppixelx!
            Case 46
                Print #un1%, steppixely!
            Case 47
                Print #un1%, plc1%
            End Select
        Else
            Print #un1%, cl$
        End If
    Wend
    Close #un%
    Close #un1%
Exit Sub
errsave:
ended% = 1
Resume Next
End Sub
Function formatter$(fval#, ni%, nf%)
'formatta una stringa con formato ii.ff
'dove ii sono gli interi ff i frazionari
'ni% e' il numero di interi, nf% e' il numero di frazionari
'il separatore (se necessario) e' il punto
fstr$ = String$(ni%, "#") + "." + String$(nf%, "#")
tval$ = Format(fval#, fstr$)
c% = InStr(tval$, ",")
If c% > 0 Then Mid$(tval$, c%, 1) = "."
If Right$(tval$, 1) = "." Then tval$ = Left$(tval$, Len(tval$) - 1)
If Left$(tval$, 1) = "." Or tval$ = "" Then tval$ = "0" + tval$
formatter$ = tval$
End Function
Function step2mm#(nsteps&, thestep!)
    'converte i passi in mm
    step2mm# = nsteps& / thestep!
End Function
Function mm2step#(themm#, thestep!)
    'converte i mm in passi
    mm2step# = themm# * thestep!
End Function
Sub updateposxy()
    Call getposxy(xxx$, yyy$)
    With FrmEuro
        If dispstep% = 0 Then
            .lblposx = "X:" + formatter$(step2mm#(Val(xxx$), stepxy!), 3, 2)
            .Lblposy = "Y:" + formatter$(step2mm#(Val(yyy$), stepxy!), 3, 2)
        Else
            .lblposx = Trim$(Str(Val(xxx$)))
            .Lblposy = Trim$(Str(Val(yyy$)))
        End If
        If .Picpos.Visible = False Then
            .Picpos.Visible = True
            .Picpos.ZOrder 0
        End If
    End With
End Sub
Sub updateposzw()
    Call getposzw(xxx$, yyy$)
    With FrmEuro
        If dispstep% = 0 Then
            .lblposx = "Z:" + formatter$(step2mm#(Val(xxx$), stepzw!), 3, 2)
            .Lblposy = "W:" + formatter$(step2mm#(Val(yyy$), stepzw!), 3, 2)
        Else
            .lblposx = Trim$(Str(Val(xxx$)))
            .Lblposy = Trim$(Str(Val(yyy$)))
        End If
        If .Picpos.Visible = False Then
            .Picpos.Visible = True
            .Picpos.ZOrder 0
        End If
    End With

End Sub
Sub updateposz()
    Call getposzw(xxx$, yyy$)
    With FrmEuro
        If dispstep% = 0 Then
            .lblposx = "Z:" + formatter$(step2mm#(Val(xxx$), stepzw!), 3, 2)
        Else
            .lblposx = Trim$(Str(Val(xxx$)))
        End If
        If .Picpos.Visible = False Then
            .Picpos.Visible = True
            .Picpos.ZOrder 0
        End If
    End With
End Sub
Sub getposxy(xxx$, yyy$)
   Select Case mctype%
    Case 1
        Call galilcmd("TP XY", res$, ermsg$)
        cl% = InStr(res$, ",")
        xxx$ = ""
        yyy$ = ""
        If cl% > 0 Then
            xxx$ = Trim$(Left$(res$, cl% - 1))
            yyy$ = Trim$(Mid$(res$, cl% + 1))
        End If
    End Select
End Sub
Sub getposzw(xxx$, yyy$)
   Select Case mctype%
    Case 1
        Call galilcmd("TP ZW", res$, ermsg$)
        cl% = InStr(res$, ",")
        xxx$ = ""
        yyy$ = ""
        If cl% > 0 Then
            xxx$ = Trim$(Left$(res$, cl% - 1))
            yyy$ = Trim$(Mid$(res$, cl% + 1))
        End If
    End Select
End Sub
Sub initdisplay()
'inizializza le dimensioni del display in modod che venga contenuto dalla cornice esterna
'e che l'area visualizzata sia SizeX% x SizeY%
 
    With FrmEuro
        .SSPanel1.Left = 0
        .SSPanel1.Width = ((Xsize% - 3) + 2 * .SSPanel1.BevelWidth) * Screen.TwipsPerPixelX
        .SSPanel1.Height = (Ysize% + 2 * .SSPanel1.BevelWidth) * Screen.TwipsPerPixelY
        .SSPanel1.Top = .ScaleHeight - .SSPanel1.Height
        .Display.Width = (Xsize% - 3) * Screen.TwipsPerPixelX
        .Display.Height = Ysize% * Screen.TwipsPerPixelY
        .Picture1.Width = .Display.Width
        .Picture1.Height = .Display.Height
        .Picture1.Top = .SSPanel1.Top + .SSPanel1.BevelWidth * Screen.TwipsPerPixelY
        .Picture1.Left = .SSPanel1.BevelWidth * Screen.TwipsPerPixelX
        '.Display.Top = .SSPanel1.Top + .SSPanel1.BevelWidth * Screen.TwipsPerPixelY
        '.Display.Left = .SSPanel1.BevelWidth * Screen.TwipsPerPixelX
        .Display.Top = 0
        .Display.Left = 0
        Call switchcamera(0, 1)
        .SSPanel1.Visible = True
        .Display.Visible = True
        .Picture1.ZOrder 0
        .Piclogo.Left = .SSPanel1.Width + (.ScaleWidth - .SSPanel1.Width - .Piclogo.Width) / 2
        .Piclogo.Top = 200 + .Toolbar1.Height
        .Piclogo.Visible = True
        .Framstat.Top = .SSPanel1.Top - 50
        .Framstat.Left = .SSPanel1.Width + 50
        .Framstat.Visible = True
        If LaserX& < 0 Then
            LaserX& = (.SSPanel1.Width / 2) / Screen.TwipsPerPixelX
        End If
        If LaserY& < 0 Then
            LaserY& = (Screen.Height - .SSPanel1.Height / 2) / Screen.TwipsPerPixelY
        End If
        Call movecross(LaserX&, LaserY&, RGB(255, 0, 0))
        FrmEuro.Refresh
    End With
End Sub
Sub checkstatus()
    With FrmEuro
        If d0.O_System_On = 1 Then
            If .Imgmacon.Visible = False Then
                  .Imgmacon.Visible = True
                  .Imgmacoff.Visible = False
            End If
        Else
            If .Imgmacoff.Visible = False Then
                  .Imgmacoff.Visible = True
                  .Imgmacon.Visible = False
            End If
        End If
        If d0.O_Rele_Comm_Pompa_Ref = 1 Then
            If .Imgpumpon.Visible = False Then
                  .Imgpumpon.Visible = True
                  .Imgpumpoff.Visible = False
            End If
        Else
            If .Imgpumpoff.Visible = False Then
                  .Imgpumpoff.Visible = True
                  .Imgpumpon.Visible = False
            End If
        End If
        If d0.I_Contaore_Laser_On = 1 Then
            If .Toolbar1.Buttons.Item(8).value = tbrUnpressed Then .Toolbar1.Buttons.Item(8).value = tbrPressed
            If .Imglampon.Visible = False Then
                  .Imglampon.Visible = True
                  .Imglampoff.Visible = False
            End If
        Else
            If .Toolbar1.Buttons.Item(8).value = tbrPressed Then .Toolbar1.Buttons.Item(8).value = tbrUnpressed
            If .Imglampoff.Visible = False Then
                  .Imglampoff.Visible = True
                  .Imglampon.Visible = False
            End If
        End If
        If d0.O_RF_On_12V = 1 Then
            If .ImgRFon.Visible = False Then
                  .ImgRFon.Visible = True
                  .ImgRFoff.Visible = False
            End If
        Else
            If .ImgRFoff.Visible = False Then
                  .ImgRFoff.Visible = True
                  .ImgRFon.Visible = False
            End If
        End If
        If d0.O_Lamp_On = 1 Then
            If .Lblfreq.Caption <> lastfreq$ Then .Lblfreq.Caption = lastfreq$
            If .Lblcurr.Caption <> lastcurr$ Then .Lblcurr.Caption = lastcurr$
        Else
            If .Lblfreq.Caption <> "0" Then .Lblfreq.Caption = "0"
            If .Lblcurr.Caption <> "0" Then .Lblcurr.Caption = "0"
        End If
        'If d0.O_Rele_Vuoto_Tav_A = 1 Then
            'If .Toolbar1.Buttons.Item(9).value = tbrUnpressed Then .Toolbar1.Buttons.Item(9).value = tbrPressed
        'Else
            'If .Toolbar1.Buttons.Item(9).value = tbrPressed Then .Toolbar1.Buttons.Item(9).value = tbrUnpressed
        'End If
    End With
End Sub
Sub grabber(gr%)
With FrmEuro
On Error GoTo errgrab
Select Case gr%
Case 1
If isgrabbing% = 0 Then
    .Digitizer.Grab
    .Digitizer.GrabContinuous
    isgrabbing% = 1
End If
Case 0
If isgrabbing% = 1 Then
    .Digitizer.Grab
    .Digitizer.Halt
    isgrabbing% = 0
End If
End Select
End With
Exit Sub
errgrab:
Call updatelog(mss$(116), 1)
Exit Sub
End Sub
Sub edgex(white2black%, startx%, endx%, starty%, endy%, thestep%)
'trova il bordo lungo l'asse x
'white2black%=1 : transizione da chiaro a scuro,=0 viceversa
'thestep% da' il passo di ricerca punti
thinstep% = 1
If isgrabbing% = 1 Then
    isgrabbing% = 0
    FrmEuro.Digitizer.Halt
End If
FrmEuro.Buffer.Get BufPixel()
Erase Pmat()
Delta% = 4
numpoints% = (endx% - startx%) / thestep%
For x% = startx% To endx% Step thestep%
    lastwhite% = -1
    bl% = 0
    wh% = 0
    theder% = 40
    If white2black% = 1 Then theder% = -40
    they% = -1
    omavg% = -1
    For y% = starty% To endy% Step Delta%
            mavg% = 0
            For k% = 0 To Delta% - 1
                mavg% = mavg% + BufPixel(x%, y% + k%)
            Next k%
            If omavg% >= 0 Then
                der% = mavg% - omavg%
                If white2black% = 1 Then
                    If der% < theder% Then
                        theder% = der%
                        they% = y%
                    End If
                Else
                    If der% > theder% Then
                        theder% = der%
                        they% = y%
                    End If
                End If
        End If
        omavg% = mavg%
    Next y%
    If they% >= 0 Then
            dl% = they% - Delta%
            ul% = they% + Delta%
            If dl% < 2 Then dl% = 2
            If ul% > Ysize% Then ul% = Ysize%
            thedif% = 0
            For k% = dl% To ul%
                pix1% = BufPixel(x%, k%)
                pix2% = BufPixel(x%, k% - 1)
                dif% = pix1% - pix2%
                If white2black% = 1 Then
                    If dif% < thedif% Then
                        thedif% = dif%
                        they% = k%
                    End If
                Else
                    If dif% > thedif% Then
                        thedif% = dif%
                        they% = k%
                    End If
                End If
            Next k%
            cc% = cc% + 1
            Pmat(cc%, 1) = x%
            Pmat(cc%, 2) = they%
    End If
Next x%
cc% = cc% + 1
Pmat(cc%, 1) = 0
Pmat(cc%, 2) = 0
End Sub
Sub switchcamera(cn%, gr%)
If doublecamera% = 0 Then cn% = 0
With FrmEuro
Select Case cn%
Case -1
    If .Digitizer.Channel = mCh0 Then
        .Digitizer.Channel = mCh1
        .Toolbar1.Buttons.Item(10).value = tbrPressed
        cg% = 1
    Else
        .Digitizer.Channel = mCh0
        .Toolbar1.Buttons.Item(10).value = tbrUnpressed
        cg% = 1
    End If
Case 0
    If .Digitizer.Channel = mCh1 Then
        .Digitizer.Channel = mCh0
        cg% = 1
    End If
Case 1
    If .Digitizer.Channel = mCh0 Then
        .Digitizer.Channel = mCh1
        cg% = 1
    End If
End Select
If cg% = 1 Then
    'se cambio un canale forzo il grab per controllo video input
    If gr% = 1 Then isgrabbing% = 0
    If gr% = 0 Then isgrabbing% = 1
End If
Call grabber(gr%)
End With
End Sub
Sub updatelog(ms$, warn%)
   If debugging% = 1 Then
        Call updatedebug(ms$)
   End If

sh% = 0
If warn% = 2 Then
    'status
    warn% = 0
    sh% = 1
End If
With FrmEuro
Select Case warn%
Case 0
    .TxtLog.SelColor = RGB(0, 0, 0)
Case 1
    .TxtLog.SelColor = RGB(255, 0, 0)
    sh% = 1
End Select
If Len(.TxtLog.Text) > 30000 Then .TxtLog = ""
If sh% = 1 Then
    'Call showlog
End If
.TxtLog.SelStart = 65535
.TxtLog.SelText = " " + Date$ + ">" + Time$ + ">" + ms$ + Chr$(13) + Chr$(10)
.TxtLog.SelStart = 65535
End With
End Sub
Sub updateterminal(ms$)
If Len(Frmterminal.Txtrx.Text) > 30000 Then Frmterminal.Txtrx.Text = ""
Frmterminal.Txtrx.SelStart = 65535
Frmterminal.Txtrx.SelText = ms$ + Chr$(13) + Chr$(10)
Frmterminal.Txtrx.SelStart = 65535
End Sub
Sub showlog()
'visualizza la finestra di log se non e' gia' visibile
With FrmEuro
    If .Toolbar1.Buttons.Item(12).value = tbrUnpressed Then .Toolbar1.Buttons.Item(12).value = tbrPressed
    If .TxtLog.Visible = False Then
        .TxtLog.Top = .Toolbar1.Height
        .TxtLog.Left = 0
        .TxtLog.Height = .SSPanel1.Top - .TxtLog.Top
        .TxtLog.Width = .SSPanel1.Width
        .TxtLog.ZOrder 0
        .TxtLog.Visible = True
        .TxtLog.SelStart = 65535
    End If
End With
End Sub
Sub hidelog()
With FrmEuro
    If .Toolbar1.Buttons.Item(12).value = tbrPressed Then .Toolbar1.Buttons.Item(12).value = tbrUnpressed
    If .TxtLog.Visible = True Then
        .TxtLog.Visible = False
    End If
End With
End Sub
Sub drawline(axis%, m#, b#)
'traccia la retta 'best fit' trovata
'disegna i punti buoni in bianco e i punti scartati in nero
If axis% = 1 Then
    'asse X
    For i% = 1 To Xsize%
        ty# = m# * i% + b#
        If ty# > 1 And ty# < Ysize% Then
            y% = Int(ty#)
            BufPixel(i%, y%) = 0
        End If
    Next i%
    For i% = 1 To 1000
        Select Case Pmat(i%, 1)
        Case Is > 0
            BufPixel(Pmat(i%, 1), Pmat(i%, 2)) = 255
        Case Is < 0
            BufPixel(Abs(Pmat(i%, 1)), Pmat(i%, 2)) = 0
        Case Is = 0
            Exit For
        End Select
    Next i%
    FrmEuro.Buffer.Put BufPixel()
Else
    'asse Y
    For i% = 1 To Ysize%
        tx# = m# * i% + b#
        If tx# > 1 And tx# < Xsize% Then
            x% = Int(tx#)
            BufPixel(x%, i%) = 0
        End If
    Next i%
    For i% = 1 To 1000
        Select Case Pmat(i%, 1)
        Case Is > 0
            BufPixel(Pmat(i%, 1), Pmat(i%, 2)) = 255
        Case Is < 0
            BufPixel(Abs(Pmat(i%, 1)), Pmat(i%, 2)) = 0
        Case Is = 0
            Exit For
        End Select
    Next i%
    FrmEuro.Buffer.Put BufPixel()
End If

End Sub
Sub edgey(white2black%, startx%, endx%, starty%, endy%, thestep%)
'trova il bordo lungo l'asse y
'white2black%=1 : transizione da chiaro a scuro,=0 viceversa
'thestep% da' il passo di ricerca punti
thinstep% = 1
If isgrabbing% = 1 Then
    isgrabbing% = 0
    FrmEuro.Digitizer.Halt
End If
FrmEuro.Buffer.Get BufPixel()
Erase Pmat()
Delta% = 4
numpoints% = (endy% - starty%) / thestep%
For y% = starty% To endy% Step thestep%
    lastwhite% = -1
    bl% = 0
    wh% = 0
    theder% = 40
    If white2black% = 1 Then theder% = -40
    thex% = -1
    omavg% = -1
    For x% = startx% To endx% Step Delta%
            mavg% = 0
            For k% = 0 To Delta% - 1
                mavg% = mavg% + BufPixel(x% + k%, y%)
            Next k%
            If omavg% >= 0 Then
                der% = mavg% - omavg%
                If white2black% = 1 Then
                    If der% < theder% Then
                        theder% = der%
                        thex% = x%
                    End If
                Else
                    If der% > theder% Then
                        theder% = der%
                        thex% = x%
                    End If
                End If
        End If
        omavg% = mavg%
    Next x%
    If thex% >= 0 Then
            dl% = thex% - Delta%
            ul% = thex% + Delta%
            If dl% < 2 Then dl% = 2
            If ul% > Xsize% Then ul% = Xsize%
            thedif% = 0
            For k% = dl% To ul%
                pix1% = BufPixel(k%, y%)
                pix2% = BufPixel(k% - 1, y%)
                dif% = pix1% - pix2%
                If white2black% = 1 Then
                    If dif% < thedif% Then
                        thedif% = dif%
                        thex% = k%
                    End If
                Else
                    If dif% > thedif% Then
                        thedif% = dif%
                        thex% = k%
                    End If
                End If
            Next k%
            cc% = cc% + 1
            Pmat(cc%, 1) = thex%
            Pmat(cc%, 2) = y%
    End If
Next y%

cc% = cc% + 1
Pmat(cc%, 1) = 0
Pmat(cc%, 2) = 0

End Sub
Sub liner(m#, b#, mode%)
'estrae da pmat le coppie di punti nell'ordine determinato da mode%
'se mode%=0: pmat(n,1) -> X, pmat(n,2) -> Y
'se mode%=1: pmat(n,1) -> Y, pmat(n,2) -> X
'se la prima coordinata e' negativa la coppia viene scartata (il ns. sistema di riferimento lavora per definizione a quadrante positivo)
'restituisce i coefficienti m# (angolare) e b# della retta approssimante
'l'approssimazione si intende "ottima" rispetto alla coordinata  prescelta come X
'occorre che volta per volta l'asse X di riferimento sia quello piu' "parallelo" alla retta cercata
'questo viene stabilito con mode% se =0 cerco una retta orizzontale sullo schermo, se =1 verticale
'trovata la retta scarta il punto con errore massimo
'il ciclo si ripete iterativamente fino a quando l'errore massimo e' inferiore a 3 pixel
'se alla fine ho scartato un numero di punti superiore alla meta' dei punti teorici da' "not found"
indexX% = 1
indexY% = 2
If mode% = 1 Then
    indexX% = 2
    indexY% = 1
End If
Do
    cc% = 0
    m# = 0
    b# = 0
    xmean# = 0
    ymean# = 0
    sumx# = 0
    sumy# = 0
    sumxy# = 0
    sumx2# = 0
    errmax# = 0
    kerr% = 0
    For k% = 1 To UBound(Pmat)
        If Pmat(k%, 1) > 0 Then
            cc% = cc% + 1
            xx# = Pmat(k%, indexX%)
            yy# = Pmat(k%, indexY%)
            sumx# = sumx# + xx#
            sumy# = sumy# + yy#
            sumxy# = sumxy# + (xx# * yy#)
            sumx2# = sumx2# + (xx# * xx#)
            sumy2# = sumy2# + (yy# * yy#)
        End If
    Next k%
    If cc% = 0 Then
        m# = 0
        b# = 0
        msg$ = mss$(145)
        If mode% = 1 Then msg$ = mss$(146)
        MsgBox (msg$)
        Exit Sub
    End If
    xmean# = sumx# / cc%
    ymean# = sumy# / cc%
    upper# = (cc% * sumxy#) - (sumx# * sumy#)
    under# = (cc% * sumx2#) - (sumx# * sumx#)
    upper1# = (sumy# * sumx2#) - (sumx# * sumxy#)
    under1# = (cc% * sumx2#) - (sumx# * sumx#)
    m# = upper# / under#
    b# = upper1# / under1#
    cc% = 0
    errmax# = 0
    kerr% = 0
    For k% = 1 To UBound(Pmat)
        If Pmat(k%, 1) > 0 Then
            cc% = cc% + 1
            erri# = Pmat(k%, indexY%) - (m# * Pmat(k%, indexX%)) - b#
            If Abs(erri#) > errmax# Then
                kerr% = k%
                xerr% = Pmat(k%, 1)
                yerr% = Pmat(k%, 2)
                errmax# = Abs(erri#)
            End If
        End If
    Next k%
    If errmax# > 1 Then
        dcc% = dcc% + 1
        Pmat(kerr%, 1) = -xerr%
        Pmat(kerr%, 2) = yerr%
    End If
Loop While errmax# > 2
If cc% < (numpoints% / 2) Then
    'Pmat(1, 1) = 0
    m# = 0
    b# = 0
    msg$ = mss$(145)
    If mode% = 1 Then msg$ = mss$(146)
    MsgBox (msg$)
End If
End Sub

Sub movecross(CenterX&, CenterY&, Crosscolor&)
With FrmEuro
    If .PictureX.BackColor <> Crosscolor& Then .PictureX.BackColor = Crosscolor&
    If .PictureY.BackColor <> Crosscolor& Then .PictureY.BackColor = Crosscolor&
    If .PictureX.Visible = False Then .PictureX.Visible = True
    If .PictureY.Visible = False Then .PictureY.Visible = True
    XL& = (CenterX& * Screen.TwipsPerPixelX - (.PictureX.Width - .PictureY.Width) / 2) - (.SSPanel1.BevelWidth * Screen.TwipsPerPixelX)
    XT& = (CenterY& * Screen.TwipsPerPixelY) - (Screen.Height - .SSPanel1.Height + (.SSPanel1.BevelWidth * Screen.TwipsPerPixelY))
    YL& = XL& + (.PictureX.Width - .PictureY.Width) / 2
    YT& = XT& - (.PictureY.Height - .PictureX.Height) / 2
    mv% = 0
    If .PictureY.Left <> YL& Then
        mv% = 1
        .PictureY.Left = YL&
    End If
    If .PictureY.Top <> YT& Then
        mv% = 1
        .PictureY.Top = YT&
    End If
    If .PictureX.Left <> XL& Then
        mv% = 1
        .PictureX.Left = XL&
    End If
    If .PictureX.Top <> XT& Then
        mv% = 1
        .PictureX.Top = XT&
    End If
    If mv% = 1 Then
        .PictureX.Refresh
        .PictureY.Refresh
    End If
End With
End Sub
Sub hidecursor()
    Screen.MouseIcon = FrmEuro.MouseIcon
    Screen.MousePointer = 99
End Sub
Sub showcursor()
    Screen.MousePointer = 0
End Sub
