# lget.py -- Get a line from the line index
#
# This file is part of Weeds.

import sys
from sicparse import OptionParser
import pyclass
import linedb

def main():
    """
    weeds/lget

    """

    # First make sure that the index is not empty

    try:
        dummy = linedb.linesOut
        dummy = linedb.lineIdx
    except NameError:
        pyclass.message(pyclass.seve.e, "LGET", "Line index is empty")
        pyclass.sicerror()
        return

    # Parse options and arguments

    parser = OptionParser()
    parser.add_option("-s", "--index", dest="index",
                                      action="store_true", default = False)
    try:
        (options, args) = parser.parse_args()
    except:
        pyclass.message(pyclass.seve.e, "LGET", "Invalid option")
        pyclass.sicerror()
        return
    index_mode = options.index

    if len(args) != 1:
        pyclass.message(pyclass.seve.e, "LGET", "Incorrect number of arguments (need 1)")
        pyclass.sicerror()
        return
    # Do it
    try:
        l = linedb.lget(args[0])
    except IndexError as idxerr:
        pyclass.message(pyclass.seve.e, "LGET", "{0}".format(idxerr))
        pyclass.sicerror()
        return
    except:
        pyclass.message(pyclass.seve.e, "LGET", "unhandled exception")
        pyclass.sicerror()
        return

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

    if index_mode:

        # Search for the first scan in the scan index that covers the
        # line frequency.

        pyclass.comm("@ weeds/scanfind.class %.3f" % (l.frequency))
        foundscan = pyclass.gdict.foundscan
        if not(foundscan):
            pyclass.message(pyclass.seve.e, "LGET", "Line frequency is not in the scan index")
            pyclass.sicerror()
            return
        pyclass.message(pyclass.seve.i, "LGET", "Found line frequency in the scan index")

    else:

        # Check if the line is in the current scan
        (fmin,fmax) = pyclass.rx_minmax('F')

        if (l.frequency > fmin) and (l.frequency < fmax):
            pyclass.message(pyclass.seve.i, "LGET", "Found line frequency in the current scan")
        else:
            pyclass.message(pyclass.seve.e, "LGET", "Line frequency is not in current scan. Use LGET /INDEX to search for it in other scans of the index.")
            pyclass.sicerror()
            return

    # Modify the scan frequency

    pyclass.comm("modify frequency %.3f" % (l.frequency))

    linedb.llist([l])

if __name__ == "__main__":
    main()
