#!/usr/bin/perl

use Expect ;

$ENV{"PAGER"} = "cat" ;
$ENV{"EDITOR"} = "gnuclient" ;

$DATA_BEGIN = "\02" ;
$DATA_END = "\05" ;

my $R_ps_begin = "__R_PS_BEGIN__" ;
my $R_ps_end = "__R_PS_END__" ;
my $R_latex_begin = "__R_LATEXX_BEGIN__" ;
my $R_latex_end = "__R_LATEXX_END__" ;
my $R_prompt = "__R prompt__" ;

my $R = Expect->spawn("/usr/bin/R") or die "can not start R\n" ;
$R->log_stdout(0) ;

$|=1 ;

print $DATA_BEGIN."verbatim:" ;
$R->expect(undef,"-re","^> ") ;
{ 
  my $v = $R->before() ;
  $v =~ s/\r//g ;
  print $v ;
}
print <<END_START;
---------------------------------------------------------
TeXmacs interface. Use v() to insert current graphic into
TeXmacs buffer. Use q("yes") to quit and save.
---------------------------------------------------------
END_START



print $R <<END_R_INIT;
v<-function(){ dev.copy2eps(print.it=T,command="rprint")}
options(prompt=\"$R_prompt\")
END_R_INIT

$R->expect(undef,"options(prompt=\"$R_prompt\")") ;
$R->expect(undef,"-re","^".$R_prompt ) ;


$counter = 0 ;

sub next_input {
  $counter++ ;
  print $DATA_BEGIN."channel:prompt".$DATA_END ;
  print $DATA_BEGIN."latex:\\red\$\\succ\$\\black ".$DATA_END." " ;
}


sub get_line {
  my $line = <STDIN> ;
open(TMP,">>/tmp/out") ;
  print TMP $line."\n" ;
  close(TMP) ;
  chop $line ;
  $line =~ s/leftarrow/<-/g ;
  $line ;
}

next_input() ;
print $DATA_END ;

$line = get_line() ;
print $R $line."\n" ;
while( !defined($R->exitstatus()) ) {
$R->expect(undef,
	   [ qr/^\Q$line\E/ => sub {
	       $line = "NOTHING" ;
	     }] ,
	   [ $R_prompt => sub{
	       my $R = shift ;
	       my $v = $R->before() ;
	       $v =~ s/\r//g ;
	       $v =~ s/^\n*// ;
	       if( !( $v =~ /^\s*$/ ) ) {
		 print $DATA_BEGIN."verbatim:".$v.$DATA_END ;
	       }
	       next_input() ;
	       print $DATA_END ;
	       
	       $line = get_line() ;
	       print $R $line."\n" ;
	       print $DATA_BEGIN."verbatim:" ;
	     } ],
	   [ qr/^\+ /, sub {
	       $line = get_line() ;
	       print $R $line."\n" ;
	       print "now line is: $line\n" ;
	     } ],
	   [ $R_ps_begin => sub {
	       my $R = shift ;
	       my $v = $R->before() ;
	       $v =~ s/^\s*// ;
	       if( !( $v =~ /^\s*$/ ) ) {
		 $v =~ s/\r//g ;
		 print $DATA_BEGIN."verbatim:".$v.$DATA_END ;
	       }
	       print "\n".$DATA_BEGIN."ps:" ;
	       $R->expect(undef,
			  [ $R_ps_end => sub {
			      $v = $R->before() ;
			      $v =~ s/\r//g ;
			      print $v.$DATA_END ;
			    } ] ) ;

	     } ],
	   [ $R_latex_begin => sub {
	       my $R = shift ;
	       my $v = $R->before() ;
	       $v =~ s/^\s*// ;
	       if( !( $v =~ /^\s*$/ ) ) {
		 $v =~ s/\r//g ;
		 print $DATA_BEGIN."verbatim:".$v.$DATA_END ;
	       }
	       print "\n".$DATA_BEGIN."latex:" ;
	       $R->expect(undef,
			  [ $R_latex_end => sub {
			      $v = $R->before() ;
			      $v =~ s/\r//g ;
			      print $v.$DATA_END ;
			    } ] ) ;

	     } ],
	   ) ;
}
