#!/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;

$MYPI = 3.1415926;

$temp = $ARGV[0];

$start_lambda = 1e10;
$end_lambda = 1e-18;
$dlog_lambda = -0.001;

$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;
}
else {
  $start_lambda = 1e10;
  $end_lambda = 1e-18;
}
$dlog_lambda = -0.0001;

$start_lambda = 0.299;
$end_lambda = 0.272;


$sum_flux = 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);
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 ($exponent < 100) {
    $bot = exp($exponent) - 1;
    $blam = $top/$bot;
  }
  else {
    $blam = 1e-90;
  }
  # printf "exponent %9.4e  bot %9.4e \n", $exponent, $bot;


  $logblam = log10($blam);

  $nu = $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  %10.5e \n", $logl, $lambda, $blam, $logblam, 
                  $nu, $lognu, $sum_energy;
}

exit 0;

