<?php

//Initialize the XML parser
$parser=xml_parser_create();

//Function to use at the start of an element
function start($parser,$element_name,$element_attrs) {

  global $i,$elementos;

  switch($element_name) {
//   case "RESULTS":
//     echo "-- Lista de Teoremas --<br />";
//     break; 
//   case "RESULT":
//     echo "Teorema<br/>";
//     break; 
//   case "USERNAME":
//     echo "Utilizador: ";
//     break; 
//  case "THEONAME":
//    echo "Nome do Teorema: ";
//     break; 
//  case "DESCRIPTION":
//    $elementos[$i] = "\begin{geothm}<br/>";
//    break; 
//   case "SHORTDESCRIPTION":
//     echo "Txt: ";
//     break; 
//   case "OBSERVATIONS":
//     echo "obs: ";
//     break; 
  case "FIGCODE":
    $elementos[$i] = "";
    break; 
//   case "PROOFSCODE":
//     echo "Provas: <pre>";
//     break; 
//   case "BIBTEXENTRY":
//     echo "BibTeX: ";
//     break; 
  }
}

//Function to use at the end of an element
function stop($parser,$element_name) {

  global $i,$elementos;

  switch($element_name)    {
//   case "RESULT":
//     echo "<br/> - - - - - - - - <br/></br>";
//    break; 
//   case "USERNAME":
//     echo "<br/><br/> ";
//     break; 
//   case "THEONAME":
//     echo "<br/><br/>";
//     break; 
//  case "DESCRIPTION":
//      echo "</pre><br/><br/>";
//      break; 
//   case "SHORTDESCRIPTION":
//      echo "<br/><br/>";
//     break; 
//   case "OBSERVATIONS":
//      echo "<br/><br/>";
//      break; 
  case "FIGCODE":
    $elementos[$i].="";
    $i++;
    break; 
//   case "PROOFSCODE":
//      echo "</pre><br/><br/>";
//      break; 
//   case "BIBTEXENTRY":
//      echo "<br/><br/>";
//      break; 
  }
}

//Function to use when finding character data
function char($parser,$data)  {
  global $elementos,$i;
  //  echo $data;
  $elementos[$i].=$data;
}

//Specify element handler
xml_set_element_handler($parser,"start","stop");

//Specify data handler
xml_set_character_data_handler($parser,"char");

//Open XML file
$fp=fopen("geothms0301.xml","r");

//Read data
$i=0;
while ($data=fread($fp,4096))  {
  xml_parse($parser,$data,feof($fp)) or 
     die (sprintf("XML Error: %s at line %d", 
		  xml_error_string(xml_get_error_code($parser)),
		  xml_get_current_line_number($parser)));
 }

//echo "Elementos";
//print_r($elementos);

$aux=0;
while ($aux<=99) {
  //  print("<p>Nome Utilizador: ".$elementos[$aux]."</p>");
  //  $aux++;
  //  print("<p>Nome do Teorema: ".$elementos[$aux]."</p>");
  //  $aux++;

  // wait for 1 seconds
  usleep(1000000);

  $vNameCode = 'figure'.$aux.'.code';
  $vNameErr = 'figure'.$aux.'.err';
  $vNameErrors = 'figure'.$aux.'.errors';
  $vNamePIC = 'figure'.$aux.'.pic';
  $vNameTeX = 'figure'.$aux.'.tex';
  $vNameDVI = 'figure'.$aux.'.dvi';
  $vNamePS = 'figure'.$aux.'.ps';
  $vNameEPSI = 'figure'.$aux.'.epsi';
  $vNameJPG = 'figure'.$aux.'.jpg';


  ob_start();
  print $elementos[$aux]."\n";
  $texfile=fopen($vNameCode,"w");
  fwrite($texfile,ob_get_contents()); 
  fclose($texfile); 
  ob_end_clean(); 

  print("gclc $vNameCode $vNamePIC > $vNameErrors");

  ob_start();

  system("gclc $vNameCode $vNamePIC > $vNameErrors");
  system("grep Syntax $vNameErrors > $vNameErr");
  
  ob_end_clean(); 
  
  $filename = $vNameErr;
  
  // Vai verificar se houve erros ou não
  if  (file_exists($filename) and filesize($filename)>0) { // há erros 
    $file = fopen ($filename, "r");
    $contents = fread ($file, filesize ($filename));
    echo $contents;
    //system("rm figure.err");
    echo "<center>\n";
    echo "<br>There are errors in the figure's code.</b>\n";
    echo "</center>\n";
  }
  else { // Caso não haja erros vai processar a figura
    // Vai produzir o texto LaTeX referente à Figura
    ob_start();
    print "\documentclass[11pt]{article}\n";
    print "\usepackage{gclc}\n";
    print "\pagestyle{empty}\n";
    print "\begin{document}\n";
    print "\input{ $vNamePIC }\n";
    print "\end{document}\n";
    
    $texfile=fopen($vNameTeX,"w");
    fwrite($texfile,ob_get_contents()); 
    fclose($texfile); 
    
    system("latex $vNameTeX"); 
    system("dvips $vNameDVI -o $vNamePS"); 
    system("ps2epsi $vNamePS $vNameEPSI");
    system("convert $vNameEPSI $vNameJPG");
    ob_end_clean(); 
    
    // Agora vai produzir os ficheiros XML e SVG  - para já só para o GCLC
    
    $vNameXML = 'figure'.$aux.'.xml';
    $vNameXMLaux = 'figaux'.$aux.'.xml';
    
    $vNameSVG = 'figure'.$aux.'.svg';
    
    
    ob_start();   
    // primeiro cria o XML correspondente ao GCLC
    system("/usr/local/bin/gclc $vNameCode $vNameXMLaux -xml");
    system("/usr/local/bin/gclc $vNameCode $vNamePIC > $vNameErrors");
    // depois faz o "rendering" do XML em linguagem natural
    // modifica o estilo de saída para a Natural Language
    system("sed -e 's/GeoConsHTML.xsl/GeoConsNL.xsl/g' $vNameXMLaux > $vNameXML"); 
    // agora cria o SVG correspondente ao GCLC
    system("/usr/local/bin/gclc $vNameCode $vNameSVG -svg");    
  }
  ob_end_clean(); 
  
  
  // e agora a escrita do ficheiro referente à imagem
  $fpJPG   = fopen($vNameJPG, 'r');
  $contentJPG = fread($fpJPG, filesize($vNameJPG));
  $contentJPG = addslashes($contentJPG);
  fclose($fpJPG);
  
  // e do ficheiro XML
  $fpXML = fopen($vNameXML,'r');
  $contentXML = fread($fpXML,filesize($vNameXML));
  $contentXML = addslashes($contentXML);
  fclose($fpXML);
  
  // e do ficheiro SVG
  $fpSVG = fopen($vNameSVG,'r');
  $contentSVG = fread($fpSVG,filesize($vNameSVG));
  $contentSVG = addslashes($contentSVG);
  fclose($fpSVG);
  
  echo "<center><h3>Figura $aux</h3></center>";
  echo "<ul>";
  echo "<li>
         <span class='ficha'>Figure</span>
        </li>";
  echo "<li>
         <a href='$vNameJPG'>$vNameJPG</a>
        </li>";
  echo "<li>
         <span class='ficha'>
          Description of the construction in natural language
         </span>
        </li>";
  echo "<li>
         <a href='$vNameXML'>$vNameXML</a>
        </li>";
  echo "<li>
         <span class='ficha'>Figure in SVG format</span>
        </li>";
  echo "<li>
         <a href='$vNameSVG'>$vNameSVG</a>
        </li>\n";
  echo "</ul>";


  $aux++;
  //  print("<p>Descrição Breve: ".$elementos[$aux]."</p>");
  //  $aux++;
  //  print("<p>Observações: ".$elementos[$aux]."</p>");
  //  $aux++;
  //  print("<p>Código GCLC: <pre>".$elementos[$aux]."</pre></p>");
  //  $aux++;
  //  print("<p>Código GCLCprover: <pre>".$elementos[$aux]."</pre></p>");
  //  $aux++;
  //  print("<p>Referência BiBTeX: ".$elementos[$aux]."</p>");
  //  $aux++;
 }

  

//Free the XML parser
xml_parser_free($parser);

?>