	program ped_dark1

	include		'openfile.h'

	parameter	(nXX=1272)
	parameter	(nYY= 256)
	integer		iframe(nXX,nYY)

	character	cSearch*256
	character	cFile*256
	character	cName*21

	logical		bOK
	logical		bReadNic
	character	cInfo*256

	integer		iPedCol(8)	/13,14,15,16, 1269,1270,1271,1272/
	integer		iDrkCol(8)	/17,18,19,20, 1265,1266,1267,1268/

	i = 1
	call ForeignInput(' ',i,cSearch)
	if (i .eq. 0) stop 'no source directory'

	i = iFilePath(cSearch,0,'','*.*',cSearch)
	iFile1 = i-2
	iFile2 = iFile1+20

	kcr	= -1
	badsum  = 0.0
	kbase   = 10
	pedgood = -1.0
	drkgood = -1.0
	nbad    = 0

	npedtot = 0
	ndrktot = 0
	fpedtot = 0
	fdrktot = 0

	k = 0
		
	newsearch = 2
	do while (iSearch(newsearch,cSearch,cFile) .eq. 1)
	    newsearch = 0

	    if (k .eq. kbase .and. pedgood .lt. 0) stop 'bad pedlast'

	    bOK = bReadNic(OPN__REOPEN+OPN__NOMESSAGE+OPN__STOP, cFile, nXX*nYY, nX, nY, iframe, cInfo)

	    k = k+1

	    pedcnt = 0.0
	    ped = 0.0

	    do i=1,8		! Loop over ped columns
		ii = iPedCol(i)

		do j=1,nY	! Loop over all 256 rows

		    arg = iframe(ii,j)

		    if (arg .ne. 0) then
			if (k .le. kbase .or. abs(arg-pedgood) .lt. 10.0) then
			    ped    = ped   +arg
			    pedcnt = pedcnt+1.0
			end if
		    end if

		end do

	    end do

	    ped = ped/pedcnt

	    drkcnt = 0.0
	    drk = 0.0

	    do i=1,8		! Loop over drk columns
		ii = iDrkCol(i)

		do j=1,nY	! Loop over all 256 rows

		    arg = iframe(ii,j)

		    if (arg .ne. 0) then
			if (k .le. kbase .or. abs(arg-(pedgood+drkgood)) .lt. 10.0) then
			    drk    = drk   +arg
			    drkcnt = drkcnt+1.0
			end if
		    end if

		end do

	    end do

	    drk = drk/drkcnt-ped

	    drk = drk-0.0018*(1965.0-drkcnt)		!ad hoc dark current adjustment

	    cName = cFile(iFile1:iFile2)

	    if (k .le. kbase) then

		do j=1,nY
		    do i=1,8
			arg = iframe(iDrkCol(i),j)-(drk+ped)
			if (arg .gt. 200.0) then
			    if (k .ne. kcr) write (*,'(2A,2I5,F9.2)') cName,' CR in first ',kbase,k,arg
			    kcr = k
			else if (arg .gt. 10.0) then
			    badsum = badsum+arg
			end if
	    	    end do
		end do

		if (k .eq. kbase) then
		    badsum = badsum/20480.0
	   	    write (*,*) 'badsum = ',badsum
	        end if

	    end if

	    if (pedcnt .lt. 1850) then
		nbad = nbad+1
		write (*,'(2A,2I5,F8.2,F6.2)') cName,' Low count ped ',nint(pedcnt),nint(drkcnt),ped,drk
	    else if (drkcnt .lt. 1000) then
		nbad = nbad+1
		write (*,'(2A,2I5,F8.2,F6.2)') cName,' Low count drk ',nint(pedcnt),nint(drkcnt),ped,drk
	    else if (drk .le. 1.17) then
		nbad = nbad+1
		write (*,'(2A,2I5,F8.2,F6.2)') cName,' Low value drk ',nint(pedcnt),nint(drkcnt),ped,drk
	    else
		pedgood = ped
		drkgood = drk
		npedtot = npedtot+1
		ndrktot = ndrktot+1
		fpedtot = fpedtot+ped
		fdrktot = fdrktot+drk
	    end if

	end do

	print *, 'average pedestal: ', fpedtot/npedtot
	print *, 'average dark current: ', fdrktot/ndrktot
	write (*,*) 'done, discarded', nbad, '/', k

	end
