import java.util.Iterator;
import java.util.NoSuchElementException;
import java.io.Reader;
import java.io.IOException;
import java.io.StringWriter;

/** 
 * WordScanner
 *
 *  Provides a String iterator that wraps a Reader.  Objects of this class
 *  scan through the input, returning the sequence of legal <i>words</i>. 
 *  
 *  A word is a string of letters (upper and lower case A-Z) that does not
 *  include any whitespace, numbers or punctuation characters.  
 *   
 *  The scanner returns the words in the order found, skipping any punctuation,
 *  numbers or whitespace. 
 * 
 * 
 */
public class WordScanner implements Iterator<String> { 
	private Reader r;
	private int c;   
	
	// Invariant: 
	//    c   is -1 for EOF, otherwise the int representation 
    //        for letter starting the next word.
	
	public WordScanner (Reader initR) {
		r = initR;
		c = -1;
		skipNonLetters(); 
	}
	
	// scans the file to make c equal to the next letter character in 
	// the file. If there are none left, c is -1.
	private void skipNonLetters() {
		try {
			c = r.read();   // will return -1 if the end of the file is reached
			while (c != -1 && !Character.isLetter(c)) {
				c = r.read();
			}
		} catch (IOException e) {
			c = -1;
		}
	}
	
	/**
	 *  Returns true if there is a word available.
	 */
	public boolean hasNext() {
		return (c != -1);
	}

	/** 
	 * Returns the next word available from the Reader and then skips 
	 * all non-letter characters. 
	 * 
	 * Throws "NoSuchElementException" if there is not another character
	 * 
	 * @see java.util.Iterator#next()
	 */
	public String next() {
		if (c == -1) throw new NoSuchElementException();
		// a "buffer" to read the word into
		StringWriter buf = new StringWriter();
		try {
			while (Character.isLetter(c)) {
				buf.write(c);
				c = r.read();
			} 
		} catch (IOException e) {
			throw new NoSuchElementException();
		}
		skipNonLetters();
		return buf.toString();
	}

	/** 
	 * Unsupported by this iterator.
	 */
	public void remove() {
		throw new UnsupportedOperationException ();

	}
	

}

