#!/usr/bin/perl

@gov = split (/\//,$0); pop @gov; $BINDIR = join ('/',@gov);
# Read common PERL subs
require "$BINDIR/perlutil.pl";
&ini_vars;
$getpar   = "$BINDIR/getpar";
@PARS = &fixpars (@ARGV); # this is needed to escape arguments with parens etc

%calname=(); %caldir=(); %sortcti=();

############################# SETUP #########################################
# QEU:
$calname{"qeu"}="qeu_Mn_bg_";
$caldir{"qeu"}='$CH/CAL';
$sortcti{"qeu"}=1;
$calformat{"qeu"}=".fits";
$calkeyword{"qeu"}="qeuMn";

#############################################################################

$caltype = $ARGV[0];

if (! defined $calname{$caltype}) {
  die "ERROR: Wrong cal type: $caltype; allowed types: ",join(",",sort keys %calname), "\n";
}

# get the event file name
chop ($evtfile = `$getpar evtfile @PARS`);

# determine, if the cal dataset is CTI-dependent, whether the evt file was CTI-corrected
$ctiaff="";
if ($sortcti{$caltype}) {
  chop($cticorr = `printkey $evtfile'[events]' CTI_CORR`);
  if ($cticorr eq "T") {
    $ctiaff=".cti";
  }
}

# determine the observation date
($info1,$info2) = `printkey $evtfile\[events\] date-obs,date-end`;
chop $info1; chop $info2;
($date_start) = split (' ',$info1); $date_start =~ s/T.*//;
($date_end) = split (' ',$info2); $date_end =~ s/T.*//;
$mjd_start = &sla_cldj (split('-',$date_start));
$mjd_end   = &sla_cldj (split('-',$date_end));
($yy,$mm,$dd) = &sla_djcl(0.5*($mjd_start+$mjd_end));
$mm=sprintf("%2.2d",$mm);$dd=sprintf("%2.2d",$dd);
$dateobs = join('-',$yy,$mm,$dd);

# get the list of file names
$command = "ls $caldir{$caltype} | grep $calname{$caltype} | grep $ctiaff$calformat{$caltype} | sort -r | uniq";

open ( CALLIST , "$command |") || die "Cannot run $command\n";
while (<CALLIST>) {
  chomp;
  $filename = $_;
  $filename =~ /(\d\d\d\d-\d\d-\d\d)/;
  $datecal = $1;
  if ($dateobs ge $datecal) {
    last;
  }
}
close (CALLIST);
print "$calkeyword{$caltype}=$caldir{$caltype}/$filename","\n";

exit(0);

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

############################################################################
sub sla_mod {
 my ($x,$y) = @_;
 return $x-int($x/$y)*$y;
}
sub sla_nint {
  my $x = $_[0];
  my $n = int($x);
  if ( $x > 0 ) {
    if ( $x-$n > 0.5) {
      return $n+1;
    }
    else {
      return $n;
    }
  }
  else {
    if ( $n-$x > 0.5) {
      return $n-1;
    }
    else {
      return $n;
    }
  }
}
sub sla_cldj {
  my ($IY, $IM, $ID) = @_;
  my ($DJM);

  my @MTAB = (0,31,28,31,30,31,30,31,31,30,31,30,31);

  if ($IY<-4699) {
    return -1e10;
  }

# Validate month
  if ($IM>=1&&$IM<=12) {
#     Allow for leap year
    if (sla_mod($IY,4)==0) {
      $MTAB[2]=29;
    } else {
      $MTAB[2]=28;
    }
    if (sla_mod($IY,100)==0&&sla_mod($IY,400)!=0) {
      $MTAB[2]=28;
    }

#   Validate day
    if ($ID<1||ID>$MTAB[$IM]) {
      return -3e10;
    }

    use integer;
    #   Modified Julian Date
    $DJM = (1461*($IY-(12-$IM)/10+4712))/4
      +(306*sla_mod($IM+9,12)+5)/10
	-(3*(($IY-(12-$IM)/10+4900)/100))/4
	  +$ID-2399904;
    return $DJM
  } else {
    return -2e10;
  }
}

sub sla_djcl {
  my ($DJM) = @_;
  my ($IY, $IM, $ID, $FD);
  my ($F,$D,$N4,$ND10);
  if ($DJM<=-2395522||$DJM>=1e9) {
    return (-1e10,-1,-1,-1);
  }

  #  Separate day and fraction
  $F=sla_mod(DJM,1.0);
  if ($F<0.0) { $F+=1.0;}
  $D=sla_nint($DJM-$F);

  #  Express day in Gregorian calendar
  $JD=sla_nint($D)+2400001;

  use integer;
  $N4=4*($JD+((6*((4*$JD-17918)/146097))/4+1)/2-37);
  $ND10=10*(sla_mod($N4-237,1461)/4)+5;
  $IY=$N4/1461-4712;
  $IM=sla_mod($ND10/306+2,12)+1;
  $ID=sla_mod($ND10,306)/10+1;
  $FD=$F;
  return ($IY, $IM, $ID, $FD);
}
