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

# you.lu@ukri.stfc.org
# Jan 2022


def hack():
    '''Increase the value of mxb in ffield.f90'''

    from os     import path
    from shutil import copy
    
    CHEMSH_ARCH = '@CHEMSH_ARCH@'
    
    CWD = path.abspath(path.join(path.dirname(__file__)))
    DL_POLY_SRC_DIR = path.join(CWD, CHEMSH_ARCH, 'src', 'source')
    FILENAME = path.join(DL_POLY_SRC_DIR, 'ffield.F90')
    
    if path.isfile(FILENAME):
        BAK = FILENAME+'.BAK'
        if not path.isfile(BAK):
            with open(FILENAME, 'r') as fp:
                lines = fp.readlines()
            # backup file
            copy(FILENAME, BAK)
        else:
            with open(BAK, 'r') as fp:
                lines = fp.readlines()
    
        # replace string
        for i, line in enumerate(lines):
            if 'mxb = 6' in line:
                lines[i] = line.replace('mxb = 6', 'mxb = 14')
    
        # write out a new file
        with open(FILENAME, 'w') as fp:
            for line in lines:
                fp.write(line)
    
        print("ChemShell has hacked DL_POLY's ffield.F90 by increasing mxb")

    else:

        print("\n\n### not found!\n\n")


if __name__ == '__main__':

    hack()

