c
c    @(#)budget.f	1.3
c
      subroutine budget

      include'mladv.inc'

      common/parm/kz,m,mm1,mm2,mp1,msq,tim,tmax,tstart,hy,rea,dt,
     +   xbasin,yy(mx0),icalc,kzp1,kzm1,iftop,ifbot,iftvv,ifrel,theta,
     +   ifsbl,ifeva

      common /extpar/ rlat0,rlng0,t0,v0,dhor,ht,time0,r0,f0star

      common/inform/ifdiff,ifpert,titl(20,2),runid(6),restid(9),
     +              idstring,ident

      character*70 idstring
      character*80 ident,fname
      character*4 restid,runid

      character*1 trno

      dimension tbud(lmax+1,maxtrace)

      data icall/0/

      if (icall.eq.0) then
         iflen=lnblk(ident,80)
         do 5 i=1,ntrace
            write(trno,6)i
  6         format(i1)
            fname=ident(:iflen)//'.bd'//trno
            open(unit=ibunit+i,file=fname,status='new',form='formatted')
  5       continue
         icall=1
        endif

      tstd = tstart * t0 / 86400.
      if (amod(mltime-tstd+qgts*.5/86400.,dtbudi)
     .                           .ge.qgts/86400.) return

      do 1 i=1,ntrace

         do 2 j=1,l+1
            tbud(j,i)=0.
  2       continue

         icurtrace = i

         do 3 j=1,l
            do 4 k=1,msq
               tbud(j,i)=tbud(j,i)+trace(k,j,mlcur,i)+trcqgofk(k,j)
  4          continue
            tbud(j,i)=tbud(j,i)/float(msq)
  3       continue

            do 9 k=1,msq
               tbud(l+1,i)=tbud(l+1,i)+trace(k,l+1,mlcur,i)
  9          continue
            tbud(l+1,i)=tbud(l+1,i)/float(msq)

          write(ibunit+i,7)mltime,(tbud(j,i),j=1,l+1)
c         call xwrite(tbud(1,i),l+1,mltime,1,i,1,1,ibunit+i)

  7      format(99e13.5)

  1    continue

      return
      end
