      SUBROUTINE POTTS_ZLN(nlink,namin,beta0,b,ha,hasum,iopt,
     &                     Zln,Aln,A2ln)
C Copyright Bernd Berg, May 12 2000.
C Potts model ln of the partition function Z and related variables.
      include 'implicit.sta'
      include 'constants.par'
      dimension b(0:nlink),ha(0:nlink),hasum(0:nlink)
C
      if(namin.le.0) stop "POTTS_ZLN: namin false."
      ilink_min=nlink
      do ilink=0,nlink
        ha(ilink)=hasum(ilink)-ha(ilink) ! Jackknife histogram.
        if(ha(ilink).gt.half) then
          iact=ilink-namin
          if(ilink_min.gt.ilink) then
            ilink_min=ilink
            a=zero
            Zln=log(ha(ilink))+two*(beta0-b(ilink))*iact
            Zln1_max=Zln
            Aln=Zln+log(ilink*one)
            A2ln=Zln+two*log(ilink*one)
          else
            if(ilink.eq.namin) a=b(namin)*iact_old
            if(ilink.gt.namin) then
              a=a+(b(ilink)-b(ilink_old))*iact_old
            end if
            Zln1=log(ha(ilink))+two*((beta0-b(ilink))*iact+a)
            Zln1_max=max(Zln1_max,Zln1)
            Aln1=Zln1+log(ilink*one)
            A2ln1=Zln1+two*log(ilink*one)
            Zln=addln(Zln,Zln1)
            Aln=addln(Aln,Aln1)
            A2ln=addln(A2ln,A2ln1)
            iact_old=iact
            ilink_old=ilink
          end if
        end if
      end do
C
      if(iopt.ne.1) return
C iact probability density at beta0:
C
      a=zero
      hsum=zero
      do ilink=0,nlink
        if(ha(ilink).gt.half) then
          if(ilink.eq.namin) a=b(namin)*iact_old
          if(ilink.gt.namin) a=a+(b(ilink)-b(ilink_old))*iact_old
          iact=ilink-namin
          Zln1=log(ha(ilink))+two*((beta0-b(ilink))*iact+a)-Zln1_max
          if(Zln1.gt.0.01d00) stop "Zln1." 
          ha(ilink)=exp(Zln1)
          hsum=hsum+ha(ilink)
          iact_old=iact
          ilink_old=ilink
        else
          ha(ilink)=zero
        end if
      end do
      do ilink=0,nlink
        ha(ilink)=ha(ilink)/hsum
      end do
C
      return
      end
