#!/bin/csh
#  determines the cross correlation between target and reference
#  returns DR, DC, MAGDIFF, and MAGERR in the .cand file
# 8/19/94 REF_DIR --> sn/ref

if ($#argv < 1) then
	stderr usage: sn_cormatch target 
	exit 1
endif

set target=$argv[1]
set ref=`picksym data_dir`/sn/ref/`picksym file=$target.fts object`
set ofile=$target.cand

if (-e $target.fts == 0 ) then
	stderr sn_cormatch: $target.fts not found
	exit 1
endif

if (-e $ref.fts == 0 ) then
	stderr sn_cormatch: $ref.fts not found
	exit 1
endif

set TMP=tmp.$$
set TMP2=tmp2.$$

#now we determine the offset and magnitude difference
# by a correlation technique of the column and row spectra
#
box 10 sr=10 nr=490 sc=10 nc=490 >& /dev/null
mash $target  sp=10,500 cols norm box=10 | awk '{print $2}' > $TMP
mash $ref sp=10,500 cols norm box=10 | awk '{print $2}' | \
	paste $TMP - > $TMP2
set cross=`corrcol $TMP2 slope  max `
set auto_ref=`corrcol $TMP2 auto2 slope  max |awk '{print $2}'`
set auto_target=`corrcol $TMP2 auto  slope  max | awk '{print $2}'`
set scale1=`val "sqrt($auto_target/$auto_ref)"`
set scale2=`val "$cross[2]/$auto_ref"`
set dr=$cross[1]
#mv $TMP2 rows

mash $target  sp=10,500 rows norm box=10 | awk '{print $2}' > $TMP
mash $ref sp=10,500 rows norm box=10 | awk '{print $2}' | \
	paste $TMP - > $TMP2
set cross=`corrcol $TMP2 slope  max`
set auto_ref=`corrcol $TMP2 auto2 slope  max | awk '{print $2}'`
set auto_target=`corrcol $TMP2 auto  slope  max | awk '{print $2}'`
set scale3=`val "sqrt($auto_target/$auto_ref)"`
set scale4=`val "$cross[2]/$auto_ref"`
set dc=$cross[1]
set mscale=`echo $scale1 $scale2 $scale3 $scale4 | awk '{printf"%s\n%s\n%s\n%s\n",$1,$2,$3,$4}' | stat`

set magdiff=`val "2.5*log10($mscale[2])"`
putsym file=$ofile dr=$dr dc=$dc magdiff=$magdiff magerr=$mscale[3] 

#mv $TMP2 cols

#see if there are any star that match
subheader $target.coo 	| \
	phot $target aper=8 |  \
	listshift  - dr=$dr dc=$dc > $TMP
subheader $ref.ref | phot $ref aper=8 > $TMP2
findmatch $TMP2 $TMP noshift radius=5 mag  > findmatch.log
if($status == 0) then
	set magdiff2=`awk '{print $4}' findmatch.log | sed s/magdiff=//`
	putsym file=$ofile magdiff2=$magdiff2 nmatch=1
else
	putsym file=$ofile nmatch=0
endif

# compute the exposure time corrected magnitude difference
set exptime=`picksym file=$target.coo exptime`
set reftime=`picksym file=$ref.ref exptime`
set magdiff3=`val "$magdiff - 2.5*log10($exptime/$reftime)"`
putsym file=$ofile magdiff3=$magdiff3 

rm $TMP $TMP2
exit 0
