#  Copyright (C) 2020 The authors of Py-ChemShell
#
#  This file is part of Py-ChemShell.
#
#  Py-ChemShell is free software: you can redistribute it and/or modify
#  it under the terms of the GNU Lesser General Public License as
#  published by the Free Software Foundation, either version 3 of the
#  License, or (at your option) any later version.
#
#  Py-ChemShell is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU Lesser General Public License for more details.
#
#  You should have received a copy of the GNU Lesser General Public
#  License along with Py-ChemShell.  If not, see
#  <http://www.gnu.org/licenses/>.

__author__ = 'You Lu <you.lu@stfc.ac.uk>'

import chemsh

def parse(filename, _regex=None, receiver=None, prefix='', **kwargs):
    '''GULP output'''

    from numpy      import array
    from os         import path
    from ...dl_py2f import utils
    from ...data    import unitconvert

    # YL 13/08/2022: path prefix
    filename = path.join(prefix, filename)

    with open(filename) as fp:

        # we currently only get the stress derivative information
        for line in fp:
            if line.startswith('gradients strain eV'):
                # 3D
                try:
                    lbuff = next(fp)
                    lbuff += next(fp)
                    abuff = array(lbuff.split(), dtype=float)*unitconvert.unit2au['eV']
                # 2D
                except StopIteration:
                    abuff = array(lbuff.split(), dtype=float)*unitconvert.unit2au['eV']
                break

        utils.nputils.setField(receiver, abuff, debug=chemsh.CHEMSH_DEBUG)
