C Calculate the optimal step size given the errors before moody
C the errors after saco (with an assumed step size of 1). 
C 
C 30 Nov, 1998  CGH - velocity terms only
C 3 Dec, 1998   CGH - add boundary elevation terms 
C 20 Aug 1999: added Wrho_t cgh
C 12 Nov 2002   CGH add elevation observations and expected cost reduction.
C 
      real function stepsize5(uerr0,verr0,uerr,verr,w_delta,nobs,
     $        eerr0,eerr,w_eps,n_eobs,
     $        dbc_best, dbc, Wrho,Wrho_t, IQrho, JQrho, nr,ntbc,
     $        nrdim,ntbcdim,nwrhodim, scratch1,scratch3,scratch2)

          integer nobs, n_eobs,nr, ntbc
	  integer nrdim,ntbcdim, nwrhodim 
	  real    uerr0(nobs), verr0(nobs), uerr(nobs), verr(nobs)
	  real    w_delta(nobs)
          real    eerr0(n_eobs),eerr(N_eobs)
          real    w_eps(n_eobs) 
	  real    dbc_best(nrdim,ntbcdim), dbc(nrdim,ntbcdim)
	  real    Wrho(nwrhodim)
	  real    Wrho_t(nrdim)
	  integer IQrho(nrdim), JQrho(nwrhodim)
	  real    scratch1(nobs), scratch3(n_eobs)
	  real    scratch2(nrdim,ntbcdim)

	  integer i,j
	  real    sum1, sum2, sum3, sum4 
	  real    sum5, sum6, sum7, sum8
          real    exp_costreduce
C
C   functions
	  real d1WDELTAd2, dWDELTAd 
	  real xWrhox, xWrhoy 

	  write(*,*)'stepsize5: nobs,n_eobs ', nobs,n_eobs
	  write(*,*)'stepsize5: nr,ntbc ', nr,ntbc

C Velocity error terms
          sum1 = 0.
          sum2 = 0.
	  do i = 1, nobs
	     scratch1(i) = uerr(i) - uerr0(i)
	  enddo
	  sum1 = d1WDELTAd2(scratch1,w_delta,uerr0,nobs)
	  sum2 = dWDELTAd(scratch1,w_delta,nobs)

	  do i = 1, nobs
	     scratch1(i) = verr(i) - verr0(i)
	  enddo
	  sum3 = d1WDELTAd2(scratch1,w_delta,verr0,nobs)
	  sum4 = dWDELTAd(scratch1,w_delta,nobs)

C Elevation error terms
          sum7 = 0.0
          sum8 = 0.0 
c          write(*,*)'stepsize5 elevation error'
	  do i = 1, n_eobs
	     scratch3(i) = eerr(i) - eerr0(i)
c             write(*,*)i,eerr(i),eerr0(i),scratch3(i),w_eps(i)
	  enddo
	  sum7 = d1WDELTAd2(scratch3,w_eps,eerr0,n_eobs)
	  sum8 = dWDELTAd(scratch3,w_eps,n_eobs)

C Elevation Boundary Condition terms
          do j = 1, ntbc
	     do i = 1, nr
		scratch2(i,j) = dbc(i,j) - dbc_best(i,j) 
c               scratch2(i,j) = dbc_best(i,j) - dbc(i,j)
	     enddo
	  enddo

          sum5 = xWrhoy(scratch2,Wrho,Wrho_t,dbc_best,IQrho,JQrho
     $                  ,nr,ntbc) 
	  sum6 = xWrhox(scratch2,Wrho,Wrho_t,IQrho,JQrho,nr,ntbc)


c	  stepsize2 = -(sum1+sum3)/(sum2+sum4)
c         stepsize4 = -(sum1+sum3+sum5)/(sum2+sum4+sum6)
	  stepsize5 = -(sum1+sum3+sum5+sum7)/(sum2+sum4+sum6+sum8)

          exp_costreduce = (sum1+sum3+sum5+sum7)**2/
     $                                    (sum2+sum4+sum6+sum8)

          write(*,101)sum1,sum2,sum3,sum4
          write(*,101)sum5,sum6,sum7,sum8
          write(*,102)exp_costreduce
          
101       format('stepsize5:',6(1x,G10.3))
102       format('exp_costreduce:',6(1x,G10.3))

      return
      end
C   
C
C

