      SUBROUTINE zfit_min(iagem,itypem,av,zmin_f,zmax_f,
     .     dz_f,chi2,zop)

      REAL*8 bm,wt,sxx,sxy,b
      INCLUDE 'dimension.dec'
      DIMENSION dif(101),yob(mxwl),y(mxwl),y1(mxwl),fluz(mxfil),
     .     fl2(mxfil),ww(mxwl)
      COMMON/et1/surf(0:mxfil)
      COMMON/et2/W(mxwl,mxtyp),F(mxwl,mxage,mxtyp),fl(mxfil),
     .     err_fl(mxfil)
      COMMON/et3/law_rd
      COMMON/et4/n_filter,nfil(0:mxfil),iw(mxtyp),i_lyman(mxfil)
      COMMON/et5/bm
      
      nz_f=INT((zmax_f-zmin_f)/dz_f)+1
      chi2=1.E+12
      DO k=1,iw(itypem)   
         y(k)=f(k,iagem,itypem) !age et type minimum
         ww(k)=w(k,itypem)
      END DO
      IF (av.gt.0..and.law_rd.ne.0) THEN
         CALL red_spec(ww,y,av,yob,1,iw(itypem),law_rd)
         DO k=1,iw(itypem)
            y(k)=yob(k)
         END DO
      END IF

      DO i=2,nz_f-1             !Scan in z excluding limits of range
         zz=zmin_f+(i-1)*dz_f
         DO k=1,iw(itypem)
            y1(k)=y(k)
         END DO
         CALL lyman_forest(ww,y1,iw(itypem),zz)
         dif(i)=0.0
         sxx=0.
         sxy=0.
         b=0.
         DO k=1,n_filter
            fluz(k)=filter(nfil(k),ww,y1,iw(itypem),zz)/surf(k)
         END DO

         DO k=1,n_filter
            IF (fl(k).ge.0.) THEN ! no oof objects
               IF (fluz(k).eq.0..and.i_lyman(k).eq.1) THEN
                  fl2(k)=0.
               ELSE
                  fl2(k)=fl(k)
                  wt=1./(err_fl(k)**2)
                  sxx=sxx+(fluz(k)**2)*wt
                  sxy=sxy+fluz(k)*fl2(k)*wt
               END IF
            ELSE
               fl2(k)=-1.
            END IF
         END DO
         b=sxy/sxx
         DO k=1,n_filter
            IF (fl2(k).ge.0.) THEN ! no oof objects
               dif(i)=dif(i)+((fl2(k)-b*fluz(k))/err_fl(k))**2
            END IF
         END DO

         IF (dif(i).lt.chi2) THEN
            chi2=dif(i)
            i_min=i
            bm=b
         END IF
      END DO

      zop=zmin_f+(i_min-1)*dz_f

      RETURN
      END


