# Archive existing NWChem static libraries

#  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/>.

# you.lu@stfc.ac.uk
# July 2016

# YL 30/11/2023: not in use
set(NWCHEM_TAG v7.2.2-release)

# CMake headers
#include(${CHEMSH_DIR}/chemsh/utils/cmake/print.cmake)
include(${CHEMSH_DIR}/chemsh/utils/cmake/colours.cmake)

include_directories(${CHEMSH_BUILD_DIR}/modules
                    ${CHEMSH_BUILD_DIR}/modules/parallel
                    ${CHEMSH_BUILD_DIR}/modules/dl_py2f)

option(WITH_NWCHEM "Build ChemShell with linked-in NWChem" OFF)
# get user-defined NWChem path
if(NOT "${NWCHEM}" STREQUAL "")
    if(IS_DIRECTORY ${NWCHEM})
        get_filename_component(NWCHEM ${NWCHEM} ABSOLUTE)
        get_filename_component(NWCHEM_SRC_DIR ${NWCHEM}/src ABSOLUTE)
        set(WITH_NWCHEM ON)
        # YL 12/01/2021: added version check as we stopped supporting versions earlier than 7.0
        file(READ ${NWCHEM_SRC_DIR}/nwchem.F NWCHEM_VERSION)
        string(REGEX MATCH "\' Version [0-9]+[.]+[0-9]+([.]?[0-9])?" NWCHEM_VERSION ${NWCHEM_VERSION})
        string(REGEX MATCH "[0-9]+[.]+[0-9]+([.]?[0-9])?" NWCHEM_VERSION ${NWCHEM_VERSION})
        if(NOT ${NWCHEM_VERSION} GREATER_EQUAL 7.0)
            message("")
            message(" WARNING: We have changed the support for NWChem to versions later than 7.0 although the current specified version ${NWCHEM_VERSION} may still work")
            message("")
        endif()
        configure_file(${NWCHEM_SCRIPT} ${NWCHEM_SCRIPT}.tmp @ONLY)
        file(RENAME ${NWCHEM_SCRIPT}.tmp ${NWCHEM_SCRIPT})
        string(REPLACE ":" ";" NWCHEM_PATCHES "${NWCHEM_PATCHES}")
        # loop over patches
        foreach(PATCH ${NWCHEM_PATCHES})
            execute_process(COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/patch.py ${NWCHEM} ${PATCH})
        endforeach(PATCH)
        option(NWCHEM_BUILD_MANUALLY "Let the user build NWChem manually" ON)
    else()
        # get the version number
        string(REGEX MATCH "[0-9]+[.]+[0-9]+([.]?[0-9])?" NWCHEM_VERSION ${NWCHEM})
        # YL 21/06/2023: URL could be https://github.com/nwchemgit/nwchem/archive/refs/heads/hotfix/release-7-2-0.zip
        if("${NWCHEM_VERSION}" STREQUAL "")
            string(REGEX MATCH "[0-9]+[-]+[0-9]+([-]?[0-9])?" NWCHEM_VERSION ${NWCHEM})
            string(REPLACE "-" "." NWCHEM_VERSION "${NWCHEM_VERSION}")
        endif()
        # YL 30/11/2023: not in use -- NWChem 7.2.2 from the GitHub repo
        if("${NWCHEM_VERSION}" STREQUAL "")
            string(REGEX MATCH "[0-9]+[.]+[0-9]+([.]?[0-9])?" NWCHEM_VERSION ${NWCHEM_TAG})
        endif()

        # clean if requested before redownload
        if(${NWCHEM_RECOMPILE})
            file(REMOVE_RECURSE ${CMAKE_CURRENT_SOURCE_DIR}/${NWCHEM_VERSION})
            file(REMOVE_RECURSE ${CMAKE_CURRENT_SOURCE_DIR}/src)
            file(REMOVE_RECURSE ${CMAKE_CURRENT_SOURCE_DIR}/tmp)
            file(REMOVE_RECURSE ${CMAKE_BINARY_DIR}/_deps/nwchem-build)
            file(REMOVE_RECURSE ${CMAKE_BINARY_DIR}/_deps/nwchem-subbuild)
        endif()
        # download and extract
        get_module(NWCHEM "${NWCHEM}" "${CMAKE_CURRENT_SOURCE_DIR}" src ON "")
        message("NWChem ${NWCHEM_VERSION} has been downloaded to ${CMAKE_CURRENT_SOURCE_DIR}/src")
        # do NOT redefine ${NWCHEM} before it has been used by get_module()
        set(NWCHEM ${CMAKE_CURRENT_SOURCE_DIR}/src CACHE PATH "Setting for GA" FORCE)
        get_filename_component(NWCHEM_SRC_DIR ${NWCHEM}/src ABSOLUTE)
        set(WITH_NWCHEM ON)
        # YL 16/06/2023: GA version is needed
        file(GLOB GA_NAME "${NWCHEM}/src/tools/ga-[0-9]\.[0-9]*")
        if("${GA_NAME}" STREQUAL "")
            set(GA_NAME "unknown")
        endif()
        string(REGEX MATCH "ga-[0-9]\.[0-9]([\.][0-9])?" GA_NAME "${GA_NAME}")
        set(GA_NAME "${GA_NAME}" CACHE STRING "GA name")
        # script generated by Python before CMake
        get_filename_component(NWCHEM_SCRIPT_FILENAME ${NWCHEM_SCRIPT} NAME)
        # configure to carve NWCHEM_TOP in the script before copying
        configure_file(${NWCHEM_SCRIPT} ${NWCHEM_SCRIPT}.tmp @ONLY)
        # move script to src/
        file(RENAME ${NWCHEM_SCRIPT}.tmp ${NWCHEM}/src/${NWCHEM_SCRIPT_FILENAME})
        file(REMOVE ${CMAKE_CURRENT_SOURCE_DIR}/${NWCHEM_SCRIPT_FILENAME})
        # because we can't pass in ";" from the command line argument -D, we don't convert the string to list until now
        string(REPLACE ":" ";" NWCHEM_PATCHES "${NWCHEM_PATCHES}")
        # loop over patches
        foreach(PATCH ${NWCHEM_PATCHES})
            execute_process(COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/patch.py ${NWCHEM} ${PATCH})
        endforeach(PATCH)
        option(NWCHEM_BUILD_MANUALLY "Let the user build NWChem manually" OFF)
    endif()
endif()

# paths
set(CMAKE_Fortran_MODULE_DIRECTORY ${CHEMSH_BUILD_DIR}/modules/nwchem)
set(NWCHEM_LIB_DIRECTORY           ${CHEMSH_BUILD_DIR}/lib/nwchem)
set(CHEMSH_GA_LIB_DIR              ${CHEMSH_BUILD_DIR}/lib/ga)
set(NWCHEM_INCLUDE_DIRECTORY       ${CHEMSH_BUILD_DIR}/include/nwchem)
set(PEIGS_INCLUDE_DIRECTORY        ${CHEMSH_BUILD_DIR}/include/ga/peigs)
set(GA_INCLUDE_DIRECTORY           ${CHEMSH_BUILD_DIR}/include/ga)
set(MA_INCLUDE_DIRECTORY           ${CHEMSH_BUILD_DIR}/include/ga/ma)
file(MAKE_DIRECTORY ${NWCHEM_LIB_DIRECTORY})
file(MAKE_DIRECTORY ${NWCHEM_INCLUDE_DIRECTORY})
file(MAKE_DIRECTORY ${PEIGS_INCLUDE_DIRECTORY})

if(${CHEMSH_ARCH} MATCHES "intel")
    set(NWCHEM_ROUTINES_FILE nwchem_routines.f90)
# YL 08/03/2021: our nwchem_routines.f90 is in free format requiring many fixed-formatted preprocessing files (.fh)
#                and we use `!DEC$ NOFREEFORM` to treat it with ifort but GNU or Cray GNU or Cray can't handle it!
else()
    set(NWCHEM_ROUTINES_FILE nwchem_routines.f)
endif()

# engrave the following information into nwchem_routines.f90
string(TIMESTAMP COMPILATION_DATE %Y-%m-%dT%H:%M:%S)
set(NWCHEM_BRANCH NWChem-ChemShell)

# compile libnwchem.so (containing only Py-ChemShell interface files)
# list of source files
# YL 13.08.2017: now must include $NWCHEM_TOP/src/stubs.F to exclude modules not in the build (determined by NWChem config)
if(WITH_NWCHEM)
    list(APPEND NWCHEM_FSOURCES nwchem.f90
                                ${NWCHEM_ROUTINES_FILE}
                                nwchem_dummies.f90
                                nwchem_undefined.f90
#                                nwchem_input_file_info.F
                                ${NWCHEM}/src/stubs.F
                                ${LINKED})
    set(NWCHEM_SUBROUTINE "")
    set(NWCHEM_ENDSUBROUTINE "")
else()
    list(APPEND NWCHEM_FSOURCES nwchem.f90 nwchem_dummies.f90 ${NOTLINKED})
    set(NWCHEM_SUBROUTINE "subroutine chemshell_nwchem")
    set(NWCHEM_ENDSUBROUTINE "endsubroutine")
endif()

# YL 30/11/2023: for printing the right version number
configure_file(nwchem_routines.f90.in nwchem_routines.f90 @ONLY)
configure_file(nwchem_routines.f.in   nwchem_routines.f   @ONLY)
configure_file(nwchem_dummies.f90.in  nwchem_dummies.f90  @ONLY)

# compile
add_library(nwchem SHARED ${NWCHEM_FSOURCES})

# "-cpp" equals "-fpp" in ifort
# YL: NWChem is a special case that we integrate a lot of original subroutines and integer8 is required
if(${CHEMSH_ARCH} STREQUAL "gnu")
    set_target_properties(nwchem PROPERTIES COMPILE_FLAGS "-cpp                                                      \
                                                           -fdefault-integer-8")

### Cray GNU
elseif(${CHEMSH_ARCH} STREQUAL "cpe-gnu")
    # YL 03/03/2021: we only back up once to make sure it's the original version
    if(WITH_NWCHEM)
        if(NOT EXISTS ${NWCHEM_SRC_DIR}/config/makefile.h.BAK)
            file(COPY ${NWCHEM_SRC_DIR}/config/makefile.h DESTINATION ${NWCHEM_SRC_DIR}/config/makefile.h.BAK)
        endif()
        # YL 03/03/2021: we need to hack the native makefile.h because all FOPTIONS and FOPTIMIZE are hardcoded for gfortran
        #                and hence there is no way to insert -fPIC
        if(${NWCHEM_VERSION} GREATER_EQUAL 7.2)
            configure_file(makefile.h.in.7.2 makefile.h @ONLY)
        else()
            configure_file(makefile.h.in.7.0 makefile.h @ONLY)
        endif()
        file(REMOVE ${NWCHEM_SRC_DIR}/config/makefile.h)
        # NB: CMake file(COPY) doesn't overwrite!
        file(COPY ${CMAKE_CURRENT_LIST_DIR}/makefile.h DESTINATION ${NWCHEM_SRC_DIR}/config)
    endif()
    if(DEBUG)
        set_target_properties(nwchem PROPERTIES COMPILE_FLAGS "-O0 -g -std=legacy -cpp -fPIC -fdefault-integer-8 -fbacktrace -ffixed-line-length-255 -DUSE_OPENMP -DUSE_SUBGROUPS=1")
    else()
        # YL 01/08/2021: added -DUSE_SUBGROUPS=1 to redefine luout with a value other than 6
        set_target_properties(nwchem PROPERTIES COMPILE_FLAGS "-fPIC -fdefault-integer-8 -DUSE_OPENMP -DUSE_SUBGROUPS=1")
        # YL 09/04/2021: -fcheck=no-bounds must be used to prevent gfortran-10 checking array bounds (DBL_MT, for example)
        set_source_files_properties(nwchem_routines.f PROPERTIES COMPILE_FLAGS "-O2 -legacy -cpp -fPIC -fdefault-integer-8 -fbacktrace -ffixed-line-length-255 -fcheck=no-bounds")
    endif()

### Cray
elseif(${CHEMSH_ARCH} STREQUAL "cray")
    set_target_properties(nwchem PROPERTIES COMPILE_FLAGS "-cpp                                                      \
                                                           -sdefault64")
# \
#                                                           -DCOMPILATION_DATE=\"\\'${NWCHEM_COMPILATION_DATE}\\'\"\
#                                                           -DNWCHEM_BRANCH=\"\\'NWChem-ChemShell\\'\"")

### Intel
else()
# YL 09/02/2022: moved to ChemShell's top level CMakeLists.txt
#    if(${CMAKE_Fortran_COMPILER_VERSION} VERSION_GREATER_EQUAL 20.0)
#        if(WITH_MPI)
#            set(INTEL_OMP_FLAGS "-qmkl=parallel")
#        else()
#            set(INTEL_OMP_FLAGS "-qmkl=sequential")
#        endif()
#    else()
#        if(WITH_MPI)
#            set(INTEL_OMP_FLAGS "-mkl=parallel")
#        else()
#            set(INTEL_OMP_FLAGS "-mkl=sequential")
#        endif()
#    endif()
    if(${DEBUG})
        set(NWCHEM_DEBUG_FLAGS "-g -ggdb")
    endif()
    # force 64-bit integers using '-i8' to match GA/MA
    set_target_properties(nwchem PROPERTIES COMPILE_FLAGS "-fpp ${NWCHEM_DEBUG_FLAGS}                                \
                                                           -i8")
#  \
#                                                           -DCOMPILATION_DATE=\"\\'${NWCHEM_COMPILATION_DATE}\\'\"\
#                                                           -DNWCHEM_BRANCH=\"\\'NWChem-ChemShell\\'\"")
endif()

add_dependencies(nwchem parallel)

# END OF DYNAMIC LIB #

# if CMAKE argument NWCHEM given
if(WITH_NWCHEM)

    # it is likely GNU compiler cannot handle free-format fortran source code files with "include" statements of fixed-format .fh files
    if(${CHEMSH_ARCH} STREQUAL "gnu")
        message(FATAL_ERROR "${BoldWhite}GNU Fortran compiler currently does not support linking NWChem in ChemShell. Please run compiled NWChem executables in ChemShell or compile ChemShell with Intel compiler if applicable.${EndColour}")
    endif()

    # NWChem dir
    set(NWCHEM_DIR         ${NWCHEM})
    set(NWCHEM_LIB_DIR     ${NWCHEM_DIR}/lib/${NWCHEM_TARGET})

    list(APPEND NWCHEM_BASIS_HEADER_FILES 
                                          ${NWCHEM}/src/basis/bas.fh
                                          ${NWCHEM}/src/basis/basP.fh
                                          ${NWCHEM}/src/basis/basdeclsP.fh
                                          ${NWCHEM}/src/basis/baslibraryP.fh
                                          ${NWCHEM}/src/basis/bas_exndcf.fh
                                          ${NWCHEM}/src/basis/bas_exndcf_dec.fh
                                          ${NWCHEM}/src/basis/bas_exndcf_sfn.fh
                                          ${NWCHEM}/src/basis/bas_ibs.fh
                                          ${NWCHEM}/src/basis/bas_ibs_dec.fh
                                          ${NWCHEM}/src/basis/bas_ibs_sfn.fh
                                          ${NWCHEM}/src/basis/bas_starP.fh
                                          ${NWCHEM}/src/basis/bas_staticP.fh
                                          ${NWCHEM}/src/basis/ecpso_decP.fh
                                          ${NWCHEM}/src/basis/ecpso_sfnP.fh
                                          ${NWCHEM}/src/basis/geobasmapP.fh
    )

    # YL 05/12/2021: we should copy from src/util rather than src/include which only exists after built
    if(${NWCHEM_VERSION} GREATER_EQUAL 7.2)
        list(APPEND NWCHEM_HEADER_FILES
                                        ${NWCHEM}/src/util/bgj.fh
                                        ${NWCHEM}/src/util/bgj_common.fh
                                        ${NWCHEM}/src/util/bitops.fh
                                        ${NWCHEM}/src/util/bitops_decls.fh
                                        ${NWCHEM}/src/util/bitops_funcs.fh
                                        ${NWCHEM}/src/util/ceccemoprint.fh
                                        ${NWCHEM}/src/util/cfileprefix.fh
                                        ${NWCHEM}/src/util/cproject.fh
                                        ${NWCHEM}/src/util/errquit.fh
                                        ${NWCHEM}/src/util/itri.fh
                                        ${NWCHEM}/src/util/msgids.fh
                                        ${NWCHEM}/src/util/numerical_constants.fh
                                        ${NWCHEM}/src/util/nwc_const.fh
                                        ${NWCHEM}/src/util/nwmolden.fh
                                        ${NWCHEM}/src/util/printcommon.fh
                                        ${NWCHEM}/src/util/printlevels.fh
                                        ${NWCHEM}/src/util/stdio.fh
                                        ${NWCHEM}/src/util/testutil.fh
                                        ${NWCHEM}/src/util/util.fh
                                        ${NWCHEM}/src/util/utilc_nwchem_srcdir.fh
                                        ${NWCHEM}/src/util/util_intsize.fh
                                        ${NWCHEM}/src/util/util_io_data.fh
                                        ${NWCHEM}/src/util/util_maxlength.fh
                                        ${NWCHEM}/src/util/util_params.fh
                                        ${NWCHEM}/src/util/util_sgroup.fh
                                        ${NWCHEM}/src/util/vtune.fh
            )
    else()
        list(APPEND NWCHEM_HEADER_FILES
                                        ${NWCHEM}/src/util/ecce_print.h
                                        ${NWCHEM}/src/util/testutil.h
                                        ${NWCHEM}/src/util/bgj.fh
                                        ${NWCHEM}/src/util/bgj_common.fh
                                        ${NWCHEM}/src/util/bitops.fh
                                        ${NWCHEM}/src/util/bitops_decls.fh
                                        ${NWCHEM}/src/util/bitops_funcs.fh
                                        ${NWCHEM}/src/util/ceccemoprint.fh
                                        ${NWCHEM}/src/util/cfileprefix.fh
                                        ${NWCHEM}/src/util/cproject.fh
                                        ${NWCHEM}/src/util/errquit.fh
                                        ${NWCHEM}/src/util/itri.fh
                                        ${NWCHEM}/src/util/msgids.fh
                                        ${NWCHEM}/src/util/numerical_constants.fh
                                        ${NWCHEM}/src/util/nwc_const.fh
                                        ${NWCHEM}/src/util/nwmolden.fh
                                        ${NWCHEM}/src/util/printcommon.fh
                                        ${NWCHEM}/src/util/printlevels.fh
                                        ${NWCHEM}/src/util/stdio.fh
                                        ${NWCHEM}/src/util/testutil.fh
                                        ${NWCHEM}/src/util/util.fh
                                        ${NWCHEM}/src/util/utilc_nwchem_srcdir.fh
                                        ${NWCHEM}/src/util/util_io_data.fh
                                        ${NWCHEM}/src/util/util_params.fh
                                        ${NWCHEM}/src/util/util_sgroup.fh
                                        ${NWCHEM}/src/util/vtune.fh
            )
    endif()

    # PEIGS header files
    list(APPEND PEIGS_HEADER_FILES ${NWCHEM}/src/peigs/h/blas_lapackf.h
                                   ${NWCHEM}/src/peigs/h/blas_lapack.h
                                   ${NWCHEM}/src/peigs/h/clustr_inv.h
                                   ${NWCHEM}/src/peigs/h/defines.h
                                   ${NWCHEM}/src/peigs/h/globalp.c.h
                                   ${NWCHEM}/src/peigs/h/peigs_types.h
                                   ${NWCHEM}/src/peigs/h/timing.h)

    # NB: these files are not available until NWChem has been built
    list(APPEND NWCHEM_EXTRA_HEADER_FILES ${NWCHEM}/src/tools/install/include/tcgmsg.fh
                                          ${NWCHEM}/src/tools/install/include/gacommon.h
                                          ${NWCHEM}/src/tools/install/include/global.fh
                                          ${NWCHEM}/src/tools/install/include/mafdecls.fh
                                          ${NWCHEM}/src/tools/install/include/macommon.h
        )

    list(APPEND NWCHEM_MORE_HEADER_FILES ${NWCHEM}/src/rtdb/rtdb.fh
                                         ${NWCHEM}/src/pstat/pstat.fh
                                         ${NWCHEM}/src/pstat/pstat_consts.fh
                                         ${NWCHEM}/src/inp/inp.fh
                                         ${NWCHEM}/src/bq/bq.fh
                                         ${NWCHEM}/src/bq/bq_params.fh
                                         ${NWCHEM}/src/geom/geom.fh
        )

    # do NOT mess up the order! duplicated? must be!
    # new in 6.8: libnwcblas.a, libnwclapack.a, libdimqm.a
    # YL 02/07/2023: new in 7.2: libfcidump.a libgwmol.a
# YL TODO: libpeigs.a
    list(APPEND NWCHEM_STATIC_LIBS libnwcblas.a
                                   libnwclapack.a
                                   libnwctask.a
                                   libccsd.a
                                   libmcscf.a
                                   libselci.a
                                   libmp2.a
                                   libmoints.a
                                   libstepper.a
                                   libdriver.a
                                   liboptim.a
                                   libnwdft.a
                                   libgradients.a
                                   libcphf.a
                                   libesp.a
                                   libddscf.a
                                   libdangchang.a
                                   libguess.a
                                   libhessian.a
                                   libvib.a
                                   librimp2.a
                                   libnwcutil.a
                                   libsolvation.a
                                   libnwints.a
                                   libprepar.a
                                   libnwmd.a
                                   libnwpw.a
                                   libofpw.a
                                   libpaw.a
                                   libpspw.a
                                   libband.a
                                   libnwpwlib.a
                                   libcafe.a
                                   libspace.a
                                   libanalyze.a
                                   libqhop.a
                                   libpfft.a
                                   libdplot.a
                                   libdrdy.a
                                   libvscf.a
                                   libqmmm.a
                                   libqmd.a
                                   libetrans.a
                                   libbq.a
                                   libmm.a
                                   libcons.a
                                   libperfm.a
                                   libdntmc.a
                                   libccca.a
                                   libproperty.a
                                   libtce.a
                                   libdimqm.a
                                   libfcidump.a
                                   libgwmol.a
                                   lib64to32.a
)

    list(APPEND NWCHEM_EXTRA_STATIC_LIBS "")

# TODO: replace with copied header files
#    include_directories(${NWCHEM_DIR}/src/nwdft/include)
#    include_directories(${NWCHEM_DIR}/src/tools/install/include)


    # check if the provided NWChem has been precompiled
    set(TEST_RESULT "")
    set(NUM_NWCHEM_FOUND_STATIC_LIBS 0)
    message("\n${BoldMagenta}Scanning pre-compiled NWChem libraries...${EndColour}")
    foreach(NWCHEM_LIB ${NWCHEM_STATIC_LIBS})
        if(EXISTS ${NWCHEM_LIB_DIR}/${NWCHEM_LIB})
            math(EXPR NUM_NWCHEM_FOUND_STATIC_LIBS ${NUM_NWCHEM_FOUND_STATIC_LIBS}+1)
            set(NWCHEM_FOUND_STATIC_LIBS "${NWCHEM_FOUND_STATIC_LIBS} ${NWCHEM_LIB_DIR}/${NWCHEM_LIB}")
        endif()
    endforeach(NWCHEM_LIB)
    # do the following commands in a sequence because multiple COMMANDs are processed in parallel!
    # have to define the command line as a list of words (annoying!)
    set(NWCHEM_TRIAL_CMD "${CMAKE_Fortran_COMPILER} ${CMAKE_Fortran_FLAGS} -fPIC -c ${CHEMSH_DIR}/chemsh/utils/cmake/trial_nwchem.f90 -o ${CHEMSH_DIR}/chemsh/utils/cmake/trial_nwchem.f90.o")
    string(REPLACE " " ";" NWCHEM_TRIAL_CMD ${NWCHEM_TRIAL_CMD})
    execute_process(COMMAND ${NWCHEM_TRIAL_CMD}
                    WORKING_DIRECTORY ${CHEMSH_DIR}/chemsh/utils/cmake
                    RESULT_VARIABLE TEST_RESULT
                    OUTPUT_QUIET
                    ERROR_QUIET
                   )
    set(NWCHEM_TRIAL_CMD "${CMAKE_Fortran_COMPILER} ${CMAKE_Fortran_FLAGS} -shared -Wl,--whole-archive ${NWCHEM_FOUND_STATIC_LIBS} -Wl,--no-whole-archive -Wl,--allow-multiple-definition -Wl,-soname,libtrial_nwchem.so -o ${CHEMSH_DIR}/chemsh/utils/cmake/libtrial_nwchem.so ${CHEMSH_DIR}/chemsh/utils/cmake/trial_nwchem.f90.o")
    string(REPLACE " " ";" NWCHEM_TRIAL_CMD ${NWCHEM_TRIAL_CMD})
    execute_process(COMMAND ${NWCHEM_TRIAL_CMD}
                    WORKING_DIRECTORY ${CHEMSH_DIR}/chemsh/utils/cmake
                    RESULT_VARIABLE TEST_RESULT
#                    OUTPUT_QUIET
#                    ERROR_QUIET
                   )
    if(TEST_RESULT OR NOT NUM_NWCHEM_FOUND_STATIC_LIBS OR NOT IS_DIRECTORY ${NWCHEM_LIB_DIR})
        # if not from URL
        if(NWCHEM_BUILD_MANUALLY)
            # mixed formatted and unformatted markup language output
            # see: https://stackoverflow.com/questions/50447052/cmake-multiline-message-with-fatal-error
            message(FATAL_ERROR
                "\n \n"
                " ${BoldRed}It looks that NWChem has not been compiled with -fPIC flag in the provided location${EndColour}"
                "\n \n"
                " ${Blue}${NWCHEM}${EndColour}"
                "\n \n"
                " ${BoldRed}ChemShell does not compile NWChem as does for other codes since it can take hours. Please go to${EndColour}"
                "\n \n"
                " ${Blue}${NWCHEM_SRC_DIR}${EndColour}"
                "\n \n"
                " ${BoldRed}and run the script${EndColour}"
                "\n \n"
                " ${BoldGreen}${NWCHEM_SCRIPT}${EndColour}"
                "\n \n"
                " ${BoldRed}that ChemShell has just generated. Come back and try again when you have finished the NWChem compile.${EndColour}")
        else()
            # automatic build in URL mode: unlike other programs NWChem has to be built at the configure stage
            message("${BoldRed}\nIt takes ChemShell a while to compile NWChem. Please be patient.\n${EndColour}")
            # remove the log files before proceeding so to check the progress
            file(REMOVE ${NWCHEM}/src/config.log ${NWCHEM}/src/64_to_32.log ${NWCHEM}/src/make.log)
            message("Using script: ${NWCHEM}/src/${NWCHEM_SCRIPT_FILENAME}")
            execute_process(COMMAND ${NWCHEM}/src/${NWCHEM_SCRIPT_FILENAME})
        endif()
    endif()

    # YL 05/12/2021: copy header files only after NWChem has been compiled (because otherwise the GA headers won't be available)
    foreach(NWCHEM_HEADER ${NWCHEM_BASIS_HEADER_FILES})
        if(EXISTS ${NWCHEM_HEADER})
            file(COPY ${NWCHEM_HEADER} DESTINATION ${NWCHEM_INCLUDE_DIRECTORY})
        endif()
    endforeach(NWCHEM_HEADER)
    foreach(NWCHEM_HEADER ${NWCHEM_HEADER_FILES})
        if(EXISTS ${NWCHEM_HEADER})
            file(COPY ${NWCHEM_HEADER} DESTINATION ${NWCHEM_INCLUDE_DIRECTORY})
        endif()
    endforeach(NWCHEM_HEADER)
    foreach(NWCHEM_HEADER ${NWCHEM_EXTRA_HEADER_FILES})
        if(EXISTS ${NWCHEM_HEADER})
            file(COPY ${NWCHEM_HEADER} DESTINATION ${NWCHEM_INCLUDE_DIRECTORY})
        endif()
    endforeach(NWCHEM_HEADER)
    foreach(NWCHEM_HEADER ${NWCHEM_MORE_HEADER_FILES})
        if(EXISTS ${NWCHEM_HEADER})
            file(COPY ${NWCHEM_HEADER} DESTINATION ${NWCHEM_INCLUDE_DIRECTORY})
        endif()
    endforeach(NWCHEM_HEADER)
    foreach(PEIGS_HEADER ${PEIGS_HEADER_FILES})
        if(EXISTS ${PEIGS_HEADER})
            file(COPY ${PEIGS_HEADER} DESTINATION ${PEIGS_INCLUDE_DIRECTORY})
        endif()
    endforeach(PEIGS_HEADER)


    # link static libs under
    # has to be absolute path!
    set(NWCHEM_COPIED_LIBS "")
    foreach(NWCHEM_LIB ${NWCHEM_STATIC_LIBS})
        if(EXISTS ${NWCHEM_LIB_DIR}/${NWCHEM_LIB})
            file(COPY ${NWCHEM_LIB_DIR}/${NWCHEM_LIB} DESTINATION ${NWCHEM_LIB_DIRECTORY})
            set(NWCHEM_COPIED_LIBS "${NWCHEM_COPIED_LIBS} ${NWCHEM_LIB_DIRECTORY}/${NWCHEM_LIB}")
        else()
            message("${NWCHEM_LIB_DIR}/${NWCHEM_LIB} not found, omitting...")
        endif()
    endforeach(NWCHEM_LIB)

    # link to libchemsh.so
    message("${BoldBlue}Pre-compiled NWChem libraries will be built into ChemShell...${EndColour}")
    target_include_directories(nwchem PRIVATE ${NWCHEM_INCLUDE_DIRECTORY}
#                                      PRIVATE ${CHEMSH_BUILD_DIR}/modules/parallel
                                      PRIVATE ${GA_INCLUDE_DIRECTORY}
                                      PRIVATE ${MA_INCLUDE_DIRECTORY})

    # YL 21/01/2021: on ARCHER2 with Cray compilers the ChemShellParallelModule is only kept in memory when libparallel.so is dynamically linked
    add_dependencies(nwchem parallel ga dl_py2f)
    #target_link_libraries(nwchem dl_py2f parallel)
    target_link_libraries(nwchem dl_py2f)

    # compile all pre-compiled NWChem static libs in to libnwchem.so
    # place libparallel.so FIRST(!) for linking purpose to enable valid Fortran `common block` defined in header files,
    # otherwise DBL_MB, INT_MB, etc. will be created again besides in GA module!
    # YL 08/12/2017: bizarre that the above statement turns opposite now!!! first linking argument MUST be ligga.so,
    #                otherwise MA arrays (will be created twice?) and cannot be indexed (segmentation fault) outside libga.so!
    # YL FIXME 08/12/2017: --unresolved-symbols=ignore-all required on ARCHER at link time
    set_target_properties(nwchem PROPERTIES LINK_FLAGS "${CHEMSH_BUILD_DIR}/lib/libga.so \
                                                        -Wl,--whole-archive              \
                                                        ${NWCHEM_COPIED_LIBS}            \
                                                        -Wl,--no-whole-archive           \
                                                        -Wl,--version-script=${CMAKE_CURRENT_LIST_DIR}/export.map \
                                                        -Wl,--allow-multiple-definition")#                           \
#                                                        -Wl,--unresolved-symbols=ignore-all")
#                                                        -Wl,--allow-multiple-definition  \
#                                                        -Wl,--unresolved-symbols=ignore-all")
#                                                        #${CHEMSH_MKL_FLAGS}              \

else()

    target_include_directories(nwchem PRIVATE ${CHEMSH_BUILD_DIR}/modules/parallel)
    target_link_libraries(nwchem dl_py2f)

endif()

#set_directory_properties(PROPERTIES ADDITIONAL_MAKE_CLEAN_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src;nwchem_dummies.f90;makefile.h;")
