
# This chunk of stuff was generated by App::FatPacker. To find the original
# file's code, look for the end of this BEGIN block or the string 'FATPACK'
BEGIN {
my %fatpacked;

$fatpacked{"App/pandoc/preprocess.pm"} = <<'APP_PANDOC_PREPROCESS';
  package App::pandoc::preprocess;
  
  #  PODNAME: App::pandoc::preprocess
  # ABSTRACT: Preprocess Pandoc before Processing Pandoc
  
  =begin wikidoc
  
  = ppp - pandoc pre-process
  
  = USAGE
  
      cat chapters/input-*.pandoc | ppp | pandoc -o output.pdf --smart [more pandoc options...]
  
  Additionally see `etc/input.txt` for concrete examples.
  
  = PREREQUISITES
  
  * dot/neato (neato is new!)
  * rdfdot
  * ditaa
  * Image::Magick (for downscaling of large images)
  
  = BACKGROUND
  
  * much simpler design than version 1: pipeable & chainable, reading line-by-line
  * parallelized work on image file creation
  
  == How it works
  
  1. while-loop will iterate line by line and is using the flip-flop-operator:
      * as soon, as a ditaa/rdfdot/dot-block starts,
        globals ($fileno, $outfile, etc) are set, so all other routines can see them
      * when actually *inside* the block, the block's contents are printed
        to the newly generated file (image-X.(ditaa/rdfdot/dot))
  2. once the flip-flop-operator hits the end of the ditaa/rdfdot/dot-block,
  a child will be spawned to take over the actual ditaa/rdfdot/dot-process
  to create the png-file and the globals are reset
  
  3. all other lines which are not part of a ditaa/rdfdot/dot-block will simply
  be piped through to stdout
  
  4. at the end of the program, all children are waited for
  
  5. in the meantime, the new pandoc contents are printed to stdout
  
  6. all child-processes will remain quiert as far as stdout is concerned and
  write to their individual log-files
  
  == Todo
  
  * Captions
  * Checks whether ditaa... are available
  * check whether ditaa has file.encoding set
  * bundle ditaa with this
  
  =end wikidoc
  
  'make CPAN happy -- we only have a main in bin/ppp'
APP_PANDOC_PREPROCESS

$fatpacked{"Carp.pm"} = <<'CARP';
  package Carp;
  
  { use 5.006; }
  use strict;
  use warnings;
  BEGIN {
      # Very old versions of warnings.pm load Carp.  This can go wrong due
      # to the circular dependency.  If warnings is invoked before Carp,
      # then warnings starts by loading Carp, then Carp (above) tries to
      # invoke warnings, and gets nothing because warnings is in the process
      # of loading and hasn't defined its import method yet.  If we were
      # only turning on warnings ("use warnings" above) this wouldn't be too
      # bad, because Carp would just gets the state of the -w switch and so
      # might not get some warnings that it wanted.  The real problem is
      # that we then want to turn off Unicode warnings, but "no warnings
      # 'utf8'" won't be effective if we're in this circular-dependency
      # situation.  So, if warnings.pm is an affected version, we turn
      # off all warnings ourselves by directly setting ${^WARNING_BITS}.
      # On unaffected versions, we turn off just Unicode warnings, via
      # the proper API.
      if(!defined($warnings::VERSION) || eval($warnings::VERSION) < 1.06) {
  	${^WARNING_BITS} = "";
      } else {
  	"warnings"->unimport("utf8");
      }
  }
  
  sub _fetch_sub { # fetch sub without autovivifying
      my($pack, $sub) = @_;
      $pack .= '::';
      # only works with top-level packages
      return unless exists($::{$pack});
      for ($::{$pack}) {
  	return unless ref \$_ eq 'GLOB' && *$_{HASH} && exists $$_{$sub};
  	for ($$_{$sub}) {
  	    return ref \$_ eq 'GLOB' ? *$_{CODE} : undef
  	}
      }
  }
  
  # UTF8_REGEXP_PROBLEM is a compile-time constant indicating whether Carp
  # must avoid applying a regular expression to an upgraded (is_utf8)
  # string.  There are multiple problems, on different Perl versions,
  # that require this to be avoided.  All versions prior to 5.13.8 will
  # load utf8_heavy.pl for the swash system, even if the regexp doesn't
  # use character classes.  Perl 5.6 and Perls [5.11.2, 5.13.11) exhibit
  # specific problems when Carp is being invoked in the aftermath of a
  # syntax error.
  BEGIN {
      if("$]" < 5.013011) {
  	*UTF8_REGEXP_PROBLEM = sub () { 1 };
      } else {
  	*UTF8_REGEXP_PROBLEM = sub () { 0 };
      }
  }
  
  # is_utf8() is essentially the utf8::is_utf8() function, which indicates
  # whether a string is represented in the upgraded form (using UTF-8
  # internally).  As utf8::is_utf8() is only available from Perl 5.8
  # onwards, extra effort is required here to make it work on Perl 5.6.
  BEGIN {
      if(defined(my $sub = _fetch_sub utf8 => 'is_utf8')) {
  	*is_utf8 = $sub;
      } else {
  	# black magic for perl 5.6
  	*is_utf8 = sub { unpack("C", "\xaa".$_[0]) != 170 };
      }
  }
  
  # The downgrade() function defined here is to be used for attempts to
  # downgrade where it is acceptable to fail.  It must be called with a
  # second argument that is a true value.
  BEGIN {
      if(defined(my $sub = _fetch_sub utf8 => 'downgrade')) {
  	*downgrade = \&{"utf8::downgrade"};
      } else {
  	*downgrade = sub {
  	    my $r = "";
  	    my $l = length($_[0]);
  	    for(my $i = 0; $i != $l; $i++) {
  		my $o = ord(substr($_[0], $i, 1));
  		return if $o > 255;
  		$r .= chr($o);
  	    }
  	    $_[0] = $r;
  	};
      }
  }
  
  our $VERSION = '1.32';
  
  our $MaxEvalLen = 0;
  our $Verbose    = 0;
  our $CarpLevel  = 0;
  our $MaxArgLen  = 64;    # How much of each argument to print. 0 = all.
  our $MaxArgNums = 8;     # How many arguments to print. 0 = all.
  our $RefArgFormatter = undef; # allow caller to format reference arguments
  
  require Exporter;
  our @ISA       = ('Exporter');
  our @EXPORT    = qw(confess croak carp);
  our @EXPORT_OK = qw(cluck verbose longmess shortmess);
  our @EXPORT_FAIL = qw(verbose);    # hook to enable verbose mode
  
  # The members of %Internal are packages that are internal to perl.
  # Carp will not report errors from within these packages if it
  # can.  The members of %CarpInternal are internal to Perl's warning
  # system.  Carp will not report errors from within these packages
  # either, and will not report calls *to* these packages for carp and
  # croak.  They replace $CarpLevel, which is deprecated.    The
  # $Max(EvalLen|(Arg(Len|Nums)) variables are used to specify how the eval
  # text and function arguments should be formatted when printed.
  
  our %CarpInternal;
  our %Internal;
  
  # disable these by default, so they can live w/o require Carp
  $CarpInternal{Carp}++;
  $CarpInternal{warnings}++;
  $Internal{Exporter}++;
  $Internal{'Exporter::Heavy'}++;
  
  # if the caller specifies verbose usage ("perl -MCarp=verbose script.pl")
  # then the following method will be called by the Exporter which knows
  # to do this thanks to @EXPORT_FAIL, above.  $_[1] will contain the word
  # 'verbose'.
  
  sub export_fail { shift; $Verbose = shift if $_[0] eq 'verbose'; @_ }
  
  sub _cgc {
      no strict 'refs';
      return \&{"CORE::GLOBAL::caller"} if defined &{"CORE::GLOBAL::caller"};
      return;
  }
  
  sub longmess {
      local($!, $^E);
      # Icky backwards compatibility wrapper. :-(
      #
      # The story is that the original implementation hard-coded the
      # number of call levels to go back, so calls to longmess were off
      # by one.  Other code began calling longmess and expecting this
      # behaviour, so the replacement has to emulate that behaviour.
      my $cgc = _cgc();
      my $call_pack = $cgc ? $cgc->() : caller();
      if ( $Internal{$call_pack} or $CarpInternal{$call_pack} ) {
          return longmess_heavy(@_);
      }
      else {
          local $CarpLevel = $CarpLevel + 1;
          return longmess_heavy(@_);
      }
  }
  
  our @CARP_NOT;
  
  sub shortmess {
      local($!, $^E);
      my $cgc = _cgc();
  
      # Icky backwards compatibility wrapper. :-(
      local @CARP_NOT = $cgc ? $cgc->() : caller();
      shortmess_heavy(@_);
  }
  
  sub croak   { die shortmess @_ }
  sub confess { die longmess @_ }
  sub carp    { warn shortmess @_ }
  sub cluck   { warn longmess @_ }
  
  BEGIN {
      if("$]" >= 5.015002 || ("$]" >= 5.014002 && "$]" < 5.015) ||
  	    ("$]" >= 5.012005 && "$]" < 5.013)) {
  	*CALLER_OVERRIDE_CHECK_OK = sub () { 1 };
      } else {
  	*CALLER_OVERRIDE_CHECK_OK = sub () { 0 };
      }
  }
  
  sub caller_info {
      my $i = shift(@_) + 1;
      my %call_info;
      my $cgc = _cgc();
      {
  	# Some things override caller() but forget to implement the
  	# @DB::args part of it, which we need.  We check for this by
  	# pre-populating @DB::args with a sentinel which no-one else
  	# has the address of, so that we can detect whether @DB::args
  	# has been properly populated.  However, on earlier versions
  	# of perl this check tickles a bug in CORE::caller() which
  	# leaks memory.  So we only check on fixed perls.
          @DB::args = \$i if CALLER_OVERRIDE_CHECK_OK;
          package DB;
          @call_info{
              qw(pack file line sub has_args wantarray evaltext is_require) }
              = $cgc ? $cgc->($i) : caller($i);
      }
  
      unless ( defined $call_info{file} ) {
          return ();
      }
  
      my $sub_name = Carp::get_subname( \%call_info );
      if ( $call_info{has_args} ) {
          my @args;
          if (CALLER_OVERRIDE_CHECK_OK && @DB::args == 1
              && ref $DB::args[0] eq ref \$i
              && $DB::args[0] == \$i ) {
              @DB::args = ();    # Don't let anyone see the address of $i
              local $@;
              my $where = eval {
                  my $func    = $cgc or return '';
                  my $gv      =
                      (_fetch_sub B => 'svref_2object' or return '')
                          ->($func)->GV;
                  my $package = $gv->STASH->NAME;
                  my $subname = $gv->NAME;
                  return unless defined $package && defined $subname;
  
                  # returning CORE::GLOBAL::caller isn't useful for tracing the cause:
                  return if $package eq 'CORE::GLOBAL' && $subname eq 'caller';
                  " in &${package}::$subname";
              } || '';
              @args
                  = "** Incomplete caller override detected$where; \@DB::args were not set **";
          }
          else {
              @args = @DB::args;
              my $overflow;
              if ( $MaxArgNums and @args > $MaxArgNums )
              {    # More than we want to show?
                  $#args = $MaxArgNums;
                  $overflow = 1;
              }
  
              @args = map { Carp::format_arg($_) } @args;
  
              if ($overflow) {
                  push @args, '...';
              }
          }
  
          # Push the args onto the subroutine
          $sub_name .= '(' . join( ', ', @args ) . ')';
      }
      $call_info{sub_name} = $sub_name;
      return wantarray() ? %call_info : \%call_info;
  }
  
  # Transform an argument to a function into a string.
  our $in_recurse;
  sub format_arg {
      my $arg = shift;
  
      if ( ref($arg) ) {
           # legitimate, let's not leak it.
          if (!$in_recurse &&
  	    do {
                  local $@;
  	        local $in_recurse = 1;
  		local $SIG{__DIE__} = sub{};
                  eval {$arg->can('CARP_TRACE') }
              })
          {
              return $arg->CARP_TRACE();
          }
          elsif (!$in_recurse &&
  	       defined($RefArgFormatter) &&
  	       do {
                  local $@;
  	        local $in_recurse = 1;
  		local $SIG{__DIE__} = sub{};
                  eval {$arg = $RefArgFormatter->($arg); 1}
                  })
          {
              return $arg;
          }
          else
          {
  	    my $sub = _fetch_sub(overload => 'StrVal');
  	    return $sub ? &$sub($arg) : "$arg";
          }
      }
      return "undef" if !defined($arg);
      downgrade($arg, 1);
      return $arg if !(UTF8_REGEXP_PROBLEM && is_utf8($arg)) &&
  	    $arg =~ /\A-?[0-9]+(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?\z/;
      my $suffix = "";
      if ( 2 < $MaxArgLen and $MaxArgLen < length($arg) ) {
          substr ( $arg, $MaxArgLen - 3 ) = "";
  	$suffix = "...";
      }
      if(UTF8_REGEXP_PROBLEM && is_utf8($arg)) {
  	for(my $i = length($arg); $i--; ) {
  	    my $c = substr($arg, $i, 1);
  	    my $x = substr($arg, 0, 0);   # work around bug on Perl 5.8.{1,2}
  	    if($c eq "\"" || $c eq "\\" || $c eq "\$" || $c eq "\@") {
  		substr $arg, $i, 0, "\\";
  		next;
  	    }
  	    my $o = ord($c);
  	    substr $arg, $i, 1, sprintf("\\x{%x}", $o)
  		if $o < 0x20 || $o > 0x7f;
  	}
      } else {
  	$arg =~ s/([\"\\\$\@])/\\$1/g;
  	$arg =~ s/([^ -~])/sprintf("\\x{%x}",ord($1))/eg;
      }
      downgrade($arg, 1);
      return "\"".$arg."\"".$suffix;
  }
  
  sub Regexp::CARP_TRACE {
      my $arg = "$_[0]";
      downgrade($arg, 1);
      if(UTF8_REGEXP_PROBLEM && is_utf8($arg)) {
  	for(my $i = length($arg); $i--; ) {
  	    my $o = ord(substr($arg, $i, 1));
  	    my $x = substr($arg, 0, 0);   # work around bug on Perl 5.8.{1,2}
  	    substr $arg, $i, 1, sprintf("\\x{%x}", $o)
  		if $o < 0x20 || $o > 0x7f;
  	}
      } else {
  	$arg =~ s/([^ -~])/sprintf("\\x{%x}",ord($1))/eg;
      }
      downgrade($arg, 1);
      my $suffix = "";
      if($arg =~ /\A\(\?\^?([a-z]*)(?:-[a-z]*)?:(.*)\)\z/s) {
  	($suffix, $arg) = ($1, $2);
      }
      if ( 2 < $MaxArgLen and $MaxArgLen < length($arg) ) {
          substr ( $arg, $MaxArgLen - 3 ) = "";
  	$suffix = "...".$suffix;
      }
      return "qr($arg)$suffix";
  }
  
  # Takes an inheritance cache and a package and returns
  # an anon hash of known inheritances and anon array of
  # inheritances which consequences have not been figured
  # for.
  sub get_status {
      my $cache = shift;
      my $pkg   = shift;
      $cache->{$pkg} ||= [ { $pkg => $pkg }, [ trusts_directly($pkg) ] ];
      return @{ $cache->{$pkg} };
  }
  
  # Takes the info from caller() and figures out the name of
  # the sub/require/eval
  sub get_subname {
      my $info = shift;
      if ( defined( $info->{evaltext} ) ) {
          my $eval = $info->{evaltext};
          if ( $info->{is_require} ) {
              return "require $eval";
          }
          else {
              $eval =~ s/([\\\'])/\\$1/g;
              return "eval '" . str_len_trim( $eval, $MaxEvalLen ) . "'";
          }
      }
  
      # this can happen on older perls when the sub (or the stash containing it)
      # has been deleted
      if ( !defined( $info->{sub} ) ) {
          return '__ANON__::__ANON__';
      }
  
      return ( $info->{sub} eq '(eval)' ) ? 'eval {...}' : $info->{sub};
  }
  
  # Figures out what call (from the point of view of the caller)
  # the long error backtrace should start at.
  sub long_error_loc {
      my $i;
      my $lvl = $CarpLevel;
      {
          ++$i;
          my $cgc = _cgc();
          my @caller = $cgc ? $cgc->($i) : caller($i);
          my $pkg = $caller[0];
          unless ( defined($pkg) ) {
  
              # This *shouldn't* happen.
              if (%Internal) {
                  local %Internal;
                  $i = long_error_loc();
                  last;
              }
              elsif (defined $caller[2]) {
                  # this can happen when the stash has been deleted
                  # in that case, just assume that it's a reasonable place to
                  # stop (the file and line data will still be intact in any
                  # case) - the only issue is that we can't detect if the
                  # deleted package was internal (so don't do that then)
                  # -doy
                  redo unless 0 > --$lvl;
                  last;
              }
              else {
                  return 2;
              }
          }
          redo if $CarpInternal{$pkg};
          redo unless 0 > --$lvl;
          redo if $Internal{$pkg};
      }
      return $i - 1;
  }
  
  sub longmess_heavy {
      return @_ if ref( $_[0] );    # don't break references as exceptions
      my $i = long_error_loc();
      return ret_backtrace( $i, @_ );
  }
  
  # Returns a full stack backtrace starting from where it is
  # told.
  sub ret_backtrace {
      my ( $i, @error ) = @_;
      my $mess;
      my $err = join '', @error;
      $i++;
  
      my $tid_msg = '';
      if ( defined &threads::tid ) {
          my $tid = threads->tid;
          $tid_msg = " thread $tid" if $tid;
      }
  
      my %i = caller_info($i);
      $mess = "$err at $i{file} line $i{line}$tid_msg";
      if( defined $. ) {
          local $@ = '';
          local $SIG{__DIE__};
          eval {
              CORE::die;
          };
          if($@ =~ /^Died at .*(, <.*?> line \d+).$/ ) {
              $mess .= $1;
          }
      }
      $mess .= "\.\n";
  
      while ( my %i = caller_info( ++$i ) ) {
          $mess .= "\t$i{sub_name} called at $i{file} line $i{line}$tid_msg\n";
      }
  
      return $mess;
  }
  
  sub ret_summary {
      my ( $i, @error ) = @_;
      my $err = join '', @error;
      $i++;
  
      my $tid_msg = '';
      if ( defined &threads::tid ) {
          my $tid = threads->tid;
          $tid_msg = " thread $tid" if $tid;
      }
  
      my %i = caller_info($i);
      return "$err at $i{file} line $i{line}$tid_msg\.\n";
  }
  
  sub short_error_loc {
      # You have to create your (hash)ref out here, rather than defaulting it
      # inside trusts *on a lexical*, as you want it to persist across calls.
      # (You can default it on $_[2], but that gets messy)
      my $cache = {};
      my $i     = 1;
      my $lvl   = $CarpLevel;
      {
          my $cgc = _cgc();
          my $called = $cgc ? $cgc->($i) : caller($i);
          $i++;
          my $caller = $cgc ? $cgc->($i) : caller($i);
  
          if (!defined($caller)) {
              my @caller = $cgc ? $cgc->($i) : caller($i);
              if (@caller) {
                  # if there's no package but there is other caller info, then
                  # the package has been deleted - treat this as a valid package
                  # in this case
                  redo if defined($called) && $CarpInternal{$called};
                  redo unless 0 > --$lvl;
                  last;
              }
              else {
                  return 0;
              }
          }
          redo if $Internal{$caller};
          redo if $CarpInternal{$caller};
          redo if $CarpInternal{$called};
          redo if trusts( $called, $caller, $cache );
          redo if trusts( $caller, $called, $cache );
          redo unless 0 > --$lvl;
      }
      return $i - 1;
  }
  
  sub shortmess_heavy {
      return longmess_heavy(@_) if $Verbose;
      return @_ if ref( $_[0] );    # don't break references as exceptions
      my $i = short_error_loc();
      if ($i) {
          ret_summary( $i, @_ );
      }
      else {
          longmess_heavy(@_);
      }
  }
  
  # If a string is too long, trims it with ...
  sub str_len_trim {
      my $str = shift;
      my $max = shift || 0;
      if ( 2 < $max and $max < length($str) ) {
          substr( $str, $max - 3 ) = '...';
      }
      return $str;
  }
  
  # Takes two packages and an optional cache.  Says whether the
  # first inherits from the second.
  #
  # Recursive versions of this have to work to avoid certain
  # possible endless loops, and when following long chains of
  # inheritance are less efficient.
  sub trusts {
      my $child  = shift;
      my $parent = shift;
      my $cache  = shift;
      my ( $known, $partial ) = get_status( $cache, $child );
  
      # Figure out consequences until we have an answer
      while ( @$partial and not exists $known->{$parent} ) {
          my $anc = shift @$partial;
          next if exists $known->{$anc};
          $known->{$anc}++;
          my ( $anc_knows, $anc_partial ) = get_status( $cache, $anc );
          my @found = keys %$anc_knows;
          @$known{@found} = ();
          push @$partial, @$anc_partial;
      }
      return exists $known->{$parent};
  }
  
  # Takes a package and gives a list of those trusted directly
  sub trusts_directly {
      my $class = shift;
      no strict 'refs';
      my $stash = \%{"$class\::"};
      for my $var (qw/ CARP_NOT ISA /) {
          # Don't try using the variable until we know it exists,
          # to avoid polluting the caller's namespace.
          if ( $stash->{$var} && *{$stash->{$var}}{ARRAY} && @{$stash->{$var}} ) {
             return @{$stash->{$var}}
          }
      }
      return;
  }
  
  if(!defined($warnings::VERSION) ||
  	do { no warnings "numeric"; $warnings::VERSION < 1.03 }) {
      # Very old versions of warnings.pm import from Carp.  This can go
      # wrong due to the circular dependency.  If Carp is invoked before
      # warnings, then Carp starts by loading warnings, then warnings
      # tries to import from Carp, and gets nothing because Carp is in
      # the process of loading and hasn't defined its import method yet.
      # So we work around that by manually exporting to warnings here.
      no strict "refs";
      *{"warnings::$_"} = \&$_ foreach @EXPORT;
  }
  
  1;
  
  __END__
  
  =head1 NAME
  
  Carp - alternative warn and die for modules
  
  =head1 SYNOPSIS
  
      use Carp;
  
      # warn user (from perspective of caller)
      carp "string trimmed to 80 chars";
  
      # die of errors (from perspective of caller)
      croak "We're outta here!";
  
      # die of errors with stack backtrace
      confess "not implemented";
  
      # cluck, longmess and shortmess not exported by default
      use Carp qw(cluck longmess shortmess);
      cluck "This is how we got here!";
      $long_message   = longmess( "message from cluck() or confess()" );
      $short_message  = shortmess( "message from carp() or croak()" );
  
  =head1 DESCRIPTION
  
  The Carp routines are useful in your own modules because
  they act like C<die()> or C<warn()>, but with a message which is more
  likely to be useful to a user of your module.  In the case of
  C<cluck()> and C<confess()>, that context is a summary of every
  call in the call-stack; C<longmess()> returns the contents of the error
  message.
  
  For a shorter message you can use C<carp()> or C<croak()> which report the
  error as being from where your module was called.  C<shortmess()> returns the
  contents of this error message.  There is no guarantee that that is where the
  error was, but it is a good educated guess.
  
  C<Carp> takes care not to clobber the status variables C<$!> and C<$^E>
  in the course of assembling its error messages.  This means that a
  C<$SIG{__DIE__}> or C<$SIG{__WARN__}> handler can capture the error
  information held in those variables, if it is required to augment the
  error message, and if the code calling C<Carp> left useful values there.
  Of course, C<Carp> can't guarantee the latter.
  
  You can also alter the way the output and logic of C<Carp> works, by
  changing some global variables in the C<Carp> namespace. See the
  section on C<GLOBAL VARIABLES> below.
  
  Here is a more complete description of how C<carp> and C<croak> work.
  What they do is search the call-stack for a function call stack where
  they have not been told that there shouldn't be an error.  If every
  call is marked safe, they give up and give a full stack backtrace
  instead.  In other words they presume that the first likely looking
  potential suspect is guilty.  Their rules for telling whether
  a call shouldn't generate errors work as follows:
  
  =over 4
  
  =item 1.
  
  Any call from a package to itself is safe.
  
  =item 2.
  
  Packages claim that there won't be errors on calls to or from
  packages explicitly marked as safe by inclusion in C<@CARP_NOT>, or
  (if that array is empty) C<@ISA>.  The ability to override what
  @ISA says is new in 5.8.
  
  =item 3.
  
  The trust in item 2 is transitive.  If A trusts B, and B
  trusts C, then A trusts C.  So if you do not override C<@ISA>
  with C<@CARP_NOT>, then this trust relationship is identical to,
  "inherits from".
  
  =item 4.
  
  Any call from an internal Perl module is safe.  (Nothing keeps
  user modules from marking themselves as internal to Perl, but
  this practice is discouraged.)
  
  =item 5.
  
  Any call to Perl's warning system (eg Carp itself) is safe.
  (This rule is what keeps it from reporting the error at the
  point where you call C<carp> or C<croak>.)
  
  =item 6.
  
  C<$Carp::CarpLevel> can be set to skip a fixed number of additional
  call levels.  Using this is not recommended because it is very
  difficult to get it to behave correctly.
  
  =back
  
  =head2 Forcing a Stack Trace
  
  As a debugging aid, you can force Carp to treat a croak as a confess
  and a carp as a cluck across I<all> modules. In other words, force a
  detailed stack trace to be given.  This can be very helpful when trying
  to understand why, or from where, a warning or error is being generated.
  
  This feature is enabled by 'importing' the non-existent symbol
  'verbose'. You would typically enable it by saying
  
      perl -MCarp=verbose script.pl
  
  or by including the string C<-MCarp=verbose> in the PERL5OPT
  environment variable.
  
  Alternately, you can set the global variable C<$Carp::Verbose> to true.
  See the C<GLOBAL VARIABLES> section below.
  
  =head2 Stack Trace formatting
  
  At each stack level, the subroutine's name is displayed along with
  its parameters.  For simple scalars, this is sufficient.  For complex
  data types, such as objects and other references, this can simply
  display C<'HASH(0x1ab36d8)'>.
  
  Carp gives two ways to control this.
  
  =over 4
  
  =item 1.
  
  For objects, a method, C<CARP_TRACE>, will be called, if it exists.  If
  this method doesn't exist, or it recurses into C<Carp>, or it otherwise
  throws an exception, this is skipped, and Carp moves on to the next option,
  otherwise checking stops and the string returned is used.  It is recommended
  that the object's type is part of the string to make debugging easier.
  
  =item 2.
  
  For any type of reference, C<$Carp::RefArgFormatter> is checked (see below).
  This variable is expected to be a code reference, and the current parameter
  is passed in.  If this function doesn't exist (the variable is undef), or
  it recurses into C<Carp>, or it otherwise throws an exception, this is
  skipped, and Carp moves on to the next option, otherwise checking stops
  and the string returned is used.
  
  =item 3.
  
  Otherwise, if neither C<CARP_TRACE> nor C<$Carp::RefArgFormatter> is
  available, stringify the value ignoring any overloading.
  
  =back
  
  =head1 GLOBAL VARIABLES
  
  =head2 $Carp::MaxEvalLen
  
  This variable determines how many characters of a string-eval are to
  be shown in the output. Use a value of C<0> to show all text.
  
  Defaults to C<0>.
  
  =head2 $Carp::MaxArgLen
  
  This variable determines how many characters of each argument to a
  function to print. Use a value of C<0> to show the full length of the
  argument.
  
  Defaults to C<64>.
  
  =head2 $Carp::MaxArgNums
  
  This variable determines how many arguments to each function to show.
  Use a value of C<0> to show all arguments to a function call.
  
  Defaults to C<8>.
  
  =head2 $Carp::Verbose
  
  This variable makes C<carp()> and C<croak()> generate stack backtraces
  just like C<cluck()> and C<confess()>.  This is how C<use Carp 'verbose'>
  is implemented internally.
  
  Defaults to C<0>.
  
  =head2 $Carp::RefArgFormatter
  
  This variable sets a general argument formatter to display references.
  Plain scalars and objects that implement C<CARP_TRACE> will not go through
  this formatter.  Calling C<Carp> from within this function is not supported.
  
  local $Carp::RefArgFormatter = sub {
      require Data::Dumper;
      Data::Dumper::Dump($_[0]); # not necessarily safe
  };
  
  =head2 @CARP_NOT
  
  This variable, I<in your package>, says which packages are I<not> to be
  considered as the location of an error. The C<carp()> and C<cluck()>
  functions will skip over callers when reporting where an error occurred.
  
  NB: This variable must be in the package's symbol table, thus:
  
      # These work
      our @CARP_NOT; # file scope
      use vars qw(@CARP_NOT); # package scope
      @My::Package::CARP_NOT = ... ; # explicit package variable
  
      # These don't work
      sub xyz { ... @CARP_NOT = ... } # w/o declarations above
      my @CARP_NOT; # even at top-level
  
  Example of use:
  
      package My::Carping::Package;
      use Carp;
      our @CARP_NOT;
      sub bar     { .... or _error('Wrong input') }
      sub _error  {
          # temporary control of where'ness, __PACKAGE__ is implicit
          local @CARP_NOT = qw(My::Friendly::Caller);
          carp(@_)
      }
  
  This would make C<Carp> report the error as coming from a caller not
  in C<My::Carping::Package>, nor from C<My::Friendly::Caller>.
  
  Also read the L</DESCRIPTION> section above, about how C<Carp> decides
  where the error is reported from.
  
  Use C<@CARP_NOT>, instead of C<$Carp::CarpLevel>.
  
  Overrides C<Carp>'s use of C<@ISA>.
  
  =head2 %Carp::Internal
  
  This says what packages are internal to Perl.  C<Carp> will never
  report an error as being from a line in a package that is internal to
  Perl.  For example:
  
      $Carp::Internal{ (__PACKAGE__) }++;
      # time passes...
      sub foo { ... or confess("whatever") };
  
  would give a full stack backtrace starting from the first caller
  outside of __PACKAGE__.  (Unless that package was also internal to
  Perl.)
  
  =head2 %Carp::CarpInternal
  
  This says which packages are internal to Perl's warning system.  For
  generating a full stack backtrace this is the same as being internal
  to Perl, the stack backtrace will not start inside packages that are
  listed in C<%Carp::CarpInternal>.  But it is slightly different for
  the summary message generated by C<carp> or C<croak>.  There errors
  will not be reported on any lines that are calling packages in
  C<%Carp::CarpInternal>.
  
  For example C<Carp> itself is listed in C<%Carp::CarpInternal>.
  Therefore the full stack backtrace from C<confess> will not start
  inside of C<Carp>, and the short message from calling C<croak> is
  not placed on the line where C<croak> was called.
  
  =head2 $Carp::CarpLevel
  
  This variable determines how many additional call frames are to be
  skipped that would not otherwise be when reporting where an error
  occurred on a call to one of C<Carp>'s functions.  It is fairly easy
  to count these call frames on calls that generate a full stack
  backtrace.  However it is much harder to do this accounting for calls
  that generate a short message.  Usually people skip too many call
  frames.  If they are lucky they skip enough that C<Carp> goes all of
  the way through the call stack, realizes that something is wrong, and
  then generates a full stack backtrace.  If they are unlucky then the
  error is reported from somewhere misleading very high in the call
  stack.
  
  Therefore it is best to avoid C<$Carp::CarpLevel>.  Instead use
  C<@CARP_NOT>, C<%Carp::Internal> and C<%Carp::CarpInternal>.
  
  Defaults to C<0>.
  
  =head1 BUGS
  
  The Carp routines don't handle exception objects currently.
  If called with a first argument that is a reference, they simply
  call die() or warn(), as appropriate.
  
  Some of the Carp code assumes that Perl's basic character encoding is
  ASCII, and will go wrong on an EBCDIC platform.
  
  =head1 SEE ALSO
  
  L<Carp::Always>,
  L<Carp::Clan>
  
  =head1 AUTHOR
  
  The Carp module first appeared in Larry Wall's perl 5.000 distribution.
  Since then it has been modified by several of the perl 5 porters.
  Andrew Main (Zefram) <zefram@fysh.org> divested Carp into an independent
  distribution.
  
  =head1 COPYRIGHT
  
  Copyright (C) 1994-2013 Larry Wall
  
  Copyright (C) 2011, 2012, 2013 Andrew Main (Zefram) <zefram@fysh.org>
  
  =head1 LICENSE
  
  This module is free software; you can redistribute it and/or modify it
  under the same terms as Perl itself.
CARP

$fatpacked{"Carp/Heavy.pm"} = <<'CARP_HEAVY';
  package Carp::Heavy;
  
  use Carp ();
  
  our $VERSION = '1.32';
  
  my $cv = defined($Carp::VERSION) ? $Carp::VERSION : "undef";
  if($cv ne $VERSION) {
  	die "Version mismatch between Carp $cv ($INC{q(Carp.pm)}) and Carp::Heavy $VERSION ($INC{q(Carp/Heavy.pm)}).  Did you alter \@INC after Carp was loaded?\n";
  }
  
  1;
  
  # Most of the machinery of Carp used to be here.
  # It has been moved in Carp.pm now, but this placeholder remains for
  # the benefit of modules that like to preload Carp::Heavy directly.
  # This must load Carp, because some modules rely on the historical
  # behaviour of Carp::Heavy loading Carp.
CARP_HEAVY

$fatpacked{"Smart/Comments.pm"} = <<'SMART_COMMENTS';
  package Smart::Comments;
  
  our $VERSION = '1.000005';
  
  use warnings;
  use strict;
  use Carp;
  
  use List::Util qw(sum);
  
  use Filter::Simple;
  
  my $maxwidth           = 69;  # Maximum width of display
  my $showwidth          = 35;  # How wide to make the indicator
  my $showstarttime      = 6;   # How long before showing time-remaining estimate
  my $showmaxtime        = 10;  # Don't start estimate if less than this to go
  my $whilerate          = 30;  # Controls the rate at which while indicator grows
  my $minfillwidth       = 5;   # Fill area must be at least this wide
  my $average_over       = 5;   # Number of time-remaining estimates to average
  my $minfillreps        = 2;   # Minimum size of a fill and fill cap indicator
  my $forupdatequantum   = 0.01;  # Only update every 1% of elapsed distance
  
  # Synonyms for asserts and requirements...
  my $require = qr/require|ensure|assert|insist/;
  my $check   = qr/check|verify|confirm/;
  
  # Horizontal whitespace...
  my $hws     = qr/[^\S\n]/;
  
  # Optional colon...
  my $optcolon = qr/$hws*;?/;
  
  # Automagic debugging as well...
  my $DBX = '$DB::single = $DB::single = 1;';
  
  # Implement comments-to-code source filter...
  FILTER {
      shift;        # Don't need the package name
      s/\r\n/\n/g;  # Handle win32 line endings
  
      # Default introducer pattern...
      my $intro = qr/#{3,}/;
  
      # Handle args...
      my @intros;
      while (@_) {
          my $arg = shift @_;
  
          if ($arg =~ m{\A -ENV \Z}xms) {
              my $env =  $ENV{Smart_Comments} || $ENV{SMART_COMMENTS}
                      || $ENV{SmartComments}  || $ENV{SMARTCOMMENTS}
                      ;
  
              return if !$env;   # i.e. if no filtering
  
              if ($env !~ m{\A \s* 1 \s* \Z}xms) {
                  unshift @_, split m{\s+|\s*:\s*}xms, $env;
              }
          }
          else {
              push @intros, $arg;
          }
      }
  
      if (my @unknowns = grep {!/$intro/} @intros) {
          croak "Incomprehensible arguments: @unknowns\n",
                "in call to 'use Smart::Comments'";
      }
  
      # Make non-default introducer pattern...
      if (@intros) {
          $intro = '(?-x:'.join('|',@intros).')(?!\#)';
      }
  
      # Preserve DATA handle if any...
      if (s{ ^ __DATA__ \s* $ (.*) \z }{}xms) {
          no strict qw< refs >;
          my $DATA = $1;
          open *{caller(1).'::DATA'}, '<', \$DATA or die "Internal error: $!";
      }
  
      # Progress bar on a for loop...
      s{ ^ $hws* ( (?: [^\W\d]\w*: \s*)? for(?:each)? \s* (?:my)? \s* (?:\$ [^\W\d]\w*)? \s* ) \( ([^;\n]*?) \) \s* \{
              [ \t]* $intro \s (.*) \s* $
       }
       { _decode_for($1, $2, $3) }xgem;
  
      # Progress bar on a while loop...
      s{ ^ $hws* ( (?: [^\W\d]\w*: \s*)? (?:while|until) \s* \( .*? \) \s* ) \{
              [ \t]* $intro \s (.*) \s* $
       }
       { _decode_while($1, $2) }xgem;
  
      # Progress bar on a C-style for loop...
      s{ ^ $hws* ( (?: [^\W\d]\w*: \s*)? for \s* \( .*? ; .*? ; .*? \) \s* ) \{
              $hws* $intro $hws (.*) $hws* $
       }
       { _decode_while($1, $2) }xgem;
  
      # Requirements...
      s{ ^ $hws* $intro [ \t] $require : \s* (.*?) $optcolon $hws* $ }
       { _decode_assert($1,"fatal") }gemx;
  
      # Assertions...
      s{ ^ $hws* $intro [ \t] $check : \s* (.*?) $optcolon $hws* $ }
       { _decode_assert($1) }gemx;
  
      # Any other smart comment is a simple dump.
      # Dump a raw scalar (the varname is used as the label)...
      s{ ^ $hws* $intro [ \t]+ (\$ [\w:]* \w) $optcolon $hws* $ }
       {Smart::Comments::_Dump(pref=>q{$1:},var=>[$1]);$DBX}gmx;
  
      # Dump a labelled scalar...
      s{ ^ $hws* $intro [ \t] (.+ :) [ \t]* (\$ [\w:]* \w) $optcolon $hws* $ }
       {Smart::Comments::_Dump(pref=>q{$1},var=>[$2]);$DBX}gmx;
  
      # Dump a raw hash or array (the varname is used as the label)...
      s{ ^ $hws* $intro [ \t]+ ([\@%] [\w:]* \w) $optcolon $hws* $ }
       {Smart::Comments::_Dump(pref=>q{$1:},var=>[\\$1]);$DBX}gmx;
  
      # Dump a labelled hash or array...
      s{ ^ $hws* $intro [ \t]+ (.+ :) [ \t]* ([\@%] [\w:]* \w) $optcolon $hws* $ }
       {Smart::Comments::_Dump(pref=>q{$1},var=>[\\$2]);$DBX}gmx;
  
      # Dump a labelled expression...
      s{ ^ $hws* $intro [ \t]+ (.+ :) (.+) }
       {Smart::Comments::_Dump(pref=>q{$1},var=>[$2]);$DBX}gmx;
  
      # Dump an 'in progress' message
      s{ ^ $hws* $intro $hws* (.+ [.]{3}) $hws* $ }
       {Smart::Comments::_Dump(pref=>qq{$1});$DBX}gmx;
  
      # Dump an unlabelled expression (the expression is used as the label)...
      s{ ^ $hws* $intro $hws* (.*) $optcolon $hws* $ }
       {Smart::Comments::_Dump(pref=>q{$1:},var=>Smart::Comments::_quiet_eval(q{[$1]}));$DBX}gmx;
  
      # An empty comment dumps an empty line...
      s{ ^ $hws* $intro [ \t]+ $ }
       {warn qq{\n};}gmx;
  
      # Anything else is a literal string to be printed...
      s{ ^ $hws* $intro $hws* (.*) }
       {Smart::Comments::_Dump(pref=>q{$1});$DBX}gmx;
  };
  
  sub _quiet_eval {
      local $SIG{__WARN__} = sub{};
      return scalar eval shift;
  }
  
  sub _uniq { my %seen; grep { !$seen{$_}++ } @_ }
  
  # Converts an assertion to the equivalent Perl code...
  sub _decode_assert {
      my ($assertion, $fatal) = @_;
  
      # Choose the right signalling mechanism...
      $fatal = $fatal ? 'die "\n"' : 'warn "\n"';
  
      my $dump = 'Smart::Comments::_Dump';
      use Text::Balanced qw(extract_variable extract_multiple);
  
      # Extract variables from assertion and enreference any arrays or hashes...
      my @vars = map { /^$hws*[%\@]/ ? "$dump(pref=>q{    $_ was:},var=>[\\$_], nonl=>1);"
                                     : "$dump(pref=>q{    $_ was:},var=>[$_],nonl=>1);"
                     }
                  _uniq extract_multiple($assertion, [\&extract_variable], undef, 1);
  
      # Generate the test-and-report code...
      return qq{unless($assertion){warn "\\n", q{### $assertion was not true};@vars; $fatal}};
  }
  
  # Generate progress-bar code for a Perlish for loop...
  my $ID = 0;
  sub _decode_for {
      my ($for, $range, $mesg) = @_;
  
      # Give the loop a unique ID...
      $ID++;
  
      # Rewrite the loop with a progress bar as its first statement...
      return "my \$not_first__$ID;$for (my \@SmartComments__range__$ID = $range) { Smart::Comments::_for_progress(qq{$mesg}, \$not_first__$ID, \\\@SmartComments__range__$ID);";
  }
  
  # Generate progress-bar code for a Perlish while loop...
  sub _decode_while {
      my ($while, $mesg) = @_;
  
      # Give the loop a unique ID...
      $ID++;
  
      # Rewrite the loop with a progress bar as its first statement...
      return "my \$not_first__$ID;$while { Smart::Comments::_while_progress(qq{$mesg}, \\\$not_first__$ID);";
  }
  
  # Generate approximate time descriptions...
  sub _desc_time {
      my ($seconds) = @_;
      my $hours = int($seconds/3600);    $seconds -= 3600*$hours;
      my $minutes = int($seconds/60);    $seconds -= 60*$minutes;
      my $remaining;
  
      # Describe hours to the nearest half-hour (and say how close to it)...
      if ($hours) {
          $remaining =
            $minutes < 5   ? "about $hours hour".($hours==1?"":"s")
          : $minutes < 25  ? "less than $hours.5 hours"
          : $minutes < 35  ? "about $hours.5 hours"
          : $minutes < 55  ? "less than ".($hours+1)." hours"
          :                  "about ".($hours+1)." hours";
      }
      # Describe minutes to the nearest minute
      elsif ($minutes) {
          $remaining = "about $minutes minutes";
          chop $remaining if $minutes == 1;
      }
      # Describe tens of seconds to the nearest ten seconds...
      elsif ($seconds > 10) { 
          $seconds = int(($seconds+5)/10);
          $remaining = "about ${seconds}0 seconds";
      }
      # Never be more accurate than ten seconds...
      else {  
          $remaining = "less than 10 seconds";
      }
      return $remaining;
  }
  
  # Update the moving average of a series given the newest measurement...
  my %started;
  my %moving;
  sub _moving_average {
      my ($context, $next) = @_;
      my $moving = $moving{$context} ||= [];
      push @$moving, $next;
      if (@$moving >= $average_over) {
          splice @$moving, 0, $#$moving-$average_over;
      }
      return sum(@$moving)/@$moving;
  }
  
  # Recognize progress bars...
  my @progress_pats = (
     #    left     extending                 end marker of bar      right
     #    anchor   bar ("fill")               |    gap after bar    anchor
     #    ======   =======================   === =================  ====
     qr{^(\s*.*?) (\[\]\[\])                 ()    \s*               (\S?.*)}x,
     qr{^(\s*.*?) (\(\)\(\))                 ()    \s*               (\S?.*)}x,
     qr{^(\s*.*?) (\{\}\{\})                 ()    \s*               (\S?.*)}x,
     qr{^(\s*.*?) (\<\>\<\>)                 ()    \s*               (\S?.*)}x,
     qr{^(\s*.*?) (?>(\S)\2{$minfillreps,})  (\S+) \s{$minfillreps,} (\S.*)}x,
     qr{^(\s*.*?) (?>(\S)\2{$minfillreps,})  ()    \s{$minfillreps,} (\S.*)}x,
     qr{^(\s*.*?) (?>(\S)\2{$minfillreps,})  (\S*)                   (?=\s*$)}x,
     qr{^(\s*.*?) ()                         ()                      () \s*$ }x,
  );
  
  # Clean up components of progress bar (inserting defaults)...
  sub _prog_pat {
      for my $pat (@progress_pats) {
          $_[0] =~ $pat or next;
          return ($1, $2||"", $3||"", $4||""); 
      }
      return;
  }
  
  # State information for various progress bars...
  my (%count, %max, %prev_elapsed, %prev_fraction, %showing);
  
  # Animate the progress bar of a for loop...
  sub _for_progress {
      my ($mesg, $not_first, $data) = @_;
      my ($at, $max, $elapsed, $remaining, $fraction);
  
      # Update progress bar...
      if ($not_first) {
          # One more iteration towards the maximum...
          $at = ++$count{$data};
          $max = $max{$data};
  
          # How long now (both absolute and relative)...
          $elapsed = time - $started{$data};
          $fraction = $max>0 ? $at/$max : 1;
  
          # How much change occurred...
          my $motion = $fraction - $prev_fraction{$data};
  
          # Don't update if count wrapped (unlikely) or if finished
          # or if no visible change...
          return unless $not_first < 0
                     || $at == $max
                     || $motion > $forupdatequantum;
  
          # Guestimate how long still to go...
          $remaining = _moving_average $data,
                                      $fraction ? $elapsed/$fraction-$elapsed
                                                : 0;
      }
      # If first iteration...
      else {
          # Start at the beginning...
          $at = $count{$data} = 0;
  
          # Work out where the end will be...
          $max = $max{$data} = $#$data;
  
          # Start the clock...
          $started{$data} = time;
          $elapsed = 0;
          $fraction = 0;
  
          # After which, it will no longer be the first iteration.
          $_[1] = 1;  # $not_first
      }
  
      # Remember the previous increment fraction...
      $prev_fraction{$data} = $fraction;
  
      # Now draw the progress bar (if it's a valid one)...
      if (my ($left, $fill, $leader, $right) = _prog_pat($mesg)) {
          # Insert the percentage progress in place of a '%'...
          s/%/int(100*$fraction).'%'/ge for ($left, $leader, $right);
  
          # Work out how much space is available for the bar itself...
          my $fillwidth = $showwidth - length($left) - length($right);
  
          # But no less than the prespecified minimum please...
          $fillwidth = $minfillwidth if $fillwidth < $minfillwidth;
  
          # Make enough filler...
          my $totalfill = $fill x $fillwidth;
  
          # How big is the end of the bar...
          my $leaderwidth = length($leader);
  
          # Truncate where?
          my $fillend = $at==$max ? $fillwidth 
                      :             $fillwidth*$fraction-$leaderwidth;
          $fillend = 0 if $fillend < 0;
  
          # Now draw the bar, using carriage returns to overwrite it...
          print STDERR "\r", " "x$maxwidth,
                       "\r", $left,
                       sprintf("%-${fillwidth}s",
                                 substr($totalfill, 0, $fillend)
                               . $leader),
                       $right;
  
          # Work out whether to show an ETA estimate...
          if ($elapsed >= $showstarttime &&
              $at < $max &&
              ($showing{$data} || $remaining && $remaining >= $showmaxtime)
          ) {
              print STDERR "  (", _desc_time($remaining), " remaining)";
              $showing{$data} = 1;
          }
  
          # Close off the line, if we're finished...
          print STDERR "\r", " "x$maxwidth, "\n" if $at >= $max;
      }
  }
  
  my %shown;
  my $prev_length = -1;
  
  # Animate the progress bar of a while loop...
  sub _while_progress {
      my ($mesg, $not_first_ref) = @_;
      my $at;
  
      # If we've looped this one before, recover the current iteration count...
      if ($$not_first_ref) {
          $at = ++$count{$not_first_ref};
      }
      # Otherwise set the iteration count to zero...
      else {
          $at = $count{$not_first_ref} = 0;
          $$not_first_ref = 1;
      }
  
      # Extract the components of the progress bar...
      if (my ($left, $fill, $leader, $right) = _prog_pat($mesg)) {
          # Replace any '%' with the current iteration count...
          s/%/$at/ge for ($left, $leader, $right);
  
          # How much space is there for the progress bar?
          my $fillwidth = $showwidth - length($left) - length($right);
  
          # Make it at least the prespecified minimum amount...
          $fillwidth = $minfillwidth if $fillwidth < $minfillwidth;
  
          # How big is the end of the bar?
          my $leaderwidth = length($leader);
  
          # How big does that make the bar itself (use reciprocal growth)...
          my $length = int(($fillwidth-$leaderwidth)
                             *(1-$whilerate/($whilerate+$at)));
  
          # Don't update if the picture would look the same...
          return
              if length $fill && $prev_length == $length;
  
          # Otherwise, remember where we got to...
          $prev_length = $length;
  
          # And print the bar...
          print STDERR "\r", " "x$maxwidth,
                       "\r", $left,
                       sprintf("%-${fillwidth}s", substr($fill x $fillwidth, 0, $length) . $leader),
                       $right;
      }
  }
  
  # Vestigal (I think)...
  #sub Assert {
  #   my %arg = @_;
  #   return unless $arg{pass}
  #}
  
  use Data::Dumper 'Dumper';
  
  # Dump a variable and then reformat the resulting string more prettily...
  my $prev_STDOUT = 0;
  my $prev_STDERR = 0;
  my %prev_caller = ( file => q{}, line => 0 );
  
  sub _Dump {
      my %args = @_;
      my ($pref, $varref, $nonl) = @args{qw(pref var nonl)};
  
      # Handle timestamps and spacestamps...
      my (undef, $file, $line) = caller;
      $pref =~ s/<(?:now|time|when)>/scalar localtime()/ge;
      $pref =~ s/<(?:here|place|where)>/"$file", line $line/g;
      $pref =~ s/<(?:file)>/$file/g;
      $pref =~ s/<(?:line)>/$line/g;
  
      # Add a newline?
      my @caller = caller;
      my $spacer_required
          =  $prev_STDOUT != tell(*STDOUT)
          || $prev_STDERR != tell(*STDERR)
          || $prev_caller{file} ne $caller[1]
          || $prev_caller{line} != $caller[2]-1;
      $spacer_required &&= !$nonl;
      @prev_caller{qw<file line>} = @caller[1,2];
  
      # Handle a prefix with no actual variable...
      if ($pref && !defined $varref) {
          $pref =~ s/:$//;
          print STDERR "\n" if $spacer_required;
          warn "### $pref\n";
          $prev_STDOUT = tell(*STDOUT);
          $prev_STDERR = tell(*STDERR);
          return;
      }
  
      # Set Data::Dumper up for a tidy dump and do the dump...
      local $Data::Dumper::Quotekeys = 0;
      local $Data::Dumper::Sortkeys  = 1;
      local $Data::Dumper::Indent    = 2;
      my $dumped = Dumper $varref;
  
      # Clean up the results...
      $dumped =~ s/\$VAR1 = \[\n//;
      $dumped =~ s/\s*\];\s*$//;
      $dumped =~ s/\A(\s*)//;
  
      # How much to shave off and put back on each line...
      my $indent  = length $1;
      my $outdent = " " x (length($pref) + 1);
  
      # Report "inside-out" and "flyweight" objects more cleanly...
      $dumped =~ s{bless[(] do[{]\\[(]my \$o = undef[)][}], '([^']+)' [)]}
                  {<Opaque $1 object (blessed scalar)>}g;
  
      # Adjust the indents...
      $dumped =~ s/^[ ]{$indent}([ ]*)/### $outdent$1/gm;
  
      # Print the message...
      print STDERR "\n" if $spacer_required;
      warn "### $pref $dumped\n";
      $prev_STDERR = tell(*STDERR);
      $prev_STDOUT = tell(*STDOUT);
  }
  
  1; # Magic true value required at end of module
  __END__
  
  =head1 NAME
  
  Smart::Comments - Comments that do more than just sit there
  
  
  =head1 VERSION
  
  This document describes Smart::Comments version 1.000005
  
  
  =head1 SYNOPSIS
  
      use Smart::Comments;
  
      my $var = suspect_value();
  
      ### $var
  
      ### got: $var
  
      ### Now computing value...
  
      # and when looping:
  
      for my $big_num (@big_nums) {  ### Factoring...      done
          factor($big_num);
      }
  
      while ($error > $tolerance) {  ### Refining--->      done
          refine_approximation()
      }
  
      for (my $i=0; $i<$MAX_INT; $i++) {   ### Working===[%]     done
          do_something_expensive_with($i);
      }
  
    
  =head1 DESCRIPTION
  
  Smart comments provide an easy way to insert debugging and tracking code
  into a program. They can report the value of a variable, track the
  progress of a loop, and verify that particular assertions are true.
  
  Best of all, when you're finished debugging, you don't have to remove them.
  Simply commenting out the C<use Smart::Comments> line turns them back into
  regular comments. Leaving smart comments in your code is smart because if you
  needed them once, you'll almost certainly need them again later.
  
  
  =head1 INTERFACE 
  
  All smart comments start with three (or more) C<#> characters. That is,
  they are regular C<#>-introduced comments whose first two (or more)
  characters are also C<#>'s.
  
  =head2 Using the Module
  
  The module is loaded like any other:
  
      use Smart::Comments;
  
  When loaded it filters the remaining code up to the next:
  
      no Smart::Comments;
  
  directive, replacing any smart comments with smart code that implements the
  comments behaviour.
  
  If you're debugging an application you can also invoke it with the module from
  the command-line:
  
      perl -MSmart::Comments $application.pl
  
  Of course, this only enables smart comments in the application file itself,
  not in any modules that the application loads.
  
  You can also specify particular levels of smartness, by including one or more
  markers as arguments to the C<use>:
  
      use Smart::Comments '###', '####';
  
  These arguments tell the module to filter only those comments that start with
  the same number of C<#>'s. So the above C<use> statement would "activate" any
  smart comments of the form:
  
      ###   Smart...
  
      ####  Smarter...
  
  but not those of the form:
  
      ##### Smartest...
  
  This facility is useful for differentiating progress bars (see
  L<Progress Bars>), which should always be active, from debugging
  comments (see L<Debugging via Comments>), which should not:
  
      #### Debugging here...
  
      for (@values) {         ### Progress: 0...  100
          do_stuff();
      }
  
  Note that, for simplicity, all smart comments described below will be
  written with three C<#>'s; in all such cases, any number of C<#>'s
  greater than three could be used instead.
  
  
  =head2 Debugging via Comments
  
  The simplest way to use smart comments is for debugging. The module
  supports the following forms, all of which print to C<STDERR>:
  
  =over
  
  =item C<< ### LABEL : EXPRESSION >>
  
  The LABEL is any sequence of characters up to the first colon. 
  The EXPRESSION is any valid Perl expression, including a simple variable.
  When active, the comment prints the label, followed by the value of the
  expression. For example:
  
      ### Expected: 2 * $prediction
      ###      Got: $result
  
  prints:
  
      ### Expected: 42
      ###      Got: 13
  
  
  =item C<< ### EXPRESSION >>
  
  The EXPRESSION is any valid Perl expression, including a simple
  variable. When active, the comment prints the expression, followed by
  the value of the expression. For example:
  
      ### 2 * $prediction
      ### $result
  
  prints:
  
      ### 2 * $prediction: 42
      ### $result: 13
  
  
  =item C<< ### TEXT... >>
  
  The TEXT is any sequence of characters that end in three dots.
  When active, the comment just prints the text, including the dots. For
  example:
  
      ### Acquiring data...
  
      $data = get_data();
  
      ### Verifying data...
  
      verify_data($data);
  
      ### Assimilating data...
  
      assimilate_data($data);
  
      ### Tired now, having a little lie down...
  
      sleep 900;
  
  would print:
  
  
      ### Acquiring data...
  
      ### Verifying data...
  
      ### Assimilating data...
  
      ### Tired now, having a little lie down...
  
  as each phase commenced. This is particularly useful for tracking down
  precisely where a bug is occurring. It is also useful in non-debugging
  situations, especially when batch processing, as a simple progress
  feedback mechanism.
  
  Within a textual smart comment you can use the special sequence C<<
  <now> >> (or C<< <time> >> or C<< <when> >>) which is replaced with a
  timestamp. For example:
  
      ### [<now>] Acquiring data...
  
  would produce something like:
  
      ### [Fri Nov 18 15:11:15 EST 2005] Acquiring data...
  
  There are also "spacestamps": C<< <here> >>
  (or C<< <loc> >> or C<< <place> >> or C<< <where> >>):
  
      ### Acquiring data at <loc>...
  
  to produce something like:
  
      ### Acquiring data at "demo.pl", line 7...
  
  You can also request just the filename (C<< <file> >>) or just the line
  number (C<< <line> >>) to get finer control over formatting:
  
      ### Acquiring data at <file>[<line>]...
  
  and produce something like:
  
      ### Acquiring data at demo.pl[7]...
  
  You can, of course, use any combination of stamps in the one comment.
  
  =back
  
  =head2 Checks and Assertions via Comments
  
  =over
  
  =item C<< ### require: BOOLEAN_EXPR >>
  
  =item C<< ### assert:  BOOLEAN_EXPR >>
  
  =item C<< ### ensure:  BOOLEAN_EXPR >>
  
  =item C<< ### insist:  BOOLEAN_EXPR >>
  
  These four are synonyms for the same behaviour. The comment evaluates
  the expression in a boolean context. If the result is true, nothing more
  is done. If the result is false, the comment throws an exception listing
  the expression, the fact that it failed, and the values of any variables
  used in the expression.
  
  For example, given the following assertion:
  
      ### require: $min < $result && $result < $max
  
  if the expression evaluated false, the comment would die with the following
  message:
   
      ### $min < $result && $result < $max was not true at demo.pl line 86.
      ###     $min was: 7
      ###     $result was: 1000004
      ###     $max was: 99
  
  
  =item C<< ### check:   BOOLEAN_EXPR >>
  
  =item C<< ### confirm: BOOLEAN_EXPR >>
  
  =item C<< ### verify:  BOOLEAN_EXPR >>
  
  These three are synonyms for the same behaviour. The comment evaluates
  the expression in a boolean context. If the result is true, nothing more
  is done. If the result is false, the comment prints a warning message
  listing the expression, the fact that it failed, and the values of any
  variables used in the expression.
  
  The effect is identical to that of the four assertions listed earlier, except
  that C<warn> is used instead of C<die>.
  
  =back
  
  =head2 Progress Bars
  
  You can put a smart comment on the same line as any of the following
  types of Perl loop:
  
      foreach my VAR ( LIST ) {       ### Progressing...   done
  
      for my VAR ( LIST ) {           ### Progressing...   done
  
      foreach ( LIST ) {              ### Progressing...   done
  
      for ( LIST ) {                  ### Progressing...   done
  
      while (CONDITION) {             ### Progressing...   done
  
      until (CONDITION) {             ### Progressing...   done
  
      for (INIT; CONDITION; INCR) {   ### Progressing...   done
  
  
  In each case, the module animates the comment, causing the dots to
  extend from the left text, reaching the right text on the last
  iteration. For "open ended" loops (like C<while> and C-style C<for>
  loops), the dots will never reach the right text and their progress
  slows down as the number of iterations increases.
  
  For example, a smart comment like:
  
      for (@candidates) {       ### Evaluating...     done
  
  would be animated is the following sequence (which would appear
  sequentially on a single line, rather than on consecutive lines):
  
      Evaluating                          done
  
      Evaluating......                    done
  
      Evaluating.............             done
  
      Evaluating...................       done
  
      Evaluating..........................done
  
  The module animates the first sequence of three identical characters in
  the comment, provided those characters are followed by a gap of at least
  two whitespace characters. So you can specify different types of
  progress bars. For example:
  
      for (@candidates) {       ### Evaluating:::     done
  
  or:
  
      for (@candidates) {       ### Evaluating===     done
  
  or:
  
      for (@candidates) {       ### Evaluating|||     done
  
  If the characters to be animated are immediately followed by other
  non-whitespace characters before the gap, then those other non-whitespace
  characters are used as an "arrow head" or "leader" and are pushed right
  by the growing progress bar. For example:
  
      for (@candidates) {       ### Evaluating===|    done
  
  would animate like so:
  
      Evaluating|                         done
  
      Evaluating=====|                    done
  
      Evaluating============|             done
  
      Evaluating==================|       done
  
      Evaluating==========================done
  
  If a percentage character (C<%>) appears anywhere in the comment, it is
  replaced by the percentage completion. For example:
  
      for (@candidates) {       ### Evaluating [===|    ] % done
  
  animates like so:
  
      Evaluating [|                ]   0% done
  
      Evaluating [===|             ]  25% done
  
      Evaluating [========|        ]  50% done
  
      Evaluating [============|    ]  75% done
  
      Evaluating [=================] 100% done
  
  If the C<%> is in the "arrow head" it moves with the progress bar. For
  example:
  
      for (@candidates) {       ### Evaluating |===[%]    |
  
  would be animated like so:
  
      Evaluating |[0%]                       |
  
      Evaluating |=[25%]                     |
  
      Evaluating |========[50%]              |
  
      Evaluating |===============[75%]       |
  
      Evaluating |===========================|
  
  For "open-ended" loops, the percentage completion is unknown, so the module
  replaces each C<%> with the current iteration count. For example:
  
      while ($next ne $target) {       ### Evaluating |===[%]    |
  
  would animate like so:
  
      Evaluating |[0]                        |
  
      Evaluating |=[2]                       |
  
      Evaluating |==[3]                      |
  
      Evaluating |===[5]                     |
  
      Evaluating |====[7]                    |
  
      Evaluating |=====[8]                   |
  
      Evaluating |======[11]                 |
  
  Note that the non-sequential numbering in the above example is a result
  of the "hurry up and slow down" algorithm that prevents open-ended
  loops from ever reaching the right-hand side.
  
  As a special case, if the progress bar is drawn as two pairs of
  identical brackets:
  
      for (@candidates) {       ### Evaluating: [][]
  
      for (@candidates) {       ### Evaluating: {}{}
  
      for (@candidates) {       ### Evaluating: ()()
  
      for (@candidates) {       ### Evaluating: <><>
  
  Then the bar grows by repeating bracket pairs:
  
      Evaluating: [
  
      Evaluating: []
  
      Evaluating: [][
  
      Evaluating: [][]
  
      Evaluating: [][][
  
  etc.
  
  Finally, progress bars don't have to have an animated component. They
  can just report the loop's progress numerically:
  
      for (@candidates) {       ### Evaluating (% done)
  
  which would animate (all of the same line):
  
      Evaluating (0% done)
  
      Evaluating (25% done)
  
      Evaluating (50% done)
  
      Evaluating (75% done)
  
      Evaluating (100% done)
  
  
  =head2 Time-Remaining Estimates
  
  When a progress bar is used with a C<for> loop, the module tracks how long
  each iteration is taking and makes an estimate of how much time will be
  required to complete the entire loop.
  
  Normally this estimate is not shown, unless the estimate becomes large
  enough to warrant informing the user. Specifically, the estimate will
  be shown if, after five seconds, the time remaining exceeds ten seconds.
  In other words, a time-remaining estimate is shown if the module
  detects a C<for> loop that is likely to take more than 15 seconds in
  total. For example:
  
      for (@seven_samurai) {      ### Fighting: [|||    ]
          fight();
          sleep 5;
      }
  
  would be animated like so:
  
      Fighting: [                           ]
  
      Fighting: [||||                       ]
  
      Fighting: [|||||||||                  ]  (about 20 seconds remaining)
  
      Fighting: [||||||||||||||             ]  (about 20 seconds remaining)
  
      Fighting: [||||||||||||||||||         ]  (about 10 seconds remaining)
  
      Fighting: [|||||||||||||||||||||||    ]  (less than 10 seconds remaining)
  
      Fighting: [|||||||||||||||||||||||||||]
  
  The precision of the reported time-remaining estimate is deliberately vague,
  mainly to prevent it being annoyingly wrong.
  
  
  =head1 DIAGNOSTICS
  
  In a sense, everything this module does is a diagnostic. All comments that
  print anything, print it to C<STDERR>.
  
  However, the module itself has only one diagnostic:
  
  =over
  
  =item C<< Incomprehensible arguments: %s in call to 'use Smart::Comments >>
  
  You loaded the module and passed it an argument that wasn't three-or-
  more C<#>'s. Arguments like C<'###'>, C<'####'>, C<'#####'>, etc. are
  the only ones that the module accepts.
  
  =back
  
  =head1 CONFIGURATION AND ENVIRONMENT
  
  Smart::Comments can make use of an environment variable from your shell:
  C<Smart_Comments>. This variable can be specified either with a
  true/false value (i.e. 1 or 0) or with the same arguments as may be
  passed on the C<use> line when loading the module (see L<"INTERFACE">).
  The following table summarizes the behaviour:
  
           Value of
      $ENV{Smart_Comments}          Equivalent Perl
  
              1                     use Smart::Comments;
              0                      no Smart::Comments;
          '###:####'                use Smart::Comments qw(### ####);
          '### ####'                use Smart::Comments qw(### ####);
  
  To enable the C<Smart_Comments> environment variable, you need to load the
  module with the C<-ENV> flag:
  
      use Smart::Comments -ENV;
  
  Note that you can still specify other arguments in the C<use> statement:
  
      use Smart::Comments -ENV, qw(### #####);
  
  In this case, the contents of the environment variable replace the C<-ENV> in
  the argument list.
  
  
  =head1 DEPENDENCIES
  
  The module requires the following modules:
  
  =over
  
  =item *
  
  Filter::Simple
  
  =item *
  
  version.pm
  
  =item *
  
  List::Util
  
  =item *
  
  Data::Dumper
  
  =item *
  
  Text::Balanced
  
  =back
  
  =head1 INCOMPATIBILITIES
  
  None reported. This module is probably even relatively safe with other
  Filter::Simple modules since it is very specific and limited in what
  it filters.
  
  
  =head1 BUGS AND LIMITATIONS
  
  No bugs have been reported.
  
  This module has the usual limitations of source filters (i.e. it looks
  smarter than it is).
  
  Please report any bugs or feature requests to
  C<bug-smart-comments@rt.cpan.org>, or through the web interface at
  L<http://rt.cpan.org>.
  
  
  =head1 AUTHOR
  
  Damian Conway  C<< <DCONWAY@cpan.org> >>
  
  
  =head1 LICENCE AND COPYRIGHT
  
  Copyright (c) 2005, Damian Conway C<< <DCONWAY@cpan.org> >>. All rights reserved.
  
  This module is free software; you can redistribute it and/or
  modify it under the same terms as Perl itself.
  
  
  =head1 DISCLAIMER OF WARRANTY
  
  BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
  FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
  OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
  PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
  EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
  ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
  YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
  NECESSARY SERVICING, REPAIR, OR CORRECTION.
  
  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
  WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
  REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE
  LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL,
  OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE
  THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
  RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
  FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
  SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
  SUCH DAMAGES.
SMART_COMMENTS

$fatpacked{"darwin-2level/List/Util.pm"} = <<'DARWIN-2LEVEL_LIST_UTIL';
  # List::Util.pm
  #
  # Copyright (c) 1997-2009 Graham Barr <gbarr@pobox.com>. All rights reserved.
  # This program is free software; you can redistribute it and/or
  # modify it under the same terms as Perl itself.
  #
  # Maintained since 2013 by Paul Evans <leonerd@leonerd.org.uk>
  
  package List::Util;
  
  use strict;
  require Exporter;
  
  our @ISA        = qw(Exporter);
  our @EXPORT_OK  = qw(
    all any first min max minstr maxstr none notall product reduce sum sum0 shuffle
    pairmap pairgrep pairfirst pairs pairkeys pairvalues
  );
  our $VERSION    = "1.35";
  our $XS_VERSION = $VERSION;
  $VERSION    = eval $VERSION;
  
  require XSLoader;
  XSLoader::load('List::Util', $XS_VERSION);
  
  sub import
  {
    my $pkg = caller;
  
    # (RT88848) Touch the caller's $a and $b, to avoid the warning of
    #   Name "main::a" used only once: possible typo" warning
    no strict 'refs';
    ${"${pkg}::a"} = ${"${pkg}::a"};
    ${"${pkg}::b"} = ${"${pkg}::b"};
  
    goto &Exporter::import;
  }
  
  1;
  
  __END__
  
  =head1 NAME
  
  List::Util - A selection of general-utility list subroutines
  
  =head1 SYNOPSIS
  
      use List::Util qw(first max maxstr min minstr reduce shuffle sum);
  
  =head1 DESCRIPTION
  
  C<List::Util> contains a selection of subroutines that people have
  expressed would be nice to have in the perl core, but the usage would
  not really be high enough to warrant the use of a keyword, and the size
  so small such that being individual extensions would be wasteful.
  
  By default C<List::Util> does not export any subroutines.
  
  =cut
  
  =head1 LIST-REDUCTION FUNCTIONS
  
  The following set of functions all reduce a list down to a single value.
  
  =cut
  
  =head2 reduce BLOCK LIST
  
  Reduces LIST by calling BLOCK, in a scalar context, multiple times,
  setting C<$a> and C<$b> each time. The first call will be with C<$a>
  and C<$b> set to the first two elements of the list, subsequent
  calls will be done by setting C<$a> to the result of the previous
  call and C<$b> to the next element in the list.
  
  Returns the result of the last call to BLOCK. If LIST is empty then
  C<undef> is returned. If LIST only contains one element then that
  element is returned and BLOCK is not executed.
  
  The following examples all demonstrate how C<reduce> could be used to
  implement the other list-reduction functions in this module. (They are
  not in fact implemented like this, but instead in a more efficient
  manner in individual C functions).
  
      $foo = reduce { defined($a)            ? $a :
                      $code->(local $_ = $b) ? $b :
                                               undef } undef, @list # first
  
      $foo = reduce { $a > $b ? $a : $b } 1..10       # max
      $foo = reduce { $a gt $b ? $a : $b } 'A'..'Z'   # maxstr
      $foo = reduce { $a < $b ? $a : $b } 1..10       # min
      $foo = reduce { $a lt $b ? $a : $b } 'aa'..'zz' # minstr
      $foo = reduce { $a + $b } 1 .. 10               # sum
      $foo = reduce { $a . $b } @bar                  # concat
  
      $foo = reduce { $a || $code->(local $_ = $b) } 0, @bar   # any
      $foo = reduce { $a && $code->(local $_ = $b) } 1, @bar   # all
      $foo = reduce { $a && !$code->(local $_ = $b) } 1, @bar  # none
      $foo = reduce { $a || !$code->(local $_ = $b) } 0, @bar  # notall
         # Note that these implementations do not fully short-circuit
  
  If your algorithm requires that C<reduce> produce an identity value, then
  make sure that you always pass that identity value as the first argument to prevent
  C<undef> being returned
  
    $foo = reduce { $a + $b } 0, @values;             # sum with 0 identity value
  
  The remaining list-reduction functions are all specialisations of this
  generic idea.
  
  =head2 any BLOCK LIST
  
  Similar to C<grep> in that it evaluates BLOCK setting C<$_> to each element
  of LIST in turn. C<any> returns true if any element makes the BLOCK return a
  true value. If BLOCK never returns true or LIST was empty then it returns
  false.
  
  Many cases of using C<grep> in a conditional can be written using C<any>
  instead, as it can short-circuit after the first true result.
  
      if( any { length > 10 } @strings ) {
          # at least one string has more than 10 characters
      }
  
  =head2 all BLOCK LIST
  
  Similar to C<any>, except that it requires all elements of the LIST to make
  the BLOCK return true. If any element returns false, then it returns true. If
  the BLOCK never returns false or the LIST was empty then it returns true.
  
  =head2 none BLOCK LIST
  
  =head2 notall BLOCK LIST
  
  Similar to C<any> and C<all>, but with the return sense inverted. C<none>
  returns true if no value in the LIST causes the BLOCK to return true, and
  C<notall> returns true if not all of the values do.
  
  =head2 first BLOCK LIST
  
  Similar to C<grep> in that it evaluates BLOCK setting C<$_> to each element
  of LIST in turn. C<first> returns the first element where the result from
  BLOCK is a true value. If BLOCK never returns true or LIST was empty then
  C<undef> is returned.
  
      $foo = first { defined($_) } @list    # first defined value in @list
      $foo = first { $_ > $value } @list    # first value in @list which
                                            # is greater than $value
  
  =head2 max LIST
  
  Returns the entry in the list with the highest numerical value. If the
  list is empty then C<undef> is returned.
  
      $foo = max 1..10                # 10
      $foo = max 3,9,12               # 12
      $foo = max @bar, @baz           # whatever
  
  =head2 maxstr LIST
  
  Similar to C<max>, but treats all the entries in the list as strings
  and returns the highest string as defined by the C<gt> operator.
  If the list is empty then C<undef> is returned.
  
      $foo = maxstr 'A'..'Z'          # 'Z'
      $foo = maxstr "hello","world"   # "world"
      $foo = maxstr @bar, @baz        # whatever
  
  =head2 min LIST
  
  Similar to C<max> but returns the entry in the list with the lowest
  numerical value. If the list is empty then C<undef> is returned.
  
      $foo = min 1..10                # 1
      $foo = min 3,9,12               # 3
      $foo = min @bar, @baz           # whatever
  
  =head2 minstr LIST
  
  Similar to C<min>, but treats all the entries in the list as strings
  and returns the lowest string as defined by the C<lt> operator.
  If the list is empty then C<undef> is returned.
  
      $foo = minstr 'A'..'Z'          # 'A'
      $foo = minstr "hello","world"   # "hello"
      $foo = minstr @bar, @baz        # whatever
  
  =head2 product LIST
  
  Returns the product of all the elements in LIST. If LIST is empty then C<1> is
  returned.
  
      $foo = product 1..10            # 3628800
      $foo = product 3,9,12           # 324
  
  =head2 sum LIST
  
  Returns the sum of all the elements in LIST. If LIST is empty then
  C<undef> is returned.
  
      $foo = sum 1..10                # 55
      $foo = sum 3,9,12               # 24
      $foo = sum @bar, @baz           # whatever
  
  =head2 sum0 LIST
  
  Similar to C<sum>, except this returns 0 when given an empty list, rather
  than C<undef>.
  
  =cut
  
  =head1 KEY/VALUE PAIR LIST FUNCTIONS
  
  The following set of functions, all inspired by L<List::Pairwise>, consume
  an even-sized list of pairs. The pairs may be key/value associations from a
  hash, or just a list of values. The functions will all preserve the original
  ordering of the pairs, and will not be confused by multiple pairs having the
  same "key" value - nor even do they require that the first of each pair be a
  plain string.
  
  =cut
  
  =head2 pairgrep BLOCK KVLIST
  
  Similar to perl's C<grep> keyword, but interprets the given list as an
  even-sized list of pairs. It invokes the BLOCK multiple times, in scalar
  context, with C<$a> and C<$b> set to successive pairs of values from the
  KVLIST.
  
  Returns an even-sized list of those pairs for which the BLOCK returned true
  in list context, or the count of the B<number of pairs> in scalar context.
  (Note, therefore, in scalar context that it returns a number half the size
  of the count of items it would have returned in list context).
  
      @subset = pairgrep { $a =~ m/^[[:upper:]]+$/ } @kvlist
  
  Similar to C<grep>, C<pairgrep> aliases C<$a> and C<$b> to elements of the
  given list. Any modifications of it by the code block will be visible to
  the caller.
  
  =head2 pairfirst BLOCK KVLIST
  
  Similar to the C<first> function, but interprets the given list as an
  even-sized list of pairs. It invokes the BLOCK multiple times, in scalar
  context, with C<$a> and C<$b> set to successive pairs of values from the
  KVLIST.
  
  Returns the first pair of values from the list for which the BLOCK returned
  true in list context, or an empty list of no such pair was found. In scalar
  context it returns a simple boolean value, rather than either the key or the
  value found.
  
      ( $key, $value ) = pairfirst { $a =~ m/^[[:upper:]]+$/ } @kvlist
  
  Similar to C<grep>, C<pairfirst> aliases C<$a> and C<$b> to elements of the
  given list. Any modifications of it by the code block will be visible to
  the caller.
  
  =head2 pairmap BLOCK KVLIST
  
  Similar to perl's C<map> keyword, but interprets the given list as an
  even-sized list of pairs. It invokes the BLOCK multiple times, in list
  context, with C<$a> and C<$b> set to successive pairs of values from the
  KVLIST.
  
  Returns the concatenation of all the values returned by the BLOCK in list
  context, or the count of the number of items that would have been returned
  in scalar context.
  
      @result = pairmap { "The key $a has value $b" } @kvlist
  
  Similar to C<map>, C<pairmap> aliases C<$a> and C<$b> to elements of the
  given list. Any modifications of it by the code block will be visible to
  the caller.
  
  =head2 pairs KVLIST
  
  A convenient shortcut to operating on even-sized lists of pairs, this
  function returns a list of ARRAY references, each containing two items from
  the given list. It is a more efficient version of
  
      pairmap { [ $a, $b ] } KVLIST
  
  It is most convenient to use in a C<foreach> loop, for example:
  
      foreach ( pairs @KVLIST ) {
         my ( $key, $value ) = @$_;
         ...
      }
  
  =head2 pairkeys KVLIST
  
  A convenient shortcut to operating on even-sized lists of pairs, this
  function returns a list of the the first values of each of the pairs in
  the given list. It is a more efficient version of
  
      pairmap { $a } KVLIST
  
  =head2 pairvalues KVLIST
  
  A convenient shortcut to operating on even-sized lists of pairs, this
  function returns a list of the the second values of each of the pairs in
  the given list. It is a more efficient version of
  
      pairmap { $b } KVLIST
  
  =cut
  
  =head1 OTHER FUNCTIONS
  
  =cut
  
  =head2 shuffle LIST
  
  Returns the elements of LIST in a random order
  
      @cards = shuffle 0..51      # 0..51 in a random order
  
  =cut
  
  =head1 KNOWN BUGS
  
  With perl versions prior to 5.005 there are some cases where reduce
  will return an incorrect result. This will show up as test 7 of
  reduce.t failing.
  
  =head1 SUGGESTED ADDITIONS
  
  The following are additions that have been requested, but I have been reluctant
  to add due to them being very simple to implement in perl
  
    # How many elements are true
  
    sub true { scalar grep { $_ } @_ }
  
    # How many elements are false
  
    sub false { scalar grep { !$_ } @_ }
  
  =head1 SEE ALSO
  
  L<Scalar::Util>, L<List::MoreUtils>
  
  =head1 COPYRIGHT
  
  Copyright (c) 1997-2007 Graham Barr <gbarr@pobox.com>. All rights reserved.
  This program is free software; you can redistribute it and/or
  modify it under the same terms as Perl itself.
  
  Recent additions and current maintenance by
  Paul Evans, <leonerd@leonerd.org.uk>.
  
  =cut
DARWIN-2LEVEL_LIST_UTIL

$fatpacked{"darwin-2level/List/Util/XS.pm"} = <<'DARWIN-2LEVEL_LIST_UTIL_XS';
  package List::Util::XS;
  use strict;
  use List::Util;
  
  our $VERSION = "1.35";       # FIXUP
  $VERSION = eval $VERSION;    # FIXUP
  
  1;
  __END__
  
  =head1 NAME
  
  List::Util::XS - Indicate if List::Util was compiled with a C compiler
  
  =head1 SYNOPSIS
  
      use List::Util::XS 1.20;
  
  =head1 DESCRIPTION
  
  C<List::Util::XS> can be used as a dependency to ensure List::Util was
  installed using a C compiler and that the XS version is installed.
  
  During installation C<$List::Util::XS::VERSION> will be set to
  C<undef> if the XS was not compiled.
  
  Starting with release 1.23_03, Scalar-List-Util is B<always> using
  the XS implementation, but for backwards compatibility, we still
  ship the C<List::Util::XS> module which just loads C<List::Util>.
  
  =head1 SEE ALSO
  
  L<Scalar::Util>, L<List::Util>, L<List::MoreUtils>
  
  =head1 COPYRIGHT
  
  Copyright (c) 2008 Graham Barr <gbarr@pobox.com>. All rights reserved.
  This program is free software; you can redistribute it and/or
  modify it under the same terms as Perl itself.
  
  =cut
DARWIN-2LEVEL_LIST_UTIL_XS

$fatpacked{"darwin-2level/Scalar/Util.pm"} = <<'DARWIN-2LEVEL_SCALAR_UTIL';
  # Scalar::Util.pm
  #
  # Copyright (c) 1997-2007 Graham Barr <gbarr@pobox.com>. All rights reserved.
  # This program is free software; you can redistribute it and/or
  # modify it under the same terms as Perl itself.
  #
  # Maintained since 2013 by Paul Evans <leonerd@leonerd.org.uk>
  
  package Scalar::Util;
  
  use strict;
  require Exporter;
  require List::Util; # List::Util loads the XS
  
  our @ISA       = qw(Exporter);
  our @EXPORT_OK = qw(
    blessed
    dualvar
    isdual
    isvstring
    isweak
    looks_like_number
    openhandle
    readonly
    refaddr
    reftype
    set_prototype
    tainted
    weaken
  );
  our $VERSION    = "1.35";
  $VERSION   = eval $VERSION;
  
  our @EXPORT_FAIL;
  
  unless (defined &weaken) {
    push @EXPORT_FAIL, qw(weaken);
  }
  unless (defined &isweak) {
    push @EXPORT_FAIL, qw(isweak isvstring);
  }
  unless (defined &isvstring) {
    push @EXPORT_FAIL, qw(isvstring);
  }
  
  sub export_fail {
    if (grep { /^(?:weaken|isweak)$/ } @_ ) {
      require Carp;
      Carp::croak("Weak references are not implemented in the version of perl");
    }
  
    if (grep { /^isvstring$/ } @_ ) {
      require Carp;
      Carp::croak("Vstrings are not implemented in the version of perl");
    }
  
    @_;
  }
  
  1;
  
  __END__
  
  =head1 NAME
  
  Scalar::Util - A selection of general-utility scalar subroutines
  
  =head1 SYNOPSIS
  
      use Scalar::Util qw(blessed dualvar isdual readonly refaddr reftype
                          tainted weaken isweak isvstring looks_like_number
                          set_prototype);
                          # and other useful utils appearing below
  
  =head1 DESCRIPTION
  
  C<Scalar::Util> contains a selection of subroutines that people have
  expressed would be nice to have in the perl core, but the usage would
  not really be high enough to warrant the use of a keyword, and the size
  so small such that being individual extensions would be wasteful.
  
  By default C<Scalar::Util> does not export any subroutines. The
  subroutines defined are
  
  =head2 blessed EXPR
  
  If EXPR evaluates to a blessed reference the name of the package
  that it is blessed into is returned. Otherwise C<undef> is returned.
  
     $scalar = "foo";
     $class  = blessed $scalar;           # undef
  
     $ref    = [];
     $class  = blessed $ref;              # undef
  
     $obj    = bless [], "Foo";
     $class  = blessed $obj;              # "Foo"
  
  Take care when using this function simply as a truth test (such as in
  C<if(blessed $ref)...>) because the package name C<"0"> is defined yet
  false.
  
  =head2 dualvar NUM, STRING
  
  Returns a scalar that has the value NUM in a numeric context and the
  value STRING in a string context.
  
      $foo = dualvar 10, "Hello";
      $num = $foo + 2;                    # 12
      $str = $foo . " world";             # Hello world
  
  =head2 isdual EXPR
  
  If EXPR is a scalar that is a dualvar, the result is true.
  
      $foo = dualvar 86, "Nix";
      $dual = isdual($foo);               # true
  
  Note that a scalar can be made to have both string and numeric content
  through numeric operations:
  
      $foo = "10";
      $dual = isdual($foo);               # false
      $bar = $foo + 0;
      $dual = isdual($foo);               # true
  
  Note that although C<$!> appears to be dual-valued variable, it is
  actually implemented using a tied scalar:
  
      $! = 1;
      print("$!\n");                      # "Operation not permitted"
      $dual = isdual($!);                 # false
  
  You can capture its numeric and string content using:
  
      $err = dualvar $!, $!;
      $dual = isdual($err);               # true
  
  =head2 isvstring EXPR
  
  If EXPR is a scalar which was coded as a vstring the result is true.
  
      $vs   = v49.46.48;
      $fmt  = isvstring($vs) ? "%vd" : "%s"; #true
      printf($fmt,$vs);
  
  =head2 looks_like_number EXPR
  
  Returns true if perl thinks EXPR is a number. See
  L<perlapi/looks_like_number>.
  
  =head2 openhandle FH
  
  Returns FH if FH may be used as a filehandle and is open, or FH is a tied
  handle. Otherwise C<undef> is returned.
  
      $fh = openhandle(*STDIN);           # \*STDIN
      $fh = openhandle(\*STDIN);          # \*STDIN
      $fh = openhandle(*NOTOPEN);         # undef
      $fh = openhandle("scalar");         # undef
  
  =head2 readonly SCALAR
  
  Returns true if SCALAR is readonly.
  
      sub foo { readonly($_[0]) }
  
      $readonly = foo($bar);              # false
      $readonly = foo(0);                 # true
  
  =head2 refaddr EXPR
  
  If EXPR evaluates to a reference the internal memory address of
  the referenced value is returned. Otherwise C<undef> is returned.
  
      $addr = refaddr "string";           # undef
      $addr = refaddr \$var;              # eg 12345678
      $addr = refaddr [];                 # eg 23456784
  
      $obj  = bless {}, "Foo";
      $addr = refaddr $obj;               # eg 88123488
  
  =head2 reftype EXPR
  
  If EXPR evaluates to a reference the type of the variable referenced
  is returned. Otherwise C<undef> is returned.
  
      $type = reftype "string";           # undef
      $type = reftype \$var;              # SCALAR
      $type = reftype [];                 # ARRAY
  
      $obj  = bless {}, "Foo";
      $type = reftype $obj;               # HASH
  
  =head2 set_prototype CODEREF, PROTOTYPE
  
  Sets the prototype of the given function, or deletes it if PROTOTYPE is
  undef. Returns the CODEREF.
  
      set_prototype \&foo, '$$';
  
  =head2 tainted EXPR
  
  Return true if the result of EXPR is tainted
  
      $taint = tainted("constant");       # false
      $taint = tainted($ENV{PWD});        # true if running under -T
  
  =head2 weaken REF
  
  REF will be turned into a weak reference. This means that it will not
  hold a reference count on the object it references. Also when the reference
  count on that object reaches zero, REF will be set to undef.
  
  This is useful for keeping copies of references , but you don't want to
  prevent the object being DESTROY-ed at its usual time.
  
      {
        my $var;
        $ref = \$var;
        weaken($ref);                     # Make $ref a weak reference
      }
      # $ref is now undef
  
  Note that if you take a copy of a scalar with a weakened reference,
  the copy will be a strong reference.
  
      my $var;
      my $foo = \$var;
      weaken($foo);                       # Make $foo a weak reference
      my $bar = $foo;                     # $bar is now a strong reference
  
  This may be less obvious in other situations, such as C<grep()>, for instance
  when grepping through a list of weakened references to objects that may have
  been destroyed already:
  
      @object = grep { defined } @object;
  
  This will indeed remove all references to destroyed objects, but the remaining
  references to objects will be strong, causing the remaining objects to never
  be destroyed because there is now always a strong reference to them in the
  @object array.
  
  =head2 isweak EXPR
  
  If EXPR is a scalar which is a weak reference the result is true.
  
      $ref  = \$foo;
      $weak = isweak($ref);               # false
      weaken($ref);
      $weak = isweak($ref);               # true
  
  B<NOTE>: Copying a weak reference creates a normal, strong, reference.
  
      $copy = $ref;
      $weak = isweak($copy);              # false
  
  =head1 DIAGNOSTICS
  
  Module use may give one of the following errors during import.
  
  =over
  
  =item Weak references are not implemented in the version of perl
  
  The version of perl that you are using does not implement weak references, to use
  C<isweak> or C<weaken> you will need to use a newer release of perl.
  
  =item Vstrings are not implemented in the version of perl
  
  The version of perl that you are using does not implement Vstrings, to use
  C<isvstring> you will need to use a newer release of perl.
  
  =item C<NAME> is only available with the XS version of Scalar::Util
  
  C<Scalar::Util> contains both perl and C implementations of many of its functions
  so that those without access to a C compiler may still use it. However some of the functions
  are only available when a C compiler was available to compile the XS version of the extension.
  
  At present that list is: weaken, isweak, dualvar, isvstring, set_prototype
  
  =back
  
  =head1 KNOWN BUGS
  
  There is a bug in perl5.6.0 with UV's that are >= 1<<31. This will
  show up as tests 8 and 9 of dualvar.t failing
  
  =head1 SEE ALSO
  
  L<List::Util>
  
  =head1 COPYRIGHT
  
  Copyright (c) 1997-2007 Graham Barr <gbarr@pobox.com>. All rights reserved.
  This program is free software; you can redistribute it and/or modify it
  under the same terms as Perl itself.
  
  Except weaken and isweak which are
  
  Copyright (c) 1999 Tuomas J. Lukka <lukka@iki.fi>. All rights reserved.
  This program is free software; you can redistribute it and/or modify it
  under the same terms as perl itself.
  
  =cut
DARWIN-2LEVEL_SCALAR_UTIL

s/^  //mg for values %fatpacked;

unshift @INC, sub {
  if (my $fat = $fatpacked{$_[1]}) {
    if ($] < 5.008) {
      return sub {
        return 0 unless length $fat;
        $fat =~ s/^([^\n]*\n?)//;
        $_ = $1;
        return 1;
      };
    }
    open my $fh, '<', \$fat
      or die "FatPacker error loading $_[1] (could be a perl installation issue?)";
    return $fh;
  }
  return
};

} # END OF FATPACK CODE

#!/usr/bin/env perl -s

package main;
BEGIN {
  $main::AUTHORITY = 'cpan:DBR';
}
{
  $main::VERSION = '0.9.0';
}

#  PODNAME: ppp
# ABSTRACT: Preprocess Pandoc before Processing Pandoc

use v5.14;
use strict;
use warnings;
use File::Spec;
use File::Temp 'tempdir';
use File::Path 'make_path';
use Smart::Comments '####';

# These can be set like: `ppp -tmp=tmpdir -log=logdir`
our $tmp;
our $log;

create_directories($tmp, $log);

state $fileno = 0;
state $outfile;
state $format;
state @children;
state %attributes;
state $tmpdir = tempdir('ppp-render-XXXXX', CLEANUP => 0, $tmp ? (DIR => $tmp) : File::Spec->tmpdir);
state $logdir = tempdir('ppp-log-XXXXX'   , CLEANUP => 0, $log ? (DIR => $log) : File::Spec->tmpdir);

MAIN: {
  while(<>) {
    if ( (my $start = /^~{3,}\s*\{.*?(?<format>rdfdot|ditaa|dot|neato|yuml|plantuml)(?<attributes>.*)\}.*/) ... (my $end = /^~{3,}\s*$/) ) {
        $start ? begin_ppp() : $end ? end_ppp() : print {$outfile} $_
    } else {
      print
    }
  }
}

SUBS: {
  sub begin_ppp {
    $fileno++;
    $format = $+{format};
    $attributes{$fileno.$format} = $+{attributes};
    open $outfile, '>', "$tmpdir/image-$fileno.$format"
  }

  sub render {
    my ($format, $fileno, %attrs) = @_;
    my $cmd = '';
    
    $format =~ /^ditaa$/ and 
      $cmd = "ditaa"
           . " @{[exists $attrs{'rounded-corners'} ? '--round-corners ' : ' ']}"
           . " @{[exists $attrs{'no-shadows'}      ? '--no-shadows '    : ' ']}"
           . " @{[exists $attrs{'no-separation'}   ? '--no-separation ' : ' ']}"
           . " @{[exists $attrs{'no-antialias'}    ? '--no-antialias '  : ' ']}"
           . " $tmpdir/image-$fileno.$format $tmpdir/image-$fileno.png"
           . " 2>&1 >>$logdir/ditaa.log";

    $format =~ /^rdfdot$/ and
      $cmd = "rdfdot"
           . " -ttl"
           . " $tmpdir/image-$fileno.$format $tmpdir/image-$fileno.svg"
           . " 2>&1 >>$logdir/rdfdot.log";

    $format =~ /^dot$/ and 
      $cmd = "dot"
           . " -Tsvg"
           . " -o $tmpdir/image-$fileno.svg $tmpdir/image-$fileno.$format"
           . " 2>&1 >>$logdir/dot.log";

    $format =~ /^neato$/ and 
      $cmd = "neato"
           . " -Tsvg "
           . " -o $tmpdir/image-$fileno.svg $tmpdir/image-$fileno.$format "
           . " 2>&1 >>$logdir/neato.log";

    $format =~ /^yuml$/ and 
      $cmd = "yuml "
           . " --format svg"
           . " --type  @{[exists $attrs{type}      ? $attrs{type}     : 'class']}"
           . " --style @{[exists $attrs{style}     ? $attrs{style}    : 'nofunky']}"
           . " --dir   @{[exists $attrs{direction} ? $attrs{direction}: 'LR']}"
           . " --in $tmpdir/image-$fileno.$format --out $tmpdir/image-$fileno.svg"
           . " 2>&1 >>$logdir/yuml.log";

    $format =~ /^plantuml$/ and 
      $cmd = "plantuml"
           . " -tsvg "
           . " -charset UTF-8"
           . " $tmpdir/image-$fileno.$format"
           . " 2>&1 >>$logdir/plantuml.log";

    ### $cmd
    system($cmd);
    
  }
  sub scale {
    my ($format, $fileno, %attrs) = @_;
    my $cmd = '';

    # TODO: These two formats should get svg support
    if ($format =~ /^(ditaa)$/) {
      $cmd = "mogrify"
           . " -scale @{[exists $attrs{scale} ? $attrs{scale} : '100%']}"
           . " $tmpdir/image-$fileno.png"
           . " 2>&1 >>$logdir/mogrify.log";
    } else {
      my $scale = exists $attrs{scale} ? do { $_ = $attrs{scale}; s/%//; $_/100 }: 1.0;
      $cmd = "rsvg-convert"
           . " --zoom $scale"
           . " --format png"
           . " --output $tmpdir/image-$fileno.png"
           . " $tmpdir/image-$fileno.svg"
           . " 2>&1 >>$logdir/plantuml.log";
    };
    ### $cmd
    system($cmd);        
  }

  sub end_ppp {
    close $outfile;

    my %attrs = map { /(.+?)=(["']?.+["']?)/ ? ($1 => $2) : ($_ => 1) } split /\s+\./, $attributes{$fileno.$format};
    if( my $child = fork == 0 ) {
       push @children, $child;
       render($format, $fileno, %attrs);
       scale($format, $fileno, %attrs);
       exit 0;
    }

    $format =
      "![" . (exists $attrs{title} ? $attrs{title} : '' )
           . (exists $attrs{label} ? "\\label{$attrs{label}}" : '' ).
      "]"  .
      "($tmpdir/image-$fileno.png)" .
      (exists $attrs{inline} ? '\\ ' : '')
    ;
    say STDOUT $format;
    $format = '';
  }

  sub create_directories {
    for (@_) {
      if (defined $_) {
        unless (-d $_) {
          make_path $_ or die "Failed to create path: $_";
        }
      }
    }
  }
}

END {
  while (1) {
    my $child = waitpid(-1, 0);
    last if $child == -1;       # No more outstanding children
  }
}

__END__

=pod

=head1 NAME

ppp - Preprocess Pandoc before Processing Pandoc

=head1 VERSION

version 0.9.0

=head1 AUTHOR

DBR <dbr@cpan.org>

=head1 COPYRIGHT AND LICENSE

This software is Copyright (c) 2014 by DBR.

This is free software, licensed under:

  DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE, Version 2, December 2004

=cut
