#!/usr/bin/perl

# wrap-md-html BODY TEMPLATE
#   A simple script to wrap HTML generated by Markdown into a full
#   page.  The HTML is taken from standard input, the wrapper is
#   taken from the command line.  The HTML is inserted in the
#   body in place of *BODY*.
#
#   At some point, I need to add command-line processing.

my $original = readFile($ARGV[0]);
my $template = readFile($ARGV[1]);
my $title = $body;
my ($title,$body) = split /\n/, $original, 2;
$title =~ s/<\/h1>.*//;
$title =~ s/<h1>//;

$template =~ s/\*BODY\*/$body/g;
$template =~ s/\*TITLE\*/$title/g;

print $template;

# +-------------+-----------------------------------------------------
# | Subroutines |
# +-------------+

# Read in the contents of a file.
sub readFile
{
  my $filename = shift;
  open(PORT, "< $filename");
  my $contents = readPort(PORT);
  close(PORT);
  return $contents;
} # readFile

# Read in the contents of a port.
sub readPort
{
  my $PORT = shift;
  my $linesep = $/;     # Save for later
  undef $/;             # When %/ is undefined, read reads the whole file
  my $contents = <$PORT>;
  $/ = $linesep;        # Restore
  return $contents;
} # readPort
