#!/usr/bin/env perl

use strict;
use FindBin;
use lib "$FindBin::Bin/../lib";
use lib "$FindBin::Bin/../../pegex-pm/lib";
use Pegex::Parser;
use Kwim::Grammar;
use Getopt::Long;

use Getopt::Long;

my $to = "html";
my $debug = $ENV{PERL_PEGEX_DEBUG} || 0;
my %opts = (
  'wrap' => 0,
  'complete' => 0,
  'pod-upper-head' => 0,
);
my %opt_spec = (
  "to=s" => \$to,
  "debug" => \$debug,
  "complete=s" => \&opt,
  "wrap=s" => \&opt,
  "pod-upper-head=s" => \&opt,
  "pod-cpan" => \&pod_cpan_opts,
);

sub main {
  GetOptions(%opt_spec) or die "Error in command line arguments";

  my $ext_to_receiver = {
    html => 'Kwim::HTML',
    md => 'Kwim::Markdown',
    markdown => 'Kwim::Markdown',
    pod => 'Kwim::Pod',
    byte => 'Kwim::Byte',
  };

  my $receiver_class = $ext_to_receiver->{$to}
    or die "Unknown extension '$to'";
  eval "require $receiver_class; 1"
    or die "$@";

  my $kwim = do {local $/; <>};
  my $parser = Pegex::Parser->new(
    grammar => 'Kwim::Grammar'->new,
    receiver => $receiver_class->new(option => \%opts),
    debug => $debug,
  );
  print $parser->parse($kwim);
}

sub opt {
  my ($option, $value) = @_;
  $opts{$option} =
    $value =~ /^(true|1)$/ ? 1 :
    $value =~ /^(false|0)$/ ? 0 :
    0;
}

sub pod_cpan_opts {
  $to = 'pod';
  $opts{complete} = 1;
  $opts{wrap} = 1;
  $opts{'pod-upper-head'} = 1;
}

main();

# vim: set sw=2:
