#!/usr/bin/env python

import warnings
warnings.filterwarnings('ignore','PyArray_FromDimsAndDataAndDescr: use PyArray_NewFromDescr.*'.lower())
warnings.filterwarnings('ignore','the sets module is deprecated')

import sys,os
from optparse import OptionParser
from glob import glob

op = OptionParser()
op.usage = '%prog [ops] [file(s)]'
op.add_option('-t','--type',dest='type',default='astropysics',help='file format of spectra: "wcs", "deimos", or "astropysics"(default)')
op.add_option('-e','--extension',dest='ext',default=None,help='Fits extension number')
op.add_option('-c','--config',dest='configfile',default=None,help='File to save Spylot configuration')

ops,args = op.parse_args()

#if ops.configfile is None or not os.path.exists(ops.configfile):
#if input is ok import the gui stuff
from astropysics.gui import spylot
from astropysics import spec

if len(args) == 0:
    fns = []
    fns.extend(glob('*.fits'))
    fns.extend(glob('*.fits.gz'))
else:
    fns = []
    for pattern in args:
        fns.extend(glob(pattern))       
        
if len(fns) == 0:
    print 'No files found!'
    sys.exit(1)
    
ss = []
if ops.type == 'wcs':
    specs = []
    if ops.ext is None:
        ext = 1
    else:
        ext = ops.ext
    for fn in fns:
        print 'loading wcs spectrum file',fn
        ss.append(spec.load_wcs_spectrum(fn,ext))    
elif ops.type == 'deimos':
    for fn in fns:
        if 'spec1d' in fn.lower():
            print 'loading deimos spectrum file',fn
            ss.append(spec.load_deimos_spectrum(fn,False))
        else:
            print 'deimos spectrum must be spec1d format'
            sys.exit(1)
elif ops.type == 'astropysics':
    for fn in fns:
        print 'loading astropysics spectrum file',fn
        ss.append(spec.Spectrum.load(fn))
            
else:
    print 'Unrecognized spectrum type ',ops.type
    sys.exit(1)
    
sp = spylot.Spylot(ss)
    
sp.configure_traits(ops.configfile)
    

    
