import org.rosuda.REngine.Rserve.*; 
import java.io.* ;

public class RserveWire {
  
  private RConnection r; 
  
  public RserveWire( RConnection r){
    this.r = r ;
  }
  
  public void transfer_toserver( String client_file, String server_file ){
    
    byte [] b = new byte[8192];
    try{
      /* the file on the client machine we read from */
      BufferedInputStream client_stream = new BufferedInputStream( 
        new FileInputStream( new File( client_file ) ) ); 
      
      /* the file on the server we write to */
      RFileOutputStream server_stream = r.createFile( server_file );
      
      /* typical java IO stuff */
      int c = client_stream.read(b) ; 
      while( c >= 0 ){
        server_stream.write( b, 0, c ) ;
        c = client_stream.read(b) ;
      }
      server_stream.close();
      client_stream.close(); 
      
    } catch( IOException e){
      e.printStackTrace(); 
    }
    
  }
  
  public void transfer_toclient( String client_file, String server_file ){
    
    byte [] b = new byte[8192];
    try{
      
      /* the file on the client machine we write to */
      BufferedOutputStream client_stream = new BufferedOutputStream( 
        new FileOutputStream( new File( client_file ) ) );
      
      /* the file on the server machine we read from */
      RFileInputStream server_stream = r.openFile( server_file );
      
      /* typical java io stuff */
      int c = server_stream.read(b) ; 
      while( c >= 0 ){
        client_stream.write( b, 0, c ) ;
        c = server_stream.read(b) ;
      }
      client_stream.close();
      server_stream.close(); 
      
    } catch( IOException e){
      e.printStackTrace(); 
    }
    
  }
  
  public static void main( String[] args){
    try{
      RConnection r = new RConnection();
      System.out.println( r.parseAndEval( "getwd()").asString() ) ;
      
      RserveWire wire = new RserveWire( r ); 
      
      String client_file = args[0];
      String server_file = args[1]; 
      System.out.println( "writing the client file '" + 
        client_file + "' to the server as '" + 
        server_file + "'" ) ;
      wire.transfer_toserver( client_file, server_file ) ;
      
      r.parseAndEval( "sink('file.txt') ; print( rnorm(30) ); sink()" ) ;
      System.out.println( "writing the server file 'file.txt' to the client as 'file.txt' " ) ;
      wire.transfer_toclient( "file.txt", "file.txt" ) ;
      
    } catch( Exception e){
      e.printStackTrace(); 
    }
    
  }
  
  
}