package DDMT.Nodes;

/*
 * ReadFile.java
 *
 * Created on 21:46, August 1st, 2004
 */

/** Read data file
 * @author Kun Liu
 * @version 1.1
 */

import java.lang.*;
import java.io.*;
import java.math.*;
import java.util.*;

public final class ReadFile{

    public  static ArrayList read(java.lang.String filename) {

        String t;
        java.util.ArrayList SiteXData = new java.util.ArrayList();

        try{

            java.io.File f ;
            if (filename!=null && filename.length()!=0){
                f = new java.io.File(filename);
            }
            else{
                System.out.println("file name incorrect!");
                return SiteXData;
            }

            // read file
            java.lang.String line;
            java.util.StringTokenizer StrTok = null;
            int NumRows = 0; // total number of rows
            int NumCols = 0; // total number of columns
            int tmpNumCols = 0;

            // open file
            java.io.BufferedReader in = new java.io.BufferedReader(new java.io.FileReader(f));
            // get the number of columns
            line = in.readLine();
            if (line == null)
            {
                System.out.println("empty file!");
                return SiteXData;
            }
            else
            {
                StrTok = new StringTokenizer(line," \t\n\r\f,");
                NumCols = StrTok.countTokens();
            }
            in.close();

            // initial a data point array
            double [] DataArray;
            in = new java.io.BufferedReader(new java.io.FileReader(f));

            //now read file to pick up values
            while (null != (line = in.readLine())) 
            {
                NumRows ++ ;
                StrTok = new StringTokenizer(line," \t\n\r\f,");
                tmpNumCols = StrTok.countTokens();
                if (tmpNumCols != NumCols) {
                    System.out.println("inconsisten columns in row "+NumRows+" .");
                    SiteXData.clear();
                    return SiteXData;
                }

                DataArray = new double [NumCols];
                for(int i=0;i < NumCols;i++) 
                {
                    DataArray[i] = (Double.valueOf(StrTok.nextToken())).doubleValue();
                }
                DataPoint dp = new DataPoint(DataArray);
                SiteXData.add(dp);

            }
        in.close();
        }
        catch (Exception e) 
        {
            e.printStackTrace();
        }
        return SiteXData;
    }

    /** Main function -- for test*/
    public static void main(String args[])
    {
        DataPoint dp;
        ArrayList data = ReadFile.read("datafile.txt");
        for (int i=0;i<data.size();i++)
        {
            dp = (DataPoint)data.get(i);
            dp.print();
        }
    }
}
