MODULE PotentialData

! This module allows the program to smartly detect where the data for a
! potential is stored.

  USE ErrorTrap

  IMPLICIT NONE

  PRIVATE :: NumLocations, Locations, CurrentLocation

  INTEGER, PARAMETER :: NumLocations = 10, MaxStringLength = 200
  CHARACTER( LEN=MaxStringLength ), DIMENSION( NumLocations ) :: Locations
  INTEGER :: CurrentLocation = 1

CONTAINS

! Set up standard potential data folders. The program checks the following
! directories, in order:
!
! Input file parameter PESDataBase (this folder is not added here but in Read_Input())
! Environment variable PESDATA (requires -DHAVE_GET_ENVIRONMENT_VARIABLE)
! The current folder (.)
! The folders QCTraj, .QCTraj, PESDATA, .PESDATA in the home directory of the user (requires -DHAVE_GET_ENVIRONMENT_VARIABLE)
  SUBROUTINE Standard_Potential_Data_Folders( )
    IMPLICIT NONE

#ifdef HAVE_GET_ENVIRONMENT_VARIABLE
    CHARACTER( LEN=MaxStringLength ) :: HomeDir, PESDir
#endif

#ifdef HAVE_GET_ENVIRONMENT_VARIABLE
    CALL GET_ENVIRONMENT_VARIABLE( "PESDATA", PESDir )
    CALL Add_Potential_Data_Folder( TRIM(PESDir) )
#endif
    CALL Add_Potential_Data_Folder( "." )
#ifdef HAVE_GET_ENVIRONMENT_VARIABLE
    CALL GET_ENVIRONMENT_VARIABLE( "HOME", HomeDir )
    CALL Add_Potential_Data_Folder( TRIM(HomeDir) // "/QCTraj" )
    CALL Add_Potential_Data_Folder( TRIM(HomeDir) // "/.QCTraj" )
    CALL Add_Potential_Data_Folder( TRIM(HomeDir) // "/PESDATA" )
    CALL Add_Potential_Data_Folder( TRIM(HomeDir) // "/.PESDATA" )
#endif
  END SUBROUTINE

  SUBROUTINE Add_Potential_Data_Folder( Location )
    IMPLICIT NONE

    CHARACTER( LEN=* ) :: Location

    IF ( CurrentLocation .LE. NumLocations ) THEN
      Locations( CurrentLocation ) = Location
      CurrentLocation = CurrentLocation + 1
    ELSE
      CALL AbortwithError( "Could not add location of potential data, array is full." )
    END IF
  END SUBROUTINE

  FUNCTION Test_Potential_Data( PotentialFile )
    IMPLICIT NONE

    INTEGER :: i
    CHARACTER( LEN=* ) :: PotentialFile
    CHARACTER( LEN=MaxStringLength ) :: Test_Potential_Data
    LOGICAL :: Exists

    IF ( CurrentLocation == 1 ) THEN
      CALL AbortwithError( "The potential data search path was not set up." )
    END IF

    DO i = 1, CurrentLocation - 1
      INQUIRE( FILE=TRIM(Locations(i)) // "/" // TRIM(PotentialFile), EXIST=Exists )
      IF ( Exists ) THEN
        Test_Potential_Data = TRIM(Locations(i))
        RETURN
      END IF
    END DO
    CALL AbortwithError( "Could not find potential data " // PotentialFile // " in the potential data search path." )
  END FUNCTION

END MODULE
