import java.io.*;
import org.rosuda.JRI.Rengine;
import org.rosuda.JRI.REXP;

public class rtest {
    public static void main(String[] args) {
        try{   
            //args[1] -output file            
            //args[2] -timestamp
            //args[3] -metric
            String m_path;
            File f = new File ("exportForR.csv");
            m_path=f.getAbsolutePath();            
    
            if (System.getProperty("os.name").toLowerCase().indexOf("windows") > -1) 
                m_path=m_path.replace('\\', '/');
            
            FileOutputStream out;
            PrintStream p; 
            out = new FileOutputStream(args[1]);
            p = new PrintStream( out );
       
            String ar[]={"--save"};
	      Rengine re=new Rengine(ar, false, null); 
     
	// the engine creates R is a new thread, so we should wait until it's ready
            if (!re.waitForR()) {
               // p.println("Cannot load R");
               return;
            }
            re.eval("measures<-read.csv(file='"+m_path+"',head=FALSE,sep=',')");
            re.eval("desim <-dist(measures, method = "+args[3]+", diag = TRUE, upper = TRUE, p = 2)");
            re.eval("coordinates <- cmdscale(desim, k=2)");
            REXP rexp = new REXP();
            rexp=re.eval("coordinates");
        
            double[][] matrix= rexp.asDoubleMatrix();
                
            for(int i=0;i<matrix.length;i++){
                p.println(matrix[i][0]+","+matrix[i][1]);
            }                 
            p.println(args[2]);

        }catch(Exception e){
                e.getMessage(); e.printStackTrace();  
            }     
        System.exit(0);
    }
}