/**
 * Code authored by Richard Rasala
 * Associate Dean
 * College of Computer and Information Science
 * Northeastern University
 *
 * Modified by Brandon Schory
 * 
 */

import edu.neu.ccs.util.*;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
import java.util.Vector;

public class FileNameTools implements JPTConstants{

    
	/** The method which creates a String array of the file names*/
	public static String[] getFileNames(String urlString) {
        String contents = readTextFile(urlString);
        
        return extractNonEmptyLines(contents);
    }
    
	/** The method which creates a char array from the read file*/
    public static String readTextFile(String urlString) {
        char[] data = copySmallFile(urlString);
        
        return new String(data);
    }
    
    /** The method that removes all the valuable lines from a string*/
    public static String[] extractNonEmptyLines(String string) {
        if ((string == null) || (string.length() == 0))
            return new String[0];
        
        StringTokenizer tokenizer =
            new StringTokenizer(string, "\n");
        
        Vector list = new Vector();
        
        while (tokenizer.hasMoreTokens()) {
            String token = tokenizer.nextToken();
            
            if (token.length() > 0)
                list.add(token);
        }
        
        return (String[]) list.toArray(new String[0]);
    }
	
    /** The method that copies a small file from any location into memory*/
    private static char[] copySmallFile(String oldPath) {
        
        int bufferSize = 8092;
    		StringBuffer buffer = new StringBuffer(bufferSize);
        char[] data = new char[bufferSize];
    	
    		if ((oldPath == null))
            return data;
        
        // read file
        try {
            // use pattern: open file; read file; close file
            FileReader reader = new FileReader(oldPath);
            
            while(true) {
                int count = reader.read(data);
                
                if (count > 0)
                    buffer.append(data, 0, count);
                else
                    break;
            }
            
            reader.close();
        }
        catch (IOException ex) {
            // print messages if IO errors happen
            System.out.println("IO failure reading: " + oldPath);
            System.out.println("Message: " + ex.getMessage());
            
            // exit since things are not OK
            throw new RuntimeException("Exiting due to IO Failure");
        }

        return data;
    }

}

