#!/usr/bin/env perl
use strict;
require 5.010;

my $VERSION = '0.14';

use Getopt::Long;
use Pod::Usage;
use Pod::Simple::Pandoc;

my %opt;
GetOptions( \%opt, 'help|h|?', 'man', 'filter=s' ) or exit 1;
pod2usage(1) if $opt{help};
pod2usage( -verbose => 2 ) if $opt{man};
@ARGV = '-' unless @ARGV;

my $combined;

foreach my $input (@ARGV) {
    my $doc = Pod::Simple::Pandoc->parse_file($input);
    if ($combined) {
        push @{ $combined->content }, @{ $doc->content };
    }
    else {
        $combined = $doc;
    }
}

if ( $opt{filter} ) {
    use Pandoc::Filter::Lazy;
    my $filter = Pandoc::Filter::Lazy->new( $opt{filter} );
    if ( $filter->error ) {
        say STDERR "Failed to compile filter code:\n";
        say STDERR $filter->code( indent => '    ' ) . "\n";
        say STDERR $filter->error;
        exit 1;
    } else {
        $filter->apply($combined);
    }
}

print $combined->to_json;

=head1 NAME

pod2pandoc - convert Pod to Pandoc document model

=head1 SYNOPSIS

  pod2pandoc [OPTIONS] [INPUT...] | pandoc -f json ...

=head1 DESCRIPTION

C<pod2pandoc> converts POD format documentation (L<perlpod>) to the abstract
document model used by L<Pandoc|http://pandoc.org/> for further processing to
other document formats (HTML, Markdown, LaTeX, PDF, EPUB, docx, ODT, man,
ICML...). By default or with input C<-> a document is read from STDIN. Multiple
input files are combined to one document.

Conversion is based on L<Pod::Simple::Pandoc> which uses L<Pandoc::Element>.

=head2 Examples

  pod2pandoc Module.pm | pandoc -f json -o Module.pdf
  pod2pandoc Module.pm | pandoc -f json -o Module.html

Or even shorter (not implemented yet):

  pod2pandoc Module.pm -- -o Module.pdf

With processing:

  pod2pandoc --filter 'Header => sub { Para [ Strong [ Str $_->string ] ] }' Module.pm

=head1 OPTIONS

=over 

=item --filter 'SELECTOR => ACTION'

Preprocess the document. See L<Pandoc::Filter::Lazy> for filter syntax.

=item --help|-h|-?

Print out usage information and exit

=item --man

Print the full manual page and exit

=back

=head1 SEE ALSO

This script together with Pandoc can be used as customizable replacement for
specialized Pod converter scripts such as L<pod2html>, L<pod2man>,
L<pod2readme>, L<pod2usage>, L<pod2latex>, L<pod2markdown>, and L<pod2text>.

=cut
