#Gcordデータからcsvファイルへの変換プログラム試作2016/11/03 T.Inoue
#r1:csvデータに％および（　）で区々まれた注釈文を書き込まないように改訂：2018/02/05　T.Inoue
#r1はncdデータをcsvデータに変換して、そのままPIO_PC_Hostアプリで読み込める改良である。
#r2はz値の整数から小数点以下表示への改良中である。

$num = 000;
$add = 1;
$gcord = "G01";
$xtp = "0";
$ytp = "0";
$ztp = "0";

while ( <STDIN> ) {
	if ( /^[O\d]/ or /^$/ ) {	#除外は O % ( または　空行
		print;
	}
	if(/ ^"%" /){
		 print;
	}
	if(/ [^\(] /){
		 print;
	}	
	else{		
		printf "%03d ", $num;	#番号を振る
		$num += $add;
			print ",";
	
#17 アルファベットに続く数字と-数字と小数点をマッチ
		if (/^[GM]\d+/){
			($pre, $_) = ($&, $');
			if($pre =~ /^(.)(..)/){
			print "$&";
			print ",";
			}
		}
		elsif (/^S\d+/){
			($pre, $_) = ($&, $');
			if(/M\d+/){
			($pre, $_) = ($&, $');
			if($pre =~ /^(.)(..)/){
			print "$&";
			print ",";
			}	
			}
			else{
			print "$&";
			print ",";
			}
		}	
		else{
		print $gcord. ",";
		}
	
#37 X 
		if ((/X\d+\.\d+/)||(/X\d+/)){	
			($pre, $_) = ($&, $');
			if($pre =~ /^(.)(......|.....|....|...|..|.)/){
			print "$2"; $xtp = $2;		
			print ",";
			}
		}
		elsif((/X-\d+\.\d+/)||(/X-\d+/)){
			($pre, $_) = ($&, $');
			if($pre =~ /^(.)(.......|......|.....|....|...|..|.)/){
			print "$2"; $xtp = $2;		
			print ",";
			}
		}
		else{
		print "$xtp"; print ",";
		}
#55 Y
		if ((/Y\d+\.\d+/)||(/Y\d+/)){	
			($pre, $_) = ($&, $');
			if($pre =~ /^(.)(......|.....|....|...|..|.)/){
			print "$2"; $ytp = $2;		
			print ",";
			}
		}
		elsif((/Y-\d+\.\d+/)||(/Y-\d+/)){
			($pre, $_) = ($&, $');
			if($pre =~ /^(.)(.......|......|.....|....|...|..|.)/){
			print "$2"; $ytp = $2;		
			print ",";
			}
		}
		else{
		print "$ytp"; print ",";
		}
#73 Z		
		if ((/Z\d+\.\d+/)||(/Z\d+/)){
			($pre, $_) = ($&, $');
			if($pre =~ /^(.)(......|.....|....|...|..|.)/){
			print "$2"; $ztp = $2;		
			print ",";
			}
		}
		elsif((/Z-\d+\.\d+/)||(/Z-\d+/)){
			($pre, $_) = ($&, $');
			if($pre =~ /^(.)(.......|......|.....|....|...|..|.)/){
			print "$2"; $ztp = $2;		
			print ",";
			}
		}
		else{
		print "$ztp"; print ",";
		}
#91 R
		if (/R\d+/){
			($pre, $_) = ($&, $');
			if($pre =~ /^(.)(...|..|.)/){
			print "$2";		
			print ",";
			}
		}
		else{
		print "0,";
		}
#102 I
		if ((/I\d+\.\d+/)||(/I\d+/)){
			($pre, $_) = ($&, $');
			if($pre =~ /^(.)(.....|....|...|..|.)/){
			print "$2";		
			print ",";
			}
		}
		elsif ((/I-\d+\.\d+/)||(/I-\d+/)){
			($pre, $_) = ($&, $');
			if($pre =~ /^(.)(......|.....|....|...|..)/){
			print "$2";		
			print ",";
			}
		}
		else{
		print "0,";
		}
#120 J
		if ((/J\d+\.\d+/)||(/J\d+/)){
			($pre, $_) = ($&, $');
			if($pre =~ /^(.)(.....|....|...|..|.)/){
			print "$2";		
			print ",";
			}
		}
		elsif ((/J-\d+\.\d+/)||(/J-\d+/)){
			($pre, $_) = ($&, $');
			if($pre =~ /^(.)(......|.....|....|...|..)/){
			print "$2";		
			print ",";
			}
		}
		else{
		print "0,";
		}
	print "\n";
	}
}
