/*====================================================================*/
/* Tool management variables and macros                               */
/*====================================================================*/
/* Tool class definition                                              */
/*--------------------------------------------------------------------*/
CTool = ObjDef T_classDscr               /* Tool class =              */
"Crc"   T_short  0                       /* radius compensation       */
"EMU"   T_short  0                       /* index of to real tool     */
"Ident" T_short  0                       /* Tool identifier           */
"Ofs"   T_double _drvnMax                /* one offset for each axis  */
"Rad"   T_double 0                       /* tool radius               */
"Len"   T_double 0                       /* tool length               */ 
"Speed" T_double 0                       /* tool speed                */
"Rpm"   T_Long   0                       /* rotations per minute      */ 
"Out"   T_short  0                       /* not used (output number)  */
"BTC"   T_object 0                       /* before tool change macro  */
"ATC"   T_object 0                       /* after tool change macro   */
"DXF"   T_object 0                       /* DXF processing macro      */
"Flags" T_short  0                       /* flags for tool shape      */
"File"  T_object 0                       /* file name for tool shape  */
"Text"  T_object 0                       /* tool description          */           
"Color" T_Long   0;                      /* tool color                */

Tools = ObjDef CTool 1;                  /* 1 default instance        */

Tools[0].Crc     = 0;                    /* Initialising zero tool    */  
Tools[0].EMU     = 0;
Tools[0].Ident   = 0;
Tools[0].Ofs     = Array _drvnMax 0.0;
Tools[0].Rad     = 0.0;
Tools[0].Len     = 0.0;
Tools[0].Speed   = 0.0;
Tools[0].Rpm     = 0L;
Tools[0].Out     = 0;
Tools[0].Flags   = 0;
(*Tools[0].BTC)  = "Default"; 
(*Tools[0].ATC)  = "Default";
(*Tools[0].DXF)  = "Default"; 
(*Tools[0].File) = "Default"; 
(*Tools[0].Text) = "Not Used";
Tools[0].Color   = 0L;

/*--------------------------------------------------------------------*/
/* Tool management variables                                          */
/*--------------------------------------------------------------------*/
_ToolAuto      = 0;                      /* no tool change as default */
_RpmFromTool   = 0;                      /* Rpm from scrollbar        */ 
_SpeedFromTool = 0;                      /* MF  from _ToolSpeedF      */
_ToolPrbState  = 0;                      /* tool probe not ready      */
_ExecToPark    = 0;                      /* stand still after exec    */ 
_TchToHome     = 1;                      /* To Home after ToolChange  */ 

_ToolMode      = 0L;        /* Bit masks for tool management:         */
                            /* 0: normal (default)                    */
                            /* 1: check Ident-No. and use the tool it */
                            /*    points to instead. Allows emulating */
                            /*    a bigger Radius for drilling        */
                            /* 2: search tool with matching Ident-No. */

_ToolWidthVar  = 0;         /* Tool width is variable (>0)            */
_MM2Pix        = 1.0;       /* conversion from mm to pixel            */ 

_ToolN       = 0;           /* number of loaded tools                 */

_ToolNc      = 0;           /* real current tool in the machine       */
_ToolNcEmu   = 0;           /* emulated current tool                  */

_ToolSel     = 0;           /* selected tool during graphic display   */
_ToolSelEmu  = 0;           /* or requested prior to changing         */

_ToolSpeedF = 20.0;                       /* Werkzeugwechsel anfahren */ 	
_ToolSpeedS = 10.0;                       /* Werkzeug ablegen/holen   */

_ToolProbeF = 2.0;                        /* Taster anfahren          */  
_ToolProbeS = 0.5;                        /* Taster Feinmessung       */ 

_ToolFileAsked  = "no file asked";                /* init value       */
_ToolFileLoaded = "no file loaded";               /* init value       */

_GTA = 0;                                  /* tool change in progress */ 

/* ================================================================== */
/* Data for  tool changing                                            */ 
/* ================================================================== */
CToolChange = ObjDef T_classDscr
"OldSpeedF"    T_double  0              /* speed values to restore    */
"OldSpeedS"    T_double  0 
"TongSwitch"   T_Short   0              /* with tongswitch message    */
"AllowT0"      T_Short   0              /* allow tool 0               */
"doBefore"     T_object  0              /* do before changing         */
"doAfter"      T_object  0              /* do after  changing         */

"Prolog"       T_object  0              /* current point to ToolHome  */
"Epilog"       T_object  0              /* change  point to ToolHome  */
"LimitsOff"    T_object  0              /* suspend limit watching     */
"LimitsOn"     T_object  0              /* restore limit watching     */
"ManChange"    T_object  0              /* manual tool change         */
"DropFetch"    T_object  0              /* move to pickpos; drop/fetch*/
"ReadSwitch"   T_object  0              /* get tool length            */
"GotoPos"      T_object  0              /* move to posintion %1       */
"SaveResult"   T_object  0              /* save new tool to file etc. */
"SwitchState"  T_Short   0              /* Expected status of switch  */
;

_tlch = ObjDef CToolChange;             /* create CToolChange object  */

_tlch.TongSwitch  =  0;                 /* without tongswitch message */
_tlch.SwitchState = -1;                 /* unknown                    */
_tlch.AllowT0     =  0;                 /* Tool 0 not allowed         */

_tlch.doBefore    = &("");
_tlch.doAfter     = &("");

/* ------------------------------------------------------------------ */
_tlch.Prolog = &(                       /* current point to tool home */
/* ------------------------------------------------------------------ */
"if(_IndMc2Oc) {Wait 0; mReset \"Unzulässiger Aufruf von Prolog\";}
 
 wait 0; _PrgStop; _dspUpdate;
 OldPos = GetOc;
 
 print GetIniTxt \"GetTool\" \"Prn000\";  /* start toolchange         */
 
 if(_ToolAuto == 3)
   {MCall *_MGoto.Pos McPos[3].Ofs 1;}    /* move to tool home        */
 else
   {MCall *_MGoto.Pos McPos[1].Ofs 1;}    /* move to service position */

 mf_f = _ToolSpeedF;                    /* set toolchange speed       */
 ml_f = _ToolSpeedS; MvPar;             /* restore in calling program */
");

/* ------------------------------------------------------------------ */
_tlch.ManChange = &(                    /* manual tool change         */
/* ------------------------------------------------------------------ */
"if(_tlch.TongSwitch > 0)
 {                                      /* show open message          */
   MsgBox (GetIniTxt \"GetTool\" \"Msg000\") 
          (GetIniTxt \"GetTool\" \"Msg002\");
 
   _ToolOpen;
 }
                                        /* ask for tool to replace    */
 local \"MsgText\";
 MsgText = sprint (GetIniTxt \"GetTool\" \"Msg001\") _toolSel;

 MsgBox (MsgText & \"\\n\\n\" & *Tools[_toolsel].Text)
        (GetIniTxt \"GetTool\" \"Msg002\");

 _ToolClose;                            /* close tong switch          */    
");

/* ------------------------------------------------------------------ */
_tlch.DropFetch = &(                    /* drop or fetch tool         */
/* ------------------------------------------------------------------ */
"if(_IndMc2Oc) {Wait 0; mReset \"Unzulässiger Aufruf von DropFetch\";}

 local \"CallOnExit\" \"CallOnError\";     /* variables to restore    */
 CallOnExit = sprint \"Wait 0; MtransFlag01 = '%c'; mreset;\" MtransFlag01;
 CallOnError = CallOnExit; 

 Wait 0; MtransFlag01 = '0'; mreset;       /* disable MTrans          */

 if(_OcNext[2] < ToolZup1)                 /* move up                 */
  {_OcNext[2] = mcall *_Mgoto.GetZMax ToolZup1; MF;} 

 _OcNext[0] = PickPos[%1].Ofs[0];
 _OcNext[1] = PickPos[%1].Ofs[1]; MF;      /* approach XY             */

 if(%2 == 0) /* drop */
 {
   Tools[_ToolNC].Ofs[2] = 0.0; SetMc2Oc 0;            /* kill offset */
   print GetIniTxt \"GetTool\" \"Prn002\";

   _OcNext[2] = PickPos[%1].Ofs[2]; ML; wait 0;        /* move down   */
   _ToolOpen; wait 0.5;                                /* drop        */ 
 }

 if(%2 == 1) /* fetch */
 {
   print GetIniTxt \"GetTool\" \"Prn004\";
   wait 0; _ToolOpen;                                  /* open tong   */
 
   _OcNext[2] = PickPos[%1].Ofs[2]; ML; wait 0;        /* move down   */
   _ToolClose; wait 0.5;                               /* fetch       */
 }

 _OcNext[2] = mcall *_Mgoto.GetZMax ToolZup1; MF; wait 0; /* move up  */
");

/* ------------------------------------------------------------------ */
_tlch.ReadSwitch = &(                   /* check tool length          */
/* ------------------------------------------------------------------ */
/* %1 = 0: Hit not expected; %1 = 1: Hit expected                     */ 
/* ------------------------------------------------------------------ */
"if(_IndMc2Oc) {Wait 0; mReset \"Unzulässiger Aufruf von ReadSwitch\";}

 local \"CallOnExit\" \"CallOnError\";     /* variables to restore    */
 CallOnExit = CallOnError = (sprint \"MF_F = %.3lf; ML_F = %.3lf; MvPar;\" MF_F ML_F)
                          & \" Wait 0; MtransFlag01 = '1'; mreset;\";

 Tools[_toolNc].ofs[2] = 0; SetMc2Oc 0;    /* clear tool offset       */     
 MtransFlag01 = '0'; mreset;               /* disable MTrans          */

 _OcNext[0] = PickPos[0].Ofs[0];           /* approach X,Y            */
 _OcNext[1] = PickPos[0].Ofs[1]; MF;  
 wait 0;

 if(%1 == 0) {print GetIniTxt \"GetTool\" \"Prn003\";}
 if(%1 == 1) {print GetIniTxt \"GetTool\" \"PrnSearchZ\";}

 local \"ZSwitch\"; ZSwitch = PickPos[0].Ofs[2];
 local \"Ok\";      Ok      = _Tlch.SwitchState;

 _OcNext[2] = ZSwitch + _TPrbZUp; MF; Wait 0;     /* to top of range  */
 local \"Result\"; Result = GetOc[2];

 Mf_f = _ToolProbeF;                    /* set probing speed          */
 Ml_f = _ToolProbeS; MVPAR;     

 if(0 == _Test AND 1)                   /* move to switch and touch   */
 {
   if(Ok < 0) {Ok = 0 == in _InpDsc[_iTPrb];}

   if(Ok == 1 == in _InpDsc[_iTPrb])
    {mreset GetIniTxt \"GetTool\" \"ErrSwitch\";}

   _OcNext[2] = ZSwitch + _TPrbZDn; MF;
   stoprequest _InpDsc[_iTPrb] Ok; wait 0.2 0;
   wait 0 3; mreset; Result = GetOc[2];
 }
 else                                   /* simulation with message box*/
 {
   local \"SimOk\" \"Txt\"; wait 0;
   if(%1 == 0) {Txt = GetIniTxt \"GetTool\" \"MsgChange2\"; SimOk = 7;}
   if(%1 == 1) {Txt = GetIniTxt \"GetTool\" \"MsgChange3\"; SimOk = 6;}

   if(SimOk == MsgBox Txt \"\" MB_YESNO)   /* simulation with _ToolNC */
    {Result = ZSwitch + _TPrbZDn + _ToolNc + 5.0;}
 } 	

 local \"Found\"; Found = 0;

 if((Result > ZSwitch + _TPrbZDn + 0.1)  
 AND(Result < ZSwitch + _TPrbZUp - 1.0))
 {
   Found = 1;
 
   if((%1 == 1) AND (0 == _Test AND 1))
   {
     stoprequest _InpDsc[_iTPrb] (Ok == 0); /* move up and take probe */ 
     _OcNext[2] = _OcNext[2] + 5.0; ML;
     wait 0 3; mreset; Result = GetOc[2];
   }
 }

 mf_f = _ToolSpeedF;                    /* reset to toolchange speed  */
 ml_f = _ToolSpeedS; MvPar; 

 _OcNext[2] = mcall *_Mgoto.GetZMax ToolZup1; MF;       /* move up    */
 Wait 0; mreset;      

 if((%1 == 0) AND (Found == 1))         /* cancel if switch is hit    */
  {mreset GetIniTxt \"GetTool\" \"Err005\";}

 if((%1 == 1) AND (Found == 0))         /* cancel if switch is not hit*/
  {mreset GetIniTxt \"GetTool\" \"MsgNoSignal\";}
 
 if(Found == 1)
 { 
   Tools[_toolNc].ofs[2] = ZSwitch - Result;  /* set tool offset      */     
   setMc2Oc 0;                                /* install tool offset  */
 } 
");

/* ------------------------------------------------------------------ */
_tlch.SaveResult = &(                   /* Save new tool to file etc. */
/* ------------------------------------------------------------------ */
"WriteIniString (_path & \"/EdiTasc.ini\")  \"ToolConfig\" \"CurrTool\"
                (sprint \"%d\" _toolSel + 0L);

 _toolNc = _toolSel;                    /* update tool no.            */
 _mtStat.dirtyTool = 1;                 /* signal changes             */
 SetMc2Oc _IndMc2Oc;                    /* update offset              */
 _dspupdate;                            /* update display             */   
");

/* ------------------------------------------------------------------ */
_tlch.EpiLog = &(                       /* current point to tool home */
/* ------------------------------------------------------------------ */
"if(_tchToHome == 2)                    /* go to last position        */
 {
   print GetIniTxt \"GetTool\" \"PrnOldPos\";  /* print message       */
   mcall *_MGoto.Pos OldPos;
 }

 print GetIniTxt \"GetTool\" \"Prn001\";/* Tool change ready message  */ 
 _PrgCont;                              /* prepare to continue work   */ 
");

/* ------------------------------------------------------------------ */
_tlch.LimitsOff = &(                    /* suspend limit watching     */
/* ------------------------------------------------------------------ */
"Local \"OldLim\"; OldLim = Mlimit '?'; /* get current state          */
 Mlimit '0'; MlimitIsSuspended = 1;     /* Limit watching off         */
 _mtStat.dirtyTrans = 1;                /* redraw limits              */
 Oldlim                                 /* return state, no ';'!      */
");

/* ------------------------------------------------------------------ */
_tlch.LimitsOn = &(                     /* restore limit watching     */
/* ------------------------------------------------------------------ */
" wait 0; mreset;                       /* make position valid        */
  Mlimit %1;                            /* restore limit flag         */
  MlimitIsSuspended  = 0;
  _mtStat.dirtyTrans = 1;               /* redraw limits              */
");

/* ================================================================== */
/* ToolMacros:  _ToolOpen, _ToolClose, ToolRad, LoadTools, GetTool    */ 
/* ================================================================== */
(Macrodef "_ToolOpen")  = "";
(Macrodef "_ToolClose") = "";
(Macrodef "ToolRad")    = "Tools[_ToolSel].Rad;";
(Macrodef "ToolRadEmu") = "Tools[_ToolSelEmu].Rad;";

/* ================================================================== */
/* LoadTools: Load tools from file                                    */
/* ================================================================== */
/* Parameter: %1 = tool file, %2 = 1: enforce loading                 */  
/* ------------------------------------------------------------------ */
_ToolFileAsked  = "no file asked";                /* init value       */
_ToolFileLoaded = "no file loaded";               /* init value       */

(Macrodef "LoadTools") = 
"Local \"DoLoad\"; DoLoad = 0;

 if(%P > 1) {if(%2) {DoLoad = 1;}}                /* enforce loading  */
 if(0 == (_ToolFileLoaded == %1)) {DoLoad = 1;}   /* new file to load */

 if(DoLoad)                                       /* load tool file   */
 {
   if(FileExists %1) 
   {
     local \"n\" \"i\" \"lFDnR\" \"Dft1\" \"Dft2\" \"TmpTxt\";
     Local \"OneLine\" \"Version\" \"DoLoad\";

     Dft1 = \"\\\"Default;\\\" \\\"Default;\\\" \\\"Default;\\\"\";
     Dft2 = \"0 \\\"Default\\\"\";

     Local \"ZeroTool\"; ZeroTool = Tools[0];

     Version = scall GetIniString %1 \"Tools\" \"Version\" \"0\";

     n = 0L + scall GetIniString %1 \"Tools\" \"n\" \"0\";
     if(n > 0)
     {
       _ToolN   = n;                                     
       Tools    = ObjDef CTool _ToolN + 1;
       Tools[0] = ZeroTool;
     }
 
     TmpTxt = ObjDef T_Char n + 1;
     i = 0;
     for(n)
     { TmpTxt[i] = '1'; 
       LfdNr = sprint \"%d\" i = i + 1;
       OneLine = GetIniString %1 \"Tools\" LfdnR \"\";

       if(OneLine == \"\"){msgbox \"Missing line in tool file section!\";}

       Tools[i].CRC     = GetStkObj 0 scall OneLine;
       Tools[i].EMU     = GetStkObj 1 scall OneLine;
       Tools[i].Ident   = GetStkObj 2 scall OneLine;
       Tools[i].Rad     = GetStkObj 3 scall OneLine;
       Tools[i].Len     = GetStkObj 4 scall OneLine;
       Tools[i].Speed   = GetStkObj 5 scall OneLine;
       Tools[i].Rpm     = GetStkObj 6 scall OneLine;
       Tools[i].Out     = GetStkObj 7 scall OneLine;
       Tools[i].Color   = GetStkObj 8 scall OneLine;
       (*Tools[i].Text) = \"Tool Text\";
       
       if(Version >= 1) {(*Tools[i].Text) = GetStkObj 9 scall OneLine;}

       Tools[i].Ofs = ARRAY _nAx scall GetIniString %1 \"Offset\" LfdNr \"\";

       OneLine = GetIniString %1 \"Macros\" LfdNr Dft1;   
 
       if(Version == 0)
       {
         (*Tools[i].BTC) = GetStkObj 0 scall Oneline; 
         (*Tools[i].ATC) = GetStkObj 2 scall Oneline; 
         (*Tools[i].DXF) = GetStkObj 4 scall Oneline; 
       }

       if(Version == 1)
       {
         (*Tools[i].BTC) = GetStkObj 0 scall Oneline; 
         (*Tools[i].ATC) = GetStkObj 1 scall Oneline; 
         (*Tools[i].DXF) = GetStkObj 2 scall Oneline; 
       }

       OneLine = GetIniString %1 \"Shape\" LfdNr Dft2;

       Tools[i].Flags    = GetStkObj 0 scall OneLine;
       (*Tools[i].File)  = GetStkObj 1 scall Oneline;
     }

     _ToolMode = scall GetIniString %1 \"Tools\" \"ToolMode\" \"0\";
     _ToolFileLoaded = %1;
   }
   else  
    {MsgBox \"Tool file not found: \" & %1;}
 }
";

(Macrodef "MakeHex") = 
"local \"Txt\" \"i\"; i = 1;
 Txt = sprint \"0x%8XL\" %1 + 0L;
 for(8) {if(Txt[i = i + 1] == 32) {Txt[i] = 48;}}
 Txt
";

/* ================================================================== */
/* SaveToolHeader                                                     */
/* ================================================================== */
/* Parameter: %1 = tool file                                          */  
/* ------------------------------------------------------------------ */
(Macrodef "SaveToolHeader") =
"WriteIniString %1 \"Tools\" \"Version\"  \"1\";
 WriteIniString %1 \"Tools\" \"ToolMode\" sprint \"%d\" _ToolMode;
 WriteIniString %1 \"Tools\" \"n\"        sprint \"%d\" _ToolN;

 WriteIniString %1 \"Tools\"  \"HD\" \" CRC  EMU  Id      Rad      Len    Speed    Rpm   Out Color       Kommentar\";
 WriteIniString %1 \"Offset\" \"HD\" \"      OX       OY       OZ       OA       OB       OC       OD       OE\";
 WriteIniString %1 \"Macros\" \"HD\" \"     BTC                    ATC                    DXF\";
";

/* ================================================================== */
/* SaveTools: Save tools to file                                      */
/* ================================================================== */
/* Parameter: %1 = tool file                                          */  
/* ------------------------------------------------------------------ */
(Macrodef "SaveTools") = 
"local \"Txt\" \"LfdNr\" \"i\" \"j\"; i = 0;

 SaveToolHeader %1;

 for(_ToolN)
 {
   LfdNr = sprint \"%d\" i = i + 1;

   Txt = \" \"; if(i > 9) {Txt = \"\";}

   Txt = Txt & (sprint \" %2d %4d %4d\"          Tools[i].CRC Tools[i].EMU Tools[i].Ident)
             & (sprint \" %8.3lf %8.3lf %8.3lf\" Tools[i].Rad Tools[i].Len Tools[i].Speed)
             & (sprint \" %6dL%5d %s\"           Tools[i].Rpm Tools[i].Out MakeHex Tools[i].Color)
   ;

   WriteIniString %1 \"Tools\" LfdNr Txt & \" \\\"\" & (*Tools[i].Text) & \"\\\"\";

   j = 0; Txt = \" \"; if(i > 9) {Txt = \"\";}
   for(8) {Txt = Txt & sprint \" %8.3lf\" Tools[i].Ofs[j]; j = j + 1;}
   WriteIniString %1 \"Offset\" LfdNr Txt;

   Txt = \" \"; if(i > 9) {Txt = \"\";}

   Txt = Txt & (sprint \"%-22s \" \"\\\"\" & (*Tools[i].BTC) & \"\\\"\")
             & (sprint \"%-22s \" \"\\\"\" & (*Tools[i].ATC) & \"\\\"\")
             & (sprint \"%s\"     \"\\\"\" & (*Tools[i].DXF) & \"\\\"\")
   ;

   WriteIniString %1 \"Macros\" LfdNr \"'\" & Txt & \"'\";

   Txt = \" \"; if(i > 9) {Txt = \"\";}
   Txt = Txt & sprint \" %3d   \\\"%s\\\"\" Tools[i].Flags *Tools[i].File;
   WriteIniString %1 \"Shape\" LfdNr Txt;
 }
";

/* ================================================================== */
/* CheckTools: check tool file                                        */
/* ================================================================== */
(MacroDef "CheckTools") =
"if(0 == (_ToolFileLoaded == %1))
 {if(0 == (_ToolFileAsked == %1))
   {MsgBox ((GetIniTxt \"Dxf2Et\" \"ToolFileInfo0\") 
           & \"\n\n\" & %1 & \".\n\n\" 
           & (GetIniTxt \"Dxf2Et\" \"ToolFileInfo1\"))
           (\"Dxf2Et\");
     _ToolFileAsked = %1;
   }
 }
";

/* ================================================================== */
/* GetTool: Get real tool from emulated tool and                      */
/*          Change real tool by calling file GetTool.ts               */
/* ================================================================== */
/* Parameter: %1 = new tool number -> _ToolSelEmu                     */ 
/*  optional: %2 = override active flag                               */ 
/*  optional: %3 = enforce tool change                                */ 
/* ------------------------------------------------------------------ */
(Macrodef "GetTool") = 
"local \"ToolFound\";

 ToolFound = NcFromEmu %1 _ToolMode;     /* Get NC tool from EMU tool */

 if(ToolFound == -1)                               /* invalid tool    */
  {mreset sprint (GetIniTxt \"GetTool\" \"Err002\") %1;}

 if(ToolFound == -2)                               /* invalid pointer */
  {mreset sprint (GetIniTxt \"GetTool\" \"Err006\") %1;}

/*--------------------------------------------------------------------*/
/* Check tool position for automatic tool change                      */
/*--------------------------------------------------------------------*/
 if((_ToolAuto == 3) and (ToolFound > SizeOfArray PickPos))
 {                                      /* no tool location           */
   mreset sprint (GetIniTxt \"GetTool\" \"Err003\") %1;
 }

 _ToolSelEmu = %1;                      /* assign tool                */
 _ToolSel    = ToolFound;
 if(_toolMode == 2) {_ToolSelEmu = ToolFound;}

/*--------------------------------------------------------------------*/
/* Grafik aktivieren / deaktivieren aufgrund des Werkzeug-Modus       */
/*--------------------------------------------------------------------*/
 local \"ToolEmuActive\";

 ToolEmuActive = 1;

 if(T_undefined != (TypeOf \"_FParm\").type)      /* if _FParm exists */ 
  {ToolEmuActive = ('1' == (*_Fparm.ToolActive)[_ToolselEmu]);}

 if(%P >= 2)       {ToolEmuActive = %2;} /* override active flag      */ 
 if(_tlch.AllowT0) {ToolEmuActive =  1;} /* override for tool=0       */

/*--------------------------------------------------------------------*/
/* Aktivieren / deaktivieren aufgrund des Werkzeug-Modus              */
/*--------------------------------------------------------------------*/
 if(_Mode == 'G')                        /* Ausführungsmodus Grafik   */
  {_grMode = ToolEmuActive;}             /* Grafikmodus anpassen      */

 if(_mode != 'G')
 {
   local \"CallOnExit\" \"DoChange\";

   CallOnExit = (sprint \"@ SetMc2Oc  %d;  \" _indMc2Oc)  
              & (sprint \" _VciCurr = %dL; \" _VciCurr)
              & (sprint \" RmpMode   '%c'; \" RmpMode '?')
              & (       \" _GTA = 0;\");

   DoChange = 0;
   if(%P == 3) {DoChange = %3;}        /* enforce tool change         */ 

   _GTA     = 1;                       /* signal tool change          */
   RmpMode 'Y';                        /* no ramps in toolchange      */
   SetMc2Oc 0;                         /* set machine coordinates     */
   
   wait 0; MpLock '+';
   CallOnExit = CallOnExit & \" MpLock '-';\";

   If((0 == _ncMode AND 1)                  /* Werkzeug ist inaktiv   */  
   AND(1 == ToolEmuActive))                 /* aktivieren verlangt    */ 
   {
     _ncMode = _NcMode or 1;                /* aktivieren             */
     mreset;
     if(_ToolAuto > 0)
     {
       if(_Z < McPos[3].ofs[2])             /* hochfahren             */
        {_OcNext[2] = McPos[3].ofs[2]; MF; Wait 0; mreset;}
     }
   }  
      
   If((1 == _ncMode AND 1)                  /* Werkzeug ist aktiv     */  
   AND(0 == ToolEmuActive))                 /* deaktivieren verlangt  */ 
   { 
     if(_ToolAuto > 0)
     {
       if(_Z < McPos[3].ofs[2])             /* hochfahren             */
        {_OcNext[2] = McPos[3].ofs[2]; MF; Wait 0; mreset;}
     }
     _ncMode = _NcMode and -2;              /* deaktivieren           */
   }

   If(1 == _ncMode AND 1)                   /* real tool change       */
   {
     if(ThreadFlags \"DrvLoaded\")
     {
       if((_toolSel != _toolNc) OR (DoChange > 0)) 
        {fcall _Path & \"/Macros/GetTool.ts\"; wait 0;}
     }
     _toolNcEmu = _toolSelEmu;              /* update EMU-tool        */
     _mtStat.dirtyTool = 1;                 /* signal EMU changes     */
   }
 }

/*--------------------------------------------------------------------*/
/* Abschlussarbeiten                                                  */ 
/*--------------------------------------------------------------------*/
 local \"ToolCol\";                              /* select tool color */
 ToolCol = Tools[_toolSelEMU].Color;             /* ...from tools     */ 

 if(T_undefined != (TypeOf \"_FParm\").type)     /* if _FParm exists  */ 
 {
   local \"CM\"; CM = _fParm.CrcMode;            /* default = fParm   */
   if(CM == 0) {CM = _pParm.CrcMode;}            /* fParm => pParm    */
   if(CM == 5) {CM = Tools[_ToolNcEmu].CRC;}     /* pParm => tool     */

   ModeToCrc CM; 

   if(_PParm.ColorMode)
   {                                                  /* tool color   */
     If(_fParm.MlColor) {ToolCol = _fParm.MlColor;}   /* from project */
   }
 }  

 _Crcpar.Rad = ToolRadEmu;                       /* set crc radius    */
 
 SetDrawPar 'L' ToolCol -1 -1 -1;                /* set color         */

 if(_ToolWidthVar)                               /* set width         */
 {
   local \"ToolWidth\";       
   ToolWidth = 0;                
   Toolwidth = 2.0 * _MM2Pix * ToolRadEmu;
   if(_mtStat.crcstate == 0) {SetDrawPar 'L' ToolCol -1 ToolWidth -1;}
   if(_mtStat.crcstate >  0) {SetDrawPar '0' ToolCol -1 ToolWidth -1;}
 }

 if(_SpeedFromTool > 0)
 {
   if(Tools[_toolSelEmu].Speed > 0)              /* set speed         */
    {ML_F = Tools[_toolSelEmu].Speed; MvPar;}
 }

 if(_RpmFromTool > 0)
 {
   _oaValue = Tools[_toolSelEmu].Rpm;            /* set spindle speed */
   if(_ncMode AND 1){_oaSet _oaValue; _dspUpdate;}
 }
";

/* ================================================================== */
/* Ask if the tool rack is empty at location _ToolNC                  */
/* ================================================================== */
(MacroDef "QueryToolOk") =
"local \"mb\";
 
 mb = MsgBox                     
      (sprint (scall \"\\\"\" & (GetIniTxt \"AutoStrt\" \"QueryToolOK\") & \"\\\"\") _ToolNC + 0L)
      (sprint (GetIniTxt \"AutoStrt\" \"QueryToolCapt\") _ToolNC + 0L)
       MB_YESNO or MB_ICONEXCLAMATION;

 if(mb == 7)                               /* altes Tool herausnehmen */
 {
   local \"CallOnExit\" \"CallOnError\";
   CallOnExit = CallOnError = sprint \"Setmc2Oc %d\" _IndMc2Oc;
   SetMc2Oc 0;

   _OcNext[2] = McPos[1].Ofs[2]; MF;       /* Z zur Serviceposition   */
   _OcNext[0] = McPos[1].Ofs[0];
   _OcNext[1] = McPos[1].Ofs[1]; MF;       /* X,Y zur Serviceposition */
   Wait 0; mreset;

   MsgBox (sprint (GetIniTxt \"AutoStrt\" \"InsertTool\") _ToolNC + 0L)
           \"AutoStart.ts\"  MB_OK or MB_ICONEXCLAMATION;
   wait 0.5;
 }
";

/* ================================================================== */
/* Ask if the tool is to be calibrated                                */
/* ================================================================== */
(MacroDef "QueryToolCalib") =
"Local \"Msg\"; 

 _ToolPrbState = 0;                        /* reset flag              */   

 if(0 == _Test AND 2)
 { 
   Msg = GetIniTxt \"GetTool\" \"MsgKalib1\";   /* want calibration?  */

   if(6 == MsgBox (Scall \"\\\"\" & Msg & \"\\\"\") 
                  (GetIniTxt \"GetTool\" \"MsgKalib2\") MB_YESNO)
   { 
     _ToolPrbState = 2;                         /* calibration wanted */   
     if(_iTPrb == 0)
     {
      _Test = _Test OR 1;                  /* switch is not defined   */
       msgbox GetIniTxt \"GetTool\" \"MsgKalib3\";
     }

     local \"OldLim\"; OldLim = Mlimit '?';/* Save current limit flag */
     mcall *_tlch.LimitsOff;               /* suspend limit watching  */ 

     local \"CallOnExit\" \"CallOnError\";
     CallOnExit = (sprint \"MF_F = %.3lf; ML_F = %.3lf; MvPar;\" MF_F ML_F)
                & (sprint \"SetMc2Oc %d;\" _indMc2Oc);
     
     CallOnError = CallOnExit; 
     SetMc2Oc 0;

     mf_f = _ToolSpeedF;                   /* set toolchange speed    */
     ml_f = _ToolSpeedS; MvPar;

     Mcall *_tlch.ReadSwitch 1;            /* cancel if switch not hit*/

     if(_TchToHome == 1)
      {MCall *_MGoto.Pos McPos[3].Ofs 1;}  /* return to tool home     */ 

     mcall *_tlch.LimitsOn OldLim;         /* restore limit watching  */ 
   }
 } 
";

/* ================================================================== */
/* Get NC tool from EMU tool:                                         */  
/* ================================================================== */
/* Parameter: %1 = EMU tool, %2 = ToolMode (0, 1, 2)                  */  
/* ------------------------------------------------------------------ */
(Macrodef "NcFromEmu") =
"local \"i\" \"Result\";

 Result = %1;                           /* default = requested tool   */      

 if(%2 <= 1)                            /* check tool variable        */
 {
  if((%1 < 0) OR (%1 > _toolN)) {Result = -1;}     /* invalid tool    */
 }

 if((Result > 0) AND (%2 == 1))         /* get tool pointed to by EMU */
 {
   i = 0L + Tools[%1].EMU;
   if((i > 0) and (i <= _toolN)) {Result =  i;} 
   if((i < 0) or  (i >  _toolN)) {Result = -2;}    /* invalid pointer */
 }

 if((Result > 0) AND (%2 == 2))         /* search tool with Ident-No. */
 { 
   i = Result = 0;                      /* there is no default        */ 
   while \"i < _ToolN\"
   {
     if(Tools[i = i + 1].Ident == %1) {Result = i; i = _ToolN;}
   }
 }

 if((Result == 0) And (_tlch.AllowT0 == 0)) {Result = -1;}

Result";                                 /* return result (=tool)     */

