""" Code to select FITS files

Context : SRP
Module  : SRPSelect.py
Version : 1.0.7
Author  : Stefano Covino
Date    : 11/09/2011
E-mail  : stefano.covino@brera.inaf.it
URL:    : http://www.merate.mi.astro.it/utenti/covino
Purpose : Manage the selection of FITS files

Usage   : SRPSelect [-i arg1] -k arg2 -o arg3 [-v] 
            -i passes to the scripts the file with the list
                of FITS file and keyword values as created, for
                instance, by SRPClassify.
            -k is the keyword to be searched for.
            -o is the output file with results of the selection.

History : (22/05/2003) First version.
        : (23/05/2003) Number of selected entries.
        : (04/06/2003) Better keywords for command line.
        : (13/06/2003) Better help and output messages.
        : (03/02/2005) Optparse.
        : (11/09/2009) Minor correction.
        : (11/06/2011) Cosmetic changes.
"""



import os, os.path, string
from optparse import OptionParser
import SRP.SRPConstants as SRPConstants
import SRP.SRPFiles as SRPFiles
import SRP.SRPUtil as SRPUtil


parser = OptionParser(usage="usage: %prog [-i arg1] -k arg2 -o arg3 [-v]", version="%prog 1.0.7")
parser.add_option("-i", "--inputilelist", action="store", nargs=1, type="string", dest="fitsfilelist", help="Input classified FITS file list")
parser.add_option("-v", "--verbose", action="store_true", dest="verbose", help="Fully describe operations")	
parser.add_option("-o", "--outfile", action="store", nargs=1, type="string", dest="outfilelist", help="Output classified FITS file list")
parser.add_option("-k", "--key", action="store", nargs=1, type="string", dest="keybase", help="Keyword to be searched for")
(options, args) = parser.parse_args()


sname = SRPFiles.getSRPSessionName()
if options.verbose:
	print "Session name %s retrieved." % sname

	
if options.fitsfilelist:
	if os.path.isfile(options.fitsfilelist):
		fitsfile = options.fitsfilelist
	else:
		parser.error("Input classified FITS file %s not found" % options.fitsfilelist)
else:
	fitsfile = sname+SRPConstants.SRPClassFile
if options.verbose:
	print "FITS file name is: %s." % fitsfile

	
	
if options.outfilelist and options.keybase:
	o = SRPFiles.SRPFile(SRPConstants.SRPLocalDir,sname+options.outfilelist,SRPFiles.WriteMode)
	o.SRPOpenFile()
	if options.verbose:
		print "Output file name is: %s." % (sname+options.outfilelist)
		print "Keyword to be searched is: %s" % options.keybase
	i = SRPFiles.SRPFile(SRPConstants.SRPLocalDir,fitsfile,SRPFiles.ReadMode)
	i.SRPOpenFile()
	nentr = 0
	while True:
		dt = i.SRPReadFile()
		if dt != '':
			if string.find(dt,options.keybase) != -1:
				o.SRPWriteFile(dt)
				nentr = nentr + 1
				if options.verbose:
					print "FITS file selected: %s" % string.strip(dt)
		else:
			break
	o.SRPCloseFile()
	i.SRPCloseFile()
	if options.verbose:
		print "%d selected entries." % nentr
else:
	parser.print_help()
	
