#!/usr/bin/python3

import os,sys,math


def get_savenumber(fname):
    num = 0

    fn2 = os.path.split(fname)[1]
    fn2 = os.path.splitext(fn2)[0]

    L = len(fn2)
    L2 = L
    for I in range(L-1,0,-1):
        c = fn2[I]
        if(not c.isnumeric()):
            L2 = I+1
            break
    nm = fn2[L2:L]
    
    try:
        num = int(nm)
    except:
        num = 0

    return num


def sorttwopythonlists(list1, list2):
 
    zipped_pairs = zip(list2, list1)
 
    z = [x for _, x in sorted(zipped_pairs)]
    z2 = sorted(list2)
 
    return [z,z2]

def get_current_save(directory,saveseries):
    fname = None

    fl = os.listdir(directory)
    fl2 = []
    nums = []

    for f in fl:
        if(f.find(saveseries)>=0):
            fl2.append(os.path.join(directory,f))
    
    for f in fl2:
        n = get_savenumber(f)
        nums.append(n)

    [fl2,nums] = sorttwopythonlists(fl2,nums)

    if(len(fl2)>0):
        fname = fl2[len(fl2)-1]
    else:
        fname = None
    
    return fname

def get_next_save(directory,saveseries):
    fname = None
    fncurrent = get_current_save(directory,saveseries)
    if(fncurrent is None):
        fname = os.path.join(directory,"{}{:02d}.pyt".format(saveseries,0))
    else:
        N = get_savenumber(fncurrent)
        N = N + 1
        fname = os.path.join(directory,"{}{:02d}.pyt".format(saveseries,N))
        

    return fname

if(__name__=="__main__"):

    #print(get_savenumber("./saves/helloworld05202.py"))
    pass
