      subroutine facRES
c
c  Calculate new residual variances
c
      include 'TThead.f'
c
      real*8 wv(nog+10),dif,c,y,z,w,x,dx
      real*8 ry(ntr),ay(ntr),ey(ntr),u,chi
      real*8 hh(nog),qq(nog),sse(nog)
      integer iv(nog+10),ndf

      sse=0.d0
      kob=0
       ndf=0.d0
c      print *,' TTres '
c////////////////////////////////////////////////
      do 12 krec=1,mrec
c
        icod = kcod(krec)
        iam  = an(krec)
        iage = bage(krec)
         ihys = hys(krec)
         iymj = kymj(krec)
c%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
         ay=0.d0
         do 20 ka=1,ntr
            y=obs(krec,ka)
            if(y.gt.0.d0)then
            y = y - shys(ihys,ka)-sanm(iam,ka)-sage(iage,ka)
            y = y - symj(iymj,ka)-sape(iam,ka)
            ay(ka) = y
         endif
 20     continue
c%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
c&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
        ry=0.d0
        do 30 ir=1,ntr
         z = 0.d0
         do 35 ic=1,ntr
            m=ihmssf(ir,ic,ntr)
            z = z + ric(icod,m)*ay(ic)
 35      continue
         ry(ir) = z
 30   continue
      ey=0.d0
      do 36 ir=1,ntr
         z=0.d0
         do 37 ic=1,ntr
            m=ihmssf(ir,ic,ntr)
            z=z+Ri(m)*ry(ic)
 37      continue
         ey(ir)=z
 36   continue
      m=0
      ndf=ndf+1
      do 41 ir=1,ntr
         c=ey(ir)
         do 42 ic=ir,ntr
            m=m+1
            sse(m)=sse(m)+c*ey(ic)
 42      continue
 41   continue
c&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
c
 12   continue

      nm=4
      Ri =0.d0
      ric = 0.d0
      ndf=ndf+2
      call fgchi1(ndf,chi)
      dif=1.d0/chi
      do 44 m=1,nog
         Ri(m)=sse(m)*dif
 44   continue
      if(bayes.gt.0)then
         write(19)iter,nm,(Ri(mc),mc=1,nog)
      endif
      do 219 ir=1,no
         hh(ir)=Ri(ihmssf(ir,ir,no))
 219  continue
      if(itest.gt.0)then
      print 2224,ndf
 2224 format(1x,'RES ',i10)
      print 2229,(hh(k),k=1,no)
 2229 format(1x,5f12.4)
      endif
      ric=0.d0
      do 73 icod=1,28
      qq=0.d0
      do 176 i=1,no
       if(rcod(icod,i).gt.0)then
          do 76 j=i,no
             if(rcod(icod,j).gt.0)then
                  k=ihmssf(i,j,no)
                  qq(k)=Ri(k)
             endif
 76       continue
       endif
 176  continue
      call dkmvhf(qq,no,wv,iv)
c  move into ri
      do 77 i=1,no
        do 77 j=i,no
          mn=ihmssf(i,j,no)
          ric(icod,mn)=qq(mn) 
 77    continue
 73    continue
c 
      return
      end
