#!/usr/bin/env perl -w
#Program to convert Bessell files taken from the internet
#(http://www.mso.anu.edu.au/~bessell/FTP/Spectrophotometry/) to IRAF
#readable files. The trick is to convert the micro-Jy in the Bessell
#file to magnitudes.
#06/04/2005 Created by Eduard Westra

use strict;
use Getopt::Long;
use File::Basename;

my $argc = $#ARGV + 1;

die("Usage: ".basename($0)." [--fnu|-f fnu] [--bandwidth|-b b] inputfile [outputfile]\n")
    unless ($argc >= 1);

my $input  = $ARGV[0];
die($input." does not exist!\n")
    unless (-e $input);

my $output = ($input =~ /(.*)[.]tab$/m ? $1.".dat" : $input.".dat");

my $fnu = 3.68e-20;
my $bandwidth = 50.;

GetOptions('fnu|f=f' => \$fnu,
	   'bandwidth|b=f' => \$bandwidth
	   );

open(IN, $input);
my @data = <IN>;
close(IN);

open(OUT, ">".$output);
$data[0] =~ s/[*]/\#/g;
@data = trim(@data);
splice @data, 0, 7;

foreach my $line (@data) {
    chomp $line;
    my @col = split(' ', $line);
    print OUT $col[0]." ".-2.5 * (log10($col[1]) - 29 - log10($fnu))." ".$bandwidth."\n";
}
close(OUT);


#FUNCTIONS
sub log10($) {
    my $x = shift;
    return log($x)/log(10);
}

sub trim {
    my @out = @_ ? @_ : $_;
    $_ = join(' ', split(' ')) for @out;
    return wantarray ? @out : "@out";
}

