      subroutine p_ts_zln(nq,nlink,nmeas,beta0,b,a,tsa,zln,aln,a2ln,
     &                    xm2ln,nstate) ! bernd berg, jul 13 2002. 
c potts model: ln of the partition function z and related variables 
c              from time series fragments.
      include '../../libs/fortran/implicit.sta'
      include '../../libs/fortran/constants.par'
      dimension b(0:nlink),a(0:nlink),tsa(nmeas,0:nq)
      dimension nstate(0:nq-1)
c
      nqm1=nq-1
      do imeas=1,nmeas
        iact=nint(tsa(imeas,nq))
        if(iact.le.0) stop "p_ts_zln: iact.le.0."
        do iq=0,nqm1
          nstate(iq)=nint(tsa(imeas,iq))
c         if(iq.eq.0) nstate(iq)=nlink/2 ! test purposes.
c         if(iq.ne.0) nstate(iq)=0
        end do
        if(imeas.eq.1) then
          zln=two*((beta0-b(iact))*iact+a(iact))
          aln=zln+log(iact*one)
          a2ln=zln+two*log(iact*one)
          xm2ln=zln+two*log(nstate(0)*one)
          do iq=1,nqm1
            xm2ln1=zln+two*log(nstate(iq)*one)
            xm2ln=addln(xm2ln,xm2ln1)
          end do
        else
          zln1=two*((beta0-b(iact))*iact+a(iact))
          aln1=zln1+log(iact*one)
          a2ln1=zln1+two*log(iact*one)
          zln=addln(zln,zln1)
          aln=addln(aln,aln1)
          a2ln=addln(a2ln,a2ln1)
          do iq=0,nqm1
            xm2ln1=zln1+two*log(nstate(iq)*one)
            xm2ln=addln(xm2ln,xm2ln1)
          end do
        end if
      end do
c
      return
      end
