#!/usr/bin/perl
#
#

$BINDIR   = "/data/alexey1/chandra/bin";
$getpar   = "$BINDIR/getpar";

# Read common PERL subs
require "$BINDIR/perlutil.pl";

# Check external packages
&check_ftools; &check_zhtools;


# Initialize internal variables ($UNDEF etc)
&ini_vars;

@PARS = &fixpars (@ARGV); # this is needed to escape arguments with parens etc
chop (
      ($srcspec,$bgspec,$bgnorm,$bgreg,$srcreg,$regwcs) = 
      `$getpar src,bg,bgnorm,bgreg,srcreg,regwcs @PARS`
);

print $bgreg," ",$srcreg," ",$regwcs,"\n";

# Fill in default values;
if ( $srcspec eq $UNDEF )  {  die "please set the source spectrum with -src\n"}
if ( $bgspec eq $UNDEF )  {  die "please set the source spectrum with -bg\n"}
if ( $bgnorm eq $UNDEF )  {  
  if (  ! ( $bgreg ne $UNDEF || $srcreg ne $UNDEF || $regwcs ne $UNDEF ) ) {
    die "please set the background norm. factor with -bgnorm\n"}
  else {
    if ($srcreg eq $UNDEF ) { die "please set the source region with -srcreg\n"}
    if ($bgreg eq $UNDEF )  { die "please set the background region with -bgreg\n"}
    if ($regwcs eq $UNDEF )  { die "please set the region WCS image with -wcsreg\n"}
  }
}

if ( $bgnorm eq $UNDEF ) {
  if ( $bgreg =~ /[\(\s]/ ) { $reg = $bgreg } else {$reg="file:$bgreg"}
  system (mkreg,"refimg=$regwcs","out=/tmp/mask$$","reg=$reg");
  $bgarea = `imexam /tmp/mask$$ sum`;
  if ( $srcreg =~ /[\(\s]/ ) { $reg = $srcreg } else {$reg="file:$srcreg"}
  system (mkreg,"refimg=$regwcs","out=/tmp/mask$$","reg=$reg");
  $srcarea = `imexam /tmp/mask$$ sum`;
  $bgnorm = $srcarea/$bgarea;
  unlink ("/tmp/mask$$");
  print "bgnorm=",$bgnorm,"\n";
}

$tmp = $srcspec."_templ_$$";
open (TMP,"> $tmp") || die "Cannot open $tmp for writing\n";
print TMP "BACKFILE=",$bgspec,"\n";
print TMP "BACKSCAL=",$bgnorm,"\n";
close(TMP);
system ("modifyheader","infile=$srcspec\[SPECTRUM\]","templ=$tmp");
unlink($tmp);


#####################################################################
sub ini_vars {
  $UNDEF = "undefined";
}
