from .config import *
from .classes.INPUT import INPUT

def opt2hes(optfile, logfile):
    """
    This function writes a hessian calculation input file using a previously
    run optimization input file and the log file generated by the calculation.

    Parameters
    ----------
    optfile: string
        This should be a string that points to the input file of an
        already run optimization file. (FULL DIRECTORY STRING REQUIRED)
    logfile: string
        This should be a string that points to the log file of an
        already run optimization file. (FULL DIRECTORY STRING REQUIRED)

    Returns
    -------
    This function returns nothing if it terminates successfully, otherwise
    it returns ValueError.

    Example
    -------
    >>> import autogamess as ag
    >>>
    >>> logfile = './Optimization_Log_Folder/IBv6_NH3_CCSD-T_CC6_opt.log'
    >>> optfile = './IBv6_NH3_CCSD-T_CC6_opt.inp'
    >>>
    >>> ag.opt2hes(optfile, logfile)
    >>>
    """
    #Define file identifiers
    opt = '_opt'
    hes = '_hes'

    #Make INPUT object
    inp = INPUT(optfile)

    #Open, read in, and close log file
    log = read_file(logfile)

    #Grabs optimized geometries tail index
    tfind = 'COORDINATES OF ALL ATOMS ARE'
    dtail = len(log) - ctr_f(tfind, log[::-1]) - 1
    if (hasattr(inp.Contrl, 'nosym')) and (inp.Contrl.nosym == '1'):
        tfind = 'INTERNUCLEAR DISTANCES (ANGS.)'
        dtail = len(log) - ctr_f(tfind, log[::-1]) - 2

    #Grabs optimized geometries header index
    hfind = '***** EQUILIBRIUM GEOMETRY LOCATED *****'
    dhead = ctr_f(hfind, log) + 4

    #Checks to make sure head and tail exist
    if check_if_exists(logfile, ctr_f(hfind, log)):
        raise ValueError()

    #Assemble list of optimized geometry coordinates and get size
    coords = log[dhead : dtail]

    #Change run type
    inp.Contrl.runtyp = 'HESSIAN'

    #Change atomic coordinates
    inp.Data.coords = coords

    #Save new file
    inp.check()
    inp.write_inp(optfile.replace(opt, hes))

    return
