#!/usr/bin/perl

use warnings;
use strict;

use Pandoc::Filter 0.05;
use Pandoc::Elements;

# FIXME: avoid eating content past tweaked headers
pandoc_filter(
	\&frontmatter,
	\&mainmatter,
	\&backmatter,
	\&toc,
);

# FIXME: use Header (not latex RawBlock) - why does it hang?!?
sub header {
	my $label = shift;
#	Header( 1, attributes {}, [ Str $label ], );
	RawBlock( 'latex', '\\chapter{'.$label.'}' );
};

sub frontmatter {
	my $self = shift;
	return [ RawBlock( 'latex', '\\frontmatter' ), header('About'), ]
		if ( $self->name eq 'Header' and $self->level >= 1
			and stringify($self) eq 'About' );
	return;
}

sub mainmatter {
	my $self = shift;
	return [ RawBlock( 'latex', '\\mainmatter' ), header(stringify($self)), ]
		if ( $self->name eq 'Header' and $self->level == 1
			and stringify($self) =~ /^Scope/ );
	return;
}

sub backmatter {
	my $self = shift;
	return [ RawBlock( 'latex', '\\backmatter' ), header('References'), ]
		if ( $self->name eq 'Header' and $self->level == 1
			and stringify($self) =~ /^Notes/ );
	return;
}

sub toc {
	my $self = shift;
	return RawBlock( 'latex',
		'{\\hypersetup{linkcolor=black}\\setcounter{tocdepth}{3}\\clearpage\\tableofcontents}'
	)
		if ( $self->name eq 'Header' and $self->level == 1
			and stringify($self) =~ /^Table/ );
	return []
		if ( $self->name eq 'Para' and stringify($self) =~ /__TOC__/ );
	return;
}