import sys
from collections import Counter




def most_common_letter(filename):
    try:
        with open(filename, 'r') as f:
            contents = f.read().replace(' ', '') # remove whitespace characters
            letter_counts = Counter(contents) # count the occurrences of each letter
            most_common = letter_counts.most_common(1)[0] # get the most common letter and its count
        return most_common
    except FileNotFoundError:
        print("File not found!")
        exit()

def count_the(filename):
    try:
        with open(filename, 'r') as f:
            contents = f.read() # read the contents of the file
            all_words = re.findall(r'\w+'?\w*', contents.lower()
            word_counts = Counter(word.lower() for word in contents.split()) # count the occurrences of each word, ignoring case
            the_count = word_counts['the'] # get the count of the word “the”, regardless of case
            total_count = sum(word_counts.values()) # get the total number of words in the file
            percent = "{0:.2f}".format(the_count / total_count * 100) # calculate the percentage of "the"s with two decimal places

        return (the_count, total_count, percent) # return a tuple containing the counts and percentage
    except FileNotFoundError:
        print("File not found!")
        exit()

def write_first_ten_words(filename):
    try:
        with open(filename, 'r') as f:
            contents = f.read().split() # split the contents into words
            first_ten = contents[:10] # get the first ten words
        with open('Exercise_8_output.txt', 'w') as f:
            f.write(' '.join(first_ten)) # write the first ten words to a new file
    except FileNotFoundError:
        print("File not found!")
        exit()

if len(sys.argv) != 2:
    print("Usage: python3 program.py <filename>")
    exit()

filename = sys.argv[1]
common = most_common_letter(filename)
the_count, total_count, percent = count_the(filename)
write_first_ten_words(filename)

print("{} is the most common letter. It occurs {} times.".format(common[0].lower(), common[1]))
print("The is {} of {} words or {}%.".format(the_count, total_count, percent))
print("The first ten words of the file have been written to Exercise_8_output.txt.")

