#  Copyright (C) 2017 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/>.

def parse(filename, _regex=None, receiver=None, prefix='', **kwargs):
    '''Parse an XYZ file'''

    from numpy   import char, genfromtxt
    from os      import path
    from ...data import atomicdata, unitconvert

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

    # assign znums
    abuff = genfromtxt(filename, usecols=0, skip_header=2, dtype='U8')
    receiver.znums = [ atomicdata.symbols.index(symbol.title()) for symbol in abuff ]

    # assign coords
    abuff = genfromtxt(filename, usecols=[1,2,3], skip_header=2)
    receiver.coords = abuff
    # JJM 17/08: changed default behaviour to read in as Angstroms
    receiver.coords *= unitconvert.Angstrom2Bohr

    # assign title
    strbuff = genfromtxt(filename, skip_header=1, max_rows=1, dtype='U255')
    # strbuff is list
    try:
        receiver.title = ' '.join(char.strip(strbuff))
    # strbuff is str
    except:
        receiver.title = '{}'.format(strbuff)


# YL 08/02/2019: rewritten because the previous version was wrong!
def write(filename, frag, **kwargs):
    '''Write out a fragment in XYZ file format'''

    with open(filename, 'w') as fp:
        # number of atoms
        fp.write('{}\n'.format(frag.natoms))
        # title
        fp.write('{}\n'.format(frag.title.strip()))
        # coordinates
        fp.write(frag.coords2str(atoms='symbols', coords=12, charges=None, delimiter=' ', unit='angstrom', notations={'c':'e'}))
    

