##^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^Lance Simms, Stanford University 2009
#strip_scf.py
##A COLLECTION OF FUNCTIONS 

import glob
import os
##
##PURPOSE: 
##To strip special characters from a string so the literal string can be 
##output instead of a latex escape sequence
##
##INPUTS:
##  s - the string with the special characters
##OUTPUTS:
##  s - the string with all special characters preceded by a '\'
def strip_sc(s):
    remove = (r'_','$')
    for sc in remove: s = s.replace(sc, '\\'+ sc)
    return s
 
##sort_files_by_date
##
##PURPOSE: 
##To sort the files in a directory and return a list sorted by date
##
##INPUTS:
##  SearchExp - The expression used to search for files, ex- 'Dark*100_Reads*'
##OUTPUTS:
##  Files     - The list of matching files, sorted by modification time
def sort_files_by_date(SearchExp):
    List = [(os.stat(i).st_mtime, i) for i in glob.glob(SearchExp)]
    List.sort()
    Files = [i[1] for i in List]
    return Files

#SortFilesByTime.py
#
#PURPOSE: A simple function that will take a list of FitsFiles 
#and sort them based upon the "TIME" keyword in the header.
#
#INPUT:
#  FileList: (array of strings)
#       The list of files, contained in an array of strings to be sorted.
#OUTPUT:
#  FileList: (array of strings)
#       The list of files sorted by the "TIME" keyword
#
import operator,pyfits

def SortFilesByTime(FileList):

  Dictl = {}
  NumFiles = len(FileList)
  print NumFiles
  for FitsFileName in FileList:
    FitsHDU = pyfits.open(FitsFileName)
    Header  = FitsHDU[0].header
    TIME    = Header["TIME"]
    Dictl[FitsFileName] = TIME

  #Sort the files based upon the time key
  Index1 = operator.itemgetter(1)
  Files= Dictl.items()
  Files.sort(key=Index1, reverse=False)
  SortedFiles = []
  for FileNum in range(NumFiles):
    SortedFiles.append(Files[FileNum][0])
  return SortedFiles

