#!/usr/bin/perl
#-------------------------------------------------------------------------------
#Purpose     : generate repair.csh script
#Author      : Robert Greimel (rgreimel@mail.com)
#Last Change : 21-Feb-2000
#-------------------------------------------------------------------------------
use Scripts;

@oheader=("RA      ","DEC     ","EPOCH   ","SIDEREAL","HA      ","DATE-OBS","EXPTIME ","OBSTYPE ");
$epoch='""';
$type='';
$ut="00:00:00";
$ra="00:00:00.00";
$sidereal="00:00:00";

##
# make sure directory ends with a "/"
##
$dir = $ARGV[0];
if ($dir !~ m|/$|) {$dir = $dir."/"};

##########
#read generation options
##########
%filenames=();
print "$0: reading filename configuration ... ";
&Scripts::read_filenames(\%filenames,"config.names");
print "done\n";

%options=();
print "$0: reading default options ... ";
( &Scripts::read_options(\%options,$filenames{"default_options"}) ) ? print "successful\n" : print "failed\n" ;

print "$0: reading directory specific options ... ";
( &Scripts::read_options(\%options,$dir.$filenames{"custom_options"}) ) ? print "successful\n" : print "failed\n" ;

if ($options{"directory"} eq "yes")
  {
  print "directory option is on\n";
  $dir_inout=$filenames{"dir_inout"}."/";
  }
else
  {
  print "directory option is off\n";
  $dir_inout="";
  }

#####
# additional header information
#####
if ( -e $dir."add.info" )
  {
  open INFO,$dir."add.info";
  while (<INFO>)
    {
    split;
    if (/^INSTRUME/){$instrument=$_[1];}
    if (/^EPOCH/){$epoch=$_[2];}
    }
  close INFO;
  }

#####
# read information about stars
#####
open STARS,"stars.coo";
while (<STARS>)
  {
  split;
  $star_ra{$_[0]}=$_[1];
  $star_dec{$_[0]}=$_[2];
  }
close STARS;
if ( -e $dir."addstars.coo" )
  {
  open STARS,$dir."addstars.coo";
  while (<STARS>)
    {
    split;
    $star_ra{$_[0]}=$_[1];
    $star_dec{$_[0]}=$_[2];
    }
  close STARS;
  }

#####
# get telescope from collected header information
#####
open HEADER,$dir.$filenames{"header_info"};
#$fname = (split m/\//,<HEADER>)[-1];
$_=<HEADER>;
($tel,$year)= ($_ =~ /.*c([0-9]+)_([0-9]+).[0-9]+.*/);
close HEADER;

#####
# open output file
#####
open REPAIR,">".$dir.$filenames{"repair_script"};

# write first part of repair file
&write_fh;

#####
# read collected header information
#####
open HEADER,$dir.$filenames{"header_info"};
open TYPE,$dir.$filenames{"type_file"};
while (<HEADER>)
  {
  if ( /^END$/ )
    {
    # check the header information and write missing bits to repair script
    &check_header;
    @header=@oheader;
    $siderealo=$sidereal;$sidereal='';
    $uto=$ut;$ut='';
    $deco=$dec;$dec='';
    $typeo=$type;
    next;
    }
  if ( ! /^.*=/ )
    {
    @frameinfo=split ' ',<TYPE>;
    $type=$frameinfo[2];
    $star_name=$frameinfo[-1];
    if ( $type eq "unknown" ) {$type='';}
    if ( $type eq "arc" ) {$type='comparison';}
    $file=$_;
    chomp $file;
    next;
    }
  for ($i=0;$i<=$#header;$i++)
    {
    splice @header,$i,1 if (/^$header[$i]/);
    }
  if ( /^EPOCH   / ) {$epoch=(split)[2];}
  if ( /^RA      / ) {$ra=(split)[2];}
  if ( /^DEC     / ) {$dec=(split)[2];}
  if ( /^SIDEREAL/ ) {$sidereal=(split)[1];}
  if ( /^DATE-OBS/ ) {$ut=(split)[2];}
  if ( /^INSTRUME/ ) {$instrument=(split)[1];}
  }
close HEADER;
close TYPE;

# write repair script trailer
print REPAIR "if ( -e ".$filenames{"header_info"}." ) then\n";
print REPAIR '  \rm '.$filenames{"header_info"}."\n";
print REPAIR "endif\n";
print REPAIR "if ( -e ".$filenames{"type_file"}." ) then\n";
print REPAIR '  \rm '.$filenames{"type_file"}."\n";
print REPAIR "endif\n";

# done
print REPAIR "echo done\n";
close REPAIR;

################################################################################
#                       S U B R O U T I N E S
################################################################################
sub check_header()
  {
  if ($#header >= 0)
    {
    print REPAIR "sethead $file";
    for ($i=0;$i<=$#header;$i++)
      {
      $header[$i]=~s/ *$//;
      print REPAIR " ",$header[$i],"=";
      if ( $header[$i]=~/EPOCH/ )
        {print REPAIR $epoch;}
      elsif ( $header[$i]=~/OBSTYPE/ )
        {print REPAIR '"',$type,'"';}
      elsif ( $header[$i]=~/SIDEREAL/ )
        {
        if ($ut eq "")
          {print REPAIR '""';}
        else
          {$sidereal = &time_calc($ut,$uto,$siderealo);}
        }
      elsif ( $header[$i]=~/UT/ )
        {
        if ($sidereal eq "")
          {print REPAIR '""';}
        else
          {$ut = &time_calc($sidereal,$siderealo,$uto);}
        }
      elsif ( $header[$i]=~/HA/ )
        {
        @a=split ":",$ra;
        $ras=$a[0]*3600+$a[1]*60+$a[2];
        @a=split ":",$sidereal;
        $sid=$a[0]*3600+$a[1]*60+$a[2];
        $has=$sid-$ras+12*60*60;
        if ($has > 24*60*60 ) {$has-=24*60*60;}
        $has-=12*60*60;
        print REPAIR '"';
        if ( $has < 0 ) {print REPAIR "-";$has=-$has;}
        else {print REPAIR "+";}
        $a=int($has/3600);$has-=$a*3600;$str=sprintf "%2d",$a;$str=~s/ /0/g;
        print REPAIR $str,":";
        $a=int($has/60);$has-=$a*60;$str=sprintf "%2d",$a;$str=~s/ /0/g;
        print REPAIR $str,":";
        $a=$has;$str=sprintf "%5.2f",$a;$str=~s/ /0/g;
        print REPAIR $str,'"';
        }
      elsif ( $header[$i]=~/RA/ )
        {
        if ( $type eq "object" )
          {print REPAIR '"'.$star_ra{$star_name}.'"';}
        else
          {print REPAIR '"00:00:00.00"';}
        }
      elsif ( $header[$i]=~/DEC/ )
        {
        if ( $type eq "object" )
          {print REPAIR '"'.$star_dec{$star_name}.'"';}
        elsif ( $typeo ne "object" && $deco ne '' )
          {print REPAIR '"'.$deco.'"';}
        else
          {print REPAIR '"+00:00:00.0"';}
        }
      else
        {print REPAIR '""';}
      }
    print REPAIR "\n";
    }
  }

sub time_calc()
  {
  my ($ta,$tao,$tbo)=@_;

  @a=split ":",$tao;
  $taos=$a[0]*3600+$a[1]*60+$a[2];
  @a=split ":",$ta;
  $tas=$a[0]*3600+$a[1]*60+$a[2];
  $dta=$tas-$taos;
  if ( $dta < 0 ) {$dta+=24*60*60;}
  @a=split ":",$tbo;
  $tb=$a[0]*3600+$a[1]*60+$a[2]+$dta;
  if ($tb > 24*60*60) {$tb-=24*60*60;}
  print REPAIR '"';
  $a=int($tb/3600);$tb-=$a*3600;$str=sprintf "%2d",$a;$str=~s/ /0/g;
  print REPAIR $str,":";$tbstr=$str.":";
  $a=int($tb/60);$tb-=$a*60;$str=sprintf "%2d",$a;$str=~s/ /0/g;
  print REPAIR $str,":";$tbstr=$tbstr.$str.":";
  $a=$tb;$str=sprintf "%5.2f",$a;$str=~s/ /0/g;
  print REPAIR $str,'"';$tbstr=$tbstr.$str;
  return($tbstr);
  }

sub write_fh()
  {
  print REPAIR '#!/bin/csh',"\n";
  print REPAIR '#',"\n";
  print REPAIR '# make sure all files are writeable',"\n";
  print REPAIR '#',"\n";
  print REPAIR 'echo -n "making data files writable ..."',"\n";
  print REPAIR 'chmod u+w rawdat/c',$tel,'*',"\n";
  print REPAIR 'echo "done"',"\n";
  print REPAIR '',"\n";
  print REPAIR '#',"\n";
  print REPAIR '# add general headers needed by all files',"\n";
  print REPAIR '# what are the header parameters used for -',"\n";
  print REPAIR '#  BIASSEC .... ccdred',"\n";
  print REPAIR '#  DATASEC .... ccdred',"\n";
  print REPAIR '#  TRIMSEC .... ccdred',"\n";
  print REPAIR '#  BPM ........ IRAF v2.11, bad pixel mask',"\n";
  print REPAIR '#  GAIN ....... photometry, CCD gain [e- / ADU ]',"\n";
  print REPAIR '#  RDNOISE .... photometry, CCD read out noise [e-]',"\n";
  print REPAIR '#',"\n";
  print REPAIR '#foreach i (rawdat/c',$tel,'*)',"\n";
  print REPAIR '#  sethead -w $i BIASSEC="[513:520,1:512]" DATASEC="[1:512,1:512]" TRIMSEC="[1:512,1:512]" BPM=\'rg_ccddb$dao/SITe5.imh\' GAIN=3.297 RDNOISE=12.716',"\n";
  print REPAIR '#end',"\n";
  print REPAIR '#',"\n";
  print REPAIR '# repair individual files',"\n";
  print REPAIR '#',"\n";
  print REPAIR 'echo -n "repairing individual files ..."',"\n";
  }
