!--------------------------------------- LICENCE BEGIN -----------------------------------
!Environment Canada - Atmospheric Science and Technology License/Disclaimer,
!                     version 3; Last Modified: May 7, 2008.
!This is free but copyrighted software; you can use/redistribute/modify it under the terms
!of the Environment Canada - Atmospheric Science and Technology License/Disclaimer
!version 3 or (at your option) any later version that should be found at:
!http://collaboration.cmc.ec.gc.ca/science/rpn.comm/license.html
!
!This software 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 above mentioned License/Disclaimer for more details.
!You should have received a copy of the License/Disclaimer along with this software;
!if not, you can write to: EC-RPN COMM Group, 2121 TransCanada, suite 500, Dorval (Quebec),
!CANADA, H9P 1J3; or send e-mail to service.rpn@ec.gc.ca
!-------------------------------------- LICENCE END --------------------------------------


function getNumAnalyses() result(numAnalyses) 1,1

  ! function: getNumAnalyses - Determine the number of analyses to perform
  !                            by checking which trlm files exist

  implicit none
  integer :: numAnalyses, indexAnalysis
  integer, parameter :: maxNumAnalyses = 256
  character(len=128) :: fileName
  character(len=4)   :: flnum
  logical   fileExists

  filename='./trlm_01'
  inquire(file=trim(fileName),exist=fileExists)
  if(fileExists) then
    numAnalyses = 1
  else
    LOOP_ANL: do indexAnalysis = 1,maxNumAnalyses
      write(flnum,'(I4.4)') (indexAnalysis-1)
      fileName='./trlm_01_' // trim(flnum)
      inquire(file=trim(fileName),exist=fileExists)
      if(.not.fileExists) then
        numAnalyses = indexAnalysis-1
        exit LOOP_ANL
      endif
    enddo LOOP_ANL
  endif

  if(numAnalyses.eq.0) then
    call abort3d('getNumAnalyses: could not find trlm_01 files!')
  else
    write(*,*) '======================================================'
    write(*,*) 'getNumAnalyses: number of Analyses to be performed = ',numAnalyses
    write(*,*) '======================================================'
  endif

END function getNumAnalyses