/*
 *  Draco Econometrics
 *  Copyright (C) 2006-2007 Approximatrix, LLC
 *  http://www.approximatrix.com
 *  
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.approximatrix.draco.io;

import java.io.BufferedReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.regex.Pattern;

public class PastedData {

	// Most windows programs will simply use tabs to separate table entries,
	// including Excel, Gnumeric, and this program
	private static final String SEPARATORS = "\t"; //"\t ,";
	
	private String[] headers = null;
	private ArrayList<String[]> data = null;
	
	public PastedData(String text) {
		
		int headers_present = 0;
		String[] one_split = text.split("\n", 1);
		if(one_split != null) {
			Pattern p = Pattern.compile("[A-Za-z]+");
			if(p.matcher(one_split[0]).find())
				headers_present = 1;
		}
		
		Object[] parsed = ImportExport.LoadText(new BufferedReader(new StringReader(text)),headers_present,headers_present,SEPARATORS,0);
		
		headers = (String[])parsed[1];
		data = (ArrayList)parsed[0];
		
		if(headers == null) {
			String[] values = (String [])data.get(0);
			generateDefaultHeaders(values.length);
		} else {
				Double[] new_values = new Double[headers.length];
				for(int i=0;i<headers.length;i++) {
					try {
						new_values[i] = new Double(headers[i]);
					} catch(NumberFormatException nfe) {
						new_values[i] = null;
					}
				}
					
				
				// No exceptions - so insert the header string and generate new ones
				//String[] bad_headers = new String[headers.length];
				//for(int i=0;i<headers.length;i++)
				//	bad_headers[i] = new String(headers[i]);
				
				//data.add(0,bad_headers);
				//generateDefaultHeaders(headers.length);
		}	
	}
	
	public String[] getHeaders() {
		return headers;
	}
	
	private void generateDefaultHeaders(int numbers) {
		headers = new String[numbers];
		for(int i=0;i<numbers;i++) {
			headers[i] = new String(ImportExport.DEFAULT_COLUMN_NAME+new Integer(i).toString());
		}
	}
	
	public ArrayList getData() {
		return data;
	}
	
}
