#!/usr/bin/python
#
#**********************************************************************
#*************Play By File Transfer Protocol***************************
#*************A script for Space Empires V  ***************************
#*************Made by se5a.                 ***************************
#*************THIS VERSON IS   BETA!!      ***************************
#*************                              ***************************
#**********************************************************************
#
#
# Vars list:
#
#
# function list:
# YesNo():
#       just a y/n question, loops if input is not 'y' or 'n' or 'q', make sure to print question before calling!
#       use yesno = YesNo() when calling, Returns vars: answer
#
# FtpProgU(block):
# FtpProgD(block):
#       These two functions are meant to print a dot (.) for each block transferd over FTP
#           currently they do not work and are not used (V0.050)
#
# FobjExist(fobjexist, gamedata, gamedate):
#       This function checks to see if the file exists already or not, returns True or False.
#       most places it creates the file name from the fobjexist string, however
#       in some cases the filename cannot be created from the gamedata[] list
#       so sending the whole filename to this function will also work.(ie, ZipIt() multiple plr files)
#       
#
# IndexHlp():
#       function does what you would expect. is a help index.
#
# GameSetup():
#       funtion gets information needed from the user. this uses a recursive loop
#       use gamesetup = GameSetup() when calling, and gamesetup[0] [1] [2] [4] for the four vars it returns.
#       [gamename, hostflag, maxplr, playnum]
#
# FtpSetup ():
#       function gets information for FTP connection
#       [ftpserv, ftpuser, portnum, ftppath]

#
# SaveData(gamesetup, ftpsetup):
#       This function saves information from GameSetup() and FtpSetup().
#
# ZipIt(ziptype, maxplrI, gamename, playnum, gamedate):
#       function zips the files
#       use ZipPlr(maxplrI, gamename, prepros) to call. currently returns no vars
#
# UnZip(filename):
#       function does what you think it does: unzips stuff.
#
# FtpIt(ftptype, hostzip, plrzip, plrfile):
#       function handles file transfer to and from an FTP host.
#
# IndexGames():
#       function lists all saved games and allowes the user to pick one.
#       returns gamedata[0] to [8]
#
# IndexEdit()
#       function allows the user to edit or del current game setup.
#
# IndexHst(gamedata):
#       This function is the host menu.
#
# IndexPlr(gamedata):
#       This function is the player menu.
#

# Todo list:
#
#   Catch more errors and warn the user as to what maybe wrong.
#
#   Get FTP progress bar working.
#   Create a PBIRC option...



import os
import zipfile
from ftplib import FTP

global debug        #yes I used a global var, naughty me... this is just a swich as to weather you 
debug = False        #want to get spammed with debug information or not.
version = '0.101b'

def YesNo():
    answer = raw_input("(y/n): ")
    while answer != 'y' and answer != 'n' and answer != 'q':
        print "only input (y/n) please"
        answer = raw_input("(y/n): ")
    return answer

def FtpProgU(block):
    fobj
    print ".",
def FtpProgD(file):
    #print file
    #print block
    file.write(block)
    print ".",

def FobjExist(fobjexist, gamedata, gamedate):

    gamename = gamedata[0]
    hostflag = gamedata[1]
    maxplr = gamedata[2]
    playnum = gamedata[3]
    if fobjexist == 'hostzip':
        fobjexist = gamename+"Hst"+gamedate+".zip"              #This one gets uploaded
    elif fobjexist == 'rrzip':
        fobjexist = zipname = gamename+"RR"+gamedate+".zip"           #This one gets uploaded round robbin.
    elif fobjexist == 'prepzip':
        fobjexist = gamename+"Pre"+gamedate+".zip"              #This one is a backup of pre-prossesed files
    elif fobjexist == 'plrzip':
        fobjexist = gamename+"Plr"+playnum+gamedate+".zip"      #This is the zipped player files
    elif fobjexist == 'plrfile':
        fobjexist = gamename+"_plr_"+playnum+".plr"             #This is the unzipped plr files
    elif fobjexist == 'gamefile':
        fobjexist = gamename+".gam"							    #game file for players
    elif fobjexist == 'logfile':
        fobjexist = gamename+"_log.mvl"						    #log file for players 
    elif fobjexist == 'cmbtfile':
        fobjexist = gamename+"_current_replay_combat.cmb"		#combat file for players
    elif fobjexist == 'plogfile':
        fobjexist = gamename+"_plr_"+playnum+"_log.hlg"		    #players history log 
    elif fobjexist == 'statfile':   
        fobjexist = gamename+"_plr_"+playnum+"_stats.txt"	    #players stats 
    else:
        if debug: print fobjexist                               #some bits cycle the plr num so it's 
        fobjexist = os.access(fobjexist, os.F_OK)               # easyer to just pass the filename.
        if debug: print fobjexist
        return fobjexist
    if debug: print fobjexist
    fobjexist = os.access(fobjexist, os.F_OK)                   #checks for existance and returns fobjexist as boolan
    if debug: print fobjexist
    return fobjexist
 
def IndexHlp():
    donext = '0'
    while donext != 'q': 
        reloop = False            
        while donext != 'q' or reloop != True:
            print"Welcome to the help Index"
            print"[1] to read help on setting up a game in space empires for PBFTP"
            print"[2] to read help on setting up a game in this application as a host"
            print"[3] to read help on setting up a game in this application as a player"
            print"[4] to read about how Round Robin hosting works"
            print"[v] to read version log"
            print"[q] to return to last menu"
            donext = raw_input()
            if donext == '1':
                print"set up a multiplayer game in Space Empires V as you normaly would"
                print"In the multiplayer settings select:"
                print"Multiplayer savegame filename = this MUST be lowercase * "
                print"Savegame directory path       = leave this blank"
                print"Turn Style                    = Similtanious play"
                print"Play Style                    = Different Mashines"
                print"connection type               = Manual file moving"
                print""
                print"Once you've checked everything, start the game"
                print"The game should then tell you to send every one the game files."
                print"at this point, it's only the gamename.gam file"
                print"now you need to set up the game in this PBFTP application"
                print" * if you do use caps, se5 will save as lowercase on the second turn"
                print" if this happens, either do the first turn manualy"
                print"making sure you enter the gamename lowercase in PBFTP"
                print"if you forget that, you can edit the PBFTP.dat"
                inp = raw_input('<... press the anykey key to go back to the help index')
                reloop = True
            if donext == '2':
                print"Select option [2] in the main index"
                print"The program will then ask you a bunch of things about the game"
                print"firstly the game name, if this game has already been set up"
                print"you will not be able to enter it again"
                print"currently there is no way to del or edit a game setup"
                print"this can be done manualy however, by editing the PBFTP.dat file"
                print"Next you will be asked weather you are the host"
                print"input y"
                print"then the number of human players"
                print"you will then be asked what number YOUR player is"
                print"if you are playing the game enter YOUR player number"
                print"or 0 if you are not playing, only prossessing the turns"
                inp = raw_input('<... press the anykey key to continue')
                print"now you will be asked information on the FTP server"
                print"this is prety self explanitory,"
                print"all you have to worry about is syntax"
                print"for the server, don't put ftp://"
                print"just the name, i.e. server.net"
                print"for the path, just something like se5a/pbftp games"
                print"the path MUST exist, currently PBFTP does not make folders"
                print"if you screw up, it doesn't matter,"
                print"PBFTP checks the FTP info by trying to connect before it saves"
                inp = raw_input('<... press the anykey key to go back to the help index')
                reloop = True
            if donext == '3':
                print "setting up PBFT as a player is dead easy"
                print "just select option [2] from the main index"
                print "enter the game name,"
                print "and enter n when it askes if you are the host"
                print "after that it's just setting up the FPT addres and stuff"
                inp = raw_input('<... press the anykey key to go back to the help index')
                reloop = True
            if donext == '4':
                print "Round Robin hosting is for two player games"
                print "it's best when both players can't play turns at the same time"
                print "What happens is you download the turnfiles, [2] which includes:"
                print "the .gam file and other necicary files to play your turn"
                print "the .plr file of the other player"
                print "you play your turn"
                print "you will now have the host files, and both .plr files"
                print "use [3] to zip up the preprosessed files 'justincase'"
                print "you now prosess the game turn in SEV"
                print "you now have the turn files, play YOUR turn"
                print "and now select [4] to zip up the turn files"
                print "and [5] to upload them"
                print "the other player now does the same thing"
                print "downloads, plays, zips, prosesses, plays, zips and uploads"
                print "rinse and repeat"
                inp = raw_input('<... press the anykey key to go back to the help index')
                reloop = True
            if donext == 'v':
                print" Version Log:"
                print"0.070a"
                print"  added an index for continuing an already saved game, rather than having the user type the name of the"
                print"  game and looking for it in the .dat file. (IndexGames(): function)"
                print"  removed GetData function as it was obsoleated by IndexGames():"
                print"0.071a"
                print"  changed dating system to use decimal points."
                print"0.072a"
                print"  added game setup editing index"
                print"  games can now be deleted, PBFTP currenly breaks when trying to save an"
                print"  edited setup however, also the edit hostflag does not currently work."
                print" 0.073a"
                print"  quickfixed a bug where game setup would not work due to old function"
                print"  being removed, and still used (getdata)"
                print"  fixed plr file not being found."
                print"0.074a"
                print"  fixed plr upload bug"
                print"0.075a"
                print"  cleaned up unused code, added an index for the diferent hostflags."
                print"  editing a game nearly works, except for one bug where it doesnt work..."
                print"  it puts extra *** between the lists."
                print"  moved this version log the help index"
                print"0.080a"
                print"  THIS is the pre beta version! yay! :-)"
                print"  Implemented round robin hosting"
                print"  fixed editing setup bugs, these were caused by my lack of"
                print"  understaning of how list objects work, and annother one because"
                print"  I was appending a string to a list"
                print"0.100b"
                print"  fixed a small bug where it didn't go to the round robbin index"
                print"  this is beta version, there may be bugs I don't know about"
                print"  but I think I've got most things..."
                print"0.101b"
                print"  Fixed more bugs with round robin hosting, "
                print"  and wrote a helpfile section on it"
                inp = raw_input('<... press the anykey key to go back to the help index')
            else:
                reloop = True
                
                
def GameSetup():
    print "Please enter the game filename, do NOT include file extensions."
    gamename = raw_input("Game Name is: ")
    pbftpdat_exists = os.access('PBFTP.dat', os.F_OK)
    if pbftpdat_exists == True:     
        oupf = open('PBFTP.dat', 'r')
        read = oupf.readline()
        issetup = read.count(gamename+':=')
        oupf.close()
        print issetup
        while issetup > 0:
            print "this game is already setup"
            numgam = read.count('***') -1
            allgames = read.split('***')
            gamnum = 0
            while gamename != gamedata[0]:
                gamedata = allgames[gamnum].split(':=')
                if gamnum >= numgam: 
                    break
                else:
                    gamnum = gamnum +1   
            if gamename == gamedata[0]:
                IndexEdit(gamedata)
                return
            
    hostflag = IndexHstflag()
    if hostflag == 'q':
        return
    
    if hostflag == 'FALSE':
        maxplrI = 20
        maxplr = '20'
    else: 
        print "Please enter the number of (human) players in this game"
        maxplr = raw_input("Number of players: ")
        maxplrI = int(maxplr)

    if hostflag == 'TRUE':
        playnum == '0'
    else:
        print "Please input your player number, 1 to 20"
        playnum = raw_input("Your Player number is: ")
        playnumI = int(playnum)
    
    if playnum == '0' and hostflag != 'FALSE':
        hostflag = 'TRUE'
        print "You are the host"
        print "You are NOT a player"
        print "There are "+maxplr+"human players in this game."
        print "Is this correct?"
        yesno = YesNo()
        if yesno == 'y':
            return [gamename, hostflag, maxplr, playnum]
        elif yesno == 'n':
            return GameSetup()
        else:
            return    
    if hostflag!= 'TRUE' and playnumI > 0 and playnumI <= maxplrI:
        playnum = playnum.zfill(4)
        if hostflag == 'FALSE':
            print "You are NOT the host"
            print "You are player #"+playnum
            print "Is this correct?"
            yesno = YesNo()
            if yesno == 'y':
                return [gamename, hostflag, maxplr, playnum]
            else:
                return GameSetup()
        elif hostflag == 'BOTH':
            print "You are the host"
            print "You are player #"+playnum+" of"
            print maxplr+" human players in this game."
            print "Is this correct?"
            yesno = YesNo()
            if yesno == 'y':
                return [gamename, hostflag, maxplr, playnum]
            else:
                return GameSetup()
    if hostflag == 'RR':
        playnum = playnum.zfill(4)
        print "You are hosting round robbin style"
        print "You are player #"+playnum+" of"
        print maxplr+" human players in this game."
        print "Is this correct?"
        yesno = YesNo()
        if yesno == 'y':
            return [gamename, hostflag, maxplr, playnum]
        else:
            return GameSetup()
        
    else:
        if hostflag == 'FALSE' and playnum == 0:
            print "you have cotradicted yourself, you ask not to be host,"
            print "yet you ask to be host only,"
        elif playnum < 0:
            print "you can not have a negitive player number,"
        elif playnum > maxplr:
            print "you have chosen a player number larger than the maximum players allowed"
            print playnum
            print maxplr
        else: 
            print "You have chosen something invalid,"
        print "please try again."
        return GameSetup()

def FtpSetup ():
    ftpserv = raw_input("please enter ftp address: ")
    portnum = raw_input("please enter port number or 21 if youre unsure: ")
    ftpuser = raw_input("please enter FTP user login: ")
    ftppass = raw_input("please enter password: ")
    ftppath = raw_input("please enter path: ")
    print "Is this correct?"
    yesno = YesNo()
    if yesno == 'y':
        print "testing FTP"
        try:
            ftp = FTP()
            ftp.connect(ftpserv, portnum)
            ftp.login(ftpuser,ftppass)
            ftp.getwelcome()
            ftp.cwd(ftppath)
            print "FTP test successful, closing link."
            ftp.close()
        except: #eventualy warn the user what's causing the problem.
            print "FTP test failed."
            ftp.close()
            return FtpSetup()

        return [ftpserv, portnum, ftpuser, ftppass, ftppath]
    elif yesno == 'n':
        return FtpSetup()
    else:
        return
def SaveData(gamesetup, ftpsetup):
    gamename = gamesetup[0]
    hostflag = gamesetup[1]
    maxplr = gamesetup[2]
    playnum = gamesetup[3]

    ftpserv = ftpsetup[0]
    portnum = ftpsetup[1]
    ftpuser = ftpsetup[2]
    ftppass = ftpsetup[3]
    ftppath = ftpsetup[4]

    vb = ':='   #seperates vars in games
    gb = '***'  #seperates games

    inpf = open('PBFTP.dat', 'a')
    inpf.write(gamename+vb+hostflag+vb+maxplr+vb+playnum+vb+ftpserv+vb+portnum+vb+ftpuser+vb+ftppass+vb+ftppath+gb)
    inpf.close()
    return

def DelGame(gamedata):
    gamename = gamedata[0]
    oupf = open('PBFTP.dat', 'r')
    read = oupf.readline()
    oupf.close()
    allgames = read.split('***')
    delgame = ':='.join(gamedata)
    allgames.remove(delgame)
    alldata = '***'.join(allgames)
    inpf = open('PBFTP.dat', 'w')
    inpf.write(alldata)
    inpf.close()
    return

def SaveEdit(olddata, newdata):
    gamename = olddata[0]
    print gamename
    print olddata[0]
    print newdata[0]
    oupf = open('PBFTP.dat', 'r')
    read = oupf.readline()
    oupf.close()
    allgames = read.split('***')    #allgames is a list
    delgame = ':='.join(olddata)    #delgame is a string made from olddata which is a list
    allgames.remove(delgame)        #removes delgame(str) from allgames(list)
    newdata = ':='.join(newdata)    #newdata is now a string
    newdata = newdata+'***'         #appends *** to the end of newdata string
    alldata = '***'.join(allgames)  #alldata is a string made from allgames(list)
    alldata = alldata+newdata       #concitantes alldata and newdata
    
    inpf = open('PBFTP.dat', 'w')
    inpf.write(alldata)
    inpf.close()
    return
    
def ZipIt(ziptype, gamedata, gamedate):
    gamename = gamedata[0]
    maxplr = gamedata[2]
    playnum = gamedata[3]
    maxplrI = int(maxplr)
    ######Create var names for filenames likely to be used#####
    # files created by host
    gamefile = gamename+".gam"							    #game file for players
    logfile = gamename+"_log.mvl"						    #log file for players - what does this one do?
    cmbtfile = gamename+"_current_replay_combat.cmb"		#combat file for players
    plogfile = gamename+"_plr_"+playnum+"_log.hlg"		    #players history log 
    statfile = gamename+"_plr_"+playnum+"_stats.txt"	    #players stats 
    # files created by player
    plrfile = gamename+"_plr_"+playnum+".plr"			#game file for host
    #zipfiles
    print ziptype
    if ziptype == 'Plr':
        zipname = gamename+"Plr"+playnum+"_"+gamedate+".zip"
    else:
        zipname = gamename+ziptype+gamedate+".zip"
    zip_w = zipfile.ZipFile(zipname, "w")
    #justify for asthetics
    justnum = 30 + len(gamename)    
    just_gamefile = gamefile.ljust(justnum,'.')
    just_logfile = logfile.ljust(justnum,'.')
    just_cmbtfile = cmbtfile.ljust(justnum,'.')
    just_plogfile = plogfile.ljust(justnum,'.')
    just_statfile = statfile.ljust(justnum,'.')
    just_plrfile = plrfile.ljust(justnum,'.')
        
    if ziptype == 'Hst' or ziptype == 'Pre' or ziptype == 'RR':
        print "Creating zipfile"
        print just_gamefile,
        fobjexist = FobjExist('gamefile', gamedata, gamedate)
        if fobjexist == True:  
          zip_w.write(gamefile)
          print"Found and ziped"
        else:
          print"Cannot be found, this may NOT be normal"
        print just_logfile,
        fobjexist = FobjExist('logfile', gamedata, gamedate)
        if fobjexist == True:
          zip_w.write(logfile)
          print"Found and ziped"
        else:
          print"Cannot be found, this may be normal"
        print just_cmbtfile,
        fobjexist = FobjExist('cmbtfile', gamedata, gamedate)
        if fobjexist == True:
          zip_w.write(cmbtfile)
          print"Found and ziped"
        else:
          print"Cannot be found, this may be normal"
            
        zipnumI = 0
        while zipnumI < maxplrI:
            zipnumI = zipnumI + 1
            playnumz = str(zipnumI)
            playnumz = playnumz.zfill(4)
            plrfile = gamename+"_plr_"+playnumz+".plr"
            plrfile_exists = os.access(plrfile, os.F_OK)
            plogfile = gamename+"_plr_"+playnumz+"_log.hlg"
            plogfile_exists = os.access(plogfile, os.F_OK)
            statfile = gamename+"_plr_"+playnumz+"_stats.txt"
            statfile_exists = os.access(statfile, os.F_OK)
            just_plogfile = plogfile.ljust(justnum,'.')
            just_statfile = statfile.ljust(justnum,'.')
            just_plrfile = plrfile.ljust(justnum,'.')
            if ziptype == 'Pre' or ziptype == 'RR':
                print just_plrfile,
                fobjexist = FobjExist(plrfile, gamedata, gamedate)
                if fobjexist == True:
                    zip_w.write(plrfile)
                    print"Found and ziped"
                else:
                    print"Cannot be found"
            print just_plogfile,
            fobjexist = FobjExist(plogfile, gamedata, gamedate)
            if fobjexist == True:
                zip_w.write(plogfile)
                print"Found and ziped"
            else:
                print"Cannot be found"
            print just_statfile,
            fobjexist = FobjExist(statfile, gamedata, gamedate)
            if fobjexist == True:
                zip_w.write(statfile)
                print"Found and ziped"
            else:
                print"Cannot be found"
    elif ziptype == 'Plr' or ziptype == 'RR':
        fobjexist = FobjExist(plrfile, gamedata, gamedate)
        if fobjexist == True:
          zip_w.write(plrfile)
          print"Found and ziped"
        else:
          print"Cannot be found"
    
    zip_w.close()
    print "Files ziped, closing zipfile"
    return
def UnZip(filename):
    try:
        zname = zipfile.ZipFile(filename, 'r')
        for name in zname.namelist():
            file(name, 'wb').write(zname.read(name))
            print name
        print "Done"
    except:
        print"unzip failed"
    zname.close()
    return

def FtpIt(ftptype, gamedata, gamedate): #ftptype can be 'uphost' 'upplr' 'downhost' 'downplr' 'upany' 'downany'
    gamename = gamedata[0]
    hostflag = gamedata[1]
    maxplr = gamedata[2]
    playnum = gamedata[3]
    ftpserv = gamedata[4]
    portnum = gamedata[5]
    ftpuser = gamedata[6]
    ftppass = gamedata[7]
    ftppath = gamedata[8]
    
    playnumI = int(playnum)
    maxplrI = int(maxplr)
    
    hostzip = gamename+"Hst"+gamedate+".zip"
    plrzip = gamename+"Plr"+playnum+"_"+gamedate+".zip"
    plrfile = gamename+"_plr_"+playnum+".plr"
    rrzip = gamename+"RR"+gamedate+".zip"
    
    if ftptype == 'uphost':
        upfile = hostzip
        downfile = False
    elif ftptype == 'upplr':
        upfile = plrzip
        downfile = False
    elif ftptype == 'uprr':
        upfile = rrzip
        downfile = False
    elif ftptype == 'downhost':
        downfile = hostzip
        upfile = False
    elif ftptype == 'downrr':
        downfile = rrzip
        upfile = False
    else:
        downfile = plrzip
        upfile = False
        
    ftp = FTP()
    if debug:
        ftp.set_debuglevel(2)
        print ftptype
    print "attempting connection to:"+ftpserv+":"+portnum
    ftp.connect(ftpserv, portnum)
    print "attempting login with:"+ftpuser+":"+ftppass
    ftp.login(ftpuser,ftppass)
    ftp.getwelcome()
    print "attempting to find path:"+ftppath
    ftp.cwd(ftppath)
    
    if downfile == False:
        
        print "sending "+upfile
        try:
            fobj = open(upfile, 'rb')
            ftp.storbinary('STOR '+upfile, fobj)
            #ftp.storbinary('STOR '+upfile, FtpProgU)
            fobj.close()
            print "upload sucsessfull"
        except:
            print "upload failed"
       
    elif upfile == False and ftptype != 'downplr' :
        print "getting "+downfile
        try:
            wfobj = open(downfile, 'wb')
            ftp.retrbinary('RETR '+downfile, wfobj.write)
            #ftp.retrbinary('RETR '+downfile, FtpProgD)
            wfobj.close()
            print "download of turn files sucessfull"            
        except:
            print "download failed"
            ftp.close()
            return
        print "unzipping..."
        UnZip(downfile)

    elif ftptype == 'downplr':   #download the files as .plr files or .zip files
        print "[p] to download as .plr files,"
        print "[z] to download as .zip files." 
        plr_or_zip = raw_input()
        while plr_or_zip != 'p' and answer != 'z': #loop if the answer was anything other than p or z
            print "[p] to download as .plr files,"
            print "[z] to download as .zip files." 
            plr_or_zip = raw_input()
        if playnumI == 1:       #if host is player 1 then start looking for plr files at 2
            numplayI = 2
        else:
            numplayI = 1        #otherwise just start at 1
        while numplayI <= maxplrI:
            numplay = str(numplayI)
            numplay = numplay.zfill(4)
            
            if plr_or_zip == 'p':
                downfile = gamename+"_plr_"+numplay+".plr"
            elif plr_or_zip == 'z':
                downfile = gamename+"Plr"+numplay+gamedate+".zip"
            try:
                wfobj = open(downfile, 'wb')
                ftp.retrbinary('RETR '+downfile, wfobj.write)
                #ftp.retrbinary('RETR '+downfile, FtpProgD)
                wfobj.close()
                print downfile+" found and downloaded"
                if plr_or_zip == 'p':
                    print "removing "+downfile+".....",
                    ftp.delete(downfile)
                    print "done"
            except:
                print downfile+" could not be found."
            if plr_or_zip == 'z':
                UnZip(downfile)
            if numplayI + 1 == playnumI:      #if count == host player file, go up 2
                numplayI = numplayI + 2
            else:
                numplayI = numplayI + 1     #count up normaly.
        print "player file download compleated."

    elif ftptype == 'upany':
        print "type the name of the file you would like to upload: "
        upfile = raw_input()
        try:
            fobj = open(upfile, 'rb')
            ftp.storbinary('STOR '+upfile, fobj)
            #ftp.storbinary('STOR '+upfile, FtpProgU)
            fobj.close()
            print "upload sucsessfull"
        except:
            print "upload failed"

    elif ftptype == 'downany':
        #print "type the name of the file you would like to download: "
        downfile = raw_input()
    #try:
        file = open(downfile, 'wb')
        #ftp.retrbinary('RETR '+downfile, wfobj.write)
        ftp.retrbinary('RETR ' + downfile, FtpProgD)
        file.close()
        print "download sucessfull"
    #except:
    #    print "download failed"

    else:
        print "somethings screwed up" #should only print this if somthing has messed up with my code.
    print "closing the connection"
    ftp.close()
    return

def IndexHstflag():
    donext = '0'
    while donext != 'q': 
        reloop = False            
        while donext != 'q' or reloop != True:
            print "plese select from the following"
            print "[1] for host, not player"
            print "[2] for host AND player"
            print "[3] for player NOT host"
            print "[4] for round robbin hosting"
            donext = raw_input()
            if donext == '1':
                hostflag = 'TRUE'
                return hostflag
            if donext == '2':
                hostflag = 'BOTH'
                return hostflag
            if donext == '3':
                hostflag = 'FALSE'
                return hostflag
            if donext == '4':
                hostflag = 'RR'
                return hostflag
            if donext == 'q':
                return donext
            else:
                reloop = True
                
def IndexGames():
    pbftpdat_exists = os.access('PBFTP.dat', os.F_OK)
    gamedata = ['NONE']
    if pbftpdat_exists == True:
        oupf = open('PBFTP.dat', 'r')
        read = oupf.readline()
        numgam = read.count('***') -1
        allgames = read.split('***')
        donext = '0'
        while donext != 'q':
            reloop = False
            while donext != 'q' or reloop != True:
                gamnum = 0
                print "***Game Index***"
                while gamnum <= numgam:
                    gamedata = allgames[gamnum].split(':=')
                    print"[%s]" % (gamnum+1,),
                    print"for "+gamedata[0]
                    gamnum = gamnum +1
                print "[q] to quit to Main Index"
                oupf.close()
                donext = raw_input()
                try:
                    donextI = int(donext)
                    gamedata = allgames[donextI-1].split(':=')
                    return gamedata
                        #list of vars returned:
                        #gamename = gamedata[0]
                        #hostflag = gamedata[1]
                        #maxplr = gamedata[2]
                        #playnum = gamedata[3]

                        #ftpserv = gamedata[4]
                        #portnum = gamedata[5]
                        #ftpuser = gamedata[6]
                        #ftppass = gamedata[7]
                        #ftppath = gamedata[8]
                except:
                    if donext == 'q':
                        reloop = True
                    else:
                        reloop = True
        gamedata = ['QUIT']
        return gamedata     # 'QUIT' user quit
    return gamedata     # 'NONE' .dat file non existent

def IndexEdit(gamedata):
    olddata = gamedata[:]
    donext = '0'
    while donext != 'q': 
        reloop = False            
        while donext != 'q' or reloop != True:
            print"[D] to delete this game setup"
            print"[1] edit gamename..............."+gamedata[0]
            print"[2] edit hostflag..............."+gamedata[1]
            print"[3] edit max players............"+gamedata[2]
            print"[4] edit Your player number....."+gamedata[3]
            print"[5] edit FTP server address....."+gamedata[4]
            print"[6] edit FTP port number........"+gamedata[5]
            print"[7] edit FTP login name........."+gamedata[6]
            print"[8] edit FTP password..........."+gamedata[7]
            print"[9] edit FTP path..............."+gamedata[8]
            print"[u] undo changes"
            print"[s] save changes and exit"
            print"[q] quit editing without saving"
            donext = raw_input()

            if donext == 'D':
                DelGame(olddata)
                print"Are you sure you want to compleatly remove this gamesetup?"
                yesno = YesNo()
                if yesno == 'y':
                    print"Game Setup Deleted"
                    indexedit = 'DEL'
                    return indexedit
                else:
                    reloop = True
            if donext == '1':
                print "current gamename is "+gamedata[0]
                print "please enter a gamename"
                gamedata[0] = raw_input()
                reloop = True
            if donext == '2':
                print "current hostflag is "+gamedata[1]
                indexhstflag = IndexHstflag()
                if indexhstflag != 'q':
                    gamedata[1] = indexhstflag
                reloop = True
                
            if donext == '3':
                reloop2 = False
                while reloop2 == False:
                    print "current max players is "+gamedata[2]
                    print "plese enter max number of players"
                    donext = raw_input()
                    try:
                        donextI = int(donext)
                        if donextI > 0 and donextI < 21:
                            gamedata[2] = donext
                            donext = '0'
                            break
                        else:
                            reloop2 = False
                    except:
                        reloop2 = False
                reloop = True
                
            if donext == '4':
                if gamedata[1] != 'TRUE':
                    reloop2 = False
                    while reloop2 == False:
                        print "Your current player number is "+gamedata[3]
                        print "plese enter Your Player number"
                        donext = raw_input()
                        try:
                            donextI = int(donext)
                            if donextI > 0 and donextI <= gamedata[2]:
                                gamedata[3] = donext
                                donext = '0'
                                break 
                            else:
                                print "incorect entry"
                                reloop2 = False
                        except:
                            print "opps"
                            reloop2 = False
                    reloop = True
                    reloop2 = True
                else:
                    print "currently you are not a player, please edit the hostflag option first"
                    reloop = True
                
            if donext == '5':
                print "FTP server address is currently "+gamedata[4]
                print "plese enter new address"
                gamedata[4] = raw_input()
                reloop = True
                
            if donext == '6':
                reloop2 = False
                while reloop2 == False:
                    print "current port number is "+gamedata[5]
                    print "plese enter new port number"
                    donext = raw_input()
                    try:
                        donextI = int(donext)
                        gamedata[5] = donext
                        break
                    except:
                        reloop2 = False
                        
            if donext == '7':
                print "FTP server login is "+gamedata[6]
                print "plese enter new login"
                gamedata[6] = raw_input()
                reloop = True
                
            if donext == '8':
                print "FTP server pass is currently "+gamedata[7]
                print "plese enter new pass"
                gamedata[7] = raw_input()
                reloop = True
                
            if donext == '9':
                print "FTP server path is currently "+gamedata[8]
                print "plese enter new path"
                gamedata[8] = raw_input()
                reloop = True
                
            if donext == 's':
                gamedata = gamedata
                SaveEdit(olddata, gamedata)
                return
            if donext == 'u':
                gamedata = olddata[:]
                reloop = True
            if donext == 'q':
                return
            else:
                reloop = True

            
    
def IndexHst(gamedata):
    gamename = gamedata[0]
    hostflag = gamedata[1]
    maxplr = gamedata[2]
    playnum = gamedata[3]

    ftpserv = gamedata[4]
    portnum = gamedata[5]
    ftpuser = gamedata[6]
    ftppass = gamedata[7]
    ftppath = gamedata[8]
    
    gamedate = raw_input("please enter the game date i.e. 2400.0 for begining: ")
    gamedate = gamedate.split('.')
    gameyearI = int(gamedate[0]) # turn strings into ints
    gamemonthI = int(gamedate[1])
    gamedate = '.'.join(gamedate)
    
    maxplrI = int(maxplr)     
    playnumI = int(playnum)

    donext = '0'
    while donext != 'q': 
        reloop = False            
        while donext != 'q' or reloop != True:
            gamedate = gamedate.split('.')
            if gamemonthI > 9:
                gameyearI = gameyearI + 1
                gamemonthI = 0
            if gamemonthI < 0:
                gameyearI = gameyearI - 1
                gamemonthI = 9
            gameyear = str(gameyearI)
            gamemonth = str(gamemonthI)
            gamedate[0] = gameyear
            gamedate[1] = gamemonth
            gamedate = '.'.join(gamedate)
            print "***Host Index***"
            print "gamedate is: ",
            print gamedate
            print "what would you like to do?"
            print "[1] to download player, zip, wait for prosess, zip, and upload."
            print "[2] to download and unzip player file only."
            print "[3] to zip up the preprosessing files only."
            print "[4] to zip up host files only."
            print "[5] to upload the (ziped) host files only."        

            print "[>] to increase gamedate."
            print "[<] to decrease gamedate."
            print "[M] to edit or del this gamesetup"
            print "[u] to upload any file"
            print "[d] to download any file"
            print "[q] to quit to last index"
            donext = raw_input()
            
            if donext == '1' or donext == '2': #download player files.
                ftptype = 'downplr'
                FtpIt(ftptype, gamedata, gamedate)
            if donext == '1' or donext == '3': #zip up pre prosessed files as backup
                fobjexist = FobjExist('prepzip', gamedata, gamedate)
                if fobjexist == False:
                    ziptype = 'Pre'
                    ZipIt(ziptype, gamedata, gamedate)
                else:
                    print "this file exists already"
                    reloop = True
            if donext == '1' or donext == '4': #zip up post prosessing files
                fobjexist = FobjExist('hostzip', gamedata, gamedate)
                if fobjexist == False:
                    inp = raw_input('<... Prosses the turn then hit the anykey key to continue.>')
                    ziptype = 'Hst'
                    ZipIt(ziptype, gamedata, gamedate)
                    
                else:
                    print "this file exists already"
                    reloop = True
            if donext == '1' or donext == '5': #upload host files to ftp
                ftptype = 'uphost'
                FtpIt(ftptype, gamedata, gamedate)
                print"changing gamedate"
                gamemonthI = gamemonthI + 1
                
            if donext == 'M':
                indexedit = IndexEdit(gamedata)
                if indexedit == 'DEL':
                    return
                else:
                    reloop = True
                    
            if donext == '>' or donext == '.':
                gamemonthI = gamemonthI + 1
                reloop = True
            if donext == '<' or donext == ',':
                gamemonthI = gamemonthI - 1
                reloop = True
            if donext == 'u':
                ftptype = 'upany'
                FtpIt(ftptype, gamedata, '0')
                reloop = True
            if donext == 'd':
                ftptype = 'downany'
                FtpIt(ftptype, gamedata, '0')
                reloop = True
            if donext == 'q':
                reloop = True
            else:
                reloop = True
    return


def IndexPlr(gamedata):
    gamename = gamedata[0]
    hostflag = gamedata[1]
    maxplr = gamedata[2]
    playnum = gamedata[3]

    ftpserv = gamedata[4]
    portnum = gamedata[5]
    ftpuser = gamedata[6]
    ftppass = gamedata[7]
    ftppath = gamedata[8]
    
    gamedate = raw_input("please enter the game date i.e. 2400.0 for begining: ")
    gamedate = gamedate.split('.')
    gameyearI = int(gamedate[0]) # turn strings into ints
    gamemonthI = int(gamedate[1])
    gamedate = '.'.join(gamedate)
    
    maxplrI = int(maxplr)     
    playnumI = int(playnum)

    donext = '0'
    while donext != 'q': 
        reloop = False            
        while donext != 'q' or reloop != True:
            gamedate = gamedate.split('.')
            if gamemonthI > 9:
                gameyearI = gameyearI + 1
                gamemonthI = 0
            if gamemonthI < 0:
                gameyearI = gameyearI - 1
                gamemonthI = 9
            gameyear = str(gameyearI)
            gamemonth = str(gamemonthI)
            gamedate[0] = gameyear
            gamedate[1] = gamemonth
            gamedate = '.'.join(gamedate)
            print "***Player Index***"
            print "gamedate is: ",
            print gamedate
            print "[1] to zip and upload player file."
            print "[2] to zip your playerfile only."
            print "[3] to upload your zipped playerfile."
            print "[4] to download and unzip the hostfiles."
            print "[5] to unzip the hostfiles only."

            print "[>] to increase gamedate."
            print "[<] to decrease gamedate."
            print "[M] to edit or del this gamesetup"
            print "[u] to upload any file"
            print "[d] to download any file"
            print "[q] to quit to last index"
            donext = raw_input()
            if donext == '1':
                fobjexist = FobjExist('plrfile', gamedata, gamedate)
                if fobjexist == True:
                    ziptype = 'Plr'
                    ZipIt(ziptype, gamedata, gamedate)
                    ftptype = 'upplr'
                    FtpIt(ftptype, gamedata, gamedate)
            if donext == '2':
                fobjexist = FobjExist('plrfile', gamedata, gamedate)
                if fobjexist == True:
                    ziptype = 'Plr'
                    ZipIt(ziptype, gamedata, gamedate)
                else:
                    print "the .plr file does not exist, play the turn first"
                    reloop = True
            if donext == '3': # upload plr file.
                fobjexist = FobjExist('plrfile', gamedata, gamedate)
                if fobjexist == True:
                    ftptype = 'upplr'
                    FtpIt(ftptype, gamedata, gamedate)
                else:
                    reloop = True
            if donext == '4': #download host files.
                fobjexist = FobjExist('hostzip', gamedata, gamedate)
                if fobjexist == False:
                    ftptype = 'downhost'
                    FtpIt(ftptype, gamedata, gamedate)
                    print"changing gamedate"
                    gamemonthI = gamemonthI + 1
                   
                else:
                    print "this file already exists in your savegame folder"
                    reloop = True
            if donext == '5':
                UnZip(hostzip)
                reloop = True
                
            if donext == 'M':
                indexedit = IndexEdit(gamedata)
                if indexedit == 'DEL':
                    return
                else:
                    reloop = True
                
            if donext == '>' or donext == '.':
                gamemonthI = gamemonthI + 1
                reloop = True
            if donext == '<' or donext == ',':
                gamemonthI = gamemonthI - 1
                reloop = True
            if donext == 'u':
                ftptype = 'upany'
                FtpIt(ftptype, gamedata, '0')
                reloop = True
            if donext == 'd':
                ftptype = 'downany'
                FtpIt(ftptype, gamedata, '0')
                reloop = True
            if donext == 'q':
                reloop = True
            else:
                reloop = True
    return

def IndexRR(gamedata):
    gamename = gamedata[0]
    hostflag = gamedata[1]
    maxplr = gamedata[2]
    playnum = gamedata[3]

    ftpserv = gamedata[4]
    portnum = gamedata[5]
    ftpuser = gamedata[6]
    ftppass = gamedata[7]
    ftppath = gamedata[8]
    
    gamedate = raw_input("please enter the game date i.e. 2400.0 for begining: ")
    gamedate = gamedate.split('.')
    gameyearI = int(gamedate[0]) # turn strings into ints
    gamemonthI = int(gamedate[1])
    gamedate = '.'.join(gamedate)
    
    maxplrI = int(maxplr)     
    playnumI = int(playnum)

    donext = '0'
    while donext != 'q': 
        reloop = False            
        while donext != 'q' or reloop != True:
            gamedate = gamedate.split('.')
            if gamemonthI > 9:
                gameyearI = gameyearI + 1
                gamemonthI = 0
            if gamemonthI < 0:
                gameyearI = gameyearI - 1
                gamemonthI = 9
            gameyear = str(gameyearI)
            gamemonth = str(gamemonthI)
            gamedate[0] = gameyear
            gamedate[1] = gamemonth
            gamedate = '.'.join(gamedate)
            print "***Round Robin Index***"
            print "gamedate is: ",
            print gamedate
            print "what would you like to do?"
            print "[1] to download turnfiles, unzipzip, wait for prosess, zip, and upload."
            print "[2] to download and unzip turnfiles only."
            print "[3] to zip up the preprosessing files only."
            print "[4] to zip up turn files only."
            print "[5] to upload the (ziped) turn files only."        

            print "[>] to increase gamedate."
            print "[<] to decrease gamedate."
            print "[M] to edit or del this gamesetup"
            print "[u] to upload any file"
            print "[d] to download any file"
            print "[q] to quit to last index"
            donext = raw_input()
            
            if donext == '1' or donext == '2': #download player files.
                ftptype = 'downrr'
                FtpIt(ftptype, gamedata, gamedate)
                
            if donext == '1' or donext == '3': #zip up pre prosessed files as backup
                inp = raw_input('<... play your turn then hit the anykey key to continue.>')
                fobjexist = FobjExist('prepzip', gamedata, gamedate)
                if fobjexist == False:
                    ziptype = 'Pre'
                    ZipIt(ziptype, gamedata, gamedate)
                else:
                    print "this file exists already"
                    reloop = True
            if donext == '1' or donext == '4': #zip up post prosessing files
                fobjexist = FobjExist('rrzip', gamedata, gamedate)
                if fobjexist == False:
                    inp = raw_input('<... Prosses the turn then hit the anykey key to continue.>')
                    inp = raw_input('<... play your turn then hit the anykey key to continue.>')
                    ziptype = 'RR'
                    ZipIt(ziptype, gamedata, gamedate)
                    
                else:
                    print "this file exists already"
                    reloop = True
            if donext == '1' or donext == '5': #upload host files to ftp
                ftptype = 'uprr'
                FtpIt(ftptype, gamedata, gamedate)
                print"changing gamedate"
                gamemonthI = gamemonthI + 1
                
            if donext == 'M':
                indexedit = IndexEdit(gamedata)
                if indexedit == 'DEL':
                    return
                else:
                    reloop = True
                    
            if donext == '>' or donext == '.':
                gamemonthI = gamemonthI + 1
                reloop = True
            if donext == '<' or donext == ',':
                gamemonthI = gamemonthI - 1
                reloop = True
            if donext == 'u':
                ftptype = 'upany'
                FtpIt(ftptype, gamedata, '0')
                reloop = True
            if donext == 'd':
                ftptype = 'downany'
                FtpIt(ftptype, gamedata, '0')
                reloop = True
            if donext == 'q':
                reloop = True
            else:
                reloop = True
    return
    
def IndexMain():
    donext = '0'
    while donext != 'q':
        reloop = False
        while donext != 'q' or reloop != True: #this double while just enables it to continue looping.
            
            print "*** Main Index ***"
            print "what would you like to do?"
            print "[1] to continue an already setup game"
            print "[2] to setup a new game"
            print "[h] to read the help"
            print "[q] to quit this application"
            donext = raw_input()
            if donext == '1':
                gamedata = IndexGames()
                if gamedata[0] == 'NONE':
                    print"There Are no games set up"
                    reloop = True
                elif gamedata[0] == 'QUIT':
                    print"You quit the menu"
                    reloop = True
                elif gamedata[1] == 'FALSE':
                    IndexPlr(gamedata)
                elif gamedata[1] == 'RR':
                    IndexRR(gamedata)
                else:
                    IndexHst(gamedata)
                
            elif donext == '2':
                gamesetup = GameSetup()
                if gamesetup[0] != 'Fail':
                    ftpsetup = FtpSetup()
                    SaveData(gamesetup, ftpsetup)
                else:
                    print "game setup failed"
            elif donext == 'h':
                IndexHlp()
                reloop = True
            else:
                reloop = True
    return


#*****************************Start!*********************************
print "Wellcome to Play By FTP V"+version
IndexMain()
print "Thankyou for useing PBFTP, Have a nice day!"