# lfind.py -- Find lines within a given frequency range
#
# This file is part of Weeds.

from sicparse import OptionParser
import numpy
import linedb
import pyclass

def main():
    """
    linedb/select using CLASS

    """

    # Parse arguments and options

    parser = OptionParser()
    parser.add_option("-o", "--origin", dest="origin", nargs=1, default="All")
    parser.add_option("-r", "--sortby", dest="sortby", nargs=3)
    parser.add_option( "-e", "--energy", dest="energy", nargs=1, type="float", default=-1)
    parser.add_option( "-a", "--aij", dest="aij", nargs=1, type="float", default=-1)
    try:
        (options, args) = parser.parse_args()
    except:
        pyclass.message(pyclass.seve.e, "LFIND", "Invalid option")
        pyclass.sicerror()
        return

    sortby = ['frequency']
    if options.sortby != None:
        if len(options.sortby) not in [1,2,3]:
            pyclass.message(pyclass.seve.e, "LFIND", sortUsage)
            pyclass.sicerror()
            return
        sortby = []
        try:
            for i in range(len(options.sortby)):
                j = sicparse.ambigs(options.sortby[i], linedb.sortCrit)
                sortby.append(linedb.sortCrit[j])
        except Exception as error:
            pyclass.message(pyclass.seve.e, "LFIND", "{0}".format(error))
            pyclass.sicerror()
            return

    origin = options.origin

    # Import Gildas variables if not yet done:
    if (not pyclass.gotgdict()):
        pyclass.get(verbose=False)

    if (len(args)<2 and not pyclass.ingdict('rx')):
        pyclass.message(pyclass.seve.e, "LFIND", "No R spectrum in memory")
        pyclass.sicerror()
        return

    if len(args) == 3:
        species = args[0]
        try:
            fmin = float(args[1])
            fmax = float(args[2])
        except:
            pyclass.message(pyclass.seve.e, "LFIND", "Incorrect frequency values")
            pyclass.sicerror()
            return
    elif len(args) == 1:
        species = args[0]
        (fmin,fmax) = pyclass.rx_minmax('F')
    elif len(args) == 0:
        species = "All"
        (fmin,fmax) = pyclass.rx_minmax('F')
    else:
        pyclass.message(pyclass.seve.e, "LFIND", "Incorrect number of arguments")
        pyclass.sicerror()
        return

    try:
        linedb.select_command("LFIND",fmin,fmax,species,origin,options.energy,
          options.aij,sortby,-1)
    except Exception as error:
        pyclass.message(pyclass.seve.e,"LFIND","{0}".format(error))
        pyclass.sicerror()
        return

    # Export some variables back to class
    pyclass.gdict.weeds.lfound = len(linedb.linesOut)

if __name__ == "__main__":
    main()
