#!/usr/bin/env perl

use strict;
use warnings FATAL => 'all';

use English qw(-no_match_vars);

my %headings = (
   '1' => '=',
   '2' => '-',
);
my $list   = 0;
my $marker = "";

# Skip up until the documentation starts.
while(<>) {
   last if m/^=pod/;
}

# Read a para at a time
$RS = "";

LINE:
while (<>) {
   my $line = $_;
   chomp $line;

   if ( $line eq '=cut' ) {
      last LINE;
   }

   # Take care of inline stylings.
   $line =~ s/C<(.*?)>/``$1``/gs;

   # Escape special characters that aren't at the beginning of a line.
   $line =~ s/(?<!^)([*])/\\$1/gm;

   # Headings
   if ( my ($level, $val) = $line =~ m/^=head(\d)\s+(.*)$/ ) {
      print $val, "\n";
      $val =~ s/./$headings{$level}/g;
      print $val, "\n\n";
      next LINE;
   }

   # Indented lines are turned into code blocks.
   if ( $line =~ m/^(\s+)/ ) {
      print ".. code-block:: none\n\n", $line, "\n\n";
      next LINE;
   }

   # Lists begin and end.
   if ( $line =~ m/=over/ ) {
      $list = 1;
      next LINE;
   }
   elsif ( $line =~ m/=back/ ) {
      $list = 0;
      next LINE;
   }

   # Paragraphs within a list.
   if ( $list ) {
      if ( my ($m) = $line =~ m/^=item \\?(.*)/g ) {
         $marker = $m;
         next LINE;
      }
      else {
         $line =~ s/^/   /gm;
         # The first paragraph after printing the bullet marker needs to be
         # prepended with the marker.
         if ( $marker ) {
            if ( length($marker) == 1 ) {
               $line =~ s/\A /$marker/;
            }
            else {
               $line = "$marker\n\n$line";
            }
            $marker = "";
         }
         print $line, "\n\n";
         next LINE;
      }
   }

   print $line, "\n\n";
}
