#!/usr/local/bin/perl -I/home/gwyn/perlib
#### awk alert! ####
$,=" ";
$\="\n";
#### awk alert! ####

use Gwynlib;

@style= ('c10','c07','c20');
@sigval=('1.0','0.7','2.0');

for $it (1..1) {  # begin the big loop over style
$style=$style[$it];
$sigval=$sigval[$it];

open TEST,'chisq.sex';
open TESTQ,'>testq.sex';
while (<TEST>) {
  chomp;
  @a=split;
  if ($a[0] =~ /DETECT_THRESH|ANALYSIS_THRESH/ ) {
    $a[1]=$sigval;
    $_=join "\t",@a[0..1];
    }  
  print TESTQ;
  }
close TEST;
close TESTQ;

system "addgal4 0 23 1 4";
system "sex tdc.fits    ti.fits -c testq.sex -MAG_ZEROPOINT 29.81 -CATALOG_NAME    ti$style.cat -PARAMETERS_NAME comp.param"; 
system "addgal4 0  0 1 4";
system "sex tdc.fits negti.fits -c testq.sex -MAG_ZEROPOINT 29.81 -CATALOG_NAME negti$style.cat -PARAMETERS_NAME comp.param";

$realrun=1;
if ($realrun) { ###### do a real run

system "rm comp.log ";

$zp=29.81; $scale=0.205; $pi=3.141593;
$magt=27;
$mpeakt=25;

$domax=20;        # number of times at each spot
for (1..$domax) { # iterate per spot
for $imagt (0..14 )  {$magt  =.5*$imagt  + 22;
for $impeakt (0..8) {$mpeakt=.5*$impeakt + 22;

$seed=-(time % 10000 );

$command="addgal4 $magt $mpeakt $seed > fred$$ ";
system $command;

open FRED,"fred$$";
while (<FRED>) {($mag,$mpeak)=split;}
close FRED;

system "sex tdc.fits tdi.fits -c testq.sex -MAG_ZEROPOINT 29.81 -CATALOG_NAME tdi.cat -PARAMETERS_NAME comp.param ";

print $command;
print $mag,$mpeak;


$FOUND="tdi.cat" ; open FOUND;
@x=@y=(); $id=0; $infound=0;
while (<FOUND>) {
  next if /#/;
  ($id,$x,$y,$magq,$narea,)=split;
  next unless ($narea>1);
  next unless ($magq<30);
  $infound++;
  $m{$id}{x}=$x;
  $m{$id}{y}=$y;
  #print $x,$y;
  }
close FOUND;
$numput=0;
$numgot=0;

$INPUT='fort.21'; open INPUT;

while (<INPUT>) {$numput++;
  ($x,$y)=split;  
  $rmin=1e10;
  $idmin=0;
  for $id (keys %m) {
    $dx=$x-$m{$id}{x};
    $dy=$y-$m{$id}{y};
    $r=sqrt($dx*$dx+$dy*$dy);
    if ($r<$rmin) { $rmin=$r; $idmin=$id};
    }
  print RLOG $rmin,$magt,$mpeakt,$infound;
    
  if ($rmin<5) {$numgot++;
    delete $m{$idmin};
    }
  }
close INPUT;
print "## $numgot $numput ##";


close INPUT;
print $numgot,$numput;

open LOG,'>>comp.log';
printf LOG "%s ## %8.3f %8.3f %3i %3i\n",$command,$mag,$mpeak,$numgot,$numput;
close LOG; 
}}} # end the simulation iterations

system "compread.pl";
system "text2fort";
system "cp fredc connum$style";
system "cp fort.31 concon$style";
} # end of a real run

} # end of the big loop