C convergence.f
C    calculate whether the system has converged
C
      logical function convergence(iter)
	 integer iter 
         
	 include 'statistics.h' 
	 include 'casco_params.h' 

	 real relcost, deltacost
	 real  del_bccost, del_velcost
	 real  del_elevcost

	 relcost = costfunc/cost0

	 if(iter.gt.1) then 
	    deltacost = (costm1 - costfunc )/costm1
	    del_bccost = (bc_costm1 - bc_cost)/bc_costm1
	    
	    if (vel_costm1.gt.0.)then    
	      del_velcost = (vel_costm1 - vel_cost)/vel_costm1
            else
	      del_velcost=0.
	    endif 
	    
	    if (elev_costm1.gt.0.)then    
	      del_elevcost = (elev_costm1 - elev_cost)/elev_costm1
            else
	      del_elevcost=0.
	    endif 
	 else
	    deltacost = 2*cutoff2
	    del_bccost = 2*cutoff2
	    del_velcost = 2*cutoff2
	    del_elevcost = 2*cutoff2
	 endif

         write(*,*)'CONVER1 ', iter, relcost, cutoff1
         write(*,*)'CONVER2 ', iter, deltacost, cutoff2
         write(*,*)'CONVER3 ', iter, del_bccost, cutoff2
         write(*,*)'CONVER4 ', iter, del_velcost, cutoff2
         write(*,*)'CONVER5 ', iter, del_elevcost, cutoff2

	 if ((relcost.le.cutoff1).or.(deltacost.le.cutoff2)) then 
	    convergence = .true. 
	 else
	    convergence = .false.
	 endif

      return 
      end
