import java.util.Scanner;
import java.io.File;

/**
 * Class that reads in and stores the contents of a text file.  
 *   @author Dave Reed
 *   @version 11/11/16
 */
public class TextProcessor {
    private String text;
    
    /**
     * Constructs a TextProcessor object that reads in text from a file.  
     * The text is processed to remove non-letters and adjacent spaces, and 
     * letters are converted to lowercase.
     *   @param fileName the file containing the text
     */
    public TextProcessor(String fileName) {
        this.text = "";
        try {
            Scanner infile = new Scanner(new File(fileName));
            while (infile.hasNextLine()) {
                this.text += " " + this.strip(infile.nextLine().toLowerCase());
            }
            this.text = this.text.trim().replaceAll("\\s+", " ");
            infile.close(); 
        }
        catch (java.io.FileNotFoundException e) {
            System.out.println("File not found.");
        }
    }

    /**
     * Accesses and returns the file contents as a single String.
     * @return the file contents (lowercase, with non-letters and adjacent spaces removed)
     */
    public String toString() {
        return this.text;
    }
   
    ///////////////////////////////////////////////////////////////////////////////

    /**
     * Strips the specified String of all characters except letters and spaces.
     *   @param str the String to be stripped
     *   @return str with all characters except letters and spaces removed
     */
    private String strip(String str) {
        String copy = "";
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (Character.isLetter(ch) || ch == ' ') {
                copy += ch;
            }
        }
        return copy;
    }
}
