<?php
 // tr_mapping.php
 // RJM Programming
 // March, 2017
 // Global substitution in two parts:
 //    1) From filespec create CSV mapping (tr_mapping.csv) for second part via section tags containing role="paragraph" and old_label="[OldLabel]" and label="[NewLabel]" all before section tag end
 //    2) From input index file and CSV above create Korn Shell (ksh) file that runs ... ksh -x tr_mapping.ksh ... to update for new index file (but backup yourself first)

 $csvout="";
 $kshout="#!/bin/ksh\n";
 $delim="";
 
 $filespec="COMM.PINSW*.xml";
 if (isset($_GET['filespec'])) $filespec=urldecode($_GET['filespec']);
 $indexfilecalled="COMM.PIN~INDEX.xml";
 if (isset($_GET['index'])) $indexfilecalled=urldecode($_GET['index']);
 
 foreach (glob($filespec) as $filename) {
   $cont=@file_get_contents($filename);
   $sections=explode("<section ", $cont);
   for ($i=1; $i<sizeof($sections); $i++) {
     $thisbits=explode(">", $sections[$i]);
     $thebit="  " . $thisbits[0];
     if (strpos($thebit, ' old_label="') !== false && strpos($thebit, ' label="') !== false &&  strpos($thebit, ' role="paragraph"') !== false) {
      if (str_replace("]","\\]",explode('"',explode(' old_label="', $thebit)[1])[0]) != "") {
        $csvout.=$delim . "," . explode('"',explode(' old_label="', $thebit)[1])[0] . ",," . explode('"',explode(' label="', $thebit)[1])[0];
        $kshout.=$delim . "cat " . $indexfilecalled . " | sed '/\\" . str_replace("]","\\]",explode('"',explode(' old_label="', $thebit)[1])[0]) . "/s//\\" . str_replace("]","\\]",explode('"',explode(' label="', $thebit)[1])[0]) . "/g' > " . str_replace(".XML",".XXX",str_replace(".xml",".xxx",$indexfilecalled)) . " ; rm -f " . $indexfilecalled . " ; cat " . str_replace(".XML",".XXX",str_replace(".xml",".xxx",$indexfilecalled)) . " > " . $indexfilecalled . " ; ";
		$delim="\n";
	  }
     }
   }
 }
 
 file_put_contents("tr_mapping.csv", $csvout); 
 file_put_contents("tr_mapping.ksh", $kshout);
 
 ?>