#!/usr/bin/perl -wn

use strict;
use autodie;

our (@doc, @toc);
our $last;

sub scanline () {
  if (m/^-+$/ || m/^=+$/) {
    my $lev = $& =~ m/^=/ ? '  ' : '    ';
    my $href = $last;
    $href =~ y/ A-Z/-a-z/;
    $href =~ y/-._a-z//cd;
    my $text = $last;
    $text = 'Introduction' if $. == 2;
    push @toc, "${lev}* [$text](#$href)\n";
  }
  $last = $_;
  chomp $last;
}

if (1..(m/^[A-Z]/ && m/table of contents/i)) {
  # before TOC
  scanline();
  print;
} elsif (m/^\w/..0) {
  # after TOC
  push @doc, $_;
  scanline();
} else {
  # in TOC
  print if m/^===|^---/;
  scanline();
}

END {
  print <<END, @toc, "\n";

<!-- TOC autogenerated by $0, do not edit -->

END
  print @doc;
}
