#!/bin/csh -f
# Automatically find stars
if ( $#argv < 2 ) then
  caterr <<'EOF'
  Automatically find bright stars from their first moment radius.
    usage: findstars Nmin sigma <catalog >catalog
    Arguments: Nmin - minimum number of stars to be found
               sigma - maximum (sigma ir1)/<ir1> for stars
    Input: catalog of source objects
    Output: catalog of stars
    Diagnostics: The running statistics of the search are printed on
		 the standard error output.
'EOF'
  exit
endif

set a=findstars1.tmp
set b=findstars2.tmp
set cat=findstars3.tmp
set sa=-1
set sb=3
@ m = 10 * $1

ffilter F E G BPD > $cat
#<$cat catlist prob ir1 o|fltstrm r 10 1000000 c c|skip s1 0 1 >$a
<$cat catlist prob ir1 o|sort -rn|head -$m |skip s1 0 1 >$a
set stat = \
  (`<$a skip 1| statstrm f c a s|opstrm c f6.2f r = r = i / = $2 / .5 - f8.0f =`)
while ( $stat[1] > $1  )
	set n = $stat[1]
	echoerr Objects = $stat[1] \<ir1\> = $stat[2] sigma = $stat[3] sigma/\<ir1\> = $stat[4]
	<$a opstrm $stat[2] r = c - $stat[3] / = |\
	fltstrm c c r $sa $sb |skip 0 1 >$b
	mv $b $a
	set stat = \
	  (`<$a skip 1| statstrm f c a s|opstrm c f6.2f r = r = i / = $2 / .5 - f8.0f =`)
	if ( $stat[1] == $n ) break
	if ( $stat[5] < 1 ) break
end
echoerr Final statistics:
echoerr Objects = $stat[1] \<ir1\> = $stat[2] sigma = $stat[3] sigma/\<ir1\> = $stat[4]
<$a skip s1 1|select $cat
rm $a $cat
