#!/usr/bin/perl

# Routine to reformat the Stardust index file to a proper format


$srcfile = "../index/index.tab";
$newfile = "../index/index_new.tab";

  # read the original index file and write it out to the new file with proper format

open(INDEX,$srcfile) || die "Could not open source file";
open(INDOUT,">$newfile") ;

printf INDOUT "1                                2                 3        ";
printf INDOUT "                      4                   5          6     ";
printf INDOUT "              7                      8    9       10    11 ";
printf INDOUT "                     12                      13       14   ";
printf INDOUT "       15       16       17      18         \r\n"; 

printf INDOUT "================================ ================ ==========";
printf INDOUT "===================== =================== ========== ======";
printf INDOUT "============= ====================== ==== ======= ===== ===";
printf INDOUT "==================== ======================= ======== =====";
printf INDOUT "====== ======== ======== ======= ========== \r\n"; 

$not_done = 1;
while (($line=<INDEX>) && $not_done)
  {#print $line;
   $spec = substr($line,0,30) ;
   $file = substr($line,36,14) ;
   $dsid = substr($line,52,30) ;
   $creat = substr($line,83,19) ;
   $host = substr($line,103,8) ;
   $inst = substr($line,112,17) ;
   $targ = substr($line,130,20) ;
   $frmnm = substr($line,151,4) ;
   $filt = substr($line,157,5) ;
   $cwv = substr($line,164,5) ;
   $start = substr($line,170,23) ;
   $stop = substr($line,194,23) ;
   $exp = substr($line,218,16) ;
     if ($exp =~ /\s*(.*)</) {$exp=$1;}
   $cat = substr($line,235,20) ;
     if ($cat =~ /\s*(.*)/) {$cat=$1;}
   $ra = substr($line,256,15) ;
     if ($ra =~ /\s*(.*)/) {$ra=$1;}
   $dec = substr($line,272,15) ;
     if ($dec =~ /\s*(.*)/) {$dec=$1;}
   $phase = substr($line,288,13) ;
     if ($phase =~ /N\/A/) {$phase=-9.999;}
   $delta = substr($line,302,20) ;
     if ($delta =~ /N\/A/) {$delta=-9999999.9;}

# write the index data to the new file

   printf INDOUT "\"%-30.30s\" \"%-14.14s\" \"%-29.29s\" ", $spec,$file,$dsid ;
   printf INDOUT "%-19.19s \"%-8.8s\" \"%-17.17s\" ", $creat,$host,$inst ;
   printf INDOUT "\"%-20.20s\" %4.4s \"%-5.5s\" %5.5s ",$targ,$frmnm,$filt,$cwv ;
   printf INDOUT "%-23.23s %-23.23s %8.2f %11.6f ",$start,$stop,$exp,$cat ;
   printf INDOUT "%8.4f %8.4f %7.3f %10.1f \r\n",$ra,$dec,$phase,$delta ;

  } 

close (INDEX);
close (INDOUT);

#=============================================================================