#! /bin/csh -f
#------------------------------------------------------
#This is a csh script for maesuring of listed images
#------------------------------------------------------
#
#       Created by Masami Ouchi
#               April 23, 2002
#
#------------------------------------------------------

#
# necessary files & programs
#
# fwhmpsf_batch.lis : list of images to be measured
# /usr/bin/gawk : GNU awk
# fwhmpsf.csh : program for measuring FWHM(PSF) for an image
#

#parameters

#aquire names of the list and parameters

if ( $#argv != 6 ) then
    echo "Usage:" $0 " [fwhmpsf_batch.lis] [max number of objects(50)] [min peak flux(2000)] [max peak flux(45000)] [min FWHM(2.3)] [max FWHM(6.5)]" 
    echo "Example:"
    echo "fwhmpsf_batch.csh fwhmpsf_batch.lis 50 2000 45000 2.3 6.5"
    exit 1
endif

if ( !(-r $1) ) then
    echo "fwhmpsf_batch.csh: Cannot open "$1": No such file or directory"
    exit 1
endif

set fwhmpsf_batchlist = $1
set MF_number_of_obj = $2
set MF_min_flux = $3
set MF_max_flux = $4
set MF_min_fwhm = $5
set MF_max_fwhm = $6

set SDFREDSH = /data1/Data/SUBARU/SDFRED2/sdfredSH
set AWK = /usr/bin/gawk

rm tmp_fwhmpsf_batch1

# version 1.2 

## foreach image (`cat $fwhmpsf_batchlist`)
set list = $fwhmpsf_batchlist
set nmax = `wc -l $list | awk '{print $1}'`
@ n = 1
while ( $n <= $nmax )
set image = `sed -n "$n"p $list`

    #echo fwhmpsf.csh ${image} ${MF_number_of_obj} ${MF_min_flux} ${MF_max_flux} ${MF_min_fwhm} ${MF_max_fwhm}
    fwhmpsf.csh ${image} ${MF_number_of_obj} ${MF_min_flux} ${MF_max_flux} ${MF_min_fwhm} ${MF_max_fwhm} >> tmp_fwhmpsf_batch1

# version 1.2 (I dislike csh...YAGI)
@ n ++
end

echo ""
echo ""
echo "### results ###"
echo ""

cat tmp_fwhmpsf_batch1

echo "###"

#make a histogram
$AWK '$2!="" {print $2}' tmp_fwhmpsf_batch1 >  tmp_fwhmpsf_batch2
set hist_min = `sort -n tmp_fwhmpsf_batch2 | head -1`
set hist_max = `sort -n tmp_fwhmpsf_batch2 | tail -1`
mkhist tmp_fwhmpsf_batch2 ${hist_min} ${hist_max} 0.1 | $AWK '{printf("%.1f %s\n",$1,$2)}' > tmp_fwhmpsf_batch3

echo ""
echo "PSF | number of images"
foreach psf (`$AWK '{print $1}' tmp_fwhmpsf_batch3`)
    echo -n ${psf}" |"
    set num = `$AWK '$1=='${psf}' {print $2}' tmp_fwhmpsf_batch3`
    set i = 0
    while (`echo ${i} ${num} | $AWK '{if ($1<$2) {print 1} else {print 0}}'`)
	echo -n "*"
	set i = `echo ${i} | $AWK '{print $1+1}'`
    end

    echo ""

end

echo ""
