package main

import (
	"fmt"
	"io/ioutil"
	"path/filepath"
	"sort"
	"strings"
)

/* Pair type */
type Pair struct {
	key   string
	value int
}

/* Pair Slice type */
type PairSlice []Pair

/* Functions used for sort */
func (s PairSlice) Len() int {
	return len(s)
}

func (s PairSlice) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}

func (s PairSlice) Less(i, j int) bool {
	if s[i].value == s[j].value {
		return s[i].key < s[j].key
	} else {
		return s[i].value > s[j].value
	}
}

func main() {
	const path = "../testdata"
	dataDir, err := ioutil.ReadDir(path)
	if err != nil {
		fmt.Println("Directory not found!")
		return
	}

	dict := make(map[string]int)
	for _, file := range dataDir {
		data, _ := ioutil.ReadFile(filepath.Join(path, file.Name()))
		word := ""
		for i := range data {
			if data[i] >= 'A' && data[i] <= 'Z' {
				data[i] += 'a' - 'A' // to lower case
			}
			if data[i] >= 'a' && data[i] <= 'z' || word != "" && data[i] == '\'' {
				word = strings.Join([]string{word, string(data[i])}, "")
			} else if word != "" {
				dict[word]++
				word = ""
			}
		}
		if word != "" {
			dict[word]++
		}
	}

	answer := make(PairSlice, 0)
	for word, cnt := range dict {
		answer = append(answer, Pair{word, cnt})
	}
	sort.Sort(answer)
	for _, pair := range answer {
		fmt.Printf("%s\t%d\n", pair.key, pair.value)
	}
}
