<?php
    require_once '../database.php';
    require_once '../global_functions.php';

    // Method to modify the tools for the task at present
    function modifyTaskToolsInDatabase($db, $userRow, $tid, $mid){
        // Assume that we are successful unless proven otherwise
        $errorString='';
        
        try {
            // Determine if the TID is one greater than 0
            if ($tid!=null && $tid>0 &&
                $mid!=null && $mid>0){

                // Set a variable to hold the tools that are ok
                $goodTools='';

// TODO: Leaving this here for now in case we want to revisit forcing tools into slots that the programmer has chosen that work.
//       Still need to figure out what happensd if there are two tools that are the same though if we want to do this.
                
//                // Get the tool positions that WILL work as is
//                $sql='SELECT ttl.ToolPosition ' .
//                     'FROM tooltotasklinker ttl ' .
//                     'LEFT JOIN assignedtools asst ON ttl.ToolPosition=asst.Position ' .
//                     'WHERE ttl.TaskID=' . $tid . ' ' .
//                     'AND asst.MachineID=' . $mid . ' ' .
//                     'AND IF((asst.CurrentToolID=ttl.ToolID), 1, 0) * IF((asst.ExposedLength>=ttl.ExposedLength), 1, 0)=1 ' .
//                     'ORDER BY ttl.ToolPosition;';
//
//                // Run the query
//                $currentTaskTools = $db->queryDB($sql, $userRow, "modify_task_for_presentation Form occurance 1");
//
//                // Determine if there are any rows before attempting to loop through them
//                if ($currentTaskTools != null && 
//                    mysqli_num_rows($currentTaskTools)>0){
//
//                    // Loop through the returned results
//                    $amount=0;
//                    while ($currentLoopTaskTool=mysqli_fetch_array($currentTaskTools)){
//                        // Add this tool position as one that is good already
//                        $goodTools=$goodTools . $currentLoopTaskTool["ToolPosition"] . ',';
//                    }
//                    
//                    // Now determine if we do NOT have an empty string
//                    if ($goodTools!=''){
//                        // Remove the last comma
//                        $goodTools=substr($goodTools, 0, -1);
//                    }
//                }
//                
//                // Setup the good tools part of the SQL
//                $goodToolsSQL=($goodTools!='')?'AND asst.Position NOT IN (' . $goodTools . ') ':'';

                // Make a query to match tools that are currently in the database  
                // and useable WorkablePositions is concatinated by commas in case 
                // there are multiple working positions.
                $sql='SELECT DISTINCT GROUP_CONCAT(asst.Position) AS WorkablePositions, ttl.ToolToTaskLinkerID ' .
                     'FROM tooltotasklinker ttl ' .
                     'LEFT JOIN assignedtools asst ON ttl.ToolID=asst.CurrentToolID ' .
                     'WHERE ttl.TaskID=' . $tid . ' ' .
                     'AND asst.MachineID=' . $mid . ' ' .
                     'AND IF((asst.CurrentToolID=ttl.ToolID), 1, 0) * IF((asst.ExposedLength>=ttl.ExposedLength), 1, 0)=1 ' .
//                     $goodToolsSQL .
                     'GROUP BY asst.CurrentToolID ' .
                     'ORDER BY ttl.ToolPosition DESC;';

//return $sql;
                // Run the query
                $workableToolPositions = $db->queryDB($sql, $userRow, "modify_task_for_presentation Form occurance 1");

                // Determine if there are any rows before attempting to loop through them
                if ($workableToolPositions != null && 
                    mysqli_num_rows($workableToolPositions)>0){

                    // Loop through the returned results
                    while ($workableToolPosition=mysqli_fetch_array($workableToolPositions)){
                        // Get the first tool in the array if there is one
                        $firstPosition = explode(",", $workableToolPosition["WorkablePositions"])[0];
                        
                        // Clear out any tool that is set as there first before anything
                        $sql='UPDATE tooltotasklinker ' . 
                             'SET ToolPosition=0 ' . 
                             'WHERE ToolPosition= ' . $firstPosition . ' ' .
                             'AND TaskID=' . $tid . ';';
                        
                        // Attempt to run the update query
                        $db->queryDB($sql, $userRow, "modify_task_for_presentation Form occurance 2");

                        // Create the query to update the tooltotasklinker table with this new position
                        $sql='UPDATE tooltotasklinker ' . 
                             'SET ToolPosition=' . $firstPosition . ' ' . 
                             'WHERE ToolToTaskLinkerID = ' . $workableToolPosition["ToolToTaskLinkerID"] . ';';
                        
                        // Attempt to run the update query
                        $db->queryDB($sql, $userRow, "modify_task_for_presentation Form occurance 3");

                        // Determine if we have any good tools yet
                        if ($goodTools==''){
                            // Add this as a tool not to query for on the possible next query
                            $goodTools = $firstPosition;
                        }
                        else{
                            // Add this as a tool not to query for on the possible next query
                            $goodTools = $goodTools . ',' . $firstPosition;
                        }
                    }
                }
                 
                // Setup the good tools part of the SQL
                $goodToolsSQL=($goodTools!='')?'AND ttl.ToolPosition NOT IN (' . $goodTools . ') ':'';
                
                // Create a query to get the tools for the task
                $sql='SELECT ttl.* ' . 
                     'FROM tooltotasklinker ttl ' . 
                     'WHERE ttl.TaskID=' . $tid . ' ' . 
                     $goodToolsSQL .  
                     'ORDER BY ttl.ToolPosition DESC;';

                // Run the query
                $taskToolsNeedingChanged = $db->queryDB($sql, $userRow, "modify_task_for_presentation Form occurance 4");

                // Determine if there are any rows before attempting to loop through them
                if ($taskToolsNeedingChanged != null && 
                    mysqli_num_rows($taskToolsNeedingChanged)>0){
                    // Setup the good tools part of the SQL
                    $goodToolsSQL=($goodTools!='')?'AND asst.Position NOT IN (' . $goodTools . ') ':'';

                    // Now create a query to determine ALL available slots to put tools that are NOT the tools that are ok.
                    $sql='SELECT asst.* ' .
                         'FROM assignedtools asst ' .
                         'WHERE asst.MachineID=' . $mid . ' ' .
                         $goodToolsSQL .
                         'AND asst.CommonTool<>1 ' .
                         'ORDER BY asst.Position DESC;';

                    // Run the query
                    $allAvailableToolSlots = $db->queryDB($sql, $userRow, "modify_task_for_presentation Form occurance 5");

                    // Determine if there are any rows before attempting to loop through them
                    if ($allAvailableToolSlots == null || 
                        (mysqli_num_rows($taskToolsNeedingChanged)>mysqli_num_rows($allAvailableToolSlots))){
                        // Create an error string to be reported to the user
                        return 'ABORT MODIFY (modify_task_for_present)::There are not enough available slots on the machine to setup tools to allow for g-code modification. Open up machine slots by unchecking common tools, checking exposed lengths or create the packet without g-code modification. Aborting...';
                    }

                    // Loop through the returned results to create an array of tools needing positions.
                    $taskIDsNeedingPositions=array();
                    while ($taskToolNeedingChanged=mysqli_fetch_array($taskToolsNeedingChanged)){
                        // Add this one to the array of tools needing slots
                        array_push($taskIDsNeedingPositions, $taskToolNeedingChanged["ToolToTaskLinkerID"]);
                    }
                    
                    // Set the array position of the tools that a slot in a machine to the beginning 
                    $toolArrayPosition=0;
                    
                    // Setup the good tools part of the SQL
                    $goodToolsSQL=($goodTools!='')?'AND asst.Position NOT IN (' . $goodTools . ') ':'';

                    // Now create a query to determine tool slots that do not have a tool yet.
                    $sql='SELECT asst.* ' .
                         'FROM assignedtools asst ' .
                         'WHERE asst.MachineID=' . $mid . ' ' .
                         $goodToolsSQL .
                         'AND asst.CommonTool<>1 ' .
                         'AND asst.CurrentToolID=-1 ' .
                         'ORDER BY asst.Position DESC;';

                    // Run the query
                    $emptyAvailableToolSlots = $db->queryDB($sql, $userRow, "modify_task_for_presentation Form occurance 6");
                    
                    // Determine if there are any rows before attempting to loop through them
                    if ($emptyAvailableToolSlots != null && 
                        mysqli_num_rows($emptyAvailableToolSlots)>0){
                        // Loop through the returned results
                        while ($emptyAvailableToolSlot=mysqli_fetch_array($emptyAvailableToolSlots)){
                            // Create the query to update the tooltotasklinker table with this new position
                            $sql='UPDATE tooltotasklinker ' . 
                                 'SET ToolPosition=' . $emptyAvailableToolSlot["Position"] . ' ' . 
                                 'WHERE ToolToTaskLinkerID = ' . $taskIDsNeedingPositions[$toolArrayPosition] . ';';

                            // Attempt to run the update query
                            $db->queryDB($sql, $userRow, "modify_task_for_presentation Form occurance 7");

                            // Determine if all tools have been accounted for
                            if (($toolArrayPosition+1)<sizeof($taskIDsNeedingPositions)){
                                // Increase the position in the array to the next one
                                $toolArrayPosition++;
                            }                            
                            else {
                                // Break out of this loop
                                break;
                            }
                            
                            // Determine if we have any good tools yet
                            if ($goodTools==''){
                                // Add this as a tool not to query for on the possible next query
                                $goodTools = $emptyAvailableToolSlot["Position"];
                            }
                            else{
                                // Add this as a tool not to query for on the possible next query
                                $goodTools = $goodTools . ',' . $emptyAvailableToolSlot["Position"];
                            }
                        }
                    }
                    
                    // determine if the empty slots did not cut it
                    if (($toolArrayPosition)<sizeof($taskIDsNeedingPositions)){
                        // Setup the good tools part of the SQL
                        $goodToolsSQL=($goodTools!='')?'AND asst.Position NOT IN (' . $goodTools . ') ':'';

                        // Now time to fill the slots that are not empty. Create a query to determine left available slots.
                        $sql='SELECT asst.* ' .
                             'FROM assignedtools asst ' .
                             'WHERE asst.MachineID=' . $mid . ' ' .
                             $goodToolsSQL .
                             'AND asst.CommonTool<>1 ' .
                             'ORDER BY asst.Position DESC;';

                        // Run the query
                        $leftAvailableToolSlots = $db->queryDB($sql, $userRow, "modify_task_for_presentation Form occurance 8");

                        // Determine if there are any rows before attempting to loop through them
                        if ($leftAvailableToolSlots != null && 
                            mysqli_num_rows($leftAvailableToolSlots)>0){

                            // Loop through the returned results
                            while ($leftAvailableToolSlot=mysqli_fetch_array($leftAvailableToolSlots)){
                                // Create the query to update the tooltotasklinker table with this new position
                                $sql='UPDATE tooltotasklinker ' . 
                                     'SET ToolPosition=' . $leftAvailableToolSlot["Position"] . ' ' . 
                                     'WHERE ToolToTaskLinkerID = ' . $taskIDsNeedingPositions[$toolArrayPosition] . ';';
                                
                                // Attempt to run the update query
                                $db->queryDB($sql, $userRow, "modify_task_for_presentation Form occurance 9");

                                // Determine if all tools have been accounted for
                                if (($toolArrayPosition+1)<sizeof($taskIDsNeedingPositions)){
                                    // Increase the position in the array to the next one
                                    $toolArrayPosition++;
                                }                            
                                else {
                                    // Break out of this loop
                                    break;
                                }
                            }
                        }    
                    }
                }
            }
        } 
        catch (Exception $exc) {
            // Create the error string to return back to the caller
            return 'ABORT MODIFY (modify_task_for_present)::There is an uncaught error while setting new tool slots to prepare for g-code mods.  The exception is: ' . $exc->getMessage() . '. Aborting...';
        }
        
        // Return what could be an error string
        return $errorString;
    }
    
    // function to determine if the command is tru
    function isActiveCommand($gCodeLine, $command){
        // Assume that is is NOT an active command until I prove it otherwise
        $returnValue=false;
        
        // Determine if there are comments on this line
        if (($firstCommentPos=strpos($gCodeLine,"("))!==FALSE &&
            ($lastCommentPos=strpos($gCodeLine,")"))!==FALSE){
            // Set variables used
            $lastPos = 0;
            $positions = array();

            // Loop through the line to get all positions of the GCode comment
            while (($lastPos = strpos($gCodeLine, $command, $lastPos))!== false) {
                // Put the position into the array
                $positions[] = $lastPos;

                // Change the last position to increment by the size of the string
                $lastPos = $lastPos + strlen($command);
            }

            // Loop through the array to determine if this code is NOT in a comment
            foreach ($positions as $value) {
                // Determine if this code is outside the comment block
                if ($value<$firstCommentPos || 
                    $value>$lastCommentPos){
                    // Set the value to true that it is an active command
                    $returnValue=true;
                    
                    // No need to continue with this loop, so jump out
                    break;
                }
            }                            
        }
        else {
            // No comments mean that all on the line are active commands
            $returnValue=true;
        }
        
        // Return the value
        return $returnValue;
        
    }
    
    function createModifiedGCode($db, $userRow, $tid, $setupid, $gcode, $gCodeName){
        // Assume that we are successful unless proven otherwise
        $errorString="";
        
        try {
            // Determine if there is any GCode name before attempting to make the directory
            if ($gCodeName != null && $gCodeName != '' && $gcode != null){
                // Remove directory in case it is there
                unlink( dirname(__FILE__) . '/../../pdf_templates/temp/MachiningInfo_' . $tid);

                // Make the directory for the files
                mkdir(dirname(__FILE__) . '/../../pdf_templates/temp/MachiningInfo_' . $tid);

                // Create a file that will be the new modified GCode
                $newGCodeFile = fopen((dirname(__FILE__) . '/../../pdf_templates/temp/MachiningInfo_' . $tid . '/' . $gCodeName), "w");

                // Determine if the TID is one greater than 0
                if ($tid!==null && $tid>0){
                    // Create a multi-dimensional array that will hold the tools current position, old position and name
                    $toolsInGCode=array();

                    // Create a loop variable to hold the number of tool we are on
                    $toolNumber=0;

                    // Split the string on end line characters
                    $lines = explode("\r\n", $gcode);

                    // Keep a tally of the amount of M00's we run into in the file
                    $m00Number=0;

                    // Array that will hold lines that need to be ignored
                    $linesToIgnore=array();

                    // Create variable to hold the current and old tool numbers
                    $currentNewToolNumber=-1;
                    $oldToolNumber=-1;

                    // Loop through the file looking for end line characters
                    for ($i = 0; $i<count($lines); $i++) {
                        $currentLine=$lines[$i];

                        // Check to see if this is a tool line
                        if (strpos($currentLine,"(/-/)")!==FALSE) {
                            // Remove the end and beginning
                            $currentLine = str_replace("(/-/)(T","", trim($currentLine, "'"));
                            $currentLine = str_replace(")(/-/)", "", trim($currentLine, "'"));

                            // Split the string on the tool name and number
                            $toolInfo = explode("-", $currentLine, 2);

                            // Ensure we get two values
                            if (count($toolInfo)!==2){
                                // Go on to the next tool and try that.
                                continue;
                            }

                            // Create a query to get the tool as it stands in the TMS (New Position).
                            $sql = 'SELECT ttl.ToolPosition, t.Name ' .
                                   'FROM tooltotasklinker ttl ' .
                                   'LEFT JOIN tools t on ttl.ToolID = t.ToolID ' .
                                   'WHERE ttl.TaskID = ' . $tid . ' ' .
                                   'AND t.Name = "' . trim($toolInfo[1]) . '"; ';

                            // Get the new tool position
                            $newToolInfo = $db->queryDB($sql, $userRow, "modify_task_for_present occurance 10");

                            // Ensure that the query came back well
                            if (mysqli_num_rows($newToolInfo)===1){
                                // Get the readable row
                                $newToolInfoAssocRow = $newToolInfo->fetch_assoc();
                                
                                // Add this tool to the tools to check for while looping through code 
                                $toolsInGCode[$toolNumber]=array('NewPosition' => $newToolInfoAssocRow["ToolPosition"],
                                                                 'OldPosition' => trim($toolInfo[0]),
                                                                 'ToolName' => $toolInfo[1]
                                );

                                // Add the line to the temp GCode file
                                fwrite($newGCodeFile, str_replace("T" . $toolsInGCode[$toolNumber]['OldPosition'] . " ", "T" . $toolsInGCode[$toolNumber]['NewPosition'] . " ", $lines[$i]) . "\r\n");

                                // Increment the amount of tools found
                                $toolNumber++;
                            }
                            else {
                                // Tools do not match the database to the GCode, so let's just abort the modify of the GCode and making of the packet
                                return 'ABORT MODIFY (modify_task_for_present)::Tool number ' . trim($toolInfo[0]) . ' (' . trim($toolInfo[1]) . ') in the G-Code is not a tool associated with this machining task. Check the task and make sure ALL tools in the task tool tab match the tools in the G-Code. Aborting...';
                            }
                        }
                        else if (strpos($lines[$i],"M130")!==FALSE ||
                                 in_array($i, $linesToIgnore)) {
                            // Determine if the command is an active command
                            if (isActiveCommand($lines[$i], "M130")===true){
                                // Skip past the next line to add to the temp file
                                continue;
                            }
                            else {
                                // Just add the line to the GCode
                                $tempGCode = $tempGCode . $lines[$i] . "\r\n";
                            }
                        }
                        // Determine if we are at the start of the real GCode yet
                        else if (strpos($lines[$i],"G00 G17 G20 G40 G80 G90 G94")!==FALSE) {
                            // Loop until we find the appropriate M Code
                            for ($i2 = $i; $i2<count($lines); $i2++) {
                                // If this line has a M130 or M00
                                if (isActiveCommand($lines[$i2],"M130")===true || 
                                    isActiveCommand($lines[$i2],"M00") ===true) {
                                    // Add this line number to the lines to ignore
                                    array_push($linesToIgnore, $i2);
                                }
                                // Determine if this line has an M6.  If so, jump out.
                                else if (isActiveCommand($lines[$i2],"M6")===true) {
                                    // Break out of the loop
                                    break;
                                }
                            }

                            // Now add this line to the GCode file
                            fwrite($newGCodeFile, $lines[$i] . "\r\n\r\n");

                            // Create a query to get start M00s of this setup 
                            $sql='SELECT FileName FROM notes ' . 
                                 'WHERE AssociatedCategoryID='. $setupid . ' ' .
                                 'AND Category="SETUP_M00" ' . 
                                 'AND FileName LIKE "M00_START%" ' . 
                                 'ORDER BY NoteOrder;';

                            // Run the query
                            $startMOOs = $db->queryDB($sql, $userRow, "modify_task_for_presentation Form occurance 12");

                            // Determine if there are any rows before attempting to loop through them
                            if ($startMOOs !== null && 
                                mysqli_num_rows($startMOOs)>0){

                                // Loop through the returned results
                                while ($startMOO=mysqli_fetch_array($startMOOs)){
                                    // Add the line to the GCode file
                                    fwrite($newGCodeFile, "M130(USB0/" . $startMOO["FileName"] . ")\r\n");
                                    fwrite($newGCodeFile, "M00\r\n");
                                }
                            }
                        }
                        // Check to see if this is a mandatory stop. 
                        else if (strpos($lines[$i],"M00") !== FALSE) {
                            // Determine if the command is an active command
                            if (isActiveCommand($lines[$i], "M00")===true){
                                // Increase the tally
                                $m00Number++;

                                // Create a query to get all of the setup MOOs for this setup
                                $sql='SELECT FileName FROM notes ' . 
                                     'WHERE AssociatedCategoryID='. $setupid . ' ' .
                                     'AND Category="SETUP_M00" ' . 
                                     'AND FileName LIKE "M00_' . $m00Number . '_%" ' . 
                                     'ORDER BY NoteOrder;';

                                // Run the query
                                $m00s = $db->queryDB($sql, $userRow, "modify_task_for_presentation Form occurance 11");

                                // Determine if there are any rows before attempting to loop through them
                                if ($m00s !== null && 
                                    mysqli_num_rows($m00s)>0){

                                    // Loop through the returned results
                                    while (($m00=mysqli_fetch_array($m00s))){
                                        // Add the line to the GCode file with M00 code
                                        fwrite($newGCodeFile, "\r\nM130(USB0/" . $m00["FileName"] . ")\r\n");
                                    }
                                }

                                // Now add the M00 line
                                fwrite($newGCodeFile, $lines[$i] . "\r\n");
                            }
                            else {
                                // Just add the line to the GCode
                                fwrite($newGCodeFile, $lines[$i] . "\r\n");
                            }
                        }
                        // Determine if we are on a tool change line
                        else if (strpos($lines[$i],"M6") !== FALSE) {
                            // Determine if the command is an active command
                            if (isActiveCommand($lines[$i], "M6")===true){
                                // Set a variable for tool found
                                $toolFoundOnLine=false;
                                
                                // Loop through the tools descriptions to determine what tool number the current tool is
                                foreach ($toolsInGCode as $toolInfo) {
                                    // Try to see if this tool description matches
                                    if (strpos($lines[$i], '(' . $toolInfo['ToolName'] . ')') !== FALSE){
                                        // Set the current tool number as this one found
                                        $currentNewToolNumber=$toolInfo['NewPosition'];

                                        // set that we found the tool
                                        $toolFoundOnLine=true;

                                        // break out of the loop, so we do not do a douple replace
                                        break;
                                    }
                                }      

                                // Determine if the tool was found
                                if ($toolFoundOnLine==true){
                                    // Get the position of the T and the position of the next space in order to get the old tool number
                                    $tPosition=strpos($lines[$i],"T")+1;
                                    $nextSpacePosition=strpos($lines[$i]," ", ($tPosition+1));
                                    $oldToolNumber=substr($lines[$i], $tPosition, ($nextSpacePosition-$tPosition));

                                    // Replace tool numbers on this line and add it to the code
                                    fwrite($newGCodeFile, str_replace(("T" . $oldToolNumber), ("T" . $currentNewToolNumber), $lines[$i]) . "\r\n");
                                }
                                else{
                                    // Throw an error that there was an unknown tool at this line
                                    return 'ABORT MODIFY (modify_task_for_present)::There is a tool that does not match the tools in the header of the GCode at line ' . $i . ' in GCode file "' . $gCodeName . '". Please check that file and determine the problem.';
                                }
                            }
                            else {
                                // Just add the line to the GCode
                                fwrite($newGCodeFile, $lines[$i] . "\r\n");
                            }
                        }
                        // Check to see if they are turning on tool length compensation
                        else if (strpos($lines[$i],("H" . $oldToolNumber . " ")) !== FALSE) {
                            // Replace tool numbers and add the line to the GCode
                            fwrite($newGCodeFile, str_replace(("H" . $oldToolNumber . " "), ("H" . $currentNewToolNumber . " "), $lines[$i]) . "\r\n");
                        }
                        // Check to see if they are turning on tool radius compensation
                        else if (strpos($lines[$i],("D" . $oldToolNumber . " ")) !== FALSE) {
                            // Replace tool numbers on this line and add the line to the GCode
                            fwrite($newGCodeFile, str_replace(("D" . $oldToolNumber . " "), ("D" . $currentNewToolNumber . " "), $lines[$i]) . "\r\n");
                        }
                        // Determine if there are any T numbers on this line
                        else if (strpos($lines[$i],("T" . $oldToolNumber . " ")) !== FALSE) {
                            // Replace tool numbers on this line and add it to the code
                            fwrite($newGCodeFile, str_replace(("T" . $oldToolNumber . " "), ("T" . $currentNewToolNumber . " "), $lines[$i]) . "\r\n");
                        }
                        else {
                            // Now add the line to the GCode
                            fwrite($newGCodeFile, $lines[$i] . "\r\n");
                        }
                    }

                    // Close the file 
                    fclose();
                }
            }
        } catch (Exception $exc) {
            // Create the error string to return back to the caller
            return 'ABORT MODIFY (modify_task_for_present)::There an uncaught error while modifying file for the tools.  The exception is: ' . $exc->getMessage() . '. Aborting...';
        }

        // Return what could be an error string
        return $errorString;
    }

    // Modify GCode to add M00 image references and change tooling witin the code
    function createAllModifiedGCodes($db, $userRow, $tid){
        // Set success to false until proven otherwise
        $errorString='';
        
        try {
            // Determine if the TID is one greater than 0
            if ($tid!=null && $tid>0){
                // Create a query to get the setups associated with this task
                $sql='SELECT MachiningSetupID, GCode, GCodeFileName ' . 
                     'FROM machiningsetups ' .
                     'WHERE TaskID=' . $tid . ';';
                
                // Run the query
                $currentSetups = $db->queryDB($sql, $userRow, "modify_task_for_presentation Form occurance 13");

                // Determine if there are any rows before attempting to loop through them
                if ($currentSetups !== null && 
                    mysqli_num_rows($currentSetups)>0){
                    // Loop through the returned results
                    while ($currentSetup=mysqli_fetch_array($currentSetups)){
                        // Get a variable to hold the current loop GCode
                        $gcode=$currentSetup["GCode"];
                        
                        // The tools should already have been setup correctly, so match what has changed to the GCode.
                        $errorString=createModifiedGCode($db, $userRow, $tid, $currentSetup["MachiningSetupID"], $gcode, $currentSetup["GCodeFileName"]);
                    }
                }
            }
        } 
        catch (Exception $exc) {
            // Create the error string to return back to the caller
            return 'ABORT MODIFY (modify_task_for_present)::There an uncaught error while modifying the GCode.  The exception is: ' . $exc->getMessage() . '. Aborting...';
        } 
        
        // Return what could be an error string
        return $errorString;
    }
    
    $db = new Database();
    $db->setupTmsDB();
    
    // Set defaults for the passed in variables
    $sessionID=-1;

    // check the passed in session ID
    if (isset($_GET['sessionID']) ){
        // get the passed in session ID
        $sessionID = $_GET['sessionID'];
    }

    // Attempt to log in with this user
    $currentUser = $db->getLoggedInSessionUser($sessionID);
    if (mysqli_num_rows($currentUser)!==1){
        echo 'ABORT MOVE (modify_task_for_present)::Your session has expired.  ' . 
             'Refresh the page before modifying the task for present.';
    }
    else {
        // Set defaults for the passed in variables
        $taskID=-1;
        $machineID=-1;
        $setupSheetOnly=1;

        // check the passed in value as to if they ONLY want setup sheep
        if (isset($_GET['setupSheetOnly']) ){
            // get the passed in setup sheet only parameter
            $setupSheetOnly = $_GET['setupSheetOnly'];
        }

        // check the passed in task ID
        if (isset($_GET['taskID']) ){
            // get the passed in task ID
            $taskID = $_GET['taskID'];
        }

        // check the passed in machine ID
        if (isset($_GET['machineID']) ){
            // get the passed in machine ID
            $machineID = $_GET['machineID'];
        }

        // Set the user row to nothing because we are not getting the current user
        $userRow = null;

        // Determine if the TID is one greater than 0
        if ($taskID!=null && $taskID>0){
            // Create a query to determine if this is a machine that we currently handle.
            $sql='SELECT m.Type ' . 
                 'FROM tasktomachinelinker ttml ' . 
                 'LEFT JOIN machines m ON ttml.MachineID=m.MachineID ' .
                 'WHERE TaskID=' . $taskID . ';';

            // Run the query
            $machineType = $db->queryDB($sql, $userRow, "modify_task_for_presentation Form occurance 14");

            // Get the assoc row
            $machineTypeAssocRow = $machineType->fetch_assoc();

            // Determine if there are any rows. 
            // TODO: Currently we are only handling Mills for the tools. Update this as we handle more.
            if ($machineTypeAssocRow["Type"] != null &&
                $machineTypeAssocRow["Type"] != 'MILL'){
                // Send no message back so we can continue processesing machines we do not handle yet, but do not mess up the database later
                $errorString = '';
            }
            else {
                // Attempt to adjust the tools.  Assign the error string the result.
                $errorString=modifyTaskToolsInDatabase($db, $userRow, $taskID, $machineID);

                // Determine if we are gtg onto the next phase
                if ($errorString==='') {
                    // Now we can modify the Tool Details in the table to match new tools
                    $errorString = modifyToolDetailsToMatchCurrent($db, $userRow, $taskID);
                }
                
                // Determine if we are gtg onto the next phase
                if ($errorString==='' && $setupSheetOnly!=1) {
                    // Now we can modify the GCode and check result
                    $errorString = createAllModifiedGCodes($db, $userRow, $taskID);
                }
            }
        }

        // return any error result
        echo $errorString;
    }
?>