/*
 * Anagram.java
 * A sample solution to the homework 4
 */

import java.io.*;


public class Anagram {


    protected static String cleanUp(String string) {
        int i, len = string.length();
  	StringBuffer dest = new StringBuffer(len);
	char c;

	for (i = (len - 1); i >= 0; i--) {
	    c = string.charAt(i);
	    if (Character.isLetterOrDigit(c)) {
		dest.append(c);
	    }
	}

        return dest.toString().toLowerCase();
    }


    public static boolean areAnagram(String phrase1, String phrase2) {
	String s1 = cleanUp(phrase1);
  	StringBuffer sb2 = new StringBuffer(cleanUp(phrase2));
	int s1Length = s1.length();
	int i, j;
	char s1Char;

	if (s1Length != sb2.length()) {
	    return false;
	}

	iLoop:
	for (i = 0; i < s1Length; i++) {
	    s1Char = s1.charAt(i);
	    for (j = 0; j < sb2.length(); j++) {
		if (s1Char == sb2.charAt(j)) {
		    sb2 = sb2.deleteCharAt(j);
		    continue iLoop;
		}
	    }
	    return false;
	}

	return true;
    }


    public static void main(String[] args) throws IOException {

	// set up for interactice input
	BufferedReader consoleIn =
		new BufferedReader(new InputStreamReader(System.in));

	while (true) {
	    System.out.print("\nAnagramTester (type \"quit\" to exit):"
		    + "\n phrase1-> ");
	    String phrase1 = consoleIn.readLine();

	    // quit if requested
	    if ((phrase1 == null) || phrase1.equals("quit")) {
		break;
	    }

	    System.out.print(" phrase2-> ");
	    String phrase2 = consoleIn.readLine();

	    // quit if requested
	    if ((phrase2 == null) || phrase2.equals("quit")) {
		break;
	    }


	    System.out.println("\n--> Testing whether the following "
		    + "phrases are anagrams of each other:");
	    System.out.println("--> " + phrase1);
	    System.out.println("--> " + phrase2);

	    if (areAnagram(phrase1, phrase2)) {
		System.out.println("--> These phrases ARE anagrams"
		    + " of each other!");
	    } else {
		System.out.println("--> These phrases ARE NOT anagrams"
		    + " of each other!");
	    }
	}

    }
}
