	program phil2select
C      written by p. massey, Lowell Observatory, March 2002
C
C Assumes that you've dumped the id, xc, yc, mag, and merr
C from *mag.1 with selection criteria = "yes"
C into temp:
C
	parameter(maxstar=200000)
	character*80 inline(maxstar),inline2,inline1
	open(unit=1,file="temppsf",status="old")
        open(unit=2,file="pospst",status="new")
	idebug=0
	i=0
C Get another potential PSF star
1	read(1,2,end=1001) inline1
	i=i+1
	if(i.gt.maxstar) stop 'TOO MANY STARS!'
2	format(a80)
	inline(i)=inline1
	go to 1
1001	inum=i
	close(unit=1)
	write(6,1002) inum
1002	format('Read in',i7,' stars for PSF selection')
3000	continue
	iz=0
	do 1000 i=1,inum
	inline1=inline(i)
 	read(inline1,*,err=1000) id,xc,yc,amag,amerr
	if(amerr.gt..02) go to 1000
	debug=0
C change this if you want to see what's going on...
	if(id.eq.-1) debug=1
	if(debug.eq.1) write(6,1003) id,xc,yc,amag,amerr
1003	format('Potential PSF star:' i5,4f10.2)
C OK, now see if this star has something nearby
	do 500 j=1,inum
	if(j.eq.i) go to 500
	inline2=inline(j)
C see if the x and y are close
	read(inline2,*) id2,xc2,yc2
	dist2=(xc-xc2)**2+(yc-yc2)**2
34	format('Distance=',5f12.0)
	if(dist2.gt.(11+11)**2) go to 500
	if(debug.eq.1) write(6,35) dist2,id2,xc2,yc2
35	format('It is closeby:',f8.2,i5,2f6.2)
C OK, it's nearby.  Now what?
	read(inline2,*,err=1000) id2,xc2,yc2,amag2,amerr2
C If we are here, then amag2 is not indef.
C How much fainter is amag2?
	dif=amag-amag2
C      -10=  15 -  25
C       -5=  15 -  20
C        0=  15 -  15
C        5=  15 -  10
C      
	if(debug.eq.1) write(6,80) id2,dist2,xc2,yc2,amag2,amerr2,dif
80	format('This star is closeby:',i5,6f12.2)
	if(dif.lt.-4) go to 500
	if((dist2.gt.(11+2)**2).and.(dif.lt.-2.5)) go to 500
	if((dist2.gt.(11+5)**2).and.(dif.lt.-1.5)) go to 500
	if((dist2.gt.(11+7)**2).and.(dif.lt.-0.5)) go to 500
	if((dist2.gt.(11+9)**2).and.(dif.lt.0.0)) go to 500
	if(debug.eq.1) write(6,37)
37	format('WE HAVE REJECTED THIS POOR STAR!')
	go to 1000
500	continue
88      write(2,89) id,xc,yc,amag,amerr
Cwrite(6,87) id,xc,yc,amag,amerr
	iz=iz+1
87	format('We have a winner:' i5,4f10.3)
89	format(i5,4f10.3)
1000	continue
	write(6,2001) iz
2001	format('We found potentially',i5,' PSF stars')
	close(unit=2)
	stop
	end
