import java.util.*;
import java.io.*;
import javax.swing.JFileChooser;

/**
 * Contrast this Java program with C++ wordlines.cpp to
 * understand basic Java idioms.
 *
 * @author Owen Astrachan
 */

public class WordCount
{
    /**
     * Create a WordCount object that will be able to read
     * from a file selected using standard java FileChooser.
     */
    
    public WordCount()
    {
    	if (ourFileChooser == null){
    		ourFileChooser = new JFileChooser(".");	
    	}
	try{
	    int retval = ourFileChooser.showOpenDialog(null); 
	    if (retval == JFileChooser.APPROVE_OPTION) {
		myFile = ourFileChooser.getSelectedFile();
		myReader = new BufferedReader(
		               new FileReader(myFile.getPath())); 
	    }
	}
	catch(Exception e){
	    throw new RuntimeException("file open problem in WordReader"); 
	}
    }

    /**
     * Read file selected at construction time and store words and
     * line numbers internally for subsequent reporting by print.
     *
     * @throws IOexception of reading file fails
     */
    void read() throws IOException
    {
	myMap = new TreeMap();
	String line;
	int linecount = 0;
	while ((line = myReader.readLine()) != null) {
	    linecount++;
		
	    StringTokenizer tokenizer = new StringTokenizer(line);
	    while (tokenizer.hasMoreTokens()) {
		String word = tokenizer.nextToken();
		
		Set lineset = (Set) myMap.get(word);
		if (lineset != null) {
		    lineset.add(new Integer(linecount));
		}
		else {
		    lineset = new TreeSet();
		    lineset.add(new Integer(linecount));
		    myMap.put(word,lineset);
		}
	    }
	}	
    }

    /**
     * Print list of words with line numbers as obtained
     * by most recent call to read.
     * 
     */
    
    public void print()
    {
	Iterator allKeys = myMap.keySet().iterator();      // each word
	
	while (allKeys.hasNext()) {

	    Object key =  allKeys.next();
	    
	    System.out.print(key + "\t");
	    Iterator lines = ((Set) myMap.get(key)).iterator();
	    while (lines.hasNext()) {
		System.out.print(lines.next() + " ");
	    }
	    System.out.println();
	}
    }    

    public static void main(String[] args){
	WordCount wc = new WordCount();
	try{
	    wc.read();
	    wc.print();	    
	}
	catch (Exception e){
	    System.err.println("trouble in wordcount");
	}
	System.exit(0);  // need because of filechooser
    }
    
    private static JFileChooser ourFileChooser;
    private File myFile;
    private Map myMap;    
    private BufferedReader myReader;
}
