public class Mystery
{
    private String previous;
    private String current;
    private int count;
    private int max;

    public Mystery(int max)
    {
        previous = "";
        current = "";
        this.max = max;
    }

    public String get()
    {
        flush();
        String r = previous;
        previous = "";
        return r;
    }

    public void flush()
    {
        previous = previous + current + "\n";
        current = "";
        count = 0; // Take screen capture here
    }

    public void spread()
    {
        int d = max - current.length();
        if (d > 0 && count > 0)
        {
            int gap = d / count;
            int extra = d % count;
            int start = 0;
            int j = 0;
            for (int i = 0; i <= current.length(); i++)
            {            
                String letter;
                if (i == current.length())
                    letter = " ";
                else
                    letter = current.substring(i, i + 1);
                if (letter.equals(" "))
                {
                    previous = previous + current.substring(start, i);
                    if (i < current.length())
                    {                        
                        for (int k = 0; k <= gap; k++)
                            previous = previous + " ";
                        if (j < extra) 
                            previous = previous + " ";
                    }
                    j++;
                    start = i + 1;
                }
            }       
            current = "";
        }
        flush();
    }

    public void add1(String w)
    {
        if (current.length() + 1 + w.length() <= max)
        {
            count++;
            if (!current.equals("")) current = current + " ";
            current = current + w;
        }
        else
        {
            spread();
            current = w;
        }
    }

    public void add(String w)
    {
        int i = 0; 
        while (i < w.length())
        {
            boolean done = false;
            char ch = '?';
            while (!done)
            {
                ch = w.charAt(i);
                if (Character.isWhitespace(ch)) i++;
                else done = true;
                if (i == w.length()) done = true;
            }
            int j;
            if (i < w.length())
            {
                for (j = i; !Character.isWhitespace(ch) && j < w.length(); j++)
                {
                    ch = w.charAt(j);
                }
                if (j == w.length()) j++;
            }
            else j = i + 1;
            add1(w.substring(i, j - 1));
            i = j;
        }
    }
}
