def ls_cmd(ls_arg, infile):

# routine to execute an 'ls' on 'infile' with argument 'ls_arg' and return
# a list of string files
     import subprocess

     if ls_arg == None:
         lsout = subprocess.check_output(["ls", infile], shell=True)
     else:
         lsout = subprocess.check_output(["ls", ls_arg, infile], shell=True)
     lso = lsout.decode(encoding='UTF-8')
     files = lso.split('\n')
     return files

# routine to do a find command and return a list of items
def findit (dir, file):
    import subprocess

    out = subprocess.check_output(['find', dir, '-name', file], shell=True)
    outt = out.decode(encoding='UTF-8')
    files = outt.split('\n')
    return files

def get_image_size(fname):
#	gets and returns the width and height from a jpeg image.  Code modified
#	from a code from draco
    import struct
    import imghdr

    fhandle = open(fname, 'rb')
    head = fhandle.read(24)
    if len(head) != 24:
        return
#    if imghdr.what(fname) == 'png':
#        check = struct.unpack('>i', head[4:8])[0]
#        if check != 0x0d0a1a0a:
#            return
#        width, height = struct.unpack('>ii', head[16:24])
#    elif imghdr.what(fname) == 'gif':
#        width, height = struct.unpack('<HH', head[6:10])
#    elif imghdr.what(fname) == 'jpeg':
    if imghdr.what(fname) == 'jpeg':
        try:
            fhandle.seek(0) # Read 0xff next
            size = 2
            ftype = 0
            while not 0xc0 <= ftype <= 0xcf:
                fhandle.seek(size, 1)
                byte = fhandle.read(1)
                while ord(byte) == 0xff:
                    byte = fhandle.read(1)
                ftype = ord(byte)
                size = struct.unpack('>H', fhandle.read(2))[0] - 2
            # We are at a SOFn block
            fhandle.seek(1, 1)  # Skip `precision' byte.
            height, width = struct.unpack('>HH', fhandle.read(4))
        except Exception: #IGNORE:W0703
            return
    else:
        return
    return width, height

def get_subdirs (dir):
#	recursively find all the subdirectories in 'dir'
    import subprocess
    out = str(subprocess.check_output(["find", dir, "-type", "d", "-print"], shell=True), encoding='utf8')
    outt = out.split('\n')
    return outt

def get_metdata_date (dir, files):
#   get the Original shooting date from the jpg/CR2 metadata
    import exifread
            # first find a .CR2 or JPG to get the date
    afile = ""
    for file in files:
        if ".JPG" in file or ".jpg" in file or ".CR2" in file:
            afile = file
            break;
    if not afile:
        print ("No .jpg or CR2 in: ", dir+afile)
        exit
    f = open(dir+afile,'rb')

    tags = exifread.process_file(f)
    for tag in tags.keys():
        if "DateTimeOriginal" in tag:
            date = str(tags[tag])
            ldate = date.split(':')
            fdate = ldate[0]+'/'+ldate[1]
    f.close()
    return fdate
