#!/usr/bin/perl
#
# Calculate a blackbody spectrum and print out intensity as
#   as a function of wavelength.  Include log(lambda) and log(Intensity),
#   too.
#
# usage:  bb.pl  temp
#
# where "temp" is temperature in Kelvin
# 
# MWR 7/23/2003
#
# fixed error in computation of the "bot" piece -- was missing "-1".
# MWR 12/9/2003
#
# Add a piece to integrate flux over some range of wavelengths.
#
# MWR 2/27/2015

use POSIX;

$debug = 0;

$MYPI = 3.1415926;

$temp = $ARGV[0];

$dlog_lambda = -0.0001;

$filter = "none";
if ($filter eq "J") {
  $central_lambda = 1.26E-6;
  $width_lambda = 0.16E-6;
}
if ($filter eq "H") {
  $central_lambda = 1.60E-6;
  $width_lambda = 0.23E-6;
}
if ($filter eq "K") {
  $central_lambda = 2.15E-6;
  $width_lambda = 0.26E-6;
}
if ($filter eq "L") {
  $central_lambda = 3.80E-6;
  $width_lambda = 0.35E-6;
}
if ($filter eq "M") {
  $central_lambda = 4.70E-6;
  $width_lambda = 0.30E-6;
}
if ($filter ne "none") {
  $start_lambda = $central_lambda + 0.5*$width_lambda;
  $end_lambda = $central_lambda - 0.5*$width_lambda;
  $dlog_lambda = -0.0001;
}
else {
  $start_lambda = 1e1;
  $end_lambda = 1e-12;
  $dlog_lambda = -0.001;
}

$sum_energy = 0.0;

$h = 6.626e-34;
$c = 3.0e8;
$k = 1.38e-23;
# this should be 2*h*c^2
$const = 2.0*$h*$c*$c;
$exponent_const = ($h*$c)/($k*$temp);


$log_start = log10($start_lambda);
$log_end = log10($end_lambda);
if ($debug > 0) {
  printf " log_start %10.4f   log_end %10.4f \n", $log_start, $log_end;
}
for ($logl = $log_start; $logl > $log_end; $logl += $dlog_lambda) {

  $lambda = pow(10.0, $logl);

  $top = $const/(pow($lambda, 5.0));
  $exponent = $exponent_const/$lambda;
  if ($debug > 0) {
    printf "lambda %10.4e  exponent %9.4e  top %9.4e  bot %9.4e \n", 
            $lambda, $exponent, $top, $bot;
  }
  if ($exponent < 100) {
    $bot = exp($exponent) - 1;
    $blam = $top/$bot;
  }
  else {
    $blam = 1e-90;
  }


  $logblam = log10($blam);

  $nu = $h*$c/$lambda;
  $lognu = log10($nu);

  # add up the energy in this little piece
  $next_lambda = pow(10.0, ($logl + $dlog_lambda));
  $d_lambda = $lambda - $next_lambda;
  $energy = $MYPI*$blam*$d_lambda;
  $sum_energy += $energy;

  printf "%9.4e %9.4e %9.4e %9.4e %9.4e   %9.4e %9.4e  %10.5e \n", $logl, $lambda, $blam, $logblam, 
                  $nu, $lognu, $energy, $sum_energy;
}

exit 0;

