#  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 force field definition file'''

    from os import path

# YL: it's really strange sys.tracebacklimit isn't available in all Python distributions!
#    from sys import tracebacklimit
#    import sys
#    from contextlib import suppress

#    # suppress the error/exception traceback for the first two cases which looks confusing to the user
#    def _except_hook(exceptionType, exception, traceback, debug_hook=sys.__excepthook__):
#        if chemsh.CHEMSH_DEBUG > 2:
#            debug_hook(exceptionType, exception, traceback)
#
#    sys.excepthook = _except_hook

    # file
    try:
        # YL 13/08/2022: path prefix
        filename = path.join(prefix, filename)
        with open(filename, 'r') as fp:
            # receiver has to be bytearray, as str/bytes is immutable!
            receiver += fp.read().encode()

    # text
    except TypeError:

#        with suppress(AttributeError):
        # YL: I don't remember why split first and then concat
        ff = filename.encode().splitlines()
        for ffline in ff:
            # remember receiver is a bytearray
            receiver += ffline + '\n'.encode()
#        sys.excepthook = sys.__excepthook__

