      double precision function
     &sumthemup(n,time,starttime,endtime,xtosum)
      implicit none
      integer n,i,j
      double precision time(n),starttime,endtime,xtosum(n),agap,
     &fmean
      agap=-9999.0d0
      sumthemup=agap
      fmean=0.0d0
      j=0
      do i=1,n
        if(time(i).ge.starttime.and.time(i).lt.endtime)then
          if(dabs(xtosum(i)-agap).gt.1.0d-5)then
            j=j+1
            fmean=fmean+xtosum(i)
          endif
        endif
      enddo
      if(j.eq.0)return
      fmean=fmean/dble(j)
      sumthemup=0.0d0
      do i=1,n
        if(time(i).ge.starttime.and.time(i).lt.endtime)then
          if(dabs(xtosum(i)-agap).gt.1.0d-5)then
            sumthemup=sumthemup+xtosum(i)
          else
            sumthemup=sumthemup+fmean
          endif
        endif
      enddo 
      return
      end

