#!/usr/bin/env php
<?php
	$version="1.0";
	
	$laser_on = "M67 E0 Q100 (turn on laser at 100% on next movement)\r\n";
	
	$laser_off = "M68 E0 Q0 (turn off laser immediately)\r\n";
	
	$feed_rate = "F60.0";
	
	$gcode = "";
	$file_path = $_SERVER["argv"][1];
	$handle = @fopen($file_path, "r");
	$handle2 = @fopen("./temp_ngc", "w");
	
	if($handle)
	{
		while(($line = fgets($handle)) != false)
		{
			$gcode .= laserify($line);
		}
	}
	echo $gcode;
	
	fclose($handle);
	fclose($handle2);




	
		
	
	function laserify($gcode)
	{
		global $laser_on, $laser_off, $feed_rate;
		
		// capitalize all words
		$gcode = strtoupper($gcode);
		// strip whitespace
		$gcode = str_replace(' ', '', $gcode);
		// remove M6
		$gcode = str_replace("M6", "(removed M6)", $gcode);
		// remove M3
		$gcode = str_replace("M3", "(removed M3)", $gcode);
		// remove M4
		$gcode = str_replace("M4", "(removed M4)", $gcode);
		
		// S words
		//$preg = '~[S][0-9]+?:[.]?:[0-9]+~';
		$preg = '/S\d*\.?\d*/';
		preg_match($preg, $gcode, $matches);
		$gcode = preg_replace($preg, "(removed " . @$matches[0] . ")", $gcode);
		
		// T words
		$preg = '~T[0-9]+~';
		preg_match($preg, $gcode, $matches);
		$gcode = preg_replace($preg, "(removed " . @$matches[0] . ")", $gcode);
		
		// F words
		$preg = '/F\d*\.?\d*/';
		preg_match($preg, $gcode, $matches);
		$gcode = preg_replace($preg, $feed_rate, $gcode);
		
		// must do the Z- moves first
		
		$preg = '/Z-\d*[\.]?\d*/';
		$preg2 = '/Z\d*\.?\d*/';
		if(preg_match($preg, $gcode, $matches)) // Z- moves
		{
			$gcode = preg_replace($preg, $laser_on . " (removed " . @$matches[0] . ")", $gcode);
			$gcode = $laser_on;
		}
		elseif(preg_match($preg2, $gcode, $matches)) // Z+ moves
		{
			$gcode = preg_replace($preg2, $laser_off, $gcode);
		}
		
				
		// add whitespace between words
		$gcode = preg_replace('/[A-Z]/', " $0", $gcode);
		
		
		return $gcode;
	}
	
	function check_array($array, $string)
	{
		foreach ($array as $value)
		{
    			if(strpos($string,$value))
			{
        			return $value;
    			}

		}
		return false;
	}
	


?>
