import java.util.*;
import java.io.*;
 
public class Perm {
    public static void main(String[] args) {
        if (args.length != 2) {
            System.err.println("Usage: java Perm <File> <Min group size>");
            System.exit(1);
        }

        int minGroupSize = Integer.parseInt(args[1]);
  
        // Read words from file and put into simulated multimap
        Map<String,List<String>> wordMap = readWords(args[0]);

        // Print all permutation groups above size threshold
        printPermutations(wordMap, minGroupSize);
    }
    
    // readWords takes a filename and reads the words in that file. 
    // It is assumed that each word occurs on a separate line.

    private static Map<String,List<String>> readWords(String fileName) {
        Map<String,List<String>> wordMap = 
            new HashMap<String, List<String>>();
        try {
            BufferedReader in =
                new BufferedReader(new FileReader(fileName));

            String word = in.readLine();
            while(word != null) {
                String alpha = alphabetize(word);
                List<String> l = wordMap.get(alpha);
                if (l==null) {
                    l = new ArrayList<String>();
                    wordMap.put(alpha, l);
                }
                l.add(word);

                word = in.readLine(); // Read next word
            }
        } 

        catch(IOException e) {
            throw new RuntimeException(e); 
            //Don't know what to do with IO exceptions
        }
        return wordMap;
    }

    private static void printPermutations(Map<String,List<String>> wordMap, 
                                          int minGroupSize) {
        for (List<String> l : wordMap.values()) {
            if (l.size() >= minGroupSize) {
                System.out.println(l.size() + ": " + l);
            }
        }
    }

    private static String alphabetize(String s) {
        //Sortera tecknen i en sträng genom att räkna hur många gånger
        //varje tecken förekommer

        SortedMap<Character, Integer> count = 
            new TreeMap<Character, Integer> ();

        int len = s.length();
        for (int i=0; i<len; i++) {

            char c = s.charAt(i);

            if (count.containsKey(c)) {
                count.put(c, count.get(c)+1);
            }
            else {
                count.put(c, 1);
            }
        }

        StringBuffer result = new StringBuffer(len);
        
        for (Map.Entry<Character, Integer> e : count.entrySet()) {
            char c = e.getKey();
            int n = e.getValue();

            for (int i=0; i<n; i++) {
                result.append(c);
            }
        }
        return result.toString();
    }
}
