#!/usr/bin/perl -w
use strict;
use warnings;
use HTML::Entities;
use utf8::all;
use autodie;

sub read_file {
	my ($file) = @_;
	my $fh;
	if (ref $file) {
		$fh = $file;
	} else {
		open $fh, "<:encoding(UTF-8)", $file;
	}
	local $/;
	return <$fh>;
}
sub ee { return encode_entities(@_); }

my ($text_file, $html_file, $prev, $next, $first, $last) = @ARGV;

my $text = read_file($text_file);
my $head = read_file('_head.html');
my $foot = read_file('_foot.html');

$text =~ s/\n+\z//;

# title, author, date
$text =~ s/^(.*?)\n(.*?), (\d{4}-\d{2}-\d{2})\n+//
	or die "bad text format";
my $title = ee($1);
my $author = ee($2);
my $date = ee($3);

# paragraphs
sub p {
	my ($s) = @_;
	return "<p>".ee($s)."</p>\n\n";
}

my @parts = split /\n\n+/, $text;
for my $part (@parts) {
	$part = p($part);
}

# TODO:
# links
# images
# sections of code

# h1 includes links to other pages...
my $show_h1_controls = 1;
my $h1_controls = '';
if ($show_h1_controls) {
	$h1_controls .= ' <span class="spacer"></span> ';
	$h1_controls .= qq{<a href="$first">|&lt;</a>} if $first ne $html_file;
	$h1_controls .= qq{<a href="$prev">&lt;</a>} if $prev;
	$h1_controls .= qq{<a href="contents.html">&#9776;</a>} if -e "contents.html";
	$h1_controls .= qq{<a href="$next">&gt;</a>} if $next;
	$h1_controls .= qq{<a href="$last">&gt;|</a>} if $last ne $html_file;
}

open my $out, ">:encoding(UTF-8)", $html_file;

print $out $head;
print $out <<EOT;
<title>$title</title>
<h1>$title$h1_controls</h1>
<div>$author, <small>$date</small></div>

<div class="columns">
EOT

for my $part (@parts) {
	print $out $part;
}

print $out <<EOT;
</div>
EOT

print $out $foot;

close $out;
