      subroutine ts_z(n,nmeas,tsa,tspr,tspi,betap,beta,actm,z,a1,a2,
     &                p2b,pabsb,pbetb) ! 
c bernd berg, jan 29 2006. reweighting of energy and specific heat.
c n:     multiplicative factor to convert energy (action) per 
c        degree of freedom to extensive energy (action
c nmeas: number of measurements in tsa(nmeas) on input. 
c tsa:   energy (action) times series on input.
c betap: beta value too which we reweight.
c beta:  beta value at which the data were produced.
c actm:  means value over all data of the action variable.
c z:     partition function patch one output.
c a1:    numerator of action density on output
c a2:    numerator of action density squared on output.
      include '../../libs/fortran/implicit.sta'
      include '../../libs/fortran/constants.par'
      dimension tsa(nmeas),tspr(nmeas),tspi(nmeas)
      ltest=.true.
      ltest=.false.
      if(ltest) stop "ts_z: ltest."
c
      act=tsa(1) 
      p2=tspr(1)**2+tspi(1)**2
      pabs=sqrt(p2)
      pbet=act*pabs
      z=exp((betap-beta)*(act-actm)*n)
      a1=act*z
      a2=act*a1
      p2b=p2*z
      pabsb=pabs*z
      pbetb=pbet*z
      do imeas=2,nmeas
        act=tsa(imeas) 
        p2=tspr(imeas)**2+tspi(imeas)**2
        pabs=sqrt(p2)
        pbet=act*pabs
        zadd=exp((betap-beta)*(act-actm)*n)
        a1add=act*zadd
        a2add=act*a1add
        p2add=p2*zadd
        pabsadd=pabs*zadd
        pbetadd=pbet*zadd
        z=z+zadd
        a1=a1+a1add
        a2=a2+a2add
        p2b=p2b+p2add
        pabsb=pabsb+pabsadd
        pbetb=pbetb+pbetadd
      enddo
c
      return
      end
