/*****************************************************************
** Decode - decode words encoded as per the telephone keypad
**
** Usage: java Decode dictionary [max_words]
**
** where 'dictionary' is a file containing words and word
** frequencies, for example...
**
**    the 5776384
**    of 2789403
**    and 2421302
**    a 1939617
**    in 1695860
**    ...
**
** and 'max_words' is an optional parameter specifying the maximum
** number of suggestions to give.  The default is 1 (the most
** probable match for the given code).
**
** Here is a sample dialogue:
**
**    PROMPT>java Decode maxfreq1.txt
**    Loading dictionary...(done)
**    Dictionary contains 9025 words
**    Sorting dictionary... (done)
**    Enter words encoded as per phone keypad...
**    43556 96753
**    hello world
**    ^z
**    PROMPT>
**
** (c) Scott MacKenzie, 2000                             
******************************************************************/
import java.io.*;
import java.util.*;

public class Decode
{
   public static void main(String[] args) throws IOException
   {
      // one or two command line arguments needed
      if (args.length == 0 || args.length > 2)
      {
         System.out.println(
            "usage: java WordPredict dictionary [max_words]");
         return;
      }

      int max = 1; // default
      if (args.length == 2)
         max = Integer.parseInt(args[1]);

      EncodedWord[] ew;

      System.out.print("Load and sort dictionary...");
      ew = EncodedWord.loadDictionary(args[0]);
      System.out.println("(done)");
      System.out.println("Dictionary contains " + ew.length + " words");

      BufferedReader stdin =
         new BufferedReader(new InputStreamReader(System.in), 1);

      System.out.println("Enter words encoded as per phone keypad...");

      // process lines until no more input
      String line;
      while ((line = stdin.readLine()) != null)
      {
         // process words in line
         StringTokenizer st = new StringTokenizer(line);
         while (st.hasMoreTokens())
         {
            String s1 = st.nextToken();

            // get ordered list of unique words matching code
            String[] s2 = EncodedWord.getUnique(s1, ew);

            // if no matches, continue with next code
            if (s2 == null)
               continue;

            // n = number of matches to output
            int n = max;
            if (n > s2.length)
               n = s2.length;

            // output matches
            for (int i = 0; i < n; ++i)
               System.out.print(s2[i] + " ");
         }
         System.out.println();
      }
   }
}

