import java.util.*;

//this class simulates the bag of pieces that comes with scrabble

public class bag
{
  public static int[] pieces = new int[28];  //the total number of each type of piece in the bag
  public static Random rand = new Random();  //random object
  public static int totalPieces = 0;         //total pieces remaining in the bag

  public static void initBag()
  {
    totalPieces = 99;
    pieces[1]=9; //A
    pieces[2]=2; //B
    pieces[3]=2; //C
    pieces[4]=4; //D
    pieces[5]=12; //E
    pieces[6]=2; //F
    pieces[7]=3; //G
    pieces[8]=2; //H
    pieces[9]=9; //I
    pieces[10]=1; //J
    pieces[11]=1; //K
    pieces[12]=4; //L
    pieces[13]=2; //M
    pieces[14]=6; //N
    pieces[15]=8; //O
    pieces[16]=1; //P
    pieces[17]=1; //Q
    pieces[18]=6; //R
    pieces[19]=4; //S
    pieces[20]=6; //T
    pieces[21]=4; //U
    pieces[22]=2; //V
    pieces[23]=2; //W
    pieces[24]=1; //X
    pieces[25]=2; //Y
    pieces[26]=1; //Z
    pieces[27]=2; //blanks
  } //method initBag

  private static char byteToChar(byte a)
  {
    if (a==27)
      return ' ';
    else
      return (char)(a+96);
  } //method byteToChar
                       
  private static byte charToByte(char c)
  {
    if (c==' ')
      return 27;
    else              
     return (byte)(c-'`'); //this should make it that 'a' returns 1
  } //method charToByte

  public static int getCharsLeft()
  {
    return totalPieces;
  } //method getCharsLeft

  public static char getChar()
  {
    int a=0;
    int b=0;
    byte c=0;
    boolean notdone = true;

    if (totalPieces==0)
      { return 0; }

    //return a number 0 <= x < totalPieces
    a = (Math.abs(rand.nextInt()) % totalPieces);
  
    while (notdone)
    {
      if ((a>=b)&&(a<=b+pieces[c]))
      {
        notdone = false;
      }
      else
      {
        b = b + pieces[c];
        c++;
      }
      if (c>27)
      {
        notdone = false;
        a = 27;
      }
    }
    pieces[c]--;
    totalPieces--;
    return byteToChar(c);
  } //method getChar

  public static void throwInChar(char c)
  {
    byte a;
    a = charToByte(c);
    pieces[a]++;
    totalPieces++;
  } //method throwInChar
} //class bag
