#!/usr/bin/php
<?php
/*
 *      po2php
 *            
 *  Improved from http://www.rogerdudler.com/?p=342     
 */
 if (!is_file  ($argv[1]))
 {
	 print "El primer argumento debe ser un archivo po
	 
	 forma de uso po2php archivo.po
";

	 exit (1);
 }
 $valid=strpos ($argv[1],".po");
 if ($valid == false )
 {
	print "Se esperaba un archivo .po";
	exit (3);
 }
 $phpfile=str_replace (".po",".php",$argv[1]);
 $pofile=file ($argv[1]);
 $translations = array();
 $current = null;
 $line=current ($pofile);
 do
 {
    if (substr($line,0,5) == 'msgid') 
    {
        $current = trim (substr(trim(substr($line,5)),1,-1));
        next ($pofile);
        $line=current ($pofile);
        while (strlen ($line)>1 && substr($line,0,6) != 'msgstr')// For multi line msgid
        {
			$current.=substr (trim ($line),1,-1);
			next ($pofile);
			$line=current ($pofile);
		}
    }
    if (substr($line,0,6) == 'msgstr' && $current != "") 
    {
        //print "msgid $current\n";
        $translations[$current] = trim (substr(trim(substr($line,6)),1,-1));
        next ($pofile);
        $line=current ($pofile);
        while (strlen ($line)>1) //For multi line msgstr
        {
			$translations[$current].=substr (trim ($line),1,-1);
			next ($pofile);
			$line=current ($pofile);
		}
		//print "msgstr ".$translations[$current]."\n";
    }
  next ($pofile);
 }while ($line=current ($pofile));
 $destfile=fopen ($phpfile,"w");
 if ($destfile != NULL )
 {
   fwrite ($destfile,"<?php\n\n");
   foreach ($translations as $msgid => $msgstr) 
   {
    fwrite ($destfile,"\$Text['" . $msgid . "'] = '" . 
    addslashes ($msgstr).
    "';\n");
   }
   fwrite ($destfile,"\n?>");
  }
  else
  {
	  print "No se pudo crear ".$phpfile;
	  exit (2);
  }
  fclose ($destfile);
  print "Creado ".$phpfile."
";
  exit (0);
?>
