text: import fileinput
  import os
  import shutil
  import time
  from sitemap import *
  
  
  def GenerateFiles(epsiodefilename, cardfilename, pagefilename, maincardfilename, folderName):
  
      episodeInfo = parseEpisode(episodefilename)
  
      newCardFilename = episodeInfo[0]+"_Card.html"
      newMainCardFilename = episodeInfo[0]+"_MainCard.html"
      newPageFilename = episodeInfo[0]+".html"
  
      src_dir = os.getcwd()
      # clean up, in case files had been generated previously, to avoid errors
      # creates a backup of the edited files the first time only
      logMessage("cleaning up previous automation attempts")
      cleanAutomation(episodeInfo[0], newPageFilename, folderName)
      # time.sleep(15) #to see if automated deleting is working
  
      # start generating pages
      logMessage("creating copies of the files to edit")
      os.makedirs(folderName+episodeInfo[0])
      shutil.copyfile(cardfilename, newCardFilename)
      shutil.copyfile(pagefilename, newPageFilename)
      shutil.copyfile(maincardfilename, newMainCardFilename)
  
      # generates html code
      logMessage("generating new html files")
      generateCard(episodeInfo, newCardFilename)
      generateMainCard(episodeInfo, newMainCardFilename)
      generatePage(episodeInfo, newPageFilename)
  
      logMessage("automatically updating the html of the website")
      # updating and moving files automatically
      # copies the generated episode file to the main site
      shutil.copyfile(newPageFilename, "../pages/episodeList/"+newPageFilename)
  
      # copies the card into episodeIndex.html
      updateIndex(newMainCardFilename)
      updateEpisodeIndex(newCardFilename)
  
      logMessage("cleaing up remaining files")
      # file organization
      shutil.move(newCardFilename, folderName+episodeInfo[0])
      shutil.move(newPageFilename, folderName+episodeInfo[0])
      shutil.move(newMainCardFilename, folderName+episodeInfo[0])
  
      print("enter y if you're running this in a linux environment and have the same path setup as Owen")
      text = input() 
      if(text == "y" or text == "Y"):
          mainRoutine()
          if os.path.exists("../sitemap.xml"):
              os.remove("../sitemap.xml")
          shutil.move("sitemap.xml", "..")
      
      print('completed, check log.txt for more information')
      time.sleep(2)
  
  
  def cleanAutomation(filename1, filename2, foldername):
      #logMessage(not os.listdir(folderName+filename1))
      if (os.path.exists(folderName+filename1) or os.path.exists("../pages/episodeList/"+filename2) and os.path.exists(folderName+filename1)):
          if os.path.exists(folderName+filename1):
              shutil.rmtree(folderName+filename1)
          if os.path.exists("../pages/episodeList/"+filename2):
              os.remove("../pages/episodeList/"+filename2)
          # todo: restore the other 2 files from backup perhaps?
      else:
          logMessage("since this is the first time for this episode, taking a backup")
          if os.path.exists(folderName+filename1):
              shutil.rmtree(folderName+filename1)
          d = datetime.datetime.now()
          unixtime = str(time.mktime(d.timetuple()))[:-2]
          shutil.copyfile("../pages/episodeIndex.html", "backups/episodeIndex"+unixtime+".backup")
          shutil.copyfile("../index.html", "backups/index"+unixtime+".backup")
  
  def logMessage(message):
      with open("log.txt", "a") as logFile:
          logFile.write(message + "\n")
  
  # updates the homepage automatically, works really great
  def updateIndex(filename):
      indexFilename = "../index.html"
      i = -1
      j = 0
      newIndex = []
      maincard = open(filename, "r").readlines()
      with open(indexFilename, 'r') as file:
          for line in file.readlines():
              i += 1
              if "<!--Autogenerated-->" in line or (j > 0 and j < 14): #todo replace the 14 with something passed in or whatever
                  newIndex.append(maincard[j])
                  j += 1
                  continue
              newIndex.append(line)
      open(indexFilename, 'w').close()
      with open(indexFilename, "w") as file:
          for line in newIndex:
              file.write(line)
  
  # updates the index, some indentation gets messed up, but appears to work overall
  def updateEpisodeIndex(filename):
      indexFilename = "../pages/episodeIndex.html"
      i = -1
      j = 0
      k = -1
      newIndex = []
      oldEpisode = []
      card = open(filename, "r").readlines()
      with open(indexFilename, 'r') as file:
          for line in file.readlines():
              i += 1
              checkFlag = ("Autogenerated" in line and k == -1) or (k >= 0 and j < len(card)-1)
              if checkFlag:
                  if k == -1:
                      k = i
                  newIndex.append(card[j])
                  oldEpisode.append((line))
                  j += 1
              else:
                  newIndex.append(line)
      k+= len(card)-1
      newIndex = newIndex[:k] + oldEpisode + newIndex[k:]
      open(indexFilename, 'w').close()
      with open(indexFilename, "w") as file:
           for line in newIndex:
               file.write(line)
  
  #reigon Gets the data from the
  def generateCard(info, filename):
      EPISODEFILENAME, IMAGENAME, EPISODETITLE, EPISODESUBTITLE, PAGETITLE, BUZZSPROUTURL, SPOTIFYURL, YOUTUBEURL, CITATIONS = GetPageData(
          info)
  
      with open(filename, 'r') as file:
          filedata = file.read()
  
      filedata = getBasicData(filedata, EPISODEFILENAME, IMAGENAME, EPISODETITLE, EPISODESUBTITLE)
  
      with open(filename, 'w') as file:
          file.write(filedata)
  
  
  def generateMainCard(info, filename):
      EPISODEFILENAME, IMAGENAME, EPISODETITLE, EPISODESUBTITLE, PAGETITLE, BUZZSPROUTURL, SPOTIFYURL, YOUTUBEURL, CITATIONS = GetPageData(
          info)
  
      with open(filename, 'r') as file:
          filedata = file.read()
  
      filedata = getBasicData(filedata, EPISODEFILENAME, IMAGENAME, EPISODETITLE, EPISODESUBTITLE)
  
      with open(filename, 'w') as file:
          file.write(filedata)
  
  
  def generatePage(info, filename):
      EPISODEFILENAME, IMAGENAME, EPISODETITLE, EPISODESUBTITLE, PAGETITLE, BUZZSPROUTURL, SPOTIFYURL, YOUTUBEURL, CITATIONS = GetPageData(
          info)
  
      with open(filename, 'r') as file:
          filedata = file.read()
  
      filedata = editData(filedata, EPISODEFILENAME, IMAGENAME, EPISODETITLE,
                              EPISODESUBTITLE, PAGETITLE, BUZZSPROUTURL, SPOTIFYURL, YOUTUBEURL,CITATIONS)
  
      with open(filename, 'w') as file:
          file.write(filedata)
  #endreigon
  
  #reigon Parses and Edits the Page Data
  def GetPageData(info):
      EPISODEFILENAME = info[0]
      IMAGENAME = info[1]
      EPISODETITLE = info[2]
      EPISODESUBTITLE = info[3]
      PAGETITLE = info[4]
      BUZZSPROUTURL = info[5]
      SPOTIFYURL = info[6][info[6].rindex('/')+1:]
      YOUTUBEURL = info[7][info[7].rindex('=')+1:]
      CITATIONS = info[8]
      return EPISODEFILENAME, IMAGENAME, EPISODETITLE, EPISODESUBTITLE, PAGETITLE, BUZZSPROUTURL, SPOTIFYURL, YOUTUBEURL, CITATIONS
  
  def editData(filedata, EPISODEFILENAME, IMAGENAME, EPISODETITLE, EPISODESUBTITLE, PAGETITLE, BUZZSPROUTURL, SPOTIFYURL, YOUTUBEURL,CITATIONS):
      filedata = getBasicData(filedata, EPISODEFILENAME, IMAGENAME, EPISODETITLE, EPISODESUBTITLE)
      filedata = filedata.replace('PAGETITLE', PAGETITLE)
      filedata = filedata.replace('BUZZSPROUTURL', BUZZSPROUTURL)
      filedata = filedata.replace('SPOTIFYURL', SPOTIFYURL)
      filedata = filedata.replace('YOUTUBEURL', YOUTUBEURL)
      filedata = filedata.replace('CITATIONS', CITATIONS)
      return filedata
  
  def getBasicData(filedata, EPISODEFILENAME, IMAGENAME, EPISODETITLE, EPISODESUBTITLE):
      filedata = filedata.replace('EPISODEFILENAME', EPISODEFILENAME)
      filedata = filedata.replace('IMAGENAME', IMAGENAME)
      filedata = filedata.replace('EPISODETITLE', EPISODETITLE)
      filedata = filedata.replace('EPISODESUBTITLE', EPISODESUBTITLE)
      return filedata
  #endreigon
  
  #Hopefully works with linux and windows
  def parseEpisode(episodefilename):
      episode = open(episodefilename, "r+")
      lines = [line for line in episode.readlines()]
      linesParsed = []
      for _ in lines:
          if _[-2:] == "\r\n":
              linesParsed.append(_[0:-2])
              continue
          elif _[-1:] == "\n":
              linesParsed.append(_[0:-1])
              continue
          else:
              linesParsed.append(_)
      return linesParsed[linesParsed.index("---")+1:]
  
  
  if __name__ == "__main__":
      #print('please note that the sitemap is currently only working on linux environments, please contact Owen to generate it')
      print("enter y if you're sure you want to do this, don't do it until the thumbnail image is in place!")
      print("please make sure you have read ../help/help.pdf and have followed the steps exactly")
      text = input() 
      if(text != "y" and text != "Y"):
          exit()
      episodefilename = "episode.txt"
      cardfilename = "templates/card.html"
      maincardfilename = "templates/mainCard.html"
      pagefilename = "templates/page.html"
      folderName = "./GeneratedPages/"
      GenerateFiles(episodefilename, cardfilename,
                    pagefilename, maincardfilename, folderName)
  