#!/usr/bin/perl

#   Copyright (C) 2003 J-P Branchard <Jean-Pierr.Branchard@ac-grenoble.fr>
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 of the License, or
#   (at your option) any later version.
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#   You should have received a copy of the GNU General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

#-----------------------------------
# variables utilisées dans le script
#-----------------------------------
# nombre de lignes et de colonnes du tableur
my $nb_col=5;
my $nb_line=13;
my $last_col=$nb_col-1;
my $last_line=$nb_line-1;
my @cell;
my $spread="";
my $spread_changed=0;
my $spread_index=-1;
my $lt="&lt;";
my $input_name="Calculer";
my $ulimit=1;			#temps de calcul max : 1 seconde
my $delay_max=3600;		# durée de survie d'une archive. Le fichier est libéré si pas écrit pendant 3600s
my $num_archive=-1;		# numéro du fichier d'archive
my $langue="fr";
my $delay=0;
my $param="";
my $ans;
my $trois_d=0;
my $complexes="off";
my $complexes_state="off";
my $command_complexes_on = "\"complex_mode:=1\"";
my $command_complexes_off ="\"complex_mode:=0\"";
my $option=" -t -l -m ";
my $command_line;
my $script;
my $char;
my $separateur="separateur";
my $focus_prog=0;
my $mml;
my $nb_frames=1;
my $main_frame_side=1;
my $main_frame="help";
my $second_frame="histo";
my $xmin=-5;
my $xmax=5;
my $ymin=-5;
my $ymax=5;
my $color="black";
my $prev_color="black";
my $replot=0;
my $frame_url="";
#-------------------------------------------------------------------------
# Autodétection des adresses
#-------------------------------------------------------------------------

$url=($ENV{'REQUEST_URI'} || $ENV{'SCRIPT_NAME'});
#$url=($ENV{'SCRIPT_NAME'});
$url=~ s/\?.*//gs;
$url='http://'.($ENV{'SERVER_NAME'} || $ENV{'HTTP_HOST'}).$url;
$pl_directory=$url;
$pl_directory=~ s/giac.pl//g;
$html_directory=$pl_directory;
$html_directory=~ s/cgi-bin\///g;
$png_directory=$html_directory."png/";
$exe_directory=`pwd`."/";
$exe_directory=~ s/\n//g;
#$exe_directory= $ENV{'DOCUMENT_ROOT'}."/";
#$exe_directory=~ s/html/cgi-bin/g;
#$exe_directory=$exe_directory."giac_online/";
#$make_png= "cd archive ; chmod 644 casgraph* ../../../html/giac_online/png/casgraph*;latex casgraph.tex ; dvips  casgraph -o casgraph.ps -T 12cm,12cm -O -3.5cm,-6cm ; pstopnm casgraph.ps ; pnmtopng casgraph001.ppm > ../../../html/giac_online/png/casgraph";
if ($html_directory eq "http://127.0.0.1/giac_online/" || $html_directory eq "http://localhost.localdomain/giac_online/" ){
  $doc_directory="/home/jp/giac-0.3.0/doc/fr/casflan/index.html";
  $xsl= "<?xml-stylesheet type=\"application/xsl\" href=\"".$html_directory."pmathml.xsl\"?>\n";
} else {
  $doc_directory="http://www-fourier.ujf-grenoble.fr/~parisse/casflan/casflan.html";
  $xsl= "<?xml-stylesheet type=\"text/xsl\" href=\"".$html_directory."pmathml.xsl\"?>\n";
}
#----------------------------------------------------------------------------

#-----------------
# déclarations xml
#-----------------
sub print_xml_preamble{
  my $focus=$_[0];
  print "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n";
  print $xsl;
  print "<!DOCTYPE MMLEntities [\n";
  print " <!ENTITY reals \"&#x0211D;\">\n";
  print " <!ENTITY complexes \"&#x02102;\" >\n";
  print " <!ENTITY int \"&#8747;\">\n";
  print "<!ENTITY Integral \"&#x0222B;\">\n";
  print "<!ENTITY Sigma \"&#931;\">\n";
  print " <!ENTITY part \"&#8706;\" >\n";
  print "<!ENTITY nbsp \"&#160;\" >\n";
  # print "<!ENTITY amp \"&#38;\" >\n";#plante ie
  print "<!ENTITY quot \"&#34;\" >\n";
  print "<!ENTITY rarr \"&#8594;\" >\n";
  print "<!ENTITY VerticalBar \"&#x02223;\">\n";
  print "<!ENTITY lsqb \"&#x0005B;\" >\n";
  print "<!ENTITY deg  \"&#x000B0;\" >\n";
  print "<!ENTITY infin    \"&#8734;\" >\n";
  print "<!ENTITY InvisibleTimes \"&#x02062;\" >\n";
  print "<!ENTITY pi \"&#960;\" >\n";
  #print "<!ENTITY lt \"&#x26;&#x0003C;\" >\n"; #plante ie
  print "<!ENTITY le \"&#x02264;\">\n";
  print "<!ENTITY gt \"&#62;\" >\n";
  print "<!ENTITY ge \"&#x02265;\" >\n";
  print "]>\n";
  #print "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN\"\n";
  #print "      \"http://www.w3.org/TR/MathML2/dtd/xhtml-math11-f.dtd\">\n";
  #print " [<!ENTITY mathml \"http://www.w3.org/1998/Math/MathML\">]>\n";
  #print "<?xml-stylesheet type=\"text/xsl\" href=\"pmathml.xsl\"?>\n";
  print "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";
  print "<head>\n";
  print  "<title>Giac en ligne</title>\n";
  print "<link  rel=\"stylesheet\" type=\"text/css\" href=\""
    .$html_directory."giac.css\" />\n";
 # print "<link  rel=\"stylesheet\" type=\"text/css\" href=\"../../giac_online/giac.css\" />\n";
  print "<script type=\"text/javascript\" src=\"".$html_directory."giac_svg.js\"></script>\n";
 # print "<script type=\"text/javascript\" src=\"../../giac_online/giac_svg.js\"></script>\n";
  print "</head>\n";
  print "<body onload=\"init_frames($focus), selectionne(), scroll_down() \">\n";# calcule_png(),
}


sub print_xml_end{
  print "<script>resize_window();</script>\n";
  print "</body>";
  print "</html>";
}

$mathml_preamble = "<math mode=\"display\" xmlns=\"http://www.w3.org/1998/Math/MathML\">\n";
$mathml_end = "</math>";
# fin des déclarations xml

#----------------------------------
# subroutine interface avec irem.cc
#----------------------------------
sub cas {
  my $local_cas=$_[0];
  my $local_option=$_[1];
  my $local_command_line=$_[2];
  my $archive=$_[3];
  my $mml;
  # $num_archive et $print_mode sont initialisés dans le programme principal
  # on réinitialise $num_archive pour l'impression des feuilles de calcul
  if ($archive ne "archive") {
    $print_mode= ">";
  }
  # gestion des archives texte, latex et mathml
  open(ARCHIVE_TXT, $print_mode."archive/".$archive."_txt".$num_archive);
  open(ARCHIVE_TEX, $print_mode."archive/".$archive."_tex".$num_archive);
  open(ARCHIVE_MML, $print_mode."archive/".$archive."_mml".$num_archive);
  open(CAS, "cd archive ;".$local_cas.$local_option.$local_command_line."; cd ..  |");
#print  "cd archive ; ".$local_cas.$local_option.$local_command_line."; cd ..  |";
  my $plot_flag=0;
  FORCAS : for ($i=0; <CAS>;) {	
    $_=~ s/\n//g;
    if ($i==0) {
      if ($_ ne "separateur"){
	$ans= $_;
      }
      print ARCHIVE_TXT $_."\n"; #expression non évaluée
    } elsif ($i==1) {
      if ($plot==0) {
	if ($_ ne "separateur"){
	  $ans= $_;
	}
	print ARCHIVE_TXT $_."\n"; #expression évaluée
	$ans =~ s/\n//g;
	$ans=~ s/\"/&quot;/g;
	#elimination des caractères 0 à 31 qui plantent le navigateur (code peu satisfaisant)
	for ($j=0 ; $j<32 ; $j++) {
	  $char=chr($j);
	  $ans=~ s/$char/,undef/g;
	}
      } elsif ($plot_flag==0) {
	print ARCHIVE_TXT "Plotted\n";
	print ARCHIVE_TXT $separateur."\n";
	$plot_flag=1;		#sinon on y passe 2 fois
	$ans="plotted";
      }	
    } elsif ($i<4) {
      print ARCHIVE_TEX $_."\n";
    } elsif ($_ eq "3d") {
      $trois_d=1;
      last FORCAS;
    } elsif ($i==5 && $plot==1 && $archive ne "spread_archive") {
      print ARCHIVE_MML "<mtext>Plotted</mtext>\n";
      $i++
    } else {
      $mml=$_;
      $mml=~ s/&&/&amp;&amp;/g;
      print ARCHIVE_MML $mml."\n";
    }
    if ($_ eq $separateur) {
      $i++;
    }
  }
  close ARCHIVE_TXT;
  close ARCHIVE_TEX;
  close ARCHIVE_MML;
  close(CAS);
}

#------------------------------------------------------
# subroutine d'impression xhtml de la feuille de calcul
#------------------------------------------------------
sub print_spreadsheet{
  open(SPREAD_MML, "<".$exe_directory."archive/spread_archive_mml".$num_archive);
  for (;<SPREAD_MML>;) {
    $mml=$_;
    $mml=~ s/\n//g;
    if ($mml ne $separateur) {
      print "<p align=\"center\">".$mml."</p>\n";
    }
  }
  close(SPREAD_MML);
}

#-----------------------------------------
#Enleve les car indésirables dans une url
#-----------------------------------------
sub url_arg{
  $arg=shift(@_);
  $arg=~s/\%/%25/g;
  $arg=~s/\+/%2B/g;
  $arg=~s/\=/%3D/g;
  $arg=~s/\?/%3F/g;
  $arg=~s/\&/%26/g;
  return $arg;
}

# subroutine encore non utilisée pose des problèmes
#sub sans_car_speciaux {
#  my $string=shift(@_);
#  #élimination des retours chariots
#  $string =~ s/\n//g;
#  #remplacemnet des caract spéciaux par leur code html
#  #  $string =~ s/\&/\&\#38\;/g;
#  $string =~ s/\"/\&quot\;/g;
#  # $string =~ s/</&\#x26\;/g;
#  # $string =~ s/>/&gt\;/g;
#  $string =~ s/´/\&acute\;/g;
#  #elimination des caractères 0 à 31 qui plantent le navigateur (code peu satisfaisant)
#  for ($i=0 ; $i<32 ; $i++) {
#    $a=chr($i);
#    $string=~ s/$a/,undef/g;
#  }
#  #  print $string;
#  return $string;
#}

#-----------------------------------------------
#affiche historique mathml
#-----------------------------------------------
sub hist_mathml{

  my @command;
  my $com;
  open(ARCHIVE_TXT, "<".$exe_directory."archive/archive_txt".$num_archive);
  $i=0;
  $ligne="";
  for (;<ARCHIVE_TXT>;) {
    $com=$_;
    $com=~ s/\n//g;
    $com=~ s/</&lt;/g;
    $com=~ s/&&/&amp;&amp;/g;
    if ($com eq $separateur) {
      $i=$i+1;
      $i=$i%2;
      if ($i==1){
	push (@command,$ligne);
      }
      $ligne="";
    }
    elsif ($i==0){
      $ligne.=$com."<br />";
    }
  }
  close ARCHIVE_TXT;
  my $mml;
  my $k;

  open(ARCHIVE_MML, "<".$exe_directory."archive/archive_mml".$num_archive);
  $i=0;
  $k=0;
  $l=0;
  for (;<ARCHIVE_MML>;) {
    $mml=$_;
    $mml=~s/\n//g;
    if ($mml ne $separateur) {
      #elimination des caractères 0 à 31 qui plantent le navigateur
      for ($j=0 ; $j<32 ; $j++) {
	$char=chr($j);
	$mml=~ s/$char/,undef/g;
      }
      if ($l==0) {
	print "<p  style=\"color:red;\">\n".$k." : ".$command[$k]."</p>\n";
	$k++;
	print  "<p>".$mathml_preamble."<mstyle mathcolor=\"red\">\n";
      } else {
	print "<p>".$mathml_preamble."<mstyle  mathcolor=\"green\">\n";
      }
      print $mml;
      print "</mstyle></math></p>\n";
      #affichage éventuel de la feuille de calcul
      if ($k-1==$spread_index && $l!=0) {
	print_spreadsheet();
      }
    } else {
      $l=$l+1;
      $l=$l%2;
    }
  }
  my $last_history_index=$k;
  if ($k==0 && $spread_index!=-1){
    print_spreadsheet();
  }
  close ARCHIVE_MML;

}

#---------------------------------------------------
# Récupération des données du formulaire s'il y en a
#---------------------------------------------------
# les donnees sont envoyees par methode PST
# donc on recupere les donnees dans STDIN
read(STDIN,$buffer,$ENV{'CONTENT_LENGTH'});
#$buffer=$ENV{"QUERY_STRING"};

# on split la chaine de donnees en des paires name=value
local(@champs) = split(/&/, $buffer);

# recuperation et mise en forme des donnees
# on parcourt la liste des paires name=value

foreach $i (0 .. $#champs) {
  # On convertit les plus en espaces
  $champs[$i] =~ s/\+/ /g;
    
  # On separe chaque champ en une cle et sa valeur
  ($key, $val) = split(/=/,$champs[$i],2); 
    
  # On convertit les %XX de leur valeur hexadecimale en alphanumerique
  $key =~ s/%(..)/pack("c",hex($1))/ge;
  $val =~ s/%(..)/pack("c",hex($1))/ge;

  # on initialise les variables
  if ($key eq "langue") {
    $langue =$val;
  }
  if ($key eq "num_archive" && $val ne "") {
    $num_archive=$val;
  }
  if ($key eq "complexes") {
    $complexes =$val;
  }
 if ($key eq "complexes_state") {
    $complexes_state =$val;
  }
  if ($key eq "giac") {
    $param =$val;
    $param=~s/Â²/^2/g;
    $param=~s/²/^2/g;
    $param =~ s/\"/\\\"/g;
  }
  if ($key eq "spread") {
    $spread =$val;
    $spread=~s/²/^2/g;
    $spread =~ s/\"/\\\"/g;
  }
  if ($key eq "spread_changed") {
    $spread_changed =$val;
  }
  if ($key eq "spread_index") {
    $spread_index =$val;
  }
  if ($key eq "script") {
    $script =$val;
    $script =~ s/\"/\\\"/g;
  }
  if ($key eq "ans") {
    $ans="(".$val.")";
  }
  if ($key eq "calculer") {
    $input_name="Calculer";
  }
 if ($key eq "hist_mathml") {
    $input_name="Historique mathml";
  }
  if ($key eq "hist_latex") {
    $input_name="Historique LATEX";
  }
  if ($key eq "hist_texte") {
    $input_name="Historique texte";
  }
  if ($key eq "focus_prog") {
    $focus_prog=$val;
  }
  if ($key eq "nb_frames") {
    $nb_frames=$val;
  }
  if ($key eq "main_frame_side") {
    $main_frame_side=$val;
  }
  if ($key eq "main_frame") {
    $main_frame=$val;
  }
  if ($key eq "second_frame") {
    $second_frame=$val;
  }
  if ($key eq "xmin"){
    $xmin=$val;
  }
  if ($key eq "xmax"){
    $xmax=$val;
  }
  if ($key eq "ymin"){
    $ymin=$val;
  }
  if ($key eq "ymax"){
    $ymax=$val;
  }
  if ($key eq "new_xmin"){
    $new_xmin=$val;
  }
  if ($key eq "new_xmax"){
    $new_xmax=$val;
  }
  if ($key eq "new_ymin"){
    $new_ymin=$val;
  }
  if ($key eq "new_ymax"){
    $new_ymax=$val;
  }
  if ($key eq "couleur"){
    $color=$val;
  }
  if ($key eq "prev_color"){
    $prev_color=$val;
  }
  if ($key eq "focus_svg"){
    $focus_svg=$val;
  }
  if ($key eq "replot"){
    $replot=$val;
  }
  if ($key eq "frame_url"){
    $frame_url=$val;
  }
}

if ($color ne $prev_color && $param ne ""){
  $param="couleur($color);".$param;
}

if ($replot == 1 && $new_xmin<$new_xmax && $new_ymin<$new_ymax){
  $xmax=$new_xmax;
  $xmin=$new_xmin;
  $ymax=$new_ymax;
  $ymin=$new_ymin;
} else {
$replot=0;
}

# Détermine le type du document -------------------------------------------
if ($input_name eq "Historique LATEX" || $input_name eq "Historique texte") {
  print "Content-type: text/\n\n";
} else {
  print "Content-type: text/xml \n\n";
}
#print "**".$color."**".$prev_color."**\n";

#----------------------------------------------
# Gestion des fichiers d'archives sur le serveur
#----------------------------------------------
if ($num_archive==-1) {
  $print_mode= ">";
} else {
  $print_mode= ">>";
}
if ($num_archive==-1) {
  #cela veut dire qu'on n'a pas encore d'archive
  #Recherche d'un numero d'archive disponible
  for ($i=1 ;$i<100 ; $i++) {
    $num_archive=$i;
    $archive="archive/archive".$i;
    @stat_archive=stat($archive);
    if (stat($archive)) {
      @stat_archive=stat($archive);
      $date=$stat_archive[9]+0;	#date derniere modif
      $delay=time-$date;
      if ($delay-$delay_max>0) {
	last;
      }
    } else {
      last;
    }
  }
  # on a recyclé une ancienne archive
  $option.=" -i ";		#pour réinitialiser l'archive
  $archive="archive/*".$i;
  open(EFFACE, "rm -f ".$archive." archive/gd".$i.".gif |");
  close (EFFACE);
}
# on fabrique une nouvelle archive giac
$archive = "archive".$num_archive;

#  --------------------------
#    Traitement des données
#    ----------------------
if ($input_name eq "Calculer") {
  if ($script ne "") {
    $script =~ s/&quot;/\\\"/g;
  }
  if ($param ne "") {
    $param =~ s/ans\(\)/$ans/g;
    $param =~ s/&quot;/\\\"/g;
    $command_line="\"".$param."\"";
  }
}

if ($param =~ m/plot/i) {
  $plot=1;
  $option.=" -plot ";
} else {
  $plot=0;
}


$cas="ulimit -t ".$ulimit." ; ".$exe_directory."./cas2html_ar"." 2>&1 \"".$num_archive."\"";
if ($complexes eq "on" && $complexes_state eq "off") {
  cas($cas,$option,$command_complexes_on,"archive");
  $complexes_state="on";
} elsif ($complexes eq "off" && $complexes_state eq "on"){
  cas($cas,$option,$command_complexes_off,"archive");
  $complexes_state="off";
}


open (CHMOD,"chmod a+wr archive/session3d* archive/gd* |");
close CHMOD;



if ($script ne "" && $focus_prog==1 ) {
  cas ($cas,$option," \"".$script."\"","archive");
}

if ($param ne "") {
  cas($cas,$option,$command_line,"archive");
}


# calcul du tableur

  $spread=~ s/\$/\\\$/g;
  $spread=~ s/\"/\'/g;
  $spread=~ s/é/e/g;
  $spread=~ s/è/e/g;
  $spread=~ s/ê/e/g;
  $spread=~ s/à/a/g;
  $spread=~ s/â/a/g;
  @cell=split "end_cell",$spread;
if ($spread ne "" && $spread_changed==1) {
  # construction de l'objet spreadsheet à passer à GIAC
  my $spreadsheet="spreadsheet[";
  for ($i=0 ; $i<$nb_line ; $i++) {
    $spreadsheet.="[";
    for ($j=0 ; $j<$nb_col ; $j++) {
      $k=$i*$nb_col+$j;
      $spreadsheet.="[".$cell[$k].",1,0]";
      $cell[$k]=~ s/\\\$/\$/g;
      if ($j<$last_col) {
	$spreadsheet.=",";
      }
    }
    if ($i<$last_line) {
      $spreadsheet.="],";
    } else {
      $spreadsheet.="]";
    }
  }
  $spreadsheet.="]";
  $option.=" -S ";		#pour avoir spread2tex et spread2mathml
  cas($cas,$option," \"".$spreadsheet."\"","spread_archive");
}



# élimination de caractères gênants
if ($param ne "") {
  $param =~ s/\\\"/&quot\;/g;
  $param =~ s/&/&\#38\;/g;
  $param =~ s/</&\#x0003C\;/g;
}
if ($ans eq "()"){
  $ans="";
}

# on teste la présence d'une sortie gif
#my $png_output=0;
$archive="archive/gd".$num_archive.".gif";
#print $archive;
#if (stat($archive) && $nb_frames==1) {
if ($param ne "") {
  $nb_frames=2;
  $main_frame="histo";
#print $ans;
  if ( $ans=~m/plot/i || $ans=~m/pnt/i){
    $second_frame="svg";
  } elsif($ans=~m/spread/i){
    $second_frame="tab";
  } elsif ($focus_prog==1) {
    $second_frame="progr";
  } else {
    $second_frame="help";
  }
  $main_frame_side="left";
}

# commnande png (ou gif)
if ($trois_d==0){
$png_output="giac_gif_output.pl?num_archive=".$num_archive."&amp;xmin=".$xmin."&amp;xmax=".$xmax."&amp;ymin=".$ymin."&amp;ymax=".$ymax."&amp;color=".$color."&amp;replot=".url_arg($replot)."&amp;command_gif=".url_arg($param);
} else {
$png_output="giac_gif_output.pl?xmin=".$xmin."&amp;xmax=".$xmax."&amp;ymin=".$ymin."&amp;ymax=".$ymax."&amp;trois_d=1&amp;command_gif=".url_arg($param);
}


# ---------------- Affichage de la page xhtml ----------------
@langage=("en","fr");
%compute=();
$compute{en}="Compute";
$compute{fr}="Calculer";
%help=();
$help{en}="Help";
$help{fr}="Aide";
%history=();
$history{fr}="Historique";
$history{en}="History";
%program=();
$program{en}="Program";
$program{fr}="Programmer";
%table=();
$table{en}="Table";
$table{fr}="Tableur";
%geo=();
$geo{en}="Geometry";
$geo{fr}="Géométrie";
%text=();
$text{en}="Text";
$text{fr}="Texte";
%latex=();
$latex{en}="Latex";
$latex{fr}="Latex";
%doc=();
$doc{en}="../../giac_online/doc_en.html";
$doc{fr}="../../giac_online/doc_fr.html";
%title=();
$title{en}="<b>XCAS on line</b>";
$title{fr}="<b>XCAS en ligne</b>";
%title_language=();
$title_language{en}="language : ";
$title_language{fr}="langue : ";
%instruction=();
$instruction{fr}="Entrez ici une instruction :";
$instruction{en}="Type your instruction here :";
%copy=();
$copy{fr}="Copier";
$copy{en}="Copy";
%paste=();
$paste{fr}="Coller";
$paste{en}="Paste";
%fill_bottom=();
$fill_bottom{en}="Fill to bottom";
$fill_bottom{fr}="Remplir en bas";
%fill_right=();
$fill_right{en}="Fill to right";
$fill_right{fr}="Remplir à droite";
%window=();
$window{en}="1 window";
$window{fr}="1 fenêtre";
%window2=();
$window2{en}="2 windows";
$window2{fr}="2 fenêtres";
%couleur=();
$couleur{en}="Color";
$couleur{fr}="Couleur";
%black=();
$black{en}="black";
$black{fr}="noir";
%red=();
$red{en}="red";
$red{fr}="rouge";
%blue=();
$blue{en}="blue";
$blue{fr}="bleu";
%green=();
$green{en}="green";
$green{fr}="vert";
%yellow=();
$yellow{en}="yellow";
$yellow{fr}="jaune";
%rezize=();
$resize{en}="Resize and erase";
$resize{fr}="Redimensionner et effacer";
%setup=();
$setup{en}="Do you want resize the window ? This will erase the graphic data !";
$setup{fr}="Voulez vous redimensionner la fenêtre et effacer les données graphiques ?";

if ($frame_url eq ""){
    $frame_url=$doc{$langue};
}

if ($input_name eq "Calculer") {
  print_xml_preamble($focus_prog);

  # Zone de dialogue du tableur
  print "<div  class=\"top\" id=\"tab_dialog\">\n";
  print "<form action=\"javascript:fill_cell()\" style=\"padding:0px; margin:0px;\">\n";
  print "<b id=\"tab_cell\">A0</b>\n";
  print " : <input onclick=\"window.focus()\" style=\"width:30%;\" id=\"tab_entry\"  onchange=\"fill_cell()\"/>&nbsp;&nbsp;&nbsp;\n";
  print "<input class=\"yellow\" type=\"button\"  onclick=\"copy()\"  value=\"".$copy{$langue}."\" />\n";
  print "<input class=\"yellow\" type=\"button\"  onclick=\"paste()\" value=\"".$paste{$langue}."\" />\n";
  print "<input class=\"yellow\" type=\"button\" id=\"bottom\" onclick=\"fill_bottom()\" value=\"".$fill_bottom{$langue}."\" />\n";
  print "<input class=\"yellow\" type=\"button\" id=\"right\" onclick=\"fill_right()\" value=\"".$fill_right{$langue}."\" />\n";
  print "<input class=\"green\" type=\"button\"  onclick=\"compute()\"  value=\"".$compute{$langue}."\" />\n";
  print "</form>\n";
  print "</div>\n";

  print<<END_DIALOG1;
    <div class="top" id="svg_dialog">
    Xmin : <input type="text" name="new_xmin" id="new_xmin" value="$xmin" size="4" onclick="focusSVG()" />&nbsp;
    Xmax : <input type="text" name="new_xmax" id="new_xmax" value="$xmax" size="4" onclick="focusSVG()" />&nbsp;
    Ymin : <input type="text" name="new_ymin" id="new_ymin" value="$ymin" size="4" onclick="focusSVG()" />&nbsp;
    Ymax : <input type="text" name="new_ymax" id="new_ymax" value="$ymax" size="4" onclick="focusSVG()" />&nbsp;
    <input class="green" type="button" onclick=\"_replot_png('$setup{$langue}')\" value="$resize{$langue}" />
 </div>
END_DIALOG1
  #Zmin : <input type="text" name="new_ymin" id="new_ymin" value="$zmin" size="4" onclick="focusSVG()" />&nbsp;
  #  Zmax : <input type="text" name="new_ymax" id="new_ymax" value="$zmax" size="4" onclick="focusSVG()" />

  #----------------------------------
  #     Fenêtre principale
  #----------------------------------
 print "<form   name=\"formulaire\" id=\"formulaire\" action=\"".$pl_directory.
   "giac.pl"."\" method=\"post\" onsubmit= \"explore_tab('tableau'); change_frame_url()\" style=\"margin: 0px;\">\n";
  print "<div class=\"bottom\" align=\"center\" >\n";
  #print "<table bgcolor=\"#c0c3c6\"  style=\"width : 100%;\">\n";
  print "<table bgcolor=\"lightgrey\"   style=\"width : 100%;\">\n";
  print "<tbody>\n";
  print "<tr><td style=\"text-align:center; height : 25px;\" >\n";
  if ($langue eq "fr"){
    print "<div class=\"retour\">\n";
    print "<a class=\"retour\" href=\"".$pl_directory."sommaire.pl\">Vers Exo-M\@ths</a></div>\n";
  }
  print $title{$langue}."\n";
  print "<div style=\"position:absolute; right:20px; top:0px; padding: 0px;\">\n";
  print "<i style=\"color:red\">".$title_language{$langue}."</i>\n";
  print "<select name=\"langue\"  onchange=\"submit()\" style=\"background-color :#E1E1E1;\">";
  for ($i=0; $i<=$#langage ; $i++){
    if ($langage[$i] eq $langue) {
      print "<option selected=\"selected\">".$langage[$i]."</option>"."\n";
    } else {
    print "<option>".$langage[$i]."</option>"."\n";
    }
  }
  print "</select>\n";
  print "</div>\n"; 
  print "</td></tr>\n";
  print "<tr><td>\n";
 # affichage de la doc
  if ($ans eq "" || $ans eq "(())")  {
#    print "<iframe src=\"".$html_directory.$doc{$langue}."\" id=\"help\"
#    style=\"display:block; overflow:auto;  background-color: white; width:99%; height: 100px;\">\n";
    print "<iframe src=\"$frame_url\" id=\"help\" 
    style=\"display:block; overflow:auto;  background-color: white; width:99%; \">\n";
  } else {
    print "<iframe  src=\"$frame_url\"  id=\"help\"  
    style=\"display:none; overflow: auto;  background-color: white; width:99%; \">\n";
  }
  print "</iframe>\n";

  #affichage de l'historique-----------------------------------------
  if ($ans eq "") {
    print "<div  id=\"histo\" style=\"display:none;background-color:white;width:100% ;overflow:auto; margin:0px;border:1px;\">\n";
  } else {
    print "<div  id=\"histo\" style=\"display:block; background-color: white; width:100% ;overflow:auto; margin:0px;border:1px;\">\n";
  }
hist_mathml();

#  my @command;
#  my $com;
#  open(ARCHIVE_TXT, "<".$exe_directory."archive/archive_txt".$num_archive);
#  $i=0;
#  $ligne="";
#  for (;<ARCHIVE_TXT>;) {
#    $com=$_;
#    $com=~ s/\n//g;
#    $com=~ s/</&lt;/g;
#    $com=~ s/&&/&amp;&amp;/g;
#    if ($com eq $separateur) {
#      $i=$i+1;
#      $i=$i%2;
#      if ($i==1){
#	push (@command,$ligne);
#      }
#      $ligne="";
#    }
#    elsif ($i==0){
#      $ligne.=$com."<br />";
#    }
#  }
#  close ARCHIVE_TXT;
#  my $mml;
#  my $k;

#  open(ARCHIVE_MML, "<".$exe_directory."archive/archive_mml".$num_archive);
#  $i=0;
#  $k=0;
#  $l=0;
#  for (;<ARCHIVE_MML>;) {
#    $mml=$_;
#    $mml=~s/\n//g;
#    if ($mml ne $separateur) {
#      #elimination des caractères 0 à 31 qui plantent le navigateur
#      for ($j=0 ; $j<32 ; $j++) {
#	$char=chr($j);
#	$mml=~ s/$char/,undef/g;
#      }
#      if ($l==0) {
#	print "<p  style=\"color:red;\">\n".$k." : ".$command[$k]."</p>\n";
#	$k++;
#	print  "<p>".$mathml_preamble."<mstyle mathcolor=\"red\">\n";
#      } else {
#	print "<p>".$mathml_preamble."<mstyle  mathcolor=\"green\">\n";
#      }
#      print $mml;
#      print "</mstyle></math></p>\n";
#      #affichage éventuel de la feuille de calcul
#      if ($k-1==$spread_index && $l!=0) {
#	print_spreadsheet();
#      }
#    } else {
#      $l=$l+1;
#      $l=$l%2;
#    }
#  }
#  my $last_history_index=$k;
#  if ($k==0 && $spread_index!=-1){
#    print_spreadsheet();
#  }
#  close ARCHIVE_MML;

  print "<div id=\"last_command\"></div>\n";
  print "</div>\n";

  # affichage du tableur-------------------------------------------------------
  print "<div  id=\"tab\" style=\"display:none; background-color: white; width:100% ; overflow:auto; margin:0px;\">\n";

  print "<table border=\"1\"  width=\"100%\" cellspacing=\"0\">\n";
  print "<tbody>\n";
  print "<tr >\n";
  print "<td   id=\"tableau\" bgcolor=\"lightGrey\" width=\"10%\"></td>\n";
  my $ord;
  my $col;
  for ($j=0;$j<$nb_col;$j++){
    print "<td bgcolor=\"lightGrey\" align=\"center\" width=\"18%\">";
    $ord = ord "A";
    print chr($ord+$j);
    print "</td>";
  }
  print "</tr>\n";
  for ($i=0; $i<$nb_line ; $i++){
    print "<tr><td bgcolor=\"lightGrey\" align=\"center\">".$i."</td>\n";
    for ($j=0 ; $j<$nb_col ; $j++){
      $ord = ord "A";
      $col =chr($ord+$j);
      print "<td  id=\"".$col.$i."\"  onclick=\"cell('".$col.$i."')\" \>";
      if ($#cell<0){
	print "0</td>";
      } else {
	print $cell[$i*$nb_col+$j]."</td>";
      }	
    }
    print "</tr>\n";
  }
  print "</tbody></table>\n";
  print "</div>\n";

  # affichage du la fenêtre de programmation
  print "<div  id=\"progr\" style=\"display:none;width:100% ;overflow:hidden;\">\n";
  if ($script ne "") {
    print "<textarea id=\"script\"  name=\"script\" onfocus=\"focus_prg()\"  style=\"width:100%;border:0px;margin:2px;\">";
    $script=~ s/</$lt/g;
    $script=~ s/&&/&amp;&amp;/g;
    print $script."</textarea> \n";
  } else {
    print "<textarea  id=\"script\" name=\"script\"  onfocus=\"focus_prg()\" style=\"width:100%;border:0px;margin:0px;\" >";
    print "</textarea> \n";
  }
  print "</div>\n";

# Fenêtre grphique
print<<END_SVG;
<div  id="svg" name="svg" style="display:none; overflow:auto; margin:0px; border:0; padding:0;" >
<img src="$png_output"/>
</div>
END_SVG



  #variables utilisées pour l'affichage
  print "<script>\n";
  if ($script eq ""){
    print "var script_giac=0;";
  } else {
    print "var script_giac=1;";
  }
  print "</script>\n";
  print "</td></tr><tr><td>\n";
  # affichage des boutons et des entrées
  print "<div id =\"command\" style=\"height:70px; font: 11px verdana; background-color:lightgrey; position:absolute; top:300px; left:0px; margin:0px;padding:0px;width:100%; \">\n";
  print "&nbsp;&nbsp;".$instruction{$langue}."<br />&nbsp;\n";

  #Entrée de l'instruction
  if ($param ne "") {
    print "<input id=\"ins\" type=\"text\" name=\"giac\" value=\"".$param." \" style=\"width : 380px; display:inline\" onclick=\"window.focus()\" /> \n";
  } else {
    print "<input  id=\"ins\" type=\"text\" name=\"giac\"   style=\"width : 380px; display:inline\"  onclick=\"window.focus()\" /> \n";
  }
  print "<input  class=\"green\" type=\"submit\" name=\"calculer\" value=\"".$compute{$langue}."\" />\n";
  print  "&nbsp;Complexes ";
  if ($complexes eq "on"){
    print "<input type=\"checkbox\" name=\"complexes\" checked=\"on\" />\n";
  } else {
    print "<input type=\"checkbox\" name=\"complexes\"  />\n";
  }
  print "<input type=\"hidden\" name=\"complexes_state\" value=\"".$complexes_state."\" />\n";
  print<<END_SELECT;
  $couleur{$langue} :
  <select name="couleur" id="couleur" style="background-color :#E1E1E1; font-weight:bold;" >
    <option>$black{"en"}</option>
     <option style="color:red">$red{"en"}</option>
     <option style="color:green">$green{"en"}</option>
     <option style="color:blue">$blue{"en"}</option>
     <option style="color:yellow">$yellow{"en"}</option>
  </select>
END_SELECT
  # boutons jaunes
  print "<table width=\"100%\"><tbody><tr><td>\n";
  print "<input class=\"yellow\" type=\"button\" name=\"aide\" onclick=\"affiche('help',script_giac)\" value=\"".$help{$langue}."\" />\n";
  print "<input class=\"yellow\" type=\"button\" name=\"hist\" onclick=\"affiche('histo',script_giac)\" value=\"".$history{$langue}."\"/>\n";
  print "<input class=\"yellow\" type=\"button\" name=\"table\"  onclick=\"affiche('tab',script_giac),cell('A0')\" value=\"".$table{$langue}."\" />\n";
  print "<input class=\"yellow\" type=\"button\" name=\"prg\"  onclick=\"affiche('progr',script_giac)\" value=\"".$program{$langue}."\" />\n";
  print "<input class=\"yellow\" type=\"button\" name=\"png\"  onclick=\"affiche('svg',script_giac),svg_dialog()\" value=\"".$geo{$langue}."\" />\n";
  print "<script>\nvar window1=\"$window{$langue}\";\n var  window2=\"$window2{$langue}\";\n</script>\n";
  if ($nb_frames==1){
    print "<input class=\"yellow\" type=\"button\" id=\"win2\"  onclick=\"manage_window()\" value=\"".$window2{$langue}."\" />\n";
  } else {
    print "<input class=\"yellow\" type=\"button\" id=\"win2\"  onclick=\"manage_window()\" value=\"".$window{$langue}."\" />\n";
  }
  print "</td><td style=\"text-align:right\">\n";
  print $history{$langue}." : &nbsp;\n";
  print "<input class=\"marron\"  type=\"submit\" name=\"hist_mathml\" value=\"MathML\" />\n";
  print "<input class=\"marron\"  type=\"submit\" name=\"hist_latex\" value=\"".$latex{$langue}."\" />\n";
  print "<input class=\"marron\" type=\"submit\" name=\"hist_texte\" value=\"".$text{$langue}."\" />\n";
  print "</td></tr></tbody></table>\n";
  print "</div>\n";
  # formules du tableur
  print "<input type=\"hidden\" id =\"spread\" name=\"spread\" value=\"$spread\" /> \n";
  print "<input type=\"hidden\" id =\"spread_changed\" name=\"spread_changed\" value=\"0\" /> \n";
  print "<input type=\"hidden\" id =\"last_history_index\" name=\"last_history_index\" value=\"".$last_history_index."\" /> \n";
  print "<input type=\"hidden\" id =\"spread_index\" name=\"spread_index\" value=\"".$spread_index."\" /> \n";
  # dernière réponse
  print "<input type=\"hidden\" name=\"ans\" value=\"".$ans."\" /> \n";
  print "<input type=\"hidden\" name=\"num_archive\" value=\"".$num_archive."\" /> \n";
  #nb de fenêtres
  print "<input type=\"hidden\" id=\"nb_frames\" name=\"nb_frames\" value=\"".$nb_frames."\" /> \n";
  print "<input type=\"hidden\" id=\"main_frame_side\" name=\"main_frame_side\" value=\"".$main_frame_side."\" /> \n";
  print "<input type=\"hidden\" id=\"main_frame\" name=\"main_frame\" value=\"".$main_frame."\" /> \n";
  print "<input type=\"hidden\" id=\"second_frame\" name=\"second_frame\" value=\"".$second_frame."\" /> \n";
  print "<input type=\"hidden\"  id=\"focus\"  name=\"focus_prog\" value=\"0\" /> \n";
  print "<input type=\"hidden\"  id=\"focus_svg\"  name=\"focus_svg\" value=\"0\" /> \n";
  print "<input type=\"hidden\"  id=\"prev_clor\"  name=\"prev_color\" value=\"".$color."\" /> \n";
  print "<input type=\"hidden\"  id=\"replot\"  name=\"replot\" value=\"0\" /> \n";
  print "<input type=\"hidden\" name=\"xmin\" value=\"$xmin\" />\n";
  print "<input type=\"hidden\" name=\"xmax\" value=\"$xmax\" />\n";
  print "<input type=\"hidden\" name=\"ymin\" value=\"$ymin\" />\n";
  print "<input type=\"hidden\" name=\"ymax\" value=\"$ymax\" />\n";
  print "<input type=\"hidden\" id=\"new_xmin2\" name=\"new_xmin\" value=\"$xmin\" />\n";
  print "<input type=\"hidden\" id=\"new_xmax2\" name=\"new_xmax\" value=\"$xmax\" />\n";
  print "<input type=\"hidden\" id=\"new_ymin2\" name=\"new_ymin\" value=\"$ymin\" />\n";
  print "<input type=\"hidden\" id=\"new_ymax2\" name=\"new_ymax\" value=\"$ymax\" />\n";
  print "<input type=\"hidden\" name=\"color\" value=\"$color\" />";
  if ($frame_url ne $doc{$langue}){
      print "<input type=\"hidden\" name=\"frame_url\" id= \"frame_url\" value=\"$frame_url\" />\n";
  } else {
      print "<input type=\"hidden\" name=\"frame_url\" id= \"frame_url\" value=\"\" />\n";
}
  print "</td></tr></tbody></table>\n";
  #paramètres d'affichage
  print "<input type=\"hidden\" name=\"xmin\" id=\"xmin\" value=\"$xmin\" />";
  print "<input type=\"hidden\" name=\"xmax\" id=\"xmax\" value=\"$xmax\" />";
  print "<input type=\"hidden\" name=\"ymin\" id=\"ymin\" value=\"$ymin\" />";
  print "<input type=\"hidden\" name=\"ymax\" id=\"ymax\" value=\"$ymax\" />";
  print "</div>\n";
  print "</form>\n";
  print_xml_end;
}				
#--------------------------------------------------  end if Calculer


if ($input_name eq "Historique LATEX") {
  print "\\documentclass{article} \n  \\begin{document} \n";
  print "\\title{Session Giac}\n";
  my $latex;
  open(ARCHIVE_TEX, "<".$exe_directory."archive/archive_tex".$num_archive);
  for ($i=0;<ARCHIVE_TEX>;) {
    $latex=$_;
    $latex=~ s/\n//g;
    if ($latex eq $separateur) {
      $i++;
    } else {
      if ($i%2==0) {
	print $i/2;
      }
      print  "\\[".$latex."\\]"."\n";
    }
  }
  close ARCHIVE_TEX;
  print "\n\\end{document}";
}
# ----------------------------------------------- end if historique LATEX

if ($input_name eq "Historique texte") {
  print "//Session Giac\n";
  my $text;
  open(ARCHIVE_TXT, "<".$exe_directory."archive/archive_txt".$num_archive);
  for ($i=0;<ARCHIVE_TXT>;) {
    $text=$_;
    $text=~ s/\n//g;
    if ($text eq $separateur) {
      $i++;
    } else {
      if ($i%2==0) {
	print "\n\n";
      } else {
	print ";\n//";
      }
      print  $text;
    }
  }
  close ARCHIVE_TXT;
}
# ----------------------------------------------- end if historique texte

if ($input_name eq "Historique mathml") {
print<<PREAMBULE;
<?xml version="1.0" encoding="iso-8859-1"?>
<?xml-stylesheet type="application/xsl" href="http://127.0.0.1/giac_online/pmathml.xsl"?>
<!DOCTYPE MMLEntities [
 <!ENTITY reals "&#x0211D;">
 <!ENTITY complexes "&#x02102;" >
 <!ENTITY int "&#8747;">
<!ENTITY Integral "&#x0222B;">
<!ENTITY Sigma "&#931;">
 <!ENTITY part "&#8706;" >
<!ENTITY nbsp "&#160;" >
<!ENTITY quot "&#34;" >
<!ENTITY rarr "&#8594;" >
<!ENTITY VerticalBar "&#x02223;">
<!ENTITY lsqb "&#x0005B;" >
<!ENTITY deg  "&#x000B0;" >
<!ENTITY infin    "&#8734;" >
<!ENTITY InvisibleTimes "&#x02062;" >
<!ENTITY pi "&#960;" >
<!ENTITY le "&#x02264;">
<!ENTITY gt "&#62;" >
<!ENTITY ge "&#x02265;" >
]>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Giac en ligne</title>

</head>
<body>
<h1>Giac on line sesssion</h1>
PREAMBULE
hist_mathml();
print_xml_end;
}
# ----------------------------------------------- end if historique texte


# --------------------------------------
#  destruction des archives inutilisees
# --------------------------------------
my $archive3d;
open(EFFACE, "rm -f  rm -f archive/session3d*");
close (EFFACE);
#semble bogué : n'a pas détruit les fichiers de la veille ;  bug reconstaté en 08/04 pb de cache ?
#mais fonctionne si on prend $delay_max=1 seconde ...
for ($i=0 ;$i<100 ; $i++) {
  $archive="archive/archive".$i;
  $archive_png="archive/gd".$i.".png";
  $archive_gif="archive/gd".$i.".gif";
  $archive3d="archive/session3d".$i.".*";
  @stat_archive=stat($archive);
  if (stat($archive)) {
    @stat_archive=stat($archive);
    $date=$stat_archive[9];	#date derniere modif
    $delay=time-$date;
    if ($delay-$delay_max>0) {
      open(EFFACE, "rm -f ".$archive." ".$archive3d." ".$archive_png." ".$archive_gif." |");
      close (EFFACE);
    }
  }
# else {
#    open(EFFACE, "rm -f ".$archive." ".$archive3d." ".$archive_png." ".$png_directory."casgraph".$i.".png |");
#    close (EFFACE);
#  }
}
