package ua.nure.jfn.task4;

import java.util.Scanner;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class WordContainer {

	private static Pattern WORD_PATTERN = Pattern.compile("\\S+");

	private ArrayList<Word> words = new ArrayList<>();

	public static void main(String[] args) {
		WordContainer container = new WordContainer();
		container.readAndProcessInput();
		container.printWords();
	}

	private void readAndProcessInput() {
		Scanner scanner = new Scanner(System.in);

		String input;
		outer: while (scanner.hasNextLine()) {
			input = scanner.nextLine();

			Matcher matcher = WORD_PATTERN.matcher(input);
			while (matcher.find()) {
				String wordContent = matcher.group();

				if (wordContent.equalsIgnoreCase("stop"))
					break outer;

				addWord(wordContent);
			}
		}
		scanner.close();
	}

	private void addWord(String content) {
		Word newWord = new Word(content);

		int i = words.indexOf(newWord);
		if (i == -1) {
			words.add(newWord);
		} else {
			words.get(i).incrementFrequency();
		}
	}

	private void printWords() {
		words.sort(null);
		for (Word word : words)
			System.out.println(word);
	}
}
