import java.util.*;
import java.io.*;

/**
 * read a file, print each word and line numbers
 * on which word occurs, words printed in alphabetical order
 *
 * @author Owen Astrachan
 */

public class WordLines
{
    /**
     * construct a WordLines object
     */
    
    public WordLines()
    {
	myMap = new TreeMap();
    }

    /**
     * reads a file specifed by filename
     * and tracks every word and the line numbers on which the word
     * occurs.
     * @param filename is the name of the file read/processed
     */
    
    public void read(String filename)
    {

	StringTokenizer tokenizer = null;
	String word = null;
	String line = null;
	int linecount = 0;
	Integer lineCount = new Integer(0);
	
	try{
	    BufferedReader reader =
		new BufferedReader(new FileReader(filename));

	    while ((line = reader.readLine()) != null) {
		linecount++;
		
		tokenizer = new StringTokenizer(line);
		while (tokenizer.hasMoreTokens()) {
		    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);
		    }
		}
	    }
	}
	catch (FileNotFoundException e){
	    System.err.println("***ERROR opening " + filename);
	}
	catch (IOException e)
	{
	    // what to do with an IOException??
	    System.err.println("IO Exception " + e);
	}
    }
    

    /**
     * print list of words with line numbers as from
     * previous call to read
     * @see 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((Integer) lines.next() + " ");
	    }
	    System.out.println();
	}
    }

    public static void main(String args[])
    {
	if (args.length != 1) {
	    System.out.println("usage: WordLines <filename>");
    	    System.exit(0);
	}
	
	WordLines s = new WordLines();
	s.read(args[0]);
	s.print();
    }

    private Map myMap;        
}
