!--------------------------------------- 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 --------------------------------------


subroutine getStepObsIndex(dnstepobs,kstsyn,kdobs,ktobs,knstepobs) 3

  implicit none

  ! Author : Mark Buehner (based on stepobs.ftn90)
  !
  ! Purpose: Return the stepobs index as a real number (-1.0 if out of range)
  !
  integer, intent(in) :: kstsyn    ! Synop CMC date-time stamp
  integer, intent(in) :: kdobs     ! Obs date YYYYMMDD
  integer, intent(in) :: ktobs     ! Obs time HHMM
  integer, intent(in) :: knstepobs ! number of stepobs in assimilation window

  real*8,  intent(out):: dnstepobs ! number of stepobs from synop time

  ! Locals
  real*8  :: dddt      ! dstepobs
  integer :: newdate, istat, imode
  integer :: istobs    ! Obs CMC date-time stamp
  integer :: itobs     ! Obs time HHMMSShh
  real*8  :: dlhours   ! Del time from synop time

  ! ----------------------- CODE ---------------------------------------------

  ! Building observation stamp
  imode = 3 ! printable to stamp
!  itobs = ktobs * 10000 + 2900
  itobs = ktobs * 10000
  istat = newdate(istobs, kdobs,itobs,imode)

  ! Difference (in hours) between obs time and synop time
  call difdatr (istobs,kstsyn, dlhours)

  if(knstepobs.gt.1) then
    ! FGAT: more than 1 trial field in time window
    dddt = 6.0d0/(real(knstepobs-1,8))
    dnstepobs = dlhours/dddt ! number of step obs from synop time
    dnstepobs = dnstepobs + real((knstepobs+1)/2,8)
    if(dnstepobs.lt.0.5d0.or.dnstepobs.gt.(0.5d0+real(knstepobs,8))) dnstepobs=-1.0d0

  else
    ! 3D-Var: only 1 trial field in time window
    if(dlhours.lt.-3.0d0.or.dlhours.gt.3.0d0) then
      ! outside time window
      dnstepobs=-1.0d0
    else
      ! inside time window
      dnstepobs= 1.0d0
    endif

  endif

end subroutine getStepObsIndex