# wget http://cs.whitman.edu/~davisj/cs/167/2016F/exmpls/piglatin.py
VOWELS = "aeiouyAEIOUY"

def piglatin(word):
  """Returns the pig latin equivaled of the string word. (6.3.3)
  Example: piglatin('python') returns 'ythonpay'.
  """
  # Challenge for you: How to handle y as a consonant, e.g., in "yellow"?
  # y is a consonant if it's followed by a vowel.
  if word[0] in VOWELS:
    return word + "yay"
  #Next line only works for words starting with a single consonant
  #return word[1:] + word[0] + "ay"
  #Solution for words starting with multiple consonants
  # Find index of the first vowel
  index = 0
  while word[index] not in VOWELS:
    index += 1
  # Split word on index of first vowel and reassemble
  return word[index:] + word[:index] + "ay"

def pigLatinDict(inputFilename, outputFilename):
  """Given an input file, writes the pig latin equivalent of every word 
  to the output file.
  Assume there is exactly one word on each line.
  """
  inputFile = open(inputFilename, "r", encoding="UTF-8") # Open the input file
  outputFile = open(outputFilename, "w", encoding="UTF-8") # Open output file
  for word in inputFile:                # Read each line
    word = word[:-1]           # Remove newline character from end of word
    pig = piglatin(word)                # Call piglatin on each word
    outputFile.write(pig)               # Print the result to the output file
    outputFile.write("\n")
  inputFile.close()                     # Close the files
  outputFile.close()

def pigLatinWeb(url, outputFilename):
  """Given a url for a text file, create a new file with the given name
  containing all the words transformed into pig latin.
  Assumes there is one word per line.
  """
  import urllib.request as web
  webpage = web.urlopen(url)            # Open the web page
  outputFile = open(outputFilename, "w", encoding="UTF-8") # Open output file
  for line in webpage:
    word = line.decode("UTF-8")
    word = word[:-1]
    if word == "":
      continue              # Skip over blank lines
    pig = piglatin(word)
    outputFile.write(pig + "\n")
  webpage.close()
  outputFile.close()

def main():
  pigLatinWeb("http://www.rupert.id.au/resources/1-1000.txt", 
              "piglatin1000.txt")

if __name__=="__main__":
  #If this program is running from the command line,
  #and not as a module in another function, call main.
  main()
