#!/usr/bin/env python
# encoding: utf-8
'''
 -- 	Checks the FITS header for DATE-OBS, EXPTIME, and FILTER values, then
 renames FITS files to match the ESA/PSA and NASA/PDS archive fielname format

@author:     <NAME>
@author:     <NAME>

@copyright:  Copyright 2015 <NAME> - Licensed under the Apache License 2.0

@license:    http://www.apache.org/licenses/LICENSE-2.0

@contact:    <EMAIL>
@deffield    updated: Updated
'''

import sys, os, platform, re
from optparse import OptionParser

__all__ = []
__version__ = 0.1
__date__ = '2015-12-04'
__updated__ = '2016-02-28'

isWindows = platform.system() == 'Windows'

DEBUG = 0
TESTRUN = 0
PROFILE = 0

def getObsDate(obs_datetime):
    '''Get the observation date'''
    dateIsReversed = re.compile("^.{4}-.{2}-.{2}") # matches dates in format like 2016-02-28
    if dateIsReversed.match(obs_datetime[0]):
        return ''.join( list( reversed(re.split('-', obs_datetime[0])) ) )
    return ''.join( list( re.split('-', obs_datetime[0]) ) )

def getObsTime(obs_datetime):
    '''Get the observation time'''
    obs_time = ''.join( re.split(':', obs_datetime[1]) )
    return obs_time[:6] # strip any decimal characters

def main(argv=None):
    '''Command line options.'''

    program_name = os.path.basename(sys.argv[0])
    program_version = "v0.1"
    program_build_date = "%s" % __updated__
    program_version_string = '%%prog %s (%s)' % (program_version, program_build_date)

    program_usage = '''''' # optional - will be autogenerated by optparse
    program_longdesc = '''Checks the FITS header for DATE-OBS, EXPTIME, and FILTER values, then \n
    renames FITS files to match the ESA/PSA and NASA/PDS archive filename format'''
    program_license = '''Copyright 2015 <NAME> - Licensed under the Apache License 2.0 \n
    http://www.apache.org/licenses/LICENSE-2.0'''

    # setup option parser
    parser = OptionParser(version=program_version_string, epilog=program_longdesc, description=program_license)
    parser.add_option("", "--in", dest="inpath", help="set input path [default: %default]", metavar="PATH")
    parser.add_option("", "--out", dest="outpath", help="set output path [default: %default]", metavar="PATH")
    parser.add_option("-i", "--initials", dest="initials", help="set your initials [default: %default]", metavar="INITIALS")
    parser.add_option("-o", "--object", dest="obj", help="set the object name [default: %default]", metavar="OBJ")
    parser.add_option("-m", "--move", dest="movefiles", action="store_true", help="don't keep original files; rename & move files to outpath", default=False)

    # set defaults
    parser.set_defaults(outpath="./renamed/", inpath="./", obj="67P")

    if len(argv) > 1:
        # process options
        (opts, args) = parser.parse_args(argv)

        try:
            if opts.initials:
                print("initials = %s" % opts.initials)
                opts.initials = "_%s" % opts.initials
            else:
                opts.initials = ""
            if opts.obj:
                print("obj = %s" % opts.obj)
            if opts.inpath:
                if isWindows:
                    if not opts.inpath.endswith('\\'):
                        opts.inpath = opts.inpath + '\\'
                else:
                    if not opts.inpath.endswith('/'):
                        opts.inpath = opts.inpath + '/'
                print("inpath = %s" % opts.inpath)
            if opts.outpath:
                if isWindows:
                    if not opts.outpath.endswith('\\'):
                        opts.outpath = opts.outpath + '\\'
                else:
                    if not opts.outpath.endswith('/'):
                        opts.outpath = opts.outpath + '/'
                print("outpath = %s" % opts.outpath)
            print("move files = %s" % opts.movefiles)

            import shutil
            from astropy.io import fits

            fits_count = 0
            for file in os.listdir(opts.inpath):
                if file.endswith(".fit") or file.endswith(".fits") or file.endswith(".FIT") or file.endswith(".FITS"):
                    try:
                        os.makedirs(opts.outpath)
                    except OSError:
                        if not os.path.isdir(opts.outpath):
                            raise

                    filepath = opts.inpath + os.sep + file
                    hdulist=fits.open(filepath)
                    fits_header = hdulist[0].header

                    obs_datetime = re.split('T', fits_header['DATE-OBS'])
                    print('DATE-OBS', fits_header['DATE-OBS'])
                    obs_date = getObsDate(obs_datetime)
                    obs_time = getObsTime(obs_datetime)

                    print('EXPTIME', fits_header['EXPTIME'])
                    exp_time = fits_header['EXPTIME']

                    filter = None
                    try:
                        filter = fits_header['FILTER']
                    except Exception:
                        pass
                    if filter is None:
                        filter = 'Clear'
                    print('FILTER', filter)
                    filter = filter[0]

                    file_extension = 'fit'
                    if isWindows:
                        file_extension = 'FIT'
                    new_filename = "%s_%s_%s_%s%03.0f%s.%s" % (obs_date, obs_time, opts.obj, filter, exp_time, opts.initials, file_extension)
                    print(file, '->', new_filename)
                    hdulist.close()

                    # move or copy the file as per the move parameter value
                    if opts.movefiles:
                        shutil.move(filepath, opts.outpath+new_filename)
                    else:
                        shutil.copy2(filepath, opts.outpath+new_filename)

                    # save the original filename in the FITS header of the new file
                    hdulist=fits.open(opts.outpath+new_filename, mode='update')
                    fits_header = hdulist[0].header
                    fits_header['ORIGINAL'] = file
                    hdulist.close()

                    fits_count = fits_count + 1

            if fits_count == 0:
                print("Didn't find FITS files to process")
                return 2
        except Exception as e:
            indent = len(program_name) * " "
            sys.stderr.write(program_name + ": " + repr(e) + "\n")
            sys.stderr.write(indent + "  for help use --help\n")
            return 2
    else:
        (opts, args) = parser.parse_args(["-h"])

if __name__ == "__main__":
    if DEBUG:
        sys.argv.append("-h")
    if TESTRUN:
        import astropy
        astropy.test()
    if PROFILE:
        import cProfile
        import pstats
        profile_filename = '_profile.txt'
        cProfile.run('main()', profile_filename)
        statsfile = open("profile_stats.txt", "wb")
        p = pstats.Stats(profile_filename, stream=statsfile)
        stats = p.strip_dirs().sort_stats('cumulative')
        stats.print_stats()
        statsfile.close()
        sys.exit(0)
    sys.exit(main(sys.argv))

#!/usr/bin/env python
# encoding: utf-8
'''
 -- 	Checks the FITS header for DATE-OBS, EXPTIME, and FILTER values, then
 renames FITS files to match the ESA/PSA and NASA/PDS archive fielname format

@author:     <NAME>
@author:     <NAME>

@copyright:  Copyright 2015 <NAME> - Licensed under the Apache License 2.0

@license:    http://www.apache.org/licenses/LICENSE-2.0

@contact:    <EMAIL>
@deffield    updated: Updated
'''

import sys, os, platform, re
from optparse import OptionParser

__all__ = []
__version__ = 0.1
__date__ = '2015-12-04'
__updated__ = '2016-02-28'

isWindows = platform.system() == 'Windows'

DEBUG = 0
TESTRUN = 0
PROFILE = 0

def getObsDate(obs_datetime):
    '''Get the observation date'''
    dateIsReversed = re.compile("^.{4}-.{2}-.{2}") # matches dates in format like 2016-02-28
    if dateIsReversed.match(obs_datetime[0]):
        return ''.join( list( reversed(re.split('-', obs_datetime[0])) ) )
    return ''.join( list( re.split('-', obs_datetime[0]) ) )

def getObsTime(obs_datetime):
    '''Get the observation time'''
    obs_time = ''.join( re.split(':', obs_datetime[1]) )
    return obs_time[:6] # strip any decimal characters

def main(argv=None):
    '''Command line options.'''

    program_name = os.path.basename(sys.argv[0])
    program_version = "v0.1"
    program_build_date = "%s" % __updated__
    program_version_string = '%%prog %s (%s)' % (program_version, program_build_date)

    program_usage = '''''' # optional - will be autogenerated by optparse
    program_longdesc = '''Checks the FITS header for DATE-OBS, EXPTIME, and FILTER values, then \n
    renames FITS files to match the ESA/PSA and NASA/PDS archive filename format'''
    program_license = '''Copyright 2015 <NAME> - Licensed under the Apache License 2.0 \n
    http://www.apache.org/licenses/LICENSE-2.0'''

    # setup option parser
    parser = OptionParser(version=program_version_string, epilog=program_longdesc, description=program_license)
    parser.add_option("", "--in", dest="inpath", help="set input path [default: %default]", metavar="PATH")
    parser.add_option("", "--out", dest="outpath", help="set output path [default: %default]", metavar="PATH")
    parser.add_option("-i", "--initials", dest="initials", help="set your initials [default: %default]", metavar="INITIALS")
    parser.add_option("-o", "--object", dest="obj", help="set the object name [default: %default]", metavar="OBJ")
    parser.add_option("-m", "--move", dest="movefiles", action="store_true", help="don't keep original files; rename & move files to outpath", default=False)

    # set defaults
    parser.set_defaults(outpath="./renamed/", inpath="./", obj="67P")

    if len(argv) > 1:
        # process options
        (opts, args) = parser.parse_args(argv)

        try:
            if opts.initials:
                print("initials = %s" % opts.initials)
                opts.initials = "_%s" % opts.initials
            else:
                opts.initials = ""
            if opts.obj:
                print("obj = %s" % opts.obj)
            if opts.inpath:
                if isWindows:
                    if not opts.inpath.endswith('\\'):
                        opts.inpath = opts.inpath + '\\'
                else:
                    if not opts.inpath.endswith('/'):
                        opts.inpath = opts.inpath + '/'
                print("inpath = %s" % opts.inpath)
            if opts.outpath:
                if isWindows:
                    if not opts.outpath.endswith('\\'):
                        opts.outpath = opts.outpath + '\\'
                else:
                    if not opts.outpath.endswith('/'):
                        opts.outpath = opts.outpath + '/'
                print("outpath = %s" % opts.outpath)
            print("move files = %s" % opts.movefiles)

            import shutil
            from astropy.io import fits

            fits_count = 0
            for file in os.listdir(opts.inpath):
                if file.endswith(".fit") or file.endswith(".fits") or file.endswith(".FIT") or file.endswith(".FITS"):
                    try:
                        os.makedirs(opts.outpath)
                    except OSError:
                        if not os.path.isdir(opts.outpath):
                            raise

                    filepath = opts.inpath + os.sep + file
                    hdulist=fits.open(filepath)
                    fits_header = hdulist[0].header

                    obs_datetime = re.split('T', fits_header['DATE-OBS'])
                    print('DATE-OBS', fits_header['DATE-OBS'])
                    obs_date = getObsDate(obs_datetime)
                    obs_time = getObsTime(obs_datetime)

                    print('EXPTIME', fits_header['EXPTIME'])
                    exp_time = fits_header['EXPTIME']

                    filter = None
                    try:
                        filter = fits_header['FILTER']
                    except Exception:
                        pass
                    if filter is None:
                        filter = 'Clear'
                    print('FILTER', filter)
                    filter = filter[0]

                    file_extension = 'fit'
                    if isWindows:
                        file_extension = 'FIT'
                    new_filename = "%s_%s_%s_%s%03.0f%s.%s" % (obs_date, obs_time, opts.obj, filter, exp_time, opts.initials, file_extension)
                    print(file, '->', new_filename)
                    hdulist.close()

                    # move or copy the file as per the move parameter value
                    if opts.movefiles:
                        shutil.move(filepath, opts.outpath+new_filename)
                    else:
                        shutil.copy2(filepath, opts.outpath+new_filename)

                    # save the original filename in the FITS header of the new file
                    hdulist=fits.open(opts.outpath+new_filename, mode='update')
                    fits_header = hdulist[0].header
                    fits_header['ORIGINAL'] = file
                    hdulist.close()

                    fits_count = fits_count + 1

            if fits_count == 0:
                print("Didn't find FITS files to process")
                return 2
        except Exception as e:
            indent = len(program_name) * " "
            sys.stderr.write(program_name + ": " + repr(e) + "\n")
            sys.stderr.write(indent + "  for help use --help\n")
            return 2
    else:
        (opts, args) = parser.parse_args(["-h"])

if __name__ == "__main__":
    if DEBUG:
        sys.argv.append("-h")
    if TESTRUN:
        import astropy
        astropy.test()
    if PROFILE:
        import cProfile
        import pstats
        profile_filename = '_profile.txt'
        cProfile.run('main()', profile_filename)
        statsfile = open("profile_stats.txt", "wb")
        p = pstats.Stats(profile_filename, stream=statsfile)
        stats = p.strip_dirs().sort_stats('cumulative')
        stats.print_stats()
        statsfile.close()
        sys.exit(0)
    sys.exit(main(sys.argv))

#!/usr/bin/env python # encoding: utf-8 -- 	Checks the FITS header for DATE-OBS, EXPTIME, and FILTER values, then  renames FITS files to match the ESA/PSA and NASA/PDS archive fielname format  @author:     <NAME> @author:     <NAME>  @copyright:  Copyright 2015 <NAME> - Licensed under the Apache License 2.0  @license:    http://www.apache.org/licenses/LICENSE-2.0  @contact:    <EMAIL> @deffield    updated: Updated Get the observation date # matches dates in format like 2016-02-28 Get the observation time # strip any decimal characters Command line options. # optional - will be autogenerated by optparse Checks the FITS header for DATE-OBS, EXPTIME, and FILTER values, then \n     renames FITS files to match the ESA/PSA and NASA/PDS archive filename format Copyright 2015 <NAME> - Licensed under the Apache License 2.0 \n     http://www.apache.org/licenses/LICENSE-2.0 # setup option parser # set defaults # process options # move or copy the file as per the move parameter value # save the original filename in the FITS header of the new file