import org.ejml.data.DenseMatrix64F;
import org.ejml.ops.CommonOps;

import au.com.bytecode.opencsv.*;

import java.io.*;
import java.util.List;


/**
 * A linear equation solver using csv input.
 * 
 * @author rod
 *
 */
public class Linear {
    
    public static void main(String args[] ){

        try {
            CSVReader reader = new CSVReader(
                new FileReader(args[0]));
            List rows = reader.readAll();
            String[] first = (String [])rows.get(0);
            int cols = first.length;
            int sz = cols - 1;
            
            DenseMatrix64F A = new DenseMatrix64F(sz,sz);
            DenseMatrix64F x = new DenseMatrix64F(sz,1);
            DenseMatrix64F b = new DenseMatrix64F(sz,1);
            
            for( int i = 0; i < sz; i++ ){
                double[] row = new double[sz+1];
                String[] r = (String [])rows.get(i);
                for( int j = 0; j < row.length; j++ ){
                    row[j] = Double.parseDouble( r[j]);
                }
                for( int j = 0; j < sz; j++ ){
                    A.set(i,j, row[j]);
                }
                b.set(i, row[sz]);
            }
            A.print();
            b.print();
            x.print();

            // A * x = b
            // x = invert(A) * b 
            if( !CommonOps.solve(A,b,x) ) {
                System.out.println("failed");
            }
            System.out.println("Solution");
            x.print();
            
        } catch (FileNotFoundException e) {
            System.err.println("File not found");
        } catch (IOException e) {
            System.err.println("Error reading csv");
        }
    }
}
