import java.io.*;
import java.util.*;

/**
 * An Indexer can be used to create a line index (as opposed to
 * the traditional page index) for a text file. The index
 * contains all of the words and the lines in which they appear.
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class Indexer
{
    private int                             minimumWordLength;    
    private Map<String, ArrayList<Integer>> index;
    private String                          title;    

    /**
     * Explicit Value Constructor.
     *
     * @param title  The title of the book (without the suffix)
     * @param minimumWordLength  The length of the shortest word to include
     */
    public Indexer(String title, int minimumWordLength)
    {
        this.title = title;        
        this.minimumWordLength = minimumWordLength;        
        index = new HashMap<String, ArrayList<Integer>>();
    }

    /**
     * Create the index.
     */
    public void createIndex()
    {
        int     lineNumber;        
        String  line;
        
        try
        {
            // Process the inpute file
            BufferedReader in = new BufferedReader(
                new FileReader(title+".txt"));

            lineNumber = 0;            
            while ((line = in.readLine()) != null)
            {
                String[] words = line.split("[*/\\.,;:?!(){} \t]");
                for (int i=0; i<words.length; i++)
                {
                    if (words[i].length() >= minimumWordLength) 
                    {
                        ArrayList<Integer> list = index.get(words[i]);
                        if (list == null) 
                        {
                            list = new ArrayList<Integer>();
                            index.put(words[i], list);
                        }
                        list.add(lineNumber);
                    }
                }
                ++lineNumber;
            }
            in.close();

            // Create the output file
            PrintWriter out = new PrintWriter(
                new FileOutputStream(title+".ndx"));
            List<String> keys = new ArrayList<String>(index.keySet());
            Collections.sort(keys);
            for (String key: keys)
            {
                List<Integer> list = index.get(key);                
                out.printf("%s\t", key);
                for (int i: list)
                {
                    out.printf("%d ", i);
                }
                out.printf("\n");
            }
            out.close();
        }
        catch (IOException ioe)
        {
            // Don't create an output file
        }
    }
}
