#!/usr/bin/perl 

# 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{"Carp.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'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"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'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{"Codeguard/Fixer.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'CODEGUARD_FIXER';
  package Codeguard::Fixer;
  
  use strict;
  use parent qw(Codeguard::FixerBase);
  
  use Carp qw(croak);
  use Data::Dumper;
  use JSON qw(decode_json);
  use List::Util qw(first);
  use YAML qw();
  
  use constant CG_API_URL => 'https://api.codeguard.com';
  use constant CG_IPS     => [
  	'184.72.217.227',
  	'184.72.217.230',
  	'54.236.233.46',
	'54.236.233.28',
	'54.174.91.34',
	'54.174.153.212',
	'54.174.115.171',
	'54.236.209.91',
	'54.236.206.3',
  ];
  
  our $ERROR;
  
  sub correct_sites {
  
  	my $self    = shift;
  	my $printer = shift;
  	if (not ($printer and UNIVERSAL::isa($printer, 'CODE') )) {
  		$printer = sub { };
  	}
  
  	my $cg_websites = [];
  	eval { $cg_websites = $self->get_cg_api->list_websites; };
  	if ($@) {
  		$printer->("[!] Failed to fetch website list from CG. Error: $@\n");
  		return $self->error('Failed to fetch website list from CG. Error: '.$@);
  	}
  
  	if (not scalar @{$cg_websites}) {
  		$printer->("[!] No websites configured on CG account.\n");
  		return $self->error('No websites configured on CG account');
  	}
  
  	$printer->("\n[*****] Correcting websites on the CG account [*****]\n\n");
  	my $ssh_key = $self->_get_ssh_key();
  	if (not $ssh_key) {
  		$printer->('[!] '.$self->get_errstr."\n");
  		return;
  	}
  
  	$printer->("[+] SSH key fetched successfully.\n");
  	$printer->("[+] Found ".scalar(@{$cg_websites})." website(s) on the CG account.\n\n");
  	my $success = 1;
  	my $count   = 1;
  	foreach my $website (@{$cg_websites}) {
  		$printer->("\t($count/".scalar( @{$cg_websites} )."): '$website->{website}->{url}' ...\n");
  		$count++;
  		my $update_data = {
  			website_id => $website->{website}->{id},
  		};
  
  		my ($error, $cpanel_docroot) = $self->_is_domain_blacklisted_or_missing($website->{website}->{url});
  		if ( $error ) {
  			if ($website->{website}->{disabled}) {
  				$printer->("\t\t[+] '$website->{website}->{url}' is already disabled on CG: $error\n\n");
  				next;
  			}
  			$printer->("\t\t[!] Disabling '$website->{website}->{url}' on CG: $error\n\n");
  			$self->get_cg_api->disable_website({ website_id => $website->{website}->{id} });
  			next;
  		} else {
  			$update_data->{key} = $ssh_key;
  			if ($website->{website}->{disabled}) {
  				$self->get_cg_api->enable_website({ website_id => $website->{website}->{id} });
  			}
  			if ($website->{website}->{account} ne $self->get_cpanel_username) {
  				$printer->("\t\t[!] '$website->{website}->{url}' - username mismatch found!\n");
  				$printer->("\t\t\t[+] Changing '$website->{website}->{account}' to '".$self->get_cpanel_username."'\n");
  				$update_data->{account} = $self->get_cpanel_username;
  			}
  
  			if ($website->{website}->{hostname} ne $self->get_cpanel_servername) {
  				$printer->("\t\t[!] '$website->{website}->{url}' - hostname mismatch found!\n");
  				$printer->("\t\t\t[+] Changing '$website->{website}->{hostname}' to '".$self->get_cpanel_servername."'\n");
  				$update_data->{hostname} = $self->get_cpanel_servername;
  			}
  
  			if ($cpanel_docroot and $cpanel_docroot ne $website->{website}->{dir_path}) {
  				$printer->("\t\t[!] '$website->{website}->{url}' - dir_path is incorrect!\n");
  				$printer->("\t\t\t[+] Changing '$website->{website}->{dir_path}' to '$cpanel_docroot'\n");
  				$update_data->{dir_path} = $cpanel_docroot;
  			}
  		}
  
  		my $resp;
  		eval {
  			$resp = $self->get_cg_api->edit_website($update_data);
  		};
  		if (ref $resp eq 'HASH' and exists $resp->{website}->{id} and $resp->{website}->{id} eq $website->{website}->{id}) {
  			$printer->("\t\t[+] '$website->{website}->{url}' successfully updated.\n\n");
  		} else {
  			$success = 0;
  			$printer->("\t\t[!] '$website->{website}->{url}' update failed.\n");
  			$printer->("\t\t\t[!] Response: ".Dumper $resp);
  		}
  	}
  	return $success;
  }
  
  sub correct_dbs {
  
  	my $self    = shift;
  	my $printer = shift;
  	if (not ($printer and UNIVERSAL::isa($printer, 'CODE') )) {
  		$printer = sub { };
  	}
  
  	my $cg_databases = [];
  	eval { $cg_databases = $self->get_cg_api->list_databases; };
  	if ($@) {
  		$printer->("[!] Failed to fetch database list from CG. Error: $@\n");
  		return $self->error('Failed to fetch database list from CG. Error: '.$@);
  	}
  
  	if (not scalar @{$cg_databases}) {
  		$printer->("[!] No databases configured on CG account.\n");
  		return $self->error('No databases configured on CG account');
  	}
  
  	$printer->("\n[*****] Correcting databases on the CG account [*****]\n\n");
  	my $ips_whitelisted = $self->_whitelist_cg_ips_for_mysql;
  	if ($ips_whitelisted) {
  		$printer->("[*] Whitelisted the following IPs for Remote Mysql access:\n");
  		foreach my $ip (keys %{$ips_whitelisted} ) {
  			if ($ips_whitelisted->{$ip}->{success}) {
  				$printer->("\t[+] '$ip'\n");
  			} else {
  				$printer->("\t[!] '$ip' - failed to whitelist.\n");
  			}
  		}
  	}
  
  	$printer->("[+] Found ".scalar(@{$cg_databases})." database(s) on the CG account.\n\n");
  	my $success = 1;
  	my $count   = 1;
  	foreach my $database (@{$cg_databases}) {
  		my $cg_db_user = $database->{database_backup}->{account};
  		my $cg_db_name = $database->{database_backup}->{database_name};
  		$printer->("\t($count/".scalar( @{$cg_databases} )."): DB user: '$cg_db_user' ");
  		$printer->("configured for DB: '$cg_db_name'...\n");
  		$count++;
  		if ($database->{database_backup}->{account} !~ m/_cg\d+$/) {
  			$printer->("\t\t[!] DB User configured for '$cg_db_name' does not match pattern('_cg\d+'). Skipping.\n");
  			next;
  		}
  
  		my $update_data = {
  			database_id => $database->{database_backup}->{id},
  		};
  
  		if ( my $error = $self->_is_database_blacklisted_or_missing($cg_db_name) ) {
  			if ($database->{database_backup}->{disabled}) {
  				$printer->("\t\t[+] '$cg_db_name' is already disabled on CG: $error\n\n");
  				next;
  			}
  			$printer->("\t\t[!] Disabling '$cg_db_name' on CG: $error\n\n");
  			$self->get_cg_api->disable_database({ database_id => $database->{database_backup}->{id} });
  			next;
  		} else {
              # While cPanel Account User names can be longer than 8 characters
              # the prefix for a MySQL database and username is still the first
              # 8 characters
              my $db_prefix = substr( $self->{user_name}, 0, 8 );
              if ($cg_db_user !~ m/^${db_prefix}_/) {
                      $printer->("\t\tDB User: '$cg_db_user' doesn't start with '$db_prefix'\n");
                      $cg_db_user =~ s/^\w+_/${db_prefix}_/;
                      $update_data->{account} = $database->{database_backup}->{account};
              }
              if ($cg_db_name !~ m/^${db_prefix}_/) {
                      $printer->("\t\tDB Name: '$cg_db_name' doesn't start with '$db_prefix'\n");
                      $cg_db_name =~ s/^\w+_/${db_prefix}_/;
                      $update_data->{database_name} = $cg_db_name;
              }
  
  			my $dbpass = $self->_reset_dbuser_cpanel($cg_db_user, $cg_db_name);
  			if (not $dbpass) {
  				$printer->("\t\t[!] Failed to reset DB user on cPanel.\n");
  				next;
  			}
  			$update_data->{password} = $dbpass;
  			if ($database->{database_backup}->{disabled}) {
  				$self->get_cg_api->enable_database({ database_id => $database->{database_backup}->{id} });
  			}
  		}
  
  		my $resp;
  		eval {
  			$resp = $self->get_cg_api->edit_database($update_data);
  		};
  
  		if (ref $resp eq 'HASH' and $resp->{database_backup}->{id} eq $database->{database_backup}->{id}) {
  			$printer->("\t\t[+] Successfully updated.\n\n");
  		} else {
  			$success = 0;
  			$printer->("\t\t[!] Update failed.\n");
  			$printer->("\t\t[!] Response: ".Dumper $resp);
  		}
  	}
  	return $success;
  }
  
  sub blacklist_site {
  
  	my ($self, $site_to_blacklist, $printer) = @_;
  	if (not ($printer and UNIVERSAL::isa($printer, 'CODE') )) {
  		$printer = sub { };
  	}
  
  	$printer->("\n[*****] Blacklisting '$site_to_blacklist' [*****]\n\n");
  	if ( $self->_blacklist_resource({ website => lc $site_to_blacklist }) ) {
  		$printer->("[+] '$site_to_blacklist' blacklisted successfully.\n");
  		return 1;
  	} else {
  		$printer->("[!] '$site_to_blacklist' blacklisting failed: ".$self->get_errstr."\n");
  	}
  
  	return;
  }
  
  sub blacklist_db {
  
  	my ($self, $db_to_blacklist, $printer) = @_;
  	if (not ($printer and UNIVERSAL::isa($printer, 'CODE') )) {
  		$printer = sub { };
  	}
  
  	$printer->("\n[*****] Blacklisting '$db_to_blacklist' [*****]\n\n");
  	if ( $self->_blacklist_resource({ database => lc $db_to_blacklist }) ) {
  		$printer->("[+] '$db_to_blacklist' blacklisted successfully.\n");
  		return 1;
  	} else {
  		$printer->("[!] '$db_to_blacklist' blacklisting failed: ".$self->get_errstr."\n");
  	}
  
  	return;
  }
  
  sub delete_site {
  
  	my ($self, $site_to_delete, $printer) = @_;
  	if (not ($printer and UNIVERSAL::isa($printer, 'CODE') )) {
  		$printer = sub { };
  	}
  
  	$printer->("\n[*****] Deleting '$site_to_delete' on Codeguard [*****]\n\n");
  	if ( $self->_delete_site_on_cg(lc $site_to_delete) ) {
  		$printer->("[+] '$site_to_delete' deleted successfully.\n");
  		return 1;
  	} else {
  		$printer->("[!] '$site_to_delete' deletion failed: ".$self->get_errstr."\n");
  	}
  
  	return;
  }
  
  sub delete_db {
  
  	my ($self, $db_to_delete, $printer) = @_;
  	if (not ($printer and UNIVERSAL::isa($printer, 'CODE') )) {
  		$printer = sub { };
  	}
  
  	$printer->("\n[*****] Deleting '$db_to_delete' on Codeguard [*****]\n\n");
  	if ( $self->_delete_db_on_cg(lc $db_to_delete) ) {
  		$printer->("[+] '$db_to_delete' deleted successfully.\n");
  		return 1;
  	} else {
  		$printer->("[!] '$db_to_delete' deletion failed: ".$self->get_errstr."\n");
  	}
  
  	return;
  }
  
  sub remove_blacklisted_resources {
  
  	my ($self, $printer) = @_;
  	if (not ($printer and UNIVERSAL::isa($printer, 'CODE') )) {
  		$printer = sub { };
  	}
  
  	$printer->("\n[*****] Removing blacklisted resources from the CG account [*****]\n\n");
  
  	my $current_blacklist = $self->fetch_blacklist_on_cpanel or return;
  	if (ref $current_blacklist eq 'HASH') {
  		if ( exists $current_blacklist->{websites} and UNIVERSAL::isa($current_blacklist->{websites}, 'ARRAY') ) {
  			foreach my $domain ( @{ $current_blacklist->{websites} } ) {
  				my $code = $self->_delete_site_on_cg(lc $domain);
  				if ( not $code ) {
  					$printer->("[!] Website '$domain' deletion failed: ".$self->get_errstr."\n");
  				} elsif ( $code == 1 ) {
  					$printer->("[+] Website '$domain' deleted successfully.\n");
  				} elsif ( $code > 1 ) {
  					$printer->("[+] Website '$domain' is not present on the Codeguard account.\n");
  				}
  			}
  		}
  		if ( exists $current_blacklist->{databases} and UNIVERSAL::isa($current_blacklist->{databases}, 'ARRAY') ) {
  			foreach my $db ( @{ $current_blacklist->{databases} } ) {
  				my $code = $self->_delete_db_on_cg(lc $db);
  				if ( not $code ) {
  					$printer->("[!] Database '$db' deletion failed: ".$self->get_errstr."\n");
  				} elsif ( $code == 1) {
  					$printer->("[+] Database '$db' deleted successfully.\n");
  				} elsif ( $code > 1 ) {
  					$printer->("[+] Database '$db' is not present on the Codeguard account.\n");
  				}
  			}
  		}
  	}
  	return;
  }
  
  sub clean_dbusers {
  
  	my ($self, $printer) = @_;
  	if (not ($printer and UNIVERSAL::isa($printer, 'CODE') )) {
  		$printer = sub { };
  	}
  
  	$printer->("\n[*****] Cleaning up DB users on the cPanel server [*****]\n\n");
  	my $cg_db_users = $self->_fetch_db_users_codeguard();
  	my $cp_db_users = $self->_get_cpanel_db_users_like(qr/cg\d+/);
  	$printer->("\t[*] Number of DB users configured on CG: ". scalar @{$cg_db_users}."\n");
  	$printer->("\t[*] Number of DB users configured on cPanel for CG (i.e., dbusers matching 'cg\\d+'' pattern): ". scalar @{$cp_db_users}."\n");
  
  	my $users_to_remove = $self->_array_diff($cp_db_users, $cg_db_users);
  	$printer->("\t[*] Number of DB users to remove on cPanel: ". scalar @{$users_to_remove}."\n\n");
  
  	my $count = 1;
  	foreach my $dbuser (@{$users_to_remove}) {
  		my $resp;
  		eval {
  			$resp = decode_json(
  				$self->get_cp_api->cpanel_api2_request('whostmgr',
  					{ module => 'MysqlFE', func => 'deletedbuser', 'user' => $self->get_cpanel_username },
  					{ 'dbuser' => $dbuser },
  					'json'
  				)
  			)->{cpanelresult}->{data};
  		};
  		if (ref $resp eq 'ARRAY' and $resp->[0]) {
  			$printer->("\t\t[*] ($count/".scalar(@{$users_to_remove})."): Removed DB user - '$dbuser'\n");
  		} else {
  			$printer->("\t\t[*] ($count/".scalar(@{$users_to_remove})."): Failed to remove DB user - '$dbuser'\n");
  		}
  		$count++;
  	}
  	return;
  }
  
  sub list_cg_sites {
  
  	my ($self, $printer) = @_;
  	if (not ($printer and UNIVERSAL::isa($printer, 'CODE') )) {
  		return $self->error('Must specify a printer coderef for output');
  	}
  
  	$printer->("\n[*****] Listing website(s) on the CG account [*****]\n\n");
  	my $cg_websites = [];
  	eval { $cg_websites = $self->get_cg_api->list_websites; };
  	if ($@) {
  		$printer->("[!] Failed to fetch website list from CG. Error: $@\n");
  		return $self->error('Failed to fetch website list from CG. Error: '.$@);
  	}
  
  	if (not scalar @{$cg_websites}) {
  		$printer->("[!] No websites configured on CG account.\n");
  		return $self->error('No websites configured on CG account');
  	}
  
  	$printer->("[+] Found ".scalar @{$cg_websites}." website(s) on the CG account.\n\n");
  	my $count = 1;
  	foreach my $website (@{$cg_websites}) {
  		$printer->("[+] ($count/".scalar(@{$cg_websites})."): $website->{website}->{url}:\n");
  		$printer->("\tResource ID      : $website->{website}->{id}\n");
  		$printer->("\tResource size    : ".(sprintf "%0.3f", $website->{website}->{container_size} / 1048576)." MB\n");
  		$printer->("\tDisabled?        : ".(($website->{website}->{disabled} eq JSON::true)? "Yes\n": "No\n"));
  		$printer->("\tBackup frequency : $website->{website}->{monitor_frequency}\n");
  		$printer->("\tBackup via sftp  : ".(($website->{website}->{provider} eq 'sftp')? 'Yes' : 'No')."\n");
  		$printer->("\t\tHostname : $website->{website}->{hostname}\n");
  		$printer->("\t\tUsername : $website->{website}->{account}\n");
  		$printer->("\t\tDocroot  : $website->{website}->{dir_path}\n");
  		$printer->("\t\tPort     : $website->{website}->{port}\n\n");
  		$count++;
  	}
  	return 1;
  }
  
  sub list_cg_dbs {
  
  	my ($self, $printer) = @_;
  	if (not ($printer and UNIVERSAL::isa($printer, 'CODE') )) {
  		return $self->error('Must specify a printer coderef for output');
  	}
  
  	$printer->("\n[*****] Listing database(s) on the CG account [*****]\n\n");
  	my $cg_databases = [];
  	eval { $cg_databases = $self->get_cg_api->list_databases; };
  	if ($@) {
  		$printer->("[!] Failed to fetch database list from CG. Error: $@\n");
  		return $self->error('Failed to fetch database list from CG. Error: '.$@);
  	}
  
  	if (not scalar @{$cg_databases}) {
  		$printer->("[!] No databases configured on CG account.\n");
  		return $self->error('No databases configured on CG account');
  	}
  
  	$printer->("[+] Found ".scalar @{$cg_databases}." database(s) on the CG account.\n\n");
  	my $count = 1;
  	foreach my $database (@{$cg_databases}) {
  		$printer->("[+] ($count/".scalar(@{$cg_databases})."): $database->{database_backup}->{database_name}:\n");
  		$printer->("\tResource ID      : $database->{database_backup}->{id}\n");
  		$printer->("\tResource size    : ".(sprintf "%0.3f", $database->{database_backup}->{disk_usage} / 1048576)." MB\n");
  		$printer->("\tDisabled?        : ".(($database->{database_backup}->{disabled} eq JSON::true)? "Yes\n": "No\n") );
  		$printer->("\t\tHostname : $database->{database_backup}->{server_address}\n");
  		$printer->("\t\tUsername : $database->{database_backup}->{account}\n\n");
  		$count++;
  	}
  	return 1;
  }
  
  sub sync_missing_dbs {
  
  	my ($self, $printer) = @_;
  	if (not ($printer and UNIVERSAL::isa($printer, 'CODE') )) {
  		$printer = sub { };
  	}
  
  	$printer->("\n[*****] Adding database(s) to CG account [*****]\n\n");
  	my $cg_databases = [];
  	eval { $cg_databases = $self->get_cg_api->list_databases; };
  	if ($@) {
  		$printer->("[!] Failed to fetch database list from CG. Error: $@\n");
  		return $self->error('Failed to fetch database list from CG. Error: '.$@);
  	}
  
  	my $ips_whitelisted = $self->_whitelist_cg_ips_for_mysql;
  	if ($ips_whitelisted) {
  		$printer->("[*] Whitelisted the following IPs for Remote Mysql access:\n");
  		foreach my $ip (keys %{$ips_whitelisted} ) {
  			if ($ips_whitelisted->{$ip}->{success}) {
  				$printer->("\t[+] '$ip'\n");
  			} else {
  				$printer->("\t[!] '$ip' - failed to whitelist.\n");
  			}
  		}
  	}
  
  	my $cpanel_dbs = $self->_get_cpanel_dbs() or do {
  		$printer->("[!] Failed to fetch list of databases configured on cPanel\n");
  		return $self->error('Failed to fetch list of databases configured on cPanel');
  	};
  	my $blacklist         = $self->fetch_blacklist_on_cpanel or return;
  	my $existing_db_users = $self->_get_cpanel_db_users_like;
  
  	my @dbs_to_add;
  	my @blacklisted;
  	my @already_exist;
  	foreach my $db (@{$cpanel_dbs}) {
  		if (scalar @{ $blacklist->{databases} } and
  			first { defined($_) and $_ eq $db->{db} } @{ $blacklist->{databases} }
  		) {
  			push @blacklisted, $db;
  		} elsif (scalar @{$cg_databases} and
  			first { $_->{database_backup}->{database_name} eq $db->{db} } @{$cg_databases}
  		) {
  			push @already_exist, $db;
  		} else {
  			# cause hyphens get escaped in the output.
  			$db->{db} =~ s/\@002d/\-/g;
  			push @dbs_to_add, $db;
  		}
  	}
  	$printer->("[*] Number of DBs on cPanel account    : ". scalar( @{$cpanel_dbs}   ). "\n");
  	$printer->("[*] Number of DBs on Codeguard account : ". scalar( @{$cg_databases} ). "\n\n");
  
  	$printer->("[*] Number of DBs that exist on both cPanel and Codeguard : ". scalar( @already_exist ). "\n");
  	$printer->("[*] Number of DBs blacklisted on cPanel                   : ". scalar( @blacklisted   ). "\n");
  	$printer->("[*] Number of DBs to add to Codeguard                     : ". scalar( @dbs_to_add    ). "\n\n");
  
  	my $count = 1;
  	foreach my $db (@dbs_to_add) {
  		$printer->("\t[*] ($count/".scalar(@dbs_to_add).") Processing '$db->{db}'...\n");
  		$count++;
  
  		my ($dbuser, $dbpass) = $self->_gen_random_db_user_for_cg($db->{db}, $existing_db_users);
  		if (not ($dbuser and $dbpass)) {
  			$printer->("\t\t[!] Failed to create/assign DB user on cPanel.\n\n");
  			next;
  		}
  		my $api_params = {
  			server_address => $self->get_cpanel_servername,
  			account        => $dbuser,
  			password       => $dbpass,
  			port           => '3306',
  			database_name  => $db->{db},
  		};
  		my $resp;
  		eval { $resp = $self->get_cg_api->create_database($api_params); };
  		if (ref $resp eq 'HASH' and exists $resp->{database_backup}->{id}) {
  			$printer->("\t\t[+] '$resp->{database_backup}->{database_name}' successfully created with DB user: '$resp->{database_backup}->{account}'.\n\n");
  		} else {
  			$printer->("\t\t[!] '$db->{db}' creation failed.\n");
  			$printer->("\t\t[!] Response: ".Dumper $resp."\n");
  		}
  	}
  	return 1;
  }
  
  sub update_exclude_rules {
  
  	my ($self, $printer) = @_;
  	if (not ($printer and UNIVERSAL::isa($printer, 'CODE') )) {
  		$printer = sub { };
  	}
  
  	$printer->("\n[*****] Updating exclude rules for website(s) on the CG account [*****]\n\n");
  	my $cg_websites = [];
  	eval { $cg_websites = $self->get_cg_api->list_websites; };
  	if ($@) {
  		$printer->("[!] Failed to fetch website list from CG. Error: $@\n");
  		return $self->error('Failed to fetch website list from CG. Error: '.$@);
  	}
  
  	if (not scalar @{$cg_websites}) {
  		$printer->("[!] No websites configured on CG account.\n");
  		return $self->error('No websites configured on CG account');
  	}
  
  	foreach my $website (@{ $cg_websites }) {
  		$printer->("\t[*] Updating rules for '$website->{website}->{url}...\n");
  		my @docroots_to_exclude = map { $_->{website}->{dir_path}.'/*' } grep { index ($_->{website}->{dir_path}, $website->{website}->{dir_path}.'/') == 0 } @{ $cg_websites };
  		if (scalar @docroots_to_exclude) {
  			$printer->("\t\t[*] Found overlapping docroots. Excluding the following:\n");
  			$printer->(join "\n", map { "\t\t\t[+] '$_'" } @docroots_to_exclude);
  			$printer->("\n");
  			my $api_result = $self->get_cg_api->set_website_rules({ website_id => $website->{website}->{id}, exclude_rules => \@docroots_to_exclude });
  		} else {
  			$printer->("\t\t[+] No overlapping docroots found.\n\n")
  		}
  	}
  	return 1;
  }
  
  sub fetch_blacklist_on_cpanel {
  
  	my $self = shift;
  
  	my $cpanel_resp;
  	eval {
  		$cpanel_resp = decode_json(
  			$self->get_cp_api->cpanel_api2_request('whostmgr',
  				{ module => 'Fileman', func => 'viewfile', 'user' => $self->get_cpanel_username },
  				{ dir  => '.codeguard', file => 'blacklist' },
  				'json'
  			)
  		)->{cpanelresult}->{data};
  	};
  
  	my $cpanel_blacklist;
  	if ( ref $cpanel_resp eq 'ARRAY' ) {
  		if ( $cpanel_resp->[0]->{fileinfo} =~ m/no such file/i or $cpanel_resp->[0]->{fileinfo} =~ /empty/ ) {
  			$cpanel_blacklist = {
  				websites  => [],
  				databases => [],
  			};
  		} else {
  			eval {
  				# cpanel in its infinite wisdom uri escapes any text it returns via the viewfile api call
  				# so we have to undo that ourselves.
  				$cpanel_blacklist ||= YAML::Load( $cpanel_resp->[0]->{contents} );
  			};
  			if ($@) {
  				return $self->error('Failed to decode YAML: '.$@);
  			}
  		}
  	} else {
  		return $self->error('No .codeguard directory present');
  	}
  
  	if (ref $cpanel_blacklist eq 'HASH' and
  		exists $cpanel_blacklist->{databases} and ref $cpanel_blacklist->{databases} eq 'ARRAY' and
  		exists $cpanel_blacklist->{websites}  and ref $cpanel_blacklist->{websites} eq 'ARRAY'
  	) {
  		return $cpanel_blacklist;
  	}
  
  	return $self->error('Blacklist file is malformed or missing elements. Please review the format documented in the wiki: https://gatorwiki.hostgator.com/Admin/Codeguard');
  }
  
  # get cpanel username
  sub get_cpanel_username { shift->{user_name}; }
  # get cpanel servername
  sub get_cpanel_servername { shift->{server_name}; }
  # get db sleep
  sub get_db_sleep { shift->{db_sleep}; }
  # get codeguard api url
  sub get_cg_api_url { shift->{cg_api_url}; }
  # get codeguard api object
  sub get_cg_api { shift->{cg_user_api}; }
  # get cpanel api object
  sub get_cp_api { shift->{cpanel_api}; }
  # get error string
  sub get_errstr { shift->{errstr}; }
  # clear error string
  sub clear_errstr { undef shift->{errstr}; }
  
  sub is_pwtemped {
  
  	my $self = shift;
  
  	if ( $self->{pwtemped} or -e '/root/.hgtogglehash/'.$self->get_cpanel_username ) {
  		return 1;
  	}
  	return;
  }
  
  sub error {
  
  	my $self  = shift;
  	$self->{errstr} = shift;
  	if ($self->{raise_error}) {
  		croak $self->{errstr};
  	}
  	return;
  }
  
  1;
CODEGUARD_FIXER

$fatpacked{"Codeguard/Fixer/User.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'CODEGUARD_FIXER_USER';
  package Codeguard::Fixer::User;
  
  use strict;
  use warnings;
  use parent qw(Codeguard::Fixer);
  
  use Data::Dumper;
  use Sys::Hostname qw(hostname);
  
  use cPanel::PublicAPI;
  use HTTP::Cookies;
  use HTTP::Request::Common qw(POST);
  use JSON qw(decode_json);
  use LWP::UserAgent;
  
  use WWW::Codeguard::User;
  
  use constant CG_PLUGINS_URL => 'https://plugins.hostgator.com/codeguard/ajax/ajax.php';
  
  sub new {
  
  	my ($class, $opts) = @_;
  	if (not $opts->{user_name} ) {
  		$Codeguard::Fixer::ERROR = 'Missing required parameters. Must specify "user_name"';
  		return;
  	}
  
  	my $self = {
  		user_name   => $opts->{user_name},
  		server_name => hostname(),
  		cg_api_url  => Codeguard::Fixer::CG_API_URL,
  		plugins_url => CG_PLUGINS_URL,
  		db_sleep    => $opts->{db_sleep} || 15,
  	};
  
  	bless $self, $class;
  	return $self;
  }
  
  sub initialize {
  
  	my $self    = shift;
  	my $printer = shift;
  	if (not ($printer and UNIVERSAL::isa($printer, 'CODE') )) {
  		$printer = sub { };
  	}
  
  	$printer->("[*] Initializing codeguard fixer for '".$self->get_cpanel_username."'...\n");
  	# make sure the accesshash is populated
  	if ( !-s "/root/.accesshash" ) {
  		$printer->("\t[*] Generating root accesshash...\n");
  		$ENV{'REMOTE_USER'} = 'root';
  		system('/usr/local/cpanel/bin/realmkaccesshash');
  	}
  	$self->{cpanel_api} = cPanel::PublicAPI->new();
  	$self->_set_cg_api_via_plugins($printer) or return;
  	return 1;
  }
  
  sub _set_cg_api_via_plugins {
  
  	my $self    = shift;
  	my $printer = shift;
  
  	my $session_pass = $self->_pwtemp_setuser or
  		return $self->error('Failed to pwtemp user. Error: '.$self->get_errstr);
  	$printer->("\t[+] Pwtemp'ed user successfully.\n");
  	$printer->("\t[*] Logging in with temporary password generated is '$session_pass'...\n");
  
  	my $ua   = $self->_login_via_plugins($session_pass) or
  		return $self->error('Failed to login with temp password. Please try again later.');
  	my $resp = $ua->request(POST $self->_get_plugins_url . '?action=read',
  		{
  			cpanel_user => $self->get_cpanel_username,
  			server_host => $self->get_cpanel_servername,
  		}
  	);
  	$self->_pwtemp_unsetuser;
  	$printer->("\t[+] User un-pwtemp'ed.\n\n");
  
  	if ($resp->is_success) {
  		my $json_content;
  		eval { $json_content = decode_json($resp->decoded_content); };
  		if ($@ or not $json_content) {
  			return $self->error('Failed to decode json data. Unable to parse CG tokens from READ call.');
  		}
  
  		if ($json_content->{codeguard_user_id}) {
  			$printer->("[+] Active CG subscription found: CG UserID: ".$json_content->{codeguard_user_id}.
  				", Plan: ". $json_content->{codeguard_plan_name}."\n");
  			eval {
  				$self->{cg_user_api} = WWW::Codeguard::User->new(
  					$self->get_cg_api_url,
  					{
  						api_secret    => $json_content->{codeguard_api_secret},
  						api_key       => $json_content->{codeguard_api_key},
  						access_secret => $json_content->{codeguard_access_secret},
  						access_token  => $json_content->{codeguard_access_token},
  						verify_hostname => 0,
  					},
  				);
  			};
  			if ($@ or not $self->{cg_user_api}) {
  				return $self->error('Failed to create CG API object. '.$@);
  			}
  			return 1;
  		}
  		return $self->error('No active CG subscription found for "'.$self->get_cpanel_username.'" on "'.hostname().'"');
  	}
  
  	return $self->error('Failed to fetch CG data for "'.$self->get_cpanel_username.'" on "'.hostname().'"');
  }
  
  sub _login_via_plugins {
  
  	my $self         = shift;
  	my $session_pass = shift;
  	my $ua = LWP::UserAgent->new(
  		cookie_jar => HTTP::Cookies->new('file' => '/tmp/cg_tool'.getppid.'.cache'),
  		ssl_opts   => { 'SSL_verify_mode' => 'SSL_VERIFY_NONE', 'verify_hostname' => 0 },
  		agent      => "CG Fixer",
  	);
  
  	my $resp = $ua->request(POST $self->_get_plugins_url . '?action=Cpanel_Login',
  		{
  			cpanel_user => $self->get_cpanel_username,
  			cpanel_pass => $session_pass,
  			server_host => hostname(),
  		}
  	);
  
  	if ($resp->is_success) {
  		return $ua;
  	}
  
  	return $self->error('Unable to authenticate account to read Codeguard data');
  }
  
  sub _pwtemp_setuser {
  
  	my $self = shift;
  
  	my $username = $self->get_cpanel_username;
  	$self->is_pwtemped and return $self->error('cPanel user is already pwtemped');
  
  	my $pw_output  = `pwtemp setuser $username 2>/dev/null`;
  	my ($password) = $pw_output =~ m/Temporary password for \w+ is\s(.*)$/m;
  	if (not $password) {
  		return $self->error('Failed to parse password from pwtemp output');
  	}
  
  	$self->{pwtemped} = 1;
  	return $password;
  }
  
  sub _pwtemp_unsetuser {
  
  	my $self = shift;
  
  	my $username = $self->get_cpanel_username;
  	if (not $self->is_pwtemped) {
  		return $self->error('cPanel user is not pwtemped');
  	}
  
  	my $pw_output = `pwtemp unsetuser $username 2>/dev/null`;
  	if ($pw_output =~ m/password restored.$/m) {
  		$self->{pwtemped} = 0;
  		return 1;
  	}
  
  	return;
  }
  
  # get plugins url
  sub _get_plugins_url { shift->{plugins_url}; }
  
  sub DESTROY {
  
  	my $self = shift;
  	$self->_pwtemp_unsetuser() if $self->{pwtemped};
  }
  
  1;
CODEGUARD_FIXER_USER

$fatpacked{"Codeguard/FixerBase.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'CODEGUARD_FIXERBASE';
  package Codeguard::FixerBase;
  
  use strict;
  use JSON qw(decode_json);
  use List::Util qw(first);
  use String::Random qw( random_regex );
  use YAML qw();
  
  sub _gen_random_db_user_for_cg {
  
  	my ($self, $database, $existing_db_users) = @_;
  
  	# max mysql user name length is 16,
  	# the cg user we will generate for the db will be following the pattern:
  	# cg + random number, so we calc the length we have left to work with.
      # The prefix is the first 8 chars of the cpanel_username
  	my $length = 13 - (length substr( $self->get_cpanel_username, 0, 8 ));
  	my $dbuser;
  	do {
  		$dbuser = random_regex('\d{'.$length.'}');
  	} while (grep { $_ eq 'cg'.$dbuser } @{$existing_db_users});
  	$dbuser = 'cg'.$dbuser;
  
  	my $dbpass = $self->_create_dbuser_cpanel($dbuser, $database);
  	if ($dbpass) {
  		push @{$existing_db_users}, $dbuser;
          # prefix is 8 chars
  		return (substr( $self->get_cpanel_username, 0, 8 ) .'_'.$dbuser, $dbpass);
  	}
  
  	return;
  }
  
  sub _create_dbuser_cpanel {
  
  	my ($self, $dbuser, $dbname) = @_;
  
  	my $randompw = _gen_rand_pass(16);
  	my $resp;
  	eval {
  		$resp = decode_json(
  			$self->get_cp_api->cpanel_api2_request('whostmgr',
  				{ module => 'MysqlFE', func => 'createdbuser', 'user' => $self->get_cpanel_username },
  				{ 'dbuser' => $dbuser, 'password' => $randompw },
  				'json'
  			)
  		)->{cpanelresult}->{data};
  	};
  
  	if (ref $resp eq 'ARRAY' and $resp->[0]) {
  		sleep $self->get_db_sleep;
  		if ( $self->_set_dbprivs_cpanel($dbuser, $dbname) ) {
  			return $randompw;
  		}
  	}
  
  	return;
  }
  
  sub _set_dbprivs_cpanel {
  
  	my ($self, $dbuser, $dbname) = @_;
  
  	my $resp;
  	eval {
  		$resp = decode_json(
  			$self->get_cp_api->cpanel_api2_request('whostmgr',
  				{ module => 'MysqlFE', func => 'setdbuserprivileges', 'user' => $self->get_cpanel_username },
  				{ 'db' => $dbname, 'dbuser' => $dbuser, 'privileges' => 'ALL' },
  				'json'
  			)
  		)->{cpanelresult}->{data};
  	};
  
  	if (ref $resp eq 'ARRAY' and $resp->[0]) {
  		sleep ( ($self->get_db_sleep > 5)? $self->get_db_sleep - 5 : 5 );
  		return 1;
  	}
  
  	return;
  }
  
  sub _get_cpanel_dbs {
  
  	my $self = shift;
  	my $resp;
  	eval {
          # The regex must be for only the db prefix (first 8 chars of cpanel_username)
  		$resp = decode_json(
  			$self->get_cp_api->cpanel_api2_request('whostmgr',
  				{ module => 'MysqlFE', func => 'listdbs', 'user' => $self->get_cpanel_username },
  				{ 'regex' => '^'. substr( $self->get_cpanel_username, 0, 8 ) .'_' },
  				'json'
  			)
  		)->{cpanelresult}->{data};
  	};
  
  	if (ref $resp eq 'ARRAY' and scalar @{$resp}) {
  		return $resp;
  	}
  	return;
  }
  
  sub _get_cpanel_db_users_like {
  
  	my ($self, $regex) = @_;
  
  	my $resp;
  	eval {
  		$resp = decode_json(
  			$self->get_cp_api->cpanel_api2_request('whostmgr',
  				{ module => 'MysqlFE', func => 'listusers', 'user' => $self->get_cpanel_username },
  				{ },
  				'json'
  			)
  		)->{cpanelresult}->{data};
  	};
  
  	if (ref $resp eq 'ARRAY' and scalar @{$resp}) {
  		if (ref $regex eq 'Regexp') {
  			return [ map { $_->{user} } grep { $_->{shortuser} =~ $regex } @{ $resp } ];
  		}
  		return [ map { $_->{shortuser} } @{ $resp } ];
  	}
  	return;
  }
  
  sub _array_diff {
  
  	my ($self, $first_array, $second_array) = @_;
  	my %second = map { $_ => 1 } @{$second_array};
  
  	return [ grep { not defined $second{$_} } @{$first_array} ];
  }
  
  sub _fetch_db_users_codeguard {
  
  	my $self = shift;
  
  	my $cg_databases = [];
  	eval { $cg_databases = $self->get_cg_api->list_databases; };
  
  	return [ map { $_->{database_backup}->{account} } @{$cg_databases} ];
  }
  
  sub _delete_site_on_cg {
  
  	my ($self, $site_to_delete) = @_;
  
  	my $cg_websites = [];
  	eval { $cg_websites = $self->get_cg_api->list_websites; };
  	if ($@) {
  		return $self->error('Failed to fetch website list from CG. Error: '.$@);
  	}
  
  	if (not scalar @{$cg_websites}) {
  		return $self->error('No websites configured on CG account');
  	} else {
  		if (my ($website) = grep { $_->{website}->{url} eq $site_to_delete } @{$cg_websites} ) {
  			my $resp;
  			eval {
  				$resp = $self->get_cg_api->delete_website( { website_id => $website->{website}->{id} } );
  			};
  			if ($@) {
  				return $self->error("Failed to remove '$website->{website}->{url}' from CG. Error returned: ".$@);
  			}
  
  			if ($resp and $resp->{message} eq '200') {
  				return 1;
  			} else {
  				if (exists $resp->{error}) {
  					return $self->error("Failed to remove '$website->{website}->{url}' from CG. Error returned: ".$resp->{error});
  				} else {
  					return $self->error("Failed to remove '$website->{website}->{url}' from CG. Unknown error - full API response was: ".Dumper $resp);
  				}
  			}
  		} else {
  			return 2;
  		}
  	}
  }
  
  sub _delete_db_on_cg {
  
  	my ($self, $db_to_delete) = @_;
  
  	my $cg_databases = [];
  	eval { $cg_databases = $self->get_cg_api->list_databases; };
  	if ($@) {
  		return $self->error('Failed to fetch database list from CG. Error: '.$@);
  	}
  
  	if (not scalar @{$cg_databases}) {
  		return $self->error('No databases configured on CG account');
  	} else {
  		if (my ($database) = grep { $_->{database_backup}->{database_name} eq $db_to_delete } @{$cg_databases} ) {
  			my $resp;
  			eval {
  				$resp = $self->get_cg_api->delete_database( { database_id => $database->{database_backup}->{id} } );
  			};
  			if ($@) {
  				return $self->error("Failed to remove '$database->{database_backup}->{database_name}' from CG. Error returned: ".$@);
  			}
  
  			if ($resp and $resp->{message} eq '200') {
  				return 1;
  			} else {
  				if (exists $resp->{error}) {
  					return $self->error("Failed to remove '$database->{database_backup}->{database_name}' from CG. Error returned: ".$resp->{error});
  				} else {
  					return $self->error("Failed to remove '$database->{database_backup}->{database_name}' from CG. Unknown error - full API response was: ".Dumper $resp);
  				}
  			}
  		} else {
  			return 2;
  		}
  	}
  }
  
  sub _blacklist_resource {
  
  	my ($self, $resource_to_blacklist) = @_;
  
  	my $current_blacklist = $self->fetch_blacklist_on_cpanel or return;
  	if ($resource_to_blacklist->{website}) {
  		if ( grep { $_ eq $resource_to_blacklist->{website} } @{ $current_blacklist->{websites} } ) {
  			return 1;
  		} else {
  			push @{ $current_blacklist->{websites} }, $resource_to_blacklist->{website};
  		}
  	} elsif ($resource_to_blacklist->{database}) {
  		if ( grep { $_ eq $resource_to_blacklist->{database} } @{ $current_blacklist->{databases} } ) {
  			return 1;
  		} else {
  			push @{ $current_blacklist->{databases} }, $resource_to_blacklist->{database};
  		}
  	} else {
  		return $self->error('Unknown resource type specified');
  	}
  
  	my $yml;
  	eval {
  		$yml = YAML::Dump($current_blacklist);
  	};
  	if ($@ or not $yml) {
  		return $self->error('Failed to encode YAML. '.$@);
  	} else {
  		my $cpanel_resp;
  		eval {
  			$cpanel_resp = decode_json(
  				$self->get_cp_api->cpanel_api2_request('whostmgr',
  					{ module => 'Fileman', func => 'savefile', 'user' => $self->get_cpanel_username },
  					{ dir  => '.codeguard', filename => 'blacklist', content => $yml },
  					'json'
  				)
  			)->{cpanelresult};
  		};
  
  		if (ref $cpanel_resp->{data} eq 'ARRAY' and
  			scalar @{ $cpanel_resp->{data} } and
  			$cpanel_resp->{data}->[0]->{path} =~ m{.codeguard/blacklist$}
  		) {
  			return 1;
  		} else {
  			return $self->error('Failed to update blacklist. Error: '.$cpanel_resp->{error});
  		}
  	}
  }
  
  sub _is_database_blacklisted_or_missing {
  
  	my $self     = shift;
  	my $database = shift;
  
  	my $blacklist  = $self->fetch_blacklist_on_cpanel();
  	if (ref $blacklist eq 'HASH' and scalar ( @{ $blacklist->{databases} } ) and first { defined($_) and $_ eq $database } @{$blacklist->{databases}} ) {
  		return "'$database' is blacklisted on cPanel account.";
  	}
  	return $self->_database_exists($database);
  }
  
  sub _database_exists {
  
  	my $self     = shift;
  	my $database = shift;
  
  	my $resp;
  	eval {
  		$resp = decode_json(
  			$self->get_cp_api->cpanel_api2_request('whostmgr',
  				{ module => 'MysqlFE', func => 'listdbs', 'user' => $self->get_cpanel_username },
  				{ regex => '^'.$database.'$' },
  				'json'
  			)
  		)->{cpanelresult}->{data};
  	};
  
  	if (ref $resp eq 'ARRAY' and scalar @{$resp}){
  		return;
  	}
  	return "Database '$database' does not exist on the server.";
  }
  
  sub _reset_dbuser_cpanel {
  
  	my ($self, $dbuser, $dbname) = @_;
  
  	my $resp;
  	my $randompw = _gen_rand_pass(16);
  	eval {
  		$resp = decode_json(
  			$self->get_cp_api->cpanel_api2_request('whostmgr',
  				{ module => 'MysqlFE', func => 'changedbuserpassword', 'user' => $self->get_cpanel_username },
  				{ 'dbuser' => $dbuser, 'password' => $randompw },
  				'json'
  			)
  		)->{cpanelresult}->{data};
  	};
  
  	if (ref $resp eq 'ARRAY' and $resp->[0]) {
  		sleep $self->{db_sleep};
  		if ( $self->_set_dbprivs_cpanel($dbuser, $dbname) ) {
  			return $randompw;
  		}
  		return;
  	} else {
  		eval {
  			# If the attempt to reset the db user's password fails,
  			# then try removing the user, and re-creating it.
  			$resp = decode_json(
  				$self->get_cp_api->cpanel_api2_request('whostmgr',
  					{ module => 'MysqlFE', func => 'deletedbuser', 'user' => $self->get_cpanel_username },
  					{ 'dbuser' => $dbuser },
  					'json'
  				)
  			)->{cpanelresult}->{data};
  		};
  		return $self->_create_dbuser_cpanel($dbuser, $dbname);
  	}
  }
  
  sub _create_dbuser_cpanel {
  
  	my ($self, $dbuser, $dbname) = @_;
  
  	my $randompw = _gen_rand_pass(16);
  	my $resp;
  	eval {
  		$resp = decode_json(
  			$self->get_cp_api->cpanel_api2_request('whostmgr',
  				{ module => 'MysqlFE', func => 'createdbuser', 'user' => $self->get_cpanel_username },
  				{ 'dbuser' => $dbuser, 'password' => $randompw },
  				'json'
  			)
  		)->{cpanelresult}->{data};
  	};
  
  	if (ref $resp eq 'ARRAY' and $resp->[0]) {
  		sleep $self->{db_sleep};
  		if ( $self->_set_dbprivs_cpanel($dbuser, $dbname) ) {
  			return $randompw;
  		}
  	}
  
  	return;
  }
  
  sub _set_dbprivs_cpanel {
  
  	my ($self, $dbuser, $dbname) = @_;
  
  	my $resp;
  	eval {
  		$resp = decode_json(
  			$self->get_cp_api->cpanel_api2_request('whostmgr',
  				{ module => 'MysqlFE', func => 'setdbuserprivileges', 'user' => $self->get_cpanel_username },
  				{ 'db' => $dbname, 'dbuser' => $dbuser, 'privileges' => 'ALL' },
  				'json'
  			)
  		)->{cpanelresult}->{data};
  	};
  
  	if (ref $resp eq 'ARRAY' and $resp->[0]) {
  		sleep ( ( ( $self->{db_sleep} ) > 5 )? $self->{db_sleep} - 5 : 5 );
  		return 1;
  	}
  	return;
  }
  
  sub _whitelist_cg_ips_for_mysql {
  
  	my $self = shift;
  
  	my $current_whitelist = $self->_fetch_current_whitelist();
  	my @ips_to_whitelist  = grep { not $current_whitelist->{$_} } @{ Codeguard::Fixer::CG_IPS() };
  	my $resp;
  
  	my $output;
  	foreach my $ip (@ips_to_whitelist) {
  		eval {
  			$resp = decode_json(
  				$self->get_cp_api->cpanel_api2_request('whostmgr',
  					{ module => 'MysqlFE', func => 'authorizehost', 'user' => $self->get_cpanel_username },
  					{ 'host' => $ip },
  					'json'
  				)
  			)->{cpanelresult}->{data};
  		};
  		if (ref $resp eq 'ARRAY' and $resp->[0]) {
  			$output->{$ip} = { success => 1 };
  		} else {
  			$output->{$ip} = { success => 0 };
  		}
  	}
  	return $output;
  }
  
  sub _fetch_current_whitelist {
  
  	my $self = shift;
  	my $resp;
  	eval {
  		$resp = decode_json(
  			$self->get_cp_api->cpanel_api2_request('whostmgr',
  				{ module => 'MysqlFE', func => 'listhosts', 'user' => $self->get_cpanel_username },
  				{ },
  				'json'
  			)
  		)->{cpanelresult}->{data};
  	};
  
  	my %ips;
  	if (ref $resp eq 'ARRAY' and ref $resp->[0] eq 'HASH') {
  		%ips = map { $_->{host} => 1 } @{$resp};
  	}
  	return \%ips;
  }
  
  sub _is_domain_blacklisted_or_missing {
  
  	my $self   = shift;
  	my $domain = shift;
  
  	my $blacklist  = $self->fetch_blacklist_on_cpanel;
  	if (
  		ref $blacklist eq 'HASH' and
  		scalar ( @{ $blacklist->{websites} } ) and
  		first { defined($_) and $_ eq $domain } @{$blacklist->{websites}}
  	) {
  		return "'$domain' is blacklisted on cPanel account.";
  	}
  	return $self->_docroot_exists($domain);
  }
  
  sub _docroot_exists {
  
  	my $self   = shift;
  	my $domain = shift;
  
  	my $resp;
  	eval {
  		$resp = decode_json(
  			$self->get_cp_api->cpanel_api2_request('whostmgr',
  				{ module => 'Hostgator', func => 'getdocroot', 'user' => $self->get_cpanel_username },
  				{ domain => $domain },
  				'json'
  			)
  		)->{cpanelresult}->{data};
  	};
  
  	if (ref $resp eq 'ARRAY' and ref $resp->[0] eq 'HASH'){
  		if ($resp->[0]->{exists}) {
  			return (undef, $resp->[0]->{docroot});
  		} else {
  			return "Docroot of '$domain' does not exist on the server.";
  		}
  	} else {
  		return "Unknown error!";
  	}
  }
  
  sub _get_ssh_key {
  
  	my $self = shift;
  
  	my $key  = $self->_fetch_ssh_key;
  	if ($key) {
  		return $key;
  	} else {
  		$self->_gen_auth_ssh_key or return;
  		return $self->_fetch_ssh_key;
  	}
  
  	return;
  }
  
  sub _fetch_ssh_key {
  
  	my $self = shift;
  
  	my $key;
  	eval {
  		my $resp = decode_json(
  			$self->get_cp_api->cpanel_api2_request('whostmgr',
  				{ module => 'SSH', func => 'fetchkey', 'user' => $self->get_cpanel_username },
  				{ 'name' => 'codeguard' },
  				'json'
  			)
  		)->{cpanelresult}->{data};
  		if (ref $resp eq 'ARRAY' and ref $resp->[0] eq 'HASH' and defined $resp->[0]->{key}) {
  			$key = $resp->[0]->{key};
  		}
  	};
  
  	return $key;
  }
  
  sub _gen_auth_ssh_key {
  
  	my $self = shift;
  
  	my $resp;
  	eval {
  		$resp = decode_json(
  			$self->get_cp_api->cpanel_api2_request('whostmgr',
  				{ module => 'SSH', func => 'genkey', 'user' => $self->get_cpanel_username },
  				{ bits => '2048', name => 'codeguard', type => 'rsa' },
  				'json'
  			)
  		)->{cpanelresult}->{data};
  
  		if (ref $resp eq 'ARRAY' and ref $resp->[0] eq 'HASH') {
  			if ( $resp->[0]->{result} and $resp->[0]->{reason} !~ m/failed/ ) {
  				$resp = $self->get_cp_api->cpanel_api2_request('whostmgr',
  					{ module => 'SSH', func => 'authkey', 'user' => $self->get_cpanel_username },
  					{ action => 'authorize', key => 'codeguard' },
  					'json'
  				);
  			} else {
  				die "Failed to generate SSH key. Error:\n$resp->[0]->{reason}\n";
  			}
  		} else {
  			die "Failed to generate SSH key. Unknown error.\n";
  		}
  	};
  
  	if ($@) {
  		return $self->error($@);
  	}
  	return 1;
  }
  
  sub _gen_rand_pass {
  
  	my $limit = shift;
  
  	my $allowed_letters = 'abcdefghijkmnpqrstuvwxyz';
  	my $string          = '';
  
  	while (length($string) < $limit) {
  		$string .= substr( $allowed_letters, ( int( rand( length($allowed_letters) ) ) ), 1 );
  	}
  
  	return $string;
  }
  
  1;
CODEGUARD_FIXERBASE

$fatpacked{"Exporter.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'EXPORTER';
  package Exporter;
  
  require 5.006;
  
  # Be lean.
  #use strict;
  #no strict 'refs';
  
  our $Debug = 0;
  our $ExportLevel = 0;
  our $Verbose ||= 0;
  our $VERSION = '5.68';
  our (%Cache);
  
  sub as_heavy {
    require Exporter::Heavy;
    # Unfortunately, this does not work if the caller is aliased as *name = \&foo
    # Thus the need to create a lot of identical subroutines
    my $c = (caller(1))[3];
    $c =~ s/.*:://;
    \&{"Exporter::Heavy::heavy_$c"};
  }
  
  sub export {
    goto &{as_heavy()};
  }
  
  sub import {
    my $pkg = shift;
    my $callpkg = caller($ExportLevel);
  
    if ($pkg eq "Exporter" and @_ and $_[0] eq "import") {
      *{$callpkg."::import"} = \&import;
      return;
    }
  
    # We *need* to treat @{"$pkg\::EXPORT_FAIL"} since Carp uses it :-(
    my $exports = \@{"$pkg\::EXPORT"};
    # But, avoid creating things if they don't exist, which saves a couple of
    # hundred bytes per package processed.
    my $fail = ${$pkg . '::'}{EXPORT_FAIL} && \@{"$pkg\::EXPORT_FAIL"};
    return export $pkg, $callpkg, @_
      if $Verbose or $Debug or $fail && @$fail > 1;
    my $export_cache = ($Cache{$pkg} ||= {});
    my $args = @_ or @_ = @$exports;
  
    if ($args and not %$export_cache) {
      s/^&//, $export_cache->{$_} = 1
        foreach (@$exports, @{"$pkg\::EXPORT_OK"});
    }
    my $heavy;
    # Try very hard not to use {} and hence have to  enter scope on the foreach
    # We bomb out of the loop with last as soon as heavy is set.
    if ($args or $fail) {
      ($heavy = (/\W/ or $args and not exists $export_cache->{$_}
                 or $fail and @$fail and $_ eq $fail->[0])) and last
                   foreach (@_);
    } else {
      ($heavy = /\W/) and last
        foreach (@_);
    }
    return export $pkg, $callpkg, ($args ? @_ : ()) if $heavy;
    local $SIG{__WARN__} = 
  	sub {require Carp; &Carp::carp} if not $SIG{__WARN__};
    # shortcut for the common case of no type character
    *{"$callpkg\::$_"} = \&{"$pkg\::$_"} foreach @_;
  }
  
  # Default methods
  
  sub export_fail {
      my $self = shift;
      @_;
  }
  
  # Unfortunately, caller(1)[3] "does not work" if the caller is aliased as
  # *name = \&foo.  Thus the need to create a lot of identical subroutines
  # Otherwise we could have aliased them to export().
  
  sub export_to_level {
    goto &{as_heavy()};
  }
  
  sub export_tags {
    goto &{as_heavy()};
  }
  
  sub export_ok_tags {
    goto &{as_heavy()};
  }
  
  sub require_version {
    goto &{as_heavy()};
  }
  
  1;
  __END__
  
  =head1 NAME
  
  Exporter - Implements default import method for modules
  
  =head1 SYNOPSIS
  
  In module F<YourModule.pm>:
  
    package YourModule;
    require Exporter;
    @ISA = qw(Exporter);
    @EXPORT_OK = qw(munge frobnicate);  # symbols to export on request
  
  or
  
    package YourModule;
    use Exporter 'import'; # gives you Exporter's import() method directly
    @EXPORT_OK = qw(munge frobnicate);  # symbols to export on request
  
  In other files which wish to use C<YourModule>:
  
    use YourModule qw(frobnicate);      # import listed symbols
    frobnicate ($left, $right)          # calls YourModule::frobnicate
  
  Take a look at L</Good Practices> for some variants
  you will like to use in modern Perl code.
  
  =head1 DESCRIPTION
  
  The Exporter module implements an C<import> method which allows a module
  to export functions and variables to its users' namespaces.  Many modules
  use Exporter rather than implementing their own C<import> method because
  Exporter provides a highly flexible interface, with an implementation optimised
  for the common case.
  
  Perl automatically calls the C<import> method when processing a
  C<use> statement for a module.  Modules and C<use> are documented
  in L<perlfunc> and L<perlmod>.  Understanding the concept of
  modules and how the C<use> statement operates is important to
  understanding the Exporter.
  
  =head2 How to Export
  
  The arrays C<@EXPORT> and C<@EXPORT_OK> in a module hold lists of
  symbols that are going to be exported into the users name space by
  default, or which they can request to be exported, respectively.  The
  symbols can represent functions, scalars, arrays, hashes, or typeglobs.
  The symbols must be given by full name with the exception that the
  ampersand in front of a function is optional, e.g.
  
      @EXPORT    = qw(afunc $scalar @array);   # afunc is a function
      @EXPORT_OK = qw(&bfunc %hash *typeglob); # explicit prefix on &bfunc
  
  If you are only exporting function names it is recommended to omit the
  ampersand, as the implementation is faster this way.
  
  =head2 Selecting What to Export
  
  Do B<not> export method names!
  
  Do B<not> export anything else by default without a good reason!
  
  Exports pollute the namespace of the module user.  If you must export
  try to use C<@EXPORT_OK> in preference to C<@EXPORT> and avoid short or
  common symbol names to reduce the risk of name clashes.
  
  Generally anything not exported is still accessible from outside the
  module using the C<YourModule::item_name> (or C<< $blessed_ref->method >>)
  syntax.  By convention you can use a leading underscore on names to
  informally indicate that they are 'internal' and not for public use.
  
  (It is actually possible to get private functions by saying:
  
    my $subref = sub { ... };
    $subref->(@args);            # Call it as a function
    $obj->$subref(@args);        # Use it as a method
  
  However if you use them for methods it is up to you to figure out
  how to make inheritance work.)
  
  As a general rule, if the module is trying to be object oriented
  then export nothing.  If it's just a collection of functions then
  C<@EXPORT_OK> anything but use C<@EXPORT> with caution.  For function and
  method names use barewords in preference to names prefixed with
  ampersands for the export lists.
  
  Other module design guidelines can be found in L<perlmod>.
  
  =head2 How to Import
  
  In other files which wish to use your module there are three basic ways for
  them to load your module and import its symbols:
  
  =over 4
  
  =item C<use YourModule;>
  
  This imports all the symbols from YourModule's C<@EXPORT> into the namespace
  of the C<use> statement.
  
  =item C<use YourModule ();>
  
  This causes perl to load your module but does not import any symbols.
  
  =item C<use YourModule qw(...);>
  
  This imports only the symbols listed by the caller into their namespace.
  All listed symbols must be in your C<@EXPORT> or C<@EXPORT_OK>, else an error
  occurs.  The advanced export features of Exporter are accessed like this,
  but with list entries that are syntactically distinct from symbol names.
  
  =back
  
  Unless you want to use its advanced features, this is probably all you
  need to know to use Exporter.
  
  =head1 Advanced Features
  
  =head2 Specialised Import Lists
  
  If any of the entries in an import list begins with !, : or / then
  the list is treated as a series of specifications which either add to
  or delete from the list of names to import.  They are processed left to
  right. Specifications are in the form:
  
      [!]name         This name only
      [!]:DEFAULT     All names in @EXPORT
      [!]:tag         All names in $EXPORT_TAGS{tag} anonymous list
      [!]/pattern/    All names in @EXPORT and @EXPORT_OK which match
  
  A leading ! indicates that matching names should be deleted from the
  list of names to import.  If the first specification is a deletion it
  is treated as though preceded by :DEFAULT.  If you just want to import
  extra names in addition to the default set you will still need to
  include :DEFAULT explicitly.
  
  e.g., F<Module.pm> defines:
  
      @EXPORT      = qw(A1 A2 A3 A4 A5);
      @EXPORT_OK   = qw(B1 B2 B3 B4 B5);
      %EXPORT_TAGS = (T1 => [qw(A1 A2 B1 B2)], T2 => [qw(A1 A2 B3 B4)]);
  
  Note that you cannot use tags in @EXPORT or @EXPORT_OK.
  
  Names in EXPORT_TAGS must also appear in @EXPORT or @EXPORT_OK.
  
  An application using Module can say something like:
  
      use Module qw(:DEFAULT :T2 !B3 A3);
  
  Other examples include:
  
      use Socket qw(!/^[AP]F_/ !SOMAXCONN !SOL_SOCKET);
      use POSIX  qw(:errno_h :termios_h !TCSADRAIN !/^EXIT/);
  
  Remember that most patterns (using //) will need to be anchored
  with a leading ^, e.g., C</^EXIT/> rather than C</EXIT/>.
  
  You can say C<BEGIN { $Exporter::Verbose=1 }> to see how the
  specifications are being processed and what is actually being imported
  into modules.
  
  =head2 Exporting Without Using Exporter's import Method
  
  Exporter has a special method, 'export_to_level' which is used in situations
  where you can't directly call Exporter's
  import method.  The export_to_level
  method looks like:
  
      MyPackage->export_to_level(
  	$where_to_export, $package, @what_to_export
      );
  
  where C<$where_to_export> is an integer telling how far up the calling stack
  to export your symbols, and C<@what_to_export> is an array telling what
  symbols *to* export (usually this is C<@_>).  The C<$package> argument is
  currently unused.
  
  For example, suppose that you have a module, A, which already has an
  import function:
  
      package A;
  
      @ISA = qw(Exporter);
      @EXPORT_OK = qw ($b);
  
      sub import
      {
  	$A::b = 1;     # not a very useful import method
      }
  
  and you want to Export symbol C<$A::b> back to the module that called 
  package A.  Since Exporter relies on the import method to work, via 
  inheritance, as it stands Exporter::import() will never get called. 
  Instead, say the following:
  
      package A;
      @ISA = qw(Exporter);
      @EXPORT_OK = qw ($b);
  
      sub import
      {
  	$A::b = 1;
  	A->export_to_level(1, @_);
      }
  
  This will export the symbols one level 'above' the current package - ie: to 
  the program or module that used package A. 
  
  Note: Be careful not to modify C<@_> at all before you call export_to_level
  - or people using your package will get very unexplained results!
  
  =head2 Exporting Without Inheriting from Exporter
  
  By including Exporter in your C<@ISA> you inherit an Exporter's import() method
  but you also inherit several other helper methods which you probably don't
  want.  To avoid this you can do
  
    package YourModule;
    use Exporter qw( import );
  
  which will export Exporter's own import() method into YourModule.
  Everything will work as before but you won't need to include Exporter in
  C<@YourModule::ISA>.
  
  Note: This feature was introduced in version 5.57
  of Exporter, released with perl 5.8.3.
  
  =head2 Module Version Checking
  
  The Exporter module will convert an attempt to import a number from a
  module into a call to C<< $module_name->VERSION($value) >>.  This can
  be used to validate that the version of the module being used is
  greater than or equal to the required version.
  
  For historical reasons, Exporter supplies a C<require_version> method that
  simply delegates to C<VERSION>.  Originally, before C<UNIVERSAL::VERSION>
  existed, Exporter would call C<require_version>.
  
  Since the C<UNIVERSAL::VERSION> method treats the C<$VERSION> number as
  a simple numeric value it will regard version 1.10 as lower than
  1.9.  For this reason it is strongly recommended that you use numbers
  with at least two decimal places, e.g., 1.09.
  
  =head2 Managing Unknown Symbols
  
  In some situations you may want to prevent certain symbols from being
  exported.  Typically this applies to extensions which have functions
  or constants that may not exist on some systems.
  
  The names of any symbols that cannot be exported should be listed
  in the C<@EXPORT_FAIL> array.
  
  If a module attempts to import any of these symbols the Exporter
  will give the module an opportunity to handle the situation before
  generating an error.  The Exporter will call an export_fail method
  with a list of the failed symbols:
  
    @failed_symbols = $module_name->export_fail(@failed_symbols);
  
  If the C<export_fail> method returns an empty list then no error is
  recorded and all the requested symbols are exported.  If the returned
  list is not empty then an error is generated for each symbol and the
  export fails.  The Exporter provides a default C<export_fail> method which
  simply returns the list unchanged.
  
  Uses for the C<export_fail> method include giving better error messages
  for some symbols and performing lazy architectural checks (put more
  symbols into C<@EXPORT_FAIL> by default and then take them out if someone
  actually tries to use them and an expensive check shows that they are
  usable on that platform).
  
  =head2 Tag Handling Utility Functions
  
  Since the symbols listed within C<%EXPORT_TAGS> must also appear in either
  C<@EXPORT> or C<@EXPORT_OK>, two utility functions are provided which allow
  you to easily add tagged sets of symbols to C<@EXPORT> or C<@EXPORT_OK>:
  
    %EXPORT_TAGS = (foo => [qw(aa bb cc)], bar => [qw(aa cc dd)]);
  
    Exporter::export_tags('foo');     # add aa, bb and cc to @EXPORT
    Exporter::export_ok_tags('bar');  # add aa, cc and dd to @EXPORT_OK
  
  Any names which are not tags are added to C<@EXPORT> or C<@EXPORT_OK>
  unchanged but will trigger a warning (with C<-w>) to avoid misspelt tags
  names being silently added to C<@EXPORT> or C<@EXPORT_OK>.  Future versions
  may make this a fatal error.
  
  =head2 Generating Combined Tags
  
  If several symbol categories exist in C<%EXPORT_TAGS>, it's usually
  useful to create the utility ":all" to simplify "use" statements.
  
  The simplest way to do this is:
  
    %EXPORT_TAGS = (foo => [qw(aa bb cc)], bar => [qw(aa cc dd)]);
  
    # add all the other ":class" tags to the ":all" class,
    # deleting duplicates
    {
      my %seen;
  
      push @{$EXPORT_TAGS{all}},
        grep {!$seen{$_}++} @{$EXPORT_TAGS{$_}} foreach keys %EXPORT_TAGS;
    }
  
  F<CGI.pm> creates an ":all" tag which contains some (but not really
  all) of its categories.  That could be done with one small
  change:
  
    # add some of the other ":class" tags to the ":all" class,
    # deleting duplicates
    {
      my %seen;
  
      push @{$EXPORT_TAGS{all}},
        grep {!$seen{$_}++} @{$EXPORT_TAGS{$_}}
          foreach qw/html2 html3 netscape form cgi internal/;
    }
  
  Note that the tag names in C<%EXPORT_TAGS> don't have the leading ':'.
  
  =head2 C<AUTOLOAD>ed Constants
  
  Many modules make use of C<AUTOLOAD>ing for constant subroutines to
  avoid having to compile and waste memory on rarely used values (see
  L<perlsub> for details on constant subroutines).  Calls to such
  constant subroutines are not optimized away at compile time because
  they can't be checked at compile time for constancy.
  
  Even if a prototype is available at compile time, the body of the
  subroutine is not (it hasn't been C<AUTOLOAD>ed yet).  perl needs to
  examine both the C<()> prototype and the body of a subroutine at
  compile time to detect that it can safely replace calls to that
  subroutine with the constant value.
  
  A workaround for this is to call the constants once in a C<BEGIN> block:
  
     package My ;
  
     use Socket ;
  
     foo( SO_LINGER );  ## SO_LINGER NOT optimized away; called at runtime
     BEGIN { SO_LINGER }
     foo( SO_LINGER );  ## SO_LINGER optimized away at compile time.
  
  This forces the C<AUTOLOAD> for C<SO_LINGER> to take place before
  SO_LINGER is encountered later in C<My> package.
  
  If you are writing a package that C<AUTOLOAD>s, consider forcing
  an C<AUTOLOAD> for any constants explicitly imported by other packages
  or which are usually used when your package is C<use>d.
  
  =head1 Good Practices
  
  =head2 Declaring C<@EXPORT_OK> and Friends
  
  When using C<Exporter> with the standard C<strict> and C<warnings>
  pragmas, the C<our> keyword is needed to declare the package
  variables C<@EXPORT_OK>, C<@EXPORT>, C<@ISA>, etc.
  
    our @ISA = qw(Exporter);
    our @EXPORT_OK = qw(munge frobnicate);
  
  If backward compatibility for Perls under 5.6 is important,
  one must write instead a C<use vars> statement.
  
    use vars qw(@ISA @EXPORT_OK);
    @ISA = qw(Exporter);
    @EXPORT_OK = qw(munge frobnicate);
  
  =head2 Playing Safe
  
  There are some caveats with the use of runtime statements
  like C<require Exporter> and the assignment to package
  variables, which can very subtle for the unaware programmer.
  This may happen for instance with mutually recursive
  modules, which are affected by the time the relevant
  constructions are executed.
  
  The ideal (but a bit ugly) way to never have to think
  about that is to use C<BEGIN> blocks.  So the first part
  of the L</SYNOPSIS> code could be rewritten as:
  
    package YourModule;
  
    use strict;
    use warnings;
  
    our (@ISA, @EXPORT_OK);
    BEGIN {
       require Exporter;
       @ISA = qw(Exporter);
       @EXPORT_OK = qw(munge frobnicate);  # symbols to export on request
    }
  
  The C<BEGIN> will assure that the loading of F<Exporter.pm>
  and the assignments to C<@ISA> and C<@EXPORT_OK> happen
  immediately, leaving no room for something to get awry
  or just plain wrong.
  
  With respect to loading C<Exporter> and inheriting, there
  are alternatives with the use of modules like C<base> and C<parent>.
  
    use base qw( Exporter );
    # or
    use parent qw( Exporter );
  
  Any of these statements are nice replacements for
  C<BEGIN { require Exporter; @ISA = qw(Exporter); }>
  with the same compile-time effect.  The basic difference
  is that C<base> code interacts with declared C<fields>
  while C<parent> is a streamlined version of the older
  C<base> code to just establish the IS-A relationship.
  
  For more details, see the documentation and code of
  L<base> and L<parent>.
  
  Another thorough remedy to that runtime
  vs. compile-time trap is to use L<Exporter::Easy>,
  which is a wrapper of Exporter that allows all
  boilerplate code at a single gulp in the
  use statement.
  
     use Exporter::Easy (
         OK => [ qw(munge frobnicate) ],
     );
     # @ISA setup is automatic
     # all assignments happen at compile time
  
  =head2 What Not to Export
  
  You have been warned already in L</Selecting What to Export>
  to not export:
  
  =over 4
  
  =item *
  
  method names (because you don't need to
  and that's likely to not do what you want),
  
  =item *
  
  anything by default (because you don't want to surprise your users...
  badly)
  
  =item *
  
  anything you don't need to (because less is more)
  
  =back
  
  There's one more item to add to this list.  Do B<not>
  export variable names.  Just because C<Exporter> lets you
  do that, it does not mean you should.
  
    @EXPORT_OK = qw( $svar @avar %hvar ); # DON'T!
  
  Exporting variables is not a good idea.  They can
  change under the hood, provoking horrible
  effects at-a-distance, that are too hard to track
  and to fix.  Trust me: they are not worth it.
  
  To provide the capability to set/get class-wide
  settings, it is best instead to provide accessors
  as subroutines or class methods instead.
  
  =head1 SEE ALSO
  
  C<Exporter> is definitely not the only module with
  symbol exporter capabilities.  At CPAN, you may find
  a bunch of them.  Some are lighter.  Some
  provide improved APIs and features.  Peek the one
  that fits your needs.  The following is
  a sample list of such modules.
  
      Exporter::Easy
      Exporter::Lite
      Exporter::Renaming
      Exporter::Tidy
      Sub::Exporter / Sub::Installer
      Perl6::Export / Perl6::Export::Attrs
  
  =head1 LICENSE
  
  This library is free software.  You can redistribute it
  and/or modify it under the same terms as Perl itself.
  
  =cut
  
  
  
EXPORTER

$fatpacked{"Exporter/Heavy.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'EXPORTER_HEAVY';
  package Exporter::Heavy;
  
  use strict;
  no strict 'refs';
  
  # On one line so MakeMaker will see it.
  require Exporter;  our $VERSION = $Exporter::VERSION;
  
  =head1 NAME
  
  Exporter::Heavy - Exporter guts
  
  =head1 SYNOPSIS
  
  (internal use only)
  
  =head1 DESCRIPTION
  
  No user-serviceable parts inside.
  
  =cut
  
  #
  # We go to a lot of trouble not to 'require Carp' at file scope,
  #  because Carp requires Exporter, and something has to give.
  #
  
  sub _rebuild_cache {
      my ($pkg, $exports, $cache) = @_;
      s/^&// foreach @$exports;
      @{$cache}{@$exports} = (1) x @$exports;
      my $ok = \@{"${pkg}::EXPORT_OK"};
      if (@$ok) {
  	s/^&// foreach @$ok;
  	@{$cache}{@$ok} = (1) x @$ok;
      }
  }
  
  sub heavy_export {
  
      # First make import warnings look like they're coming from the "use".
      local $SIG{__WARN__} = sub {
  	my $text = shift;
  	if ($text =~ s/ at \S*Exporter\S*.pm line \d+.*\n//) {
  	    require Carp;
  	    local $Carp::CarpLevel = 1;	# ignore package calling us too.
  	    Carp::carp($text);
  	}
  	else {
  	    warn $text;
  	}
      };
      local $SIG{__DIE__} = sub {
  	require Carp;
  	local $Carp::CarpLevel = 1;	# ignore package calling us too.
  	Carp::croak("$_[0]Illegal null symbol in \@${1}::EXPORT")
  	    if $_[0] =~ /^Unable to create sub named "(.*?)::"/;
      };
  
      my($pkg, $callpkg, @imports) = @_;
      my($type, $sym, $cache_is_current, $oops);
      my($exports, $export_cache) = (\@{"${pkg}::EXPORT"},
                                     $Exporter::Cache{$pkg} ||= {});
  
      if (@imports) {
  	if (!%$export_cache) {
  	    _rebuild_cache ($pkg, $exports, $export_cache);
  	    $cache_is_current = 1;
  	}
  
  	if (grep m{^[/!:]}, @imports) {
  	    my $tagsref = \%{"${pkg}::EXPORT_TAGS"};
  	    my $tagdata;
  	    my %imports;
  	    my($remove, $spec, @names, @allexports);
  	    # negated first item implies starting with default set:
  	    unshift @imports, ':DEFAULT' if $imports[0] =~ m/^!/;
  	    foreach $spec (@imports){
  		$remove = $spec =~ s/^!//;
  
  		if ($spec =~ s/^://){
  		    if ($spec eq 'DEFAULT'){
  			@names = @$exports;
  		    }
  		    elsif ($tagdata = $tagsref->{$spec}) {
  			@names = @$tagdata;
  		    }
  		    else {
  			warn qq["$spec" is not defined in %${pkg}::EXPORT_TAGS];
  			++$oops;
  			next;
  		    }
  		}
  		elsif ($spec =~ m:^/(.*)/$:){
  		    my $patn = $1;
  		    @allexports = keys %$export_cache unless @allexports; # only do keys once
  		    @names = grep(/$patn/, @allexports); # not anchored by default
  		}
  		else {
  		    @names = ($spec); # is a normal symbol name
  		}
  
  		warn "Import ".($remove ? "del":"add").": @names "
  		    if $Exporter::Verbose;
  
  		if ($remove) {
  		   foreach $sym (@names) { delete $imports{$sym} } 
  		}
  		else {
  		    @imports{@names} = (1) x @names;
  		}
  	    }
  	    @imports = keys %imports;
  	}
  
          my @carp;
  	foreach $sym (@imports) {
  	    if (!$export_cache->{$sym}) {
  		if ($sym =~ m/^\d/) {
  		    $pkg->VERSION($sym); # inherit from UNIVERSAL
  		    # If the version number was the only thing specified
  		    # then we should act as if nothing was specified:
  		    if (@imports == 1) {
  			@imports = @$exports;
  			last;
  		    }
  		    # We need a way to emulate 'use Foo ()' but still
  		    # allow an easy version check: "use Foo 1.23, ''";
  		    if (@imports == 2 and !$imports[1]) {
  			@imports = ();
  			last;
  		    }
  		} elsif ($sym !~ s/^&// || !$export_cache->{$sym}) {
  		    # Last chance - see if they've updated EXPORT_OK since we
  		    # cached it.
  
  		    unless ($cache_is_current) {
  			%$export_cache = ();
  			_rebuild_cache ($pkg, $exports, $export_cache);
  			$cache_is_current = 1;
  		    }
  
  		    if (!$export_cache->{$sym}) {
  			# accumulate the non-exports
  			push @carp,
  			  qq["$sym" is not exported by the $pkg module\n];
  			$oops++;
  		    }
  		}
  	    }
  	}
  	if ($oops) {
  	    require Carp;
  	    Carp::croak("@{carp}Can't continue after import errors");
  	}
      }
      else {
  	@imports = @$exports;
      }
  
      my($fail, $fail_cache) = (\@{"${pkg}::EXPORT_FAIL"},
                                $Exporter::FailCache{$pkg} ||= {});
  
      if (@$fail) {
  	if (!%$fail_cache) {
  	    # Build cache of symbols. Optimise the lookup by adding
  	    # barewords twice... both with and without a leading &.
  	    # (Technique could be applied to $export_cache at cost of memory)
  	    my @expanded = map { /^\w/ ? ($_, '&'.$_) : $_ } @$fail;
  	    warn "${pkg}::EXPORT_FAIL cached: @expanded" if $Exporter::Verbose;
  	    @{$fail_cache}{@expanded} = (1) x @expanded;
  	}
  	my @failed;
  	foreach $sym (@imports) { push(@failed, $sym) if $fail_cache->{$sym} }
  	if (@failed) {
  	    @failed = $pkg->export_fail(@failed);
  	    foreach $sym (@failed) {
                  require Carp;
  		Carp::carp(qq["$sym" is not implemented by the $pkg module ],
  			"on this architecture");
  	    }
  	    if (@failed) {
  		require Carp;
  		Carp::croak("Can't continue after import errors");
  	    }
  	}
      }
  
      warn "Importing into $callpkg from $pkg: ",
  		join(", ",sort @imports) if $Exporter::Verbose;
  
      foreach $sym (@imports) {
  	# shortcut for the common case of no type character
  	(*{"${callpkg}::$sym"} = \&{"${pkg}::$sym"}, next)
  	    unless $sym =~ s/^(\W)//;
  	$type = $1;
  	no warnings 'once';
  	*{"${callpkg}::$sym"} =
  	    $type eq '&' ? \&{"${pkg}::$sym"} :
  	    $type eq '$' ? \${"${pkg}::$sym"} :
  	    $type eq '@' ? \@{"${pkg}::$sym"} :
  	    $type eq '%' ? \%{"${pkg}::$sym"} :
  	    $type eq '*' ?  *{"${pkg}::$sym"} :
  	    do { require Carp; Carp::croak("Can't export symbol: $type$sym") };
      }
  }
  
  sub heavy_export_to_level
  {
        my $pkg = shift;
        my $level = shift;
        (undef) = shift;			# XXX redundant arg
        my $callpkg = caller($level);
        $pkg->export($callpkg, @_);
  }
  
  # Utility functions
  
  sub _push_tags {
      my($pkg, $var, $syms) = @_;
      my @nontag = ();
      my $export_tags = \%{"${pkg}::EXPORT_TAGS"};
      push(@{"${pkg}::$var"},
  	map { $export_tags->{$_} ? @{$export_tags->{$_}} 
                                   : scalar(push(@nontag,$_),$_) }
  		(@$syms) ? @$syms : keys %$export_tags);
      if (@nontag and $^W) {
  	# This may change to a die one day
  	require Carp;
  	Carp::carp(join(", ", @nontag)." are not tags of $pkg");
      }
  }
  
  sub heavy_require_version {
      my($self, $wanted) = @_;
      my $pkg = ref $self || $self;
      return ${pkg}->VERSION($wanted);
  }
  
  sub heavy_export_tags {
    _push_tags((caller)[0], "EXPORT",    \@_);
  }
  
  sub heavy_export_ok_tags {
    _push_tags((caller)[0], "EXPORT_OK", \@_);
  }
  
  1;
EXPORTER_HEAVY

$fatpacked{"Getopt/Long.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'GETOPT_LONG';
  #! perl
  
  # Getopt::Long.pm -- Universal options parsing
  # Author          : Johan Vromans
  # Created On      : Tue Sep 11 15:00:12 1990
  # Last Modified By: Johan Vromans
  # Last Modified On: Tue Oct  1 08:25:52 2013
  # Update Count    : 1651
  # Status          : Released
  
  ################ Module Preamble ################
  
  package Getopt::Long;
  
  use 5.004;
  
  use strict;
  
  use vars qw($VERSION);
  $VERSION        =  2.42;
  # For testing versions only.
  use vars qw($VERSION_STRING);
  $VERSION_STRING = "2.42";
  
  use Exporter;
  use vars qw(@ISA @EXPORT @EXPORT_OK);
  @ISA = qw(Exporter);
  
  # Exported subroutines.
  sub GetOptions(@);		# always
  sub GetOptionsFromArray(@);	# on demand
  sub GetOptionsFromString(@);	# on demand
  sub Configure(@);		# on demand
  sub HelpMessage(@);		# on demand
  sub VersionMessage(@);		# in demand
  
  BEGIN {
      # Init immediately so their contents can be used in the 'use vars' below.
      @EXPORT    = qw(&GetOptions $REQUIRE_ORDER $PERMUTE $RETURN_IN_ORDER);
      @EXPORT_OK = qw(&HelpMessage &VersionMessage &Configure
  		    &GetOptionsFromArray &GetOptionsFromString);
  }
  
  # User visible variables.
  use vars @EXPORT, @EXPORT_OK;
  use vars qw($error $debug $major_version $minor_version);
  # Deprecated visible variables.
  use vars qw($autoabbrev $getopt_compat $ignorecase $bundling $order
  	    $passthrough);
  # Official invisible variables.
  use vars qw($genprefix $caller $gnu_compat $auto_help $auto_version $longprefix);
  
  # Public subroutines.
  sub config(@);			# deprecated name
  
  # Private subroutines.
  sub ConfigDefaults();
  sub ParseOptionSpec($$);
  sub OptCtl($);
  sub FindOption($$$$$);
  sub ValidValue ($$$$$);
  
  ################ Local Variables ################
  
  # $requested_version holds the version that was mentioned in the 'use'
  # or 'require', if any. It can be used to enable or disable specific
  # features.
  my $requested_version = 0;
  
  ################ Resident subroutines ################
  
  sub ConfigDefaults() {
      # Handle POSIX compliancy.
      if ( defined $ENV{"POSIXLY_CORRECT"} ) {
  	$genprefix = "(--|-)";
  	$autoabbrev = 0;		# no automatic abbrev of options
  	$bundling = 0;			# no bundling of single letter switches
  	$getopt_compat = 0;		# disallow '+' to start options
  	$order = $REQUIRE_ORDER;
      }
      else {
  	$genprefix = "(--|-|\\+)";
  	$autoabbrev = 1;		# automatic abbrev of options
  	$bundling = 0;			# bundling off by default
  	$getopt_compat = 1;		# allow '+' to start options
  	$order = $PERMUTE;
      }
      # Other configurable settings.
      $debug = 0;			# for debugging
      $error = 0;			# error tally
      $ignorecase = 1;		# ignore case when matching options
      $passthrough = 0;		# leave unrecognized options alone
      $gnu_compat = 0;		# require --opt=val if value is optional
      $longprefix = "(--)";       # what does a long prefix look like
  }
  
  # Override import.
  sub import {
      my $pkg = shift;		# package
      my @syms = ();		# symbols to import
      my @config = ();		# configuration
      my $dest = \@syms;		# symbols first
      for ( @_ ) {
  	if ( $_ eq ':config' ) {
  	    $dest = \@config;	# config next
  	    next;
  	}
  	push(@$dest, $_);	# push
      }
      # Hide one level and call super.
      local $Exporter::ExportLevel = 1;
      push(@syms, qw(&GetOptions)) if @syms; # always export GetOptions
      $requested_version = 0;
      $pkg->SUPER::import(@syms);
      # And configure.
      Configure(@config) if @config;
  }
  
  ################ Initialization ################
  
  # Values for $order. See GNU getopt.c for details.
  ($REQUIRE_ORDER, $PERMUTE, $RETURN_IN_ORDER) = (0..2);
  # Version major/minor numbers.
  ($major_version, $minor_version) = $VERSION =~ /^(\d+)\.(\d+)/;
  
  ConfigDefaults();
  
  ################ OO Interface ################
  
  package Getopt::Long::Parser;
  
  # Store a copy of the default configuration. Since ConfigDefaults has
  # just been called, what we get from Configure is the default.
  my $default_config = do {
      Getopt::Long::Configure ()
  };
  
  sub new {
      my $that = shift;
      my $class = ref($that) || $that;
      my %atts = @_;
  
      # Register the callers package.
      my $self = { caller_pkg => (caller)[0] };
  
      bless ($self, $class);
  
      # Process config attributes.
      if ( defined $atts{config} ) {
  	my $save = Getopt::Long::Configure ($default_config, @{$atts{config}});
  	$self->{settings} = Getopt::Long::Configure ($save);
  	delete ($atts{config});
      }
      # Else use default config.
      else {
  	$self->{settings} = $default_config;
      }
  
      if ( %atts ) {		# Oops
  	die(__PACKAGE__.": unhandled attributes: ".
  	    join(" ", sort(keys(%atts)))."\n");
      }
  
      $self;
  }
  
  sub configure {
      my ($self) = shift;
  
      # Restore settings, merge new settings in.
      my $save = Getopt::Long::Configure ($self->{settings}, @_);
  
      # Restore orig config and save the new config.
      $self->{settings} = Getopt::Long::Configure ($save);
  }
  
  sub getoptions {
      my ($self) = shift;
  
      return $self->getoptionsfromarray(\@ARGV, @_);
  }
  
  sub getoptionsfromarray {
      my ($self) = shift;
  
      # Restore config settings.
      my $save = Getopt::Long::Configure ($self->{settings});
  
      # Call main routine.
      my $ret = 0;
      $Getopt::Long::caller = $self->{caller_pkg};
  
      eval {
  	# Locally set exception handler to default, otherwise it will
  	# be called implicitly here, and again explicitly when we try
  	# to deliver the messages.
  	local ($SIG{__DIE__}) = 'DEFAULT';
  	$ret = Getopt::Long::GetOptionsFromArray (@_);
      };
  
      # Restore saved settings.
      Getopt::Long::Configure ($save);
  
      # Handle errors and return value.
      die ($@) if $@;
      return $ret;
  }
  
  package Getopt::Long;
  
  ################ Back to Normal ################
  
  # Indices in option control info.
  # Note that ParseOptions uses the fields directly. Search for 'hard-wired'.
  use constant CTL_TYPE    => 0;
  #use constant   CTL_TYPE_FLAG   => '';
  #use constant   CTL_TYPE_NEG    => '!';
  #use constant   CTL_TYPE_INCR   => '+';
  #use constant   CTL_TYPE_INT    => 'i';
  #use constant   CTL_TYPE_INTINC => 'I';
  #use constant   CTL_TYPE_XINT   => 'o';
  #use constant   CTL_TYPE_FLOAT  => 'f';
  #use constant   CTL_TYPE_STRING => 's';
  
  use constant CTL_CNAME   => 1;
  
  use constant CTL_DEFAULT => 2;
  
  use constant CTL_DEST    => 3;
   use constant   CTL_DEST_SCALAR => 0;
   use constant   CTL_DEST_ARRAY  => 1;
   use constant   CTL_DEST_HASH   => 2;
   use constant   CTL_DEST_CODE   => 3;
  
  use constant CTL_AMIN    => 4;
  use constant CTL_AMAX    => 5;
  
  # FFU.
  #use constant CTL_RANGE   => ;
  #use constant CTL_REPEAT  => ;
  
  # Rather liberal patterns to match numbers.
  use constant PAT_INT   => "[-+]?_*[0-9][0-9_]*";
  use constant PAT_XINT  =>
    "(?:".
  	  "[-+]?_*[1-9][0-9_]*".
    "|".
  	  "0x_*[0-9a-f][0-9a-f_]*".
    "|".
  	  "0b_*[01][01_]*".
    "|".
  	  "0[0-7_]*".
    ")";
  use constant PAT_FLOAT => "[-+]?[0-9_]+(\.[0-9_]+)?([eE][-+]?[0-9_]+)?";
  
  sub GetOptions(@) {
      # Shift in default array.
      unshift(@_, \@ARGV);
      # Try to keep caller() and Carp consistent.
      goto &GetOptionsFromArray;
  }
  
  sub GetOptionsFromString(@) {
      my ($string) = shift;
      require Text::ParseWords;
      my $args = [ Text::ParseWords::shellwords($string) ];
      $caller ||= (caller)[0];	# current context
      my $ret = GetOptionsFromArray($args, @_);
      return ( $ret, $args ) if wantarray;
      if ( @$args ) {
  	$ret = 0;
  	warn("GetOptionsFromString: Excess data \"@$args\" in string \"$string\"\n");
      }
      $ret;
  }
  
  sub GetOptionsFromArray(@) {
  
      my ($argv, @optionlist) = @_;	# local copy of the option descriptions
      my $argend = '--';		# option list terminator
      my %opctl = ();		# table of option specs
      my $pkg = $caller || (caller)[0];	# current context
  				# Needed if linkage is omitted.
      my @ret = ();		# accum for non-options
      my %linkage;		# linkage
      my $userlinkage;		# user supplied HASH
      my $opt;			# current option
      my $prefix = $genprefix;	# current prefix
  
      $error = '';
  
      if ( $debug ) {
  	# Avoid some warnings if debugging.
  	local ($^W) = 0;
  	print STDERR
  	  ("Getopt::Long $Getopt::Long::VERSION ",
  	   "called from package \"$pkg\".",
  	   "\n  ",
  	   "argv: (@$argv)",
  	   "\n  ",
  	   "autoabbrev=$autoabbrev,".
  	   "bundling=$bundling,",
  	   "getopt_compat=$getopt_compat,",
  	   "gnu_compat=$gnu_compat,",
  	   "order=$order,",
  	   "\n  ",
  	   "ignorecase=$ignorecase,",
  	   "requested_version=$requested_version,",
  	   "passthrough=$passthrough,",
  	   "genprefix=\"$genprefix\",",
  	   "longprefix=\"$longprefix\".",
  	   "\n");
      }
  
      # Check for ref HASH as first argument.
      # First argument may be an object. It's OK to use this as long
      # as it is really a hash underneath.
      $userlinkage = undef;
      if ( @optionlist && ref($optionlist[0]) and
  	 UNIVERSAL::isa($optionlist[0],'HASH') ) {
  	$userlinkage = shift (@optionlist);
  	print STDERR ("=> user linkage: $userlinkage\n") if $debug;
      }
  
      # See if the first element of the optionlist contains option
      # starter characters.
      # Be careful not to interpret '<>' as option starters.
      if ( @optionlist && $optionlist[0] =~ /^\W+$/
  	 && !($optionlist[0] eq '<>'
  	      && @optionlist > 0
  	      && ref($optionlist[1])) ) {
  	$prefix = shift (@optionlist);
  	# Turn into regexp. Needs to be parenthesized!
  	$prefix =~ s/(\W)/\\$1/g;
  	$prefix = "([" . $prefix . "])";
  	print STDERR ("=> prefix=\"$prefix\"\n") if $debug;
      }
  
      # Verify correctness of optionlist.
      %opctl = ();
      while ( @optionlist ) {
  	my $opt = shift (@optionlist);
  
  	unless ( defined($opt) ) {
  	    $error .= "Undefined argument in option spec\n";
  	    next;
  	}
  
  	# Strip leading prefix so people can specify "--foo=i" if they like.
  	$opt = $+ if $opt =~ /^$prefix+(.*)$/s;
  
  	if ( $opt eq '<>' ) {
  	    if ( (defined $userlinkage)
  		&& !(@optionlist > 0 && ref($optionlist[0]))
  		&& (exists $userlinkage->{$opt})
  		&& ref($userlinkage->{$opt}) ) {
  		unshift (@optionlist, $userlinkage->{$opt});
  	    }
  	    unless ( @optionlist > 0
  		    && ref($optionlist[0]) && ref($optionlist[0]) eq 'CODE' ) {
  		$error .= "Option spec <> requires a reference to a subroutine\n";
  		# Kill the linkage (to avoid another error).
  		shift (@optionlist)
  		  if @optionlist && ref($optionlist[0]);
  		next;
  	    }
  	    $linkage{'<>'} = shift (@optionlist);
  	    next;
  	}
  
  	# Parse option spec.
  	my ($name, $orig) = ParseOptionSpec ($opt, \%opctl);
  	unless ( defined $name ) {
  	    # Failed. $orig contains the error message. Sorry for the abuse.
  	    $error .= $orig;
  	    # Kill the linkage (to avoid another error).
  	    shift (@optionlist)
  	      if @optionlist && ref($optionlist[0]);
  	    next;
  	}
  
  	# If no linkage is supplied in the @optionlist, copy it from
  	# the userlinkage if available.
  	if ( defined $userlinkage ) {
  	    unless ( @optionlist > 0 && ref($optionlist[0]) ) {
  		if ( exists $userlinkage->{$orig} &&
  		     ref($userlinkage->{$orig}) ) {
  		    print STDERR ("=> found userlinkage for \"$orig\": ",
  				  "$userlinkage->{$orig}\n")
  			if $debug;
  		    unshift (@optionlist, $userlinkage->{$orig});
  		}
  		else {
  		    # Do nothing. Being undefined will be handled later.
  		    next;
  		}
  	    }
  	}
  
  	# Copy the linkage. If omitted, link to global variable.
  	if ( @optionlist > 0 && ref($optionlist[0]) ) {
  	    print STDERR ("=> link \"$orig\" to $optionlist[0]\n")
  		if $debug;
  	    my $rl = ref($linkage{$orig} = shift (@optionlist));
  
  	    if ( $rl eq "ARRAY" ) {
  		$opctl{$name}[CTL_DEST] = CTL_DEST_ARRAY;
  	    }
  	    elsif ( $rl eq "HASH" ) {
  		$opctl{$name}[CTL_DEST] = CTL_DEST_HASH;
  	    }
  	    elsif ( $rl eq "SCALAR" || $rl eq "REF" ) {
  #		if ( $opctl{$name}[CTL_DEST] == CTL_DEST_ARRAY ) {
  #		    my $t = $linkage{$orig};
  #		    $$t = $linkage{$orig} = [];
  #		}
  #		elsif ( $opctl{$name}[CTL_DEST] == CTL_DEST_HASH ) {
  #		}
  #		else {
  		    # Ok.
  #		}
  	    }
  	    elsif ( $rl eq "CODE" ) {
  		# Ok.
  	    }
  	    else {
  		$error .= "Invalid option linkage for \"$opt\"\n";
  	    }
  	}
  	else {
  	    # Link to global $opt_XXX variable.
  	    # Make sure a valid perl identifier results.
  	    my $ov = $orig;
  	    $ov =~ s/\W/_/g;
  	    if ( $opctl{$name}[CTL_DEST] == CTL_DEST_ARRAY ) {
  		print STDERR ("=> link \"$orig\" to \@$pkg","::opt_$ov\n")
  		    if $debug;
  		eval ("\$linkage{\$orig} = \\\@".$pkg."::opt_$ov;");
  	    }
  	    elsif ( $opctl{$name}[CTL_DEST] == CTL_DEST_HASH ) {
  		print STDERR ("=> link \"$orig\" to \%$pkg","::opt_$ov\n")
  		    if $debug;
  		eval ("\$linkage{\$orig} = \\\%".$pkg."::opt_$ov;");
  	    }
  	    else {
  		print STDERR ("=> link \"$orig\" to \$$pkg","::opt_$ov\n")
  		    if $debug;
  		eval ("\$linkage{\$orig} = \\\$".$pkg."::opt_$ov;");
  	    }
  	}
  
  	if ( $opctl{$name}[CTL_TYPE] eq 'I'
  	     && ( $opctl{$name}[CTL_DEST] == CTL_DEST_ARRAY
  		  || $opctl{$name}[CTL_DEST] == CTL_DEST_HASH )
  	   ) {
  	    $error .= "Invalid option linkage for \"$opt\"\n";
  	}
  
      }
  
      # Bail out if errors found.
      die ($error) if $error;
      $error = 0;
  
      # Supply --version and --help support, if needed and allowed.
      if ( defined($auto_version) ? $auto_version : ($requested_version >= 2.3203) ) {
  	if ( !defined($opctl{version}) ) {
  	    $opctl{version} = ['','version',0,CTL_DEST_CODE,undef];
  	    $linkage{version} = \&VersionMessage;
  	}
  	$auto_version = 1;
      }
      if ( defined($auto_help) ? $auto_help : ($requested_version >= 2.3203) ) {
  	if ( !defined($opctl{help}) && !defined($opctl{'?'}) ) {
  	    $opctl{help} = $opctl{'?'} = ['','help',0,CTL_DEST_CODE,undef];
  	    $linkage{help} = \&HelpMessage;
  	}
  	$auto_help = 1;
      }
  
      # Show the options tables if debugging.
      if ( $debug ) {
  	my ($arrow, $k, $v);
  	$arrow = "=> ";
  	while ( ($k,$v) = each(%opctl) ) {
  	    print STDERR ($arrow, "\$opctl{$k} = $v ", OptCtl($v), "\n");
  	    $arrow = "   ";
  	}
      }
  
      # Process argument list
      my $goon = 1;
      while ( $goon && @$argv > 0 ) {
  
  	# Get next argument.
  	$opt = shift (@$argv);
  	print STDERR ("=> arg \"", $opt, "\"\n") if $debug;
  
  	# Double dash is option list terminator.
  	if ( defined($opt) && $opt eq $argend ) {
  	  push (@ret, $argend) if $passthrough;
  	  last;
  	}
  
  	# Look it up.
  	my $tryopt = $opt;
  	my $found;		# success status
  	my $key;		# key (if hash type)
  	my $arg;		# option argument
  	my $ctl;		# the opctl entry
  
  	($found, $opt, $ctl, $arg, $key) =
  	  FindOption ($argv, $prefix, $argend, $opt, \%opctl);
  
  	if ( $found ) {
  
  	    # FindOption undefines $opt in case of errors.
  	    next unless defined $opt;
  
  	    my $argcnt = 0;
  	    while ( defined $arg ) {
  
  		# Get the canonical name.
  		print STDERR ("=> cname for \"$opt\" is ") if $debug;
  		$opt = $ctl->[CTL_CNAME];
  		print STDERR ("\"$ctl->[CTL_CNAME]\"\n") if $debug;
  
  		if ( defined $linkage{$opt} ) {
  		    print STDERR ("=> ref(\$L{$opt}) -> ",
  				  ref($linkage{$opt}), "\n") if $debug;
  
  		    if ( ref($linkage{$opt}) eq 'SCALAR'
  			 || ref($linkage{$opt}) eq 'REF' ) {
  			if ( $ctl->[CTL_TYPE] eq '+' ) {
  			    print STDERR ("=> \$\$L{$opt} += \"$arg\"\n")
  			      if $debug;
  			    if ( defined ${$linkage{$opt}} ) {
  			        ${$linkage{$opt}} += $arg;
  			    }
  		            else {
  			        ${$linkage{$opt}} = $arg;
  			    }
  			}
  			elsif ( $ctl->[CTL_DEST] == CTL_DEST_ARRAY ) {
  			    print STDERR ("=> ref(\$L{$opt}) auto-vivified",
  					  " to ARRAY\n")
  			      if $debug;
  			    my $t = $linkage{$opt};
  			    $$t = $linkage{$opt} = [];
  			    print STDERR ("=> push(\@{\$L{$opt}, \"$arg\")\n")
  			      if $debug;
  			    push (@{$linkage{$opt}}, $arg);
  			}
  			elsif ( $ctl->[CTL_DEST] == CTL_DEST_HASH ) {
  			    print STDERR ("=> ref(\$L{$opt}) auto-vivified",
  					  " to HASH\n")
  			      if $debug;
  			    my $t = $linkage{$opt};
  			    $$t = $linkage{$opt} = {};
  			    print STDERR ("=> \$\$L{$opt}->{$key} = \"$arg\"\n")
  			      if $debug;
  			    $linkage{$opt}->{$key} = $arg;
  			}
  			else {
  			    print STDERR ("=> \$\$L{$opt} = \"$arg\"\n")
  			      if $debug;
  			    ${$linkage{$opt}} = $arg;
  		        }
  		    }
  		    elsif ( ref($linkage{$opt}) eq 'ARRAY' ) {
  			print STDERR ("=> push(\@{\$L{$opt}, \"$arg\")\n")
  			    if $debug;
  			push (@{$linkage{$opt}}, $arg);
  		    }
  		    elsif ( ref($linkage{$opt}) eq 'HASH' ) {
  			print STDERR ("=> \$\$L{$opt}->{$key} = \"$arg\"\n")
  			    if $debug;
  			$linkage{$opt}->{$key} = $arg;
  		    }
  		    elsif ( ref($linkage{$opt}) eq 'CODE' ) {
  			print STDERR ("=> &L{$opt}(\"$opt\"",
  				      $ctl->[CTL_DEST] == CTL_DEST_HASH ? ", \"$key\"" : "",
  				      ", \"$arg\")\n")
  			    if $debug;
  			my $eval_error = do {
  			    local $@;
  			    local $SIG{__DIE__}  = 'DEFAULT';
  			    eval {
  				&{$linkage{$opt}}
  				  (Getopt::Long::CallBack->new
  				   (name    => $opt,
  				    ctl     => $ctl,
  				    opctl   => \%opctl,
  				    linkage => \%linkage,
  				    prefix  => $prefix,
  				   ),
  				   $ctl->[CTL_DEST] == CTL_DEST_HASH ? ($key) : (),
  				   $arg);
  			    };
  			    $@;
  			};
  			print STDERR ("=> die($eval_error)\n")
  			  if $debug && $eval_error ne '';
  			if ( $eval_error =~ /^!/ ) {
  			    if ( $eval_error =~ /^!FINISH\b/ ) {
  				$goon = 0;
  			    }
  			}
  			elsif ( $eval_error ne '' ) {
  			    warn ($eval_error);
  			    $error++;
  			}
  		    }
  		    else {
  			print STDERR ("Invalid REF type \"", ref($linkage{$opt}),
  				      "\" in linkage\n");
  			die("Getopt::Long -- internal error!\n");
  		    }
  		}
  		# No entry in linkage means entry in userlinkage.
  		elsif ( $ctl->[CTL_DEST] == CTL_DEST_ARRAY ) {
  		    if ( defined $userlinkage->{$opt} ) {
  			print STDERR ("=> push(\@{\$L{$opt}}, \"$arg\")\n")
  			    if $debug;
  			push (@{$userlinkage->{$opt}}, $arg);
  		    }
  		    else {
  			print STDERR ("=>\$L{$opt} = [\"$arg\"]\n")
  			    if $debug;
  			$userlinkage->{$opt} = [$arg];
  		    }
  		}
  		elsif ( $ctl->[CTL_DEST] == CTL_DEST_HASH ) {
  		    if ( defined $userlinkage->{$opt} ) {
  			print STDERR ("=> \$L{$opt}->{$key} = \"$arg\"\n")
  			    if $debug;
  			$userlinkage->{$opt}->{$key} = $arg;
  		    }
  		    else {
  			print STDERR ("=>\$L{$opt} = {$key => \"$arg\"}\n")
  			    if $debug;
  			$userlinkage->{$opt} = {$key => $arg};
  		    }
  		}
  		else {
  		    if ( $ctl->[CTL_TYPE] eq '+' ) {
  			print STDERR ("=> \$L{$opt} += \"$arg\"\n")
  			  if $debug;
  			if ( defined $userlinkage->{$opt} ) {
  			    $userlinkage->{$opt} += $arg;
  			}
  			else {
  			    $userlinkage->{$opt} = $arg;
  			}
  		    }
  		    else {
  			print STDERR ("=>\$L{$opt} = \"$arg\"\n") if $debug;
  			$userlinkage->{$opt} = $arg;
  		    }
  		}
  
  		$argcnt++;
  		last if $argcnt >= $ctl->[CTL_AMAX] && $ctl->[CTL_AMAX] != -1;
  		undef($arg);
  
  		# Need more args?
  		if ( $argcnt < $ctl->[CTL_AMIN] ) {
  		    if ( @$argv ) {
  			if ( ValidValue($ctl, $argv->[0], 1, $argend, $prefix) ) {
  			    $arg = shift(@$argv);
  			    if ( $ctl->[CTL_TYPE] =~ /^[iIo]$/ ) {
  				$arg =~ tr/_//d;
  				$arg = $ctl->[CTL_TYPE] eq 'o' && $arg =~ /^0/
  				  ? oct($arg)
  				  : 0+$arg
  			    }
  			    ($key,$arg) = $arg =~ /^([^=]+)=(.*)/
  			      if $ctl->[CTL_DEST] == CTL_DEST_HASH;
  			    next;
  			}
  			warn("Value \"$$argv[0]\" invalid for option $opt\n");
  			$error++;
  		    }
  		    else {
  			warn("Insufficient arguments for option $opt\n");
  			$error++;
  		    }
  		}
  
  		# Any more args?
  		if ( @$argv && ValidValue($ctl, $argv->[0], 0, $argend, $prefix) ) {
  		    $arg = shift(@$argv);
  		    if ( $ctl->[CTL_TYPE] =~ /^[iIo]$/ ) {
  			$arg =~ tr/_//d;
  			$arg = $ctl->[CTL_TYPE] eq 'o' && $arg =~ /^0/
  			  ? oct($arg)
  			  : 0+$arg
  		    }
  		    ($key,$arg) = $arg =~ /^([^=]+)=(.*)/
  		      if $ctl->[CTL_DEST] == CTL_DEST_HASH;
  		    next;
  		}
  	    }
  	}
  
  	# Not an option. Save it if we $PERMUTE and don't have a <>.
  	elsif ( $order == $PERMUTE ) {
  	    # Try non-options call-back.
  	    my $cb;
  	    if ( (defined ($cb = $linkage{'<>'})) ) {
  		print STDERR ("=> &L{$tryopt}(\"$tryopt\")\n")
  		  if $debug;
  		my $eval_error = do {
  		    local $@;
  		    local $SIG{__DIE__}  = 'DEFAULT';
  		    eval {
  			# The arg to <> cannot be the CallBack object
  			# since it may be passed to other modules that
  			# get confused (e.g., Archive::Tar). Well,
  			# it's not relevant for this callback anyway.
  			&$cb($tryopt);
  		    };
  		    $@;
  		};
  		print STDERR ("=> die($eval_error)\n")
  		  if $debug && $eval_error ne '';
  		if ( $eval_error =~ /^!/ ) {
  		    if ( $eval_error =~ /^!FINISH\b/ ) {
  			$goon = 0;
  		    }
  		}
  		elsif ( $eval_error ne '' ) {
  		    warn ($eval_error);
  		    $error++;
  		}
  	    }
  	    else {
  		print STDERR ("=> saving \"$tryopt\" ",
  			      "(not an option, may permute)\n") if $debug;
  		push (@ret, $tryopt);
  	    }
  	    next;
  	}
  
  	# ...otherwise, terminate.
  	else {
  	    # Push this one back and exit.
  	    unshift (@$argv, $tryopt);
  	    return ($error == 0);
  	}
  
      }
  
      # Finish.
      if ( @ret && $order == $PERMUTE ) {
  	#  Push back accumulated arguments
  	print STDERR ("=> restoring \"", join('" "', @ret), "\"\n")
  	    if $debug;
  	unshift (@$argv, @ret);
      }
  
      return ($error == 0);
  }
  
  # A readable representation of what's in an optbl.
  sub OptCtl ($) {
      my ($v) = @_;
      my @v = map { defined($_) ? ($_) : ("<undef>") } @$v;
      "[".
        join(",",
  	   "\"$v[CTL_TYPE]\"",
  	   "\"$v[CTL_CNAME]\"",
  	   "\"$v[CTL_DEFAULT]\"",
  	   ("\$","\@","\%","\&")[$v[CTL_DEST] || 0],
  	   $v[CTL_AMIN] || '',
  	   $v[CTL_AMAX] || '',
  #	   $v[CTL_RANGE] || '',
  #	   $v[CTL_REPEAT] || '',
  	  ). "]";
  }
  
  # Parse an option specification and fill the tables.
  sub ParseOptionSpec ($$) {
      my ($opt, $opctl) = @_;
  
      # Match option spec.
      if ( $opt !~ m;^
  		   (
  		     # Option name
  		     (?: \w+[-\w]* )
  		     # Alias names, or "?"
  		     (?: \| (?: \? | \w[-\w]* ) )*
  		     # Aliases
  		     (?: \| (?: [^-|!+=:][^|!+=:]* )? )*
  		   )?
  		   (
  		     # Either modifiers ...
  		     [!+]
  		     |
  		     # ... or a value/dest/repeat specification
  		     [=:] [ionfs] [@%]? (?: \{\d*,?\d*\} )?
  		     |
  		     # ... or an optional-with-default spec
  		     : (?: -?\d+ | \+ ) [@%]?
  		   )?
  		   $;x ) {
  	return (undef, "Error in option spec: \"$opt\"\n");
      }
  
      my ($names, $spec) = ($1, $2);
      $spec = '' unless defined $spec;
  
      # $orig keeps track of the primary name the user specified.
      # This name will be used for the internal or external linkage.
      # In other words, if the user specifies "FoO|BaR", it will
      # match any case combinations of 'foo' and 'bar', but if a global
      # variable needs to be set, it will be $opt_FoO in the exact case
      # as specified.
      my $orig;
  
      my @names;
      if ( defined $names ) {
  	@names =  split (/\|/, $names);
  	$orig = $names[0];
      }
      else {
  	@names = ('');
  	$orig = '';
      }
  
      # Construct the opctl entries.
      my $entry;
      if ( $spec eq '' || $spec eq '+' || $spec eq '!' ) {
  	# Fields are hard-wired here.
  	$entry = [$spec,$orig,undef,CTL_DEST_SCALAR,0,0];
      }
      elsif ( $spec =~ /^:(-?\d+|\+)([@%])?$/ ) {
  	my $def = $1;
  	my $dest = $2;
  	my $type = $def eq '+' ? 'I' : 'i';
  	$dest ||= '$';
  	$dest = $dest eq '@' ? CTL_DEST_ARRAY
  	  : $dest eq '%' ? CTL_DEST_HASH : CTL_DEST_SCALAR;
  	# Fields are hard-wired here.
  	$entry = [$type,$orig,$def eq '+' ? undef : $def,
  		  $dest,0,1];
      }
      else {
  	my ($mand, $type, $dest) =
  	  $spec =~ /^([=:])([ionfs])([@%])?(\{(\d+)?(,)?(\d+)?\})?$/;
  	return (undef, "Cannot repeat while bundling: \"$opt\"\n")
  	  if $bundling && defined($4);
  	my ($mi, $cm, $ma) = ($5, $6, $7);
  	return (undef, "{0} is useless in option spec: \"$opt\"\n")
  	  if defined($mi) && !$mi && !defined($ma) && !defined($cm);
  
  	$type = 'i' if $type eq 'n';
  	$dest ||= '$';
  	$dest = $dest eq '@' ? CTL_DEST_ARRAY
  	  : $dest eq '%' ? CTL_DEST_HASH : CTL_DEST_SCALAR;
  	# Default minargs to 1/0 depending on mand status.
  	$mi = $mand eq '=' ? 1 : 0 unless defined $mi;
  	# Adjust mand status according to minargs.
  	$mand = $mi ? '=' : ':';
  	# Adjust maxargs.
  	$ma = $mi ? $mi : 1 unless defined $ma || defined $cm;
  	return (undef, "Max must be greater than zero in option spec: \"$opt\"\n")
  	  if defined($ma) && !$ma;
  	return (undef, "Max less than min in option spec: \"$opt\"\n")
  	  if defined($ma) && $ma < $mi;
  
  	# Fields are hard-wired here.
  	$entry = [$type,$orig,undef,$dest,$mi,$ma||-1];
      }
  
      # Process all names. First is canonical, the rest are aliases.
      my $dups = '';
      foreach ( @names ) {
  
  	$_ = lc ($_)
  	  if $ignorecase > (($bundling && length($_) == 1) ? 1 : 0);
  
  	if ( exists $opctl->{$_} ) {
  	    $dups .= "Duplicate specification \"$opt\" for option \"$_\"\n";
  	}
  
  	if ( $spec eq '!' ) {
  	    $opctl->{"no$_"} = $entry;
  	    $opctl->{"no-$_"} = $entry;
  	    $opctl->{$_} = [@$entry];
  	    $opctl->{$_}->[CTL_TYPE] = '';
  	}
  	else {
  	    $opctl->{$_} = $entry;
  	}
      }
  
      if ( $dups && $^W ) {
  	foreach ( split(/\n+/, $dups) ) {
  	    warn($_."\n");
  	}
      }
      ($names[0], $orig);
  }
  
  # Option lookup.
  sub FindOption ($$$$$) {
  
      # returns (1, $opt, $ctl, $arg, $key) if okay,
      # returns (1, undef) if option in error,
      # returns (0) otherwise.
  
      my ($argv, $prefix, $argend, $opt, $opctl) = @_;
  
      print STDERR ("=> find \"$opt\"\n") if $debug;
  
      return (0) unless defined($opt);
      return (0) unless $opt =~ /^($prefix)(.*)$/s;
      return (0) if $opt eq "-" && !defined $opctl->{''};
  
      $opt = substr( $opt, length($1) ); # retain taintedness
      my $starter = $1;
  
      print STDERR ("=> split \"$starter\"+\"$opt\"\n") if $debug;
  
      my $optarg;			# value supplied with --opt=value
      my $rest;			# remainder from unbundling
  
      # If it is a long option, it may include the value.
      # With getopt_compat, only if not bundling.
      if ( ($starter=~/^$longprefix$/
  	  || ($getopt_compat && ($bundling == 0 || $bundling == 2)))
  	 && (my $oppos = index($opt, '=', 1)) > 0) {
  	my $optorg = $opt;
  	$opt = substr($optorg, 0, $oppos);
  	$optarg = substr($optorg, $oppos + 1); # retain tainedness
  	print STDERR ("=> option \"", $opt,
  		      "\", optarg = \"$optarg\"\n") if $debug;
      }
  
      #### Look it up ###
  
      my $tryopt = $opt;		# option to try
  
      if ( $bundling && $starter eq '-' ) {
  
  	# To try overrides, obey case ignore.
  	$tryopt = $ignorecase ? lc($opt) : $opt;
  
  	# If bundling == 2, long options can override bundles.
  	if ( $bundling == 2 && length($tryopt) > 1
  	     && defined ($opctl->{$tryopt}) ) {
  	    print STDERR ("=> $starter$tryopt overrides unbundling\n")
  	      if $debug;
  	}
  	else {
  	    $tryopt = $opt;
  	    # Unbundle single letter option.
  	    $rest = length ($tryopt) > 0 ? substr ($tryopt, 1) : '';
  	    $tryopt = substr ($tryopt, 0, 1);
  	    $tryopt = lc ($tryopt) if $ignorecase > 1;
  	    print STDERR ("=> $starter$tryopt unbundled from ",
  			  "$starter$tryopt$rest\n") if $debug;
  	    $rest = undef unless $rest ne '';
  	}
      }
  
      # Try auto-abbreviation.
      elsif ( $autoabbrev && $opt ne "" ) {
  	# Sort the possible long option names.
  	my @names = sort(keys (%$opctl));
  	# Downcase if allowed.
  	$opt = lc ($opt) if $ignorecase;
  	$tryopt = $opt;
  	# Turn option name into pattern.
  	my $pat = quotemeta ($opt);
  	# Look up in option names.
  	my @hits = grep (/^$pat/, @names);
  	print STDERR ("=> ", scalar(@hits), " hits (@hits) with \"$pat\" ",
  		      "out of ", scalar(@names), "\n") if $debug;
  
  	# Check for ambiguous results.
  	unless ( (@hits <= 1) || (grep ($_ eq $opt, @hits) == 1) ) {
  	    # See if all matches are for the same option.
  	    my %hit;
  	    foreach ( @hits ) {
  		my $hit = $opctl->{$_}->[CTL_CNAME]
  		  if defined $opctl->{$_}->[CTL_CNAME];
  		$hit = "no" . $hit if $opctl->{$_}->[CTL_TYPE] eq '!';
  		$hit{$hit} = 1;
  	    }
  	    # Remove auto-supplied options (version, help).
  	    if ( keys(%hit) == 2 ) {
  		if ( $auto_version && exists($hit{version}) ) {
  		    delete $hit{version};
  		}
  		elsif ( $auto_help && exists($hit{help}) ) {
  		    delete $hit{help};
  		}
  	    }
  	    # Now see if it really is ambiguous.
  	    unless ( keys(%hit) == 1 ) {
  		return (0) if $passthrough;
  		warn ("Option ", $opt, " is ambiguous (",
  		      join(", ", @hits), ")\n");
  		$error++;
  		return (1, undef);
  	    }
  	    @hits = keys(%hit);
  	}
  
  	# Complete the option name, if appropriate.
  	if ( @hits == 1 && $hits[0] ne $opt ) {
  	    $tryopt = $hits[0];
  	    $tryopt = lc ($tryopt) if $ignorecase;
  	    print STDERR ("=> option \"$opt\" -> \"$tryopt\"\n")
  		if $debug;
  	}
      }
  
      # Map to all lowercase if ignoring case.
      elsif ( $ignorecase ) {
  	$tryopt = lc ($opt);
      }
  
      # Check validity by fetching the info.
      my $ctl = $opctl->{$tryopt};
      unless  ( defined $ctl ) {
  	return (0) if $passthrough;
  	# Pretend one char when bundling.
  	if ( $bundling == 1 && length($starter) == 1 ) {
  	    $opt = substr($opt,0,1);
              unshift (@$argv, $starter.$rest) if defined $rest;
  	}
  	if ( $opt eq "" ) {
  	    warn ("Missing option after ", $starter, "\n");
  	}
  	else {
  	    warn ("Unknown option: ", $opt, "\n");
  	}
  	$error++;
  	return (1, undef);
      }
      # Apparently valid.
      $opt = $tryopt;
      print STDERR ("=> found ", OptCtl($ctl),
  		  " for \"", $opt, "\"\n") if $debug;
  
      #### Determine argument status ####
  
      # If it is an option w/o argument, we're almost finished with it.
      my $type = $ctl->[CTL_TYPE];
      my $arg;
  
      if ( $type eq '' || $type eq '!' || $type eq '+' ) {
  	if ( defined $optarg ) {
  	    return (0) if $passthrough;
  	    warn ("Option ", $opt, " does not take an argument\n");
  	    $error++;
  	    undef $opt;
  	}
  	elsif ( $type eq '' || $type eq '+' ) {
  	    # Supply explicit value.
  	    $arg = 1;
  	}
  	else {
  	    $opt =~ s/^no-?//i;	# strip NO prefix
  	    $arg = 0;		# supply explicit value
  	}
  	unshift (@$argv, $starter.$rest) if defined $rest;
  	return (1, $opt, $ctl, $arg);
      }
  
      # Get mandatory status and type info.
      my $mand = $ctl->[CTL_AMIN];
  
      # Check if there is an option argument available.
      if ( $gnu_compat && defined $optarg && $optarg eq '' ) {
  	return (1, $opt, $ctl, $type eq 's' ? '' : 0) ;#unless $mand;
  	$optarg = 0 unless $type eq 's';
      }
  
      # Check if there is an option argument available.
      if ( defined $optarg
  	 ? ($optarg eq '')
  	 : !(defined $rest || @$argv > 0) ) {
  	# Complain if this option needs an argument.
  #	if ( $mand && !($type eq 's' ? defined($optarg) : 0) ) {
  	if ( $mand ) {
  	    return (0) if $passthrough;
  	    warn ("Option ", $opt, " requires an argument\n");
  	    $error++;
  	    return (1, undef);
  	}
  	if ( $type eq 'I' ) {
  	    # Fake incremental type.
  	    my @c = @$ctl;
  	    $c[CTL_TYPE] = '+';
  	    return (1, $opt, \@c, 1);
  	}
  	return (1, $opt, $ctl,
  		defined($ctl->[CTL_DEFAULT]) ? $ctl->[CTL_DEFAULT] :
  		$type eq 's' ? '' : 0);
      }
  
      # Get (possibly optional) argument.
      $arg = (defined $rest ? $rest
  	    : (defined $optarg ? $optarg : shift (@$argv)));
  
      # Get key if this is a "name=value" pair for a hash option.
      my $key;
      if ($ctl->[CTL_DEST] == CTL_DEST_HASH && defined $arg) {
  	($key, $arg) = ($arg =~ /^([^=]*)=(.*)$/s) ? ($1, $2)
  	  : ($arg, defined($ctl->[CTL_DEFAULT]) ? $ctl->[CTL_DEFAULT] :
  	     ($mand ? undef : ($type eq 's' ? "" : 1)));
  	if (! defined $arg) {
  	    warn ("Option $opt, key \"$key\", requires a value\n");
  	    $error++;
  	    # Push back.
  	    unshift (@$argv, $starter.$rest) if defined $rest;
  	    return (1, undef);
  	}
      }
  
      #### Check if the argument is valid for this option ####
  
      my $key_valid = $ctl->[CTL_DEST] == CTL_DEST_HASH ? "[^=]+=" : "";
  
      if ( $type eq 's' ) {	# string
  	# A mandatory string takes anything.
  	return (1, $opt, $ctl, $arg, $key) if $mand;
  
  	# Same for optional string as a hash value
  	return (1, $opt, $ctl, $arg, $key)
  	  if $ctl->[CTL_DEST] == CTL_DEST_HASH;
  
  	# An optional string takes almost anything.
  	return (1, $opt, $ctl, $arg, $key)
  	  if defined $optarg || defined $rest;
  	return (1, $opt, $ctl, $arg, $key) if $arg eq "-"; # ??
  
  	# Check for option or option list terminator.
  	if ($arg eq $argend ||
  	    $arg =~ /^$prefix.+/) {
  	    # Push back.
  	    unshift (@$argv, $arg);
  	    # Supply empty value.
  	    $arg = '';
  	}
      }
  
      elsif ( $type eq 'i'	# numeric/integer
              || $type eq 'I'	# numeric/integer w/ incr default
  	    || $type eq 'o' ) { # dec/oct/hex/bin value
  
  	my $o_valid = $type eq 'o' ? PAT_XINT : PAT_INT;
  
  	if ( $bundling && defined $rest
  	     && $rest =~ /^($key_valid)($o_valid)(.*)$/si ) {
  	    ($key, $arg, $rest) = ($1, $2, $+);
  	    chop($key) if $key;
  	    $arg = ($type eq 'o' && $arg =~ /^0/) ? oct($arg) : 0+$arg;
  	    unshift (@$argv, $starter.$rest) if defined $rest && $rest ne '';
  	}
  	elsif ( $arg =~ /^$o_valid$/si ) {
  	    $arg =~ tr/_//d;
  	    $arg = ($type eq 'o' && $arg =~ /^0/) ? oct($arg) : 0+$arg;
  	}
  	else {
  	    if ( defined $optarg || $mand ) {
  		if ( $passthrough ) {
  		    unshift (@$argv, defined $rest ? $starter.$rest : $arg)
  		      unless defined $optarg;
  		    return (0);
  		}
  		warn ("Value \"", $arg, "\" invalid for option ",
  		      $opt, " (",
  		      $type eq 'o' ? "extended " : '',
  		      "number expected)\n");
  		$error++;
  		# Push back.
  		unshift (@$argv, $starter.$rest) if defined $rest;
  		return (1, undef);
  	    }
  	    else {
  		# Push back.
  		unshift (@$argv, defined $rest ? $starter.$rest : $arg);
  		if ( $type eq 'I' ) {
  		    # Fake incremental type.
  		    my @c = @$ctl;
  		    $c[CTL_TYPE] = '+';
  		    return (1, $opt, \@c, 1);
  		}
  		# Supply default value.
  		$arg = defined($ctl->[CTL_DEFAULT]) ? $ctl->[CTL_DEFAULT] : 0;
  	    }
  	}
      }
  
      elsif ( $type eq 'f' ) { # real number, int is also ok
  	# We require at least one digit before a point or 'e',
  	# and at least one digit following the point and 'e'.
  	my $o_valid = PAT_FLOAT;
  	if ( $bundling && defined $rest &&
  	     $rest =~ /^($key_valid)($o_valid)(.*)$/s ) {
  	    $arg =~ tr/_//d;
  	    ($key, $arg, $rest) = ($1, $2, $+);
  	    chop($key) if $key;
  	    unshift (@$argv, $starter.$rest) if defined $rest && $rest ne '';
  	}
  	elsif ( $arg =~ /^$o_valid$/ ) {
  	    $arg =~ tr/_//d;
  	}
  	else {
  	    if ( defined $optarg || $mand ) {
  		if ( $passthrough ) {
  		    unshift (@$argv, defined $rest ? $starter.$rest : $arg)
  		      unless defined $optarg;
  		    return (0);
  		}
  		warn ("Value \"", $arg, "\" invalid for option ",
  		      $opt, " (real number expected)\n");
  		$error++;
  		# Push back.
  		unshift (@$argv, $starter.$rest) if defined $rest;
  		return (1, undef);
  	    }
  	    else {
  		# Push back.
  		unshift (@$argv, defined $rest ? $starter.$rest : $arg);
  		# Supply default value.
  		$arg = 0.0;
  	    }
  	}
      }
      else {
  	die("Getopt::Long internal error (Can't happen)\n");
      }
      return (1, $opt, $ctl, $arg, $key);
  }
  
  sub ValidValue ($$$$$) {
      my ($ctl, $arg, $mand, $argend, $prefix) = @_;
  
      if ( $ctl->[CTL_DEST] == CTL_DEST_HASH ) {
  	return 0 unless $arg =~ /[^=]+=(.*)/;
  	$arg = $1;
      }
  
      my $type = $ctl->[CTL_TYPE];
  
      if ( $type eq 's' ) {	# string
  	# A mandatory string takes anything.
  	return (1) if $mand;
  
  	return (1) if $arg eq "-";
  
  	# Check for option or option list terminator.
  	return 0 if $arg eq $argend || $arg =~ /^$prefix.+/;
  	return 1;
      }
  
      elsif ( $type eq 'i'	# numeric/integer
              || $type eq 'I'	# numeric/integer w/ incr default
  	    || $type eq 'o' ) { # dec/oct/hex/bin value
  
  	my $o_valid = $type eq 'o' ? PAT_XINT : PAT_INT;
  	return $arg =~ /^$o_valid$/si;
      }
  
      elsif ( $type eq 'f' ) { # real number, int is also ok
  	# We require at least one digit before a point or 'e',
  	# and at least one digit following the point and 'e'.
  	# [-]NN[.NN][eNN]
  	my $o_valid = PAT_FLOAT;
  	return $arg =~ /^$o_valid$/;
      }
      die("ValidValue: Cannot happen\n");
  }
  
  # Getopt::Long Configuration.
  sub Configure (@) {
      my (@options) = @_;
  
      my $prevconfig =
        [ $error, $debug, $major_version, $minor_version,
  	$autoabbrev, $getopt_compat, $ignorecase, $bundling, $order,
  	$gnu_compat, $passthrough, $genprefix, $auto_version, $auto_help,
  	$longprefix ];
  
      if ( ref($options[0]) eq 'ARRAY' ) {
  	( $error, $debug, $major_version, $minor_version,
  	  $autoabbrev, $getopt_compat, $ignorecase, $bundling, $order,
  	  $gnu_compat, $passthrough, $genprefix, $auto_version, $auto_help,
  	  $longprefix ) = @{shift(@options)};
      }
  
      my $opt;
      foreach $opt ( @options ) {
  	my $try = lc ($opt);
  	my $action = 1;
  	if ( $try =~ /^no_?(.*)$/s ) {
  	    $action = 0;
  	    $try = $+;
  	}
  	if ( ($try eq 'default' or $try eq 'defaults') && $action ) {
  	    ConfigDefaults ();
  	}
  	elsif ( ($try eq 'posix_default' or $try eq 'posix_defaults') ) {
  	    local $ENV{POSIXLY_CORRECT};
  	    $ENV{POSIXLY_CORRECT} = 1 if $action;
  	    ConfigDefaults ();
  	}
  	elsif ( $try eq 'auto_abbrev' or $try eq 'autoabbrev' ) {
  	    $autoabbrev = $action;
  	}
  	elsif ( $try eq 'getopt_compat' ) {
  	    $getopt_compat = $action;
              $genprefix = $action ? "(--|-|\\+)" : "(--|-)";
  	}
  	elsif ( $try eq 'gnu_getopt' ) {
  	    if ( $action ) {
  		$gnu_compat = 1;
  		$bundling = 1;
  		$getopt_compat = 0;
                  $genprefix = "(--|-)";
  		$order = $PERMUTE;
  	    }
  	}
  	elsif ( $try eq 'gnu_compat' ) {
  	    $gnu_compat = $action;
  	}
  	elsif ( $try =~ /^(auto_?)?version$/ ) {
  	    $auto_version = $action;
  	}
  	elsif ( $try =~ /^(auto_?)?help$/ ) {
  	    $auto_help = $action;
  	}
  	elsif ( $try eq 'ignorecase' or $try eq 'ignore_case' ) {
  	    $ignorecase = $action;
  	}
  	elsif ( $try eq 'ignorecase_always' or $try eq 'ignore_case_always' ) {
  	    $ignorecase = $action ? 2 : 0;
  	}
  	elsif ( $try eq 'bundling' ) {
  	    $bundling = $action;
  	}
  	elsif ( $try eq 'bundling_override' ) {
  	    $bundling = $action ? 2 : 0;
  	}
  	elsif ( $try eq 'require_order' ) {
  	    $order = $action ? $REQUIRE_ORDER : $PERMUTE;
  	}
  	elsif ( $try eq 'permute' ) {
  	    $order = $action ? $PERMUTE : $REQUIRE_ORDER;
  	}
  	elsif ( $try eq 'pass_through' or $try eq 'passthrough' ) {
  	    $passthrough = $action;
  	}
  	elsif ( $try =~ /^prefix=(.+)$/ && $action ) {
  	    $genprefix = $1;
  	    # Turn into regexp. Needs to be parenthesized!
  	    $genprefix = "(" . quotemeta($genprefix) . ")";
  	    eval { '' =~ /$genprefix/; };
  	    die("Getopt::Long: invalid pattern \"$genprefix\"\n") if $@;
  	}
  	elsif ( $try =~ /^prefix_pattern=(.+)$/ && $action ) {
  	    $genprefix = $1;
  	    # Parenthesize if needed.
  	    $genprefix = "(" . $genprefix . ")"
  	      unless $genprefix =~ /^\(.*\)$/;
  	    eval { '' =~ m"$genprefix"; };
  	    die("Getopt::Long: invalid pattern \"$genprefix\"\n") if $@;
  	}
  	elsif ( $try =~ /^long_prefix_pattern=(.+)$/ && $action ) {
  	    $longprefix = $1;
  	    # Parenthesize if needed.
  	    $longprefix = "(" . $longprefix . ")"
  	      unless $longprefix =~ /^\(.*\)$/;
  	    eval { '' =~ m"$longprefix"; };
  	    die("Getopt::Long: invalid long prefix pattern \"$longprefix\"\n") if $@;
  	}
  	elsif ( $try eq 'debug' ) {
  	    $debug = $action;
  	}
  	else {
  	    die("Getopt::Long: unknown or erroneous config parameter \"$opt\"\n")
  	}
      }
      $prevconfig;
  }
  
  # Deprecated name.
  sub config (@) {
      Configure (@_);
  }
  
  # Issue a standard message for --version.
  #
  # The arguments are mostly the same as for Pod::Usage::pod2usage:
  #
  #  - a number (exit value)
  #  - a string (lead in message)
  #  - a hash with options. See Pod::Usage for details.
  #
  sub VersionMessage(@) {
      # Massage args.
      my $pa = setup_pa_args("version", @_);
  
      my $v = $main::VERSION;
      my $fh = $pa->{-output} ||
        ($pa->{-exitval} eq "NOEXIT" || $pa->{-exitval} < 2) ? \*STDOUT : \*STDERR;
  
      print $fh (defined($pa->{-message}) ? $pa->{-message} : (),
  	       $0, defined $v ? " version $v" : (),
  	       "\n",
  	       "(", __PACKAGE__, "::", "GetOptions",
  	       " version ",
  	       defined($Getopt::Long::VERSION_STRING)
  	         ? $Getopt::Long::VERSION_STRING : $VERSION, ";",
  	       " Perl version ",
  	       $] >= 5.006 ? sprintf("%vd", $^V) : $],
  	       ")\n");
      exit($pa->{-exitval}) unless $pa->{-exitval} eq "NOEXIT";
  }
  
  # Issue a standard message for --help.
  #
  # The arguments are the same as for Pod::Usage::pod2usage:
  #
  #  - a number (exit value)
  #  - a string (lead in message)
  #  - a hash with options. See Pod::Usage for details.
  #
  sub HelpMessage(@) {
      eval {
  	require Pod::Usage;
  	import Pod::Usage;
  	1;
      } || die("Cannot provide help: cannot load Pod::Usage\n");
  
      # Note that pod2usage will issue a warning if -exitval => NOEXIT.
      pod2usage(setup_pa_args("help", @_));
  
  }
  
  # Helper routine to set up a normalized hash ref to be used as
  # argument to pod2usage.
  sub setup_pa_args($@) {
      my $tag = shift;		# who's calling
  
      # If called by direct binding to an option, it will get the option
      # name and value as arguments. Remove these, if so.
      @_ = () if @_ == 2 && $_[0] eq $tag;
  
      my $pa;
      if ( @_ > 1 ) {
  	$pa = { @_ };
      }
      else {
  	$pa = shift || {};
      }
  
      # At this point, $pa can be a number (exit value), string
      # (message) or hash with options.
  
      if ( UNIVERSAL::isa($pa, 'HASH') ) {
  	# Get rid of -msg vs. -message ambiguity.
  	$pa->{-message} = $pa->{-msg};
  	delete($pa->{-msg});
      }
      elsif ( $pa =~ /^-?\d+$/ ) {
  	$pa = { -exitval => $pa };
      }
      else {
  	$pa = { -message => $pa };
      }
  
      # These are _our_ defaults.
      $pa->{-verbose} = 0 unless exists($pa->{-verbose});
      $pa->{-exitval} = 0 unless exists($pa->{-exitval});
      $pa;
  }
  
  # Sneak way to know what version the user requested.
  sub VERSION {
      $requested_version = $_[1];
      shift->SUPER::VERSION(@_);
  }
  
  package Getopt::Long::CallBack;
  
  sub new {
      my ($pkg, %atts) = @_;
      bless { %atts }, $pkg;
  }
  
  sub name {
      my $self = shift;
      ''.$self->{name};
  }
  
  use overload
    # Treat this object as an ordinary string for legacy API.
    '""'	   => \&name,
    fallback => 1;
  
  1;
  
  ################ Documentation ################
  
  =head1 NAME
  
  Getopt::Long - Extended processing of command line options
  
  =head1 SYNOPSIS
  
    use Getopt::Long;
    my $data   = "file.dat";
    my $length = 24;
    my $verbose;
    GetOptions ("length=i" => \$length,    # numeric
                "file=s"   => \$data,      # string
                "verbose"  => \$verbose)   # flag
    or die("Error in command line arguments\n");
  
  =head1 DESCRIPTION
  
  The Getopt::Long module implements an extended getopt function called
  GetOptions(). It parses the command line from C<@ARGV>, recognizing
  and removing specified options and their possible values.
  
  This function adheres to the POSIX syntax for command
  line options, with GNU extensions. In general, this means that options
  have long names instead of single letters, and are introduced with a
  double dash "--". Support for bundling of command line options, as was
  the case with the more traditional single-letter approach, is provided
  but not enabled by default.
  
  =head1 Command Line Options, an Introduction
  
  Command line operated programs traditionally take their arguments from
  the command line, for example filenames or other information that the
  program needs to know. Besides arguments, these programs often take
  command line I<options> as well. Options are not necessary for the
  program to work, hence the name 'option', but are used to modify its
  default behaviour. For example, a program could do its job quietly,
  but with a suitable option it could provide verbose information about
  what it did.
  
  Command line options come in several flavours. Historically, they are
  preceded by a single dash C<->, and consist of a single letter.
  
      -l -a -c
  
  Usually, these single-character options can be bundled:
  
      -lac
  
  Options can have values, the value is placed after the option
  character. Sometimes with whitespace in between, sometimes not:
  
      -s 24 -s24
  
  Due to the very cryptic nature of these options, another style was
  developed that used long names. So instead of a cryptic C<-l> one
  could use the more descriptive C<--long>. To distinguish between a
  bundle of single-character options and a long one, two dashes are used
  to precede the option name. Early implementations of long options used
  a plus C<+> instead. Also, option values could be specified either
  like
  
      --size=24
  
  or
  
      --size 24
  
  The C<+> form is now obsolete and strongly deprecated.
  
  =head1 Getting Started with Getopt::Long
  
  Getopt::Long is the Perl5 successor of C<newgetopt.pl>. This was the
  first Perl module that provided support for handling the new style of
  command line options, in particular long option names, hence the Perl5
  name Getopt::Long. This module also supports single-character options
  and bundling.
  
  To use Getopt::Long from a Perl program, you must include the
  following line in your Perl program:
  
      use Getopt::Long;
  
  This will load the core of the Getopt::Long module and prepare your
  program for using it. Most of the actual Getopt::Long code is not
  loaded until you really call one of its functions.
  
  In the default configuration, options names may be abbreviated to
  uniqueness, case does not matter, and a single dash is sufficient,
  even for long option names. Also, options may be placed between
  non-option arguments. See L<Configuring Getopt::Long> for more
  details on how to configure Getopt::Long.
  
  =head2 Simple options
  
  The most simple options are the ones that take no values. Their mere
  presence on the command line enables the option. Popular examples are:
  
      --all --verbose --quiet --debug
  
  Handling simple options is straightforward:
  
      my $verbose = '';	# option variable with default value (false)
      my $all = '';	# option variable with default value (false)
      GetOptions ('verbose' => \$verbose, 'all' => \$all);
  
  The call to GetOptions() parses the command line arguments that are
  present in C<@ARGV> and sets the option variable to the value C<1> if
  the option did occur on the command line. Otherwise, the option
  variable is not touched. Setting the option value to true is often
  called I<enabling> the option.
  
  The option name as specified to the GetOptions() function is called
  the option I<specification>. Later we'll see that this specification
  can contain more than just the option name. The reference to the
  variable is called the option I<destination>.
  
  GetOptions() will return a true value if the command line could be
  processed successfully. Otherwise, it will write error messages using
  die() and warn(), and return a false result.
  
  =head2 A little bit less simple options
  
  Getopt::Long supports two useful variants of simple options:
  I<negatable> options and I<incremental> options.
  
  A negatable option is specified with an exclamation mark C<!> after the
  option name:
  
      my $verbose = '';	# option variable with default value (false)
      GetOptions ('verbose!' => \$verbose);
  
  Now, using C<--verbose> on the command line will enable C<$verbose>,
  as expected. But it is also allowed to use C<--noverbose>, which will
  disable C<$verbose> by setting its value to C<0>. Using a suitable
  default value, the program can find out whether C<$verbose> is false
  by default, or disabled by using C<--noverbose>.
  
  An incremental option is specified with a plus C<+> after the
  option name:
  
      my $verbose = '';	# option variable with default value (false)
      GetOptions ('verbose+' => \$verbose);
  
  Using C<--verbose> on the command line will increment the value of
  C<$verbose>. This way the program can keep track of how many times the
  option occurred on the command line. For example, each occurrence of
  C<--verbose> could increase the verbosity level of the program.
  
  =head2 Mixing command line option with other arguments
  
  Usually programs take command line options as well as other arguments,
  for example, file names. It is good practice to always specify the
  options first, and the other arguments last. Getopt::Long will,
  however, allow the options and arguments to be mixed and 'filter out'
  all the options before passing the rest of the arguments to the
  program. To stop Getopt::Long from processing further arguments,
  insert a double dash C<--> on the command line:
  
      --size 24 -- --all
  
  In this example, C<--all> will I<not> be treated as an option, but
  passed to the program unharmed, in C<@ARGV>.
  
  =head2 Options with values
  
  For options that take values it must be specified whether the option
  value is required or not, and what kind of value the option expects.
  
  Three kinds of values are supported: integer numbers, floating point
  numbers, and strings.
  
  If the option value is required, Getopt::Long will take the
  command line argument that follows the option and assign this to the
  option variable. If, however, the option value is specified as
  optional, this will only be done if that value does not look like a
  valid command line option itself.
  
      my $tag = '';	# option variable with default value
      GetOptions ('tag=s' => \$tag);
  
  In the option specification, the option name is followed by an equals
  sign C<=> and the letter C<s>. The equals sign indicates that this
  option requires a value. The letter C<s> indicates that this value is
  an arbitrary string. Other possible value types are C<i> for integer
  values, and C<f> for floating point values. Using a colon C<:> instead
  of the equals sign indicates that the option value is optional. In
  this case, if no suitable value is supplied, string valued options get
  an empty string C<''> assigned, while numeric options are set to C<0>.
  
  =head2 Options with multiple values
  
  Options sometimes take several values. For example, a program could
  use multiple directories to search for library files:
  
      --library lib/stdlib --library lib/extlib
  
  To accomplish this behaviour, simply specify an array reference as the
  destination for the option:
  
      GetOptions ("library=s" => \@libfiles);
  
  Alternatively, you can specify that the option can have multiple
  values by adding a "@", and pass a scalar reference as the
  destination:
  
      GetOptions ("library=s@" => \$libfiles);
  
  Used with the example above, C<@libfiles> (or C<@$libfiles>) would
  contain two strings upon completion: C<"lib/stdlib"> and
  C<"lib/extlib">, in that order. It is also possible to specify that
  only integer or floating point numbers are acceptable values.
  
  Often it is useful to allow comma-separated lists of values as well as
  multiple occurrences of the options. This is easy using Perl's split()
  and join() operators:
  
      GetOptions ("library=s" => \@libfiles);
      @libfiles = split(/,/,join(',',@libfiles));
  
  Of course, it is important to choose the right separator string for
  each purpose.
  
  Warning: What follows is an experimental feature.
  
  Options can take multiple values at once, for example
  
      --coordinates 52.2 16.4 --rgbcolor 255 255 149
  
  This can be accomplished by adding a repeat specifier to the option
  specification. Repeat specifiers are very similar to the C<{...}>
  repeat specifiers that can be used with regular expression patterns.
  For example, the above command line would be handled as follows:
  
      GetOptions('coordinates=f{2}' => \@coor, 'rgbcolor=i{3}' => \@color);
  
  The destination for the option must be an array or array reference.
  
  It is also possible to specify the minimal and maximal number of
  arguments an option takes. C<foo=s{2,4}> indicates an option that
  takes at least two and at most 4 arguments. C<foo=s{1,}> indicates one
  or more values; C<foo:s{,}> indicates zero or more option values.
  
  =head2 Options with hash values
  
  If the option destination is a reference to a hash, the option will
  take, as value, strings of the form I<key>C<=>I<value>. The value will
  be stored with the specified key in the hash.
  
      GetOptions ("define=s" => \%defines);
  
  Alternatively you can use:
  
      GetOptions ("define=s%" => \$defines);
  
  When used with command line options:
  
      --define os=linux --define vendor=redhat
  
  the hash C<%defines> (or C<%$defines>) will contain two keys, C<"os">
  with value C<"linux"> and C<"vendor"> with value C<"redhat">. It is
  also possible to specify that only integer or floating point numbers
  are acceptable values. The keys are always taken to be strings.
  
  =head2 User-defined subroutines to handle options
  
  Ultimate control over what should be done when (actually: each time)
  an option is encountered on the command line can be achieved by
  designating a reference to a subroutine (or an anonymous subroutine)
  as the option destination. When GetOptions() encounters the option, it
  will call the subroutine with two or three arguments. The first
  argument is the name of the option. (Actually, it is an object that
  stringifies to the name of the option.) For a scalar or array destination,
  the second argument is the value to be stored. For a hash destination,
  the second argument is the key to the hash, and the third argument
  the value to be stored. It is up to the subroutine to store the value,
  or do whatever it thinks is appropriate.
  
  A trivial application of this mechanism is to implement options that
  are related to each other. For example:
  
      my $verbose = '';	# option variable with default value (false)
      GetOptions ('verbose' => \$verbose,
  	        'quiet'   => sub { $verbose = 0 });
  
  Here C<--verbose> and C<--quiet> control the same variable
  C<$verbose>, but with opposite values.
  
  If the subroutine needs to signal an error, it should call die() with
  the desired error message as its argument. GetOptions() will catch the
  die(), issue the error message, and record that an error result must
  be returned upon completion.
  
  If the text of the error message starts with an exclamation mark C<!>
  it is interpreted specially by GetOptions(). There is currently one
  special command implemented: C<die("!FINISH")> will cause GetOptions()
  to stop processing options, as if it encountered a double dash C<-->.
  
  In version 2.37 the first argument to the callback function was
  changed from string to object. This was done to make room for
  extensions and more detailed control. The object stringifies to the
  option name so this change should not introduce compatibility
  problems.
  
  Here is an example of how to access the option name and value from within
  a subroutine:
  
      GetOptions ('opt=i' => \&handler);
      sub handler {
          my ($opt_name, $opt_value) = @_;
          print("Option name is $opt_name and value is $opt_value\n");
      }
  
  =head2 Options with multiple names
  
  Often it is user friendly to supply alternate mnemonic names for
  options. For example C<--height> could be an alternate name for
  C<--length>. Alternate names can be included in the option
  specification, separated by vertical bar C<|> characters. To implement
  the above example:
  
      GetOptions ('length|height=f' => \$length);
  
  The first name is called the I<primary> name, the other names are
  called I<aliases>. When using a hash to store options, the key will
  always be the primary name.
  
  Multiple alternate names are possible.
  
  =head2 Case and abbreviations
  
  Without additional configuration, GetOptions() will ignore the case of
  option names, and allow the options to be abbreviated to uniqueness.
  
      GetOptions ('length|height=f' => \$length, "head" => \$head);
  
  This call will allow C<--l> and C<--L> for the length option, but
  requires a least C<--hea> and C<--hei> for the head and height options.
  
  =head2 Summary of Option Specifications
  
  Each option specifier consists of two parts: the name specification
  and the argument specification.
  
  The name specification contains the name of the option, optionally
  followed by a list of alternative names separated by vertical bar
  characters.
  
      length	      option name is "length"
      length|size|l     name is "length", aliases are "size" and "l"
  
  The argument specification is optional. If omitted, the option is
  considered boolean, a value of 1 will be assigned when the option is
  used on the command line.
  
  The argument specification can be
  
  =over 4
  
  =item !
  
  The option does not take an argument and may be negated by prefixing
  it with "no" or "no-". E.g. C<"foo!"> will allow C<--foo> (a value of
  1 will be assigned) as well as C<--nofoo> and C<--no-foo> (a value of
  0 will be assigned). If the option has aliases, this applies to the
  aliases as well.
  
  Using negation on a single letter option when bundling is in effect is
  pointless and will result in a warning.
  
  =item +
  
  The option does not take an argument and will be incremented by 1
  every time it appears on the command line. E.g. C<"more+">, when used
  with C<--more --more --more>, will increment the value three times,
  resulting in a value of 3 (provided it was 0 or undefined at first).
  
  The C<+> specifier is ignored if the option destination is not a scalar.
  
  =item = I<type> [ I<desttype> ] [ I<repeat> ]
  
  The option requires an argument of the given type. Supported types
  are:
  
  =over 4
  
  =item s
  
  String. An arbitrary sequence of characters. It is valid for the
  argument to start with C<-> or C<-->.
  
  =item i
  
  Integer. An optional leading plus or minus sign, followed by a
  sequence of digits.
  
  =item o
  
  Extended integer, Perl style. This can be either an optional leading
  plus or minus sign, followed by a sequence of digits, or an octal
  string (a zero, optionally followed by '0', '1', .. '7'), or a
  hexadecimal string (C<0x> followed by '0' .. '9', 'a' .. 'f', case
  insensitive), or a binary string (C<0b> followed by a series of '0'
  and '1').
  
  =item f
  
  Real number. For example C<3.14>, C<-6.23E24> and so on.
  
  =back
  
  The I<desttype> can be C<@> or C<%> to specify that the option is
  list or a hash valued. This is only needed when the destination for
  the option value is not otherwise specified. It should be omitted when
  not needed.
  
  The I<repeat> specifies the number of values this option takes per
  occurrence on the command line. It has the format C<{> [ I<min> ] [ C<,> [ I<max> ] ] C<}>.
  
  I<min> denotes the minimal number of arguments. It defaults to 1 for
  options with C<=> and to 0 for options with C<:>, see below. Note that
  I<min> overrules the C<=> / C<:> semantics.
  
  I<max> denotes the maximum number of arguments. It must be at least
  I<min>. If I<max> is omitted, I<but the comma is not>, there is no
  upper bound to the number of argument values taken.
  
  =item : I<type> [ I<desttype> ]
  
  Like C<=>, but designates the argument as optional.
  If omitted, an empty string will be assigned to string values options,
  and the value zero to numeric options.
  
  Note that if a string argument starts with C<-> or C<-->, it will be
  considered an option on itself.
  
  =item : I<number> [ I<desttype> ]
  
  Like C<:i>, but if the value is omitted, the I<number> will be assigned.
  
  =item : + [ I<desttype> ]
  
  Like C<:i>, but if the value is omitted, the current value for the
  option will be incremented.
  
  =back
  
  =head1 Advanced Possibilities
  
  =head2 Object oriented interface
  
  Getopt::Long can be used in an object oriented way as well:
  
      use Getopt::Long;
      $p = Getopt::Long::Parser->new;
      $p->configure(...configuration options...);
      if ($p->getoptions(...options descriptions...)) ...
      if ($p->getoptionsfromarray( \@array, ...options descriptions...)) ...
  
  Configuration options can be passed to the constructor:
  
      $p = new Getopt::Long::Parser
               config => [...configuration options...];
  
  =head2 Thread Safety
  
  Getopt::Long is thread safe when using ithreads as of Perl 5.8.  It is
  I<not> thread safe when using the older (experimental and now
  obsolete) threads implementation that was added to Perl 5.005.
  
  =head2 Documentation and help texts
  
  Getopt::Long encourages the use of Pod::Usage to produce help
  messages. For example:
  
      use Getopt::Long;
      use Pod::Usage;
  
      my $man = 0;
      my $help = 0;
  
      GetOptions('help|?' => \$help, man => \$man) or pod2usage(2);
      pod2usage(1) if $help;
      pod2usage(-exitval => 0, -verbose => 2) if $man;
  
      __END__
  
      =head1 NAME
  
      sample - Using Getopt::Long and Pod::Usage
  
      =head1 SYNOPSIS
  
      sample [options] [file ...]
  
       Options:
         -help            brief help message
         -man             full documentation
  
      =head1 OPTIONS
  
      =over 8
  
      =item B<-help>
  
      Print a brief help message and exits.
  
      =item B<-man>
  
      Prints the manual page and exits.
  
      =back
  
      =head1 DESCRIPTION
  
      B<This program> will read the given input file(s) and do something
      useful with the contents thereof.
  
      =cut
  
  See L<Pod::Usage> for details.
  
  =head2 Parsing options from an arbitrary array
  
  By default, GetOptions parses the options that are present in the
  global array C<@ARGV>. A special entry C<GetOptionsFromArray> can be
  used to parse options from an arbitrary array.
  
      use Getopt::Long qw(GetOptionsFromArray);
      $ret = GetOptionsFromArray(\@myopts, ...);
  
  When used like this, options and their possible values are removed
  from C<@myopts>, the global C<@ARGV> is not touched at all.
  
  The following two calls behave identically:
  
      $ret = GetOptions( ... );
      $ret = GetOptionsFromArray(\@ARGV, ... );
  
  This also means that a first argument hash reference now becomes the
  second argument:
  
      $ret = GetOptions(\%opts, ... );
      $ret = GetOptionsFromArray(\@ARGV, \%opts, ... );
  
  =head2 Parsing options from an arbitrary string
  
  A special entry C<GetOptionsFromString> can be used to parse options
  from an arbitrary string.
  
      use Getopt::Long qw(GetOptionsFromString);
      $ret = GetOptionsFromString($string, ...);
  
  The contents of the string are split into arguments using a call to
  C<Text::ParseWords::shellwords>. As with C<GetOptionsFromArray>, the
  global C<@ARGV> is not touched.
  
  It is possible that, upon completion, not all arguments in the string
  have been processed. C<GetOptionsFromString> will, when called in list
  context, return both the return status and an array reference to any
  remaining arguments:
  
      ($ret, $args) = GetOptionsFromString($string, ... );
  
  If any arguments remain, and C<GetOptionsFromString> was not called in
  list context, a message will be given and C<GetOptionsFromString> will
  return failure.
  
  As with GetOptionsFromArray, a first argument hash reference now
  becomes the second argument.
  
  =head2 Storing options values in a hash
  
  Sometimes, for example when there are a lot of options, having a
  separate variable for each of them can be cumbersome. GetOptions()
  supports, as an alternative mechanism, storing options values in a
  hash.
  
  To obtain this, a reference to a hash must be passed I<as the first
  argument> to GetOptions(). For each option that is specified on the
  command line, the option value will be stored in the hash with the
  option name as key. Options that are not actually used on the command
  line will not be put in the hash, on other words,
  C<exists($h{option})> (or defined()) can be used to test if an option
  was used. The drawback is that warnings will be issued if the program
  runs under C<use strict> and uses C<$h{option}> without testing with
  exists() or defined() first.
  
      my %h = ();
      GetOptions (\%h, 'length=i');	# will store in $h{length}
  
  For options that take list or hash values, it is necessary to indicate
  this by appending an C<@> or C<%> sign after the type:
  
      GetOptions (\%h, 'colours=s@');	# will push to @{$h{colours}}
  
  To make things more complicated, the hash may contain references to
  the actual destinations, for example:
  
      my $len = 0;
      my %h = ('length' => \$len);
      GetOptions (\%h, 'length=i');	# will store in $len
  
  This example is fully equivalent with:
  
      my $len = 0;
      GetOptions ('length=i' => \$len);	# will store in $len
  
  Any mixture is possible. For example, the most frequently used options
  could be stored in variables while all other options get stored in the
  hash:
  
      my $verbose = 0;			# frequently referred
      my $debug = 0;			# frequently referred
      my %h = ('verbose' => \$verbose, 'debug' => \$debug);
      GetOptions (\%h, 'verbose', 'debug', 'filter', 'size=i');
      if ( $verbose ) { ... }
      if ( exists $h{filter} ) { ... option 'filter' was specified ... }
  
  =head2 Bundling
  
  With bundling it is possible to set several single-character options
  at once. For example if C<a>, C<v> and C<x> are all valid options,
  
      -vax
  
  would set all three.
  
  Getopt::Long supports two levels of bundling. To enable bundling, a
  call to Getopt::Long::Configure is required.
  
  The first level of bundling can be enabled with:
  
      Getopt::Long::Configure ("bundling");
  
  Configured this way, single-character options can be bundled but long
  options B<must> always start with a double dash C<--> to avoid
  ambiguity. For example, when C<vax>, C<a>, C<v> and C<x> are all valid
  options,
  
      -vax
  
  would set C<a>, C<v> and C<x>, but
  
      --vax
  
  would set C<vax>.
  
  The second level of bundling lifts this restriction. It can be enabled
  with:
  
      Getopt::Long::Configure ("bundling_override");
  
  Now, C<-vax> would set the option C<vax>.
  
  When any level of bundling is enabled, option values may be inserted
  in the bundle. For example:
  
      -h24w80
  
  is equivalent to
  
      -h 24 -w 80
  
  When configured for bundling, single-character options are matched
  case sensitive while long options are matched case insensitive. To
  have the single-character options matched case insensitive as well,
  use:
  
      Getopt::Long::Configure ("bundling", "ignorecase_always");
  
  It goes without saying that bundling can be quite confusing.
  
  =head2 The lonesome dash
  
  Normally, a lone dash C<-> on the command line will not be considered
  an option. Option processing will terminate (unless "permute" is
  configured) and the dash will be left in C<@ARGV>.
  
  It is possible to get special treatment for a lone dash. This can be
  achieved by adding an option specification with an empty name, for
  example:
  
      GetOptions ('' => \$stdio);
  
  A lone dash on the command line will now be a legal option, and using
  it will set variable C<$stdio>.
  
  =head2 Argument callback
  
  A special option 'name' C<< <> >> can be used to designate a subroutine
  to handle non-option arguments. When GetOptions() encounters an
  argument that does not look like an option, it will immediately call this
  subroutine and passes it one parameter: the argument name. Well, actually
  it is an object that stringifies to the argument name.
  
  For example:
  
      my $width = 80;
      sub process { ... }
      GetOptions ('width=i' => \$width, '<>' => \&process);
  
  When applied to the following command line:
  
      arg1 --width=72 arg2 --width=60 arg3
  
  This will call
  C<process("arg1")> while C<$width> is C<80>,
  C<process("arg2")> while C<$width> is C<72>, and
  C<process("arg3")> while C<$width> is C<60>.
  
  This feature requires configuration option B<permute>, see section
  L<Configuring Getopt::Long>.
  
  =head1 Configuring Getopt::Long
  
  Getopt::Long can be configured by calling subroutine
  Getopt::Long::Configure(). This subroutine takes a list of quoted
  strings, each specifying a configuration option to be enabled, e.g.
  C<ignore_case>, or disabled, e.g. C<no_ignore_case>. Case does not
  matter. Multiple calls to Configure() are possible.
  
  Alternatively, as of version 2.24, the configuration options may be
  passed together with the C<use> statement:
  
      use Getopt::Long qw(:config no_ignore_case bundling);
  
  The following options are available:
  
  =over 12
  
  =item default
  
  This option causes all configuration options to be reset to their
  default values.
  
  =item posix_default
  
  This option causes all configuration options to be reset to their
  default values as if the environment variable POSIXLY_CORRECT had
  been set.
  
  =item auto_abbrev
  
  Allow option names to be abbreviated to uniqueness.
  Default is enabled unless environment variable
  POSIXLY_CORRECT has been set, in which case C<auto_abbrev> is disabled.
  
  =item getopt_compat
  
  Allow C<+> to start options.
  Default is enabled unless environment variable
  POSIXLY_CORRECT has been set, in which case C<getopt_compat> is disabled.
  
  =item gnu_compat
  
  C<gnu_compat> controls whether C<--opt=> is allowed, and what it should
  do. Without C<gnu_compat>, C<--opt=> gives an error. With C<gnu_compat>,
  C<--opt=> will give option C<opt> and empty value.
  This is the way GNU getopt_long() does it.
  
  =item gnu_getopt
  
  This is a short way of setting C<gnu_compat> C<bundling> C<permute>
  C<no_getopt_compat>. With C<gnu_getopt>, command line handling should be
  fully compatible with GNU getopt_long().
  
  =item require_order
  
  Whether command line arguments are allowed to be mixed with options.
  Default is disabled unless environment variable
  POSIXLY_CORRECT has been set, in which case C<require_order> is enabled.
  
  See also C<permute>, which is the opposite of C<require_order>.
  
  =item permute
  
  Whether command line arguments are allowed to be mixed with options.
  Default is enabled unless environment variable
  POSIXLY_CORRECT has been set, in which case C<permute> is disabled.
  Note that C<permute> is the opposite of C<require_order>.
  
  If C<permute> is enabled, this means that
  
      --foo arg1 --bar arg2 arg3
  
  is equivalent to
  
      --foo --bar arg1 arg2 arg3
  
  If an argument callback routine is specified, C<@ARGV> will always be
  empty upon successful return of GetOptions() since all options have been
  processed. The only exception is when C<--> is used:
  
      --foo arg1 --bar arg2 -- arg3
  
  This will call the callback routine for arg1 and arg2, and then
  terminate GetOptions() leaving C<"arg3"> in C<@ARGV>.
  
  If C<require_order> is enabled, options processing
  terminates when the first non-option is encountered.
  
      --foo arg1 --bar arg2 arg3
  
  is equivalent to
  
      --foo -- arg1 --bar arg2 arg3
  
  If C<pass_through> is also enabled, options processing will terminate
  at the first unrecognized option, or non-option, whichever comes
  first.
  
  =item bundling (default: disabled)
  
  Enabling this option will allow single-character options to be
  bundled. To distinguish bundles from long option names, long options
  I<must> be introduced with C<--> and bundles with C<->.
  
  Note that, if you have options C<a>, C<l> and C<all>, and
  auto_abbrev enabled, possible arguments and option settings are:
  
      using argument               sets option(s)
      ------------------------------------------
      -a, --a                      a
      -l, --l                      l
      -al, -la, -ala, -all,...     a, l
      --al, --all                  all
  
  The surprising part is that C<--a> sets option C<a> (due to auto
  completion), not C<all>.
  
  Note: disabling C<bundling> also disables C<bundling_override>.
  
  =item bundling_override (default: disabled)
  
  If C<bundling_override> is enabled, bundling is enabled as with
  C<bundling> but now long option names override option bundles.
  
  Note: disabling C<bundling_override> also disables C<bundling>.
  
  B<Note:> Using option bundling can easily lead to unexpected results,
  especially when mixing long options and bundles. Caveat emptor.
  
  =item ignore_case  (default: enabled)
  
  If enabled, case is ignored when matching option names. If, however,
  bundling is enabled as well, single character options will be treated
  case-sensitive.
  
  With C<ignore_case>, option specifications for options that only
  differ in case, e.g., C<"foo"> and C<"Foo">, will be flagged as
  duplicates.
  
  Note: disabling C<ignore_case> also disables C<ignore_case_always>.
  
  =item ignore_case_always (default: disabled)
  
  When bundling is in effect, case is ignored on single-character
  options also.
  
  Note: disabling C<ignore_case_always> also disables C<ignore_case>.
  
  =item auto_version (default:disabled)
  
  Automatically provide support for the B<--version> option if
  the application did not specify a handler for this option itself.
  
  Getopt::Long will provide a standard version message that includes the
  program name, its version (if $main::VERSION is defined), and the
  versions of Getopt::Long and Perl. The message will be written to
  standard output and processing will terminate.
  
  C<auto_version> will be enabled if the calling program explicitly
  specified a version number higher than 2.32 in the C<use> or
  C<require> statement.
  
  =item auto_help (default:disabled)
  
  Automatically provide support for the B<--help> and B<-?> options if
  the application did not specify a handler for this option itself.
  
  Getopt::Long will provide a help message using module L<Pod::Usage>. The
  message, derived from the SYNOPSIS POD section, will be written to
  standard output and processing will terminate.
  
  C<auto_help> will be enabled if the calling program explicitly
  specified a version number higher than 2.32 in the C<use> or
  C<require> statement.
  
  =item pass_through (default: disabled)
  
  Options that are unknown, ambiguous or supplied with an invalid option
  value are passed through in C<@ARGV> instead of being flagged as
  errors. This makes it possible to write wrapper scripts that process
  only part of the user supplied command line arguments, and pass the
  remaining options to some other program.
  
  If C<require_order> is enabled, options processing will terminate at
  the first unrecognized option, or non-option, whichever comes first.
  However, if C<permute> is enabled instead, results can become confusing.
  
  Note that the options terminator (default C<-->), if present, will
  also be passed through in C<@ARGV>.
  
  =item prefix
  
  The string that starts options. If a constant string is not
  sufficient, see C<prefix_pattern>.
  
  =item prefix_pattern
  
  A Perl pattern that identifies the strings that introduce options.
  Default is C<--|-|\+> unless environment variable
  POSIXLY_CORRECT has been set, in which case it is C<--|->.
  
  =item long_prefix_pattern
  
  A Perl pattern that allows the disambiguation of long and short
  prefixes. Default is C<-->.
  
  Typically you only need to set this if you are using nonstandard
  prefixes and want some or all of them to have the same semantics as
  '--' does under normal circumstances.
  
  For example, setting prefix_pattern to C<--|-|\+|\/> and
  long_prefix_pattern to C<--|\/> would add Win32 style argument
  handling.
  
  =item debug (default: disabled)
  
  Enable debugging output.
  
  =back
  
  =head1 Exportable Methods
  
  =over
  
  =item VersionMessage
  
  This subroutine provides a standard version message. Its argument can be:
  
  =over 4
  
  =item *
  
  A string containing the text of a message to print I<before> printing
  the standard message.
  
  =item *
  
  A numeric value corresponding to the desired exit status.
  
  =item *
  
  A reference to a hash.
  
  =back
  
  If more than one argument is given then the entire argument list is
  assumed to be a hash.  If a hash is supplied (either as a reference or
  as a list) it should contain one or more elements with the following
  keys:
  
  =over 4
  
  =item C<-message>
  
  =item C<-msg>
  
  The text of a message to print immediately prior to printing the
  program's usage message.
  
  =item C<-exitval>
  
  The desired exit status to pass to the B<exit()> function.
  This should be an integer, or else the string "NOEXIT" to
  indicate that control should simply be returned without
  terminating the invoking process.
  
  =item C<-output>
  
  A reference to a filehandle, or the pathname of a file to which the
  usage message should be written. The default is C<\*STDERR> unless the
  exit value is less than 2 (in which case the default is C<\*STDOUT>).
  
  =back
  
  You cannot tie this routine directly to an option, e.g.:
  
      GetOptions("version" => \&VersionMessage);
  
  Use this instead:
  
      GetOptions("version" => sub { VersionMessage() });
  
  =item HelpMessage
  
  This subroutine produces a standard help message, derived from the
  program's POD section SYNOPSIS using L<Pod::Usage>. It takes the same
  arguments as VersionMessage(). In particular, you cannot tie it
  directly to an option, e.g.:
  
      GetOptions("help" => \&HelpMessage);
  
  Use this instead:
  
      GetOptions("help" => sub { HelpMessage() });
  
  =back
  
  =head1 Return values and Errors
  
  Configuration errors and errors in the option definitions are
  signalled using die() and will terminate the calling program unless
  the call to Getopt::Long::GetOptions() was embedded in C<eval { ...
  }>, or die() was trapped using C<$SIG{__DIE__}>.
  
  GetOptions returns true to indicate success.
  It returns false when the function detected one or more errors during
  option parsing. These errors are signalled using warn() and can be
  trapped with C<$SIG{__WARN__}>.
  
  =head1 Legacy
  
  The earliest development of C<newgetopt.pl> started in 1990, with Perl
  version 4. As a result, its development, and the development of
  Getopt::Long, has gone through several stages. Since backward
  compatibility has always been extremely important, the current version
  of Getopt::Long still supports a lot of constructs that nowadays are
  no longer necessary or otherwise unwanted. This section describes
  briefly some of these 'features'.
  
  =head2 Default destinations
  
  When no destination is specified for an option, GetOptions will store
  the resultant value in a global variable named C<opt_>I<XXX>, where
  I<XXX> is the primary name of this option. When a program executes
  under C<use strict> (recommended), these variables must be
  pre-declared with our() or C<use vars>.
  
      our $opt_length = 0;
      GetOptions ('length=i');	# will store in $opt_length
  
  To yield a usable Perl variable, characters that are not part of the
  syntax for variables are translated to underscores. For example,
  C<--fpp-struct-return> will set the variable
  C<$opt_fpp_struct_return>. Note that this variable resides in the
  namespace of the calling program, not necessarily C<main>. For
  example:
  
      GetOptions ("size=i", "sizes=i@");
  
  with command line "-size 10 -sizes 24 -sizes 48" will perform the
  equivalent of the assignments
  
      $opt_size = 10;
      @opt_sizes = (24, 48);
  
  =head2 Alternative option starters
  
  A string of alternative option starter characters may be passed as the
  first argument (or the first argument after a leading hash reference
  argument).
  
      my $len = 0;
      GetOptions ('/', 'length=i' => $len);
  
  Now the command line may look like:
  
      /length 24 -- arg
  
  Note that to terminate options processing still requires a double dash
  C<-->.
  
  GetOptions() will not interpret a leading C<< "<>" >> as option starters
  if the next argument is a reference. To force C<< "<" >> and C<< ">" >> as
  option starters, use C<< "><" >>. Confusing? Well, B<using a starter
  argument is strongly deprecated> anyway.
  
  =head2 Configuration variables
  
  Previous versions of Getopt::Long used variables for the purpose of
  configuring. Although manipulating these variables still work, it is
  strongly encouraged to use the C<Configure> routine that was introduced
  in version 2.17. Besides, it is much easier.
  
  =head1 Tips and Techniques
  
  =head2 Pushing multiple values in a hash option
  
  Sometimes you want to combine the best of hashes and arrays. For
  example, the command line:
  
    --list add=first --list add=second --list add=third
  
  where each successive 'list add' option will push the value of add
  into array ref $list->{'add'}. The result would be like
  
    $list->{add} = [qw(first second third)];
  
  This can be accomplished with a destination routine:
  
    GetOptions('list=s%' =>
                 sub { push(@{$list{$_[1]}}, $_[2]) });
  
  =head1 Troubleshooting
  
  =head2 GetOptions does not return a false result when an option is not supplied
  
  That's why they're called 'options'.
  
  =head2 GetOptions does not split the command line correctly
  
  The command line is not split by GetOptions, but by the command line
  interpreter (CLI). On Unix, this is the shell. On Windows, it is
  COMMAND.COM or CMD.EXE. Other operating systems have other CLIs.
  
  It is important to know that these CLIs may behave different when the
  command line contains special characters, in particular quotes or
  backslashes. For example, with Unix shells you can use single quotes
  (C<'>) and double quotes (C<">) to group words together. The following
  alternatives are equivalent on Unix:
  
      "two words"
      'two words'
      two\ words
  
  In case of doubt, insert the following statement in front of your Perl
  program:
  
      print STDERR (join("|",@ARGV),"\n");
  
  to verify how your CLI passes the arguments to the program.
  
  =head2 Undefined subroutine &main::GetOptions called
  
  Are you running Windows, and did you write
  
      use GetOpt::Long;
  
  (note the capital 'O')?
  
  =head2 How do I put a "-?" option into a Getopt::Long?
  
  You can only obtain this using an alias, and Getopt::Long of at least
  version 2.13.
  
      use Getopt::Long;
      GetOptions ("help|?");    # -help and -? will both set $opt_help
  
  Other characters that can't appear in Perl identifiers are also supported
  as aliases with Getopt::Long of at least version 2.39.
  
  As of version 2.32 Getopt::Long provides auto-help, a quick and easy way
  to add the options --help and -? to your program, and handle them.
  
  See C<auto_help> in section L<Configuring Getopt::Long>.
  
  =head1 AUTHOR
  
  Johan Vromans <jvromans@squirrel.nl>
  
  =head1 COPYRIGHT AND DISCLAIMER
  
  This program is Copyright 1990,2013 by Johan Vromans.
  This program is free software; you can redistribute it and/or
  modify it under the terms of the Perl Artistic License or the
  GNU General Public License as published by the Free Software
  Foundation; either version 2 of the License, or (at your option) any
  later version.
  
  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.
  
  If you do not have a copy of the GNU General Public License write to
  the Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
  MA 02139, USA.
  
  =cut
  
GETOPT_LONG

$fatpacked{"HTTP/Config.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'HTTP_CONFIG';
  package HTTP::Config;
  
  use strict;
  use URI;
  use vars qw($VERSION);
  
  $VERSION = "6.00";
  
  sub new {
      my $class = shift;
      return bless [], $class;
  }
  
  sub entries {
      my $self = shift;
      @$self;
  }
  
  sub empty {
      my $self = shift;
      not @$self;
  }
  
  sub add {
      if (@_ == 2) {
          my $self = shift;
          push(@$self, shift);
          return;
      }
      my($self, %spec) = @_;
      push(@$self, \%spec);
      return;
  }
  
  sub find2 {
      my($self, %spec) = @_;
      my @found;
      my @rest;
   ITEM:
      for my $item (@$self) {
          for my $k (keys %spec) {
              if (!exists $item->{$k} || $spec{$k} ne $item->{$k}) {
                  push(@rest, $item);
                  next ITEM;
              }
          }
          push(@found, $item);
      }
      return \@found unless wantarray;
      return \@found, \@rest;
  }
  
  sub find {
      my $self = shift;
      my $f = $self->find2(@_);
      return @$f if wantarray;
      return $f->[0];
  }
  
  sub remove {
      my($self, %spec) = @_;
      my($removed, $rest) = $self->find2(%spec);
      @$self = @$rest if @$removed;
      return @$removed;
  }
  
  my %MATCH = (
      m_scheme => sub {
          my($v, $uri) = @_;
          return $uri->_scheme eq $v;  # URI known to be canonical
      },
      m_secure => sub {
          my($v, $uri) = @_;
          my $secure = $uri->can("secure") ? $uri->secure : $uri->_scheme eq "https";
          return $secure == !!$v;
      },
      m_host_port => sub {
          my($v, $uri) = @_;
          return unless $uri->can("host_port");
          return $uri->host_port eq $v, 7;
      },
      m_host => sub {
          my($v, $uri) = @_;
          return unless $uri->can("host");
          return $uri->host eq $v, 6;
      },
      m_port => sub {
          my($v, $uri) = @_;
          return unless $uri->can("port");
          return $uri->port eq $v;
      },
      m_domain => sub {
          my($v, $uri) = @_;
          return unless $uri->can("host");
          my $h = $uri->host;
          $h = "$h.local" unless $h =~ /\./;
          $v = ".$v" unless $v =~ /^\./;
          return length($v), 5 if substr($h, -length($v)) eq $v;
          return 0;
      },
      m_path => sub {
          my($v, $uri) = @_;
          return unless $uri->can("path");
          return $uri->path eq $v, 4;
      },
      m_path_prefix => sub {
          my($v, $uri) = @_;
          return unless $uri->can("path");
          my $path = $uri->path;
          my $len = length($v);
          return $len, 3 if $path eq $v;
          return 0 if length($path) <= $len;
          $v .= "/" unless $v =~ m,/\z,,;
          return $len, 3 if substr($path, 0, length($v)) eq $v;
          return 0;
      },
      m_path_match => sub {
          my($v, $uri) = @_;
          return unless $uri->can("path");
          return $uri->path =~ $v;
      },
      m_uri__ => sub {
          my($v, $k, $uri) = @_;
          return unless $uri->can($k);
          return 1 unless defined $v;
          return $uri->$k eq $v;
      },
      m_method => sub {
          my($v, $uri, $request) = @_;
          return $request && $request->method eq $v;
      },
      m_proxy => sub {
          my($v, $uri, $request) = @_;
          return $request && ($request->{proxy} || "") eq $v;
      },
      m_code => sub {
          my($v, $uri, $request, $response) = @_;
          $v =~ s/xx\z//;
          return unless $response;
          return length($v), 2 if substr($response->code, 0, length($v)) eq $v;
      },
      m_media_type => sub {  # for request too??
          my($v, $uri, $request, $response) = @_;
          return unless $response;
          return 1, 1 if $v eq "*/*";
          my $ct = $response->content_type;
          return 2, 1 if $v =~ s,/\*\z,, && $ct =~ m,^\Q$v\E/,;
          return 3, 1 if $v eq "html" && $response->content_is_html;
          return 4, 1 if $v eq "xhtml" && $response->content_is_xhtml;
          return 10, 1 if $v eq $ct;
          return 0;
      },
      m_header__ => sub {
          my($v, $k, $uri, $request, $response) = @_;
          return unless $request;
          return 1 if $request->header($k) eq $v;
          return 1 if $response && $response->header($k) eq $v;
          return 0;
      },
      m_response_attr__ => sub {
          my($v, $k, $uri, $request, $response) = @_;
          return unless $response;
          return 1 if !defined($v) && exists $response->{$k};
          return 0 unless exists $response->{$k};
          return 1 if $response->{$k} eq $v;
          return 0;
      },
  );
  
  sub matching {
      my $self = shift;
      if (@_ == 1) {
          if ($_[0]->can("request")) {
              unshift(@_, $_[0]->request);
              unshift(@_, undef) unless defined $_[0];
          }
          unshift(@_, $_[0]->uri_canonical) if $_[0] && $_[0]->can("uri_canonical");
      }
      my($uri, $request, $response) = @_;
      $uri = URI->new($uri) unless ref($uri);
  
      my @m;
   ITEM:
      for my $item (@$self) {
          my $order;
          for my $ikey (keys %$item) {
              my $mkey = $ikey;
              my $k;
              $k = $1 if $mkey =~ s/__(.*)/__/;
              if (my $m = $MATCH{$mkey}) {
                  #print "$ikey $mkey\n";
                  my($c, $o);
                  my @arg = (
                      defined($k) ? $k : (),
                      $uri, $request, $response
                  );
                  my $v = $item->{$ikey};
                  $v = [$v] unless ref($v) eq "ARRAY";
                  for (@$v) {
                      ($c, $o) = $m->($_, @arg);
                      #print "  - $_ ==> $c $o\n";
                      last if $c;
                  }
                  next ITEM unless $c;
                  $order->[$o || 0] += $c;
              }
          }
          $order->[7] ||= 0;
          $item->{_order} = join(".", reverse map sprintf("%03d", $_ || 0), @$order);
          push(@m, $item);
      }
      @m = sort { $b->{_order} cmp $a->{_order} } @m;
      delete $_->{_order} for @m;
      return @m if wantarray;
      return $m[0];
  }
  
  sub add_item {
      my $self = shift;
      my $item = shift;
      return $self->add(item => $item, @_);
  }
  
  sub remove_items {
      my $self = shift;
      return map $_->{item}, $self->remove(@_);
  }
  
  sub matching_items {
      my $self = shift;
      return map $_->{item}, $self->matching(@_);
  }
  
  1;
  
  __END__
  
  =head1 NAME
  
  HTTP::Config - Configuration for request and response objects
  
  =head1 SYNOPSIS
  
   use HTTP::Config;
   my $c = HTTP::Config->new;
   $c->add(m_domain => ".example.com", m_scheme => "http", verbose => 1);
   
   use HTTP::Request;
   my $request = HTTP::Request->new(GET => "http://www.example.com");
   
   if (my @m = $c->matching($request)) {
      print "Yadayada\n" if $m[0]->{verbose};
   }
  
  =head1 DESCRIPTION
  
  An C<HTTP::Config> object is a list of entries that
  can be matched against request or request/response pairs.  Its
  purpose is to hold configuration data that can be looked up given a
  request or response object.
  
  Each configuration entry is a hash.  Some keys specify matching to
  occur against attributes of request/response objects.  Other keys can
  be used to hold user data.
  
  The following methods are provided:
  
  =over 4
  
  =item $conf = HTTP::Config->new
  
  Constructs a new empty C<HTTP::Config> object and returns it.
  
  =item $conf->entries
  
  Returns the list of entries in the configuration object.
  In scalar context returns the number of entries.
  
  =item $conf->empty
  
  Return true if there are no entries in the configuration object.
  This is just a shorthand for C<< not $conf->entries >>.
  
  =item $conf->add( %matchspec, %other )
  
  =item $conf->add( \%entry )
  
  Adds a new entry to the configuration.
  You can either pass separate key/value pairs or a hash reference.
  
  =item $conf->remove( %spec )
  
  Removes (and returns) the entries that have matches for all the key/value pairs in %spec.
  If %spec is empty this will match all entries; so it will empty the configuation object.
  
  =item $conf->matching( $uri, $request, $response )
  
  =item $conf->matching( $uri )
  
  =item $conf->matching( $request )
  
  =item $conf->matching( $response )
  
  Returns the entries that match the given $uri, $request and $response triplet.
  
  If called with a single $request object then the $uri is obtained by calling its 'uri_canonical' method.
  If called with a single $response object, then the request object is obtained by calling its 'request' method;
  and then the $uri is obtained as if a single $request was provided.
  
  The entries are returned with the most specific matches first.
  In scalar context returns the most specific match or C<undef> in none match.
  
  =item $conf->add_item( $item, %matchspec )
  
  =item $conf->remove_items( %spec )
  
  =item $conf->matching_items( $uri, $request, $response )
  
  Wrappers that hides the entries themselves.
  
  =back
  
  =head2 Matching
  
  The following keys on a configuration entry specify matching.  For all
  of these you can provide an array of values instead of a single value.
  The entry matches if at least one of the values in the array matches.
  
  Entries that require match against a response object attribute will never match
  unless a response object was provided.
  
  =over
  
  =item m_scheme => $scheme
  
  Matches if the URI uses the specified scheme; e.g. "http".
  
  =item m_secure => $bool
  
  If $bool is TRUE; matches if the URI uses a secure scheme.  If $bool
  is FALSE; matches if the URI does not use a secure scheme.  An example
  of a secure scheme is "https".
  
  =item m_host_port => "$hostname:$port"
  
  Matches if the URI's host_port method return the specified value.
  
  =item m_host => $hostname
  
  Matches if the URI's host method returns the specified value.
  
  =item m_port => $port
  
  Matches if the URI's port method returns the specified value.
  
  =item m_domain => ".$domain"
  
  Matches if the URI's host method return a value that within the given
  domain.  The hostname "www.example.com" will for instance match the
  domain ".com".
  
  =item m_path => $path
  
  Matches if the URI's path method returns the specified value.
  
  =item m_path_prefix => $path
  
  Matches if the URI's path is the specified path or has the specified
  path as prefix.
  
  =item m_path_match => $Regexp
  
  Matches if the regular expression matches the URI's path.  Eg. qr/\.html$/.
  
  =item m_method => $method
  
  Matches if the request method matches the specified value. Eg. "GET" or "POST".
  
  =item m_code => $digit
  
  =item m_code => $status_code
  
  Matches if the response status code matches.  If a single digit is
  specified; matches for all response status codes beginning with that digit.
  
  =item m_proxy => $url
  
  Matches if the request is to be sent to the given Proxy server.
  
  =item m_media_type => "*/*"
  
  =item m_media_type => "text/*"
  
  =item m_media_type => "html"
  
  =item m_media_type => "xhtml"
  
  =item m_media_type => "text/html"
  
  Matches if the response media type matches.
  
  With a value of "html" matches if $response->content_is_html returns TRUE.
  With a value of "xhtml" matches if $response->content_is_xhtml returns TRUE.
  
  =item m_uri__I<$method> => undef
  
  Matches if the URI object provides the method.
  
  =item m_uri__I<$method> => $string
  
  Matches if the URI's $method method returns the given value.
  
  =item m_header__I<$field> => $string
  
  Matches if either the request or the response have a header $field with the given value.
  
  =item m_response_attr__I<$key> => undef
  
  =item m_response_attr__I<$key> => $string
  
  Matches if the response object has that key, or the entry has the given value.
  
  =back
  
  =head1 SEE ALSO
  
  L<URI>, L<HTTP::Request>, L<HTTP::Response>
  
  =head1 COPYRIGHT
  
  Copyright 2008, Gisle Aas
  
  This library is free software; you can redistribute it and/or
  modify it under the same terms as Perl itself.
  
  =cut
HTTP_CONFIG

$fatpacked{"HTTP/Cookies.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'HTTP_COOKIES';
  package HTTP::Cookies;
  
  use strict;
  use HTTP::Date qw(str2time parse_date time2str);
  use HTTP::Headers::Util qw(_split_header_words join_header_words);
  
  use vars qw($VERSION $EPOCH_OFFSET);
  $VERSION = "6.01";
  
  # Legacy: because "use "HTTP::Cookies" used be the ONLY way
  #  to load the class HTTP::Cookies::Netscape.
  require HTTP::Cookies::Netscape;
  
  $EPOCH_OFFSET = 0;  # difference from Unix epoch
  if ($^O eq "MacOS") {
      require Time::Local;
      $EPOCH_OFFSET = Time::Local::timelocal(0,0,0,1,0,70);
  }
  
  # A HTTP::Cookies object is a hash.  The main attribute is the
  # COOKIES 3 level hash:  $self->{COOKIES}{$domain}{$path}{$key}.
  
  sub new
  {
      my $class = shift;
      my $self = bless {
  	COOKIES => {},
      }, $class;
      my %cnf = @_;
      for (keys %cnf) {
  	$self->{lc($_)} = $cnf{$_};
      }
      $self->load;
      $self;
  }
  
  
  sub add_cookie_header
  {
      my $self = shift;
      my $request = shift || return;
      my $url = $request->uri;
      my $scheme = $url->scheme;
      unless ($scheme =~ /^https?\z/) {
  	return;
      }
  
      my $domain = _host($request, $url);
      $domain = "$domain.local" unless $domain =~ /\./;
      my $secure_request = ($scheme eq "https");
      my $req_path = _url_path($url);
      my $req_port = $url->port;
      my $now = time();
      _normalize_path($req_path) if $req_path =~ /%/;
  
      my @cval;    # cookie values for the "Cookie" header
      my $set_ver;
      my $netscape_only = 0; # An exact domain match applies to any cookie
  
      while ($domain =~ /\./) {
          # Checking $domain for cookies"
  	my $cookies = $self->{COOKIES}{$domain};
  	next unless $cookies;
  	if ($self->{delayload} && defined($cookies->{'//+delayload'})) {
  	    my $cookie_data = $cookies->{'//+delayload'}{'cookie'};
  	    delete $self->{COOKIES}{$domain};
  	    $self->load_cookie($cookie_data->[1]);
  	    $cookies = $self->{COOKIES}{$domain};
  	    next unless $cookies;  # should not really happen
  	}
  
  	# Want to add cookies corresponding to the most specific paths
  	# first (i.e. longest path first)
  	my $path;
  	for $path (sort {length($b) <=> length($a) } keys %$cookies) {
  	    if (index($req_path, $path) != 0) {
  		next;
  	    }
  
  	    my($key,$array);
  	    while (($key,$array) = each %{$cookies->{$path}}) {
  		my($version,$val,$port,$path_spec,$secure,$expires) = @$array;
  		if ($secure && !$secure_request) {
  		    next;
  		}
  		if ($expires && $expires < $now) {
  		    next;
  		}
  		if ($port) {
  		    my $found;
  		    if ($port =~ s/^_//) {
  			# The corresponding Set-Cookie attribute was empty
  			$found++ if $port eq $req_port;
  			$port = "";
  		    }
  		    else {
  			my $p;
  			for $p (split(/,/, $port)) {
  			    $found++, last if $p eq $req_port;
  			}
  		    }
  		    unless ($found) {
  			next;
  		    }
  		}
  		if ($version > 0 && $netscape_only) {
  		    next;
  		}
  
  		# set version number of cookie header.
  	        # XXX: What should it be if multiple matching
                  #      Set-Cookie headers have different versions themselves
  		if (!$set_ver++) {
  		    if ($version >= 1) {
  			push(@cval, "\$Version=$version");
  		    }
  		    elsif (!$self->{hide_cookie2}) {
  			$request->header(Cookie2 => '$Version="1"');
  		    }
  		}
  
  		# do we need to quote the value
  		if ($val =~ /\W/ && $version) {
  		    $val =~ s/([\\\"])/\\$1/g;
  		    $val = qq("$val");
  		}
  
  		# and finally remember this cookie
  		push(@cval, "$key=$val");
  		if ($version >= 1) {
  		    push(@cval, qq(\$Path="$path"))     if $path_spec;
  		    push(@cval, qq(\$Domain="$domain")) if $domain =~ /^\./;
  		    if (defined $port) {
  			my $p = '$Port';
  			$p .= qq(="$port") if length $port;
  			push(@cval, $p);
  		    }
  		}
  
  	    }
          }
  
      } continue {
  	# Try with a more general domain, alternately stripping
  	# leading name components and leading dots.  When this
  	# results in a domain with no leading dot, it is for
  	# Netscape cookie compatibility only:
  	#
  	# a.b.c.net	Any cookie
  	# .b.c.net	Any cookie
  	# b.c.net	Netscape cookie only
  	# .c.net	Any cookie
  
  	if ($domain =~ s/^\.+//) {
  	    $netscape_only = 1;
  	}
  	else {
  	    $domain =~ s/[^.]*//;
  	    $netscape_only = 0;
  	}
      }
  
      if (@cval) {
  	if (my $old = $request->header("Cookie")) {
  	    unshift(@cval, $old);
  	}
  	$request->header(Cookie => join("; ", @cval));
      }
  
      $request;
  }
  
  
  sub extract_cookies
  {
      my $self = shift;
      my $response = shift || return;
  
      my @set = _split_header_words($response->_header("Set-Cookie2"));
      my @ns_set = $response->_header("Set-Cookie");
  
      return $response unless @set || @ns_set;  # quick exit
  
      my $request = $response->request;
      my $url = $request->uri;
      my $req_host = _host($request, $url);
      $req_host = "$req_host.local" unless $req_host =~ /\./;
      my $req_port = $url->port;
      my $req_path = _url_path($url);
      _normalize_path($req_path) if $req_path =~ /%/;
  
      if (@ns_set) {
  	# The old Netscape cookie format for Set-Cookie
  	# http://curl.haxx.se/rfc/cookie_spec.html
  	# can for instance contain an unquoted "," in the expires
  	# field, so we have to use this ad-hoc parser.
  	my $now = time();
  
  	# Build a hash of cookies that was present in Set-Cookie2
  	# headers.  We need to skip them if we also find them in a
  	# Set-Cookie header.
  	my %in_set2;
  	for (@set) {
  	    $in_set2{$_->[0]}++;
  	}
  
  	my $set;
  	for $set (@ns_set) {
              $set =~ s/^\s+//;
  	    my @cur;
  	    my $param;
  	    my $expires;
  	    my $first_param = 1;
  	    for $param (split(/;\s*/, $set)) {
                  next unless length($param);
  		my($k,$v) = split(/\s*=\s*/, $param, 2);
  		if (defined $v) {
  		    $v =~ s/\s+$//;
  		    #print "$k => $v\n";
  		}
  		else {
  		    $k =~ s/\s+$//;
  		    #print "$k => undef";
  		}
  		if (!$first_param && lc($k) eq "expires") {
  		    my $etime = str2time($v);
  		    if (defined $etime) {
  			push(@cur, "Max-Age" => $etime - $now);
  			$expires++;
  		    }
  		    else {
  			# parse_date can deal with years outside the range of time_t,
  			my($year, $mon, $day, $hour, $min, $sec, $tz) = parse_date($v);
  			if ($year) {
  			    my $thisyear = (gmtime)[5] + 1900;
  			    if ($year < $thisyear) {
  				push(@cur, "Max-Age" => -1);  # any negative value will do
  				$expires++;
  			    }
  			    elsif ($year >= $thisyear + 10) {
  				# the date is at least 10 years into the future, just replace
  				# it with something approximate
  				push(@cur, "Max-Age" => 10 * 365 * 24 * 60 * 60);
  				$expires++;
  			    }
  			}
  		    }
  		}
                  elsif (!$first_param && lc($k) =~ /^(?:version|discard|ns-cookie)/) {
                      # ignore
                  }
  		else {
  		    push(@cur, $k => $v);
  		}
  		$first_param = 0;
  	    }
              next unless @cur;
  	    next if $in_set2{$cur[0]};
  
  #	    push(@cur, "Port" => $req_port);
  	    push(@cur, "Discard" => undef) unless $expires;
  	    push(@cur, "Version" => 0);
  	    push(@cur, "ns-cookie" => 1);
  	    push(@set, \@cur);
  	}
      }
  
    SET_COOKIE:
      for my $set (@set) {
  	next unless @$set >= 2;
  
  	my $key = shift @$set;
  	my $val = shift @$set;
  
  	my %hash;
  	while (@$set) {
  	    my $k = shift @$set;
  	    my $v = shift @$set;
  	    my $lc = lc($k);
  	    # don't loose case distinction for unknown fields
  	    $k = $lc if $lc =~ /^(?:discard|domain|max-age|
                                      path|port|secure|version)$/x;
  	    if ($k eq "discard" || $k eq "secure") {
  		$v = 1 unless defined $v;
  	    }
  	    next if exists $hash{$k};  # only first value is significant
  	    $hash{$k} = $v;
  	};
  
  	my %orig_hash = %hash;
  	my $version   = delete $hash{version};
  	$version = 1 unless defined($version);
  	my $discard   = delete $hash{discard};
  	my $secure    = delete $hash{secure};
  	my $maxage    = delete $hash{'max-age'};
  	my $ns_cookie = delete $hash{'ns-cookie'};
  
  	# Check domain
  	my $domain  = delete $hash{domain};
  	$domain = lc($domain) if defined $domain;
  	if (defined($domain)
  	    && $domain ne $req_host && $domain ne ".$req_host") {
  	    if ($domain !~ /\./ && $domain ne "local") {
  		next SET_COOKIE;
  	    }
  	    $domain = ".$domain" unless $domain =~ /^\./;
  	    if ($domain =~ /\.\d+$/) {
  		next SET_COOKIE;
  	    }
  	    my $len = length($domain);
  	    unless (substr($req_host, -$len) eq $domain) {
  		next SET_COOKIE;
  	    }
  	    my $hostpre = substr($req_host, 0, length($req_host) - $len);
  	    if ($hostpre =~ /\./ && !$ns_cookie) {
  		next SET_COOKIE;
  	    }
  	}
  	else {
  	    $domain = $req_host;
  	}
  
  	my $path = delete $hash{path};
  	my $path_spec;
  	if (defined $path && $path ne '') {
  	    $path_spec++;
  	    _normalize_path($path) if $path =~ /%/;
  	    if (!$ns_cookie &&
                  substr($req_path, 0, length($path)) ne $path) {
  		next SET_COOKIE;
  	    }
  	}
  	else {
  	    $path = $req_path;
  	    $path =~ s,/[^/]*$,,;
  	    $path = "/" unless length($path);
  	}
  
  	my $port;
  	if (exists $hash{port}) {
  	    $port = delete $hash{port};
  	    if (defined $port) {
  		$port =~ s/\s+//g;
  		my $found;
  		for my $p (split(/,/, $port)) {
  		    unless ($p =~ /^\d+$/) {
  			next SET_COOKIE;
  		    }
  		    $found++ if $p eq $req_port;
  		}
  		unless ($found) {
  		    next SET_COOKIE;
  		}
  	    }
  	    else {
  		$port = "_$req_port";
  	    }
  	}
  	$self->set_cookie($version,$key,$val,$path,$domain,$port,$path_spec,$secure,$maxage,$discard, \%hash)
  	    if $self->set_cookie_ok(\%orig_hash);
      }
  
      $response;
  }
  
  sub set_cookie_ok
  {
      1;
  }
  
  
  sub set_cookie
  {
      my $self = shift;
      my($version,
         $key, $val, $path, $domain, $port,
         $path_spec, $secure, $maxage, $discard, $rest) = @_;
  
      # path and key can not be empty (key can't start with '$')
      return $self if !defined($path) || $path !~ m,^/, ||
  	            !defined($key)  || $key  =~ m,^\$,;
  
      # ensure legal port
      if (defined $port) {
  	return $self unless $port =~ /^_?\d+(?:,\d+)*$/;
      }
  
      my $expires;
      if (defined $maxage) {
  	if ($maxage <= 0) {
  	    delete $self->{COOKIES}{$domain}{$path}{$key};
  	    return $self;
  	}
  	$expires = time() + $maxage;
      }
      $version = 0 unless defined $version;
  
      my @array = ($version, $val,$port,
  		 $path_spec,
  		 $secure, $expires, $discard);
      push(@array, {%$rest}) if defined($rest) && %$rest;
      # trim off undefined values at end
      pop(@array) while !defined $array[-1];
  
      $self->{COOKIES}{$domain}{$path}{$key} = \@array;
      $self;
  }
  
  
  sub save
  {
      my $self = shift;
      my $file = shift || $self->{'file'} || return;
      local(*FILE);
      open(FILE, ">$file") or die "Can't open $file: $!";
      print FILE "#LWP-Cookies-1.0\n";
      print FILE $self->as_string(!$self->{ignore_discard});
      close(FILE);
      1;
  }
  
  
  sub load
  {
      my $self = shift;
      my $file = shift || $self->{'file'} || return;
      local(*FILE, $_);
      local $/ = "\n";  # make sure we got standard record separator
      open(FILE, $file) or return;
      my $magic = <FILE>;
      unless ($magic =~ /^\#LWP-Cookies-(\d+\.\d+)/) {
  	warn "$file does not seem to contain cookies";
  	return;
      }
      while (<FILE>) {
  	next unless s/^Set-Cookie3:\s*//;
  	chomp;
  	my $cookie;
  	for $cookie (_split_header_words($_)) {
  	    my($key,$val) = splice(@$cookie, 0, 2);
  	    my %hash;
  	    while (@$cookie) {
  		my $k = shift @$cookie;
  		my $v = shift @$cookie;
  		$hash{$k} = $v;
  	    }
  	    my $version   = delete $hash{version};
  	    my $path      = delete $hash{path};
  	    my $domain    = delete $hash{domain};
  	    my $port      = delete $hash{port};
  	    my $expires   = str2time(delete $hash{expires});
  
  	    my $path_spec = exists $hash{path_spec}; delete $hash{path_spec};
  	    my $secure    = exists $hash{secure};    delete $hash{secure};
  	    my $discard   = exists $hash{discard};   delete $hash{discard};
  
  	    my @array =	($version,$val,$port,
  			 $path_spec,$secure,$expires,$discard);
  	    push(@array, \%hash) if %hash;
  	    $self->{COOKIES}{$domain}{$path}{$key} = \@array;
  	}
      }
      close(FILE);
      1;
  }
  
  
  sub revert
  {
      my $self = shift;
      $self->clear->load;
      $self;
  }
  
  
  sub clear
  {
      my $self = shift;
      if (@_ == 0) {
  	$self->{COOKIES} = {};
      }
      elsif (@_ == 1) {
  	delete $self->{COOKIES}{$_[0]};
      }
      elsif (@_ == 2) {
  	delete $self->{COOKIES}{$_[0]}{$_[1]};
      }
      elsif (@_ == 3) {
  	delete $self->{COOKIES}{$_[0]}{$_[1]}{$_[2]};
      }
      else {
  	require Carp;
          Carp::carp('Usage: $c->clear([domain [,path [,key]]])');
      }
      $self;
  }
  
  
  sub clear_temporary_cookies
  {
      my($self) = @_;
  
      $self->scan(sub {
          if($_[9] or        # "Discard" flag set
             not $_[8]) {    # No expire field?
              $_[8] = -1;            # Set the expire/max_age field
              $self->set_cookie(@_); # Clear the cookie
          }
        });
  }
  
  
  sub DESTROY
  {
      my $self = shift;
      local($., $@, $!, $^E, $?);
      $self->save if $self->{'autosave'};
  }
  
  
  sub scan
  {
      my($self, $cb) = @_;
      my($domain,$path,$key);
      for $domain (sort keys %{$self->{COOKIES}}) {
  	for $path (sort keys %{$self->{COOKIES}{$domain}}) {
  	    for $key (sort keys %{$self->{COOKIES}{$domain}{$path}}) {
  		my($version,$val,$port,$path_spec,
  		   $secure,$expires,$discard,$rest) =
  		       @{$self->{COOKIES}{$domain}{$path}{$key}};
  		$rest = {} unless defined($rest);
  		&$cb($version,$key,$val,$path,$domain,$port,
  		     $path_spec,$secure,$expires,$discard,$rest);
  	    }
  	}
      }
  }
  
  
  sub as_string
  {
      my($self, $skip_discard) = @_;
      my @res;
      $self->scan(sub {
  	my($version,$key,$val,$path,$domain,$port,
  	   $path_spec,$secure,$expires,$discard,$rest) = @_;
  	return if $discard && $skip_discard;
  	my @h = ($key, $val);
  	push(@h, "path", $path);
  	push(@h, "domain" => $domain);
  	push(@h, "port" => $port) if defined $port;
  	push(@h, "path_spec" => undef) if $path_spec;
  	push(@h, "secure" => undef) if $secure;
  	push(@h, "expires" => HTTP::Date::time2isoz($expires)) if $expires;
  	push(@h, "discard" => undef) if $discard;
  	my $k;
  	for $k (sort keys %$rest) {
  	    push(@h, $k, $rest->{$k});
  	}
  	push(@h, "version" => $version);
  	push(@res, "Set-Cookie3: " . join_header_words(\@h));
      });
      join("\n", @res, "");
  }
  
  sub _host
  {
      my($request, $url) = @_;
      if (my $h = $request->header("Host")) {
  	$h =~ s/:\d+$//;  # might have a port as well
  	return lc($h);
      }
      return lc($url->host);
  }
  
  sub _url_path
  {
      my $url = shift;
      my $path;
      if($url->can('epath')) {
         $path = $url->epath;    # URI::URL method
      }
      else {
         $path = $url->path;           # URI::_generic method
      }
      $path = "/" unless length $path;
      $path;
  }
  
  sub _normalize_path  # so that plain string compare can be used
  {
      my $x;
      $_[0] =~ s/%([0-9a-fA-F][0-9a-fA-F])/
  	         $x = uc($1);
                   $x eq "2F" || $x eq "25" ? "%$x" :
                                              pack("C", hex($x));
                /eg;
      $_[0] =~ s/([\0-\x20\x7f-\xff])/sprintf("%%%02X",ord($1))/eg;
  }
  
  1;
  
  __END__
  
  =head1 NAME
  
  HTTP::Cookies - HTTP cookie jars
  
  =head1 SYNOPSIS
  
    use HTTP::Cookies;
    $cookie_jar = HTTP::Cookies->new(
      file => "$ENV{'HOME'}/lwp_cookies.dat",
      autosave => 1,
    );
  
    use LWP;
    my $browser = LWP::UserAgent->new;
    $browser->cookie_jar($cookie_jar);
  
  Or for an empty and temporary cookie jar:
  
    use LWP;
    my $browser = LWP::UserAgent->new;
    $browser->cookie_jar( {} );
  
  =head1 DESCRIPTION
  
  This class is for objects that represent a "cookie jar" -- that is, a
  database of all the HTTP cookies that a given LWP::UserAgent object
  knows about.
  
  Cookies are a general mechanism which server side connections can use
  to both store and retrieve information on the client side of the
  connection.  For more information about cookies refer to
  <URL:http://curl.haxx.se/rfc/cookie_spec.html> and
  <URL:http://www.cookiecentral.com/>.  This module also implements the
  new style cookies described in I<RFC 2965>.
  The two variants of cookies are supposed to be able to coexist happily.
  
  Instances of the class I<HTTP::Cookies> are able to store a collection
  of Set-Cookie2: and Set-Cookie: headers and are able to use this
  information to initialize Cookie-headers in I<HTTP::Request> objects.
  The state of a I<HTTP::Cookies> object can be saved in and restored from
  files.
  
  =head1 METHODS
  
  The following methods are provided:
  
  =over 4
  
  =item $cookie_jar = HTTP::Cookies->new
  
  The constructor takes hash style parameters.  The following
  parameters are recognized:
  
    file:            name of the file to restore cookies from and save cookies to
    autosave:        save during destruction (bool)
    ignore_discard:  save even cookies that are requested to be discarded (bool)
    hide_cookie2:    do not add Cookie2 header to requests
  
  Future parameters might include (not yet implemented):
  
    max_cookies               300
    max_cookies_per_domain    20
    max_cookie_size           4096
  
    no_cookies   list of domain names that we never return cookies to
  
  =item $cookie_jar->add_cookie_header( $request )
  
  The add_cookie_header() method will set the appropriate Cookie:-header
  for the I<HTTP::Request> object given as argument.  The $request must
  have a valid url attribute before this method is called.
  
  =item $cookie_jar->extract_cookies( $response )
  
  The extract_cookies() method will look for Set-Cookie: and
  Set-Cookie2: headers in the I<HTTP::Response> object passed as
  argument.  Any of these headers that are found are used to update
  the state of the $cookie_jar.
  
  =item $cookie_jar->set_cookie( $version, $key, $val, $path, $domain, $port, $path_spec, $secure, $maxage, $discard, \%rest )
  
  The set_cookie() method updates the state of the $cookie_jar.  The
  $key, $val, $domain, $port and $path arguments are strings.  The
  $path_spec, $secure, $discard arguments are boolean values. The $maxage
  value is a number indicating number of seconds that this cookie will
  live.  A value <= 0 will delete this cookie.  %rest defines
  various other attributes like "Comment" and "CommentURL".
  
  =item $cookie_jar->save
  
  =item $cookie_jar->save( $file )
  
  This method file saves the state of the $cookie_jar to a file.
  The state can then be restored later using the load() method.  If a
  filename is not specified we will use the name specified during
  construction.  If the attribute I<ignore_discard> is set, then we
  will even save cookies that are marked to be discarded.
  
  The default is to save a sequence of "Set-Cookie3" lines.
  "Set-Cookie3" is a proprietary LWP format, not known to be compatible
  with any browser.  The I<HTTP::Cookies::Netscape> sub-class can
  be used to save in a format compatible with Netscape.
  
  =item $cookie_jar->load
  
  =item $cookie_jar->load( $file )
  
  This method reads the cookies from the file and adds them to the
  $cookie_jar.  The file must be in the format written by the save()
  method.
  
  =item $cookie_jar->revert
  
  This method empties the $cookie_jar and re-loads the $cookie_jar
  from the last save file.
  
  =item $cookie_jar->clear
  
  =item $cookie_jar->clear( $domain )
  
  =item $cookie_jar->clear( $domain, $path )
  
  =item $cookie_jar->clear( $domain, $path, $key )
  
  Invoking this method without arguments will empty the whole
  $cookie_jar.  If given a single argument only cookies belonging to
  that domain will be removed.  If given two arguments, cookies
  belonging to the specified path within that domain are removed.  If
  given three arguments, then the cookie with the specified key, path
  and domain is removed.
  
  =item $cookie_jar->clear_temporary_cookies
  
  Discard all temporary cookies. Scans for all cookies in the jar
  with either no expire field or a true C<discard> flag. To be
  called when the user agent shuts down according to RFC 2965.
  
  =item $cookie_jar->scan( \&callback )
  
  The argument is a subroutine that will be invoked for each cookie
  stored in the $cookie_jar.  The subroutine will be invoked with
  the following arguments:
  
    0  version
    1  key
    2  val
    3  path
    4  domain
    5  port
    6  path_spec
    7  secure
    8  expires
    9  discard
   10  hash
  
  =item $cookie_jar->as_string
  
  =item $cookie_jar->as_string( $skip_discardables )
  
  The as_string() method will return the state of the $cookie_jar
  represented as a sequence of "Set-Cookie3" header lines separated by
  "\n".  If $skip_discardables is TRUE, it will not return lines for
  cookies with the I<Discard> attribute.
  
  =back
  
  =head1 SEE ALSO
  
  L<HTTP::Cookies::Netscape>, L<HTTP::Cookies::Microsoft>
  
  =head1 COPYRIGHT
  
  Copyright 1997-2002 Gisle Aas
  
  This library is free software; you can redistribute it and/or
  modify it under the same terms as Perl itself.
  
HTTP_COOKIES

$fatpacked{"HTTP/Cookies/Microsoft.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'HTTP_COOKIES_MICROSOFT';
  package HTTP::Cookies::Microsoft;
  
  use strict;
  
  use vars qw(@ISA $VERSION);
  
  $VERSION = "6.00";
  
  require HTTP::Cookies;
  @ISA=qw(HTTP::Cookies);
  
  sub load_cookies_from_file
  {
  	my ($file) = @_;
  	my @cookies;
  	my ($key, $value, $domain_path, $flags, $lo_expire, $hi_expire);
  	my ($lo_create, $hi_create, $sep);
  
  	open(COOKIES, $file) || return;
  
  	while ($key = <COOKIES>)
  	{
  		chomp($key);
  		chomp($value     = <COOKIES>);
  		chomp($domain_path= <COOKIES>);
  		chomp($flags     = <COOKIES>);		# 0x0001 bit is for secure
  		chomp($lo_expire = <COOKIES>);
  		chomp($hi_expire = <COOKIES>);
  		chomp($lo_create = <COOKIES>);
  		chomp($hi_create = <COOKIES>);
  		chomp($sep       = <COOKIES>);
  
  		if (!defined($key) || !defined($value) || !defined($domain_path) ||
  			!defined($flags) || !defined($hi_expire) || !defined($lo_expire) ||
  			!defined($hi_create) || !defined($lo_create) || !defined($sep) ||
  			($sep ne '*'))
  		{
  			last;
  		}
  
  		if ($domain_path =~ /^([^\/]+)(\/.*)$/)
  		{
  			my $domain = $1;
  			my $path = $2;
  
  			push(@cookies, {KEY => $key, VALUE => $value, DOMAIN => $domain,
  					PATH => $path, FLAGS =>$flags, HIXP =>$hi_expire,
  					LOXP => $lo_expire, HICREATE => $hi_create,
  					LOCREATE => $lo_create});
  		}
  	}
  
  	return \@cookies;
  }
  
  sub get_user_name
  {
  	use Win32;
  	use locale;
  	my $user = lc(Win32::LoginName());
  
  	return $user;
  }
  
  # MSIE stores create and expire times as Win32 FILETIME,
  # which is 64 bits of 100 nanosecond intervals since Jan 01 1601
  #
  # But Cookies code expects time in 32-bit value expressed
  # in seconds since Jan 01 1970
  #
  sub epoch_time_offset_from_win32_filetime
  {
  	my ($high, $low) = @_;
  
  	#--------------------------------------------------------
  	# USEFUL CONSTANT
  	#--------------------------------------------------------
  	# 0x019db1de 0xd53e8000 is 1970 Jan 01 00:00:00 in Win32 FILETIME
  	#
  	# 100 nanosecond intervals == 0.1 microsecond intervals
  	
  	my $filetime_low32_1970 = 0xd53e8000;
  	my $filetime_high32_1970 = 0x019db1de;
  
  	#------------------------------------
  	# ALGORITHM
  	#------------------------------------
  	# To go from 100 nanosecond intervals to seconds since 00:00 Jan 01 1970:
  	#
  	# 1. Adjust 100 nanosecond intervals to Jan 01 1970 base
  	# 2. Divide by 10 to get to microseconds (1/millionth second)
  	# 3. Divide by 1000000 (10 ^ 6) to get to seconds
  	#
  	# We can combine Step 2 & 3 into one divide.
  	#
  	# After much trial and error, I came up with the following code which
  	# avoids using Math::BigInt or floating pt, but still gives correct answers
  
  	# If the filetime is before the epoch, return 0
  	if (($high < $filetime_high32_1970) ||
  	    (($high == $filetime_high32_1970) && ($low < $filetime_low32_1970)))
      	{
  		return 0;
  	}
  
  	# Can't multiply by 0x100000000, (1 << 32),
  	# without Perl issuing an integer overflow warning
  	#
  	# So use two multiplies by 0x10000 instead of one multiply by 0x100000000
  	#
  	# The result is the same.
  	#
  	my $date1970 = (($filetime_high32_1970 * 0x10000) * 0x10000) + $filetime_low32_1970;
  	my $time = (($high * 0x10000) * 0x10000) + $low;
  
  	$time -= $date1970;
  	$time /= 10000000;
  
  	return $time;
  }
  
  sub load_cookie
  {
  	my($self, $file) = @_;
          my $now = time() - $HTTP::Cookies::EPOCH_OFFSET;
  	my $cookie_data;
  
          if (-f $file)
          {
  		# open the cookie file and get the data
  		$cookie_data = load_cookies_from_file($file);
  
  		foreach my $cookie (@{$cookie_data})
  		{
  			my $secure = ($cookie->{FLAGS} & 1) != 0;
  			my $expires = epoch_time_offset_from_win32_filetime($cookie->{HIXP}, $cookie->{LOXP});
  
  			$self->set_cookie(undef, $cookie->{KEY}, $cookie->{VALUE}, 
  					  $cookie->{PATH}, $cookie->{DOMAIN}, undef,
  					  0, $secure, $expires-$now, 0);
  		}
  	}
  }
  
  sub load
  {
  	my($self, $cookie_index) = @_;
  	my $now = time() - $HTTP::Cookies::EPOCH_OFFSET;
  	my $cookie_dir = '';
  	my $delay_load = (defined($self->{'delayload'}) && $self->{'delayload'});
  	my $user_name = get_user_name();
  	my $data;
  
  	$cookie_index ||= $self->{'file'} || return;
  	if ($cookie_index =~ /[\\\/][^\\\/]+$/)
  	{
  		$cookie_dir = $` . "\\";
  	}
  
  	local(*INDEX, $_);
  
  	open(INDEX, $cookie_index) || return;
  	binmode(INDEX);
  	if (256 != read(INDEX, $data, 256))
  	{
  		warn "$cookie_index file is not large enough";
  		close(INDEX);
  		return;
  	}
  
  	# Cookies' index.dat file starts with 32 bytes of signature
  	# followed by an offset to the first record, stored as a little-endian DWORD
  	my ($sig, $size) = unpack('a32 V', $data);
  	
  	if (($sig !~ /^Client UrlCache MMF Ver 5\.2/) || # check that sig is valid (only tested in IE6.0)
  		(0x4000 != $size))
  	{
  		warn "$cookie_index ['$sig' $size] does not seem to contain cookies";
  		close(INDEX);
  		return;
  	}
  
  	if (0 == seek(INDEX, $size, 0)) # move the file ptr to start of the first record
  	{
  		close(INDEX);
  		return;
  	}
  
  	# Cookies are usually stored in 'URL ' records in two contiguous 0x80 byte sectors (256 bytes)
  	# so read in two 0x80 byte sectors and adjust if not a Cookie.
  	while (256 == read(INDEX, $data, 256))
  	{
  		# each record starts with a 4-byte signature
  		# and a count (little-endian DWORD) of 0x80 byte sectors for the record
  		($sig, $size) = unpack('a4 V', $data);
  
  		# Cookies are found in 'URL ' records
  		if ('URL ' ne $sig)
  		{
  			# skip over uninteresting record: I've seen 'HASH' and 'LEAK' records
  			if (($sig eq 'HASH') || ($sig eq 'LEAK'))
  			{
  				# '-2' takes into account the two 0x80 byte sectors we've just read in
  				if (($size > 0) && ($size != 2))
  				{
  				    if (0 == seek(INDEX, ($size-2)*0x80, 1))
  				    {
  					    # Seek failed. Something's wrong. Gonna stop.
  					    last;
  				    }
  				}
  			}
  			next;
  		}
  
  		#$REMOVE Need to check if URL records in Cookies' index.dat will
  		#        ever use more than two 0x80 byte sectors
  		if ($size > 2)
  		{
  			my $more_data = ($size-2)*0x80;
  
  			if ($more_data != read(INDEX, $data, $more_data, 256))
  			{
  				last;
  			}
  		}
  
                  (my $user_name2 = $user_name) =~ s/ /_/g;
  		if ($data =~ /Cookie\:\Q$user_name\E\@([\x21-\xFF]+).*?((?:\Q$user_name\E|\Q$user_name2\E)\@[\x21-\xFF]+\.txt)/)
  		{
  			my $cookie_file = $cookie_dir . $2; # form full pathname
  
  			if (!$delay_load)
  			{
  				$self->load_cookie($cookie_file);
  			}
  			else
  			{
  				my $domain = $1;
  
  				# grab only the domain name, drop everything from the first dir sep on
  				if ($domain =~ m{[\\/]})
  				{
  					$domain = $`;
  				}
  
  				# set the delayload cookie for this domain with 
  				# the cookie_file as cookie for later-loading info
  				$self->set_cookie(undef, 'cookie', $cookie_file,
  						      '//+delayload', $domain, undef,
  						      0, 0, $now+86400, 0);
  			}
  		}
  	}
  
  	close(INDEX);
  
  	1;
  }
  
  1;
  
  __END__
  
  =head1 NAME
  
  HTTP::Cookies::Microsoft - access to Microsoft cookies files
  
  =head1 SYNOPSIS
  
   use LWP;
   use HTTP::Cookies::Microsoft;
   use Win32::TieRegistry(Delimiter => "/");
   my $cookies_dir = $Registry->
        {"CUser/Software/Microsoft/Windows/CurrentVersion/Explorer/Shell Folders/Cookies"};
  
   $cookie_jar = HTTP::Cookies::Microsoft->new(
                     file     => "$cookies_dir\\index.dat",
                     'delayload' => 1,
                 );
   my $browser = LWP::UserAgent->new;
   $browser->cookie_jar( $cookie_jar );
  
  =head1 DESCRIPTION
  
  This is a subclass of C<HTTP::Cookies> which
  loads Microsoft Internet Explorer 5.x and 6.x for Windows (MSIE)
  cookie files.
  
  See the documentation for L<HTTP::Cookies>.
  
  =head1 METHODS
  
  The following methods are provided:
  
  =over 4
  
  =item $cookie_jar = HTTP::Cookies::Microsoft->new;
  
  The constructor takes hash style parameters. In addition
  to the regular HTTP::Cookies parameters, HTTP::Cookies::Microsoft
  recognizes the following:
  
    delayload:       delay loading of cookie data until a request
                     is actually made. This results in faster
                     runtime unless you use most of the cookies
                     since only the domain's cookie data
                     is loaded on demand.
  
  =back
  
  =head1 CAVEATS
  
  Please note that the code DOESN'T support saving to the MSIE
  cookie file format.
  
  =head1 AUTHOR
  
  Johnny Lee <typo_pl@hotmail.com>
  
  =head1 COPYRIGHT
  
  Copyright 2002 Johnny Lee
  
  This library is free software; you can redistribute it and/or
  modify it under the same terms as Perl itself.
  
  =cut
  
HTTP_COOKIES_MICROSOFT

$fatpacked{"HTTP/Cookies/Netscape.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'HTTP_COOKIES_NETSCAPE';
  package HTTP::Cookies::Netscape;
  
  use strict;
  use vars qw(@ISA $VERSION);
  
  $VERSION = "6.00";
  
  require HTTP::Cookies;
  @ISA=qw(HTTP::Cookies);
  
  sub load
  {
      my($self, $file) = @_;
      $file ||= $self->{'file'} || return;
      local(*FILE, $_);
      local $/ = "\n";  # make sure we got standard record separator
      my @cookies;
      open(FILE, $file) || return;
      my $magic = <FILE>;
      unless ($magic =~ /^\#(?: Netscape)? HTTP Cookie File/) {
  	warn "$file does not look like a netscape cookies file" if $^W;
  	close(FILE);
  	return;
      }
      my $now = time() - $HTTP::Cookies::EPOCH_OFFSET;
      while (<FILE>) {
  	next if /^\s*\#/;
  	next if /^\s*$/;
  	tr/\n\r//d;
  	my($domain,$bool1,$path,$secure, $expires,$key,$val) = split(/\t/, $_);
  	$secure = ($secure eq "TRUE");
  	$self->set_cookie(undef,$key,$val,$path,$domain,undef,
  			  0,$secure,$expires-$now, 0);
      }
      close(FILE);
      1;
  }
  
  sub save
  {
      my($self, $file) = @_;
      $file ||= $self->{'file'} || return;
      local(*FILE, $_);
      open(FILE, ">$file") || return;
  
      # Use old, now broken link to the old cookie spec just in case something
      # else (not us!) requires the comment block exactly this way.
      print FILE <<EOT;
  # Netscape HTTP Cookie File
  # http://www.netscape.com/newsref/std/cookie_spec.html
  # This is a generated file!  Do not edit.
  
  EOT
  
      my $now = time - $HTTP::Cookies::EPOCH_OFFSET;
      $self->scan(sub {
  	my($version,$key,$val,$path,$domain,$port,
  	   $path_spec,$secure,$expires,$discard,$rest) = @_;
  	return if $discard && !$self->{ignore_discard};
  	$expires = $expires ? $expires - $HTTP::Cookies::EPOCH_OFFSET : 0;
  	return if $now > $expires;
  	$secure = $secure ? "TRUE" : "FALSE";
  	my $bool = $domain =~ /^\./ ? "TRUE" : "FALSE";
  	print FILE join("\t", $domain, $bool, $path, $secure, $expires, $key, $val), "\n";
      });
      close(FILE);
      1;
  }
  
  1;
  __END__
  
  =head1 NAME
  
  HTTP::Cookies::Netscape - access to Netscape cookies files
  
  =head1 SYNOPSIS
  
   use LWP;
   use HTTP::Cookies::Netscape;
   $cookie_jar = HTTP::Cookies::Netscape->new(
     file => "c:/program files/netscape/users/ZombieCharity/cookies.txt",
   );
   my $browser = LWP::UserAgent->new;
   $browser->cookie_jar( $cookie_jar );
  
  =head1 DESCRIPTION
  
  This is a subclass of C<HTTP::Cookies> that reads (and optionally
  writes) Netscape/Mozilla cookie files.
  
  See the documentation for L<HTTP::Cookies>.
  
  =head1 CAVEATS
  
  Please note that the Netscape/Mozilla cookie file format can't store
  all the information available in the Set-Cookie2 headers, so you will
  probably lose some information if you save in this format.
  
  At time of writing, this module seems to work fine with Mozilla      
  Phoenix/Firebird.
  
  =head1 SEE ALSO
  
  L<HTTP::Cookies::Microsoft>
  
  =head1 COPYRIGHT
  
  Copyright 2002-2003 Gisle Aas
  
  This library is free software; you can redistribute it and/or
  modify it under the same terms as Perl itself.
  
  =cut
HTTP_COOKIES_NETSCAPE

$fatpacked{"HTTP/Date.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'HTTP_DATE';
  package HTTP::Date;
  
  $VERSION = "6.02";
  
  require Exporter;
  @ISA = qw(Exporter);
  @EXPORT = qw(time2str str2time);
  @EXPORT_OK = qw(parse_date time2iso time2isoz);
  
  use strict;
  require Time::Local;
  
  use vars qw(@DoW @MoY %MoY);
  @DoW = qw(Sun Mon Tue Wed Thu Fri Sat);
  @MoY = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
  @MoY{@MoY} = (1..12);
  
  my %GMT_ZONE = (GMT => 1, UTC => 1, UT => 1, Z => 1);
  
  
  sub time2str (;$)
  {
      my $time = shift;
      $time = time unless defined $time;
      my ($sec, $min, $hour, $mday, $mon, $year, $wday) = gmtime($time);
      sprintf("%s, %02d %s %04d %02d:%02d:%02d GMT",
  	    $DoW[$wday],
  	    $mday, $MoY[$mon], $year+1900,
  	    $hour, $min, $sec);
  }
  
  
  sub str2time ($;$)
  {
      my $str = shift;
      return undef unless defined $str;
  
      # fast exit for strictly conforming string
      if ($str =~ /^[SMTWF][a-z][a-z], (\d\d) ([JFMAJSOND][a-z][a-z]) (\d\d\d\d) (\d\d):(\d\d):(\d\d) GMT$/) {
  	return eval {
  	    my $t = Time::Local::timegm($6, $5, $4, $1, $MoY{$2}-1, $3);
  	    $t < 0 ? undef : $t;
  	};
      }
  
      my @d = parse_date($str);
      return undef unless @d;
      $d[1]--;        # month
  
      my $tz = pop(@d);
      unless (defined $tz) {
  	unless (defined($tz = shift)) {
  	    return eval { my $frac = $d[-1]; $frac -= ($d[-1] = int($frac));
  			  my $t = Time::Local::timelocal(reverse @d) + $frac;
  			  $t < 0 ? undef : $t;
  		        };
  	}
      }
  
      my $offset = 0;
      if ($GMT_ZONE{uc $tz}) {
  	# offset already zero
      }
      elsif ($tz =~ /^([-+])?(\d\d?):?(\d\d)?$/) {
  	$offset = 3600 * $2;
  	$offset += 60 * $3 if $3;
  	$offset *= -1 if $1 && $1 eq '-';
      }
      else {
  	eval { require Time::Zone } || return undef;
  	$offset = Time::Zone::tz_offset($tz);
  	return undef unless defined $offset;
      }
  
      return eval { my $frac = $d[-1]; $frac -= ($d[-1] = int($frac));
  		  my $t = Time::Local::timegm(reverse @d) + $frac;
  		  $t < 0 ? undef : $t - $offset;
  		};
  }
  
  
  sub parse_date ($)
  {
      local($_) = shift;
      return unless defined;
  
      # More lax parsing below
      s/^\s+//;  # kill leading space
      s/^(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)[a-z]*,?\s*//i; # Useless weekday
  
      my($day, $mon, $yr, $hr, $min, $sec, $tz, $ampm);
  
      # Then we are able to check for most of the formats with this regexp
      (($day,$mon,$yr,$hr,$min,$sec,$tz) =
          /^
  	 (\d\d?)               # day
  	    (?:\s+|[-\/])
  	 (\w+)                 # month
  	    (?:\s+|[-\/])
  	 (\d+)                 # year
  	 (?:
  	       (?:\s+|:)       # separator before clock
  	    (\d\d?):(\d\d)     # hour:min
  	    (?::(\d\d))?       # optional seconds
  	 )?                    # optional clock
  	    \s*
  	 ([-+]?\d{2,4}|(?![APap][Mm]\b)[A-Za-z]+)? # timezone
  	    \s*
  	 (?:\(\w+\)|\w{3,})?   # ASCII representation of timezone.
  	    \s*$
  	/x)
  
      ||
  
      # Try the ctime and asctime format
      (($mon, $day, $hr, $min, $sec, $tz, $yr) =
  	/^
  	 (\w{1,3})             # month
  	    \s+
  	 (\d\d?)               # day
  	    \s+
  	 (\d\d?):(\d\d)        # hour:min
  	 (?::(\d\d))?          # optional seconds
  	    \s+
  	 (?:([A-Za-z]+)\s+)?   # optional timezone
  	 (\d+)                 # year
  	    \s*$               # allow trailing whitespace
  	/x)
  
      ||
  
      # Then the Unix 'ls -l' date format
      (($mon, $day, $yr, $hr, $min, $sec) =
  	/^
  	 (\w{3})               # month
  	    \s+
  	 (\d\d?)               # day
  	    \s+
  	 (?:
  	    (\d\d\d\d) |       # year
  	    (\d{1,2}):(\d{2})  # hour:min
              (?::(\d\d))?       # optional seconds
  	 )
  	 \s*$
         /x)
  
      ||
  
      # ISO 8601 format '1996-02-29 12:00:00 -0100' and variants
      (($yr, $mon, $day, $hr, $min, $sec, $tz) =
  	/^
  	  (\d{4})              # year
  	     [-\/]?
  	  (\d\d?)              # numerical month
  	     [-\/]?
  	  (\d\d?)              # day
  	 (?:
  	       (?:\s+|[-:Tt])  # separator before clock
  	    (\d\d?):?(\d\d)    # hour:min
  	    (?::?(\d\d(?:\.\d*)?))?  # optional seconds (and fractional)
  	 )?                    # optional clock
  	    \s*
  	 ([-+]?\d\d?:?(:?\d\d)?
  	  |Z|z)?               # timezone  (Z is "zero meridian", i.e. GMT)
  	    \s*$
  	/x)
  
      ||
  
      # Windows 'dir' 11-12-96  03:52PM
      (($mon, $day, $yr, $hr, $min, $ampm) =
          /^
            (\d{2})                # numerical month
               -
            (\d{2})                # day
               -
            (\d{2})                # year
               \s+
            (\d\d?):(\d\d)([APap][Mm])  # hour:min AM or PM
               \s*$
          /x)
  
      ||
      return;  # unrecognized format
  
      # Translate month name to number
      $mon = $MoY{$mon} ||
             $MoY{"\u\L$mon"} ||
  	   ($mon =~ /^\d\d?$/ && $mon >= 1 && $mon <= 12 && int($mon)) ||
             return;
  
      # If the year is missing, we assume first date before the current,
      # because of the formats we support such dates are mostly present
      # on "ls -l" listings.
      unless (defined $yr) {
  	my $cur_mon;
  	($cur_mon, $yr) = (localtime)[4, 5];
  	$yr += 1900;
  	$cur_mon++;
  	$yr-- if $mon > $cur_mon;
      }
      elsif (length($yr) < 3) {
  	# Find "obvious" year
  	my $cur_yr = (localtime)[5] + 1900;
  	my $m = $cur_yr % 100;
  	my $tmp = $yr;
  	$yr += $cur_yr - $m;
  	$m -= $tmp;
  	$yr += ($m > 0) ? 100 : -100
  	    if abs($m) > 50;
      }
  
      # Make sure clock elements are defined
      $hr  = 0 unless defined($hr);
      $min = 0 unless defined($min);
      $sec = 0 unless defined($sec);
  
      # Compensate for AM/PM
      if ($ampm) {
  	$ampm = uc $ampm;
  	$hr = 0 if $hr == 12 && $ampm eq 'AM';
  	$hr += 12 if $ampm eq 'PM' && $hr != 12;
      }
  
      return($yr, $mon, $day, $hr, $min, $sec, $tz)
  	if wantarray;
  
      if (defined $tz) {
  	$tz = "Z" if $tz =~ /^(GMT|UTC?|[-+]?0+)$/;
      }
      else {
  	$tz = "";
      }
      return sprintf("%04d-%02d-%02d %02d:%02d:%02d%s",
  		   $yr, $mon, $day, $hr, $min, $sec, $tz);
  }
  
  
  sub time2iso (;$)
  {
      my $time = shift;
      $time = time unless defined $time;
      my($sec,$min,$hour,$mday,$mon,$year) = localtime($time);
      sprintf("%04d-%02d-%02d %02d:%02d:%02d",
  	    $year+1900, $mon+1, $mday, $hour, $min, $sec);
  }
  
  
  sub time2isoz (;$)
  {
      my $time = shift;
      $time = time unless defined $time;
      my($sec,$min,$hour,$mday,$mon,$year) = gmtime($time);
      sprintf("%04d-%02d-%02d %02d:%02d:%02dZ",
              $year+1900, $mon+1, $mday, $hour, $min, $sec);
  }
  
  1;
  
  
  __END__
  
  =head1 NAME
  
  HTTP::Date - date conversion routines
  
  =head1 SYNOPSIS
  
   use HTTP::Date;
  
   $string = time2str($time);    # Format as GMT ASCII time
   $time = str2time($string);    # convert ASCII date to machine time
  
  =head1 DESCRIPTION
  
  This module provides functions that deal the date formats used by the
  HTTP protocol (and then some more).  Only the first two functions,
  time2str() and str2time(), are exported by default.
  
  =over 4
  
  =item time2str( [$time] )
  
  The time2str() function converts a machine time (seconds since epoch)
  to a string.  If the function is called without an argument or with an
  undefined argument, it will use the current time.
  
  The string returned is in the format preferred for the HTTP protocol.
  This is a fixed length subset of the format defined by RFC 1123,
  represented in Universal Time (GMT).  An example of a time stamp
  in this format is:
  
     Sun, 06 Nov 1994 08:49:37 GMT
  
  =item str2time( $str [, $zone] )
  
  The str2time() function converts a string to machine time.  It returns
  C<undef> if the format of $str is unrecognized, otherwise whatever the
  C<Time::Local> functions can make out of the parsed time.  Dates
  before the system's epoch may not work on all operating systems.  The
  time formats recognized are the same as for parse_date().
  
  The function also takes an optional second argument that specifies the
  default time zone to use when converting the date.  This parameter is
  ignored if the zone is found in the date string itself.  If this
  parameter is missing, and the date string format does not contain any
  zone specification, then the local time zone is assumed.
  
  If the zone is not "C<GMT>" or numerical (like "C<-0800>" or
  "C<+0100>"), then the C<Time::Zone> module must be installed in order
  to get the date recognized.
  
  =item parse_date( $str )
  
  This function will try to parse a date string, and then return it as a
  list of numerical values followed by a (possible undefined) time zone
  specifier; ($year, $month, $day, $hour, $min, $sec, $tz).  The $year
  will be the full 4-digit year, and $month numbers start with 1 (for January).
  
  In scalar context the numbers are interpolated in a string of the
  "YYYY-MM-DD hh:mm:ss TZ"-format and returned.
  
  If the date is unrecognized, then the empty list is returned (C<undef> in
  scalar context).
  
  The function is able to parse the following formats:
  
   "Wed, 09 Feb 1994 22:23:32 GMT"       -- HTTP format
   "Thu Feb  3 17:03:55 GMT 1994"        -- ctime(3) format
   "Thu Feb  3 00:00:00 1994",           -- ANSI C asctime() format
   "Tuesday, 08-Feb-94 14:15:29 GMT"     -- old rfc850 HTTP format
   "Tuesday, 08-Feb-1994 14:15:29 GMT"   -- broken rfc850 HTTP format
  
   "03/Feb/1994:17:03:55 -0700"   -- common logfile format
   "09 Feb 1994 22:23:32 GMT"     -- HTTP format (no weekday)
   "08-Feb-94 14:15:29 GMT"       -- rfc850 format (no weekday)
   "08-Feb-1994 14:15:29 GMT"     -- broken rfc850 format (no weekday)
  
   "1994-02-03 14:15:29 -0100"    -- ISO 8601 format
   "1994-02-03 14:15:29"          -- zone is optional
   "1994-02-03"                   -- only date
   "1994-02-03T14:15:29"          -- Use T as separator
   "19940203T141529Z"             -- ISO 8601 compact format
   "19940203"                     -- only date
  
   "08-Feb-94"         -- old rfc850 HTTP format    (no weekday, no time)
   "08-Feb-1994"       -- broken rfc850 HTTP format (no weekday, no time)
   "09 Feb 1994"       -- proposed new HTTP format  (no weekday, no time)
   "03/Feb/1994"       -- common logfile format     (no time, no offset)
  
   "Feb  3  1994"      -- Unix 'ls -l' format
   "Feb  3 17:03"      -- Unix 'ls -l' format
  
   "11-15-96  03:52PM" -- Windows 'dir' format
  
  The parser ignores leading and trailing whitespace.  It also allow the
  seconds to be missing and the month to be numerical in most formats.
  
  If the year is missing, then we assume that the date is the first
  matching date I<before> current month.  If the year is given with only
  2 digits, then parse_date() will select the century that makes the
  year closest to the current date.
  
  =item time2iso( [$time] )
  
  Same as time2str(), but returns a "YYYY-MM-DD hh:mm:ss"-formatted
  string representing time in the local time zone.
  
  =item time2isoz( [$time] )
  
  Same as time2str(), but returns a "YYYY-MM-DD hh:mm:ssZ"-formatted
  string representing Universal Time.
  
  
  =back
  
  =head1 SEE ALSO
  
  L<perlfunc/time>, L<Time::Zone>
  
  =head1 COPYRIGHT
  
  Copyright 1995-1999, Gisle Aas
  
  This library is free software; you can redistribute it and/or
  modify it under the same terms as Perl itself.
  
  =cut
HTTP_DATE

$fatpacked{"HTTP/Headers.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'HTTP_HEADERS';
  package HTTP::Headers;
  
  use strict;
  use Carp ();
  
  use vars qw($VERSION $TRANSLATE_UNDERSCORE);
  $VERSION = "6.05";
  
  # The $TRANSLATE_UNDERSCORE variable controls whether '_' can be used
  # as a replacement for '-' in header field names.
  $TRANSLATE_UNDERSCORE = 1 unless defined $TRANSLATE_UNDERSCORE;
  
  # "Good Practice" order of HTTP message headers:
  #    - General-Headers
  #    - Request-Headers
  #    - Response-Headers
  #    - Entity-Headers
  
  my @general_headers = qw(
      Cache-Control Connection Date Pragma Trailer Transfer-Encoding Upgrade
      Via Warning
  );
  
  my @request_headers = qw(
      Accept Accept-Charset Accept-Encoding Accept-Language
      Authorization Expect From Host
      If-Match If-Modified-Since If-None-Match If-Range If-Unmodified-Since
      Max-Forwards Proxy-Authorization Range Referer TE User-Agent
  );
  
  my @response_headers = qw(
      Accept-Ranges Age ETag Location Proxy-Authenticate Retry-After Server
      Vary WWW-Authenticate
  );
  
  my @entity_headers = qw(
      Allow Content-Encoding Content-Language Content-Length Content-Location
      Content-MD5 Content-Range Content-Type Expires Last-Modified
  );
  
  my %entity_header = map { lc($_) => 1 } @entity_headers;
  
  my @header_order = (
      @general_headers,
      @request_headers,
      @response_headers,
      @entity_headers,
  );
  
  # Make alternative representations of @header_order.  This is used
  # for sorting and case matching.
  my %header_order;
  my %standard_case;
  
  {
      my $i = 0;
      for (@header_order) {
  	my $lc = lc $_;
  	$header_order{$lc} = ++$i;
  	$standard_case{$lc} = $_;
      }
  }
  
  
  
  sub new
  {
      my($class) = shift;
      my $self = bless {}, $class;
      $self->header(@_) if @_; # set up initial headers
      $self;
  }
  
  
  sub header
  {
      my $self = shift;
      Carp::croak('Usage: $h->header($field, ...)') unless @_;
      my(@old);
      my %seen;
      while (@_) {
  	my $field = shift;
          my $op = @_ ? ($seen{lc($field)}++ ? 'PUSH' : 'SET') : 'GET';
  	@old = $self->_header($field, shift, $op);
      }
      return @old if wantarray;
      return $old[0] if @old <= 1;
      join(", ", @old);
  }
  
  sub clear
  {
      my $self = shift;
      %$self = ();
  }
  
  
  sub push_header
  {
      my $self = shift;
      return $self->_header(@_, 'PUSH_H') if @_ == 2;
      while (@_) {
  	$self->_header(splice(@_, 0, 2), 'PUSH_H');
      }
  }
  
  
  sub init_header
  {
      Carp::croak('Usage: $h->init_header($field, $val)') if @_ != 3;
      shift->_header(@_, 'INIT');
  }
  
  
  sub remove_header
  {
      my($self, @fields) = @_;
      my $field;
      my @values;
      foreach $field (@fields) {
  	$field =~ tr/_/-/ if $field !~ /^:/ && $TRANSLATE_UNDERSCORE;
  	my $v = delete $self->{lc $field};
  	push(@values, ref($v) eq 'ARRAY' ? @$v : $v) if defined $v;
      }
      return @values;
  }
  
  sub remove_content_headers
  {
      my $self = shift;
      unless (defined(wantarray)) {
  	# fast branch that does not create return object
  	delete @$self{grep $entity_header{$_} || /^content-/, keys %$self};
  	return;
      }
  
      my $c = ref($self)->new;
      for my $f (grep $entity_header{$_} || /^content-/, keys %$self) {
  	$c->{$f} = delete $self->{$f};
      }
      if (exists $self->{'::std_case'}) {
  	$c->{'::std_case'} = $self->{'::std_case'};
      }
      $c;
  }
  
  
  sub _header
  {
      my($self, $field, $val, $op) = @_;
  
      Carp::croak("Illegal field name '$field'")
          if rindex($field, ':') > 1 || !length($field);
  
      unless ($field =~ /^:/) {
  	$field =~ tr/_/-/ if $TRANSLATE_UNDERSCORE;
  	my $old = $field;
  	$field = lc $field;
  	unless($standard_case{$field} || $self->{'::std_case'}{$field}) {
  	    # generate a %std_case entry for this field
  	    $old =~ s/\b(\w)/\u$1/g;
  	    $self->{'::std_case'}{$field} = $old;
  	}
      }
  
      $op ||= defined($val) ? 'SET' : 'GET';
      if ($op eq 'PUSH_H') {
  	# Like PUSH but where we don't care about the return value
  	if (exists $self->{$field}) {
  	    my $h = $self->{$field};
  	    if (ref($h) eq 'ARRAY') {
  		push(@$h, ref($val) eq "ARRAY" ? @$val : $val);
  	    }
  	    else {
  		$self->{$field} = [$h, ref($val) eq "ARRAY" ? @$val : $val]
  	    }
  	    return;
  	}
  	$self->{$field} = $val;
  	return;
      }
  
      my $h = $self->{$field};
      my @old = ref($h) eq 'ARRAY' ? @$h : (defined($h) ? ($h) : ());
  
      unless ($op eq 'GET' || ($op eq 'INIT' && @old)) {
  	if (defined($val)) {
  	    my @new = ($op eq 'PUSH') ? @old : ();
  	    if (ref($val) ne 'ARRAY') {
  		push(@new, $val);
  	    }
  	    else {
  		push(@new, @$val);
  	    }
  	    $self->{$field} = @new > 1 ? \@new : $new[0];
  	}
  	elsif ($op ne 'PUSH') {
  	    delete $self->{$field};
  	}
      }
      @old;
  }
  
  
  sub _sorted_field_names
  {
      my $self = shift;
      return [ sort {
          ($header_order{$a} || 999) <=> ($header_order{$b} || 999) ||
           $a cmp $b
      } grep !/^::/, keys %$self ];
  }
  
  
  sub header_field_names {
      my $self = shift;
      return map $standard_case{$_} || $self->{'::std_case'}{$_} || $_, @{ $self->_sorted_field_names },
  	if wantarray;
      return grep !/^::/, keys %$self;
  }
  
  
  sub scan
  {
      my($self, $sub) = @_;
      my $key;
      for $key (@{ $self->_sorted_field_names }) {
  	my $vals = $self->{$key};
  	if (ref($vals) eq 'ARRAY') {
  	    my $val;
  	    for $val (@$vals) {
  		$sub->($standard_case{$key} || $self->{'::std_case'}{$key} || $key, $val);
  	    }
  	}
  	else {
  	    $sub->($standard_case{$key} || $self->{'::std_case'}{$key} || $key, $vals);
  	}
      }
  }
  
  
  sub as_string
  {
      my($self, $endl) = @_;
      $endl = "\n" unless defined $endl;
  
      my @result = ();
      for my $key (@{ $self->_sorted_field_names }) {
  	next if index($key, '_') == 0;
  	my $vals = $self->{$key};
  	if ( ref($vals) eq 'ARRAY' ) {
  	    for my $val (@$vals) {
  		my $field = $standard_case{$key} || $self->{'::std_case'}{$key} || $key;
  		$field =~ s/^://;
  		if ( index($val, "\n") >= 0 ) {
  		    $val = _process_newline($val, $endl);
  		}
  		push @result, $field . ': ' . $val;
  	    }
  	}
  	else {
  	    my $field = $standard_case{$key} || $self->{'::std_case'}{$key} || $key;
  	    $field =~ s/^://;
  	    if ( index($vals, "\n") >= 0 ) {
  		$vals = _process_newline($vals, $endl);
  	    }
  	    push @result, $field . ': ' . $vals;
  	}
      }
  
      join($endl, @result, '');
  }
  
  sub _process_newline {
      local $_ = shift;
      my $endl = shift;
      # must handle header values with embedded newlines with care
      s/\s+$//;        # trailing newlines and space must go
      s/\n(\x0d?\n)+/\n/g;     # no empty lines
      s/\n([^\040\t])/\n $1/g; # initial space for continuation
      s/\n/$endl/g;    # substitute with requested line ending
      $_;
  }
  
  
  
  if (eval { require Storable; 1 }) {
      *clone = \&Storable::dclone;
  } else {
      *clone = sub {
  	my $self = shift;
  	my $clone = HTTP::Headers->new;
  	$self->scan(sub { $clone->push_header(@_);} );
  	$clone;
      };
  }
  
  
  sub _date_header
  {
      require HTTP::Date;
      my($self, $header, $time) = @_;
      my($old) = $self->_header($header);
      if (defined $time) {
  	$self->_header($header, HTTP::Date::time2str($time));
      }
      $old =~ s/;.*// if defined($old);
      HTTP::Date::str2time($old);
  }
  
  
  sub date                { shift->_date_header('Date',                @_); }
  sub expires             { shift->_date_header('Expires',             @_); }
  sub if_modified_since   { shift->_date_header('If-Modified-Since',   @_); }
  sub if_unmodified_since { shift->_date_header('If-Unmodified-Since', @_); }
  sub last_modified       { shift->_date_header('Last-Modified',       @_); }
  
  # This is used as a private LWP extension.  The Client-Date header is
  # added as a timestamp to a response when it has been received.
  sub client_date         { shift->_date_header('Client-Date',         @_); }
  
  # The retry_after field is dual format (can also be a expressed as
  # number of seconds from now), so we don't provide an easy way to
  # access it until we have know how both these interfaces can be
  # addressed.  One possibility is to return a negative value for
  # relative seconds and a positive value for epoch based time values.
  #sub retry_after       { shift->_date_header('Retry-After',       @_); }
  
  sub content_type      {
      my $self = shift;
      my $ct = $self->{'content-type'};
      $self->{'content-type'} = shift if @_;
      $ct = $ct->[0] if ref($ct) eq 'ARRAY';
      return '' unless defined($ct) && length($ct);
      my @ct = split(/;\s*/, $ct, 2);
      for ($ct[0]) {
  	s/\s+//g;
  	$_ = lc($_);
      }
      wantarray ? @ct : $ct[0];
  }
  
  sub content_type_charset {
      my $self = shift;
      require HTTP::Headers::Util;
      my $h = $self->{'content-type'};
      $h = $h->[0] if ref($h);
      $h = "" unless defined $h;
      my @v = HTTP::Headers::Util::split_header_words($h);
      if (@v) {
  	my($ct, undef, %ct_param) = @{$v[0]};
  	my $charset = $ct_param{charset};
  	if ($ct) {
  	    $ct = lc($ct);
  	    $ct =~ s/\s+//;
  	}
  	if ($charset) {
  	    $charset = uc($charset);
  	    $charset =~ s/^\s+//;  $charset =~ s/\s+\z//;
  	    undef($charset) if $charset eq "";
  	}
  	return $ct, $charset if wantarray;
  	return $charset;
      }
      return undef, undef if wantarray;
      return undef;
  }
  
  sub content_is_text {
      my $self = shift;
      return $self->content_type =~ m,^text/,;
  }
  
  sub content_is_html {
      my $self = shift;
      return $self->content_type eq 'text/html' || $self->content_is_xhtml;
  }
  
  sub content_is_xhtml {
      my $ct = shift->content_type;
      return $ct eq "application/xhtml+xml" ||
             $ct eq "application/vnd.wap.xhtml+xml";
  }
  
  sub content_is_xml {
      my $ct = shift->content_type;
      return 1 if $ct eq "text/xml";
      return 1 if $ct eq "application/xml";
      return 1 if $ct =~ /\+xml$/;
      return 0;
  }
  
  sub referer           {
      my $self = shift;
      if (@_ && $_[0] =~ /#/) {
  	# Strip fragment per RFC 2616, section 14.36.
  	my $uri = shift;
  	if (ref($uri)) {
  	    $uri = $uri->clone;
  	    $uri->fragment(undef);
  	}
  	else {
  	    $uri =~ s/\#.*//;
  	}
  	unshift @_, $uri;
      }
      ($self->_header('Referer', @_))[0];
  }
  *referrer = \&referer;  # on tchrist's request
  
  sub title             { (shift->_header('Title',            @_))[0] }
  sub content_encoding  { (shift->_header('Content-Encoding', @_))[0] }
  sub content_language  { (shift->_header('Content-Language', @_))[0] }
  sub content_length    { (shift->_header('Content-Length',   @_))[0] }
  
  sub user_agent        { (shift->_header('User-Agent',       @_))[0] }
  sub server            { (shift->_header('Server',           @_))[0] }
  
  sub from              { (shift->_header('From',             @_))[0] }
  sub warning           { (shift->_header('Warning',          @_))[0] }
  
  sub www_authenticate  { (shift->_header('WWW-Authenticate', @_))[0] }
  sub authorization     { (shift->_header('Authorization',    @_))[0] }
  
  sub proxy_authenticate  { (shift->_header('Proxy-Authenticate',  @_))[0] }
  sub proxy_authorization { (shift->_header('Proxy-Authorization', @_))[0] }
  
  sub authorization_basic       { shift->_basic_auth("Authorization",       @_) }
  sub proxy_authorization_basic { shift->_basic_auth("Proxy-Authorization", @_) }
  
  sub _basic_auth {
      require MIME::Base64;
      my($self, $h, $user, $passwd) = @_;
      my($old) = $self->_header($h);
      if (defined $user) {
  	Carp::croak("Basic authorization user name can't contain ':'")
  	  if $user =~ /:/;
  	$passwd = '' unless defined $passwd;
  	$self->_header($h => 'Basic ' .
                               MIME::Base64::encode("$user:$passwd", ''));
      }
      if (defined $old && $old =~ s/^\s*Basic\s+//) {
  	my $val = MIME::Base64::decode($old);
  	return $val unless wantarray;
  	return split(/:/, $val, 2);
      }
      return;
  }
  
  
  1;
  
  __END__
  
  =head1 NAME
  
  HTTP::Headers - Class encapsulating HTTP Message headers
  
  =head1 SYNOPSIS
  
   require HTTP::Headers;
   $h = HTTP::Headers->new;
  
   $h->header('Content-Type' => 'text/plain');  # set
   $ct = $h->header('Content-Type');            # get
   $h->remove_header('Content-Type');           # delete
  
  =head1 DESCRIPTION
  
  The C<HTTP::Headers> class encapsulates HTTP-style message headers.
  The headers consist of attribute-value pairs also called fields, which
  may be repeated, and which are printed in a particular order.  The
  field names are cases insensitive.
  
  Instances of this class are usually created as member variables of the
  C<HTTP::Request> and C<HTTP::Response> classes, internal to the
  library.
  
  The following methods are available:
  
  =over 4
  
  =item $h = HTTP::Headers->new
  
  Constructs a new C<HTTP::Headers> object.  You might pass some initial
  attribute-value pairs as parameters to the constructor.  I<E.g.>:
  
   $h = HTTP::Headers->new(
         Date         => 'Thu, 03 Feb 1994 00:00:00 GMT',
         Content_Type => 'text/html; version=3.2',
         Content_Base => 'http://www.perl.org/');
  
  The constructor arguments are passed to the C<header> method which is
  described below.
  
  =item $h->clone
  
  Returns a copy of this C<HTTP::Headers> object.
  
  =item $h->header( $field )
  
  =item $h->header( $field => $value )
  
  =item $h->header( $f1 => $v1, $f2 => $v2, ... )
  
  Get or set the value of one or more header fields.  The header field
  name ($field) is not case sensitive.  To make the life easier for perl
  users who wants to avoid quoting before the => operator, you can use
  '_' as a replacement for '-' in header names.
  
  The header() method accepts multiple ($field => $value) pairs, which
  means that you can update several fields with a single invocation.
  
  The $value argument may be a plain string or a reference to an array
  of strings for a multi-valued field. If the $value is provided as
  C<undef> then the field is removed.  If the $value is not given, then
  that header field will remain unchanged.
  
  The old value (or values) of the last of the header fields is returned.
  If no such field exists C<undef> will be returned.
  
  A multi-valued field will be returned as separate values in list
  context and will be concatenated with ", " as separator in scalar
  context.  The HTTP spec (RFC 2616) promise that joining multiple
  values in this way will not change the semantic of a header field, but
  in practice there are cases like old-style Netscape cookies (see
  L<HTTP::Cookies>) where "," is used as part of the syntax of a single
  field value.
  
  Examples:
  
   $header->header(MIME_Version => '1.0',
  		 User_Agent   => 'My-Web-Client/0.01');
   $header->header(Accept => "text/html, text/plain, image/*");
   $header->header(Accept => [qw(text/html text/plain image/*)]);
   @accepts = $header->header('Accept');  # get multiple values
   $accepts = $header->header('Accept');  # get values as a single string
  
  =item $h->push_header( $field => $value )
  
  =item $h->push_header( $f1 => $v1, $f2 => $v2, ... )
  
  Add a new field value for the specified header field.  Previous values
  for the same field are retained.
  
  As for the header() method, the field name ($field) is not case
  sensitive and '_' can be used as a replacement for '-'.
  
  The $value argument may be a scalar or a reference to a list of
  scalars.
  
   $header->push_header(Accept => 'image/jpeg');
   $header->push_header(Accept => [map "image/$_", qw(gif png tiff)]);
  
  =item $h->init_header( $field => $value )
  
  Set the specified header to the given value, but only if no previous
  value for that field is set.
  
  The header field name ($field) is not case sensitive and '_'
  can be used as a replacement for '-'.
  
  The $value argument may be a scalar or a reference to a list of
  scalars.
  
  =item $h->remove_header( $field, ... )
  
  This function removes the header fields with the specified names.
  
  The header field names ($field) are not case sensitive and '_'
  can be used as a replacement for '-'.
  
  The return value is the values of the fields removed.  In scalar
  context the number of fields removed is returned.
  
  Note that if you pass in multiple field names then it is generally not
  possible to tell which of the returned values belonged to which field.
  
  =item $h->remove_content_headers
  
  This will remove all the header fields used to describe the content of
  a message.  All header field names prefixed with C<Content-> fall
  into this category, as well as C<Allow>, C<Expires> and
  C<Last-Modified>.  RFC 2616 denotes these fields as I<Entity Header
  Fields>.
  
  The return value is a new C<HTTP::Headers> object that contains the
  removed headers only.
  
  =item $h->clear
  
  This will remove all header fields.
  
  =item $h->header_field_names
  
  Returns the list of distinct names for the fields present in the
  header.  The field names have case as suggested by HTTP spec, and the
  names are returned in the recommended "Good Practice" order.
  
  In scalar context return the number of distinct field names.
  
  =item $h->scan( \&process_header_field )
  
  Apply a subroutine to each header field in turn.  The callback routine
  is called with two parameters; the name of the field and a single
  value (a string).  If a header field is multi-valued, then the
  routine is called once for each value.  The field name passed to the
  callback routine has case as suggested by HTTP spec, and the headers
  will be visited in the recommended "Good Practice" order.
  
  Any return values of the callback routine are ignored.  The loop can
  be broken by raising an exception (C<die>), but the caller of scan()
  would have to trap the exception itself.
  
  =item $h->as_string
  
  =item $h->as_string( $eol )
  
  Return the header fields as a formatted MIME header.  Since it
  internally uses the C<scan> method to build the string, the result
  will use case as suggested by HTTP spec, and it will follow
  recommended "Good Practice" of ordering the header fields.  Long header
  values are not folded.
  
  The optional $eol parameter specifies the line ending sequence to
  use.  The default is "\n".  Embedded "\n" characters in header field
  values will be substituted with this line ending sequence.
  
  =back
  
  =head1 CONVENIENCE METHODS
  
  The most frequently used headers can also be accessed through the
  following convenience methods.  Most of these methods can both be used to read
  and to set the value of a header.  The header value is set if you pass
  an argument to the method.  The old header value is always returned.
  If the given header did not exist then C<undef> is returned.
  
  Methods that deal with dates/times always convert their value to system
  time (seconds since Jan 1, 1970) and they also expect this kind of
  value when the header value is set.
  
  =over 4
  
  =item $h->date
  
  This header represents the date and time at which the message was
  originated. I<E.g.>:
  
    $h->date(time);  # set current date
  
  =item $h->expires
  
  This header gives the date and time after which the entity should be
  considered stale.
  
  =item $h->if_modified_since
  
  =item $h->if_unmodified_since
  
  These header fields are used to make a request conditional.  If the requested
  resource has (or has not) been modified since the time specified in this field,
  then the server will return a C<304 Not Modified> response instead of
  the document itself.
  
  =item $h->last_modified
  
  This header indicates the date and time at which the resource was last
  modified. I<E.g.>:
  
    # check if document is more than 1 hour old
    if (my $last_mod = $h->last_modified) {
        if ($last_mod < time - 60*60) {
  	  ...
        }
    }
  
  =item $h->content_type
  
  The Content-Type header field indicates the media type of the message
  content. I<E.g.>:
  
    $h->content_type('text/html');
  
  The value returned will be converted to lower case, and potential
  parameters will be chopped off and returned as a separate value if in
  an array context.  If there is no such header field, then the empty
  string is returned.  This makes it safe to do the following:
  
    if ($h->content_type eq 'text/html') {
       # we enter this place even if the real header value happens to
       # be 'TEXT/HTML; version=3.0'
       ...
    }
  
  =item $h->content_type_charset
  
  Returns the upper-cased charset specified in the Content-Type header.  In list
  context return the lower-cased bare content type followed by the upper-cased
  charset.  Both values will be C<undef> if not specified in the header.
  
  =item $h->content_is_text
  
  Returns TRUE if the Content-Type header field indicate that the
  content is textual.
  
  =item $h->content_is_html
  
  Returns TRUE if the Content-Type header field indicate that the
  content is some kind of HTML (including XHTML).  This method can't be
  used to set Content-Type.
  
  =item $h->content_is_xhtml
  
  Returns TRUE if the Content-Type header field indicate that the
  content is XHTML.  This method can't be used to set Content-Type.
  
  =item $h->content_is_xml
  
  Returns TRUE if the Content-Type header field indicate that the
  content is XML.  This method can't be used to set Content-Type.
  
  =item $h->content_encoding
  
  The Content-Encoding header field is used as a modifier to the
  media type.  When present, its value indicates what additional
  encoding mechanism has been applied to the resource.
  
  =item $h->content_length
  
  A decimal number indicating the size in bytes of the message content.
  
  =item $h->content_language
  
  The natural language(s) of the intended audience for the message
  content.  The value is one or more language tags as defined by RFC
  1766.  Eg. "no" for some kind of Norwegian and "en-US" for English the
  way it is written in the US.
  
  =item $h->title
  
  The title of the document.  In libwww-perl this header will be
  initialized automatically from the E<lt>TITLE>...E<lt>/TITLE> element
  of HTML documents.  I<This header is no longer part of the HTTP
  standard.>
  
  =item $h->user_agent
  
  This header field is used in request messages and contains information
  about the user agent originating the request.  I<E.g.>:
  
    $h->user_agent('Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 6.0)');
  
  =item $h->server
  
  The server header field contains information about the software being
  used by the originating server program handling the request.
  
  =item $h->from
  
  This header should contain an Internet e-mail address for the human
  user who controls the requesting user agent.  The address should be
  machine-usable, as defined by RFC822.  E.g.:
  
    $h->from('King Kong <king@kong.com>');
  
  I<This header is no longer part of the HTTP standard.>
  
  =item $h->referer
  
  Used to specify the address (URI) of the document from which the
  requested resource address was obtained.
  
  The "Free On-line Dictionary of Computing" as this to say about the
  word I<referer>:
  
       <World-Wide Web> A misspelling of "referrer" which
       somehow made it into the {HTTP} standard.  A given {web
       page}'s referer (sic) is the {URL} of whatever web page
       contains the link that the user followed to the current
       page.  Most browsers pass this information as part of a
       request.
  
       (1998-10-19)
  
  By popular demand C<referrer> exists as an alias for this method so you
  can avoid this misspelling in your programs and still send the right
  thing on the wire.
  
  When setting the referrer, this method removes the fragment from the
  given URI if it is present, as mandated by RFC2616.  Note that
  the removal does I<not> happen automatically if using the header(),
  push_header() or init_header() methods to set the referrer.
  
  =item $h->www_authenticate
  
  This header must be included as part of a C<401 Unauthorized> response.
  The field value consist of a challenge that indicates the
  authentication scheme and parameters applicable to the requested URI.
  
  =item $h->proxy_authenticate
  
  This header must be included in a C<407 Proxy Authentication Required>
  response.
  
  =item $h->authorization
  
  =item $h->proxy_authorization
  
  A user agent that wishes to authenticate itself with a server or a
  proxy, may do so by including these headers.
  
  =item $h->authorization_basic
  
  This method is used to get or set an authorization header that use the
  "Basic Authentication Scheme".  In array context it will return two
  values; the user name and the password.  In scalar context it will
  return I<"uname:password"> as a single string value.
  
  When used to set the header value, it expects two arguments.  I<E.g.>:
  
    $h->authorization_basic($uname, $password);
  
  The method will croak if the $uname contains a colon ':'.
  
  =item $h->proxy_authorization_basic
  
  Same as authorization_basic() but will set the "Proxy-Authorization"
  header instead.
  
  =back
  
  =head1 NON-CANONICALIZED FIELD NAMES
  
  The header field name spelling is normally canonicalized including the
  '_' to '-' translation.  There are some application where this is not
  appropriate.  Prefixing field names with ':' allow you to force a
  specific spelling.  For example if you really want a header field name
  to show up as C<foo_bar> instead of "Foo-Bar", you might set it like
  this:
  
    $h->header(":foo_bar" => 1);
  
  These field names are returned with the ':' intact for
  $h->header_field_names and the $h->scan callback, but the colons do
  not show in $h->as_string.
  
  =head1 COPYRIGHT
  
  Copyright 1995-2005 Gisle Aas.
  
  This library is free software; you can redistribute it and/or
  modify it under the same terms as Perl itself.
  
HTTP_HEADERS

$fatpacked{"HTTP/Headers/Auth.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'HTTP_HEADERS_AUTH';
  package HTTP::Headers::Auth;
  
  use strict;
  use vars qw($VERSION);
  $VERSION = "6.00";
  
  use HTTP::Headers;
  
  package HTTP::Headers;
  
  BEGIN {
      # we provide a new (and better) implementations below
      undef(&www_authenticate);
      undef(&proxy_authenticate);
  }
  
  require HTTP::Headers::Util;
  
  sub _parse_authenticate
  {
      my @ret;
      for (HTTP::Headers::Util::split_header_words(@_)) {
  	if (!defined($_->[1])) {
  	    # this is a new auth scheme
  	    push(@ret, shift(@$_) => {});
  	    shift @$_;
  	}
  	if (@ret) {
  	    # this a new parameter pair for the last auth scheme
  	    while (@$_) {
  		my $k = shift @$_;
  		my $v = shift @$_;
  	        $ret[-1]{$k} = $v;
  	    }
  	}
  	else {
  	    # something wrong, parameter pair without any scheme seen
  	    # IGNORE
  	}
      }
      @ret;
  }
  
  sub _authenticate
  {
      my $self = shift;
      my $header = shift;
      my @old = $self->_header($header);
      if (@_) {
  	$self->remove_header($header);
  	my @new = @_;
  	while (@new) {
  	    my $a_scheme = shift(@new);
  	    if ($a_scheme =~ /\s/) {
  		# assume complete valid value, pass it through
  		$self->push_header($header, $a_scheme);
  	    }
  	    else {
  		my @param;
  		if (@new) {
  		    my $p = $new[0];
  		    if (ref($p) eq "ARRAY") {
  			@param = @$p;
  			shift(@new);
  		    }
  		    elsif (ref($p) eq "HASH") {
  			@param = %$p;
  			shift(@new);
  		    }
  		}
  		my $val = ucfirst(lc($a_scheme));
  		if (@param) {
  		    my $sep = " ";
  		    while (@param) {
  			my $k = shift @param;
  			my $v = shift @param;
  			if ($v =~ /[^0-9a-zA-Z]/ || lc($k) eq "realm") {
  			    # must quote the value
  			    $v =~ s,([\\\"]),\\$1,g;
  			    $v = qq("$v");
  			}
  			$val .= "$sep$k=$v";
  			$sep = ", ";
  		    }
  		}
  		$self->push_header($header, $val);
  	    }
  	}
      }
      return unless defined wantarray;
      wantarray ? _parse_authenticate(@old) : join(", ", @old);
  }
  
  
  sub www_authenticate    { shift->_authenticate("WWW-Authenticate", @_)   }
  sub proxy_authenticate  { shift->_authenticate("Proxy-Authenticate", @_) }
  
  1;
HTTP_HEADERS_AUTH

$fatpacked{"HTTP/Headers/ETag.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'HTTP_HEADERS_ETAG';
  package HTTP::Headers::ETag;
  
  use strict;
  use vars qw($VERSION);
  $VERSION = "6.00";
  
  require HTTP::Date;
  
  require HTTP::Headers;
  package HTTP::Headers;
  
  sub _etags
  {
      my $self = shift;
      my $header = shift;
      my @old = _split_etag_list($self->_header($header));
      if (@_) {
  	$self->_header($header => join(", ", _split_etag_list(@_)));
      }
      wantarray ? @old : join(", ", @old);
  }
  
  sub etag          { shift->_etags("ETag", @_); }
  sub if_match      { shift->_etags("If-Match", @_); }
  sub if_none_match { shift->_etags("If-None-Match", @_); }
  
  sub if_range {
      # Either a date or an entity-tag
      my $self = shift;
      my @old = $self->_header("If-Range");
      if (@_) {
  	my $new = shift;
  	if (!defined $new) {
  	    $self->remove_header("If-Range");
  	}
  	elsif ($new =~ /^\d+$/) {
  	    $self->_date_header("If-Range", $new);
  	}
  	else {
  	    $self->_etags("If-Range", $new);
  	}
      }
      return unless defined(wantarray);
      for (@old) {
  	my $t = HTTP::Date::str2time($_);
  	$_ = $t if $t;
      }
      wantarray ? @old : join(", ", @old);
  }
  
  
  # Split a list of entity tag values.  The return value is a list
  # consisting of one element per entity tag.  Suitable for parsing
  # headers like C<If-Match>, C<If-None-Match>.  You might even want to
  # use it on C<ETag> and C<If-Range> entity tag values, because it will
  # normalize them to the common form.
  #
  #  entity-tag	  = [ weak ] opaque-tag
  #  weak		  = "W/"
  #  opaque-tag	  = quoted-string
  
  
  sub _split_etag_list
  {
      my(@val) = @_;
      my @res;
      for (@val) {
          while (length) {
              my $weak = "";
  	    $weak = "W/" if s,^\s*[wW]/,,;
              my $etag = "";
  	    if (s/^\s*(\"[^\"\\]*(?:\\.[^\"\\]*)*\")//) {
  		push(@res, "$weak$1");
              }
              elsif (s/^\s*,//) {
                  push(@res, qq(W/"")) if $weak;
              }
              elsif (s/^\s*([^,\s]+)//) {
                  $etag = $1;
  		$etag =~ s/([\"\\])/\\$1/g;
  	        push(@res, qq($weak"$etag"));
              }
              elsif (s/^\s+// || !length) {
                  push(@res, qq(W/"")) if $weak;
              }
              else {
  	 	die "This should not happen: '$_'";
              }
          }
     }
     @res;
  }
  
  1;
HTTP_HEADERS_ETAG

$fatpacked{"HTTP/Headers/Util.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'HTTP_HEADERS_UTIL';
  package HTTP::Headers::Util;
  
  use strict;
  use vars qw($VERSION @ISA @EXPORT_OK);
  
  $VERSION = "6.03";
  
  require Exporter;
  @ISA=qw(Exporter);
  
  @EXPORT_OK=qw(split_header_words _split_header_words join_header_words);
  
  
  
  sub split_header_words {
      my @res = &_split_header_words;
      for my $arr (@res) {
  	for (my $i = @$arr - 2; $i >= 0; $i -= 2) {
  	    $arr->[$i] = lc($arr->[$i]);
  	}
      }
      return @res;
  }
  
  sub _split_header_words
  {
      my(@val) = @_;
      my @res;
      for (@val) {
  	my @cur;
  	while (length) {
  	    if (s/^\s*(=*[^\s=;,]+)//) {  # 'token' or parameter 'attribute'
  		push(@cur, $1);
  		# a quoted value
  		if (s/^\s*=\s*\"([^\"\\]*(?:\\.[^\"\\]*)*)\"//) {
  		    my $val = $1;
  		    $val =~ s/\\(.)/$1/g;
  		    push(@cur, $val);
  		# some unquoted value
  		}
  		elsif (s/^\s*=\s*([^;,\s]*)//) {
  		    my $val = $1;
  		    $val =~ s/\s+$//;
  		    push(@cur, $val);
  		# no value, a lone token
  		}
  		else {
  		    push(@cur, undef);
  		}
  	    }
  	    elsif (s/^\s*,//) {
  		push(@res, [@cur]) if @cur;
  		@cur = ();
  	    }
  	    elsif (s/^\s*;// || s/^\s+//) {
  		# continue
  	    }
  	    else {
  		die "This should not happen: '$_'";
  	    }
  	}
  	push(@res, \@cur) if @cur;
      }
      @res;
  }
  
  
  sub join_header_words
  {
      @_ = ([@_]) if @_ && !ref($_[0]);
      my @res;
      for (@_) {
  	my @cur = @$_;
  	my @attr;
  	while (@cur) {
  	    my $k = shift @cur;
  	    my $v = shift @cur;
  	    if (defined $v) {
  		if ($v =~ /[\x00-\x20()<>@,;:\\\"\/\[\]?={}\x7F-\xFF]/ || !length($v)) {
  		    $v =~ s/([\"\\])/\\$1/g;  # escape " and \
  		    $k .= qq(="$v");
  		}
  		else {
  		    # token
  		    $k .= "=$v";
  		}
  	    }
  	    push(@attr, $k);
  	}
  	push(@res, join("; ", @attr)) if @attr;
      }
      join(", ", @res);
  }
  
  
  1;
  
  __END__
  
  =head1 NAME
  
  HTTP::Headers::Util - Header value parsing utility functions
  
  =head1 SYNOPSIS
  
    use HTTP::Headers::Util qw(split_header_words);
    @values = split_header_words($h->header("Content-Type"));
  
  =head1 DESCRIPTION
  
  This module provides a few functions that helps parsing and
  construction of valid HTTP header values.  None of the functions are
  exported by default.
  
  The following functions are available:
  
  =over 4
  
  
  =item split_header_words( @header_values )
  
  This function will parse the header values given as argument into a
  list of anonymous arrays containing key/value pairs.  The function
  knows how to deal with ",", ";" and "=" as well as quoted values after
  "=".  A list of space separated tokens are parsed as if they were
  separated by ";".
  
  If the @header_values passed as argument contains multiple values,
  then they are treated as if they were a single value separated by
  comma ",".
  
  This means that this function is useful for parsing header fields that
  follow this syntax (BNF as from the HTTP/1.1 specification, but we relax
  the requirement for tokens).
  
    headers           = #header
    header            = (token | parameter) *( [";"] (token | parameter))
  
    token             = 1*<any CHAR except CTLs or separators>
    separators        = "(" | ")" | "<" | ">" | "@"
                      | "," | ";" | ":" | "\" | <">
                      | "/" | "[" | "]" | "?" | "="
                      | "{" | "}" | SP | HT
  
    quoted-string     = ( <"> *(qdtext | quoted-pair ) <"> )
    qdtext            = <any TEXT except <">>
    quoted-pair       = "\" CHAR
  
    parameter         = attribute "=" value
    attribute         = token
    value             = token | quoted-string
  
  Each I<header> is represented by an anonymous array of key/value
  pairs.  The keys will be all be forced to lower case.
  The value for a simple token (not part of a parameter) is C<undef>.
  Syntactically incorrect headers will not necessarily be parsed as you
  would want.
  
  This is easier to describe with some examples:
  
     split_header_words('foo="bar"; port="80,81"; DISCARD, BAR=baz');
     split_header_words('text/html; charset="iso-8859-1"');
     split_header_words('Basic realm="\\"foo\\\\bar\\""');
  
  will return
  
     [foo=>'bar', port=>'80,81', discard=> undef], [bar=>'baz' ]
     ['text/html' => undef, charset => 'iso-8859-1']
     [basic => undef, realm => "\"foo\\bar\""]
  
  If you don't want the function to convert tokens and attribute keys to
  lower case you can call it as C<_split_header_words> instead (with a
  leading underscore).
  
  =item join_header_words( @arrays )
  
  This will do the opposite of the conversion done by split_header_words().
  It takes a list of anonymous arrays as arguments (or a list of
  key/value pairs) and produces a single header value.  Attribute values
  are quoted if needed.
  
  Example:
  
     join_header_words(["text/plain" => undef, charset => "iso-8859/1"]);
     join_header_words("text/plain" => undef, charset => "iso-8859/1");
  
  will both return the string:
  
     text/plain; charset="iso-8859/1"
  
  =back
  
  =head1 COPYRIGHT
  
  Copyright 1997-1998, Gisle Aas
  
  This library is free software; you can redistribute it and/or
  modify it under the same terms as Perl itself.
  
HTTP_HEADERS_UTIL

$fatpacked{"HTTP/Message.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'HTTP_MESSAGE';
  package HTTP::Message;
  
  use strict;
  use vars qw($VERSION $AUTOLOAD);
  $VERSION = "6.06";
  
  require HTTP::Headers;
  require Carp;
  
  my $CRLF = "\015\012";   # "\r\n" is not portable
  unless ($HTTP::URI_CLASS) {
      if ($ENV{PERL_HTTP_URI_CLASS}
      &&  $ENV{PERL_HTTP_URI_CLASS} =~ /^([\w:]+)$/) {
          $HTTP::URI_CLASS = $1;
      } else {
          $HTTP::URI_CLASS = "URI";
      }
  }
  eval "require $HTTP::URI_CLASS"; die $@ if $@;
  
  *_utf8_downgrade = defined(&utf8::downgrade) ?
      sub {
          utf8::downgrade($_[0], 1) or
              Carp::croak("HTTP::Message content must be bytes")
      }
      :
      sub {
      };
  
  sub new
  {
      my($class, $header, $content) = @_;
      if (defined $header) {
  	Carp::croak("Bad header argument") unless ref $header;
          if (ref($header) eq "ARRAY") {
  	    $header = HTTP::Headers->new(@$header);
  	}
  	else {
  	    $header = $header->clone;
  	}
      }
      else {
  	$header = HTTP::Headers->new;
      }
      if (defined $content) {
          _utf8_downgrade($content);
      }
      else {
          $content = '';
      }
  
      bless {
  	'_headers' => $header,
  	'_content' => $content,
      }, $class;
  }
  
  
  sub parse
  {
      my($class, $str) = @_;
  
      my @hdr;
      while (1) {
  	if ($str =~ s/^([^\s:]+)[ \t]*: ?(.*)\n?//) {
  	    push(@hdr, $1, $2);
  	    $hdr[-1] =~ s/\r\z//;
  	}
  	elsif (@hdr && $str =~ s/^([ \t].*)\n?//) {
  	    $hdr[-1] .= "\n$1";
  	    $hdr[-1] =~ s/\r\z//;
  	}
  	else {
  	    $str =~ s/^\r?\n//;
  	    last;
  	}
      }
      local $HTTP::Headers::TRANSLATE_UNDERSCORE;
      new($class, \@hdr, $str);
  }
  
  
  sub clone
  {
      my $self  = shift;
      my $clone = HTTP::Message->new($self->headers,
  				   $self->content);
      $clone->protocol($self->protocol);
      $clone;
  }
  
  
  sub clear {
      my $self = shift;
      $self->{_headers}->clear;
      $self->content("");
      delete $self->{_parts};
      return;
  }
  
  
  sub protocol {
      shift->_elem('_protocol',  @_);
  }
  
  sub headers {
      my $self = shift;
  
      # recalculation of _content might change headers, so we
      # need to force it now
      $self->_content unless exists $self->{_content};
  
      $self->{_headers};
  }
  
  sub headers_as_string {
      shift->headers->as_string(@_);
  }
  
  
  sub content  {
  
      my $self = $_[0];
      if (defined(wantarray)) {
  	$self->_content unless exists $self->{_content};
  	my $old = $self->{_content};
  	$old = $$old if ref($old) eq "SCALAR";
  	&_set_content if @_ > 1;
  	return $old;
      }
  
      if (@_ > 1) {
  	&_set_content;
      }
      else {
  	Carp::carp("Useless content call in void context") if $^W;
      }
  }
  
  
  sub _set_content {
      my $self = $_[0];
      _utf8_downgrade($_[1]);
      if (!ref($_[1]) && ref($self->{_content}) eq "SCALAR") {
  	${$self->{_content}} = $_[1];
      }
      else {
  	die "Can't set content to be a scalar reference" if ref($_[1]) eq "SCALAR";
  	$self->{_content} = $_[1];
  	delete $self->{_content_ref};
      }
      delete $self->{_parts} unless $_[2];
  }
  
  
  sub add_content
  {
      my $self = shift;
      $self->_content unless exists $self->{_content};
      my $chunkref = \$_[0];
      $chunkref = $$chunkref if ref($$chunkref);  # legacy
  
      _utf8_downgrade($$chunkref);
  
      my $ref = ref($self->{_content});
      if (!$ref) {
  	$self->{_content} .= $$chunkref;
      }
      elsif ($ref eq "SCALAR") {
  	${$self->{_content}} .= $$chunkref;
      }
      else {
  	Carp::croak("Can't append to $ref content");
      }
      delete $self->{_parts};
  }
  
  sub add_content_utf8 {
      my($self, $buf)  = @_;
      utf8::upgrade($buf);
      utf8::encode($buf);
      $self->add_content($buf);
  }
  
  sub content_ref
  {
      my $self = shift;
      $self->_content unless exists $self->{_content};
      delete $self->{_parts};
      my $old = \$self->{_content};
      my $old_cref = $self->{_content_ref};
      if (@_) {
  	my $new = shift;
  	Carp::croak("Setting content_ref to a non-ref") unless ref($new);
  	delete $self->{_content};  # avoid modifying $$old
  	$self->{_content} = $new;
  	$self->{_content_ref}++;
      }
      $old = $$old if $old_cref;
      return $old;
  }
  
  
  sub content_charset
  {
      my $self = shift;
      if (my $charset = $self->content_type_charset) {
  	return $charset;
      }
  
      # time to start guessing
      my $cref = $self->decoded_content(ref => 1, charset => "none");
  
      # Unicode BOM
      for ($$cref) {
  	return "UTF-8"     if /^\xEF\xBB\xBF/;
  	return "UTF-32LE" if /^\xFF\xFE\x00\x00/;
  	return "UTF-32BE" if /^\x00\x00\xFE\xFF/;
  	return "UTF-16LE" if /^\xFF\xFE/;
  	return "UTF-16BE" if /^\xFE\xFF/;
      }
  
      if ($self->content_is_xml) {
  	# http://www.w3.org/TR/2006/REC-xml-20060816/#sec-guessing
  	# XML entity not accompanied by external encoding information and not
  	# in UTF-8 or UTF-16 encoding must begin with an XML encoding declaration,
  	# in which the first characters must be '<?xml'
  	for ($$cref) {
  	    return "UTF-32BE" if /^\x00\x00\x00</;
  	    return "UTF-32LE" if /^<\x00\x00\x00/;
  	    return "UTF-16BE" if /^(?:\x00\s)*\x00</;
  	    return "UTF-16LE" if /^(?:\s\x00)*<\x00/;
  	    if (/^\s*(<\?xml[^\x00]*?\?>)/) {
  		if ($1 =~ /\sencoding\s*=\s*(["'])(.*?)\1/) {
  		    my $enc = $2;
  		    $enc =~ s/^\s+//; $enc =~ s/\s+\z//;
  		    return $enc if $enc;
  		}
  	    }
  	}
  	return "UTF-8";
      }
      elsif ($self->content_is_html) {
  	# look for <META charset="..."> or <META content="...">
  	# http://dev.w3.org/html5/spec/Overview.html#determining-the-character-encoding
  	require IO::HTML;
  	# Use relaxed search to match previous versions of HTTP::Message:
  	my $encoding = IO::HTML::find_charset_in($$cref, { encoding    => 1,
  	                                                   need_pragma => 0 });
  	return $encoding->mime_name if $encoding;
      }
      elsif ($self->content_type eq "application/json") {
  	for ($$cref) {
  	    # RFC 4627, ch 3
  	    return "UTF-32BE" if /^\x00\x00\x00./s;
  	    return "UTF-32LE" if /^.\x00\x00\x00/s;
  	    return "UTF-16BE" if /^\x00.\x00./s;
  	    return "UTF-16LE" if /^.\x00.\x00/s;
  	    return "UTF-8";
  	}
      }
      if ($self->content_type =~ /^text\//) {
  	for ($$cref) {
  	    if (length) {
  		return "US-ASCII" unless /[\x80-\xFF]/;
  		require Encode;
  		eval {
  		    Encode::decode_utf8($_, Encode::FB_CROAK() | Encode::LEAVE_SRC());
  		};
  		return "UTF-8" unless $@;
  		return "ISO-8859-1";
  	    }
  	}
      }
  
      return undef;
  }
  
  
  sub decoded_content
  {
      my($self, %opt) = @_;
      my $content_ref;
      my $content_ref_iscopy;
  
      eval {
  	$content_ref = $self->content_ref;
  	die "Can't decode ref content" if ref($content_ref) ne "SCALAR";
  
  	if (my $h = $self->header("Content-Encoding")) {
  	    $h =~ s/^\s+//;
  	    $h =~ s/\s+$//;
  	    for my $ce (reverse split(/\s*,\s*/, lc($h))) {
  		next unless $ce;
  		next if $ce eq "identity";
  		if ($ce eq "gzip" || $ce eq "x-gzip") {
  		    require IO::Uncompress::Gunzip;
  		    my $output;
  		    IO::Uncompress::Gunzip::gunzip($content_ref, \$output, Transparent => 0)
  			or die "Can't gunzip content: $IO::Uncompress::Gunzip::GunzipError";
  		    $content_ref = \$output;
  		    $content_ref_iscopy++;
  		}
  		elsif ($ce eq "x-bzip2" or $ce eq "bzip2") {
  		    require IO::Uncompress::Bunzip2;
  		    my $output;
  		    IO::Uncompress::Bunzip2::bunzip2($content_ref, \$output, Transparent => 0)
  			or die "Can't bunzip content: $IO::Uncompress::Bunzip2::Bunzip2Error";
  		    $content_ref = \$output;
  		    $content_ref_iscopy++;
  		}
  		elsif ($ce eq "deflate") {
  		    require IO::Uncompress::Inflate;
  		    my $output;
  		    my $status = IO::Uncompress::Inflate::inflate($content_ref, \$output, Transparent => 0);
  		    my $error = $IO::Uncompress::Inflate::InflateError;
  		    unless ($status) {
  			# "Content-Encoding: deflate" is supposed to mean the
  			# "zlib" format of RFC 1950, but Microsoft got that
  			# wrong, so some servers sends the raw compressed
  			# "deflate" data.  This tries to inflate this format.
  			$output = undef;
  			require IO::Uncompress::RawInflate;
  			unless (IO::Uncompress::RawInflate::rawinflate($content_ref, \$output)) {
  			    $self->push_header("Client-Warning" =>
  				"Could not raw inflate content: $IO::Uncompress::RawInflate::RawInflateError");
  			    $output = undef;
  			}
  		    }
  		    die "Can't inflate content: $error" unless defined $output;
  		    $content_ref = \$output;
  		    $content_ref_iscopy++;
  		}
  		elsif ($ce eq "compress" || $ce eq "x-compress") {
  		    die "Can't uncompress content";
  		}
  		elsif ($ce eq "base64") {  # not really C-T-E, but should be harmless
  		    require MIME::Base64;
  		    $content_ref = \MIME::Base64::decode($$content_ref);
  		    $content_ref_iscopy++;
  		}
  		elsif ($ce eq "quoted-printable") { # not really C-T-E, but should be harmless
  		    require MIME::QuotedPrint;
  		    $content_ref = \MIME::QuotedPrint::decode($$content_ref);
  		    $content_ref_iscopy++;
  		}
  		else {
  		    die "Don't know how to decode Content-Encoding '$ce'";
  		}
  	    }
  	}
  
  	if ($self->content_is_text || (my $is_xml = $self->content_is_xml)) {
  	    my $charset = lc(
  	        $opt{charset} ||
  		$self->content_type_charset ||
  		$opt{default_charset} ||
  		$self->content_charset ||
  		"ISO-8859-1"
  	    );
  	    if ($charset eq "none") {
  		# leave it asis
  	    }
  	    elsif ($charset eq "us-ascii" || $charset eq "iso-8859-1") {
  		if ($$content_ref =~ /[^\x00-\x7F]/ && defined &utf8::upgrade) {
  		    unless ($content_ref_iscopy) {
  			my $copy = $$content_ref;
  			$content_ref = \$copy;
  			$content_ref_iscopy++;
  		    }
  		    utf8::upgrade($$content_ref);
  		}
  	    }
  	    else {
  		require Encode;
  		eval {
  		    $content_ref = \Encode::decode($charset, $$content_ref,
  			 ($opt{charset_strict} ? Encode::FB_CROAK() : 0) | Encode::LEAVE_SRC());
  		};
  		if ($@) {
  		    my $retried;
  		    if ($@ =~ /^Unknown encoding/) {
  			my $alt_charset = lc($opt{alt_charset} || "");
  			if ($alt_charset && $charset ne $alt_charset) {
  			    # Retry decoding with the alternative charset
  			    $content_ref = \Encode::decode($alt_charset, $$content_ref,
  				 ($opt{charset_strict} ? Encode::FB_CROAK() : 0) | Encode::LEAVE_SRC())
  			        unless $alt_charset eq "none";
  			    $retried++;
  			}
  		    }
  		    die unless $retried;
  		}
  		die "Encode::decode() returned undef improperly" unless defined $$content_ref;
  		if ($is_xml) {
  		    # Get rid of the XML encoding declaration if present
  		    $$content_ref =~ s/^\x{FEFF}//;
  		    if ($$content_ref =~ /^(\s*<\?xml[^\x00]*?\?>)/) {
  			substr($$content_ref, 0, length($1)) =~ s/\sencoding\s*=\s*(["']).*?\1//;
  		    }
  		}
  	    }
  	}
      };
      if ($@) {
  	Carp::croak($@) if $opt{raise_error};
  	return undef;
      }
  
      return $opt{ref} ? $content_ref : $$content_ref;
  }
  
  
  sub decodable
  {
      # should match the Content-Encoding values that decoded_content can deal with
      my $self = shift;
      my @enc;
      # XXX preferably we should determine if the modules are available without loading
      # them here
      eval {
          require IO::Uncompress::Gunzip;
          push(@enc, "gzip", "x-gzip");
      };
      eval {
          require IO::Uncompress::Inflate;
          require IO::Uncompress::RawInflate;
          push(@enc, "deflate");
      };
      eval {
          require IO::Uncompress::Bunzip2;
          push(@enc, "x-bzip2");
      };
      # we don't care about announcing the 'identity', 'base64' and
      # 'quoted-printable' stuff
      return wantarray ? @enc : join(", ", @enc);
  }
  
  
  sub decode
  {
      my $self = shift;
      return 1 unless $self->header("Content-Encoding");
      if (defined(my $content = $self->decoded_content(charset => "none"))) {
  	$self->remove_header("Content-Encoding", "Content-Length", "Content-MD5");
  	$self->content($content);
  	return 1;
      }
      return 0;
  }
  
  
  sub encode
  {
      my($self, @enc) = @_;
  
      Carp::croak("Can't encode multipart/* messages") if $self->content_type =~ m,^multipart/,;
      Carp::croak("Can't encode message/* messages") if $self->content_type =~ m,^message/,;
  
      return 1 unless @enc;  # nothing to do
  
      my $content = $self->content;
      for my $encoding (@enc) {
  	if ($encoding eq "identity") {
  	    # nothing to do
  	}
  	elsif ($encoding eq "base64") {
  	    require MIME::Base64;
  	    $content = MIME::Base64::encode($content);
  	}
  	elsif ($encoding eq "gzip" || $encoding eq "x-gzip") {
  	    require IO::Compress::Gzip;
  	    my $output;
  	    IO::Compress::Gzip::gzip(\$content, \$output, Minimal => 1)
  		or die "Can't gzip content: $IO::Compress::Gzip::GzipError";
  	    $content = $output;
  	}
  	elsif ($encoding eq "deflate") {
  	    require IO::Compress::Deflate;
  	    my $output;
  	    IO::Compress::Deflate::deflate(\$content, \$output)
  		or die "Can't deflate content: $IO::Compress::Deflate::DeflateError";
  	    $content = $output;
  	}
  	elsif ($encoding eq "x-bzip2") {
  	    require IO::Compress::Bzip2;
  	    my $output;
  	    IO::Compress::Bzip2::bzip2(\$content, \$output)
  		or die "Can't bzip2 content: $IO::Compress::Bzip2::Bzip2Error";
  	    $content = $output;
  	}
  	elsif ($encoding eq "rot13") {  # for the fun of it
  	    $content =~ tr/A-Za-z/N-ZA-Mn-za-m/;
  	}
  	else {
  	    return 0;
  	}
      }
      my $h = $self->header("Content-Encoding");
      unshift(@enc, $h) if $h;
      $self->header("Content-Encoding", join(", ", @enc));
      $self->remove_header("Content-Length", "Content-MD5");
      $self->content($content);
      return 1;
  }
  
  
  sub as_string
  {
      my($self, $eol) = @_;
      $eol = "\n" unless defined $eol;
  
      # The calculation of content might update the headers
      # so we need to do that first.
      my $content = $self->content;
  
      return join("", $self->{'_headers'}->as_string($eol),
  		    $eol,
  		    $content,
  		    (@_ == 1 && length($content) &&
  		     $content !~ /\n\z/) ? "\n" : "",
  		);
  }
  
  
  sub dump
  {
      my($self, %opt) = @_;
      my $content = $self->content;
      my $chopped = 0;
      if (!ref($content)) {
  	my $maxlen = $opt{maxlength};
  	$maxlen = 512 unless defined($maxlen);
  	if ($maxlen && length($content) > $maxlen * 1.1 + 3) {
  	    $chopped = length($content) - $maxlen;
  	    $content = substr($content, 0, $maxlen) . "...";
  	}
  
  	$content =~ s/\\/\\\\/g;
  	$content =~ s/\t/\\t/g;
  	$content =~ s/\r/\\r/g;
  
  	# no need for 3 digits in escape for these
  	$content =~ s/([\0-\11\13-\037])(?!\d)/sprintf('\\%o',ord($1))/eg;
  
  	$content =~ s/([\0-\11\13-\037\177-\377])/sprintf('\\x%02X',ord($1))/eg;
  	$content =~ s/([^\12\040-\176])/sprintf('\\x{%X}',ord($1))/eg;
  
  	# remaining whitespace
  	$content =~ s/( +)\n/("\\40" x length($1)) . "\n"/eg;
  	$content =~ s/(\n+)\n/("\\n" x length($1)) . "\n"/eg;
  	$content =~ s/\n\z/\\n/;
  
  	my $no_content = $opt{no_content};
  	$no_content = "(no content)" unless defined $no_content;
  	if ($content eq $no_content) {
  	    # escape our $no_content marker
  	    $content =~ s/^(.)/sprintf('\\x%02X',ord($1))/eg;
  	}
  	elsif ($content eq "") {
  	    $content = $no_content;
  	}
      }
  
      my @dump;
      push(@dump, $opt{preheader}) if $opt{preheader};
      push(@dump, $self->{_headers}->as_string, $content);
      push(@dump, "(+ $chopped more bytes not shown)") if $chopped;
  
      my $dump = join("\n", @dump, "");
      $dump =~ s/^/$opt{prefix}/gm if $opt{prefix};
  
      print $dump unless defined wantarray;
      return $dump;
  }
  
  
  sub parts {
      my $self = shift;
      if (defined(wantarray) && (!exists $self->{_parts} || ref($self->{_content}) eq "SCALAR")) {
  	$self->_parts;
      }
      my $old = $self->{_parts};
      if (@_) {
  	my @parts = map { ref($_) eq 'ARRAY' ? @$_ : $_ } @_;
  	my $ct = $self->content_type || "";
  	if ($ct =~ m,^message/,) {
  	    Carp::croak("Only one part allowed for $ct content")
  		if @parts > 1;
  	}
  	elsif ($ct !~ m,^multipart/,) {
  	    $self->remove_content_headers;
  	    $self->content_type("multipart/mixed");
  	}
  	$self->{_parts} = \@parts;
  	_stale_content($self);
      }
      return @$old if wantarray;
      return $old->[0];
  }
  
  sub add_part {
      my $self = shift;
      if (($self->content_type || "") !~ m,^multipart/,) {
  	my $p = HTTP::Message->new($self->remove_content_headers,
  				   $self->content(""));
  	$self->content_type("multipart/mixed");
  	$self->{_parts} = [];
          if ($p->headers->header_field_names || $p->content ne "") {
              push(@{$self->{_parts}}, $p);
          }
      }
      elsif (!exists $self->{_parts} || ref($self->{_content}) eq "SCALAR") {
  	$self->_parts;
      }
  
      push(@{$self->{_parts}}, @_);
      _stale_content($self);
      return;
  }
  
  sub _stale_content {
      my $self = shift;
      if (ref($self->{_content}) eq "SCALAR") {
  	# must recalculate now
  	$self->_content;
      }
      else {
  	# just invalidate cache
  	delete $self->{_content};
  	delete $self->{_content_ref};
      }
  }
  
  
  # delegate all other method calls the the headers object.
  sub AUTOLOAD
  {
      my $method = substr($AUTOLOAD, rindex($AUTOLOAD, '::')+2);
  
      # We create the function here so that it will not need to be
      # autoloaded the next time.
      no strict 'refs';
      *$method = sub { local $Carp::Internal{+__PACKAGE__} = 1; shift->headers->$method(@_) };
      goto &$method;
  }
  
  
  sub DESTROY {}  # avoid AUTOLOADing it
  
  
  # Private method to access members in %$self
  sub _elem
  {
      my $self = shift;
      my $elem = shift;
      my $old = $self->{$elem};
      $self->{$elem} = $_[0] if @_;
      return $old;
  }
  
  
  # Create private _parts attribute from current _content
  sub _parts {
      my $self = shift;
      my $ct = $self->content_type;
      if ($ct =~ m,^multipart/,) {
  	require HTTP::Headers::Util;
  	my @h = HTTP::Headers::Util::split_header_words($self->header("Content-Type"));
  	die "Assert" unless @h;
  	my %h = @{$h[0]};
  	if (defined(my $b = $h{boundary})) {
  	    my $str = $self->content;
  	    $str =~ s/\r?\n--\Q$b\E--.*//s;
  	    if ($str =~ s/(^|.*?\r?\n)--\Q$b\E\r?\n//s) {
  		$self->{_parts} = [map HTTP::Message->parse($_),
  				   split(/\r?\n--\Q$b\E\r?\n/, $str)]
  	    }
  	}
      }
      elsif ($ct eq "message/http") {
  	require HTTP::Request;
  	require HTTP::Response;
  	my $content = $self->content;
  	my $class = ($content =~ m,^(HTTP/.*)\n,) ?
  	    "HTTP::Response" : "HTTP::Request";
  	$self->{_parts} = [$class->parse($content)];
      }
      elsif ($ct =~ m,^message/,) {
  	$self->{_parts} = [ HTTP::Message->parse($self->content) ];
      }
  
      $self->{_parts} ||= [];
  }
  
  
  # Create private _content attribute from current _parts
  sub _content {
      my $self = shift;
      my $ct = $self->{_headers}->header("Content-Type") || "multipart/mixed";
      if ($ct =~ m,^\s*message/,i) {
  	_set_content($self, $self->{_parts}[0]->as_string($CRLF), 1);
  	return;
      }
  
      require HTTP::Headers::Util;
      my @v = HTTP::Headers::Util::split_header_words($ct);
      Carp::carp("Multiple Content-Type headers") if @v > 1;
      @v = @{$v[0]};
  
      my $boundary;
      my $boundary_index;
      for (my @tmp = @v; @tmp;) {
  	my($k, $v) = splice(@tmp, 0, 2);
  	if ($k eq "boundary") {
  	    $boundary = $v;
  	    $boundary_index = @v - @tmp - 1;
  	    last;
  	}
      }
  
      my @parts = map $_->as_string($CRLF), @{$self->{_parts}};
  
      my $bno = 0;
      $boundary = _boundary() unless defined $boundary;
   CHECK_BOUNDARY:
      {
  	for (@parts) {
  	    if (index($_, $boundary) >= 0) {
  		# must have a better boundary
  		$boundary = _boundary(++$bno);
  		redo CHECK_BOUNDARY;
  	    }
  	}
      }
  
      if ($boundary_index) {
  	$v[$boundary_index] = $boundary;
      }
      else {
  	push(@v, boundary => $boundary);
      }
  
      $ct = HTTP::Headers::Util::join_header_words(@v);
      $self->{_headers}->header("Content-Type", $ct);
  
      _set_content($self, "--$boundary$CRLF" .
  	                join("$CRLF--$boundary$CRLF", @parts) .
  			"$CRLF--$boundary--$CRLF",
                          1);
  }
  
  
  sub _boundary
  {
      my $size = shift || return "xYzZY";
      require MIME::Base64;
      my $b = MIME::Base64::encode(join("", map chr(rand(256)), 1..$size*3), "");
      $b =~ s/[\W]/X/g;  # ensure alnum only
      $b;
  }
  
  
  1;
  
  
  __END__
  
  =head1 NAME
  
  HTTP::Message - HTTP style message (base class)
  
  =head1 SYNOPSIS
  
   use base 'HTTP::Message';
  
  =head1 DESCRIPTION
  
  An C<HTTP::Message> object contains some headers and a content body.
  The following methods are available:
  
  =over 4
  
  =item $mess = HTTP::Message->new
  
  =item $mess = HTTP::Message->new( $headers )
  
  =item $mess = HTTP::Message->new( $headers, $content )
  
  This constructs a new message object.  Normally you would want
  construct C<HTTP::Request> or C<HTTP::Response> objects instead.
  
  The optional $header argument should be a reference to an
  C<HTTP::Headers> object or a plain array reference of key/value pairs.
  If an C<HTTP::Headers> object is provided then a copy of it will be
  embedded into the constructed message, i.e. it will not be owned and
  can be modified afterwards without affecting the message.
  
  The optional $content argument should be a string of bytes.
  
  =item $mess = HTTP::Message->parse( $str )
  
  This constructs a new message object by parsing the given string.
  
  =item $mess->headers
  
  Returns the embedded C<HTTP::Headers> object.
  
  =item $mess->headers_as_string
  
  =item $mess->headers_as_string( $eol )
  
  Call the as_string() method for the headers in the
  message.  This will be the same as
  
      $mess->headers->as_string
  
  but it will make your program a whole character shorter :-)
  
  =item $mess->content
  
  =item $mess->content( $bytes )
  
  The content() method sets the raw content if an argument is given.  If no
  argument is given the content is not touched.  In either case the
  original raw content is returned.
  
  Note that the content should be a string of bytes.  Strings in perl
  can contain characters outside the range of a byte.  The C<Encode>
  module can be used to turn such strings into a string of bytes.
  
  =item $mess->add_content( $bytes )
  
  The add_content() methods appends more data bytes to the end of the
  current content buffer.
  
  =item $mess->add_content_utf8( $string )
  
  The add_content_utf8() method appends the UTF-8 bytes representing the
  string to the end of the current content buffer.
  
  =item $mess->content_ref
  
  =item $mess->content_ref( \$bytes )
  
  The content_ref() method will return a reference to content buffer string.
  It can be more efficient to access the content this way if the content
  is huge, and it can even be used for direct manipulation of the content,
  for instance:
  
    ${$res->content_ref} =~ s/\bfoo\b/bar/g;
  
  This example would modify the content buffer in-place.
  
  If an argument is passed it will setup the content to reference some
  external source.  The content() and add_content() methods
  will automatically dereference scalar references passed this way.  For
  other references content() will return the reference itself and
  add_content() will refuse to do anything.
  
  =item $mess->content_charset
  
  This returns the charset used by the content in the message.  The
  charset is either found as the charset attribute of the
  C<Content-Type> header or by guessing.
  
  See L<http://www.w3.org/TR/REC-html40/charset.html#spec-char-encoding>
  for details about how charset is determined.
  
  =item $mess->decoded_content( %options )
  
  Returns the content with any C<Content-Encoding> undone and for textual content
  the raw content encoded to Perl's Unicode strings.  If the C<Content-Encoding>
  or C<charset> of the message is unknown this method will fail by returning
  C<undef>.
  
  The following options can be specified.
  
  =over
  
  =item C<charset>
  
  This override the charset parameter for text content.  The value
  C<none> can used to suppress decoding of the charset.
  
  =item C<default_charset>
  
  This override the default charset guessed by content_charset() or
  if that fails "ISO-8859-1".
  
  =item C<alt_charset>
  
  If decoding fails because the charset specified in the Content-Type header
  isn't recognized by Perl's Encode module, then try decoding using this charset
  instead of failing.  The C<alt_charset> might be specified as C<none> to simply
  return the string without any decoding of charset as alternative.
  
  =item C<charset_strict>
  
  Abort decoding if malformed characters is found in the content.  By
  default you get the substitution character ("\x{FFFD}") in place of
  malformed characters.
  
  =item C<raise_error>
  
  If TRUE then raise an exception if not able to decode content.  Reason
  might be that the specified C<Content-Encoding> or C<charset> is not
  supported.  If this option is FALSE, then decoded_content() will return
  C<undef> on errors, but will still set $@.
  
  =item C<ref>
  
  If TRUE then a reference to decoded content is returned.  This might
  be more efficient in cases where the decoded content is identical to
  the raw content as no data copying is required in this case.
  
  =back
  
  =item $mess->decodable
  
  =item HTTP::Message::decodable()
  
  This returns the encoding identifiers that decoded_content() can
  process.  In scalar context returns a comma separated string of
  identifiers.
  
  This value is suitable for initializing the C<Accept-Encoding> request
  header field.
  
  =item $mess->decode
  
  This method tries to replace the content of the message with the
  decoded version and removes the C<Content-Encoding> header.  Returns
  TRUE if successful and FALSE if not.
  
  If the message does not have a C<Content-Encoding> header this method
  does nothing and returns TRUE.
  
  Note that the content of the message is still bytes after this method
  has been called and you still need to call decoded_content() if you
  want to process its content as a string.
  
  =item $mess->encode( $encoding, ... )
  
  Apply the given encodings to the content of the message.  Returns TRUE
  if successful. The "identity" (non-)encoding is always supported; other
  currently supported encodings, subject to availability of required
  additional modules, are "gzip", "deflate", "x-bzip2" and "base64".
  
  A successful call to this function will set the C<Content-Encoding>
  header.
  
  Note that C<multipart/*> or C<message/*> messages can't be encoded and
  this method will croak if you try.
  
  =item $mess->parts
  
  =item $mess->parts( @parts )
  
  =item $mess->parts( \@parts )
  
  Messages can be composite, i.e. contain other messages.  The composite
  messages have a content type of C<multipart/*> or C<message/*>.  This
  method give access to the contained messages.
  
  The argumentless form will return a list of C<HTTP::Message> objects.
  If the content type of $msg is not C<multipart/*> or C<message/*> then
  this will return the empty list.  In scalar context only the first
  object is returned.  The returned message parts should be regarded as
  read-only (future versions of this library might make it possible
  to modify the parent by modifying the parts).
  
  If the content type of $msg is C<message/*> then there will only be
  one part returned.
  
  If the content type is C<message/http>, then the return value will be
  either an C<HTTP::Request> or an C<HTTP::Response> object.
  
  If a @parts argument is given, then the content of the message will be
  modified. The array reference form is provided so that an empty list
  can be provided.  The @parts array should contain C<HTTP::Message>
  objects.  The @parts objects are owned by $mess after this call and
  should not be modified or made part of other messages.
  
  When updating the message with this method and the old content type of
  $mess is not C<multipart/*> or C<message/*>, then the content type is
  set to C<multipart/mixed> and all other content headers are cleared.
  
  This method will croak if the content type is C<message/*> and more
  than one part is provided.
  
  =item $mess->add_part( $part )
  
  This will add a part to a message.  The $part argument should be
  another C<HTTP::Message> object.  If the previous content type of
  $mess is not C<multipart/*> then the old content (together with all
  content headers) will be made part #1 and the content type made
  C<multipart/mixed> before the new part is added.  The $part object is
  owned by $mess after this call and should not be modified or made part
  of other messages.
  
  There is no return value.
  
  =item $mess->clear
  
  Will clear the headers and set the content to the empty string.  There
  is no return value
  
  =item $mess->protocol
  
  =item $mess->protocol( $proto )
  
  Sets the HTTP protocol used for the message.  The protocol() is a string
  like C<HTTP/1.0> or C<HTTP/1.1>.
  
  =item $mess->clone
  
  Returns a copy of the message object.
  
  =item $mess->as_string
  
  =item $mess->as_string( $eol )
  
  Returns the message formatted as a single string.
  
  The optional $eol parameter specifies the line ending sequence to use.
  The default is "\n".  If no $eol is given then as_string will ensure
  that the returned string is newline terminated (even when the message
  content is not).  No extra newline is appended if an explicit $eol is
  passed.
  
  =item $mess->dump( %opt )
  
  Returns the message formatted as a string.  In void context print the string.
  
  This differs from C<< $mess->as_string >> in that it escapes the bytes
  of the content so that it's safe to print them and it limits how much
  content to print.  The escapes syntax used is the same as for Perl's
  double quoted strings.  If there is no content the string "(no
  content)" is shown in its place.
  
  Options to influence the output can be passed as key/value pairs. The
  following options are recognized:
  
  =over
  
  =item maxlength => $num
  
  How much of the content to show.  The default is 512.  Set this to 0
  for unlimited.
  
  If the content is longer then the string is chopped at the limit and
  the string "...\n(### more bytes not shown)" appended.
  
  =item no_content => $str
  
  Replaces the "(no content)" marker.
  
  =item prefix => $str
  
  A string that will be prefixed to each line of the dump.
  
  =back
  
  =back
  
  All methods unknown to C<HTTP::Message> itself are delegated to the
  C<HTTP::Headers> object that is part of every message.  This allows
  convenient access to these methods.  Refer to L<HTTP::Headers> for
  details of these methods:
  
      $mess->header( $field => $val )
      $mess->push_header( $field => $val )
      $mess->init_header( $field => $val )
      $mess->remove_header( $field )
      $mess->remove_content_headers
      $mess->header_field_names
      $mess->scan( \&doit )
  
      $mess->date
      $mess->expires
      $mess->if_modified_since
      $mess->if_unmodified_since
      $mess->last_modified
      $mess->content_type
      $mess->content_encoding
      $mess->content_length
      $mess->content_language
      $mess->title
      $mess->user_agent
      $mess->server
      $mess->from
      $mess->referer
      $mess->www_authenticate
      $mess->authorization
      $mess->proxy_authorization
      $mess->authorization_basic
      $mess->proxy_authorization_basic
  
  =head1 COPYRIGHT
  
  Copyright 1995-2004 Gisle Aas.
  
  This library is free software; you can redistribute it and/or
  modify it under the same terms as Perl itself.
  
HTTP_MESSAGE

$fatpacked{"HTTP/Request.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'HTTP_REQUEST';
  package HTTP::Request;
  
  require HTTP::Message;
  @ISA = qw(HTTP::Message);
  $VERSION = "6.00";
  
  use strict;
  
  
  
  sub new
  {
      my($class, $method, $uri, $header, $content) = @_;
      my $self = $class->SUPER::new($header, $content);
      $self->method($method);
      $self->uri($uri);
      $self;
  }
  
  
  sub parse
  {
      my($class, $str) = @_;
      my $request_line;
      if ($str =~ s/^(.*)\n//) {
  	$request_line = $1;
      }
      else {
  	$request_line = $str;
  	$str = "";
      }
  
      my $self = $class->SUPER::parse($str);
      my($method, $uri, $protocol) = split(' ', $request_line);
      $self->method($method) if defined($method);
      $self->uri($uri) if defined($uri);
      $self->protocol($protocol) if $protocol;
      $self;
  }
  
  
  sub clone
  {
      my $self = shift;
      my $clone = bless $self->SUPER::clone, ref($self);
      $clone->method($self->method);
      $clone->uri($self->uri);
      $clone;
  }
  
  
  sub method
  {
      shift->_elem('_method', @_);
  }
  
  
  sub uri
  {
      my $self = shift;
      my $old = $self->{'_uri'};
      if (@_) {
  	my $uri = shift;
  	if (!defined $uri) {
  	    # that's ok
  	}
  	elsif (ref $uri) {
  	    Carp::croak("A URI can't be a " . ref($uri) . " reference")
  		if ref($uri) eq 'HASH' or ref($uri) eq 'ARRAY';
  	    Carp::croak("Can't use a " . ref($uri) . " object as a URI")
  		unless $uri->can('scheme');
  	    $uri = $uri->clone;
  	    unless ($HTTP::URI_CLASS eq "URI") {
  		# Argh!! Hate this... old LWP legacy!
  		eval { local $SIG{__DIE__}; $uri = $uri->abs; };
  		die $@ if $@ && $@ !~ /Missing base argument/;
  	    }
  	}
  	else {
  	    $uri = $HTTP::URI_CLASS->new($uri);
  	}
  	$self->{'_uri'} = $uri;
          delete $self->{'_uri_canonical'};
      }
      $old;
  }
  
  *url = \&uri;  # legacy
  
  sub uri_canonical
  {
      my $self = shift;
      return $self->{'_uri_canonical'} ||= $self->{'_uri'}->canonical;
  }
  
  
  sub accept_decodable
  {
      my $self = shift;
      $self->header("Accept-Encoding", scalar($self->decodable));
  }
  
  sub as_string
  {
      my $self = shift;
      my($eol) = @_;
      $eol = "\n" unless defined $eol;
  
      my $req_line = $self->method || "-";
      my $uri = $self->uri;
      $uri = (defined $uri) ? $uri->as_string : "-";
      $req_line .= " $uri";
      my $proto = $self->protocol;
      $req_line .= " $proto" if $proto;
  
      return join($eol, $req_line, $self->SUPER::as_string(@_));
  }
  
  sub dump
  {
      my $self = shift;
      my @pre = ($self->method || "-", $self->uri || "-");
      if (my $prot = $self->protocol) {
  	push(@pre, $prot);
      }
  
      return $self->SUPER::dump(
          preheader => join(" ", @pre),
  	@_,
      );
  }
  
  
  1;
  
  __END__
  
  =head1 NAME
  
  HTTP::Request - HTTP style request message
  
  =head1 SYNOPSIS
  
   require HTTP::Request;
   $request = HTTP::Request->new(GET => 'http://www.example.com/');
  
  and usually used like this:
  
   $ua = LWP::UserAgent->new;
   $response = $ua->request($request);
  
  =head1 DESCRIPTION
  
  C<HTTP::Request> is a class encapsulating HTTP style requests,
  consisting of a request line, some headers, and a content body. Note
  that the LWP library uses HTTP style requests even for non-HTTP
  protocols.  Instances of this class are usually passed to the
  request() method of an C<LWP::UserAgent> object.
  
  C<HTTP::Request> is a subclass of C<HTTP::Message> and therefore
  inherits its methods.  The following additional methods are available:
  
  =over 4
  
  =item $r = HTTP::Request->new( $method, $uri )
  
  =item $r = HTTP::Request->new( $method, $uri, $header )
  
  =item $r = HTTP::Request->new( $method, $uri, $header, $content )
  
  Constructs a new C<HTTP::Request> object describing a request on the
  object $uri using method $method.  The $method argument must be a
  string.  The $uri argument can be either a string, or a reference to a
  C<URI> object.  The optional $header argument should be a reference to
  an C<HTTP::Headers> object or a plain array reference of key/value
  pairs.  The optional $content argument should be a string of bytes.
  
  =item $r = HTTP::Request->parse( $str )
  
  This constructs a new request object by parsing the given string.
  
  =item $r->method
  
  =item $r->method( $val )
  
  This is used to get/set the method attribute.  The method should be a
  short string like "GET", "HEAD", "PUT" or "POST".
  
  =item $r->uri
  
  =item $r->uri( $val )
  
  This is used to get/set the uri attribute.  The $val can be a
  reference to a URI object or a plain string.  If a string is given,
  then it should be parseable as an absolute URI.
  
  =item $r->header( $field )
  
  =item $r->header( $field => $value )
  
  This is used to get/set header values and it is inherited from
  C<HTTP::Headers> via C<HTTP::Message>.  See L<HTTP::Headers> for
  details and other similar methods that can be used to access the
  headers.
  
  =item $r->accept_decodable
  
  This will set the C<Accept-Encoding> header to the list of encodings
  that decoded_content() can decode.
  
  =item $r->content
  
  =item $r->content( $bytes )
  
  This is used to get/set the content and it is inherited from the
  C<HTTP::Message> base class.  See L<HTTP::Message> for details and
  other methods that can be used to access the content.
  
  Note that the content should be a string of bytes.  Strings in perl
  can contain characters outside the range of a byte.  The C<Encode>
  module can be used to turn such strings into a string of bytes.
  
  =item $r->as_string
  
  =item $r->as_string( $eol )
  
  Method returning a textual representation of the request.
  
  =back
  
  =head1 SEE ALSO
  
  L<HTTP::Headers>, L<HTTP::Message>, L<HTTP::Request::Common>,
  L<HTTP::Response>
  
  =head1 COPYRIGHT
  
  Copyright 1995-2004 Gisle Aas.
  
  This library is free software; you can redistribute it and/or
  modify it under the same terms as Perl itself.
  
HTTP_REQUEST

$fatpacked{"HTTP/Request/Common.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'HTTP_REQUEST_COMMON';
  package HTTP::Request::Common;
  
  use strict;
  use vars qw(@EXPORT @EXPORT_OK $VERSION $DYNAMIC_FILE_UPLOAD);
  
  $DYNAMIC_FILE_UPLOAD ||= 0;  # make it defined (don't know why)
  
  require Exporter;
  *import = \&Exporter::import;
  @EXPORT =qw(GET HEAD PUT POST);
  @EXPORT_OK = qw($DYNAMIC_FILE_UPLOAD DELETE);
  
  require HTTP::Request;
  use Carp();
  
  $VERSION = "6.04";
  
  my $CRLF = "\015\012";   # "\r\n" is not portable
  
  sub GET  { _simple_req('GET',  @_); }
  sub HEAD { _simple_req('HEAD', @_); }
  sub PUT  { _simple_req('PUT' , @_); }
  sub DELETE { _simple_req('DELETE', @_); }
  
  sub POST
  {
      my $url = shift;
      my $req = HTTP::Request->new(POST => $url);
      my $content;
      $content = shift if @_ and ref $_[0];
      my($k, $v);
      while (($k,$v) = splice(@_, 0, 2)) {
  	if (lc($k) eq 'content') {
  	    $content = $v;
  	}
  	else {
  	    $req->push_header($k, $v);
  	}
      }
      my $ct = $req->header('Content-Type');
      unless ($ct) {
  	$ct = 'application/x-www-form-urlencoded';
      }
      elsif ($ct eq 'form-data') {
  	$ct = 'multipart/form-data';
      }
  
      if (ref $content) {
  	if ($ct =~ m,^multipart/form-data\s*(;|$),i) {
  	    require HTTP::Headers::Util;
  	    my @v = HTTP::Headers::Util::split_header_words($ct);
  	    Carp::carp("Multiple Content-Type headers") if @v > 1;
  	    @v = @{$v[0]};
  
  	    my $boundary;
  	    my $boundary_index;
  	    for (my @tmp = @v; @tmp;) {
  		my($k, $v) = splice(@tmp, 0, 2);
  		if ($k eq "boundary") {
  		    $boundary = $v;
  		    $boundary_index = @v - @tmp - 1;
  		    last;
  		}
  	    }
  
  	    ($content, $boundary) = form_data($content, $boundary, $req);
  
  	    if ($boundary_index) {
  		$v[$boundary_index] = $boundary;
  	    }
  	    else {
  		push(@v, boundary => $boundary);
  	    }
  
  	    $ct = HTTP::Headers::Util::join_header_words(@v);
  	}
  	else {
  	    # We use a temporary URI object to format
  	    # the application/x-www-form-urlencoded content.
  	    require URI;
  	    my $url = URI->new('http:');
  	    $url->query_form(ref($content) eq "HASH" ? %$content : @$content);
  	    $content = $url->query;
  
  	    # HTML/4.01 says that line breaks are represented as "CR LF" pairs (i.e., `%0D%0A')
  	    $content =~ s/(?<!%0D)%0A/%0D%0A/g if defined($content);
  	}
      }
  
      $req->header('Content-Type' => $ct);  # might be redundant
      if (defined($content)) {
  	$req->header('Content-Length' =>
  		     length($content)) unless ref($content);
  	$req->content($content);
      }
      else {
          $req->header('Content-Length' => 0);
      }
      $req;
  }
  
  
  sub _simple_req
  {
      my($method, $url) = splice(@_, 0, 2);
      my $req = HTTP::Request->new($method => $url);
      my($k, $v);
      my $content;
      while (($k,$v) = splice(@_, 0, 2)) {
  	if (lc($k) eq 'content') {
  	    $req->add_content($v);
              $content++;
  	}
  	else {
  	    $req->push_header($k, $v);
  	}
      }
      if ($content && !defined($req->header("Content-Length"))) {
          $req->header("Content-Length", length(${$req->content_ref}));
      }
      $req;
  }
  
  
  sub form_data   # RFC1867
  {
      my($data, $boundary, $req) = @_;
      my @data = ref($data) eq "HASH" ? %$data : @$data;  # copy
      my $fhparts;
      my @parts;
      my($k,$v);
      while (($k,$v) = splice(@data, 0, 2)) {
  	if (!ref($v)) {
  	    $k =~ s/([\\\"])/\\$1/g;  # escape quotes and backslashes
  	    push(@parts,
  		 qq(Content-Disposition: form-data; name="$k"$CRLF$CRLF$v));
  	}
  	else {
  	    my($file, $usename, @headers) = @$v;
  	    unless (defined $usename) {
  		$usename = $file;
  		$usename =~ s,.*/,, if defined($usename);
  	    }
              $k =~ s/([\\\"])/\\$1/g;
  	    my $disp = qq(form-data; name="$k");
              if (defined($usename) and length($usename)) {
                  $usename =~ s/([\\\"])/\\$1/g;
                  $disp .= qq(; filename="$usename");
              }
  	    my $content = "";
  	    my $h = HTTP::Headers->new(@headers);
  	    if ($file) {
  		open(my $fh, "<", $file) or Carp::croak("Can't open file $file: $!");
  		binmode($fh);
  		if ($DYNAMIC_FILE_UPLOAD) {
  		    # will read file later, close it now in order to
                      # not accumulate to many open file handles
                      close($fh);
  		    $content = \$file;
  		}
  		else {
  		    local($/) = undef; # slurp files
  		    $content = <$fh>;
  		    close($fh);
  		}
  		unless ($h->header("Content-Type")) {
  		    require LWP::MediaTypes;
  		    LWP::MediaTypes::guess_media_type($file, $h);
  		}
  	    }
  	    if ($h->header("Content-Disposition")) {
  		# just to get it sorted first
  		$disp = $h->header("Content-Disposition");
  		$h->remove_header("Content-Disposition");
  	    }
  	    if ($h->header("Content")) {
  		$content = $h->header("Content");
  		$h->remove_header("Content");
  	    }
  	    my $head = join($CRLF, "Content-Disposition: $disp",
  			           $h->as_string($CRLF),
  			           "");
  	    if (ref $content) {
  		push(@parts, [$head, $$content]);
  		$fhparts++;
  	    }
  	    else {
  		push(@parts, $head . $content);
  	    }
  	}
      }
      return ("", "none") unless @parts;
  
      my $content;
      if ($fhparts) {
  	$boundary = boundary(10) # hopefully enough randomness
  	    unless $boundary;
  
  	# add the boundaries to the @parts array
  	for (1..@parts-1) {
  	    splice(@parts, $_*2-1, 0, "$CRLF--$boundary$CRLF");
  	}
  	unshift(@parts, "--$boundary$CRLF");
  	push(@parts, "$CRLF--$boundary--$CRLF");
  
  	# See if we can generate Content-Length header
  	my $length = 0;
  	for (@parts) {
  	    if (ref $_) {
  	 	my ($head, $f) = @$_;
  		my $file_size;
  		unless ( -f $f && ($file_size = -s _) ) {
  		    # The file is either a dynamic file like /dev/audio
  		    # or perhaps a file in the /proc file system where
  		    # stat may return a 0 size even though reading it
  		    # will produce data.  So we cannot make
  		    # a Content-Length header.  
  		    undef $length;
  		    last;
  		}
  	    	$length += $file_size + length $head;
  	    }
  	    else {
  		$length += length;
  	    }
          }
          $length && $req->header('Content-Length' => $length);
  
  	# set up a closure that will return content piecemeal
  	$content = sub {
  	    for (;;) {
  		unless (@parts) {
  		    defined $length && $length != 0 &&
  		    	Carp::croak "length of data sent did not match calculated Content-Length header.  Probably because uploaded file changed in size during transfer.";
  		    return;
  		}
  		my $p = shift @parts;
  		unless (ref $p) {
  		    $p .= shift @parts while @parts && !ref($parts[0]);
  		    defined $length && ($length -= length $p);
  		    return $p;
  		}
  		my($buf, $fh) = @$p;
                  unless (ref($fh)) {
                      my $file = $fh;
                      undef($fh);
                      open($fh, "<", $file) || Carp::croak("Can't open file $file: $!");
                      binmode($fh);
                  }
  		my $buflength = length $buf;
  		my $n = read($fh, $buf, 2048, $buflength);
  		if ($n) {
  		    $buflength += $n;
  		    unshift(@parts, ["", $fh]);
  		}
  		else {
  		    close($fh);
  		}
  		if ($buflength) {
  		    defined $length && ($length -= $buflength);
  		    return $buf 
  	    	}
  	    }
  	};
  
      }
      else {
  	$boundary = boundary() unless $boundary;
  
  	my $bno = 0;
        CHECK_BOUNDARY:
  	{
  	    for (@parts) {
  		if (index($_, $boundary) >= 0) {
  		    # must have a better boundary
  		    $boundary = boundary(++$bno);
  		    redo CHECK_BOUNDARY;
  		}
  	    }
  	    last;
  	}
  	$content = "--$boundary$CRLF" .
  	           join("$CRLF--$boundary$CRLF", @parts) .
  		   "$CRLF--$boundary--$CRLF";
      }
  
      wantarray ? ($content, $boundary) : $content;
  }
  
  
  sub boundary
  {
      my $size = shift || return "xYzZY";
      require MIME::Base64;
      my $b = MIME::Base64::encode(join("", map chr(rand(256)), 1..$size*3), "");
      $b =~ s/[\W]/X/g;  # ensure alnum only
      $b;
  }
  
  1;
  
  __END__
  
  =head1 NAME
  
  HTTP::Request::Common - Construct common HTTP::Request objects
  
  =head1 SYNOPSIS
  
    use HTTP::Request::Common;
    $ua = LWP::UserAgent->new;
    $ua->request(GET 'http://www.sn.no/');
    $ua->request(POST 'http://somewhere/foo', [foo => bar, bar => foo]);
  
  =head1 DESCRIPTION
  
  This module provide functions that return newly created C<HTTP::Request>
  objects.  These functions are usually more convenient to use than the
  standard C<HTTP::Request> constructor for the most common requests.  The
  following functions are provided:
  
  =over 4
  
  =item GET $url
  
  =item GET $url, Header => Value,...
  
  The GET() function returns an C<HTTP::Request> object initialized with
  the "GET" method and the specified URL.  It is roughly equivalent to the
  following call
  
    HTTP::Request->new(
       GET => $url,
       HTTP::Headers->new(Header => Value,...),
    )
  
  but is less cluttered.  What is different is that a header named
  C<Content> will initialize the content part of the request instead of
  setting a header field.  Note that GET requests should normally not
  have a content, so this hack makes more sense for the PUT() and POST()
  functions described below.
  
  The get(...) method of C<LWP::UserAgent> exists as a shortcut for
  $ua->request(GET ...).
  
  =item HEAD $url
  
  =item HEAD $url, Header => Value,...
  
  Like GET() but the method in the request is "HEAD".
  
  The head(...)  method of "LWP::UserAgent" exists as a shortcut for
  $ua->request(HEAD ...).
  
  =item PUT $url
  
  =item PUT $url, Header => Value,...
  
  =item PUT $url, Header => Value,..., Content => $content
  
  Like GET() but the method in the request is "PUT".
  
  The content of the request can be specified using the "Content"
  pseudo-header.  This steals a bit of the header field namespace as
  there is no way to directly specify a header that is actually called
  "Content".  If you really need this you must update the request
  returned in a separate statement.
  
  =item DELETE $url
  
  =item DELETE $url, Header => Value,...
  
  Like GET() but the method in the request is "DELETE".  This function
  is not exported by default.
  
  =item POST $url
  
  =item POST $url, Header => Value,...
  
  =item POST $url, $form_ref, Header => Value,...
  
  =item POST $url, Header => Value,..., Content => $form_ref
  
  =item POST $url, Header => Value,..., Content => $content
  
  This works mostly like PUT() with "POST" as the method, but this
  function also takes a second optional array or hash reference
  parameter $form_ref.  As for PUT() the content can also be specified
  directly using the "Content" pseudo-header, and you may also provide
  the $form_ref this way.
  
  The $form_ref argument can be used to pass key/value pairs for the
  form content.  By default we will initialize a request using the
  C<application/x-www-form-urlencoded> content type.  This means that
  you can emulate an HTML E<lt>form> POSTing like this:
  
    POST 'http://www.perl.org/survey.cgi',
         [ name   => 'Gisle Aas',
           email  => 'gisle@aas.no',
           gender => 'M',
           born   => '1964',
           perc   => '3%',
         ];
  
  This will create an HTTP::Request object that looks like this:
  
    POST http://www.perl.org/survey.cgi
    Content-Length: 66
    Content-Type: application/x-www-form-urlencoded
  
    name=Gisle%20Aas&email=gisle%40aas.no&gender=M&born=1964&perc=3%25
  
  Multivalued form fields can be specified by either repeating the field
  name or by passing the value as an array reference.
  
  The POST method also supports the C<multipart/form-data> content used
  for I<Form-based File Upload> as specified in RFC 1867.  You trigger
  this content format by specifying a content type of C<'form-data'> as
  one of the request headers.  If one of the values in the $form_ref is
  an array reference, then it is treated as a file part specification
  with the following interpretation:
  
    [ $file, $filename, Header => Value... ]
    [ undef, $filename, Header => Value,..., Content => $content ]
  
  The first value in the array ($file) is the name of a file to open.
  This file will be read and its content placed in the request.  The
  routine will croak if the file can't be opened.  Use an C<undef> as
  $file value if you want to specify the content directly with a
  C<Content> header.  The $filename is the filename to report in the
  request.  If this value is undefined, then the basename of the $file
  will be used.  You can specify an empty string as $filename if you
  want to suppress sending the filename when you provide a $file value.
  
  If a $file is provided by no C<Content-Type> header, then C<Content-Type>
  and C<Content-Encoding> will be filled in automatically with the values
  returned by LWP::MediaTypes::guess_media_type()
  
  Sending my F<~/.profile> to the survey used as example above can be
  achieved by this:
  
    POST 'http://www.perl.org/survey.cgi',
         Content_Type => 'form-data',
         Content      => [ name  => 'Gisle Aas',
                           email => 'gisle@aas.no',
                           gender => 'M',
                           born   => '1964',
                           init   => ["$ENV{HOME}/.profile"],
                         ]
  
  This will create an HTTP::Request object that almost looks this (the
  boundary and the content of your F<~/.profile> is likely to be
  different):
  
    POST http://www.perl.org/survey.cgi
    Content-Length: 388
    Content-Type: multipart/form-data; boundary="6G+f"
  
    --6G+f
    Content-Disposition: form-data; name="name"
  
    Gisle Aas
    --6G+f
    Content-Disposition: form-data; name="email"
  
    gisle@aas.no
    --6G+f
    Content-Disposition: form-data; name="gender"
  
    M
    --6G+f
    Content-Disposition: form-data; name="born"
  
    1964
    --6G+f
    Content-Disposition: form-data; name="init"; filename=".profile"
    Content-Type: text/plain
  
    PATH=/local/perl/bin:$PATH
    export PATH
  
    --6G+f--
  
  If you set the $DYNAMIC_FILE_UPLOAD variable (exportable) to some TRUE
  value, then you get back a request object with a subroutine closure as
  the content attribute.  This subroutine will read the content of any
  files on demand and return it in suitable chunks.  This allow you to
  upload arbitrary big files without using lots of memory.  You can even
  upload infinite files like F</dev/audio> if you wish; however, if
  the file is not a plain file, there will be no Content-Length header
  defined for the request.  Not all servers (or server
  applications) like this.  Also, if the file(s) change in size between
  the time the Content-Length is calculated and the time that the last
  chunk is delivered, the subroutine will C<Croak>.
  
  The post(...)  method of "LWP::UserAgent" exists as a shortcut for
  $ua->request(POST ...).
  
  =back
  
  =head1 SEE ALSO
  
  L<HTTP::Request>, L<LWP::UserAgent>
  
  
  =head1 COPYRIGHT
  
  Copyright 1997-2004, Gisle Aas
  
  This library is free software; you can redistribute it and/or
  modify it under the same terms as Perl itself.
  
  =cut
  
HTTP_REQUEST_COMMON

$fatpacked{"HTTP/Response.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'HTTP_RESPONSE';
  package HTTP::Response;
  
  require HTTP::Message;
  @ISA = qw(HTTP::Message);
  $VERSION = "6.04";
  
  use strict;
  use HTTP::Status ();
  
  
  
  sub new
  {
      my($class, $rc, $msg, $header, $content) = @_;
      my $self = $class->SUPER::new($header, $content);
      $self->code($rc);
      $self->message($msg);
      $self;
  }
  
  
  sub parse
  {
      my($class, $str) = @_;
      my $status_line;
      if ($str =~ s/^(.*)\n//) {
  	$status_line = $1;
      }
      else {
  	$status_line = $str;
  	$str = "";
      }
  
      my $self = $class->SUPER::parse($str);
      my($protocol, $code, $message);
      if ($status_line =~ /^\d{3} /) {
         # Looks like a response created by HTTP::Response->new
         ($code, $message) = split(' ', $status_line, 2);
      } else {
         ($protocol, $code, $message) = split(' ', $status_line, 3);
      }
      $self->protocol($protocol) if $protocol;
      $self->code($code) if defined($code);
      $self->message($message) if defined($message);
      $self;
  }
  
  
  sub clone
  {
      my $self = shift;
      my $clone = bless $self->SUPER::clone, ref($self);
      $clone->code($self->code);
      $clone->message($self->message);
      $clone->request($self->request->clone) if $self->request;
      # we don't clone previous
      $clone;
  }
  
  
  sub code      { shift->_elem('_rc',      @_); }
  sub message   { shift->_elem('_msg',     @_); }
  sub previous  { shift->_elem('_previous',@_); }
  sub request   { shift->_elem('_request', @_); }
  
  
  sub status_line
  {
      my $self = shift;
      my $code = $self->{'_rc'}  || "000";
      my $mess = $self->{'_msg'} || HTTP::Status::status_message($code) || "Unknown code";
      return "$code $mess";
  }
  
  
  sub base
  {
      my $self = shift;
      my $base = (
  	$self->header('Content-Base'),        # used to be HTTP/1.1
  	$self->header('Content-Location'),    # HTTP/1.1
  	$self->header('Base'),                # HTTP/1.0
      )[0];
      if ($base && $base =~ /^$URI::scheme_re:/o) {
  	# already absolute
  	return $HTTP::URI_CLASS->new($base);
      }
  
      my $req = $self->request;
      if ($req) {
          # if $base is undef here, the return value is effectively
          # just a copy of $self->request->uri.
          return $HTTP::URI_CLASS->new_abs($base, $req->uri);
      }
  
      # can't find an absolute base
      return undef;
  }
  
  
  sub redirects {
      my $self = shift;
      my @r;
      my $r = $self;
      while (my $p = $r->previous) {
          push(@r, $p);
          $r = $p;
      }
      return @r unless wantarray;
      return reverse @r;
  }
  
  
  sub filename
  {
      my $self = shift;
      my $file;
  
      my $cd = $self->header('Content-Disposition');
      if ($cd) {
  	require HTTP::Headers::Util;
  	if (my @cd = HTTP::Headers::Util::split_header_words($cd)) {
  	    my ($disposition, undef, %cd_param) = @{$cd[-1]};
  	    $file = $cd_param{filename};
  
  	    # RFC 2047 encoded?
  	    if ($file && $file =~ /^=\?(.+?)\?(.+?)\?(.+)\?=$/) {
  		my $charset = $1;
  		my $encoding = uc($2);
  		my $encfile = $3;
  
  		if ($encoding eq 'Q' || $encoding eq 'B') {
  		    local($SIG{__DIE__});
  		    eval {
  			if ($encoding eq 'Q') {
  			    $encfile =~ s/_/ /g;
  			    require MIME::QuotedPrint;
  			    $encfile = MIME::QuotedPrint::decode($encfile);
  			}
  			else { # $encoding eq 'B'
  			    require MIME::Base64;
  			    $encfile = MIME::Base64::decode($encfile);
  			}
  
  			require Encode;
  			require Encode::Locale;
  			Encode::from_to($encfile, $charset, "locale_fs");
  		    };
  
  		    $file = $encfile unless $@;
  		}
  	    }
  	}
      }
  
      unless (defined($file) && length($file)) {
  	my $uri;
  	if (my $cl = $self->header('Content-Location')) {
  	    $uri = URI->new($cl);
  	}
  	elsif (my $request = $self->request) {
  	    $uri = $request->uri;
  	}
  
  	if ($uri) {
  	    $file = ($uri->path_segments)[-1];
  	}
      }
  
      if ($file) {
  	$file =~ s,.*[\\/],,;  # basename
      }
  
      if ($file && !length($file)) {
  	$file = undef;
      }
  
      $file;
  }
  
  
  sub as_string
  {
      my $self = shift;
      my($eol) = @_;
      $eol = "\n" unless defined $eol;
  
      my $status_line = $self->status_line;
      my $proto = $self->protocol;
      $status_line = "$proto $status_line" if $proto;
  
      return join($eol, $status_line, $self->SUPER::as_string(@_));
  }
  
  
  sub dump
  {
      my $self = shift;
  
      my $status_line = $self->status_line;
      my $proto = $self->protocol;
      $status_line = "$proto $status_line" if $proto;
  
      return $self->SUPER::dump(
  	preheader => $status_line,
          @_,
      );
  }
  
  
  sub is_info     { HTTP::Status::is_info     (shift->{'_rc'}); }
  sub is_success  { HTTP::Status::is_success  (shift->{'_rc'}); }
  sub is_redirect { HTTP::Status::is_redirect (shift->{'_rc'}); }
  sub is_error    { HTTP::Status::is_error    (shift->{'_rc'}); }
  
  
  sub error_as_HTML
  {
      my $self = shift;
      my $title = 'An Error Occurred';
      my $body  = $self->status_line;
      $body =~ s/&/&amp;/g;
      $body =~ s/</&lt;/g;
      return <<EOM;
  <html>
  <head><title>$title</title></head>
  <body>
  <h1>$title</h1>
  <p>$body</p>
  </body>
  </html>
  EOM
  }
  
  
  sub current_age
  {
      my $self = shift;
      my $time = shift;
  
      # Implementation of RFC 2616 section 13.2.3
      # (age calculations)
      my $response_time = $self->client_date;
      my $date = $self->date;
  
      my $age = 0;
      if ($response_time && $date) {
  	$age = $response_time - $date;  # apparent_age
  	$age = 0 if $age < 0;
      }
  
      my $age_v = $self->header('Age');
      if ($age_v && $age_v > $age) {
  	$age = $age_v;   # corrected_received_age
      }
  
      if ($response_time) {
  	my $request = $self->request;
  	if ($request) {
  	    my $request_time = $request->date;
  	    if ($request_time && $request_time < $response_time) {
  		# Add response_delay to age to get 'corrected_initial_age'
  		$age += $response_time - $request_time;
  	    }
  	}
  	$age += ($time || time) - $response_time;
      }
      return $age;
  }
  
  
  sub freshness_lifetime
  {
      my($self, %opt) = @_;
  
      # First look for the Cache-Control: max-age=n header
      for my $cc ($self->header('Cache-Control')) {
  	for my $cc_dir (split(/\s*,\s*/, $cc)) {
  	    return $1 if $cc_dir =~ /^max-age\s*=\s*(\d+)/i;
  	}
      }
  
      # Next possibility is to look at the "Expires" header
      my $date = $self->date || $self->client_date || $opt{time} || time;
      if (my $expires = $self->expires) {
  	return $expires - $date;
      }
  
      # Must apply heuristic expiration
      return undef if exists $opt{heuristic_expiry} && !$opt{heuristic_expiry};
  
      # Default heuristic expiration parameters
      $opt{h_min} ||= 60;
      $opt{h_max} ||= 24 * 3600;
      $opt{h_lastmod_fraction} ||= 0.10; # 10% since last-mod suggested by RFC2616
      $opt{h_default} ||= 3600;
  
      # Should give a warning if more than 24 hours according to
      # RFC 2616 section 13.2.4.  Here we just make this the default
      # maximum value.
  
      if (my $last_modified = $self->last_modified) {
  	my $h_exp = ($date - $last_modified) * $opt{h_lastmod_fraction};
  	return $opt{h_min} if $h_exp < $opt{h_min};
  	return $opt{h_max} if $h_exp > $opt{h_max};
  	return $h_exp;
      }
  
      # default when all else fails
      return $opt{h_min} if $opt{h_min} > $opt{h_default};
      return $opt{h_default};
  }
  
  
  sub is_fresh
  {
      my($self, %opt) = @_;
      $opt{time} ||= time;
      my $f = $self->freshness_lifetime(%opt);
      return undef unless defined($f);
      return $f > $self->current_age($opt{time});
  }
  
  
  sub fresh_until
  {
      my($self, %opt) = @_;
      $opt{time} ||= time;
      my $f = $self->freshness_lifetime(%opt);
      return undef unless defined($f);
      return $f - $self->current_age($opt{time}) + $opt{time};
  }
  
  1;
  
  
  __END__
  
  =head1 NAME
  
  HTTP::Response - HTTP style response message
  
  =head1 SYNOPSIS
  
  Response objects are returned by the request() method of the C<LWP::UserAgent>:
  
      # ...
      $response = $ua->request($request)
      if ($response->is_success) {
          print $response->decoded_content;
      }
      else {
          print STDERR $response->status_line, "\n";
      }
  
  =head1 DESCRIPTION
  
  The C<HTTP::Response> class encapsulates HTTP style responses.  A
  response consists of a response line, some headers, and a content
  body. Note that the LWP library uses HTTP style responses even for
  non-HTTP protocol schemes.  Instances of this class are usually
  created and returned by the request() method of an C<LWP::UserAgent>
  object.
  
  C<HTTP::Response> is a subclass of C<HTTP::Message> and therefore
  inherits its methods.  The following additional methods are available:
  
  =over 4
  
  =item $r = HTTP::Response->new( $code )
  
  =item $r = HTTP::Response->new( $code, $msg )
  
  =item $r = HTTP::Response->new( $code, $msg, $header )
  
  =item $r = HTTP::Response->new( $code, $msg, $header, $content )
  
  Constructs a new C<HTTP::Response> object describing a response with
  response code $code and optional message $msg.  The optional $header
  argument should be a reference to an C<HTTP::Headers> object or a
  plain array reference of key/value pairs.  The optional $content
  argument should be a string of bytes.  The meanings of these arguments are
  described below.
  
  =item $r = HTTP::Response->parse( $str )
  
  This constructs a new response object by parsing the given string.
  
  =item $r->code
  
  =item $r->code( $code )
  
  This is used to get/set the code attribute.  The code is a 3 digit
  number that encode the overall outcome of an HTTP response.  The
  C<HTTP::Status> module provide constants that provide mnemonic names
  for the code attribute.
  
  =item $r->message
  
  =item $r->message( $message )
  
  This is used to get/set the message attribute.  The message is a short
  human readable single line string that explains the response code.
  
  =item $r->header( $field )
  
  =item $r->header( $field => $value )
  
  This is used to get/set header values and it is inherited from
  C<HTTP::Headers> via C<HTTP::Message>.  See L<HTTP::Headers> for
  details and other similar methods that can be used to access the
  headers.
  
  =item $r->content
  
  =item $r->content( $bytes )
  
  This is used to get/set the raw content and it is inherited from the
  C<HTTP::Message> base class.  See L<HTTP::Message> for details and
  other methods that can be used to access the content.
  
  =item $r->decoded_content( %options )
  
  This will return the content after any C<Content-Encoding> and
  charsets have been decoded.  See L<HTTP::Message> for details.
  
  =item $r->request
  
  =item $r->request( $request )
  
  This is used to get/set the request attribute.  The request attribute
  is a reference to the the request that caused this response.  It does
  not have to be the same request passed to the $ua->request() method,
  because there might have been redirects and authorization retries in
  between.
  
  =item $r->previous
  
  =item $r->previous( $response )
  
  This is used to get/set the previous attribute.  The previous
  attribute is used to link together chains of responses.  You get
  chains of responses if the first response is redirect or unauthorized.
  The value is C<undef> if this is the first response in a chain.
  
  Note that the method $r->redirects is provided as a more convenient
  way to access the response chain.
  
  =item $r->status_line
  
  Returns the string "E<lt>code> E<lt>message>".  If the message attribute
  is not set then the official name of E<lt>code> (see L<HTTP::Status>)
  is substituted.
  
  =item $r->base
  
  Returns the base URI for this response.  The return value will be a
  reference to a URI object.
  
  The base URI is obtained from one the following sources (in priority
  order):
  
  =over 4
  
  =item 1.
  
  Embedded in the document content, for instance <BASE HREF="...">
  in HTML documents.
  
  =item 2.
  
  A "Content-Base:" or a "Content-Location:" header in the response.
  
  For backwards compatibility with older HTTP implementations we will
  also look for the "Base:" header.
  
  =item 3.
  
  The URI used to request this response. This might not be the original
  URI that was passed to $ua->request() method, because we might have
  received some redirect responses first.
  
  =back
  
  If none of these sources provide an absolute URI, undef is returned.
  
  When the LWP protocol modules produce the HTTP::Response object, then
  any base URI embedded in the document (step 1) will already have
  initialized the "Content-Base:" header. This means that this method
  only performs the last 2 steps (the content is not always available
  either).
  
  =item $r->filename
  
  Returns a filename for this response.  Note that doing sanity checks
  on the returned filename (eg. removing characters that cannot be used
  on the target filesystem where the filename would be used, and
  laundering it for security purposes) are the caller's responsibility;
  the only related thing done by this method is that it makes a simple
  attempt to return a plain filename with no preceding path segments.
  
  The filename is obtained from one the following sources (in priority
  order):
  
  =over 4
  
  =item 1.
  
  A "Content-Disposition:" header in the response.  Proper decoding of
  RFC 2047 encoded filenames requires the C<MIME::QuotedPrint> (for "Q"
  encoding), C<MIME::Base64> (for "B" encoding), and C<Encode> modules.
  
  =item 2.
  
  A "Content-Location:" header in the response.
  
  =item 3.
  
  The URI used to request this response. This might not be the original
  URI that was passed to $ua->request() method, because we might have
  received some redirect responses first.
  
  =back
  
  If a filename cannot be derived from any of these sources, undef is
  returned.
  
  =item $r->as_string
  
  =item $r->as_string( $eol )
  
  Returns a textual representation of the response.
  
  =item $r->is_info
  
  =item $r->is_success
  
  =item $r->is_redirect
  
  =item $r->is_error
  
  These methods indicate if the response was informational, successful, a
  redirection, or an error.  See L<HTTP::Status> for the meaning of these.
  
  =item $r->error_as_HTML
  
  Returns a string containing a complete HTML document indicating what
  error occurred.  This method should only be called when $r->is_error
  is TRUE.
  
  =item $r->redirects
  
  Returns the list of redirect responses that lead up to this response
  by following the $r->previous chain.  The list order is oldest first.
  
  In scalar context return the number of redirect responses leading up
  to this one.
  
  =item $r->current_age
  
  Calculates the "current age" of the response as specified by RFC 2616
  section 13.2.3.  The age of a response is the time since it was sent
  by the origin server.  The returned value is a number representing the
  age in seconds.
  
  =item $r->freshness_lifetime( %opt )
  
  Calculates the "freshness lifetime" of the response as specified by
  RFC 2616 section 13.2.4.  The "freshness lifetime" is the length of
  time between the generation of a response and its expiration time.
  The returned value is the number of seconds until expiry.
  
  If the response does not contain an "Expires" or a "Cache-Control"
  header, then this function will apply some simple heuristic based on
  the "Last-Modified" header to determine a suitable lifetime.  The
  following options might be passed to control the heuristics:
  
  =over
  
  =item heuristic_expiry => $bool
  
  If passed as a FALSE value, don't apply heuristics and just return
  C<undef> when "Expires" or "Cache-Control" is lacking.
  
  =item h_lastmod_fraction => $num
  
  This number represent the fraction of the difference since the
  "Last-Modified" timestamp to make the expiry time.  The default is
  C<0.10>, the suggested typical setting of 10% in RFC 2616.
  
  =item h_min => $sec
  
  This is the lower limit of the heuristic expiry age to use.  The
  default is C<60> (1 minute).
  
  =item h_max => $sec
  
  This is the upper limit of the heuristic expiry age to use.  The
  default is C<86400> (24 hours).
  
  =item h_default => $sec
  
  This is the expiry age to use when nothing else applies.  The default
  is C<3600> (1 hour) or "h_min" if greater.
  
  =back
  
  =item $r->is_fresh( %opt )
  
  Returns TRUE if the response is fresh, based on the values of
  freshness_lifetime() and current_age().  If the response is no longer
  fresh, then it has to be re-fetched or re-validated by the origin
  server.
  
  Options might be passed to control expiry heuristics, see the
  description of freshness_lifetime().
  
  =item $r->fresh_until( %opt )
  
  Returns the time (seconds since epoch) when this entity is no longer fresh.
  
  Options might be passed to control expiry heuristics, see the
  description of freshness_lifetime().
  
  =back
  
  =head1 SEE ALSO
  
  L<HTTP::Headers>, L<HTTP::Message>, L<HTTP::Status>, L<HTTP::Request>
  
  =head1 COPYRIGHT
  
  Copyright 1995-2004 Gisle Aas.
  
  This library is free software; you can redistribute it and/or
  modify it under the same terms as Perl itself.
  
HTTP_RESPONSE

$fatpacked{"HTTP/Status.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'HTTP_STATUS';
  package HTTP::Status;
  
  use strict;
  require 5.002;   # because we use prototypes
  
  use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $VERSION);
  
  require Exporter;
  @ISA = qw(Exporter);
  @EXPORT = qw(is_info is_success is_redirect is_error status_message);
  @EXPORT_OK = qw(is_client_error is_server_error);
  $VERSION = "6.03";
  
  # Note also addition of mnemonics to @EXPORT below
  
  # Unmarked codes are from RFC 2616
  # See also: http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
  
  my %StatusCode = (
      100 => 'Continue',
      101 => 'Switching Protocols',
      102 => 'Processing',                      # RFC 2518 (WebDAV)
      200 => 'OK',
      201 => 'Created',
      202 => 'Accepted',
      203 => 'Non-Authoritative Information',
      204 => 'No Content',
      205 => 'Reset Content',
      206 => 'Partial Content',
      207 => 'Multi-Status',                    # RFC 2518 (WebDAV)
      208 => 'Already Reported',		      # RFC 5842
      300 => 'Multiple Choices',
      301 => 'Moved Permanently',
      302 => 'Found',
      303 => 'See Other',
      304 => 'Not Modified',
      305 => 'Use Proxy',
      307 => 'Temporary Redirect',
      400 => 'Bad Request',
      401 => 'Unauthorized',
      402 => 'Payment Required',
      403 => 'Forbidden',
      404 => 'Not Found',
      405 => 'Method Not Allowed',
      406 => 'Not Acceptable',
      407 => 'Proxy Authentication Required',
      408 => 'Request Timeout',
      409 => 'Conflict',
      410 => 'Gone',
      411 => 'Length Required',
      412 => 'Precondition Failed',
      413 => 'Request Entity Too Large',
      414 => 'Request-URI Too Large',
      415 => 'Unsupported Media Type',
      416 => 'Request Range Not Satisfiable',
      417 => 'Expectation Failed',
      418 => 'I\'m a teapot',		      # RFC 2324
      422 => 'Unprocessable Entity',            # RFC 2518 (WebDAV)
      423 => 'Locked',                          # RFC 2518 (WebDAV)
      424 => 'Failed Dependency',               # RFC 2518 (WebDAV)
      425 => 'No code',                         # WebDAV Advanced Collections
      426 => 'Upgrade Required',                # RFC 2817
      428 => 'Precondition Required',
      429 => 'Too Many Requests',
      431 => 'Request Header Fields Too Large',
      449 => 'Retry with',                      # unofficial Microsoft
      500 => 'Internal Server Error',
      501 => 'Not Implemented',
      502 => 'Bad Gateway',
      503 => 'Service Unavailable',
      504 => 'Gateway Timeout',
      505 => 'HTTP Version Not Supported',
      506 => 'Variant Also Negotiates',         # RFC 2295
      507 => 'Insufficient Storage',            # RFC 2518 (WebDAV)
      509 => 'Bandwidth Limit Exceeded',        # unofficial
      510 => 'Not Extended',                    # RFC 2774
      511 => 'Network Authentication Required',
  );
  
  my $mnemonicCode = '';
  my ($code, $message);
  while (($code, $message) = each %StatusCode) {
      # create mnemonic subroutines
      $message =~ s/I'm/I am/;
      $message =~ tr/a-z \-/A-Z__/;
      $mnemonicCode .= "sub HTTP_$message () { $code }\n";
      $mnemonicCode .= "*RC_$message = \\&HTTP_$message;\n";  # legacy
      $mnemonicCode .= "push(\@EXPORT_OK, 'HTTP_$message');\n";
      $mnemonicCode .= "push(\@EXPORT, 'RC_$message');\n";
  }
  eval $mnemonicCode; # only one eval for speed
  die if $@;
  
  # backwards compatibility
  *RC_MOVED_TEMPORARILY = \&RC_FOUND;  # 302 was renamed in the standard
  push(@EXPORT, "RC_MOVED_TEMPORARILY");
  
  %EXPORT_TAGS = (
     constants => [grep /^HTTP_/, @EXPORT_OK],
     is => [grep /^is_/, @EXPORT, @EXPORT_OK],
  );
  
  
  sub status_message  ($) { $StatusCode{$_[0]}; }
  
  sub is_info         ($) { $_[0] >= 100 && $_[0] < 200; }
  sub is_success      ($) { $_[0] >= 200 && $_[0] < 300; }
  sub is_redirect     ($) { $_[0] >= 300 && $_[0] < 400; }
  sub is_error        ($) { $_[0] >= 400 && $_[0] < 600; }
  sub is_client_error ($) { $_[0] >= 400 && $_[0] < 500; }
  sub is_server_error ($) { $_[0] >= 500 && $_[0] < 600; }
  
  1;
  
  
  __END__
  
  =head1 NAME
  
  HTTP::Status - HTTP Status code processing
  
  =head1 SYNOPSIS
  
   use HTTP::Status qw(:constants :is status_message);
  
   if ($rc != HTTP_OK) {
       print status_message($rc), "\n";
   }
  
   if (is_success($rc)) { ... }
   if (is_error($rc)) { ... }
   if (is_redirect($rc)) { ... }
  
  =head1 DESCRIPTION
  
  I<HTTP::Status> is a library of routines for defining and
  classifying HTTP status codes for libwww-perl.  Status codes are
  used to encode the overall outcome of an HTTP response message.  Codes
  correspond to those defined in RFC 2616 and RFC 2518.
  
  =head1 CONSTANTS
  
  The following constant functions can be used as mnemonic status code
  names.  None of these are exported by default.  Use the C<:constants>
  tag to import them all.
  
     HTTP_CONTINUE                        (100)
     HTTP_SWITCHING_PROTOCOLS             (101)
     HTTP_PROCESSING                      (102)
  
     HTTP_OK                              (200)
     HTTP_CREATED                         (201)
     HTTP_ACCEPTED                        (202)
     HTTP_NON_AUTHORITATIVE_INFORMATION   (203)
     HTTP_NO_CONTENT                      (204)
     HTTP_RESET_CONTENT                   (205)
     HTTP_PARTIAL_CONTENT                 (206)
     HTTP_MULTI_STATUS                    (207)
     HTTP_ALREADY_REPORTED		(208)
  
     HTTP_MULTIPLE_CHOICES                (300)
     HTTP_MOVED_PERMANENTLY               (301)
     HTTP_FOUND                           (302)
     HTTP_SEE_OTHER                       (303)
     HTTP_NOT_MODIFIED                    (304)
     HTTP_USE_PROXY                       (305)
     HTTP_TEMPORARY_REDIRECT              (307)
  
     HTTP_BAD_REQUEST                     (400)
     HTTP_UNAUTHORIZED                    (401)
     HTTP_PAYMENT_REQUIRED                (402)
     HTTP_FORBIDDEN                       (403)
     HTTP_NOT_FOUND                       (404)
     HTTP_METHOD_NOT_ALLOWED              (405)
     HTTP_NOT_ACCEPTABLE                  (406)
     HTTP_PROXY_AUTHENTICATION_REQUIRED   (407)
     HTTP_REQUEST_TIMEOUT                 (408)
     HTTP_CONFLICT                        (409)
     HTTP_GONE                            (410)
     HTTP_LENGTH_REQUIRED                 (411)
     HTTP_PRECONDITION_FAILED             (412)
     HTTP_REQUEST_ENTITY_TOO_LARGE        (413)
     HTTP_REQUEST_URI_TOO_LARGE           (414)
     HTTP_UNSUPPORTED_MEDIA_TYPE          (415)
     HTTP_REQUEST_RANGE_NOT_SATISFIABLE   (416)
     HTTP_EXPECTATION_FAILED              (417)
     HTTP_I_AM_A_TEAPOT			(418)
     HTTP_UNPROCESSABLE_ENTITY            (422)
     HTTP_LOCKED                          (423)
     HTTP_FAILED_DEPENDENCY               (424)
     HTTP_NO_CODE                         (425)
     HTTP_UPGRADE_REQUIRED                (426)
     HTTP_PRECONDITION_REQUIRED		(428)
     HTTP_TOO_MANY_REQUESTS		(429)
     HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE (431)
     HTTP_RETRY_WITH                      (449)
  
     HTTP_INTERNAL_SERVER_ERROR           (500)
     HTTP_NOT_IMPLEMENTED                 (501)
     HTTP_BAD_GATEWAY                     (502)
     HTTP_SERVICE_UNAVAILABLE             (503)
     HTTP_GATEWAY_TIMEOUT                 (504)
     HTTP_HTTP_VERSION_NOT_SUPPORTED      (505)
     HTTP_VARIANT_ALSO_NEGOTIATES         (506)
     HTTP_INSUFFICIENT_STORAGE            (507)
     HTTP_BANDWIDTH_LIMIT_EXCEEDED        (509)
     HTTP_NOT_EXTENDED                    (510)
     HTTP_NETWORK_AUTHENTICATION_REQUIRED (511)
  
  =head1 FUNCTIONS
  
  The following additional functions are provided.  Most of them are
  exported by default.  The C<:is> import tag can be used to import all
  the classification functions.
  
  =over 4
  
  =item status_message( $code )
  
  The status_message() function will translate status codes to human
  readable strings. The string is the same as found in the constant
  names above.  If the $code is unknown, then C<undef> is returned.
  
  =item is_info( $code )
  
  Return TRUE if C<$code> is an I<Informational> status code (1xx).  This
  class of status code indicates a provisional response which can't have
  any content.
  
  =item is_success( $code )
  
  Return TRUE if C<$code> is a I<Successful> status code (2xx).
  
  =item is_redirect( $code )
  
  Return TRUE if C<$code> is a I<Redirection> status code (3xx). This class of
  status code indicates that further action needs to be taken by the
  user agent in order to fulfill the request.
  
  =item is_error( $code )
  
  Return TRUE if C<$code> is an I<Error> status code (4xx or 5xx).  The function
  returns TRUE for both client and server error status codes.
  
  =item is_client_error( $code )
  
  Return TRUE if C<$code> is a I<Client Error> status code (4xx). This class
  of status code is intended for cases in which the client seems to have
  erred.
  
  This function is B<not> exported by default.
  
  =item is_server_error( $code )
  
  Return TRUE if C<$code> is a I<Server Error> status code (5xx). This class
  of status codes is intended for cases in which the server is aware
  that it has erred or is incapable of performing the request.
  
  This function is B<not> exported by default.
  
  =back
  
  =head1 BUGS
  
  For legacy reasons all the C<HTTP_> constants are exported by default
  with the prefix C<RC_>.  It's recommended to use explicit imports and
  the C<:constants> tag instead of relying on this.
HTTP_STATUS

$fatpacked{"JSON.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'JSON';
  package JSON;
  
  
  use strict;
  use Carp ();
  use base qw(Exporter);
  @JSON::EXPORT = qw(from_json to_json jsonToObj objToJson encode_json decode_json);
  
  BEGIN {
      $JSON::VERSION = '2.90';
      $JSON::DEBUG   = 0 unless (defined $JSON::DEBUG);
      $JSON::DEBUG   = $ENV{ PERL_JSON_DEBUG } if exists $ENV{ PERL_JSON_DEBUG };
  }
  
  my $Module_XS  = 'JSON::XS';
  my $Module_PP  = 'JSON::PP';
  my $Module_bp  = 'JSON::backportPP'; # included in JSON distribution
  my $PP_Version = '2.27203';
  my $XS_Version = '2.34';
  
  
  # XS and PP common methods
  
  my @PublicMethods = qw/
      ascii latin1 utf8 pretty indent space_before space_after relaxed canonical allow_nonref 
      allow_blessed convert_blessed filter_json_object filter_json_single_key_object 
      shrink max_depth max_size encode decode decode_prefix allow_unknown
  /;
  
  my @Properties = qw/
      ascii latin1 utf8 indent space_before space_after relaxed canonical allow_nonref
      allow_blessed convert_blessed shrink max_depth max_size allow_unknown
  /;
  
  my @XSOnlyMethods = qw/allow_tags/; # Currently nothing
  
  my @PPOnlyMethods = qw/
      indent_length sort_by
      allow_singlequote allow_bignum loose allow_barekey escape_slash as_nonblessed
  /; # JSON::PP specific
  
  
  # used in _load_xs and _load_pp ($INSTALL_ONLY is not used currently)
  my $_INSTALL_DONT_DIE  = 1; # When _load_xs fails to load XS, don't die.
  my $_INSTALL_ONLY      = 2; # Don't call _set_methods()
  my $_ALLOW_UNSUPPORTED = 0;
  my $_UNIV_CONV_BLESSED = 0;
  my $_USSING_bpPP       = 0;
  
  
  # Check the environment variable to decide worker module. 
  
  unless ($JSON::Backend) {
      $JSON::DEBUG and  Carp::carp("Check used worker module...");
  
      my $backend = exists $ENV{PERL_JSON_BACKEND} ? $ENV{PERL_JSON_BACKEND} : 1;
  
      if ($backend eq '1' or $backend =~ /JSON::XS\s*,\s*JSON::PP/) {
          _load_xs($_INSTALL_DONT_DIE) or _load_pp();
      }
      elsif ($backend eq '0' or $backend eq 'JSON::PP') {
          _load_pp();
      }
      elsif ($backend eq '2' or $backend eq 'JSON::XS') {
          _load_xs();
      }
      elsif ($backend eq 'JSON::backportPP') {
          $_USSING_bpPP = 1;
          _load_pp();
      }
      else {
          Carp::croak "The value of environmental variable 'PERL_JSON_BACKEND' is invalid.";
      }
  }
  
  
  sub import {
      my $pkg = shift;
      my @what_to_export;
      my $no_export;
  
      for my $tag (@_) {
          if ($tag eq '-support_by_pp') {
              if (!$_ALLOW_UNSUPPORTED++) {
                  JSON::Backend::XS
                      ->support_by_pp(@PPOnlyMethods) if ($JSON::Backend eq $Module_XS);
              }
              next;
          }
          elsif ($tag eq '-no_export') {
              $no_export++, next;
          }
          elsif ( $tag eq '-convert_blessed_universally' ) {
              eval q|
                  require B;
                  *UNIVERSAL::TO_JSON = sub {
                      my $b_obj = B::svref_2object( $_[0] );
                      return    $b_obj->isa('B::HV') ? { %{ $_[0] } }
                              : $b_obj->isa('B::AV') ? [ @{ $_[0] } ]
                              : undef
                              ;
                  }
              | if ( !$_UNIV_CONV_BLESSED++ );
              next;
          }
          push @what_to_export, $tag;
      }
  
      return if ($no_export);
  
      __PACKAGE__->export_to_level(1, $pkg, @what_to_export);
  }
  
  
  # OBSOLETED
  
  sub jsonToObj {
      my $alternative = 'from_json';
      if (defined $_[0] and UNIVERSAL::isa($_[0], 'JSON')) {
          shift @_; $alternative = 'decode';
      }
      Carp::carp "'jsonToObj' will be obsoleted. Please use '$alternative' instead.";
      return JSON::from_json(@_);
  };
  
  sub objToJson {
      my $alternative = 'to_json';
      if (defined $_[0] and UNIVERSAL::isa($_[0], 'JSON')) {
          shift @_; $alternative = 'encode';
      }
      Carp::carp "'objToJson' will be obsoleted. Please use '$alternative' instead.";
      JSON::to_json(@_);
  };
  
  
  # INTERFACES
  
  sub to_json ($@) {
      if (
          ref($_[0]) eq 'JSON'
          or (@_ > 2 and $_[0] eq 'JSON')
      ) {
          Carp::croak "to_json should not be called as a method.";
      }
      my $json = JSON->new;
  
      if (@_ == 2 and ref $_[1] eq 'HASH') {
          my $opt  = $_[1];
          for my $method (keys %$opt) {
              $json->$method( $opt->{$method} );
          }
      }
  
      $json->encode($_[0]);
  }
  
  
  sub from_json ($@) {
      if ( ref($_[0]) eq 'JSON' or $_[0] eq 'JSON' ) {
          Carp::croak "from_json should not be called as a method.";
      }
      my $json = JSON->new;
  
      if (@_ == 2 and ref $_[1] eq 'HASH') {
          my $opt  = $_[1];
          for my $method (keys %$opt) {
              $json->$method( $opt->{$method} );
          }
      }
  
      return $json->decode( $_[0] );
  }
  
  
  
  sub true  { $JSON::true  }
  
  sub false { $JSON::false }
  
  sub null  { undef; }
  
  
  sub require_xs_version { $XS_Version; }
  
  sub backend {
      my $proto = shift;
      $JSON::Backend;
  }
  
  #*module = *backend;
  
  
  sub is_xs {
      return $_[0]->backend eq $Module_XS;
  }
  
  
  sub is_pp {
      return not $_[0]->is_xs;
  }
  
  
  sub pureperl_only_methods { @PPOnlyMethods; }
  
  
  sub property {
      my ($self, $name, $value) = @_;
  
      if (@_ == 1) {
          my %props;
          for $name (@Properties) {
              my $method = 'get_' . $name;
              if ($name eq 'max_size') {
                  my $value = $self->$method();
                  $props{$name} = $value == 1 ? 0 : $value;
                  next;
              }
              $props{$name} = $self->$method();
          }
          return \%props;
      }
      elsif (@_ > 3) {
          Carp::croak('property() can take only the option within 2 arguments.');
      }
      elsif (@_ == 2) {
          if ( my $method = $self->can('get_' . $name) ) {
              if ($name eq 'max_size') {
                  my $value = $self->$method();
                  return $value == 1 ? 0 : $value;
              }
              $self->$method();
          }
      }
      else {
          $self->$name($value);
      }
  
  }
  
  
  
  # INTERNAL
  
  sub _load_xs {
      my $opt = shift;
  
      $JSON::DEBUG and Carp::carp "Load $Module_XS.";
  
      # if called after install module, overload is disable.... why?
      JSON::Boolean::_overrride_overload($Module_XS);
      JSON::Boolean::_overrride_overload($Module_PP);
  
      eval qq|
          use $Module_XS $XS_Version ();
      |;
  
      if ($@) {
          if (defined $opt and $opt & $_INSTALL_DONT_DIE) {
              $JSON::DEBUG and Carp::carp "Can't load $Module_XS...($@)";
              return 0;
          }
          Carp::croak $@;
      }
  
      unless (defined $opt and $opt & $_INSTALL_ONLY) {
          _set_module( $JSON::Backend = $Module_XS );
          my $data = join("", <DATA>); # this code is from Jcode 2.xx.
          close(DATA);
          eval $data;
          JSON::Backend::XS->init;
      }
  
      return 1;
  };
  
  
  sub _load_pp {
      my $opt = shift;
      my $backend = $_USSING_bpPP ? $Module_bp : $Module_PP;
  
      $JSON::DEBUG and Carp::carp "Load $backend.";
  
      # if called after install module, overload is disable.... why?
      JSON::Boolean::_overrride_overload($Module_XS);
      JSON::Boolean::_overrride_overload($backend);
  
      if ( $_USSING_bpPP ) {
          eval qq| require $backend |;
      }
      else {
          eval qq| use $backend $PP_Version () |;
      }
  
      if ($@) {
          if ( $backend eq $Module_PP ) {
              $JSON::DEBUG and Carp::carp "Can't load $Module_PP ($@), so try to load $Module_bp";
              $_USSING_bpPP++;
              $backend = $Module_bp;
              JSON::Boolean::_overrride_overload($backend);
              local $^W; # if PP installed but invalid version, backportPP redefines methods.
              eval qq| require $Module_bp |;
          }
          Carp::croak $@ if $@;
      }
  
      unless (defined $opt and $opt & $_INSTALL_ONLY) {
          _set_module( $JSON::Backend = $Module_PP ); # even if backportPP, set $Backend with 'JSON::PP'
          JSON::Backend::PP->init;
      }
  };
  
  
  sub _set_module {
      return if defined $JSON::true;
  
      my $module = shift;
  
      local $^W;
      no strict qw(refs);
  
      $JSON::true  = ${"$module\::true"};
      $JSON::false = ${"$module\::false"};
  
      push @JSON::ISA, $module;
      if ( JSON->is_xs and JSON->backend->VERSION < 3 ) {
          eval 'package JSON::PP::Boolean';
          push @{"$module\::Boolean::ISA"}, qw(JSON::PP::Boolean);
      }
  
      *{"JSON::is_bool"} = \&{"$module\::is_bool"};
  
      for my $method ($module eq $Module_XS ? @PPOnlyMethods : @XSOnlyMethods) {
          *{"JSON::$method"} = sub {
              Carp::carp("$method is not supported in $module.");
              $_[0];
          };
      }
  
      return 1;
  }
  
  
  
  #
  # JSON Boolean
  #
  
  package JSON::Boolean;
  
  my %Installed;
  
  sub _overrride_overload {
      return; # this function is currently disable.
      return if ($Installed{ $_[0] }++);
  
      my $boolean = $_[0] . '::Boolean';
  
      eval sprintf(q|
          package %s;
          use overload (
              '""' => sub { ${$_[0]} == 1 ? 'true' : 'false' },
              'eq' => sub {
                  my ($obj, $op) = ref ($_[0]) ? ($_[0], $_[1]) : ($_[1], $_[0]);
                  if ($op eq 'true' or $op eq 'false') {
                      return "$obj" eq 'true' ? 'true' eq $op : 'false' eq $op;
                  }
                  else {
                      return $obj ? 1 == $op : 0 == $op;
                  }
              },
          );
      |, $boolean);
  
      if ($@) { Carp::croak $@; }
  
      if ( exists $INC{'JSON/XS.pm'} and $boolean eq 'JSON::XS::Boolean' ) {
          local $^W;
          my $true  = do { bless \(my $dummy = 1), $boolean };
          my $false = do { bless \(my $dummy = 0), $boolean };
          *JSON::XS::true  = sub () { $true };
          *JSON::XS::false = sub () { $false };
      }
      elsif ( exists $INC{'JSON/PP.pm'} and $boolean eq 'JSON::PP::Boolean' ) {
          local $^W;
          my $true  = do { bless \(my $dummy = 1), $boolean };
          my $false = do { bless \(my $dummy = 0), $boolean };
          *JSON::PP::true  = sub { $true };
          *JSON::PP::false = sub { $false };
      }
  
      return 1;
  }
  
  
  #
  # Helper classes for Backend Module (PP)
  #
  
  package JSON::Backend::PP;
  
  sub init {
      local $^W;
      no strict qw(refs); # this routine may be called after JSON::Backend::XS init was called.
      *{"JSON::decode_json"} = \&{"JSON::PP::decode_json"};
      *{"JSON::encode_json"} = \&{"JSON::PP::encode_json"};
      *{"JSON::PP::is_xs"}  = sub { 0 };
      *{"JSON::PP::is_pp"}  = sub { 1 };
      return 1;
  }
  
  #
  # To save memory, the below lines are read only when XS backend is used.
  #
  
  package JSON;
  
  1;
  __DATA__
  
  
  #
  # Helper classes for Backend Module (XS)
  #
  
  package JSON::Backend::XS;
  
  use constant INDENT_LENGTH_FLAG => 15 << 12;
  
  use constant UNSUPPORTED_ENCODE_FLAG => {
      ESCAPE_SLASH      => 0x00000010,
      ALLOW_BIGNUM      => 0x00000020,
      AS_NONBLESSED     => 0x00000040,
      EXPANDED          => 0x10000000, # for developer's
  };
  
  use constant UNSUPPORTED_DECODE_FLAG => {
      LOOSE             => 0x00000001,
      ALLOW_BIGNUM      => 0x00000002,
      ALLOW_BAREKEY     => 0x00000004,
      ALLOW_SINGLEQUOTE => 0x00000008,
      EXPANDED          => 0x20000000, # for developer's
  };
  
  
  sub init {
      local $^W;
      no strict qw(refs);
      *{"JSON::decode_json"} = \&{"JSON::XS::decode_json"};
      *{"JSON::encode_json"} = \&{"JSON::XS::encode_json"};
      *{"JSON::XS::is_xs"}  = sub { 1 };
      *{"JSON::XS::is_pp"}  = sub { 0 };
      return 1;
  }
  
  
  sub support_by_pp {
      my ($class, @methods) = @_;
  
      local $^W;
      no strict qw(refs);
  
      my $JSON_XS_encode_orignal     = \&JSON::XS::encode;
      my $JSON_XS_decode_orignal     = \&JSON::XS::decode;
      my $JSON_XS_incr_parse_orignal = \&JSON::XS::incr_parse;
  
      *JSON::XS::decode     = \&JSON::Backend::XS::Supportable::_decode;
      *JSON::XS::encode     = \&JSON::Backend::XS::Supportable::_encode;
      *JSON::XS::incr_parse = \&JSON::Backend::XS::Supportable::_incr_parse;
  
      *{JSON::XS::_original_decode}     = $JSON_XS_decode_orignal;
      *{JSON::XS::_original_encode}     = $JSON_XS_encode_orignal;
      *{JSON::XS::_original_incr_parse} = $JSON_XS_incr_parse_orignal;
  
      push @JSON::Backend::XS::Supportable::ISA, 'JSON';
  
      my $pkg = 'JSON::Backend::XS::Supportable';
  
      *{JSON::new} = sub {
          my $proto = JSON::XS->new; $$proto = 0;
          bless  $proto, $pkg;
      };
  
  
      for my $method (@methods) {
          my $flag = uc($method);
          my $type |= (UNSUPPORTED_ENCODE_FLAG->{$flag} || 0);
             $type |= (UNSUPPORTED_DECODE_FLAG->{$flag} || 0);
  
          next unless($type);
  
          $pkg->_make_unsupported_method($method => $type);
      }
  
  #    push @{"JSON::XS::Boolean::ISA"}, qw(JSON::PP::Boolean);
  #    push @{"JSON::PP::Boolean::ISA"}, qw(JSON::Boolean);
  
      $JSON::DEBUG and Carp::carp("set -support_by_pp mode.");
  
      return 1;
  }
  
  
  
  
  #
  # Helper classes for XS
  #
  
  package JSON::Backend::XS::Supportable;
  
  $Carp::Internal{'JSON::Backend::XS::Supportable'} = 1;
  
  sub _make_unsupported_method {
      my ($pkg, $method, $type) = @_;
  
      local $^W;
      no strict qw(refs);
  
      *{"$pkg\::$method"} = sub {
          local $^W;
          if (defined $_[1] ? $_[1] : 1) {
              ${$_[0]} |= $type;
          }
          else {
              ${$_[0]} &= ~$type;
          }
          $_[0];
      };
  
      *{"$pkg\::get_$method"} = sub {
          ${$_[0]} & $type ? 1 : '';
      };
  
  }
  
  
  sub _set_for_pp {
      JSON::_load_pp( $_INSTALL_ONLY );
  
      my $type  = shift;
      my $pp    = JSON::PP->new;
      my $prop = $_[0]->property;
  
      for my $name (keys %$prop) {
          $pp->$name( $prop->{$name} ? $prop->{$name} : 0 );
      }
  
      my $unsupported = $type eq 'encode' ? JSON::Backend::XS::UNSUPPORTED_ENCODE_FLAG
                                          : JSON::Backend::XS::UNSUPPORTED_DECODE_FLAG;
      my $flags       = ${$_[0]} || 0;
  
      for my $name (keys %$unsupported) {
          next if ($name eq 'EXPANDED'); # for developer's
          my $enable = ($flags & $unsupported->{$name}) ? 1 : 0;
          my $method = lc $name;
          $pp->$method($enable);
      }
  
      $pp->indent_length( $_[0]->get_indent_length );
  
      return $pp;
  }
  
  sub _encode { # using with PP encode
      if (${$_[0]}) {
          _set_for_pp('encode' => @_)->encode($_[1]);
      }
      else {
          $_[0]->_original_encode( $_[1] );
      }
  }
  
  
  sub _decode { # if unsupported-flag is set, use PP
      if (${$_[0]}) {
          _set_for_pp('decode' => @_)->decode($_[1]);
      }
      else {
          $_[0]->_original_decode( $_[1] );
      }
  }
  
  
  sub decode_prefix { # if unsupported-flag is set, use PP
      _set_for_pp('decode' => @_)->decode_prefix($_[1]);
  }
  
  
  sub _incr_parse {
      if (${$_[0]}) {
          _set_for_pp('decode' => @_)->incr_parse($_[1]);
      }
      else {
          $_[0]->_original_incr_parse( $_[1] );
      }
  }
  
  
  sub get_indent_length {
      ${$_[0]} << 4 >> 16;
  }
  
  
  sub indent_length {
      my $length = $_[1];
  
      if (!defined $length or $length > 15 or $length < 0) {
          Carp::carp "The acceptable range of indent_length() is 0 to 15.";
      }
      else {
          local $^W;
          $length <<= 12;
          ${$_[0]} &= ~ JSON::Backend::XS::INDENT_LENGTH_FLAG;
          ${$_[0]} |= $length;
          *JSON::XS::encode = \&JSON::Backend::XS::Supportable::_encode;
      }
  
      $_[0];
  }
  
  
  1;
  __END__
  
  =head1 NAME
  
  JSON - JSON (JavaScript Object Notation) encoder/decoder
  
  =head1 SYNOPSIS
  
   use JSON; # imports encode_json, decode_json, to_json and from_json.
   
   # simple and fast interfaces (expect/generate UTF-8)
   
   $utf8_encoded_json_text = encode_json $perl_hash_or_arrayref;
   $perl_hash_or_arrayref  = decode_json $utf8_encoded_json_text;
   
   # OO-interface
   
   $json = JSON->new->allow_nonref;
   
   $json_text   = $json->encode( $perl_scalar );
   $perl_scalar = $json->decode( $json_text );
   
   $pretty_printed = $json->pretty->encode( $perl_scalar ); # pretty-printing
   
   # If you want to use PP only support features, call with '-support_by_pp'
   # When XS unsupported feature is enable, using PP (de|en)code instead of XS ones.
   
   use JSON -support_by_pp;
   
   # option-acceptable interfaces (expect/generate UNICODE by default)
   
   $json_text   = to_json( $perl_scalar, { ascii => 1, pretty => 1 } );
   $perl_scalar = from_json( $json_text, { utf8  => 1 } );
   
   # Between (en|de)code_json and (to|from)_json, if you want to write
   # a code which communicates to an outer world (encoded in UTF-8),
   # recommend to use (en|de)code_json.
   
  =head1 VERSION
  
      2.90
  
  This version is compatible with JSON::XS B<2.34> and later.
  (Not yet compatble to JSON::XS B<3.0x>.)
  
  
  =head1 NOTE
  
  JSON::PP was earlier included in the C<JSON> distribution, but
  has since Perl 5.14 been a core module. For this reason,
  L<JSON::PP> was removed from the JSON distribution and can now
  be found also in the Perl5 repository at
  
  =over
  
  =item * L<http://perl5.git.perl.org/perl.git>
  
  =back
  
  (The newest JSON::PP version still exists in CPAN.)
  
  Instead, the C<JSON> distribution will include JSON::backportPP
  for backwards computability. JSON.pm should thus work as it did
  before.
  
  =head1 DESCRIPTION
  
   *************************** CAUTION **************************************
   *                                                                        *
   * INCOMPATIBLE CHANGE (JSON::XS version 2.90)                            *
   *                                                                        *
   * JSON.pm had patched JSON::XS::Boolean and JSON::PP::Boolean internally *
   * on loading time for making these modules inherit JSON::Boolean.        *
   * But since JSON::XS v3.0 it use Types::Serialiser as boolean class.     *
   * Then now JSON.pm breaks boolean classe overload features and           *
   * -support_by_pp if JSON::XS v3.0 or later is installed.                 *
   *                                                                        *
   * JSON::true and JSON::false returned JSON::Boolean objects.             *
   * For workaround, they return JSON::PP::Boolean objects in this version. *
   *                                                                        *
   *     isa_ok(JSON::true, 'JSON::PP::Boolean');                           *
   *                                                                        *
   * And it discards a feature:                                             *
   *                                                                        *
   *     ok(JSON::true eq 'true');                                          *
   *                                                                        *
   * In other word, JSON::PP::Boolean overload numeric only.                *
   *                                                                        *
   *     ok( JSON::true == 1 );                                             *
   *                                                                        *
   **************************************************************************
  
   ************************** CAUTION ********************************
   * This is 'JSON module version 2' and there are many differences  *
   * to version 1.xx                                                 *
   * Please check your applications using old version.              *
   *   See to 'INCOMPATIBLE CHANGES TO OLD VERSION'                  *
   *******************************************************************
  
  JSON (JavaScript Object Notation) is a simple data format.
  See to L<http://www.json.org/> and C<RFC4627>(L<http://www.ietf.org/rfc/rfc4627.txt>).
  
  This module converts Perl data structures to JSON and vice versa using either
  L<JSON::XS> or L<JSON::PP>.
  
  JSON::XS is the fastest and most proper JSON module on CPAN which must be
  compiled and installed in your environment.
  JSON::PP is a pure-Perl module which is bundled in this distribution and
  has a strong compatibility to JSON::XS.
  
  This module try to use JSON::XS by default and fail to it, use JSON::PP instead.
  So its features completely depend on JSON::XS or JSON::PP.
  
  See to L<BACKEND MODULE DECISION>.
  
  To distinguish the module name 'JSON' and the format type JSON,
  the former is quoted by CE<lt>E<gt> (its results vary with your using media),
  and the latter is left just as it is.
  
  Module name : C<JSON>
  
  Format type : JSON
  
  =head2 FEATURES
  
  =over
  
  =item * correct unicode handling
  
  This module (i.e. backend modules) knows how to handle Unicode, documents
  how and when it does so, and even documents what "correct" means.
  
  Even though there are limitations, this feature is available since Perl version 5.6.
  
  JSON::XS requires Perl 5.8.2 (but works correctly in 5.8.8 or later), so in older versions
  C<JSON> should call JSON::PP as the backend which can be used since Perl 5.005.
  
  With Perl 5.8.x JSON::PP works, but from 5.8.0 to 5.8.2, because of a Perl side problem,
  JSON::PP works slower in the versions. And in 5.005, the Unicode handling is not available.
  See to L<JSON::PP/UNICODE HANDLING ON PERLS> for more information.
  
  See also to L<JSON::XS/A FEW NOTES ON UNICODE AND PERL>
  and L<JSON::XS/ENCODING/CODESET_FLAG_NOTES>.
  
  
  =item * round-trip integrity
  
  When you serialise a perl data structure using only data types supported
  by JSON and Perl, the deserialised data structure is identical on the Perl
  level. (e.g. the string "2.0" doesn't suddenly become "2" just because
  it looks like a number). There I<are> minor exceptions to this, read the
  L</MAPPING> section below to learn about those.
  
  
  =item * strict checking of JSON correctness
  
  There is no guessing, no generating of illegal JSON texts by default,
  and only JSON is accepted as input by default (the latter is a security
  feature).
  
  See to L<JSON::XS/FEATURES> and L<JSON::PP/FEATURES>.
  
  =item * fast
  
  This module returns a JSON::XS object itself if available.
  Compared to other JSON modules and other serialisers such as Storable,
  JSON::XS usually compares favorably in terms of speed, too.
  
  If not available, C<JSON> returns a JSON::PP object instead of JSON::XS and
  it is very slow as pure-Perl.
  
  =item * simple to use
  
  This module has both a simple functional interface as well as an
  object oriented interface interface.
  
  =item * reasonably versatile output formats
  
  You can choose between the most compact guaranteed-single-line format possible
  (nice for simple line-based protocols), a pure-ASCII format (for when your transport
  is not 8-bit clean, still supports the whole Unicode range), or a pretty-printed
  format (for when you want to read that stuff). Or you can combine those features
  in whatever way you like.
  
  =back
  
  =head1 FUNCTIONAL INTERFACE
  
  Some documents are copied and modified from L<JSON::XS/FUNCTIONAL INTERFACE>.
  C<to_json> and C<from_json> are additional functions.
  
  =head2 encode_json
  
      $json_text = encode_json $perl_scalar
  
  Converts the given Perl data structure to a UTF-8 encoded, binary string.
  
  This function call is functionally identical to:
  
      $json_text = JSON->new->utf8->encode($perl_scalar)
  
  =head2 decode_json
  
      $perl_scalar = decode_json $json_text
  
  The opposite of C<encode_json>: expects an UTF-8 (binary) string and tries
  to parse that as an UTF-8 encoded JSON text, returning the resulting
  reference.
  
  This function call is functionally identical to:
  
      $perl_scalar = JSON->new->utf8->decode($json_text)
  
  
  =head2 to_json
  
     $json_text = to_json($perl_scalar)
  
  Converts the given Perl data structure to a json string.
  
  This function call is functionally identical to:
  
     $json_text = JSON->new->encode($perl_scalar)
  
  Takes a hash reference as the second.
  
     $json_text = to_json($perl_scalar, $flag_hashref)
  
  So,
  
     $json_text = to_json($perl_scalar, {utf8 => 1, pretty => 1})
  
  equivalent to:
  
     $json_text = JSON->new->utf8(1)->pretty(1)->encode($perl_scalar)
  
  If you want to write a modern perl code which communicates to outer world,
  you should use C<encode_json> (supposed that JSON data are encoded in UTF-8).
  
  =head2 from_json
  
     $perl_scalar = from_json($json_text)
  
  The opposite of C<to_json>: expects a json string and tries
  to parse it, returning the resulting reference.
  
  This function call is functionally identical to:
  
      $perl_scalar = JSON->decode($json_text)
  
  Takes a hash reference as the second.
  
      $perl_scalar = from_json($json_text, $flag_hashref)
  
  So,
  
      $perl_scalar = from_json($json_text, {utf8 => 1})
  
  equivalent to:
  
      $perl_scalar = JSON->new->utf8(1)->decode($json_text)
  
  If you want to write a modern perl code which communicates to outer world,
  you should use C<decode_json> (supposed that JSON data are encoded in UTF-8).
  
  =head2 JSON::is_bool
  
      $is_boolean = JSON::is_bool($scalar)
  
  Returns true if the passed scalar represents either JSON::true or
  JSON::false, two constants that act like C<1> and C<0> respectively
  and are also used to represent JSON C<true> and C<false> in Perl strings.
  
  =head2 JSON::true
  
  Returns JSON true value which is blessed object.
  It C<isa> JSON::Boolean object.
  
  =head2 JSON::false
  
  Returns JSON false value which is blessed object.
  It C<isa> JSON::Boolean object.
  
  =head2 JSON::null
  
  Returns C<undef>.
  
  See L<MAPPING>, below, for more information on how JSON values are mapped to
  Perl.
  
  =head1 HOW DO I DECODE A DATA FROM OUTER AND ENCODE TO OUTER
  
  This section supposes that your perl version is 5.8 or later.
  
  If you know a JSON text from an outer world - a network, a file content, and so on,
  is encoded in UTF-8, you should use C<decode_json> or C<JSON> module object
  with C<utf8> enable. And the decoded result will contain UNICODE characters.
  
    # from network
    my $json        = JSON->new->utf8;
    my $json_text   = CGI->new->param( 'json_data' );
    my $perl_scalar = $json->decode( $json_text );
    
    # from file content
    local $/;
    open( my $fh, '<', 'json.data' );
    $json_text   = <$fh>;
    $perl_scalar = decode_json( $json_text );
  
  If an outer data is not encoded in UTF-8, firstly you should C<decode> it.
  
    use Encode;
    local $/;
    open( my $fh, '<', 'json.data' );
    my $encoding = 'cp932';
    my $unicode_json_text = decode( $encoding, <$fh> ); # UNICODE
    
    # or you can write the below code.
    #
    # open( my $fh, "<:encoding($encoding)", 'json.data' );
    # $unicode_json_text = <$fh>;
  
  In this case, C<$unicode_json_text> is of course UNICODE string.
  So you B<cannot> use C<decode_json> nor C<JSON> module object with C<utf8> enable.
  Instead of them, you use C<JSON> module object with C<utf8> disable or C<from_json>.
  
    $perl_scalar = $json->utf8(0)->decode( $unicode_json_text );
    # or
    $perl_scalar = from_json( $unicode_json_text );
  
  Or C<encode 'utf8'> and C<decode_json>:
  
    $perl_scalar = decode_json( encode( 'utf8', $unicode_json_text ) );
    # this way is not efficient.
  
  And now, you want to convert your C<$perl_scalar> into JSON data and
  send it to an outer world - a network or a file content, and so on.
  
  Your data usually contains UNICODE strings and you want the converted data to be encoded
  in UTF-8, you should use C<encode_json> or C<JSON> module object with C<utf8> enable.
  
    print encode_json( $perl_scalar ); # to a network? file? or display?
    # or
    print $json->utf8->encode( $perl_scalar );
  
  If C<$perl_scalar> does not contain UNICODE but C<$encoding>-encoded strings
  for some reason, then its characters are regarded as B<latin1> for perl
  (because it does not concern with your $encoding).
  You B<cannot> use C<encode_json> nor C<JSON> module object with C<utf8> enable.
  Instead of them, you use C<JSON> module object with C<utf8> disable or C<to_json>.
  Note that the resulted text is a UNICODE string but no problem to print it.
  
    # $perl_scalar contains $encoding encoded string values
    $unicode_json_text = $json->utf8(0)->encode( $perl_scalar );
    # or 
    $unicode_json_text = to_json( $perl_scalar );
    # $unicode_json_text consists of characters less than 0x100
    print $unicode_json_text;
  
  Or C<decode $encoding> all string values and C<encode_json>:
  
    $perl_scalar->{ foo } = decode( $encoding, $perl_scalar->{ foo } );
    # ... do it to each string values, then encode_json
    $json_text = encode_json( $perl_scalar );
  
  This method is a proper way but probably not efficient.
  
  See to L<Encode>, L<perluniintro>.
  
  
  =head1 COMMON OBJECT-ORIENTED INTERFACE
  
  =head2 new
  
      $json = JSON->new
  
  Returns a new C<JSON> object inherited from either JSON::XS or JSON::PP
  that can be used to de/encode JSON strings.
  
  All boolean flags described below are by default I<disabled>.
  
  The mutators for flags all return the JSON object again and thus calls can
  be chained:
  
     my $json = JSON->new->utf8->space_after->encode({a => [1,2]})
     => {"a": [1, 2]}
  
  =head2 ascii
  
      $json = $json->ascii([$enable])
      
      $enabled = $json->get_ascii
  
  If $enable is true (or missing), then the encode method will not generate characters outside
  the code range 0..127. Any Unicode characters outside that range will be escaped using either
  a single \uXXXX or a double \uHHHH\uLLLLL escape sequence, as per RFC4627.
  
  If $enable is false, then the encode method will not escape Unicode characters unless
  required by the JSON syntax or other flags. This results in a faster and more compact format.
  
  This feature depends on the used Perl version and environment.
  
  See to L<JSON::PP/UNICODE HANDLING ON PERLS> if the backend is PP.
  
    JSON->new->ascii(1)->encode([chr 0x10401])
    => ["\ud801\udc01"]
  
  =head2 latin1
  
      $json = $json->latin1([$enable])
      
      $enabled = $json->get_latin1
  
  If $enable is true (or missing), then the encode method will encode the resulting JSON
  text as latin1 (or iso-8859-1), escaping any characters outside the code range 0..255.
  
  If $enable is false, then the encode method will not escape Unicode characters
  unless required by the JSON syntax or other flags.
  
    JSON->new->latin1->encode (["\x{89}\x{abc}"]
    => ["\x{89}\\u0abc"]    # (perl syntax, U+abc escaped, U+89 not)
  
  =head2 utf8
  
      $json = $json->utf8([$enable])
      
      $enabled = $json->get_utf8
  
  If $enable is true (or missing), then the encode method will encode the JSON result
  into UTF-8, as required by many protocols, while the decode method expects to be handled
  an UTF-8-encoded string. Please note that UTF-8-encoded strings do not contain any
  characters outside the range 0..255, they are thus useful for bytewise/binary I/O.
  
  In future versions, enabling this option might enable autodetection of the UTF-16 and UTF-32
  encoding families, as described in RFC4627.
  
  If $enable is false, then the encode method will return the JSON string as a (non-encoded)
  Unicode string, while decode expects thus a Unicode string. Any decoding or encoding
  (e.g. to UTF-8 or UTF-16) needs to be done yourself, e.g. using the Encode module.
  
  
  Example, output UTF-16BE-encoded JSON:
  
    use Encode;
    $jsontext = encode "UTF-16BE", JSON::XS->new->encode ($object);
  
  Example, decode UTF-32LE-encoded JSON:
  
    use Encode;
    $object = JSON::XS->new->decode (decode "UTF-32LE", $jsontext);
  
  See to L<JSON::PP/UNICODE HANDLING ON PERLS> if the backend is PP.
  
  
  =head2 pretty
  
      $json = $json->pretty([$enable])
  
  This enables (or disables) all of the C<indent>, C<space_before> and
  C<space_after> (and in the future possibly more) flags in one call to
  generate the most readable (or most compact) form possible.
  
  Equivalent to:
  
     $json->indent->space_before->space_after
  
  The indent space length is three and JSON::XS cannot change the indent
  space length.
  
  =head2 indent
  
      $json = $json->indent([$enable])
      
      $enabled = $json->get_indent
  
  If C<$enable> is true (or missing), then the C<encode> method will use a multiline
  format as output, putting every array member or object/hash key-value pair
  into its own line, identifying them properly.
  
  If C<$enable> is false, no newlines or indenting will be produced, and the
  resulting JSON text is guaranteed not to contain any C<newlines>.
  
  This setting has no effect when decoding JSON texts.
  
  The indent space length is three.
  With JSON::PP, you can also access C<indent_length> to change indent space length.
  
  
  =head2 space_before
  
      $json = $json->space_before([$enable])
      
      $enabled = $json->get_space_before
  
  If C<$enable> is true (or missing), then the C<encode> method will add an extra
  optional space before the C<:> separating keys from values in JSON objects.
  
  If C<$enable> is false, then the C<encode> method will not add any extra
  space at those places.
  
  This setting has no effect when decoding JSON texts.
  
  Example, space_before enabled, space_after and indent disabled:
  
     {"key" :"value"}
  
  
  =head2 space_after
  
      $json = $json->space_after([$enable])
      
      $enabled = $json->get_space_after
  
  If C<$enable> is true (or missing), then the C<encode> method will add an extra
  optional space after the C<:> separating keys from values in JSON objects
  and extra whitespace after the C<,> separating key-value pairs and array
  members.
  
  If C<$enable> is false, then the C<encode> method will not add any extra
  space at those places.
  
  This setting has no effect when decoding JSON texts.
  
  Example, space_before and indent disabled, space_after enabled:
  
     {"key": "value"}
  
  
  =head2 relaxed
  
      $json = $json->relaxed([$enable])
      
      $enabled = $json->get_relaxed
  
  If C<$enable> is true (or missing), then C<decode> will accept some
  extensions to normal JSON syntax (see below). C<encode> will not be
  affected in anyway. I<Be aware that this option makes you accept invalid
  JSON texts as if they were valid!>. I suggest only to use this option to
  parse application-specific files written by humans (configuration files,
  resource files etc.)
  
  If C<$enable> is false (the default), then C<decode> will only accept
  valid JSON texts.
  
  Currently accepted extensions are:
  
  =over 4
  
  =item * list items can have an end-comma
  
  JSON I<separates> array elements and key-value pairs with commas. This
  can be annoying if you write JSON texts manually and want to be able to
  quickly append elements, so this extension accepts comma at the end of
  such items not just between them:
  
     [
        1,
        2, <- this comma not normally allowed
     ]
     {
        "k1": "v1",
        "k2": "v2", <- this comma not normally allowed
     }
  
  =item * shell-style '#'-comments
  
  Whenever JSON allows whitespace, shell-style comments are additionally
  allowed. They are terminated by the first carriage-return or line-feed
  character, after which more white-space and comments are allowed.
  
    [
       1, # this comment not allowed in JSON
          # neither this one...
    ]
  
  =back
  
  
  =head2 canonical
  
      $json = $json->canonical([$enable])
      
      $enabled = $json->get_canonical
  
  If C<$enable> is true (or missing), then the C<encode> method will output JSON objects
  by sorting their keys. This is adding a comparatively high overhead.
  
  If C<$enable> is false, then the C<encode> method will output key-value
  pairs in the order Perl stores them (which will likely change between runs
  of the same script).
  
  This option is useful if you want the same data structure to be encoded as
  the same JSON text (given the same overall settings). If it is disabled,
  the same hash might be encoded differently even if contains the same data,
  as key-value pairs have no inherent ordering in Perl.
  
  This setting has no effect when decoding JSON texts.
  
  =head2 allow_nonref
  
      $json = $json->allow_nonref([$enable])
      
      $enabled = $json->get_allow_nonref
  
  If C<$enable> is true (or missing), then the C<encode> method can convert a
  non-reference into its corresponding string, number or null JSON value,
  which is an extension to RFC4627. Likewise, C<decode> will accept those JSON
  values instead of croaking.
  
  If C<$enable> is false, then the C<encode> method will croak if it isn't
  passed an arrayref or hashref, as JSON texts must either be an object
  or array. Likewise, C<decode> will croak if given something that is not a
  JSON object or array.
  
     JSON->new->allow_nonref->encode ("Hello, World!")
     => "Hello, World!"
  
  =head2 allow_unknown
  
      $json = $json->allow_unknown ([$enable])
      
      $enabled = $json->get_allow_unknown
  
  If $enable is true (or missing), then "encode" will *not* throw an
  exception when it encounters values it cannot represent in JSON (for
  example, filehandles) but instead will encode a JSON "null" value.
  Note that blessed objects are not included here and are handled
  separately by c<allow_nonref>.
  
  If $enable is false (the default), then "encode" will throw an
  exception when it encounters anything it cannot encode as JSON.
  
  This option does not affect "decode" in any way, and it is
  recommended to leave it off unless you know your communications
  partner.
  
  =head2 allow_blessed
  
      $json = $json->allow_blessed([$enable])
      
      $enabled = $json->get_allow_blessed
  
  If C<$enable> is true (or missing), then the C<encode> method will not
  barf when it encounters a blessed reference. Instead, the value of the
  B<convert_blessed> option will decide whether C<null> (C<convert_blessed>
  disabled or no C<TO_JSON> method found) or a representation of the
  object (C<convert_blessed> enabled and C<TO_JSON> method found) is being
  encoded. Has no effect on C<decode>.
  
  If C<$enable> is false (the default), then C<encode> will throw an
  exception when it encounters a blessed object.
  
  
  =head2 convert_blessed
  
      $json = $json->convert_blessed([$enable])
      
      $enabled = $json->get_convert_blessed
  
  If C<$enable> is true (or missing), then C<encode>, upon encountering a
  blessed object, will check for the availability of the C<TO_JSON> method
  on the object's class. If found, it will be called in scalar context
  and the resulting scalar will be encoded instead of the object. If no
  C<TO_JSON> method is found, the value of C<allow_blessed> will decide what
  to do.
  
  The C<TO_JSON> method may safely call die if it wants. If C<TO_JSON>
  returns other blessed objects, those will be handled in the same
  way. C<TO_JSON> must take care of not causing an endless recursion cycle
  (== crash) in this case. The name of C<TO_JSON> was chosen because other
  methods called by the Perl core (== not by the user of the object) are
  usually in upper case letters and to avoid collisions with the C<to_json>
  function or method.
  
  This setting does not yet influence C<decode> in any way.
  
  If C<$enable> is false, then the C<allow_blessed> setting will decide what
  to do when a blessed object is found.
  
  =over
  
  =item convert_blessed_universally mode
  
  If use C<JSON> with C<-convert_blessed_universally>, the C<UNIVERSAL::TO_JSON>
  subroutine is defined as the below code:
  
     *UNIVERSAL::TO_JSON = sub {
         my $b_obj = B::svref_2object( $_[0] );
         return    $b_obj->isa('B::HV') ? { %{ $_[0] } }
                 : $b_obj->isa('B::AV') ? [ @{ $_[0] } ]
                 : undef
                 ;
     }
  
  This will cause that C<encode> method converts simple blessed objects into
  JSON objects as non-blessed object.
  
     JSON -convert_blessed_universally;
     $json->allow_blessed->convert_blessed->encode( $blessed_object )
  
  This feature is experimental and may be removed in the future.
  
  =back
  
  =head2 filter_json_object
  
      $json = $json->filter_json_object([$coderef])
  
  When C<$coderef> is specified, it will be called from C<decode> each
  time it decodes a JSON object. The only argument passed to the coderef
  is a reference to the newly-created hash. If the code references returns
  a single scalar (which need not be a reference), this value
  (i.e. a copy of that scalar to avoid aliasing) is inserted into the
  deserialised data structure. If it returns an empty list
  (NOTE: I<not> C<undef>, which is a valid scalar), the original deserialised
  hash will be inserted. This setting can slow down decoding considerably.
  
  When C<$coderef> is omitted or undefined, any existing callback will
  be removed and C<decode> will not change the deserialised hash in any
  way.
  
  Example, convert all JSON objects into the integer 5:
  
     my $js = JSON->new->filter_json_object (sub { 5 });
     # returns [5]
     $js->decode ('[{}]'); # the given subroutine takes a hash reference.
     # throw an exception because allow_nonref is not enabled
     # so a lone 5 is not allowed.
     $js->decode ('{"a":1, "b":2}');
  
  
  =head2 filter_json_single_key_object
  
      $json = $json->filter_json_single_key_object($key [=> $coderef])
  
  Works remotely similar to C<filter_json_object>, but is only called for
  JSON objects having a single key named C<$key>.
  
  This C<$coderef> is called before the one specified via
  C<filter_json_object>, if any. It gets passed the single value in the JSON
  object. If it returns a single value, it will be inserted into the data
  structure. If it returns nothing (not even C<undef> but the empty list),
  the callback from C<filter_json_object> will be called next, as if no
  single-key callback were specified.
  
  If C<$coderef> is omitted or undefined, the corresponding callback will be
  disabled. There can only ever be one callback for a given key.
  
  As this callback gets called less often then the C<filter_json_object>
  one, decoding speed will not usually suffer as much. Therefore, single-key
  objects make excellent targets to serialise Perl objects into, especially
  as single-key JSON objects are as close to the type-tagged value concept
  as JSON gets (it's basically an ID/VALUE tuple). Of course, JSON does not
  support this in any way, so you need to make sure your data never looks
  like a serialised Perl hash.
  
  Typical names for the single object key are C<__class_whatever__>, or
  C<$__dollars_are_rarely_used__$> or C<}ugly_brace_placement>, or even
  things like C<__class_md5sum(classname)__>, to reduce the risk of clashing
  with real hashes.
  
  Example, decode JSON objects of the form C<< { "__widget__" => <id> } >>
  into the corresponding C<< $WIDGET{<id>} >> object:
  
     # return whatever is in $WIDGET{5}:
     JSON
        ->new
        ->filter_json_single_key_object (__widget__ => sub {
              $WIDGET{ $_[0] }
           })
        ->decode ('{"__widget__": 5')
  
     # this can be used with a TO_JSON method in some "widget" class
     # for serialisation to json:
     sub WidgetBase::TO_JSON {
        my ($self) = @_;
  
        unless ($self->{id}) {
           $self->{id} = ..get..some..id..;
           $WIDGET{$self->{id}} = $self;
        }
  
        { __widget__ => $self->{id} }
     }
  
  
  =head2 shrink
  
      $json = $json->shrink([$enable])
      
      $enabled = $json->get_shrink
  
  With JSON::XS, this flag resizes strings generated by either
  C<encode> or C<decode> to their minimum size possible. This can save
  memory when your JSON texts are either very very long or you have many
  short strings. It will also try to downgrade any strings to octet-form
  if possible: perl stores strings internally either in an encoding called
  UTF-X or in octet-form. The latter cannot store everything but uses less
  space in general (and some buggy Perl or C code might even rely on that
  internal representation being used).
  
  With JSON::PP, it is noop about resizing strings but tries
  C<utf8::downgrade> to the returned string by C<encode>. See to L<utf8>.
  
  See to L<JSON::XS/OBJECT-ORIENTED INTERFACE> and L<JSON::PP/METHODS>.
  
  =head2 max_depth
  
      $json = $json->max_depth([$maximum_nesting_depth])
      
      $max_depth = $json->get_max_depth
  
  Sets the maximum nesting level (default C<512>) accepted while encoding
  or decoding. If a higher nesting level is detected in JSON text or a Perl
  data structure, then the encoder and decoder will stop and croak at that
  point.
  
  Nesting level is defined by number of hash- or arrayrefs that the encoder
  needs to traverse to reach a given point or the number of C<{> or C<[>
  characters without their matching closing parenthesis crossed to reach a
  given character in a string.
  
  If no argument is given, the highest possible setting will be used, which
  is rarely useful.
  
  Note that nesting is implemented by recursion in C. The default value has
  been chosen to be as large as typical operating systems allow without
  crashing. (JSON::XS)
  
  With JSON::PP as the backend, when a large value (100 or more) was set and
  it de/encodes a deep nested object/text, it may raise a warning
  'Deep recursion on subroutine' at the perl runtime phase.
  
  See L<JSON::XS/SECURITY CONSIDERATIONS> for more info on why this is useful.
  
  =head2 max_size
  
      $json = $json->max_size([$maximum_string_size])
      
      $max_size = $json->get_max_size
  
  Set the maximum length a JSON text may have (in bytes) where decoding is
  being attempted. The default is C<0>, meaning no limit. When C<decode>
  is called on a string that is longer then this many bytes, it will not
  attempt to decode the string but throw an exception. This setting has no
  effect on C<encode> (yet).
  
  If no argument is given, the limit check will be deactivated (same as when
  C<0> is specified).
  
  See L<JSON::XS/SECURITY CONSIDERATIONS>, below, for more info on why this is useful.
  
  =head2 encode
  
      $json_text = $json->encode($perl_scalar)
  
  Converts the given Perl data structure (a simple scalar or a reference
  to a hash or array) to its JSON representation. Simple scalars will be
  converted into JSON string or number sequences, while references to arrays
  become JSON arrays and references to hashes become JSON objects. Undefined
  Perl values (e.g. C<undef>) become JSON C<null> values.
  References to the integers C<0> and C<1> are converted into C<true> and C<false>.
  
  =head2 decode
  
      $perl_scalar = $json->decode($json_text)
  
  The opposite of C<encode>: expects a JSON text and tries to parse it,
  returning the resulting simple scalar or reference. Croaks on error.
  
  JSON numbers and strings become simple Perl scalars. JSON arrays become
  Perl arrayrefs and JSON objects become Perl hashrefs. C<true> becomes
  C<1> (C<JSON::true>), C<false> becomes C<0> (C<JSON::false>) and
  C<null> becomes C<undef>.
  
  =head2 decode_prefix
  
      ($perl_scalar, $characters) = $json->decode_prefix($json_text)
  
  This works like the C<decode> method, but instead of raising an exception
  when there is trailing garbage after the first JSON object, it will
  silently stop parsing there and return the number of characters consumed
  so far.
  
     JSON->new->decode_prefix ("[1] the tail")
     => ([], 3)
  
  See to L<JSON::XS/OBJECT-ORIENTED INTERFACE>
  
  =head2 property
  
      $boolean = $json->property($property_name)
  
  Returns a boolean value about above some properties.
  
  The available properties are C<ascii>, C<latin1>, C<utf8>,
  C<indent>,C<space_before>, C<space_after>, C<relaxed>, C<canonical>,
  C<allow_nonref>, C<allow_unknown>, C<allow_blessed>, C<convert_blessed>,
  C<shrink>, C<max_depth> and C<max_size>.
  
     $boolean = $json->property('utf8');
      => 0
     $json->utf8;
     $boolean = $json->property('utf8');
      => 1
  
  Sets the property with a given boolean value.
  
      $json = $json->property($property_name => $boolean);
  
  With no argument, it returns all the above properties as a hash reference.
  
      $flag_hashref = $json->property();
  
  =head1 INCREMENTAL PARSING
  
  Most of this section are copied and modified from L<JSON::XS/INCREMENTAL PARSING>.
  
  In some cases, there is the need for incremental parsing of JSON texts.
  This module does allow you to parse a JSON stream incrementally.
  It does so by accumulating text until it has a full JSON object, which
  it then can decode. This process is similar to using C<decode_prefix>
  to see if a full JSON object is available, but is much more efficient
  (and can be implemented with a minimum of method calls).
  
  The backend module will only attempt to parse the JSON text once it is sure it
  has enough text to get a decisive result, using a very simple but
  truly incremental parser. This means that it sometimes won't stop as
  early as the full parser, for example, it doesn't detect parenthesis
  mismatches. The only thing it guarantees is that it starts decoding as
  soon as a syntactically valid JSON text has been seen. This means you need
  to set resource limits (e.g. C<max_size>) to ensure the parser will stop
  parsing in the presence if syntax errors.
  
  The following methods implement this incremental parser.
  
  =head2 incr_parse
  
      $json->incr_parse( [$string] ) # void context
      
      $obj_or_undef = $json->incr_parse( [$string] ) # scalar context
      
      @obj_or_empty = $json->incr_parse( [$string] ) # list context
  
  This is the central parsing function. It can both append new text and
  extract objects from the stream accumulated so far (both of these
  functions are optional).
  
  If C<$string> is given, then this string is appended to the already
  existing JSON fragment stored in the C<$json> object.
  
  After that, if the function is called in void context, it will simply
  return without doing anything further. This can be used to add more text
  in as many chunks as you want.
  
  If the method is called in scalar context, then it will try to extract
  exactly I<one> JSON object. If that is successful, it will return this
  object, otherwise it will return C<undef>. If there is a parse error,
  this method will croak just as C<decode> would do (one can then use
  C<incr_skip> to skip the erroneous part). This is the most common way of
  using the method.
  
  And finally, in list context, it will try to extract as many objects
  from the stream as it can find and return them, or the empty list
  otherwise. For this to work, there must be no separators between the JSON
  objects or arrays, instead they must be concatenated back-to-back. If
  an error occurs, an exception will be raised as in the scalar context
  case. Note that in this case, any previously-parsed JSON texts will be
  lost.
  
  Example: Parse some JSON arrays/objects in a given string and return them.
  
      my @objs = JSON->new->incr_parse ("[5][7][1,2]");
  
  =head2 incr_text
  
      $lvalue_string = $json->incr_text
  
  This method returns the currently stored JSON fragment as an lvalue, that
  is, you can manipulate it. This I<only> works when a preceding call to
  C<incr_parse> in I<scalar context> successfully returned an object. Under
  all other circumstances you must not call this function (I mean it.
  although in simple tests it might actually work, it I<will> fail under
  real world conditions). As a special exception, you can also call this
  method before having parsed anything.
  
  This function is useful in two cases: a) finding the trailing text after a
  JSON object or b) parsing multiple JSON objects separated by non-JSON text
  (such as commas).
  
      $json->incr_text =~ s/\s*,\s*//;
  
  In Perl 5.005, C<lvalue> attribute is not available.
  You must write codes like the below:
  
      $string = $json->incr_text;
      $string =~ s/\s*,\s*//;
      $json->incr_text( $string );
  
  =head2 incr_skip
  
      $json->incr_skip
  
  This will reset the state of the incremental parser and will remove the
  parsed text from the input buffer. This is useful after C<incr_parse>
  died, in which case the input buffer and incremental parser state is left
  unchanged, to skip the text parsed so far and to reset the parse state.
  
  =head2 incr_reset
  
      $json->incr_reset
  
  This completely resets the incremental parser, that is, after this call,
  it will be as if the parser had never parsed anything.
  
  This is useful if you want to repeatedly parse JSON objects and want to
  ignore any trailing data, which means you have to reset the parser after
  each successful decode.
  
  See to L<JSON::XS/INCREMENTAL PARSING> for examples.
  
  
  =head1 JSON::PP SUPPORT METHODS
  
  The below methods are JSON::PP own methods, so when C<JSON> works
  with JSON::PP (i.e. the created object is a JSON::PP object), available.
  See to L<JSON::PP/JSON::PP OWN METHODS> in detail.
  
  If you use C<JSON> with additional C<-support_by_pp>, some methods
  are available even with JSON::XS. See to L<USE PP FEATURES EVEN THOUGH XS BACKEND>.
  
     BEING { $ENV{PERL_JSON_BACKEND} = 'JSON::XS' }
     
     use JSON -support_by_pp;
     
     my $json = JSON->new;
     $json->allow_nonref->escape_slash->encode("/");
  
     # functional interfaces too.
     print to_json(["/"], {escape_slash => 1});
     print from_json('["foo"]', {utf8 => 1});
  
  If you do not want to all functions but C<-support_by_pp>,
  use C<-no_export>.
  
     use JSON -support_by_pp, -no_export;
     # functional interfaces are not exported.
  
  =head2 allow_singlequote
  
      $json = $json->allow_singlequote([$enable])
  
  If C<$enable> is true (or missing), then C<decode> will accept
  any JSON strings quoted by single quotations that are invalid JSON
  format.
  
      $json->allow_singlequote->decode({"foo":'bar'});
      $json->allow_singlequote->decode({'foo':"bar"});
      $json->allow_singlequote->decode({'foo':'bar'});
  
  As same as the C<relaxed> option, this option may be used to parse
  application-specific files written by humans.
  
  =head2 allow_barekey
  
      $json = $json->allow_barekey([$enable])
  
  If C<$enable> is true (or missing), then C<decode> will accept
  bare keys of JSON object that are invalid JSON format.
  
  As same as the C<relaxed> option, this option may be used to parse
  application-specific files written by humans.
  
      $json->allow_barekey->decode('{foo:"bar"}');
  
  =head2 allow_bignum
  
      $json = $json->allow_bignum([$enable])
  
  If C<$enable> is true (or missing), then C<decode> will convert
  the big integer Perl cannot handle as integer into a L<Math::BigInt>
  object and convert a floating number (any) into a L<Math::BigFloat>.
  
  On the contrary, C<encode> converts C<Math::BigInt> objects and C<Math::BigFloat>
  objects into JSON numbers with C<allow_blessed> enable.
  
     $json->allow_nonref->allow_blessed->allow_bignum;
     $bigfloat = $json->decode('2.000000000000000000000000001');
     print $json->encode($bigfloat);
     # => 2.000000000000000000000000001
  
  See to L<MAPPING> about the conversion of JSON number.
  
  =head2 loose
  
      $json = $json->loose([$enable])
  
  The unescaped [\x00-\x1f\x22\x2f\x5c] strings are invalid in JSON strings
  and the module doesn't allow to C<decode> to these (except for \x2f).
  If C<$enable> is true (or missing), then C<decode>  will accept these
  unescaped strings.
  
      $json->loose->decode(qq|["abc
                                     def"]|);
  
  See to L<JSON::PP/JSON::PP OWN METHODS>.
  
  =head2 escape_slash
  
      $json = $json->escape_slash([$enable])
  
  According to JSON Grammar, I<slash> (U+002F) is escaped. But by default
  JSON backend modules encode strings without escaping slash.
  
  If C<$enable> is true (or missing), then C<encode> will escape slashes.
  
  =head2 indent_length
  
      $json = $json->indent_length($length)
  
  With JSON::XS, The indent space length is 3 and cannot be changed.
  With JSON::PP, it sets the indent space length with the given $length.
  The default is 3. The acceptable range is 0 to 15.
  
  =head2 sort_by
  
      $json = $json->sort_by($function_name)
      $json = $json->sort_by($subroutine_ref)
  
  If $function_name or $subroutine_ref are set, its sort routine are used.
  
     $js = $pc->sort_by(sub { $JSON::PP::a cmp $JSON::PP::b })->encode($obj);
     # is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|);
  
     $js = $pc->sort_by('own_sort')->encode($obj);
     # is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|);
  
     sub JSON::PP::own_sort { $JSON::PP::a cmp $JSON::PP::b }
  
  As the sorting routine runs in the JSON::PP scope, the given
  subroutine name and the special variables C<$a>, C<$b> will begin
  with 'JSON::PP::'.
  
  If $integer is set, then the effect is same as C<canonical> on.
  
  See to L<JSON::PP/JSON::PP OWN METHODS>.
  
  =head1 MAPPING
  
  This section is copied from JSON::XS and modified to C<JSON>.
  JSON::XS and JSON::PP mapping mechanisms are almost equivalent.
  
  See to L<JSON::XS/MAPPING>.
  
  =head2 JSON -> PERL
  
  =over 4
  
  =item object
  
  A JSON object becomes a reference to a hash in Perl. No ordering of object
  keys is preserved (JSON does not preserver object key ordering itself).
  
  =item array
  
  A JSON array becomes a reference to an array in Perl.
  
  =item string
  
  A JSON string becomes a string scalar in Perl - Unicode codepoints in JSON
  are represented by the same codepoints in the Perl string, so no manual
  decoding is necessary.
  
  =item number
  
  A JSON number becomes either an integer, numeric (floating point) or
  string scalar in perl, depending on its range and any fractional parts. On
  the Perl level, there is no difference between those as Perl handles all
  the conversion details, but an integer may take slightly less memory and
  might represent more values exactly than floating point numbers.
  
  If the number consists of digits only, C<JSON> will try to represent
  it as an integer value. If that fails, it will try to represent it as
  a numeric (floating point) value if that is possible without loss of
  precision. Otherwise it will preserve the number as a string value (in
  which case you lose roundtripping ability, as the JSON number will be
  re-encoded to a JSON string).
  
  Numbers containing a fractional or exponential part will always be
  represented as numeric (floating point) values, possibly at a loss of
  precision (in which case you might lose perfect roundtripping ability, but
  the JSON number will still be re-encoded as a JSON number).
  
  Note that precision is not accuracy - binary floating point values cannot
  represent most decimal fractions exactly, and when converting from and to
  floating point, C<JSON> only guarantees precision up to but not including
  the least significant bit.
  
  If the backend is JSON::PP and C<allow_bignum> is enable, the big integers 
  and the numeric can be optionally converted into L<Math::BigInt> and
  L<Math::BigFloat> objects.
  
  =item true, false
  
  These JSON atoms become C<JSON::true> and C<JSON::false>,
  respectively. They are overloaded to act almost exactly like the numbers
  C<1> and C<0>. You can check whether a scalar is a JSON boolean by using
  the C<JSON::is_bool> function.
  
     print JSON::true + 1;
      => 1
  
     ok(JSON::true eq  '1');
     ok(JSON::true == 1);
  
  C<JSON> will install these missing overloading features to the backend modules.
  
  
  =item null
  
  A JSON null atom becomes C<undef> in Perl.
  
  C<JSON::null> returns C<undef>.
  
  =back
  
  
  =head2 PERL -> JSON
  
  The mapping from Perl to JSON is slightly more difficult, as Perl is a
  truly typeless language, so we can only guess which JSON type is meant by
  a Perl value.
  
  =over 4
  
  =item hash references
  
  Perl hash references become JSON objects. As there is no inherent ordering
  in hash keys (or JSON objects), they will usually be encoded in a
  pseudo-random order that can change between runs of the same program but
  stays generally the same within a single run of a program. C<JSON>
  optionally sort the hash keys (determined by the I<canonical> flag), so
  the same data structure will serialise to the same JSON text (given same
  settings and version of JSON::XS), but this incurs a runtime overhead
  and is only rarely useful, e.g. when you want to compare some JSON text
  against another for equality.
  
  In future, the ordered object feature will be added to JSON::PP using C<tie> mechanism.
  
  
  =item array references
  
  Perl array references become JSON arrays.
  
  =item other references
  
  Other unblessed references are generally not allowed and will cause an
  exception to be thrown, except for references to the integers C<0> and
  C<1>, which get turned into C<false> and C<true> atoms in JSON. You can
  also use C<JSON::false> and C<JSON::true> to improve readability.
  
     to_json [\0,JSON::true]      # yields [false,true]
  
  =item JSON::true, JSON::false, JSON::null
  
  These special values become JSON true and JSON false values,
  respectively. You can also use C<\1> and C<\0> directly if you want.
  
  JSON::null returns C<undef>.
  
  =item blessed objects
  
  Blessed objects are not directly representable in JSON. See the
  C<allow_blessed> and C<convert_blessed> methods on various options on
  how to deal with this: basically, you can choose between throwing an
  exception, encoding the reference as if it weren't blessed, or provide
  your own serialiser method.
  
  With C<convert_blessed_universally> mode,  C<encode> converts blessed
  hash references or blessed array references (contains other blessed references)
  into JSON members and arrays.
  
     use JSON -convert_blessed_universally;
     JSON->new->allow_blessed->convert_blessed->encode( $blessed_object );
  
  See to L<convert_blessed>.
  
  =item simple scalars
  
  Simple Perl scalars (any scalar that is not a reference) are the most
  difficult objects to encode: JSON::XS and JSON::PP will encode undefined scalars as
  JSON C<null> values, scalars that have last been used in a string context
  before encoding as JSON strings, and anything else as number value:
  
     # dump as number
     encode_json [2]                      # yields [2]
     encode_json [-3.0e17]                # yields [-3e+17]
     my $value = 5; encode_json [$value]  # yields [5]
  
     # used as string, so dump as string
     print $value;
     encode_json [$value]                 # yields ["5"]
  
     # undef becomes null
     encode_json [undef]                  # yields [null]
  
  You can force the type to be a string by stringifying it:
  
     my $x = 3.1; # some variable containing a number
     "$x";        # stringified
     $x .= "";    # another, more awkward way to stringify
     print $x;    # perl does it for you, too, quite often
  
  You can force the type to be a number by numifying it:
  
     my $x = "3"; # some variable containing a string
     $x += 0;     # numify it, ensuring it will be dumped as a number
     $x *= 1;     # same thing, the choice is yours.
  
  You can not currently force the type in other, less obscure, ways.
  
  Note that numerical precision has the same meaning as under Perl (so
  binary to decimal conversion follows the same rules as in Perl, which
  can differ to other languages). Also, your perl interpreter might expose
  extensions to the floating point numbers of your platform, such as
  infinities or NaN's - these cannot be represented in JSON, and it is an
  error to pass those in.
  
  =item Big Number
  
  If the backend is JSON::PP and C<allow_bignum> is enable, 
  C<encode> converts C<Math::BigInt> objects and C<Math::BigFloat>
  objects into JSON numbers.
  
  
  =back
  
  =head1 JSON and ECMAscript
  
  See to L<JSON::XS/JSON and ECMAscript>.
  
  =head1 JSON and YAML
  
  JSON is not a subset of YAML.
  See to L<JSON::XS/JSON and YAML>.
  
  
  =head1 BACKEND MODULE DECISION
  
  When you use C<JSON>, C<JSON> tries to C<use> JSON::XS. If this call failed, it will
  C<uses> JSON::PP. The required JSON::XS version is I<2.2> or later.
  
  The C<JSON> constructor method returns an object inherited from the backend module,
  and JSON::XS object is a blessed scalar reference while JSON::PP is a blessed hash
  reference.
  
  So, your program should not depend on the backend module, especially
  returned objects should not be modified.
  
   my $json = JSON->new; # XS or PP?
   $json->{stash} = 'this is xs object'; # this code may raise an error!
  
  To check the backend module, there are some methods - C<backend>, C<is_pp> and C<is_xs>.
  
    JSON->backend; # 'JSON::XS' or 'JSON::PP'
    
    JSON->backend->is_pp: # 0 or 1
    
    JSON->backend->is_xs: # 1 or 0
    
    $json->is_xs; # 1 or 0
    
    $json->is_pp; # 0 or 1
  
  
  If you set an environment variable C<PERL_JSON_BACKEND>, the calling action will be changed.
  
  =over
  
  =item PERL_JSON_BACKEND = 0 or PERL_JSON_BACKEND = 'JSON::PP'
  
  Always use JSON::PP
  
  =item PERL_JSON_BACKEND == 1 or PERL_JSON_BACKEND = 'JSON::XS,JSON::PP'
  
  (The default) Use compiled JSON::XS if it is properly compiled & installed,
  otherwise use JSON::PP.
  
  =item PERL_JSON_BACKEND == 2 or PERL_JSON_BACKEND = 'JSON::XS'
  
  Always use compiled JSON::XS, die if it isn't properly compiled & installed.
  
  =item PERL_JSON_BACKEND = 'JSON::backportPP'
  
  Always use JSON::backportPP.
  JSON::backportPP is JSON::PP back port module.
  C<JSON> includes JSON::backportPP instead of JSON::PP.
  
  =back
  
  These ideas come from L<DBI::PurePerl> mechanism.
  
  example:
  
   BEGIN { $ENV{PERL_JSON_BACKEND} = 'JSON::PP' }
   use JSON; # always uses JSON::PP
  
  In future, it may be able to specify another module.
  
  =head1 USE PP FEATURES EVEN THOUGH XS BACKEND
  
  Many methods are available with either JSON::XS or JSON::PP and
  when the backend module is JSON::XS, if any JSON::PP specific (i.e. JSON::XS unsupported)
  method is called, it will C<warn> and be noop.
  
  But If you C<use> C<JSON> passing the optional string C<-support_by_pp>,
  it makes a part of those unsupported methods available.
  This feature is achieved by using JSON::PP in C<de/encode>.
  
     BEGIN { $ENV{PERL_JSON_BACKEND} = 2 } # with JSON::XS
     use JSON -support_by_pp;
     my $json = JSON->new;
     $json->allow_nonref->escape_slash->encode("/");
  
  At this time, the returned object is a C<JSON::Backend::XS::Supportable>
  object (re-blessed XS object), and  by checking JSON::XS unsupported flags
  in de/encoding, can support some unsupported methods - C<loose>, C<allow_bignum>,
  C<allow_barekey>, C<allow_singlequote>, C<escape_slash> and C<indent_length>.
  
  When any unsupported methods are not enable, C<XS de/encode> will be
  used as is. The switch is achieved by changing the symbolic tables.
  
  C<-support_by_pp> is effective only when the backend module is JSON::XS
  and it makes the de/encoding speed down a bit.
  
  See to L<JSON::PP SUPPORT METHODS>.
  
  =head1 INCOMPATIBLE CHANGES TO OLD VERSION
  
  There are big incompatibility between new version (2.00) and old (1.xx).
  If you use old C<JSON> 1.xx in your code, please check it.
  
  See to L<Transition ways from 1.xx to 2.xx.>
  
  =over
  
  =item jsonToObj and objToJson are obsoleted.
  
  Non Perl-style name C<jsonToObj> and C<objToJson> are obsoleted
  (but not yet deleted from the source).
  If you use these functions in your code, please replace them
  with C<from_json> and C<to_json>.
  
  
  =item Global variables are no longer available.
  
  C<JSON> class variables - C<$JSON::AUTOCONVERT>, C<$JSON::BareKey>, etc...
  - are not available any longer.
  Instead, various features can be used through object methods.
  
  
  =item Package JSON::Converter and JSON::Parser are deleted.
  
  Now C<JSON> bundles with JSON::PP which can handle JSON more properly than them.
  
  =item Package JSON::NotString is deleted.
  
  There was C<JSON::NotString> class which represents JSON value C<true>, C<false>, C<null>
  and numbers. It was deleted and replaced by C<JSON::Boolean>.
  
  C<JSON::Boolean> represents C<true> and C<false>.
  
  C<JSON::Boolean> does not represent C<null>.
  
  C<JSON::null> returns C<undef>.
  
  C<JSON> makes L<JSON::XS::Boolean> and L<JSON::PP::Boolean> is-a relation
  to L<JSON::Boolean>.
  
  =item function JSON::Number is obsoleted.
  
  C<JSON::Number> is now needless because JSON::XS and JSON::PP have
  round-trip integrity.
  
  =item JSONRPC modules are deleted.
  
  Perl implementation of JSON-RPC protocol - C<JSONRPC >, C<JSONRPC::Transport::HTTP>
  and C<Apache::JSONRPC > are deleted in this distribution.
  Instead of them, there is L<JSON::RPC> which supports JSON-RPC protocol version 1.1.
  
  =back
  
  =head2 Transition ways from 1.xx to 2.xx.
  
  You should set C<suport_by_pp> mode firstly, because
  it is always successful for the below codes even with JSON::XS.
  
      use JSON -support_by_pp;
  
  =over
  
  =item Exported jsonToObj (simple)
  
    from_json($json_text);
  
  =item Exported objToJson (simple)
  
    to_json($perl_scalar);
  
  =item Exported jsonToObj (advanced)
  
    $flags = {allow_barekey => 1, allow_singlequote => 1};
    from_json($json_text, $flags);
  
  equivalent to:
  
    $JSON::BareKey = 1;
    $JSON::QuotApos = 1;
    jsonToObj($json_text);
  
  =item Exported objToJson (advanced)
  
    $flags = {allow_blessed => 1, allow_barekey => 1};
    to_json($perl_scalar, $flags);
  
  equivalent to:
  
    $JSON::BareKey = 1;
    objToJson($perl_scalar);
  
  =item jsonToObj as object method
  
    $json->decode($json_text);
  
  =item objToJson as object method
  
    $json->encode($perl_scalar);
  
  =item new method with parameters
  
  The C<new> method in 2.x takes any parameters no longer.
  You can set parameters instead;
  
     $json = JSON->new->pretty;
  
  =item $JSON::Pretty, $JSON::Indent, $JSON::Delimiter
  
  If C<indent> is enable, that means C<$JSON::Pretty> flag set. And
  C<$JSON::Delimiter> was substituted by C<space_before> and C<space_after>.
  In conclusion:
  
     $json->indent->space_before->space_after;
  
  Equivalent to:
  
    $json->pretty;
  
  To change indent length, use C<indent_length>.
  
  (Only with JSON::PP, if C<-support_by_pp> is not used.)
  
    $json->pretty->indent_length(2)->encode($perl_scalar);
  
  =item $JSON::BareKey
  
  (Only with JSON::PP, if C<-support_by_pp> is not used.)
  
    $json->allow_barekey->decode($json_text)
  
  =item $JSON::ConvBlessed
  
  use C<-convert_blessed_universally>. See to L<convert_blessed>.
  
  =item $JSON::QuotApos
  
  (Only with JSON::PP, if C<-support_by_pp> is not used.)
  
    $json->allow_singlequote->decode($json_text)
  
  =item $JSON::SingleQuote
  
  Disable. C<JSON> does not make such a invalid JSON string any longer.
  
  =item $JSON::KeySort
  
    $json->canonical->encode($perl_scalar)
  
  This is the ascii sort.
  
  If you want to use with your own sort routine, check the C<sort_by> method.
  
  (Only with JSON::PP, even if C<-support_by_pp> is used currently.)
  
    $json->sort_by($sort_routine_ref)->encode($perl_scalar)
   
    $json->sort_by(sub { $JSON::PP::a <=> $JSON::PP::b })->encode($perl_scalar)
  
  Can't access C<$a> and C<$b> but C<$JSON::PP::a> and C<$JSON::PP::b>.
  
  =item $JSON::SkipInvalid
  
    $json->allow_unknown
  
  =item $JSON::AUTOCONVERT
  
  Needless. C<JSON> backend modules have the round-trip integrity.
  
  =item $JSON::UTF8
  
  Needless because C<JSON> (JSON::XS/JSON::PP) sets
  the UTF8 flag on properly.
  
      # With UTF8-flagged strings
  
      $json->allow_nonref;
      $str = chr(1000); # UTF8-flagged
  
      $json_text  = $json->utf8(0)->encode($str);
      utf8::is_utf8($json_text);
      # true
      $json_text  = $json->utf8(1)->encode($str);
      utf8::is_utf8($json_text);
      # false
  
      $str = '"' . chr(1000) . '"'; # UTF8-flagged
  
      $perl_scalar  = $json->utf8(0)->decode($str);
      utf8::is_utf8($perl_scalar);
      # true
      $perl_scalar  = $json->utf8(1)->decode($str);
      # died because of 'Wide character in subroutine'
  
  See to L<JSON::XS/A FEW NOTES ON UNICODE AND PERL>.
  
  =item $JSON::UnMapping
  
  Disable. See to L<MAPPING>.
  
  =item $JSON::SelfConvert
  
  This option was deleted.
  Instead of it, if a given blessed object has the C<TO_JSON> method,
  C<TO_JSON> will be executed with C<convert_blessed>.
  
    $json->convert_blessed->encode($blessed_hashref_or_arrayref)
    # if need, call allow_blessed
  
  Note that it was C<toJson> in old version, but now not C<toJson> but C<TO_JSON>.
  
  =back
  
  =head1 TODO
  
  =over
  
  =item example programs
  
  =back
  
  =head1 THREADS
  
  No test with JSON::PP. If with JSON::XS, See to L<JSON::XS/THREADS>.
  
  
  =head1 BUGS
  
  Please report bugs relevant to C<JSON> to E<lt>makamaka[at]cpan.orgE<gt>.
  
  
  =head1 SEE ALSO
  
  Most of the document is copied and modified from JSON::XS doc.
  
  L<JSON::XS>, L<JSON::PP>
  
  C<RFC4627>(L<http://www.ietf.org/rfc/rfc4627.txt>)
  
  =head1 AUTHOR
  
  Makamaka Hannyaharamitu, E<lt>makamaka[at]cpan.orgE<gt>
  
  JSON::XS was written by  Marc Lehmann <schmorp[at]schmorp.de>
  
  The release of this new version owes to the courtesy of Marc Lehmann.
  
  
  =head1 COPYRIGHT AND LICENSE
  
  Copyright 2005-2013 by Makamaka Hannyaharamitu
  
  This library is free software; you can redistribute it and/or modify
  it under the same terms as Perl itself. 
  
  =cut
  
JSON

$fatpacked{"JSON/backportPP.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'JSON_BACKPORTPP';
  package # This is JSON::backportPP
      JSON::PP;
  
  # JSON-2.0
  
  use 5.005;
  use strict;
  use base qw(Exporter);
  use overload ();
  
  use Carp ();
  use B ();
  #use Devel::Peek;
  
  use vars qw($VERSION);
  $VERSION = '2.27204';
  
  @JSON::PP::EXPORT = qw(encode_json decode_json from_json to_json);
  
  # instead of hash-access, i tried index-access for speed.
  # but this method is not faster than what i expected. so it will be changed.
  
  use constant P_ASCII                => 0;
  use constant P_LATIN1               => 1;
  use constant P_UTF8                 => 2;
  use constant P_INDENT               => 3;
  use constant P_CANONICAL            => 4;
  use constant P_SPACE_BEFORE         => 5;
  use constant P_SPACE_AFTER          => 6;
  use constant P_ALLOW_NONREF         => 7;
  use constant P_SHRINK               => 8;
  use constant P_ALLOW_BLESSED        => 9;
  use constant P_CONVERT_BLESSED      => 10;
  use constant P_RELAXED              => 11;
  
  use constant P_LOOSE                => 12;
  use constant P_ALLOW_BIGNUM         => 13;
  use constant P_ALLOW_BAREKEY        => 14;
  use constant P_ALLOW_SINGLEQUOTE    => 15;
  use constant P_ESCAPE_SLASH         => 16;
  use constant P_AS_NONBLESSED        => 17;
  
  use constant P_ALLOW_UNKNOWN        => 18;
  
  use constant OLD_PERL => $] < 5.008 ? 1 : 0;
  
  BEGIN {
      my @xs_compati_bit_properties = qw(
              latin1 ascii utf8 indent canonical space_before space_after allow_nonref shrink
              allow_blessed convert_blessed relaxed allow_unknown
      );
      my @pp_bit_properties = qw(
              allow_singlequote allow_bignum loose
              allow_barekey escape_slash as_nonblessed
      );
  
      # Perl version check, Unicode handling is enable?
      # Helper module sets @JSON::PP::_properties.
      if ($] < 5.008 ) {
          my $helper = $] >= 5.006 ? 'JSON::backportPP::Compat5006' : 'JSON::backportPP::Compat5005';
          eval qq| require $helper |;
          if ($@) { Carp::croak $@; }
      }
  
      for my $name (@xs_compati_bit_properties, @pp_bit_properties) {
          my $flag_name = 'P_' . uc($name);
  
          eval qq/
              sub $name {
                  my \$enable = defined \$_[1] ? \$_[1] : 1;
  
                  if (\$enable) {
                      \$_[0]->{PROPS}->[$flag_name] = 1;
                  }
                  else {
                      \$_[0]->{PROPS}->[$flag_name] = 0;
                  }
  
                  \$_[0];
              }
  
              sub get_$name {
                  \$_[0]->{PROPS}->[$flag_name] ? 1 : '';
              }
          /;
      }
  
  }
  
  
  
  # Functions
  
  my %encode_allow_method
       = map {($_ => 1)} qw/utf8 pretty allow_nonref latin1 self_encode escape_slash
                            allow_blessed convert_blessed indent indent_length allow_bignum
                            as_nonblessed
                          /;
  my %decode_allow_method
       = map {($_ => 1)} qw/utf8 allow_nonref loose allow_singlequote allow_bignum
                            allow_barekey max_size relaxed/;
  
  
  my $JSON; # cache
  
  sub encode_json ($) { # encode
      ($JSON ||= __PACKAGE__->new->utf8)->encode(@_);
  }
  
  
  sub decode_json { # decode
      ($JSON ||= __PACKAGE__->new->utf8)->decode(@_);
  }
  
  # Obsoleted
  
  sub to_json($) {
     Carp::croak ("JSON::PP::to_json has been renamed to encode_json.");
  }
  
  
  sub from_json($) {
     Carp::croak ("JSON::PP::from_json has been renamed to decode_json.");
  }
  
  
  # Methods
  
  sub new {
      my $class = shift;
      my $self  = {
          max_depth   => 512,
          max_size    => 0,
          indent      => 0,
          FLAGS       => 0,
          fallback      => sub { encode_error('Invalid value. JSON can only reference.') },
          indent_length => 3,
      };
  
      bless $self, $class;
  }
  
  
  sub encode {
      return $_[0]->PP_encode_json($_[1]);
  }
  
  
  sub decode {
      return $_[0]->PP_decode_json($_[1], 0x00000000);
  }
  
  
  sub decode_prefix {
      return $_[0]->PP_decode_json($_[1], 0x00000001);
  }
  
  
  # accessor
  
  
  # pretty printing
  
  sub pretty {
      my ($self, $v) = @_;
      my $enable = defined $v ? $v : 1;
  
      if ($enable) { # indent_length(3) for JSON::XS compatibility
          $self->indent(1)->indent_length(3)->space_before(1)->space_after(1);
      }
      else {
          $self->indent(0)->space_before(0)->space_after(0);
      }
  
      $self;
  }
  
  # etc
  
  sub max_depth {
      my $max  = defined $_[1] ? $_[1] : 0x80000000;
      $_[0]->{max_depth} = $max;
      $_[0];
  }
  
  
  sub get_max_depth { $_[0]->{max_depth}; }
  
  
  sub max_size {
      my $max  = defined $_[1] ? $_[1] : 0;
      $_[0]->{max_size} = $max;
      $_[0];
  }
  
  
  sub get_max_size { $_[0]->{max_size}; }
  
  
  sub filter_json_object {
      $_[0]->{cb_object} = defined $_[1] ? $_[1] : 0;
      $_[0]->{F_HOOK} = ($_[0]->{cb_object} or $_[0]->{cb_sk_object}) ? 1 : 0;
      $_[0];
  }
  
  sub filter_json_single_key_object {
      if (@_ > 1) {
          $_[0]->{cb_sk_object}->{$_[1]} = $_[2];
      }
      $_[0]->{F_HOOK} = ($_[0]->{cb_object} or $_[0]->{cb_sk_object}) ? 1 : 0;
      $_[0];
  }
  
  sub indent_length {
      if (!defined $_[1] or $_[1] > 15 or $_[1] < 0) {
          Carp::carp "The acceptable range of indent_length() is 0 to 15.";
      }
      else {
          $_[0]->{indent_length} = $_[1];
      }
      $_[0];
  }
  
  sub get_indent_length {
      $_[0]->{indent_length};
  }
  
  sub sort_by {
      $_[0]->{sort_by} = defined $_[1] ? $_[1] : 1;
      $_[0];
  }
  
  sub allow_bigint {
      Carp::carp("allow_bigint() is obsoleted. use allow_bignum() insted.");
  }
  
  ###############################
  
  ###
  ### Perl => JSON
  ###
  
  
  { # Convert
  
      my $max_depth;
      my $indent;
      my $ascii;
      my $latin1;
      my $utf8;
      my $space_before;
      my $space_after;
      my $canonical;
      my $allow_blessed;
      my $convert_blessed;
  
      my $indent_length;
      my $escape_slash;
      my $bignum;
      my $as_nonblessed;
  
      my $depth;
      my $indent_count;
      my $keysort;
  
  
      sub PP_encode_json {
          my $self = shift;
          my $obj  = shift;
  
          $indent_count = 0;
          $depth        = 0;
  
          my $idx = $self->{PROPS};
  
          ($ascii, $latin1, $utf8, $indent, $canonical, $space_before, $space_after, $allow_blessed,
              $convert_blessed, $escape_slash, $bignum, $as_nonblessed)
           = @{$idx}[P_ASCII .. P_SPACE_AFTER, P_ALLOW_BLESSED, P_CONVERT_BLESSED,
                      P_ESCAPE_SLASH, P_ALLOW_BIGNUM, P_AS_NONBLESSED];
  
          ($max_depth, $indent_length) = @{$self}{qw/max_depth indent_length/};
  
          $keysort = $canonical ? sub { $a cmp $b } : undef;
  
          if ($self->{sort_by}) {
              $keysort = ref($self->{sort_by}) eq 'CODE' ? $self->{sort_by}
                       : $self->{sort_by} =~ /\D+/       ? $self->{sort_by}
                       : sub { $a cmp $b };
          }
  
          encode_error("hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)")
               if(!ref $obj and !$idx->[ P_ALLOW_NONREF ]);
  
          my $str  = $self->object_to_json($obj);
  
          $str .= "\n" if ( $indent ); # JSON::XS 2.26 compatible
  
          unless ($ascii or $latin1 or $utf8) {
              utf8::upgrade($str);
          }
  
          if ($idx->[ P_SHRINK ]) {
              utf8::downgrade($str, 1);
          }
  
          return $str;
      }
  
  
      sub object_to_json {
          my ($self, $obj) = @_;
          my $type = ref($obj);
  
          if($type eq 'HASH'){
              return $self->hash_to_json($obj);
          }
          elsif($type eq 'ARRAY'){
              return $self->array_to_json($obj);
          }
          elsif ($type) { # blessed object?
              if (blessed($obj)) {
  
                  return $self->value_to_json($obj) if ( $obj->isa('JSON::PP::Boolean') );
  
                  if ( $convert_blessed and $obj->can('TO_JSON') ) {
                      my $result = $obj->TO_JSON();
                      if ( defined $result and ref( $result ) ) {
                          if ( refaddr( $obj ) eq refaddr( $result ) ) {
                              encode_error( sprintf(
                                  "%s::TO_JSON method returned same object as was passed instead of a new one",
                                  ref $obj
                              ) );
                          }
                      }
  
                      return $self->object_to_json( $result );
                  }
  
                  return "$obj" if ( $bignum and _is_bignum($obj) );
                  return $self->blessed_to_json($obj) if ($allow_blessed and $as_nonblessed); # will be removed.
  
                  encode_error( sprintf("encountered object '%s', but neither allow_blessed "
                      . "nor convert_blessed settings are enabled", $obj)
                  ) unless ($allow_blessed);
  
                  return 'null';
              }
              else {
                  return $self->value_to_json($obj);
              }
          }
          else{
              return $self->value_to_json($obj);
          }
      }
  
  
      sub hash_to_json {
          my ($self, $obj) = @_;
          my @res;
  
          encode_error("json text or perl structure exceeds maximum nesting level (max_depth set too low?)")
                                           if (++$depth > $max_depth);
  
          my ($pre, $post) = $indent ? $self->_up_indent() : ('', '');
          my $del = ($space_before ? ' ' : '') . ':' . ($space_after ? ' ' : '');
  
          for my $k ( _sort( $obj ) ) {
              if ( OLD_PERL ) { utf8::decode($k) } # key for Perl 5.6 / be optimized
              push @res, string_to_json( $self, $k )
                            .  $del
                            . ( $self->object_to_json( $obj->{$k} ) || $self->value_to_json( $obj->{$k} ) );
          }
  
          --$depth;
          $self->_down_indent() if ($indent);
  
          return   '{' . ( @res ? $pre : '' ) . ( @res ? join( ",$pre", @res ) . $post : '' )  . '}';
      }
  
  
      sub array_to_json {
          my ($self, $obj) = @_;
          my @res;
  
          encode_error("json text or perl structure exceeds maximum nesting level (max_depth set too low?)")
                                           if (++$depth > $max_depth);
  
          my ($pre, $post) = $indent ? $self->_up_indent() : ('', '');
  
          for my $v (@$obj){
              push @res, $self->object_to_json($v) || $self->value_to_json($v);
          }
  
          --$depth;
          $self->_down_indent() if ($indent);
  
          return '[' . ( @res ? $pre : '' ) . ( @res ? join( ",$pre", @res ) . $post : '' ) . ']';
      }
  
  
      sub value_to_json {
          my ($self, $value) = @_;
  
          return 'null' if(!defined $value);
  
          my $b_obj = B::svref_2object(\$value);  # for round trip problem
          my $flags = $b_obj->FLAGS;
  
          return $value # as is 
              if $flags & ( B::SVp_IOK | B::SVp_NOK ) and !( $flags & B::SVp_POK ); # SvTYPE is IV or NV?
  
          my $type = ref($value);
  
          if(!$type){
              return string_to_json($self, $value);
          }
          elsif( blessed($value) and  $value->isa('JSON::PP::Boolean') ){
              return $$value == 1 ? 'true' : 'false';
          }
          elsif ($type) {
              if ((overload::StrVal($value) =~ /=(\w+)/)[0]) {
                  return $self->value_to_json("$value");
              }
  
              if ($type eq 'SCALAR' and defined $$value) {
                  return   $$value eq '1' ? 'true'
                         : $$value eq '0' ? 'false'
                         : $self->{PROPS}->[ P_ALLOW_UNKNOWN ] ? 'null'
                         : encode_error("cannot encode reference to scalar");
              }
  
               if ( $self->{PROPS}->[ P_ALLOW_UNKNOWN ] ) {
                   return 'null';
               }
               else {
                   if ( $type eq 'SCALAR' or $type eq 'REF' ) {
                      encode_error("cannot encode reference to scalar");
                   }
                   else {
                      encode_error("encountered $value, but JSON can only represent references to arrays or hashes");
                   }
               }
  
          }
          else {
              return $self->{fallback}->($value)
                   if ($self->{fallback} and ref($self->{fallback}) eq 'CODE');
              return 'null';
          }
  
      }
  
  
      my %esc = (
          "\n" => '\n',
          "\r" => '\r',
          "\t" => '\t',
          "\f" => '\f',
          "\b" => '\b',
          "\"" => '\"',
          "\\" => '\\\\',
          "\'" => '\\\'',
      );
  
  
      sub string_to_json {
          my ($self, $arg) = @_;
  
          $arg =~ s/([\x22\x5c\n\r\t\f\b])/$esc{$1}/g;
          $arg =~ s/\//\\\//g if ($escape_slash);
          $arg =~ s/([\x00-\x08\x0b\x0e-\x1f])/'\\u00' . unpack('H2', $1)/eg;
  
          if ($ascii) {
              $arg = JSON_PP_encode_ascii($arg);
          }
  
          if ($latin1) {
              $arg = JSON_PP_encode_latin1($arg);
          }
  
          if ($utf8) {
              utf8::encode($arg);
          }
  
          return '"' . $arg . '"';
      }
  
  
      sub blessed_to_json {
          my $reftype = reftype($_[1]) || '';
          if ($reftype eq 'HASH') {
              return $_[0]->hash_to_json($_[1]);
          }
          elsif ($reftype eq 'ARRAY') {
              return $_[0]->array_to_json($_[1]);
          }
          else {
              return 'null';
          }
      }
  
  
      sub encode_error {
          my $error  = shift;
          Carp::croak "$error";
      }
  
  
      sub _sort {
          defined $keysort ? (sort $keysort (keys %{$_[0]})) : keys %{$_[0]};
      }
  
  
      sub _up_indent {
          my $self  = shift;
          my $space = ' ' x $indent_length;
  
          my ($pre,$post) = ('','');
  
          $post = "\n" . $space x $indent_count;
  
          $indent_count++;
  
          $pre = "\n" . $space x $indent_count;
  
          return ($pre,$post);
      }
  
  
      sub _down_indent { $indent_count--; }
  
  
      sub PP_encode_box {
          {
              depth        => $depth,
              indent_count => $indent_count,
          };
      }
  
  } # Convert
  
  
  sub _encode_ascii {
      join('',
          map {
              $_ <= 127 ?
                  chr($_) :
              $_ <= 65535 ?
                  sprintf('\u%04x', $_) : sprintf('\u%x\u%x', _encode_surrogates($_));
          } unpack('U*', $_[0])
      );
  }
  
  
  sub _encode_latin1 {
      join('',
          map {
              $_ <= 255 ?
                  chr($_) :
              $_ <= 65535 ?
                  sprintf('\u%04x', $_) : sprintf('\u%x\u%x', _encode_surrogates($_));
          } unpack('U*', $_[0])
      );
  }
  
  
  sub _encode_surrogates { # from perlunicode
      my $uni = $_[0] - 0x10000;
      return ($uni / 0x400 + 0xD800, $uni % 0x400 + 0xDC00);
  }
  
  
  sub _is_bignum {
      $_[0]->isa('Math::BigInt') or $_[0]->isa('Math::BigFloat');
  }
  
  
  
  #
  # JSON => Perl
  #
  
  my $max_intsize;
  
  BEGIN {
      my $checkint = 1111;
      for my $d (5..64) {
          $checkint .= 1;
          my $int   = eval qq| $checkint |;
          if ($int =~ /[eE]/) {
              $max_intsize = $d - 1;
              last;
          }
      }
  }
  
  { # PARSE 
  
      my %escapes = ( #  by Jeremy Muhlich <jmuhlich [at] bitflood.org>
          b    => "\x8",
          t    => "\x9",
          n    => "\xA",
          f    => "\xC",
          r    => "\xD",
          '\\' => '\\',
          '"'  => '"',
          '/'  => '/',
      );
  
      my $text; # json data
      my $at;   # offset
      my $ch;   # 1chracter
      my $len;  # text length (changed according to UTF8 or NON UTF8)
      # INTERNAL
      my $depth;          # nest counter
      my $encoding;       # json text encoding
      my $is_valid_utf8;  # temp variable
      my $utf8_len;       # utf8 byte length
      # FLAGS
      my $utf8;           # must be utf8
      my $max_depth;      # max nest number of objects and arrays
      my $max_size;
      my $relaxed;
      my $cb_object;
      my $cb_sk_object;
  
      my $F_HOOK;
  
      my $allow_bigint;   # using Math::BigInt
      my $singlequote;    # loosely quoting
      my $loose;          # 
      my $allow_barekey;  # bareKey
  
      # $opt flag
      # 0x00000001 .... decode_prefix
      # 0x10000000 .... incr_parse
  
      sub PP_decode_json {
          my ($self, $opt); # $opt is an effective flag during this decode_json.
  
          ($self, $text, $opt) = @_;
  
          ($at, $ch, $depth) = (0, '', 0);
  
          if ( !defined $text or ref $text ) {
              decode_error("malformed JSON string, neither array, object, number, string or atom");
          }
  
          my $idx = $self->{PROPS};
  
          ($utf8, $relaxed, $loose, $allow_bigint, $allow_barekey, $singlequote)
              = @{$idx}[P_UTF8, P_RELAXED, P_LOOSE .. P_ALLOW_SINGLEQUOTE];
  
          if ( $utf8 ) {
              utf8::downgrade( $text, 1 ) or Carp::croak("Wide character in subroutine entry");
          }
          else {
              utf8::upgrade( $text );
          }
  
          $len = length $text;
  
          ($max_depth, $max_size, $cb_object, $cb_sk_object, $F_HOOK)
               = @{$self}{qw/max_depth  max_size cb_object cb_sk_object F_HOOK/};
  
          if ($max_size > 1) {
              use bytes;
              my $bytes = length $text;
              decode_error(
                  sprintf("attempted decode of JSON text of %s bytes size, but max_size is set to %s"
                      , $bytes, $max_size), 1
              ) if ($bytes > $max_size);
          }
  
          # Currently no effect
          # should use regexp
          my @octets = unpack('C4', $text);
          $encoding =   ( $octets[0] and  $octets[1]) ? 'UTF-8'
                      : (!$octets[0] and  $octets[1]) ? 'UTF-16BE'
                      : (!$octets[0] and !$octets[1]) ? 'UTF-32BE'
                      : ( $octets[2]                ) ? 'UTF-16LE'
                      : (!$octets[2]                ) ? 'UTF-32LE'
                      : 'unknown';
  
          white(); # remove head white space
  
          my $valid_start = defined $ch; # Is there a first character for JSON structure?
  
          my $result = value();
  
          return undef if ( !$result && ( $opt & 0x10000000 ) ); # for incr_parse
  
          decode_error("malformed JSON string, neither array, object, number, string or atom") unless $valid_start;
  
          if ( !$idx->[ P_ALLOW_NONREF ] and !ref $result ) {
                  decode_error(
                  'JSON text must be an object or array (but found number, string, true, false or null,'
                         . ' use allow_nonref to allow this)', 1);
          }
  
          Carp::croak('something wrong.') if $len < $at; # we won't arrive here.
  
          my $consumed = defined $ch ? $at - 1 : $at; # consumed JSON text length
  
          white(); # remove tail white space
  
          if ( $ch ) {
              return ( $result, $consumed ) if ($opt & 0x00000001); # all right if decode_prefix
              decode_error("garbage after JSON object");
          }
  
          ( $opt & 0x00000001 ) ? ( $result, $consumed ) : $result;
      }
  
  
      sub next_chr {
          return $ch = undef if($at >= $len);
          $ch = substr($text, $at++, 1);
      }
  
  
      sub value {
          white();
          return          if(!defined $ch);
          return object() if($ch eq '{');
          return array()  if($ch eq '[');
          return string() if($ch eq '"' or ($singlequote and $ch eq "'"));
          return number() if($ch =~ /[0-9]/ or $ch eq '-');
          return word();
      }
  
      sub string {
          my ($i, $s, $t, $u);
          my $utf16;
          my $is_utf8;
  
          ($is_valid_utf8, $utf8_len) = ('', 0);
  
          $s = ''; # basically UTF8 flag on
  
          if($ch eq '"' or ($singlequote and $ch eq "'")){
              my $boundChar = $ch;
  
              OUTER: while( defined(next_chr()) ){
  
                  if($ch eq $boundChar){
                      next_chr();
  
                      if ($utf16) {
                          decode_error("missing low surrogate character in surrogate pair");
                      }
  
                      utf8::decode($s) if($is_utf8);
  
                      return $s;
                  }
                  elsif($ch eq '\\'){
                      next_chr();
                      if(exists $escapes{$ch}){
                          $s .= $escapes{$ch};
                      }
                      elsif($ch eq 'u'){ # UNICODE handling
                          my $u = '';
  
                          for(1..4){
                              $ch = next_chr();
                              last OUTER if($ch !~ /[0-9a-fA-F]/);
                              $u .= $ch;
                          }
  
                          # U+D800 - U+DBFF
                          if ($u =~ /^[dD][89abAB][0-9a-fA-F]{2}/) { # UTF-16 high surrogate?
                              $utf16 = $u;
                          }
                          # U+DC00 - U+DFFF
                          elsif ($u =~ /^[dD][c-fC-F][0-9a-fA-F]{2}/) { # UTF-16 low surrogate?
                              unless (defined $utf16) {
                                  decode_error("missing high surrogate character in surrogate pair");
                              }
                              $is_utf8 = 1;
                              $s .= JSON_PP_decode_surrogates($utf16, $u) || next;
                              $utf16 = undef;
                          }
                          else {
                              if (defined $utf16) {
                                  decode_error("surrogate pair expected");
                              }
  
                              if ( ( my $hex = hex( $u ) ) > 127 ) {
                                  $is_utf8 = 1;
                                  $s .= JSON_PP_decode_unicode($u) || next;
                              }
                              else {
                                  $s .= chr $hex;
                              }
                          }
  
                      }
                      else{
                          unless ($loose) {
                              $at -= 2;
                              decode_error('illegal backslash escape sequence in string');
                          }
                          $s .= $ch;
                      }
                  }
                  else{
  
                      if ( ord $ch  > 127 ) {
                          if ( $utf8 ) {
                              unless( $ch = is_valid_utf8($ch) ) {
                                  $at -= 1;
                                  decode_error("malformed UTF-8 character in JSON string");
                              }
                              else {
                                  $at += $utf8_len - 1;
                              }
                          }
                          else {
                              utf8::encode( $ch );
                          }
  
                          $is_utf8 = 1;
                      }
  
                      if (!$loose) {
                          if ($ch =~ /[\x00-\x1f\x22\x5c]/)  { # '/' ok
                              $at--;
                              decode_error('invalid character encountered while parsing JSON string');
                          }
                      }
  
                      $s .= $ch;
                  }
              }
          }
  
          decode_error("unexpected end of string while parsing JSON string");
      }
  
  
      sub white {
          while( defined $ch  ){
              if($ch le ' '){
                  next_chr();
              }
              elsif($ch eq '/'){
                  next_chr();
                  if(defined $ch and $ch eq '/'){
                      1 while(defined(next_chr()) and $ch ne "\n" and $ch ne "\r");
                  }
                  elsif(defined $ch and $ch eq '*'){
                      next_chr();
                      while(1){
                          if(defined $ch){
                              if($ch eq '*'){
                                  if(defined(next_chr()) and $ch eq '/'){
                                      next_chr();
                                      last;
                                  }
                              }
                              else{
                                  next_chr();
                              }
                          }
                          else{
                              decode_error("Unterminated comment");
                          }
                      }
                      next;
                  }
                  else{
                      $at--;
                      decode_error("malformed JSON string, neither array, object, number, string or atom");
                  }
              }
              else{
                  if ($relaxed and $ch eq '#') { # correctly?
                      pos($text) = $at;
                      $text =~ /\G([^\n]*(?:\r\n|\r|\n|$))/g;
                      $at = pos($text);
                      next_chr;
                      next;
                  }
  
                  last;
              }
          }
      }
  
  
      sub array {
          my $a  = $_[0] || []; # you can use this code to use another array ref object.
  
          decode_error('json text or perl structure exceeds maximum nesting level (max_depth set too low?)')
                                                      if (++$depth > $max_depth);
  
          next_chr();
          white();
  
          if(defined $ch and $ch eq ']'){
              --$depth;
              next_chr();
              return $a;
          }
          else {
              while(defined($ch)){
                  push @$a, value();
  
                  white();
  
                  if (!defined $ch) {
                      last;
                  }
  
                  if($ch eq ']'){
                      --$depth;
                      next_chr();
                      return $a;
                  }
  
                  if($ch ne ','){
                      last;
                  }
  
                  next_chr();
                  white();
  
                  if ($relaxed and $ch eq ']') {
                      --$depth;
                      next_chr();
                      return $a;
                  }
  
              }
          }
  
          decode_error(", or ] expected while parsing array");
      }
  
  
      sub object {
          my $o = $_[0] || {}; # you can use this code to use another hash ref object.
          my $k;
  
          decode_error('json text or perl structure exceeds maximum nesting level (max_depth set too low?)')
                                                  if (++$depth > $max_depth);
          next_chr();
          white();
  
          if(defined $ch and $ch eq '}'){
              --$depth;
              next_chr();
              if ($F_HOOK) {
                  return _json_object_hook($o);
              }
              return $o;
          }
          else {
              while (defined $ch) {
                  $k = ($allow_barekey and $ch ne '"' and $ch ne "'") ? bareKey() : string();
                  white();
  
                  if(!defined $ch or $ch ne ':'){
                      $at--;
                      decode_error("':' expected");
                  }
  
                  next_chr();
                  $o->{$k} = value();
                  white();
  
                  last if (!defined $ch);
  
                  if($ch eq '}'){
                      --$depth;
                      next_chr();
                      if ($F_HOOK) {
                          return _json_object_hook($o);
                      }
                      return $o;
                  }
  
                  if($ch ne ','){
                      last;
                  }
  
                  next_chr();
                  white();
  
                  if ($relaxed and $ch eq '}') {
                      --$depth;
                      next_chr();
                      if ($F_HOOK) {
                          return _json_object_hook($o);
                      }
                      return $o;
                  }
  
              }
  
          }
  
          $at--;
          decode_error(", or } expected while parsing object/hash");
      }
  
  
      sub bareKey { # doesn't strictly follow Standard ECMA-262 3rd Edition
          my $key;
          while($ch =~ /[^\x00-\x23\x25-\x2F\x3A-\x40\x5B-\x5E\x60\x7B-\x7F]/){
              $key .= $ch;
              next_chr();
          }
          return $key;
      }
  
  
      sub word {
          my $word =  substr($text,$at-1,4);
  
          if($word eq 'true'){
              $at += 3;
              next_chr;
              return $JSON::PP::true;
          }
          elsif($word eq 'null'){
              $at += 3;
              next_chr;
              return undef;
          }
          elsif($word eq 'fals'){
              $at += 3;
              if(substr($text,$at,1) eq 'e'){
                  $at++;
                  next_chr;
                  return $JSON::PP::false;
              }
          }
  
          $at--; # for decode_error report
  
          decode_error("'null' expected")  if ($word =~ /^n/);
          decode_error("'true' expected")  if ($word =~ /^t/);
          decode_error("'false' expected") if ($word =~ /^f/);
          decode_error("malformed JSON string, neither array, object, number, string or atom");
      }
  
  
      sub number {
          my $n    = '';
          my $v;
  
          # According to RFC4627, hex or oct digits are invalid.
          if($ch eq '0'){
              my $peek = substr($text,$at,1);
              my $hex  = $peek =~ /[xX]/; # 0 or 1
  
              if($hex){
                  decode_error("malformed number (leading zero must not be followed by another digit)");
                  ($n) = ( substr($text, $at+1) =~ /^([0-9a-fA-F]+)/);
              }
              else{ # oct
                  ($n) = ( substr($text, $at) =~ /^([0-7]+)/);
                  if (defined $n and length $n > 1) {
                      decode_error("malformed number (leading zero must not be followed by another digit)");
                  }
              }
  
              if(defined $n and length($n)){
                  if (!$hex and length($n) == 1) {
                     decode_error("malformed number (leading zero must not be followed by another digit)");
                  }
                  $at += length($n) + $hex;
                  next_chr;
                  return $hex ? hex($n) : oct($n);
              }
          }
  
          if($ch eq '-'){
              $n = '-';
              next_chr;
              if (!defined $ch or $ch !~ /\d/) {
                  decode_error("malformed number (no digits after initial minus)");
              }
          }
  
          while(defined $ch and $ch =~ /\d/){
              $n .= $ch;
              next_chr;
          }
  
          if(defined $ch and $ch eq '.'){
              $n .= '.';
  
              next_chr;
              if (!defined $ch or $ch !~ /\d/) {
                  decode_error("malformed number (no digits after decimal point)");
              }
              else {
                  $n .= $ch;
              }
  
              while(defined(next_chr) and $ch =~ /\d/){
                  $n .= $ch;
              }
          }
  
          if(defined $ch and ($ch eq 'e' or $ch eq 'E')){
              $n .= $ch;
              next_chr;
  
              if(defined($ch) and ($ch eq '+' or $ch eq '-')){
                  $n .= $ch;
                  next_chr;
                  if (!defined $ch or $ch =~ /\D/) {
                      decode_error("malformed number (no digits after exp sign)");
                  }
                  $n .= $ch;
              }
              elsif(defined($ch) and $ch =~ /\d/){
                  $n .= $ch;
              }
              else {
                  decode_error("malformed number (no digits after exp sign)");
              }
  
              while(defined(next_chr) and $ch =~ /\d/){
                  $n .= $ch;
              }
  
          }
  
          $v .= $n;
  
          if ($v !~ /[.eE]/ and length $v > $max_intsize) {
              if ($allow_bigint) { # from Adam Sussman
                  require Math::BigInt;
                  return Math::BigInt->new($v);
              }
              else {
                  return "$v";
              }
          }
          elsif ($allow_bigint) {
              require Math::BigFloat;
              return Math::BigFloat->new($v);
          }
  
          return 0+$v;
      }
  
  
      sub is_valid_utf8 {
  
          $utf8_len = $_[0] =~ /[\x00-\x7F]/  ? 1
                    : $_[0] =~ /[\xC2-\xDF]/  ? 2
                    : $_[0] =~ /[\xE0-\xEF]/  ? 3
                    : $_[0] =~ /[\xF0-\xF4]/  ? 4
                    : 0
                    ;
  
          return unless $utf8_len;
  
          my $is_valid_utf8 = substr($text, $at - 1, $utf8_len);
  
          return ( $is_valid_utf8 =~ /^(?:
               [\x00-\x7F]
              |[\xC2-\xDF][\x80-\xBF]
              |[\xE0][\xA0-\xBF][\x80-\xBF]
              |[\xE1-\xEC][\x80-\xBF][\x80-\xBF]
              |[\xED][\x80-\x9F][\x80-\xBF]
              |[\xEE-\xEF][\x80-\xBF][\x80-\xBF]
              |[\xF0][\x90-\xBF][\x80-\xBF][\x80-\xBF]
              |[\xF1-\xF3][\x80-\xBF][\x80-\xBF][\x80-\xBF]
              |[\xF4][\x80-\x8F][\x80-\xBF][\x80-\xBF]
          )$/x )  ? $is_valid_utf8 : '';
      }
  
  
      sub decode_error {
          my $error  = shift;
          my $no_rep = shift;
          my $str    = defined $text ? substr($text, $at) : '';
          my $mess   = '';
          my $type   = $] >= 5.008           ? 'U*'
                     : $] <  5.006           ? 'C*'
                     : utf8::is_utf8( $str ) ? 'U*' # 5.6
                     : 'C*'
                     ;
  
          for my $c ( unpack( $type, $str ) ) { # emulate pv_uni_display() ?
              $mess .=  $c == 0x07 ? '\a'
                      : $c == 0x09 ? '\t'
                      : $c == 0x0a ? '\n'
                      : $c == 0x0d ? '\r'
                      : $c == 0x0c ? '\f'
                      : $c <  0x20 ? sprintf('\x{%x}', $c)
                      : $c == 0x5c ? '\\\\'
                      : $c <  0x80 ? chr($c)
                      : sprintf('\x{%x}', $c)
                      ;
              if ( length $mess >= 20 ) {
                  $mess .= '...';
                  last;
              }
          }
  
          unless ( length $mess ) {
              $mess = '(end of string)';
          }
  
          Carp::croak (
              $no_rep ? "$error" : "$error, at character offset $at (before \"$mess\")"
          );
  
      }
  
  
      sub _json_object_hook {
          my $o    = $_[0];
          my @ks = keys %{$o};
  
          if ( $cb_sk_object and @ks == 1 and exists $cb_sk_object->{ $ks[0] } and ref $cb_sk_object->{ $ks[0] } ) {
              my @val = $cb_sk_object->{ $ks[0] }->( $o->{$ks[0]} );
              if (@val == 1) {
                  return $val[0];
              }
          }
  
          my @val = $cb_object->($o) if ($cb_object);
          if (@val == 0 or @val > 1) {
              return $o;
          }
          else {
              return $val[0];
          }
      }
  
  
      sub PP_decode_box {
          {
              text    => $text,
              at      => $at,
              ch      => $ch,
              len     => $len,
              depth   => $depth,
              encoding      => $encoding,
              is_valid_utf8 => $is_valid_utf8,
          };
      }
  
  } # PARSE
  
  
  sub _decode_surrogates { # from perlunicode
      my $uni = 0x10000 + (hex($_[0]) - 0xD800) * 0x400 + (hex($_[1]) - 0xDC00);
      my $un  = pack('U*', $uni);
      utf8::encode( $un );
      return $un;
  }
  
  
  sub _decode_unicode {
      my $un = pack('U', hex shift);
      utf8::encode( $un );
      return $un;
  }
  
  #
  # Setup for various Perl versions (the code from JSON::PP58)
  #
  
  BEGIN {
  
      unless ( defined &utf8::is_utf8 ) {
         require Encode;
         *utf8::is_utf8 = *Encode::is_utf8;
      }
  
      if ( $] >= 5.008 ) {
          *JSON::PP::JSON_PP_encode_ascii      = \&_encode_ascii;
          *JSON::PP::JSON_PP_encode_latin1     = \&_encode_latin1;
          *JSON::PP::JSON_PP_decode_surrogates = \&_decode_surrogates;
          *JSON::PP::JSON_PP_decode_unicode    = \&_decode_unicode;
      }
  
      if ($] >= 5.008 and $] < 5.008003) { # join() in 5.8.0 - 5.8.2 is broken.
          package # hide from PAUSE
            JSON::PP;
          require subs;
          subs->import('join');
          eval q|
              sub join {
                  return '' if (@_ < 2);
                  my $j   = shift;
                  my $str = shift;
                  for (@_) { $str .= $j . $_; }
                  return $str;
              }
          |;
      }
  
  
      sub JSON::PP::incr_parse {
          local $Carp::CarpLevel = 1;
          ( $_[0]->{_incr_parser} ||= JSON::PP::IncrParser->new )->incr_parse( @_ );
      }
  
  
      sub JSON::PP::incr_skip {
          ( $_[0]->{_incr_parser} ||= JSON::PP::IncrParser->new )->incr_skip;
      }
  
  
      sub JSON::PP::incr_reset {
          ( $_[0]->{_incr_parser} ||= JSON::PP::IncrParser->new )->incr_reset;
      }
  
      eval q{
          sub JSON::PP::incr_text : lvalue {
              $_[0]->{_incr_parser} ||= JSON::PP::IncrParser->new;
  
              if ( $_[0]->{_incr_parser}->{incr_parsing} ) {
                  Carp::croak("incr_text can not be called when the incremental parser already started parsing");
              }
              $_[0]->{_incr_parser}->{incr_text};
          }
      } if ( $] >= 5.006 );
  
  } # Setup for various Perl versions (the code from JSON::PP58)
  
  
  ###############################
  # Utilities
  #
  
  BEGIN {
      eval 'require Scalar::Util';
      unless($@){
          *JSON::PP::blessed = \&Scalar::Util::blessed;
          *JSON::PP::reftype = \&Scalar::Util::reftype;
          *JSON::PP::refaddr = \&Scalar::Util::refaddr;
      }
      else{ # This code is from Scalar::Util.
          # warn $@;
          eval 'sub UNIVERSAL::a_sub_not_likely_to_be_here { ref($_[0]) }';
          *JSON::PP::blessed = sub {
              local($@, $SIG{__DIE__}, $SIG{__WARN__});
              ref($_[0]) ? eval { $_[0]->a_sub_not_likely_to_be_here } : undef;
          };
          my %tmap = qw(
              B::NULL   SCALAR
              B::HV     HASH
              B::AV     ARRAY
              B::CV     CODE
              B::IO     IO
              B::GV     GLOB
              B::REGEXP REGEXP
          );
          *JSON::PP::reftype = sub {
              my $r = shift;
  
              return undef unless length(ref($r));
  
              my $t = ref(B::svref_2object($r));
  
              return
                  exists $tmap{$t} ? $tmap{$t}
                : length(ref($$r)) ? 'REF'
                :                    'SCALAR';
          };
          *JSON::PP::refaddr = sub {
            return undef unless length(ref($_[0]));
  
            my $addr;
            if(defined(my $pkg = blessed($_[0]))) {
              $addr .= bless $_[0], 'Scalar::Util::Fake';
              bless $_[0], $pkg;
            }
            else {
              $addr .= $_[0]
            }
  
            $addr =~ /0x(\w+)/;
            local $^W;
            #no warnings 'portable';
            hex($1);
          }
      }
  }
  
  
  # shamelessly copied and modified from JSON::XS code.
  
  unless ( $INC{'JSON/PP.pm'} ) {
      eval q|
          package
              JSON::PP::Boolean;
  
          use overload (
              "0+"     => sub { ${$_[0]} },
              "++"     => sub { $_[0] = ${$_[0]} + 1 },
              "--"     => sub { $_[0] = ${$_[0]} - 1 },
              fallback => 1,
          );
      |;
  }
  
  $JSON::PP::true  = do { bless \(my $dummy = 1), "JSON::PP::Boolean" };
  $JSON::PP::false = do { bless \(my $dummy = 0), "JSON::PP::Boolean" };
  
  sub is_bool { defined $_[0] and UNIVERSAL::isa($_[0], "JSON::PP::Boolean"); }
  
  sub true  { $JSON::PP::true  }
  sub false { $JSON::PP::false }
  sub null  { undef; }
  
  ###############################
  
  ###############################
  
  package # hide from PAUSE
    JSON::PP::IncrParser;
  
  use strict;
  
  use constant INCR_M_WS   => 0; # initial whitespace skipping
  use constant INCR_M_STR  => 1; # inside string
  use constant INCR_M_BS   => 2; # inside backslash
  use constant INCR_M_JSON => 3; # outside anything, count nesting
  use constant INCR_M_C0   => 4;
  use constant INCR_M_C1   => 5;
  
  use vars qw($VERSION);
  $VERSION = '1.01';
  
  my $unpack_format = $] < 5.006 ? 'C*' : 'U*';
  
  sub new {
      my ( $class ) = @_;
  
      bless {
          incr_nest    => 0,
          incr_text    => undef,
          incr_parsing => 0,
          incr_p       => 0,
      }, $class;
  }
  
  
  sub incr_parse {
      my ( $self, $coder, $text ) = @_;
  
      $self->{incr_text} = '' unless ( defined $self->{incr_text} );
  
      if ( defined $text ) {
          if ( utf8::is_utf8( $text ) and !utf8::is_utf8( $self->{incr_text} ) ) {
              utf8::upgrade( $self->{incr_text} ) ;
              utf8::decode( $self->{incr_text} ) ;
          }
          $self->{incr_text} .= $text;
      }
  
  
      my $max_size = $coder->get_max_size;
  
      if ( defined wantarray ) {
  
          $self->{incr_mode} = INCR_M_WS unless defined $self->{incr_mode};
  
          if ( wantarray ) {
              my @ret;
  
              $self->{incr_parsing} = 1;
  
              do {
                  push @ret, $self->_incr_parse( $coder, $self->{incr_text} );
  
                  unless ( !$self->{incr_nest} and $self->{incr_mode} == INCR_M_JSON ) {
                      $self->{incr_mode} = INCR_M_WS if $self->{incr_mode} != INCR_M_STR;
                  }
  
              } until ( length $self->{incr_text} >= $self->{incr_p} );
  
              $self->{incr_parsing} = 0;
  
              return @ret;
          }
          else { # in scalar context
              $self->{incr_parsing} = 1;
              my $obj = $self->_incr_parse( $coder, $self->{incr_text} );
              $self->{incr_parsing} = 0 if defined $obj; # pointed by Martin J. Evans
              return $obj ? $obj : undef; # $obj is an empty string, parsing was completed.
          }
  
      }
  
  }
  
  
  sub _incr_parse {
      my ( $self, $coder, $text, $skip ) = @_;
      my $p = $self->{incr_p};
      my $restore = $p;
  
      my @obj;
      my $len = length $text;
  
      if ( $self->{incr_mode} == INCR_M_WS ) {
          while ( $len > $p ) {
              my $s = substr( $text, $p, 1 );
              $p++ and next if ( 0x20 >= unpack($unpack_format, $s) );
              $self->{incr_mode} = INCR_M_JSON;
              last;
         }
      }
  
      while ( $len > $p ) {
          my $s = substr( $text, $p++, 1 );
  
          if ( $s eq '"' ) {
              if (substr( $text, $p - 2, 1 ) eq '\\' ) {
                  next;
              }
  
              if ( $self->{incr_mode} != INCR_M_STR  ) {
                  $self->{incr_mode} = INCR_M_STR;
              }
              else {
                  $self->{incr_mode} = INCR_M_JSON;
                  unless ( $self->{incr_nest} ) {
                      last;
                  }
              }
          }
  
          if ( $self->{incr_mode} == INCR_M_JSON ) {
  
              if ( $s eq '[' or $s eq '{' ) {
                  if ( ++$self->{incr_nest} > $coder->get_max_depth ) {
                      Carp::croak('json text or perl structure exceeds maximum nesting level (max_depth set too low?)');
                  }
              }
              elsif ( $s eq ']' or $s eq '}' ) {
                  last if ( --$self->{incr_nest} <= 0 );
              }
              elsif ( $s eq '#' ) {
                  while ( $len > $p ) {
                      last if substr( $text, $p++, 1 ) eq "\n";
                  }
              }
  
          }
  
      }
  
      $self->{incr_p} = $p;
  
      return if ( $self->{incr_mode} == INCR_M_STR and not $self->{incr_nest} );
      return if ( $self->{incr_mode} == INCR_M_JSON and $self->{incr_nest} > 0 );
  
      return '' unless ( length substr( $self->{incr_text}, 0, $p ) );
  
      local $Carp::CarpLevel = 2;
  
      $self->{incr_p} = $restore;
      $self->{incr_c} = $p;
  
      my ( $obj, $tail ) = $coder->PP_decode_json( substr( $self->{incr_text}, 0, $p ), 0x10000001 );
  
      $self->{incr_text} = substr( $self->{incr_text}, $p );
      $self->{incr_p} = 0;
  
      return $obj || '';
  }
  
  
  sub incr_text {
      if ( $_[0]->{incr_parsing} ) {
          Carp::croak("incr_text can not be called when the incremental parser already started parsing");
      }
      $_[0]->{incr_text};
  }
  
  
  sub incr_skip {
      my $self  = shift;
      $self->{incr_text} = substr( $self->{incr_text}, $self->{incr_c} );
      $self->{incr_p} = 0;
  }
  
  
  sub incr_reset {
      my $self = shift;
      $self->{incr_text}    = undef;
      $self->{incr_p}       = 0;
      $self->{incr_mode}    = 0;
      $self->{incr_nest}    = 0;
      $self->{incr_parsing} = 0;
  }
  
  ###############################
  
  
  1;
  __END__
  =pod
  
  =head1 NAME
  
  JSON::PP - JSON::XS compatible pure-Perl module.
  
  =head1 SYNOPSIS
  
   use JSON::PP;
  
   # exported functions, they croak on error
   # and expect/generate UTF-8
  
   $utf8_encoded_json_text = encode_json $perl_hash_or_arrayref;
   $perl_hash_or_arrayref  = decode_json $utf8_encoded_json_text;
  
   # OO-interface
  
   $coder = JSON::PP->new->ascii->pretty->allow_nonref;
   
   $json_text   = $json->encode( $perl_scalar );
   $perl_scalar = $json->decode( $json_text );
   
   $pretty_printed = $json->pretty->encode( $perl_scalar ); # pretty-printing
   
   # Note that JSON version 2.0 and above will automatically use
   # JSON::XS or JSON::PP, so you should be able to just:
   
   use JSON;
  
  
  =head1 VERSION
  
      2.27200
  
  L<JSON::XS> 2.27 (~2.30) compatible.
  
  =head1 DESCRIPTION
  
  This module is L<JSON::XS> compatible pure Perl module.
  (Perl 5.8 or later is recommended)
  
  JSON::XS is the fastest and most proper JSON module on CPAN.
  It is written by Marc Lehmann in C, so must be compiled and
  installed in the used environment.
  
  JSON::PP is a pure-Perl module and has compatibility to JSON::XS.
  
  
  =head2 FEATURES
  
  =over
  
  =item * correct unicode handling
  
  This module knows how to handle Unicode (depending on Perl version).
  
  See to L<JSON::XS/A FEW NOTES ON UNICODE AND PERL> and
  L<UNICODE HANDLING ON PERLS>.
  
  
  =item * round-trip integrity
  
  When you serialise a perl data structure using only data types
  supported by JSON and Perl, the deserialised data structure is
  identical on the Perl level. (e.g. the string "2.0" doesn't suddenly
  become "2" just because it looks like a number). There I<are> minor
  exceptions to this, read the MAPPING section below to learn about
  those.
  
  
  =item * strict checking of JSON correctness
  
  There is no guessing, no generating of illegal JSON texts by default,
  and only JSON is accepted as input by default (the latter is a
  security feature). But when some options are set, loose checking
  features are available.
  
  =back
  
  =head1 FUNCTIONAL INTERFACE
  
  Some documents are copied and modified from L<JSON::XS/FUNCTIONAL INTERFACE>.
  
  =head2 encode_json
  
      $json_text = encode_json $perl_scalar
  
  Converts the given Perl data structure to a UTF-8 encoded, binary string.
  
  This function call is functionally identical to:
  
      $json_text = JSON::PP->new->utf8->encode($perl_scalar)
  
  =head2 decode_json
  
      $perl_scalar = decode_json $json_text
  
  The opposite of C<encode_json>: expects an UTF-8 (binary) string and tries
  to parse that as an UTF-8 encoded JSON text, returning the resulting
  reference.
  
  This function call is functionally identical to:
  
      $perl_scalar = JSON::PP->new->utf8->decode($json_text)
  
  =head2 JSON::PP::is_bool
  
      $is_boolean = JSON::PP::is_bool($scalar)
  
  Returns true if the passed scalar represents either JSON::PP::true or
  JSON::PP::false, two constants that act like C<1> and C<0> respectively
  and are also used to represent JSON C<true> and C<false> in Perl strings.
  
  =head2 JSON::PP::true
  
  Returns JSON true value which is blessed object.
  It C<isa> JSON::PP::Boolean object.
  
  =head2 JSON::PP::false
  
  Returns JSON false value which is blessed object.
  It C<isa> JSON::PP::Boolean object.
  
  =head2 JSON::PP::null
  
  Returns C<undef>.
  
  See L<MAPPING>, below, for more information on how JSON values are mapped to
  Perl.
  
  
  =head1 HOW DO I DECODE A DATA FROM OUTER AND ENCODE TO OUTER
  
  This section supposes that your perl version is 5.8 or later.
  
  If you know a JSON text from an outer world - a network, a file content, and so on,
  is encoded in UTF-8, you should use C<decode_json> or C<JSON> module object
  with C<utf8> enable. And the decoded result will contain UNICODE characters.
  
    # from network
    my $json        = JSON::PP->new->utf8;
    my $json_text   = CGI->new->param( 'json_data' );
    my $perl_scalar = $json->decode( $json_text );
    
    # from file content
    local $/;
    open( my $fh, '<', 'json.data' );
    $json_text   = <$fh>;
    $perl_scalar = decode_json( $json_text );
  
  If an outer data is not encoded in UTF-8, firstly you should C<decode> it.
  
    use Encode;
    local $/;
    open( my $fh, '<', 'json.data' );
    my $encoding = 'cp932';
    my $unicode_json_text = decode( $encoding, <$fh> ); # UNICODE
    
    # or you can write the below code.
    #
    # open( my $fh, "<:encoding($encoding)", 'json.data' );
    # $unicode_json_text = <$fh>;
  
  In this case, C<$unicode_json_text> is of course UNICODE string.
  So you B<cannot> use C<decode_json> nor C<JSON> module object with C<utf8> enable.
  Instead of them, you use C<JSON> module object with C<utf8> disable.
  
    $perl_scalar = $json->utf8(0)->decode( $unicode_json_text );
  
  Or C<encode 'utf8'> and C<decode_json>:
  
    $perl_scalar = decode_json( encode( 'utf8', $unicode_json_text ) );
    # this way is not efficient.
  
  And now, you want to convert your C<$perl_scalar> into JSON data and
  send it to an outer world - a network or a file content, and so on.
  
  Your data usually contains UNICODE strings and you want the converted data to be encoded
  in UTF-8, you should use C<encode_json> or C<JSON> module object with C<utf8> enable.
  
    print encode_json( $perl_scalar ); # to a network? file? or display?
    # or
    print $json->utf8->encode( $perl_scalar );
  
  If C<$perl_scalar> does not contain UNICODE but C<$encoding>-encoded strings
  for some reason, then its characters are regarded as B<latin1> for perl
  (because it does not concern with your $encoding).
  You B<cannot> use C<encode_json> nor C<JSON> module object with C<utf8> enable.
  Instead of them, you use C<JSON> module object with C<utf8> disable.
  Note that the resulted text is a UNICODE string but no problem to print it.
  
    # $perl_scalar contains $encoding encoded string values
    $unicode_json_text = $json->utf8(0)->encode( $perl_scalar );
    # $unicode_json_text consists of characters less than 0x100
    print $unicode_json_text;
  
  Or C<decode $encoding> all string values and C<encode_json>:
  
    $perl_scalar->{ foo } = decode( $encoding, $perl_scalar->{ foo } );
    # ... do it to each string values, then encode_json
    $json_text = encode_json( $perl_scalar );
  
  This method is a proper way but probably not efficient.
  
  See to L<Encode>, L<perluniintro>.
  
  
  =head1 METHODS
  
  Basically, check to L<JSON> or L<JSON::XS>.
  
  =head2 new
  
      $json = JSON::PP->new
  
  Returns a new JSON::PP object that can be used to de/encode JSON
  strings.
  
  All boolean flags described below are by default I<disabled>.
  
  The mutators for flags all return the JSON object again and thus calls can
  be chained:
  
     my $json = JSON::PP->new->utf8->space_after->encode({a => [1,2]})
     => {"a": [1, 2]}
  
  =head2 ascii
  
      $json = $json->ascii([$enable])
      
      $enabled = $json->get_ascii
  
  If $enable is true (or missing), then the encode method will not generate characters outside
  the code range 0..127. Any Unicode characters outside that range will be escaped using either
  a single \uXXXX or a double \uHHHH\uLLLLL escape sequence, as per RFC4627.
  (See to L<JSON::XS/OBJECT-ORIENTED INTERFACE>).
  
  In Perl 5.005, there is no character having high value (more than 255).
  See to L<UNICODE HANDLING ON PERLS>.
  
  If $enable is false, then the encode method will not escape Unicode characters unless
  required by the JSON syntax or other flags. This results in a faster and more compact format.
  
    JSON::PP->new->ascii(1)->encode([chr 0x10401])
    => ["\ud801\udc01"]
  
  =head2 latin1
  
      $json = $json->latin1([$enable])
      
      $enabled = $json->get_latin1
  
  If $enable is true (or missing), then the encode method will encode the resulting JSON
  text as latin1 (or iso-8859-1), escaping any characters outside the code range 0..255.
  
  If $enable is false, then the encode method will not escape Unicode characters
  unless required by the JSON syntax or other flags.
  
    JSON::XS->new->latin1->encode (["\x{89}\x{abc}"]
    => ["\x{89}\\u0abc"]    # (perl syntax, U+abc escaped, U+89 not)
  
  See to L<UNICODE HANDLING ON PERLS>.
  
  =head2 utf8
  
      $json = $json->utf8([$enable])
      
      $enabled = $json->get_utf8
  
  If $enable is true (or missing), then the encode method will encode the JSON result
  into UTF-8, as required by many protocols, while the decode method expects to be handled
  an UTF-8-encoded string. Please note that UTF-8-encoded strings do not contain any
  characters outside the range 0..255, they are thus useful for bytewise/binary I/O.
  
  (In Perl 5.005, any character outside the range 0..255 does not exist.
  See to L<UNICODE HANDLING ON PERLS>.)
  
  In future versions, enabling this option might enable autodetection of the UTF-16 and UTF-32
  encoding families, as described in RFC4627.
  
  If $enable is false, then the encode method will return the JSON string as a (non-encoded)
  Unicode string, while decode expects thus a Unicode string. Any decoding or encoding
  (e.g. to UTF-8 or UTF-16) needs to be done yourself, e.g. using the Encode module.
  
  Example, output UTF-16BE-encoded JSON:
  
    use Encode;
    $jsontext = encode "UTF-16BE", JSON::PP->new->encode ($object);
  
  Example, decode UTF-32LE-encoded JSON:
  
    use Encode;
    $object = JSON::PP->new->decode (decode "UTF-32LE", $jsontext);
  
  
  =head2 pretty
  
      $json = $json->pretty([$enable])
  
  This enables (or disables) all of the C<indent>, C<space_before> and
  C<space_after> flags in one call to generate the most readable
  (or most compact) form possible.
  
  Equivalent to:
  
     $json->indent->space_before->space_after
  
  =head2 indent
  
      $json = $json->indent([$enable])
      
      $enabled = $json->get_indent
  
  The default indent space length is three.
  You can use C<indent_length> to change the length.
  
  =head2 space_before
  
      $json = $json->space_before([$enable])
      
      $enabled = $json->get_space_before
  
  If C<$enable> is true (or missing), then the C<encode> method will add an extra
  optional space before the C<:> separating keys from values in JSON objects.
  
  If C<$enable> is false, then the C<encode> method will not add any extra
  space at those places.
  
  This setting has no effect when decoding JSON texts.
  
  Example, space_before enabled, space_after and indent disabled:
  
     {"key" :"value"}
  
  =head2 space_after
  
      $json = $json->space_after([$enable])
      
      $enabled = $json->get_space_after
  
  If C<$enable> is true (or missing), then the C<encode> method will add an extra
  optional space after the C<:> separating keys from values in JSON objects
  and extra whitespace after the C<,> separating key-value pairs and array
  members.
  
  If C<$enable> is false, then the C<encode> method will not add any extra
  space at those places.
  
  This setting has no effect when decoding JSON texts.
  
  Example, space_before and indent disabled, space_after enabled:
  
     {"key": "value"}
  
  =head2 relaxed
  
      $json = $json->relaxed([$enable])
      
      $enabled = $json->get_relaxed
  
  If C<$enable> is true (or missing), then C<decode> will accept some
  extensions to normal JSON syntax (see below). C<encode> will not be
  affected in anyway. I<Be aware that this option makes you accept invalid
  JSON texts as if they were valid!>. I suggest only to use this option to
  parse application-specific files written by humans (configuration files,
  resource files etc.)
  
  If C<$enable> is false (the default), then C<decode> will only accept
  valid JSON texts.
  
  Currently accepted extensions are:
  
  =over 4
  
  =item * list items can have an end-comma
  
  JSON I<separates> array elements and key-value pairs with commas. This
  can be annoying if you write JSON texts manually and want to be able to
  quickly append elements, so this extension accepts comma at the end of
  such items not just between them:
  
     [
        1,
        2, <- this comma not normally allowed
     ]
     {
        "k1": "v1",
        "k2": "v2", <- this comma not normally allowed
     }
  
  =item * shell-style '#'-comments
  
  Whenever JSON allows whitespace, shell-style comments are additionally
  allowed. They are terminated by the first carriage-return or line-feed
  character, after which more white-space and comments are allowed.
  
    [
       1, # this comment not allowed in JSON
          # neither this one...
    ]
  
  =back
  
  =head2 canonical
  
      $json = $json->canonical([$enable])
      
      $enabled = $json->get_canonical
  
  If C<$enable> is true (or missing), then the C<encode> method will output JSON objects
  by sorting their keys. This is adding a comparatively high overhead.
  
  If C<$enable> is false, then the C<encode> method will output key-value
  pairs in the order Perl stores them (which will likely change between runs
  of the same script).
  
  This option is useful if you want the same data structure to be encoded as
  the same JSON text (given the same overall settings). If it is disabled,
  the same hash might be encoded differently even if contains the same data,
  as key-value pairs have no inherent ordering in Perl.
  
  This setting has no effect when decoding JSON texts.
  
  If you want your own sorting routine, you can give a code reference
  or a subroutine name to C<sort_by>. See to C<JSON::PP OWN METHODS>.
  
  =head2 allow_nonref
  
      $json = $json->allow_nonref([$enable])
      
      $enabled = $json->get_allow_nonref
  
  If C<$enable> is true (or missing), then the C<encode> method can convert a
  non-reference into its corresponding string, number or null JSON value,
  which is an extension to RFC4627. Likewise, C<decode> will accept those JSON
  values instead of croaking.
  
  If C<$enable> is false, then the C<encode> method will croak if it isn't
  passed an arrayref or hashref, as JSON texts must either be an object
  or array. Likewise, C<decode> will croak if given something that is not a
  JSON object or array.
  
     JSON::PP->new->allow_nonref->encode ("Hello, World!")
     => "Hello, World!"
  
  =head2 allow_unknown
  
      $json = $json->allow_unknown ([$enable])
      
      $enabled = $json->get_allow_unknown
  
  If $enable is true (or missing), then "encode" will *not* throw an
  exception when it encounters values it cannot represent in JSON (for
  example, filehandles) but instead will encode a JSON "null" value.
  Note that blessed objects are not included here and are handled
  separately by c<allow_nonref>.
  
  If $enable is false (the default), then "encode" will throw an
  exception when it encounters anything it cannot encode as JSON.
  
  This option does not affect "decode" in any way, and it is
  recommended to leave it off unless you know your communications
  partner.
  
  =head2 allow_blessed
  
      $json = $json->allow_blessed([$enable])
      
      $enabled = $json->get_allow_blessed
  
  If C<$enable> is true (or missing), then the C<encode> method will not
  barf when it encounters a blessed reference. Instead, the value of the
  B<convert_blessed> option will decide whether C<null> (C<convert_blessed>
  disabled or no C<TO_JSON> method found) or a representation of the
  object (C<convert_blessed> enabled and C<TO_JSON> method found) is being
  encoded. Has no effect on C<decode>.
  
  If C<$enable> is false (the default), then C<encode> will throw an
  exception when it encounters a blessed object.
  
  =head2 convert_blessed
  
      $json = $json->convert_blessed([$enable])
      
      $enabled = $json->get_convert_blessed
  
  If C<$enable> is true (or missing), then C<encode>, upon encountering a
  blessed object, will check for the availability of the C<TO_JSON> method
  on the object's class. If found, it will be called in scalar context
  and the resulting scalar will be encoded instead of the object. If no
  C<TO_JSON> method is found, the value of C<allow_blessed> will decide what
  to do.
  
  The C<TO_JSON> method may safely call die if it wants. If C<TO_JSON>
  returns other blessed objects, those will be handled in the same
  way. C<TO_JSON> must take care of not causing an endless recursion cycle
  (== crash) in this case. The name of C<TO_JSON> was chosen because other
  methods called by the Perl core (== not by the user of the object) are
  usually in upper case letters and to avoid collisions with the C<to_json>
  function or method.
  
  This setting does not yet influence C<decode> in any way.
  
  If C<$enable> is false, then the C<allow_blessed> setting will decide what
  to do when a blessed object is found.
  
  =head2 filter_json_object
  
      $json = $json->filter_json_object([$coderef])
  
  When C<$coderef> is specified, it will be called from C<decode> each
  time it decodes a JSON object. The only argument passed to the coderef
  is a reference to the newly-created hash. If the code references returns
  a single scalar (which need not be a reference), this value
  (i.e. a copy of that scalar to avoid aliasing) is inserted into the
  deserialised data structure. If it returns an empty list
  (NOTE: I<not> C<undef>, which is a valid scalar), the original deserialised
  hash will be inserted. This setting can slow down decoding considerably.
  
  When C<$coderef> is omitted or undefined, any existing callback will
  be removed and C<decode> will not change the deserialised hash in any
  way.
  
  Example, convert all JSON objects into the integer 5:
  
     my $js = JSON::PP->new->filter_json_object (sub { 5 });
     # returns [5]
     $js->decode ('[{}]'); # the given subroutine takes a hash reference.
     # throw an exception because allow_nonref is not enabled
     # so a lone 5 is not allowed.
     $js->decode ('{"a":1, "b":2}');
  
  =head2 filter_json_single_key_object
  
      $json = $json->filter_json_single_key_object($key [=> $coderef])
  
  Works remotely similar to C<filter_json_object>, but is only called for
  JSON objects having a single key named C<$key>.
  
  This C<$coderef> is called before the one specified via
  C<filter_json_object>, if any. It gets passed the single value in the JSON
  object. If it returns a single value, it will be inserted into the data
  structure. If it returns nothing (not even C<undef> but the empty list),
  the callback from C<filter_json_object> will be called next, as if no
  single-key callback were specified.
  
  If C<$coderef> is omitted or undefined, the corresponding callback will be
  disabled. There can only ever be one callback for a given key.
  
  As this callback gets called less often then the C<filter_json_object>
  one, decoding speed will not usually suffer as much. Therefore, single-key
  objects make excellent targets to serialise Perl objects into, especially
  as single-key JSON objects are as close to the type-tagged value concept
  as JSON gets (it's basically an ID/VALUE tuple). Of course, JSON does not
  support this in any way, so you need to make sure your data never looks
  like a serialised Perl hash.
  
  Typical names for the single object key are C<__class_whatever__>, or
  C<$__dollars_are_rarely_used__$> or C<}ugly_brace_placement>, or even
  things like C<__class_md5sum(classname)__>, to reduce the risk of clashing
  with real hashes.
  
  Example, decode JSON objects of the form C<< { "__widget__" => <id> } >>
  into the corresponding C<< $WIDGET{<id>} >> object:
  
     # return whatever is in $WIDGET{5}:
     JSON::PP
        ->new
        ->filter_json_single_key_object (__widget__ => sub {
              $WIDGET{ $_[0] }
           })
        ->decode ('{"__widget__": 5')
  
     # this can be used with a TO_JSON method in some "widget" class
     # for serialisation to json:
     sub WidgetBase::TO_JSON {
        my ($self) = @_;
  
        unless ($self->{id}) {
           $self->{id} = ..get..some..id..;
           $WIDGET{$self->{id}} = $self;
        }
  
        { __widget__ => $self->{id} }
     }
  
  =head2 shrink
  
      $json = $json->shrink([$enable])
      
      $enabled = $json->get_shrink
  
  In JSON::XS, this flag resizes strings generated by either
  C<encode> or C<decode> to their minimum size possible.
  It will also try to downgrade any strings to octet-form if possible.
  
  In JSON::PP, it is noop about resizing strings but tries
  C<utf8::downgrade> to the returned string by C<encode>.
  See to L<utf8>.
  
  See to L<JSON::XS/OBJECT-ORIENTED INTERFACE>
  
  =head2 max_depth
  
      $json = $json->max_depth([$maximum_nesting_depth])
      
      $max_depth = $json->get_max_depth
  
  Sets the maximum nesting level (default C<512>) accepted while encoding
  or decoding. If a higher nesting level is detected in JSON text or a Perl
  data structure, then the encoder and decoder will stop and croak at that
  point.
  
  Nesting level is defined by number of hash- or arrayrefs that the encoder
  needs to traverse to reach a given point or the number of C<{> or C<[>
  characters without their matching closing parenthesis crossed to reach a
  given character in a string.
  
  If no argument is given, the highest possible setting will be used, which
  is rarely useful.
  
  See L<JSON::XS/SSECURITY CONSIDERATIONS> for more info on why this is useful.
  
  When a large value (100 or more) was set and it de/encodes a deep nested object/text,
  it may raise a warning 'Deep recursion on subroutine' at the perl runtime phase.
  
  =head2 max_size
  
      $json = $json->max_size([$maximum_string_size])
      
      $max_size = $json->get_max_size
  
  Set the maximum length a JSON text may have (in bytes) where decoding is
  being attempted. The default is C<0>, meaning no limit. When C<decode>
  is called on a string that is longer then this many bytes, it will not
  attempt to decode the string but throw an exception. This setting has no
  effect on C<encode> (yet).
  
  If no argument is given, the limit check will be deactivated (same as when
  C<0> is specified).
  
  See L<JSON::XS/SECURITY CONSIDERATIONS> for more info on why this is useful.
  
  =head2 encode
  
      $json_text = $json->encode($perl_scalar)
  
  Converts the given Perl data structure (a simple scalar or a reference
  to a hash or array) to its JSON representation. Simple scalars will be
  converted into JSON string or number sequences, while references to arrays
  become JSON arrays and references to hashes become JSON objects. Undefined
  Perl values (e.g. C<undef>) become JSON C<null> values.
  References to the integers C<0> and C<1> are converted into C<true> and C<false>.
  
  =head2 decode
  
      $perl_scalar = $json->decode($json_text)
  
  The opposite of C<encode>: expects a JSON text and tries to parse it,
  returning the resulting simple scalar or reference. Croaks on error.
  
  JSON numbers and strings become simple Perl scalars. JSON arrays become
  Perl arrayrefs and JSON objects become Perl hashrefs. C<true> becomes
  C<1> (C<JSON::true>), C<false> becomes C<0> (C<JSON::false>) and
  C<null> becomes C<undef>.
  
  =head2 decode_prefix
  
      ($perl_scalar, $characters) = $json->decode_prefix($json_text)
  
  This works like the C<decode> method, but instead of raising an exception
  when there is trailing garbage after the first JSON object, it will
  silently stop parsing there and return the number of characters consumed
  so far.
  
     JSON->new->decode_prefix ("[1] the tail")
     => ([], 3)
  
  =head1 INCREMENTAL PARSING
  
  Most of this section are copied and modified from L<JSON::XS/INCREMENTAL PARSING>.
  
  In some cases, there is the need for incremental parsing of JSON texts.
  This module does allow you to parse a JSON stream incrementally.
  It does so by accumulating text until it has a full JSON object, which
  it then can decode. This process is similar to using C<decode_prefix>
  to see if a full JSON object is available, but is much more efficient
  (and can be implemented with a minimum of method calls).
  
  This module will only attempt to parse the JSON text once it is sure it
  has enough text to get a decisive result, using a very simple but
  truly incremental parser. This means that it sometimes won't stop as
  early as the full parser, for example, it doesn't detect parenthesis
  mismatches. The only thing it guarantees is that it starts decoding as
  soon as a syntactically valid JSON text has been seen. This means you need
  to set resource limits (e.g. C<max_size>) to ensure the parser will stop
  parsing in the presence if syntax errors.
  
  The following methods implement this incremental parser.
  
  =head2 incr_parse
  
      $json->incr_parse( [$string] ) # void context
      
      $obj_or_undef = $json->incr_parse( [$string] ) # scalar context
      
      @obj_or_empty = $json->incr_parse( [$string] ) # list context
  
  This is the central parsing function. It can both append new text and
  extract objects from the stream accumulated so far (both of these
  functions are optional).
  
  If C<$string> is given, then this string is appended to the already
  existing JSON fragment stored in the C<$json> object.
  
  After that, if the function is called in void context, it will simply
  return without doing anything further. This can be used to add more text
  in as many chunks as you want.
  
  If the method is called in scalar context, then it will try to extract
  exactly I<one> JSON object. If that is successful, it will return this
  object, otherwise it will return C<undef>. If there is a parse error,
  this method will croak just as C<decode> would do (one can then use
  C<incr_skip> to skip the erroneous part). This is the most common way of
  using the method.
  
  And finally, in list context, it will try to extract as many objects
  from the stream as it can find and return them, or the empty list
  otherwise. For this to work, there must be no separators between the JSON
  objects or arrays, instead they must be concatenated back-to-back. If
  an error occurs, an exception will be raised as in the scalar context
  case. Note that in this case, any previously-parsed JSON texts will be
  lost.
  
  Example: Parse some JSON arrays/objects in a given string and return them.
  
      my @objs = JSON->new->incr_parse ("[5][7][1,2]");
  
  =head2 incr_text
  
      $lvalue_string = $json->incr_text
  
  This method returns the currently stored JSON fragment as an lvalue, that
  is, you can manipulate it. This I<only> works when a preceding call to
  C<incr_parse> in I<scalar context> successfully returned an object. Under
  all other circumstances you must not call this function (I mean it.
  although in simple tests it might actually work, it I<will> fail under
  real world conditions). As a special exception, you can also call this
  method before having parsed anything.
  
  This function is useful in two cases: a) finding the trailing text after a
  JSON object or b) parsing multiple JSON objects separated by non-JSON text
  (such as commas).
  
      $json->incr_text =~ s/\s*,\s*//;
  
  In Perl 5.005, C<lvalue> attribute is not available.
  You must write codes like the below:
  
      $string = $json->incr_text;
      $string =~ s/\s*,\s*//;
      $json->incr_text( $string );
  
  =head2 incr_skip
  
      $json->incr_skip
  
  This will reset the state of the incremental parser and will remove the
  parsed text from the input buffer. This is useful after C<incr_parse>
  died, in which case the input buffer and incremental parser state is left
  unchanged, to skip the text parsed so far and to reset the parse state.
  
  =head2 incr_reset
  
      $json->incr_reset
  
  This completely resets the incremental parser, that is, after this call,
  it will be as if the parser had never parsed anything.
  
  This is useful if you want to repeatedly parse JSON objects and want to
  ignore any trailing data, which means you have to reset the parser after
  each successful decode.
  
  See to L<JSON::XS/INCREMENTAL PARSING> for examples.
  
  
  =head1 JSON::PP OWN METHODS
  
  =head2 allow_singlequote
  
      $json = $json->allow_singlequote([$enable])
  
  If C<$enable> is true (or missing), then C<decode> will accept
  JSON strings quoted by single quotations that are invalid JSON
  format.
  
      $json->allow_singlequote->decode({"foo":'bar'});
      $json->allow_singlequote->decode({'foo':"bar"});
      $json->allow_singlequote->decode({'foo':'bar'});
  
  As same as the C<relaxed> option, this option may be used to parse
  application-specific files written by humans.
  
  
  =head2 allow_barekey
  
      $json = $json->allow_barekey([$enable])
  
  If C<$enable> is true (or missing), then C<decode> will accept
  bare keys of JSON object that are invalid JSON format.
  
  As same as the C<relaxed> option, this option may be used to parse
  application-specific files written by humans.
  
      $json->allow_barekey->decode('{foo:"bar"}');
  
  =head2 allow_bignum
  
      $json = $json->allow_bignum([$enable])
  
  If C<$enable> is true (or missing), then C<decode> will convert
  the big integer Perl cannot handle as integer into a L<Math::BigInt>
  object and convert a floating number (any) into a L<Math::BigFloat>.
  
  On the contrary, C<encode> converts C<Math::BigInt> objects and C<Math::BigFloat>
  objects into JSON numbers with C<allow_blessed> enable.
  
     $json->allow_nonref->allow_blessed->allow_bignum;
     $bigfloat = $json->decode('2.000000000000000000000000001');
     print $json->encode($bigfloat);
     # => 2.000000000000000000000000001
  
  See to L<JSON::XS/MAPPING> about the normal conversion of JSON number.
  
  =head2 loose
  
      $json = $json->loose([$enable])
  
  The unescaped [\x00-\x1f\x22\x2f\x5c] strings are invalid in JSON strings
  and the module doesn't allow to C<decode> to these (except for \x2f).
  If C<$enable> is true (or missing), then C<decode>  will accept these
  unescaped strings.
  
      $json->loose->decode(qq|["abc
                                     def"]|);
  
  See L<JSON::XS/SSECURITY CONSIDERATIONS>.
  
  =head2 escape_slash
  
      $json = $json->escape_slash([$enable])
  
  According to JSON Grammar, I<slash> (U+002F) is escaped. But default
  JSON::PP (as same as JSON::XS) encodes strings without escaping slash.
  
  If C<$enable> is true (or missing), then C<encode> will escape slashes.
  
  =head2 indent_length
  
      $json = $json->indent_length($length)
  
  JSON::XS indent space length is 3 and cannot be changed.
  JSON::PP set the indent space length with the given $length.
  The default is 3. The acceptable range is 0 to 15.
  
  =head2 sort_by
  
      $json = $json->sort_by($function_name)
      $json = $json->sort_by($subroutine_ref)
  
  If $function_name or $subroutine_ref are set, its sort routine are used
  in encoding JSON objects.
  
     $js = $pc->sort_by(sub { $JSON::PP::a cmp $JSON::PP::b })->encode($obj);
     # is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|);
  
     $js = $pc->sort_by('own_sort')->encode($obj);
     # is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|);
  
     sub JSON::PP::own_sort { $JSON::PP::a cmp $JSON::PP::b }
  
  As the sorting routine runs in the JSON::PP scope, the given
  subroutine name and the special variables C<$a>, C<$b> will begin
  'JSON::PP::'.
  
  If $integer is set, then the effect is same as C<canonical> on.
  
  =head1 INTERNAL
  
  For developers.
  
  =over
  
  =item PP_encode_box
  
  Returns
  
          {
              depth        => $depth,
              indent_count => $indent_count,
          }
  
  
  =item PP_decode_box
  
  Returns
  
          {
              text    => $text,
              at      => $at,
              ch      => $ch,
              len     => $len,
              depth   => $depth,
              encoding      => $encoding,
              is_valid_utf8 => $is_valid_utf8,
          };
  
  =back
  
  =head1 MAPPING
  
  This section is copied from JSON::XS and modified to C<JSON::PP>.
  JSON::XS and JSON::PP mapping mechanisms are almost equivalent.
  
  See to L<JSON::XS/MAPPING>.
  
  =head2 JSON -> PERL
  
  =over 4
  
  =item object
  
  A JSON object becomes a reference to a hash in Perl. No ordering of object
  keys is preserved (JSON does not preserver object key ordering itself).
  
  =item array
  
  A JSON array becomes a reference to an array in Perl.
  
  =item string
  
  A JSON string becomes a string scalar in Perl - Unicode codepoints in JSON
  are represented by the same codepoints in the Perl string, so no manual
  decoding is necessary.
  
  =item number
  
  A JSON number becomes either an integer, numeric (floating point) or
  string scalar in perl, depending on its range and any fractional parts. On
  the Perl level, there is no difference between those as Perl handles all
  the conversion details, but an integer may take slightly less memory and
  might represent more values exactly than floating point numbers.
  
  If the number consists of digits only, C<JSON> will try to represent
  it as an integer value. If that fails, it will try to represent it as
  a numeric (floating point) value if that is possible without loss of
  precision. Otherwise it will preserve the number as a string value (in
  which case you lose roundtripping ability, as the JSON number will be
  re-encoded to a JSON string).
  
  Numbers containing a fractional or exponential part will always be
  represented as numeric (floating point) values, possibly at a loss of
  precision (in which case you might lose perfect roundtripping ability, but
  the JSON number will still be re-encoded as a JSON number).
  
  Note that precision is not accuracy - binary floating point values cannot
  represent most decimal fractions exactly, and when converting from and to
  floating point, C<JSON> only guarantees precision up to but not including
  the least significant bit.
  
  When C<allow_bignum> is enable, the big integers 
  and the numeric can be optionally converted into L<Math::BigInt> and
  L<Math::BigFloat> objects.
  
  =item true, false
  
  These JSON atoms become C<JSON::PP::true> and C<JSON::PP::false>,
  respectively. They are overloaded to act almost exactly like the numbers
  C<1> and C<0>. You can check whether a scalar is a JSON boolean by using
  the C<JSON::is_bool> function.
  
     print JSON::PP::true . "\n";
      => true
     print JSON::PP::true + 1;
      => 1
  
     ok(JSON::true eq  '1');
     ok(JSON::true == 1);
  
  C<JSON> will install these missing overloading features to the backend modules.
  
  
  =item null
  
  A JSON null atom becomes C<undef> in Perl.
  
  C<JSON::PP::null> returns C<undef>.
  
  =back
  
  
  =head2 PERL -> JSON
  
  The mapping from Perl to JSON is slightly more difficult, as Perl is a
  truly typeless language, so we can only guess which JSON type is meant by
  a Perl value.
  
  =over 4
  
  =item hash references
  
  Perl hash references become JSON objects. As there is no inherent ordering
  in hash keys (or JSON objects), they will usually be encoded in a
  pseudo-random order that can change between runs of the same program but
  stays generally the same within a single run of a program. C<JSON>
  optionally sort the hash keys (determined by the I<canonical> flag), so
  the same data structure will serialise to the same JSON text (given same
  settings and version of JSON::XS), but this incurs a runtime overhead
  and is only rarely useful, e.g. when you want to compare some JSON text
  against another for equality.
  
  
  =item array references
  
  Perl array references become JSON arrays.
  
  =item other references
  
  Other unblessed references are generally not allowed and will cause an
  exception to be thrown, except for references to the integers C<0> and
  C<1>, which get turned into C<false> and C<true> atoms in JSON. You can
  also use C<JSON::false> and C<JSON::true> to improve readability.
  
     to_json [\0,JSON::PP::true]      # yields [false,true]
  
  =item JSON::PP::true, JSON::PP::false, JSON::PP::null
  
  These special values become JSON true and JSON false values,
  respectively. You can also use C<\1> and C<\0> directly if you want.
  
  JSON::PP::null returns C<undef>.
  
  =item blessed objects
  
  Blessed objects are not directly representable in JSON. See the
  C<allow_blessed> and C<convert_blessed> methods on various options on
  how to deal with this: basically, you can choose between throwing an
  exception, encoding the reference as if it weren't blessed, or provide
  your own serialiser method.
  
  See to L<convert_blessed>.
  
  =item simple scalars
  
  Simple Perl scalars (any scalar that is not a reference) are the most
  difficult objects to encode: JSON::XS and JSON::PP will encode undefined scalars as
  JSON C<null> values, scalars that have last been used in a string context
  before encoding as JSON strings, and anything else as number value:
  
     # dump as number
     encode_json [2]                      # yields [2]
     encode_json [-3.0e17]                # yields [-3e+17]
     my $value = 5; encode_json [$value]  # yields [5]
  
     # used as string, so dump as string
     print $value;
     encode_json [$value]                 # yields ["5"]
  
     # undef becomes null
     encode_json [undef]                  # yields [null]
  
  You can force the type to be a string by stringifying it:
  
     my $x = 3.1; # some variable containing a number
     "$x";        # stringified
     $x .= "";    # another, more awkward way to stringify
     print $x;    # perl does it for you, too, quite often
  
  You can force the type to be a number by numifying it:
  
     my $x = "3"; # some variable containing a string
     $x += 0;     # numify it, ensuring it will be dumped as a number
     $x *= 1;     # same thing, the choice is yours.
  
  You can not currently force the type in other, less obscure, ways.
  
  Note that numerical precision has the same meaning as under Perl (so
  binary to decimal conversion follows the same rules as in Perl, which
  can differ to other languages). Also, your perl interpreter might expose
  extensions to the floating point numbers of your platform, such as
  infinities or NaN's - these cannot be represented in JSON, and it is an
  error to pass those in.
  
  =item Big Number
  
  When C<allow_bignum> is enable, 
  C<encode> converts C<Math::BigInt> objects and C<Math::BigFloat>
  objects into JSON numbers.
  
  
  =back
  
  =head1 UNICODE HANDLING ON PERLS
  
  If you do not know about Unicode on Perl well,
  please check L<JSON::XS/A FEW NOTES ON UNICODE AND PERL>.
  
  =head2 Perl 5.8 and later
  
  Perl can handle Unicode and the JSON::PP de/encode methods also work properly.
  
      $json->allow_nonref->encode(chr hex 3042);
      $json->allow_nonref->encode(chr hex 12345);
  
  Returns C<"\u3042"> and C<"\ud808\udf45"> respectively.
  
      $json->allow_nonref->decode('"\u3042"');
      $json->allow_nonref->decode('"\ud808\udf45"');
  
  Returns UTF-8 encoded strings with UTF8 flag, regarded as C<U+3042> and C<U+12345>.
  
  Note that the versions from Perl 5.8.0 to 5.8.2, Perl built-in C<join> was broken,
  so JSON::PP wraps the C<join> with a subroutine. Thus JSON::PP works slow in the versions.
  
  
  =head2 Perl 5.6
  
  Perl can handle Unicode and the JSON::PP de/encode methods also work.
  
  =head2 Perl 5.005
  
  Perl 5.005 is a byte semantics world -- all strings are sequences of bytes.
  That means the unicode handling is not available.
  
  In encoding,
  
      $json->allow_nonref->encode(chr hex 3042);  # hex 3042 is 12354.
      $json->allow_nonref->encode(chr hex 12345); # hex 12345 is 74565.
  
  Returns C<B> and C<E>, as C<chr> takes a value more than 255, it treats
  as C<$value % 256>, so the above codes are equivalent to :
  
      $json->allow_nonref->encode(chr 66);
      $json->allow_nonref->encode(chr 69);
  
  In decoding,
  
      $json->decode('"\u00e3\u0081\u0082"');
  
  The returned is a byte sequence C<0xE3 0x81 0x82> for UTF-8 encoded
  japanese character (C<HIRAGANA LETTER A>).
  And if it is represented in Unicode code point, C<U+3042>.
  
  Next, 
  
      $json->decode('"\u3042"');
  
  We ordinary expect the returned value is a Unicode character C<U+3042>.
  But here is 5.005 world. This is C<0xE3 0x81 0x82>.
  
      $json->decode('"\ud808\udf45"');
  
  This is not a character C<U+12345> but bytes - C<0xf0 0x92 0x8d 0x85>.
  
  
  =head1 TODO
  
  =over
  
  =item speed
  
  =item memory saving
  
  =back
  
  
  =head1 SEE ALSO
  
  Most of the document are copied and modified from JSON::XS doc.
  
  L<JSON::XS>
  
  RFC4627 (L<http://www.ietf.org/rfc/rfc4627.txt>)
  
  =head1 AUTHOR
  
  Makamaka Hannyaharamitu, E<lt>makamaka[at]cpan.orgE<gt>
  
  
  =head1 COPYRIGHT AND LICENSE
  
  Copyright 2007-2012 by Makamaka Hannyaharamitu
  
  This library is free software; you can redistribute it and/or modify
  it under the same terms as Perl itself. 
  
  =cut
JSON_BACKPORTPP

$fatpacked{"JSON/backportPP/Boolean.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'JSON_BACKPORTPP_BOOLEAN';
  =head1 NAME
  
  JSON::PP::Boolean - dummy module providing JSON::PP::Boolean
  
  =head1 SYNOPSIS
  
   # do not "use" yourself
  
  =head1 DESCRIPTION
  
  This module exists only to provide overload resolution for Storable
  and similar modules. See L<JSON::PP> for more info about this class.
  
  =cut
  
  use JSON::backportPP ();
  use strict;
  
  1;
  
  =head1 AUTHOR
  
  This idea is from L<JSON::XS::Boolean> written by
  Marc Lehmann <schmorp[at]schmorp.de>
  
  =cut
  
JSON_BACKPORTPP_BOOLEAN

$fatpacked{"JSON/backportPP/Compat5005.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'JSON_BACKPORTPP_COMPAT5005';
  package # This is JSON::backportPP
      JSON::backportPP5005;
  
  use 5.005;
  use strict;
  
  my @properties;
  
  $JSON::PP5005::VERSION = '1.10';
  
  BEGIN {
  
      sub utf8::is_utf8 {
          0; # It is considered that UTF8 flag off for Perl 5.005.
      }
  
      sub utf8::upgrade {
      }
  
      sub utf8::downgrade {
          1; # must always return true.
      }
  
      sub utf8::encode  {
      }
  
      sub utf8::decode {
      }
  
      *JSON::PP::JSON_PP_encode_ascii      = \&_encode_ascii;
      *JSON::PP::JSON_PP_encode_latin1     = \&_encode_latin1;
      *JSON::PP::JSON_PP_decode_surrogates = \&_decode_surrogates;
      *JSON::PP::JSON_PP_decode_unicode    = \&_decode_unicode;
  
      # missing in B module.
      sub B::SVp_IOK () { 0x01000000; }
      sub B::SVp_NOK () { 0x02000000; }
      sub B::SVp_POK () { 0x04000000; }
  
      $INC{'bytes.pm'} = 1; # dummy
  }
  
  
  
  sub _encode_ascii {
      join('', map { $_ <= 127 ? chr($_) : sprintf('\u%04x', $_) } unpack('C*', $_[0]) );
  }
  
  
  sub _encode_latin1 {
      join('', map { chr($_) } unpack('C*', $_[0]) );
  }
  
  
  sub _decode_surrogates { # from http://homepage1.nifty.com/nomenclator/unicode/ucs_utf.htm
      my $uni = 0x10000 + (hex($_[0]) - 0xD800) * 0x400 + (hex($_[1]) - 0xDC00); # from perlunicode
      my $bit = unpack('B32', pack('N', $uni));
  
      if ( $bit =~ /^00000000000(...)(......)(......)(......)$/ ) {
          my ($w, $x, $y, $z) = ($1, $2, $3, $4);
          return pack('B*', sprintf('11110%s10%s10%s10%s', $w, $x, $y, $z));
      }
      else {
          Carp::croak("Invalid surrogate pair");
      }
  }
  
  
  sub _decode_unicode {
      my ($u) = @_;
      my ($utf8bit);
  
      if ( $u =~ /^00([89a-f][0-9a-f])$/i ) { # 0x80-0xff
           return pack( 'H2', $1 );
      }
  
      my $bit = unpack("B*", pack("H*", $u));
  
      if ( $bit =~ /^00000(.....)(......)$/ ) {
          $utf8bit = sprintf('110%s10%s', $1, $2);
      }
      elsif ( $bit =~ /^(....)(......)(......)$/ ) {
          $utf8bit = sprintf('1110%s10%s10%s', $1, $2, $3);
      }
      else {
          Carp::croak("Invalid escaped unicode");
      }
  
      return pack('B*', $utf8bit);
  }
  
  
  sub JSON::PP::incr_text {
      $_[0]->{_incr_parser} ||= JSON::PP::IncrParser->new;
  
      if ( $_[0]->{_incr_parser}->{incr_parsing} ) {
          Carp::croak("incr_text can not be called when the incremental parser already started parsing");
      }
  
      $_[0]->{_incr_parser}->{incr_text} = $_[1] if ( @_ > 1 );
      $_[0]->{_incr_parser}->{incr_text};
  }
  
  
  1;
  __END__
  
  =pod
  
  =head1 NAME
  
  JSON::PP5005 - Helper module in using JSON::PP in Perl 5.005
  
  =head1 DESCRIPTION
  
  JSON::PP calls internally.
  
  =head1 AUTHOR
  
  Makamaka Hannyaharamitu, E<lt>makamaka[at]cpan.orgE<gt>
  
  
  =head1 COPYRIGHT AND LICENSE
  
  Copyright 2007-2012 by Makamaka Hannyaharamitu
  
  This library is free software; you can redistribute it and/or modify
  it under the same terms as Perl itself. 
  
  =cut
  
JSON_BACKPORTPP_COMPAT5005

$fatpacked{"JSON/backportPP/Compat5006.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'JSON_BACKPORTPP_COMPAT5006';
  package # This is JSON::backportPP
      JSON::backportPP56;
  
  use 5.006;
  use strict;
  
  my @properties;
  
  $JSON::PP56::VERSION = '1.08';
  
  BEGIN {
  
      sub utf8::is_utf8 {
          my $len =  length $_[0]; # char length
          {
              use bytes; #  byte length;
              return $len != length $_[0]; # if !=, UTF8-flagged on.
          }
      }
  
  
      sub utf8::upgrade {
          ; # noop;
      }
  
  
      sub utf8::downgrade ($;$) {
          return 1 unless ( utf8::is_utf8( $_[0] ) );
  
          if ( _is_valid_utf8( $_[0] ) ) {
              my $downgrade;
              for my $c ( unpack( "U*", $_[0] ) ) {
                  if ( $c < 256 ) {
                      $downgrade .= pack("C", $c);
                  }
                  else {
                      $downgrade .= pack("U", $c);
                  }
              }
              $_[0] = $downgrade;
              return 1;
          }
          else {
              Carp::croak("Wide character in subroutine entry") unless ( $_[1] );
              0;
          }
      }
  
  
      sub utf8::encode ($) { # UTF8 flag off
          if ( utf8::is_utf8( $_[0] ) ) {
              $_[0] = pack( "C*", unpack( "C*", $_[0] ) );
          }
          else {
              $_[0] = pack( "U*", unpack( "C*", $_[0] ) );
              $_[0] = pack( "C*", unpack( "C*", $_[0] ) );
          }
      }
  
  
      sub utf8::decode ($) { # UTF8 flag on
          if ( _is_valid_utf8( $_[0] ) ) {
              utf8::downgrade( $_[0] );
              $_[0] = pack( "U*", unpack( "U*", $_[0] ) );
          }
      }
  
  
      *JSON::PP::JSON_PP_encode_ascii      = \&_encode_ascii;
      *JSON::PP::JSON_PP_encode_latin1     = \&_encode_latin1;
      *JSON::PP::JSON_PP_decode_surrogates = \&JSON::PP::_decode_surrogates;
      *JSON::PP::JSON_PP_decode_unicode    = \&JSON::PP::_decode_unicode;
  
      unless ( defined &B::SVp_NOK ) { # missing in B module.
          eval q{ sub B::SVp_NOK () { 0x02000000; } };
      }
  
  }
  
  
  
  sub _encode_ascii {
      join('',
          map {
              $_ <= 127 ?
                  chr($_) :
              $_ <= 65535 ?
                  sprintf('\u%04x', $_) : sprintf('\u%x\u%x', JSON::PP::_encode_surrogates($_));
          } _unpack_emu($_[0])
      );
  }
  
  
  sub _encode_latin1 {
      join('',
          map {
              $_ <= 255 ?
                  chr($_) :
              $_ <= 65535 ?
                  sprintf('\u%04x', $_) : sprintf('\u%x\u%x', JSON::PP::_encode_surrogates($_));
          } _unpack_emu($_[0])
      );
  }
  
  
  sub _unpack_emu { # for Perl 5.6 unpack warnings
      return   !utf8::is_utf8($_[0]) ? unpack('C*', $_[0]) 
             : _is_valid_utf8($_[0]) ? unpack('U*', $_[0])
             : unpack('C*', $_[0]);
  }
  
  
  sub _is_valid_utf8 {
      my $str = $_[0];
      my $is_utf8;
  
      while ($str =~ /(?:
            (
               [\x00-\x7F]
              |[\xC2-\xDF][\x80-\xBF]
              |[\xE0][\xA0-\xBF][\x80-\xBF]
              |[\xE1-\xEC][\x80-\xBF][\x80-\xBF]
              |[\xED][\x80-\x9F][\x80-\xBF]
              |[\xEE-\xEF][\x80-\xBF][\x80-\xBF]
              |[\xF0][\x90-\xBF][\x80-\xBF][\x80-\xBF]
              |[\xF1-\xF3][\x80-\xBF][\x80-\xBF][\x80-\xBF]
              |[\xF4][\x80-\x8F][\x80-\xBF][\x80-\xBF]
            )
          | (.)
      )/xg)
      {
          if (defined $1) {
              $is_utf8 = 1 if (!defined $is_utf8);
          }
          else {
              $is_utf8 = 0 if (!defined $is_utf8);
              if ($is_utf8) { # eventually, not utf8
                  return;
              }
          }
      }
  
      return $is_utf8;
  }
  
  
  1;
  __END__
  
  =pod
  
  =head1 NAME
  
  JSON::PP56 - Helper module in using JSON::PP in Perl 5.6
  
  =head1 DESCRIPTION
  
  JSON::PP calls internally.
  
  =head1 AUTHOR
  
  Makamaka Hannyaharamitu, E<lt>makamaka[at]cpan.orgE<gt>
  
  
  =head1 COPYRIGHT AND LICENSE
  
  Copyright 2007-2012 by Makamaka Hannyaharamitu
  
  This library is free software; you can redistribute it and/or modify
  it under the same terms as Perl itself. 
  
  =cut
  
JSON_BACKPORTPP_COMPAT5006

$fatpacked{"LWP.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'LWP';
  package LWP;
  
  $VERSION = "6.05";
  sub Version { $VERSION; }
  
  require 5.008;
  require LWP::UserAgent;  # this should load everything you need
  
  1;
  
  __END__
  
  =encoding utf-8
  
  =head1 NAME
  
  LWP - The World-Wide Web library for Perl
  
  =head1 SYNOPSIS
  
    use LWP;
    print "This is libwww-perl-$LWP::VERSION\n";
  
  
  =head1 DESCRIPTION
  
  The libwww-perl collection is a set of Perl modules which provides a
  simple and consistent application programming interface (API) to the
  World-Wide Web.  The main focus of the library is to provide classes
  and functions that allow you to write WWW clients. The library also
  contain modules that are of more general use and even classes that
  help you implement simple HTTP servers.
  
  Most modules in this library provide an object oriented API.  The user
  agent, requests sent and responses received from the WWW server are
  all represented by objects.  This makes a simple and powerful
  interface to these services.  The interface is easy to extend
  and customize for your own needs.
  
  The main features of the library are:
  
  =over 3
  
  =item *
  
  Contains various reusable components (modules) that can be
  used separately or together.
  
  =item *
  
  Provides an object oriented model of HTTP-style communication.  Within
  this framework we currently support access to http, https, gopher, ftp, news,
  file, and mailto resources.
  
  =item *
  
  Provides a full object oriented interface or
  a very simple procedural interface.
  
  =item *
  
  Supports the basic and digest authorization schemes.
  
  =item *
  
  Supports transparent redirect handling.
  
  =item *
  
  Supports access through proxy servers.
  
  =item *
  
  Provides parser for F<robots.txt> files and a framework for constructing robots.
  
  =item *
  
  Supports parsing of HTML forms.
  
  =item *
  
  Implements HTTP content negotiation algorithm that can
  be used both in protocol modules and in server scripts (like CGI
  scripts).
  
  =item *
  
  Supports HTTP cookies.
  
  =item *
  
  Some simple command line clients, for instance C<lwp-request> and C<lwp-download>.
  
  =back
  
  
  =head1 HTTP STYLE COMMUNICATION
  
  
  The libwww-perl library is based on HTTP style communication. This
  section tries to describe what that means.
  
  Let us start with this quote from the HTTP specification document
  <URL:http://www.w3.org/Protocols/>:
  
  =over 3
  
  =item
  
  The HTTP protocol is based on a request/response paradigm. A client
  establishes a connection with a server and sends a request to the
  server in the form of a request method, URI, and protocol version,
  followed by a MIME-like message containing request modifiers, client
  information, and possible body content. The server responds with a
  status line, including the message's protocol version and a success or
  error code, followed by a MIME-like message containing server
  information, entity meta-information, and possible body content.
  
  =back
  
  What this means to libwww-perl is that communication always take place
  through these steps: First a I<request> object is created and
  configured. This object is then passed to a server and we get a
  I<response> object in return that we can examine. A request is always
  independent of any previous requests, i.e. the service is stateless.
  The same simple model is used for any kind of service we want to
  access.
  
  For example, if we want to fetch a document from a remote file server,
  then we send it a request that contains a name for that document and
  the response will contain the document itself.  If we access a search
  engine, then the content of the request will contain the query
  parameters and the response will contain the query result.  If we want
  to send a mail message to somebody then we send a request object which
  contains our message to the mail server and the response object will
  contain an acknowledgment that tells us that the message has been
  accepted and will be forwarded to the recipient(s).
  
  It is as simple as that!
  
  
  =head2 The Request Object
  
  The libwww-perl request object has the class name C<HTTP::Request>.
  The fact that the class name uses C<HTTP::> as a
  prefix only implies that we use the HTTP model of communication.  It
  does not limit the kind of services we can try to pass this I<request>
  to.  For instance, we will send C<HTTP::Request>s both to ftp and
  gopher servers, as well as to the local file system.
  
  The main attributes of the request objects are:
  
  =over 3
  
  =item *
  
  B<method> is a short string that tells what kind of
  request this is.  The most common methods are B<GET>, B<PUT>,
  B<POST> and B<HEAD>.
  
  =item *
  
  B<uri> is a string denoting the protocol, server and
  the name of the "document" we want to access.  The B<uri> might
  also encode various other parameters.
  
  =item *
  
  B<headers> contains additional information about the
  request and can also used to describe the content.  The headers
  are a set of keyword/value pairs.
  
  =item *
  
  B<content> is an arbitrary amount of data.
  
  =back
  
  =head2 The Response Object
  
  The libwww-perl response object has the class name C<HTTP::Response>.
  The main attributes of objects of this class are:
  
  =over 3
  
  =item *
  
  B<code> is a numerical value that indicates the overall
  outcome of the request.
  
  =item *
  
  B<message> is a short, human readable string that
  corresponds to the I<code>.
  
  =item *
  
  B<headers> contains additional information about the
  response and describe the content.
  
  =item *
  
  B<content> is an arbitrary amount of data.
  
  =back
  
  Since we don't want to handle all possible I<code> values directly in
  our programs, a libwww-perl response object has methods that can be
  used to query what kind of response this is.  The most commonly used
  response classification methods are:
  
  =over 3
  
  =item is_success()
  
  The request was successfully received, understood or accepted.
  
  =item is_error()
  
  The request failed.  The server or the resource might not be
  available, access to the resource might be denied or other things might
  have failed for some reason.
  
  =back
  
  =head2 The User Agent
  
  Let us assume that we have created a I<request> object. What do we
  actually do with it in order to receive a I<response>?
  
  The answer is that you pass it to a I<user agent> object and this
  object takes care of all the things that need to be done
  (like low-level communication and error handling) and returns
  a I<response> object. The user agent represents your
  application on the network and provides you with an interface that
  can accept I<requests> and return I<responses>.
  
  The user agent is an interface layer between
  your application code and the network.  Through this interface you are
  able to access the various servers on the network.
  
  The class name for the user agent is C<LWP::UserAgent>.  Every
  libwww-perl application that wants to communicate should create at
  least one object of this class. The main method provided by this
  object is request(). This method takes an C<HTTP::Request> object as
  argument and (eventually) returns a C<HTTP::Response> object.
  
  The user agent has many other attributes that let you
  configure how it will interact with the network and with your
  application.
  
  =over 3
  
  =item *
  
  B<timeout> specifies how much time we give remote servers to
  respond before the library disconnects and creates an
  internal I<timeout> response.
  
  =item *
  
  B<agent> specifies the name that your application uses when it
  presents itself on the network.
  
  =item *
  
  B<from> can be set to the e-mail address of the person
  responsible for running the application.  If this is set, then the
  address will be sent to the servers with every request.
  
  =item *
  
  B<parse_head> specifies whether we should initialize response
  headers from the E<lt>head> section of HTML documents.
  
  =item *
  
  B<proxy> and B<no_proxy> specify if and when to go through
  a proxy server. <URL:http://www.w3.org/History/1994/WWW/Proxies/>
  
  =item *
  
  B<credentials> provides a way to set up user names and
  passwords needed to access certain services.
  
  =back
  
  Many applications want even more control over how they interact
  with the network and they get this by sub-classing
  C<LWP::UserAgent>.  The library includes a
  sub-class, C<LWP::RobotUA>, for robot applications.
  
  =head2 An Example
  
  This example shows how the user agent, a request and a response are
  represented in actual perl code:
  
    # Create a user agent object
    use LWP::UserAgent;
    my $ua = LWP::UserAgent->new;
    $ua->agent("MyApp/0.1 ");
  
    # Create a request
    my $req = HTTP::Request->new(POST => 'http://search.cpan.org/search');
    $req->content_type('application/x-www-form-urlencoded');
    $req->content('query=libwww-perl&mode=dist');
  
    # Pass request to the user agent and get a response back
    my $res = $ua->request($req);
  
    # Check the outcome of the response
    if ($res->is_success) {
        print $res->content;
    }
    else {
        print $res->status_line, "\n";
    }
  
  The $ua is created once when the application starts up.  New request
  objects should normally created for each request sent.
  
  
  =head1 NETWORK SUPPORT
  
  This section discusses the various protocol schemes and
  the HTTP style methods that headers may be used for each.
  
  For all requests, a "User-Agent" header is added and initialized from
  the $ua->agent attribute before the request is handed to the network
  layer.  In the same way, a "From" header is initialized from the
  $ua->from attribute.
  
  For all responses, the library adds a header called "Client-Date".
  This header holds the time when the response was received by
  your application.  The format and semantics of the header are the
  same as the server created "Date" header.  You may also encounter other
  "Client-XXX" headers.  They are all generated by the library
  internally and are not received from the servers.
  
  =head2 HTTP Requests
  
  HTTP requests are just handed off to an HTTP server and it
  decides what happens.  Few servers implement methods beside the usual
  "GET", "HEAD", "POST" and "PUT", but CGI-scripts may implement
  any method they like.
  
  If the server is not available then the library will generate an
  internal error response.
  
  The library automatically adds a "Host" and a "Content-Length" header
  to the HTTP request before it is sent over the network.
  
  For a GET request you might want to add a "If-Modified-Since" or
  "If-None-Match" header to make the request conditional.
  
  For a POST request you should add the "Content-Type" header.  When you
  try to emulate HTML E<lt>FORM> handling you should usually let the value
  of the "Content-Type" header be "application/x-www-form-urlencoded".
  See L<lwpcook> for examples of this.
  
  The libwww-perl HTTP implementation currently support the HTTP/1.1
  and HTTP/1.0 protocol.
  
  The library allows you to access proxy server through HTTP.  This
  means that you can set up the library to forward all types of request
  through the HTTP protocol module.  See L<LWP::UserAgent> for
  documentation of this.
  
  
  =head2 HTTPS Requests
  
  HTTPS requests are HTTP requests over an encrypted network connection
  using the SSL protocol developed by Netscape.  Everything about HTTP
  requests above also apply to HTTPS requests.  In addition the library
  will add the headers "Client-SSL-Cipher", "Client-SSL-Cert-Subject" and
  "Client-SSL-Cert-Issuer" to the response.  These headers denote the
  encryption method used and the name of the server owner.
  
  The request can contain the header "If-SSL-Cert-Subject" in order to
  make the request conditional on the content of the server certificate.
  If the certificate subject does not match, no request is sent to the
  server and an internally generated error response is returned.  The
  value of the "If-SSL-Cert-Subject" header is interpreted as a Perl
  regular expression.
  
  
  =head2 FTP Requests
  
  The library currently supports GET, HEAD and PUT requests.  GET
  retrieves a file or a directory listing from an FTP server.  PUT
  stores a file on a ftp server.
  
  You can specify a ftp account for servers that want this in addition
  to user name and password.  This is specified by including an "Account"
  header in the request.
  
  User name/password can be specified using basic authorization or be
  encoded in the URL.  Failed logins return an UNAUTHORIZED response with
  "WWW-Authenticate: Basic" and can be treated like basic authorization
  for HTTP.
  
  The library supports ftp ASCII transfer mode by specifying the "type=a"
  parameter in the URL. It also supports transfer of ranges for FTP transfers
  using the "Range" header.
  
  Directory listings are by default returned unprocessed (as returned
  from the ftp server) with the content media type reported to be
  "text/ftp-dir-listing". The C<File::Listing> module provides methods
  for parsing of these directory listing.
  
  The ftp module is also able to convert directory listings to HTML and
  this can be requested via the standard HTTP content negotiation
  mechanisms (add an "Accept: text/html" header in the request if you
  want this).
  
  For normal file retrievals, the "Content-Type" is guessed based on the
  file name suffix. See L<LWP::MediaTypes>.
  
  The "If-Modified-Since" request header works for servers that implement
  the MDTM command.  It will probably not work for directory listings though.
  
  Example:
  
    $req = HTTP::Request->new(GET => 'ftp://me:passwd@ftp.some.where.com/');
    $req->header(Accept => "text/html, */*;q=0.1");
  
  =head2 News Requests
  
  Access to the USENET News system is implemented through the NNTP
  protocol.  The name of the news server is obtained from the
  NNTP_SERVER environment variable and defaults to "news".  It is not
  possible to specify the hostname of the NNTP server in news: URLs.
  
  The library supports GET and HEAD to retrieve news articles through the
  NNTP protocol.  You can also post articles to newsgroups by using
  (surprise!) the POST method.
  
  GET on newsgroups is not implemented yet.
  
  Examples:
  
    $req = HTTP::Request->new(GET => 'news:abc1234@a.sn.no');
  
    $req = HTTP::Request->new(POST => 'news:comp.lang.perl.test');
    $req->header(Subject => 'This is a test',
                 From    => 'me@some.where.org');
    $req->content(<<EOT);
    This is the content of the message that we are sending to
    the world.
    EOT
  
  
  =head2 Gopher Request
  
  The library supports the GET and HEAD methods for gopher requests.  All
  request header values are ignored.  HEAD cheats and returns a
  response without even talking to server.
  
  Gopher menus are always converted to HTML.
  
  The response "Content-Type" is generated from the document type
  encoded (as the first letter) in the request URL path itself.
  
  Example:
  
    $req = HTTP::Request->new(GET => 'gopher://gopher.sn.no/');
  
  
  
  =head2 File Request
  
  The library supports GET and HEAD methods for file requests.  The
  "If-Modified-Since" header is supported.  All other headers are
  ignored.  The I<host> component of the file URL must be empty or set
  to "localhost".  Any other I<host> value will be treated as an error.
  
  Directories are always converted to an HTML document.  For normal
  files, the "Content-Type" and "Content-Encoding" in the response are
  guessed based on the file suffix.
  
  Example:
  
    $req = HTTP::Request->new(GET => 'file:/etc/passwd');
  
  
  =head2 Mailto Request
  
  You can send (aka "POST") mail messages using the library.  All
  headers specified for the request are passed on to the mail system.
  The "To" header is initialized from the mail address in the URL.
  
  Example:
  
    $req = HTTP::Request->new(POST => 'mailto:libwww@perl.org');
    $req->header(Subject => "subscribe");
    $req->content("Please subscribe me to the libwww-perl mailing list!\n");
  
  =head2 CPAN Requests
  
  URLs with scheme C<cpan:> are redirected to the a suitable CPAN
  mirror.  If you have your own local mirror of CPAN you might tell LWP
  to use it for C<cpan:> URLs by an assignment like this:
  
    $LWP::Protocol::cpan::CPAN = "file:/local/CPAN/";
  
  Suitable CPAN mirrors are also picked up from the configuration for
  the CPAN.pm, so if you have used that module a suitable mirror should
  be picked automatically.  If neither of these apply, then a redirect
  to the generic CPAN http location is issued.
  
  Example request to download the newest perl:
  
    $req = HTTP::Request->new(GET => "cpan:src/latest.tar.gz");
  
  
  =head1 OVERVIEW OF CLASSES AND PACKAGES
  
  This table should give you a quick overview of the classes provided by the
  library. Indentation shows class inheritance.
  
   LWP::MemberMixin   -- Access to member variables of Perl5 classes
     LWP::UserAgent   -- WWW user agent class
       LWP::RobotUA   -- When developing a robot applications
     LWP::Protocol          -- Interface to various protocol schemes
       LWP::Protocol::http  -- http:// access
       LWP::Protocol::file  -- file:// access
       LWP::Protocol::ftp   -- ftp:// access
       ...
  
   LWP::Authen::Basic -- Handle 401 and 407 responses
   LWP::Authen::Digest
  
   HTTP::Headers      -- MIME/RFC822 style header (used by HTTP::Message)
   HTTP::Message      -- HTTP style message
     HTTP::Request    -- HTTP request
     HTTP::Response   -- HTTP response
   HTTP::Daemon       -- A HTTP server class
  
   WWW::RobotRules    -- Parse robots.txt files
     WWW::RobotRules::AnyDBM_File -- Persistent RobotRules
  
   Net::HTTP          -- Low level HTTP client
  
  The following modules provide various functions and definitions.
  
   LWP                -- This file.  Library version number and documentation.
   LWP::MediaTypes    -- MIME types configuration (text/html etc.)
   LWP::Simple        -- Simplified procedural interface for common functions
   HTTP::Status       -- HTTP status code (200 OK etc)
   HTTP::Date         -- Date parsing module for HTTP date formats
   HTTP::Negotiate    -- HTTP content negotiation calculation
   File::Listing      -- Parse directory listings
   HTML::Form         -- Processing for <form>s in HTML documents
  
  
  =head1 MORE DOCUMENTATION
  
  All modules contain detailed information on the interfaces they
  provide.  The L<lwpcook> manpage is the libwww-perl cookbook that contain
  examples of typical usage of the library.  You might want to take a
  look at how the scripts L<lwp-request>, L<lwp-download>, L<lwp-dump>
  and L<lwp-mirror> are implemented.
  
  =head1 ENVIRONMENT
  
  The following environment variables are used by LWP:
  
  =over
  
  =item HOME
  
  The C<LWP::MediaTypes> functions will look for the F<.media.types> and
  F<.mime.types> files relative to you home directory.
  
  =item http_proxy
  
  =item ftp_proxy
  
  =item xxx_proxy
  
  =item no_proxy
  
  These environment variables can be set to enable communication through
  a proxy server.  See the description of the C<env_proxy> method in
  L<LWP::UserAgent>.
  
  =item PERL_LWP_ENV_PROXY
  
  If set to a TRUE value, then the C<LWP::UserAgent> will by default call
  C<env_proxy> during initialization.  This makes LWP honor the proxy variables
  described above.
  
  =item PERL_LWP_SSL_VERIFY_HOSTNAME
  
  The default C<verify_hostname> setting for C<LWP::UserAgent>.  If
  not set the default will be 1.  Set it as 0 to disable hostname
  verification (the default prior to libwww-perl 5.840.
  
  =item PERL_LWP_SSL_CA_FILE
  
  =item PERL_LWP_SSL_CA_PATH
  
  The file and/or directory
  where the trusted Certificate Authority certificates
  is located.  See L<LWP::UserAgent> for details.
  
  =item PERL_HTTP_URI_CLASS
  
  Used to decide what URI objects to instantiate.  The default is C<URI>.
  You might want to set it to C<URI::URL> for compatibility with old times.
  
  =back
  
  =head1 AUTHORS
  
  LWP was made possible by contributions from Adam Newby, Albert
  Dvornik, Alexandre Duret-Lutz, Andreas Gustafsson, Andreas König,
  Andrew Pimlott, Andy Lester, Ben Coleman, Benjamin Low, Ben Low, Ben
  Tilly, Blair Zajac, Bob Dalgleish, BooK, Brad Hughes, Brian
  J. Murrell, Brian McCauley, Charles C. Fu, Charles Lane, Chris Nandor,
  Christian Gilmore, Chris W. Unger, Craig Macdonald, Dale Couch, Dan
  Kubb, Dave Dunkin, Dave W. Smith, David Coppit, David Dick, David
  D. Kilzer, Doug MacEachern, Edward Avis, erik, Gary Shea, Gisle Aas,
  Graham Barr, Gurusamy Sarathy, Hans de Graaff, Harald Joerg, Harry
  Bochner, Hugo, Ilya Zakharevich, INOUE Yoshinari, Ivan Panchenko, Jack
  Shirazi, James Tillman, Jan Dubois, Jared Rhine, Jim Stern, Joao
  Lopes, John Klar, Johnny Lee, Josh Kronengold, Josh Rai, Joshua
  Chamas, Joshua Hoblitt, Kartik Subbarao, Keiichiro Nagano, Ken
  Williams, KONISHI Katsuhiro, Lee T Lindley, Liam Quinn, Marc Hedlund,
  Marc Langheinrich, Mark D. Anderson, Marko Asplund, Mark Stosberg,
  Markus B Krüger, Markus Laker, Martijn Koster, Martin Thurn, Matthew
  Eldridge, Matthew.van.Eerde, Matt Sergeant, Michael A. Chase, Michael
  Quaranta, Michael Thompson, Mike Schilli, Moshe Kaminsky, Nathan
  Torkington, Nicolai Langfeldt, Norton Allen, Olly Betts, Paul
  J. Schinder, peterm, Philip GuentherDaniel Buenzli, Pon Hwa Lin,
  Radoslaw Zielinski, Radu Greab, Randal L. Schwartz, Richard Chen,
  Robin Barker, Roy Fielding, Sander van Zoest, Sean M. Burke,
  shildreth, Slaven Rezic, Steve A Fink, Steve Hay, Steven Butler,
  Steve_Kilbane, Takanori Ugai, Thomas Lotterer, Tim Bunce, Tom Hughes,
  Tony Finch, Ville Skyttä, Ward Vandewege, William York, Yale Huang,
  and Yitzchak Scott-Thoennes.
  
  LWP owes a lot in motivation, design, and code, to the libwww-perl
  library for Perl4 by Roy Fielding, which included work from Alberto
  Accomazzi, James Casey, Brooks Cutter, Martijn Koster, Oscar
  Nierstrasz, Mel Melchner, Gertjan van Oosten, Jared Rhine, Jack
  Shirazi, Gene Spafford, Marc VanHeyningen, Steven E. Brenner, Marion
  Hakanson, Waldemar Kebsch, Tony Sanders, and Larry Wall; see the
  libwww-perl-0.40 library for details.
  
  =head1 COPYRIGHT
  
    Copyright 1995-2009, Gisle Aas
    Copyright 1995, Martijn Koster
  
  This library is free software; you can redistribute it and/or
  modify it under the same terms as Perl itself.
  
  =head1 AVAILABILITY
  
  The latest version of this library is likely to be available from CPAN
  as well as:
  
    http://github.com/libwww-perl/libwww-perl
  
  The best place to discuss this code is on the <libwww@perl.org>
  mailing list.
  
  =cut
LWP

$fatpacked{"LWP/Authen/Basic.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'LWP_AUTHEN_BASIC';
  package LWP::Authen::Basic;
  use strict;
  
  require MIME::Base64;
  
  sub auth_header {
      my($class, $user, $pass) = @_;
      return "Basic " . MIME::Base64::encode("$user:$pass", "");
  }
  
  sub authenticate
  {
      my($class, $ua, $proxy, $auth_param, $response,
         $request, $arg, $size) = @_;
  
      my $realm = $auth_param->{realm} || "";
      my $url = $proxy ? $request->{proxy} : $request->uri_canonical;
      return $response unless $url;
      my $host_port = $url->host_port;
      my $auth_header = $proxy ? "Proxy-Authorization" : "Authorization";
  
      my @m = $proxy ? (m_proxy => $url) : (m_host_port => $host_port);
      push(@m, realm => $realm);
  
      my $h = $ua->get_my_handler("request_prepare", @m, sub {
          $_[0]{callback} = sub {
              my($req, $ua, $h) = @_;
              my($user, $pass) = $ua->credentials($host_port, $h->{realm});
  	    if (defined $user) {
  		my $auth_value = $class->auth_header($user, $pass, $req, $ua, $h);
  		$req->header($auth_header => $auth_value);
  	    }
          };
      });
      $h->{auth_param} = $auth_param;
  
      if (!$proxy && !$request->header($auth_header) && $ua->credentials($host_port, $realm)) {
  	# we can make sure this handler applies and retry
          add_path($h, $url->path);
          return $ua->request($request->clone, $arg, $size, $response);
      }
  
      my($user, $pass) = $ua->get_basic_credentials($realm, $url, $proxy);
      unless (defined $user and defined $pass) {
  	$ua->set_my_handler("request_prepare", undef, @m);  # delete handler
  	return $response;
      }
  
      # check that the password has changed
      my ($olduser, $oldpass) = $ua->credentials($host_port, $realm);
      return $response if (defined $olduser and defined $oldpass and
                           $user eq $olduser and $pass eq $oldpass);
  
      $ua->credentials($host_port, $realm, $user, $pass);
      add_path($h, $url->path) unless $proxy;
      return $ua->request($request->clone, $arg, $size, $response);
  }
  
  sub add_path {
      my($h, $path) = @_;
      $path =~ s,[^/]+\z,,;
      push(@{$h->{m_path_prefix}}, $path);
  }
  
  1;
LWP_AUTHEN_BASIC

$fatpacked{"LWP/Authen/Digest.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'LWP_AUTHEN_DIGEST';
  package LWP::Authen::Digest;
  
  use strict;
  use base 'LWP::Authen::Basic';
  
  require Digest::MD5;
  
  sub auth_header {
      my($class, $user, $pass, $request, $ua, $h) = @_;
  
      my $auth_param = $h->{auth_param};
  
      my $nc = sprintf "%08X", ++$ua->{authen_md5_nonce_count}{$auth_param->{nonce}};
      my $cnonce = sprintf "%8x", time;
  
      my $uri = $request->uri->path_query;
      $uri = "/" unless length $uri;
  
      my $md5 = Digest::MD5->new;
  
      my(@digest);
      $md5->add(join(":", $user, $auth_param->{realm}, $pass));
      push(@digest, $md5->hexdigest);
      $md5->reset;
  
      push(@digest, $auth_param->{nonce});
  
      if ($auth_param->{qop}) {
  	push(@digest, $nc, $cnonce, ($auth_param->{qop} =~ m|^auth[,;]auth-int$|) ? 'auth' : $auth_param->{qop});
      }
  
      $md5->add(join(":", $request->method, $uri));
      push(@digest, $md5->hexdigest);
      $md5->reset;
  
      $md5->add(join(":", @digest));
      my($digest) = $md5->hexdigest;
      $md5->reset;
  
      my %resp = map { $_ => $auth_param->{$_} } qw(realm nonce opaque);
      @resp{qw(username uri response algorithm)} = ($user, $uri, $digest, "MD5");
  
      if (($auth_param->{qop} || "") =~ m|^auth([,;]auth-int)?$|) {
  	@resp{qw(qop cnonce nc)} = ("auth", $cnonce, $nc);
      }
  
      my(@order) = qw(username realm qop algorithm uri nonce nc cnonce response);
      if($request->method =~ /^(?:POST|PUT)$/) {
  	$md5->add($request->content);
  	my $content = $md5->hexdigest;
  	$md5->reset;
  	$md5->add(join(":", @digest[0..1], $content));
  	$md5->reset;
  	$resp{"message-digest"} = $md5->hexdigest;
  	push(@order, "message-digest");
      }
      push(@order, "opaque");
      my @pairs;
      for (@order) {
  	next unless defined $resp{$_};
  	push(@pairs, "$_=" . qq("$resp{$_}"));
      }
  
      my $auth_value  = "Digest " . join(", ", @pairs);
      return $auth_value;
  }
  
  1;
LWP_AUTHEN_DIGEST

$fatpacked{"LWP/Authen/Ntlm.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'LWP_AUTHEN_NTLM';
  package LWP::Authen::Ntlm;
  
  use strict;
  use vars qw/$VERSION/;
  
  $VERSION = "6.00";
  
  use Authen::NTLM "1.02";
  use MIME::Base64 "2.12";
  
  sub authenticate {
      my($class, $ua, $proxy, $auth_param, $response,
         $request, $arg, $size) = @_;
  
      my($user, $pass) = $ua->get_basic_credentials($auth_param->{realm},
                                                    $request->uri, $proxy);
  
      unless(defined $user and defined $pass) {
  		return $response;
  	}
  
  	if (!$ua->conn_cache()) {
  		warn "The keep_alive option must be enabled for NTLM authentication to work.  NTLM authentication aborted.\n";
  		return $response;
  	}
  
  	my($domain, $username) = split(/\\/, $user);
  
  	ntlm_domain($domain);
  	ntlm_user($username);
  	ntlm_password($pass);
  
      my $auth_header = $proxy ? "Proxy-Authorization" : "Authorization";
  
  	# my ($challenge) = $response->header('WWW-Authenticate'); 
  	my $challenge;
  	foreach ($response->header('WWW-Authenticate')) { 
  		last if /^NTLM/ && ($challenge=$_);
  	}
  
  	if ($challenge eq 'NTLM') {
  		# First phase, send handshake
  	    my $auth_value = "NTLM " . ntlm();
  		ntlm_reset();
  
  	    # Need to check this isn't a repeated fail!
  	    my $r = $response;
  		my $retry_count = 0;
  	    while ($r) {
  			my $auth = $r->request->header($auth_header);
  			++$retry_count if ($auth && $auth eq $auth_value);
  			if ($retry_count > 2) {
  				    # here we know this failed before
  				    $response->header("Client-Warning" =>
  						      "Credentials for '$user' failed before");
  				    return $response;
  			}
  			$r = $r->previous;
  	    }
  
  	    my $referral = $request->clone;
  	    $referral->header($auth_header => $auth_value);
  	    return $ua->request($referral, $arg, $size, $response);
  	}
  	
  	else {
  		# Second phase, use the response challenge (unless non-401 code
  		#  was returned, in which case, we just send back the response
  		#  object, as is
  		my $auth_value;
  		if ($response->code ne '401') {
  			return $response;
  		}
  		else {
  			my $challenge;
  			foreach ($response->header('WWW-Authenticate')) { 
  				last if /^NTLM/ && ($challenge=$_);
  			}
  			$challenge =~ s/^NTLM //;
  			ntlm();
  			$auth_value = "NTLM " . ntlm($challenge);
  			ntlm_reset();
  		}
  
  	    my $referral = $request->clone;
  	    $referral->header($auth_header => $auth_value);
  	    my $response2 = $ua->request($referral, $arg, $size, $response);
  		return $response2;
  	}
  }
  
  1;
  
  
  =head1 NAME
  
  LWP::Authen::Ntlm - Library for enabling NTLM authentication (Microsoft) in LWP
  
  =head1 SYNOPSIS
  
   use LWP::UserAgent;
   use HTTP::Request::Common;
   my $url = 'http://www.company.com/protected_page.html';
  
   # Set up the ntlm client and then the base64 encoded ntlm handshake message
   my $ua = LWP::UserAgent->new(keep_alive=>1);
   $ua->credentials('www.company.com:80', '', "MyDomain\\MyUserCode", 'MyPassword');
  
   $request = GET $url;
   print "--Performing request now...-----------\n";
   $response = $ua->request($request);
   print "--Done with request-------------------\n";
  
   if ($response->is_success) {print "It worked!->" . $response->code . "\n"}
   else {print "It didn't work!->" . $response->code . "\n"}
  
  =head1 DESCRIPTION
  
  C<LWP::Authen::Ntlm> allows LWP to authenticate against servers that are using the 
  NTLM authentication scheme popularized by Microsoft.  This type of authentication is 
  common on intranets of Microsoft-centric organizations.
  
  The module takes advantage of the Authen::NTLM module by Mark Bush.  Since there 
  is also another Authen::NTLM module available from CPAN by Yee Man Chan with an 
  entirely different interface, it is necessary to ensure that you have the correct 
  NTLM module.
  
  In addition, there have been problems with incompatibilities between different 
  versions of Mime::Base64, which Bush's Authen::NTLM makes use of.  Therefore, it is 
  necessary to ensure that your Mime::Base64 module supports exporting of the 
  encode_base64 and decode_base64 functions.
  
  =head1 USAGE
  
  The module is used indirectly through LWP, rather than including it directly in your 
  code.  The LWP system will invoke the NTLM authentication when it encounters the 
  authentication scheme while attempting to retrieve a URL from a server.  In order 
  for the NTLM authentication to work, you must have a few things set up in your 
  code prior to attempting to retrieve the URL:
  
  =over 4
  
  =item *
  
  Enable persistent HTTP connections
  
  To do this, pass the "keep_alive=>1" option to the LWP::UserAgent when creating it, like this:
  
      my $ua = LWP::UserAgent->new(keep_alive=>1);
  
  =item *
  
  Set the credentials on the UserAgent object
  
  The credentials must be set like this:
  
     $ua->credentials('www.company.com:80', '', "MyDomain\\MyUserCode", 'MyPassword');
  
  Note that you cannot use the HTTP::Request object's authorization_basic() method to set 
  the credentials.  Note, too, that the 'www.company.com:80' portion only sets credentials 
  on the specified port AND it is case-sensitive (this is due to the way LWP is coded, and 
  has nothing to do with LWP::Authen::Ntlm)
  
  =back
  
  =head1 AVAILABILITY
  
  General queries regarding LWP should be made to the LWP Mailing List.
  
  Questions specific to LWP::Authen::Ntlm can be forwarded to jtillman@bigfoot.com
  
  =head1 COPYRIGHT
  
  Copyright (c) 2002 James Tillman. All rights reserved. This
  program is free software; you can redistribute it and/or modify it
  under the same terms as Perl itself.
  
  =head1 SEE ALSO
  
  L<LWP>, L<LWP::UserAgent>, L<lwpcook>.
LWP_AUTHEN_NTLM

$fatpacked{"LWP/ConnCache.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'LWP_CONNCACHE';
  package LWP::ConnCache;
  
  use strict;
  use vars qw($VERSION $DEBUG);
  
  $VERSION = "6.02";
  
  
  sub new {
      my($class, %cnf) = @_;
  
      my $total_capacity = 1;
      if (exists $cnf{total_capacity}) {
          $total_capacity = delete $cnf{total_capacity};
      }
      if (%cnf && $^W) {
  	require Carp;
  	Carp::carp("Unrecognised options: @{[sort keys %cnf]}")
      }
      my $self = bless { cc_conns => [] }, $class;
      $self->total_capacity($total_capacity);
      $self;
  }
  
  
  sub deposit {
      my($self, $type, $key, $conn) = @_;
      push(@{$self->{cc_conns}}, [$conn, $type, $key, time]);
      $self->enforce_limits($type);
      return;
  }
  
  
  sub withdraw {
      my($self, $type, $key) = @_;
      my $conns = $self->{cc_conns};
      for my $i (0 .. @$conns - 1) {
  	my $c = $conns->[$i];
  	next unless $c->[1] eq $type && $c->[2] eq $key;
  	splice(@$conns, $i, 1);  # remove it
  	return $c->[0];
      }
      return undef;
  }
  
  
  sub total_capacity {
      my $self = shift;
      my $old = $self->{cc_limit_total};
      if (@_) {
  	$self->{cc_limit_total} = shift;
  	$self->enforce_limits;
      }
      $old;
  }
  
  
  sub capacity {
      my $self = shift;
      my $type = shift;
      my $old = $self->{cc_limit}{$type};
      if (@_) {
  	$self->{cc_limit}{$type} = shift;
  	$self->enforce_limits($type);
      }
      $old;
  }
  
  
  sub enforce_limits {
      my($self, $type) = @_;
      my $conns = $self->{cc_conns};
  
      my @types = $type ? ($type) : ($self->get_types);
      for $type (@types) {
  	next unless $self->{cc_limit};
  	my $limit = $self->{cc_limit}{$type};
  	next unless defined $limit;
  	for my $i (reverse 0 .. @$conns - 1) {
  	    next unless $conns->[$i][1] eq $type;
  	    if (--$limit < 0) {
  		$self->dropping(splice(@$conns, $i, 1), "$type capacity exceeded");
  	    }
  	}
      }
  
      if (defined(my $total = $self->{cc_limit_total})) {
  	while (@$conns > $total) {
  	    $self->dropping(shift(@$conns), "Total capacity exceeded");
  	}
      }
  }
  
  
  sub dropping {
      my($self, $c, $reason) = @_;
      print "DROPPING @$c [$reason]\n" if $DEBUG;
  }
  
  
  sub drop {
      my($self, $checker, $reason) = @_;
      if (ref($checker) ne "CODE") {
  	# make it so
  	if (!defined $checker) {
  	    $checker = sub { 1 };  # drop all of them
  	}
  	elsif (_looks_like_number($checker)) {
  	    my $age_limit = $checker;
  	    my $time_limit = time - $age_limit;
  	    $reason ||= "older than $age_limit";
  	    $checker = sub { $_[3] < $time_limit };
  	}
  	else {
  	    my $type = $checker;
  	    $reason ||= "drop $type";
  	    $checker = sub { $_[1] eq $type };  # match on type
  	}
      }
      $reason ||= "drop";
  
      local $SIG{__DIE__};  # don't interfere with eval below
      local $@;
      my @c;
      for (@{$self->{cc_conns}}) {
  	my $drop;
  	eval {
  	    if (&$checker(@$_)) {
  		$self->dropping($_, $reason);
  		$drop++;
  	    }
  	};
  	push(@c, $_) unless $drop;
      }
      @{$self->{cc_conns}} = @c;
  }
  
  
  sub prune {
      my $self = shift;
      $self->drop(sub { !shift->ping }, "ping");
  }
  
  
  sub get_types {
      my $self = shift;
      my %t;
      $t{$_->[1]}++ for @{$self->{cc_conns}};
      return keys %t;
  }
  
  
  sub get_connections {
      my($self, $type) = @_;
      my @c;
      for (@{$self->{cc_conns}}) {
  	push(@c, $_->[0]) if !$type || ($type && $type eq $_->[1]);
      }
      @c;
  }
  
  
  sub _looks_like_number {
      $_[0] =~ /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/;
  }
  
  1;
  
  
  __END__
  
  =head1 NAME
  
  LWP::ConnCache - Connection cache manager
  
  =head1 NOTE
  
  This module is experimental.  Details of its interface is likely to
  change in the future.
  
  =head1 SYNOPSIS
  
   use LWP::ConnCache;
   my $cache = LWP::ConnCache->new;
   $cache->deposit($type, $key, $sock);
   $sock = $cache->withdraw($type, $key);
  
  =head1 DESCRIPTION
  
  The C<LWP::ConnCache> class is the standard connection cache manager
  for LWP::UserAgent.
  
  The following basic methods are provided:
  
  =over
  
  =item $cache = LWP::ConnCache->new( %options )
  
  This method constructs a new C<LWP::ConnCache> object.  The only
  option currently accepted is 'total_capacity'.  If specified it
  initialize the total_capacity option.  It defaults to the value 1.
  
  =item $cache->total_capacity( [$num_connections] )
  
  Get/sets the number of connection that will be cached.  Connections
  will start to be dropped when this limit is reached.  If set to C<0>,
  then all connections are immediately dropped.  If set to C<undef>,
  then there is no limit.
  
  =item $cache->capacity($type, [$num_connections] )
  
  Get/set a limit for the number of connections of the specified type
  that can be cached.  The $type will typically be a short string like
  "http" or "ftp".
  
  =item $cache->drop( [$checker, [$reason]] )
  
  Drop connections by some criteria.  The $checker argument is a
  subroutine that is called for each connection.  If the routine returns
  a TRUE value then the connection is dropped.  The routine is called
  with ($conn, $type, $key, $deposit_time) as arguments.
  
  Shortcuts: If the $checker argument is absent (or C<undef>) all cached
  connections are dropped.  If the $checker is a number then all
  connections untouched that the given number of seconds or more are
  dropped.  If $checker is a string then all connections of the given
  type are dropped.
  
  The $reason argument is passed on to the dropped() method.
  
  =item $cache->prune
  
  Calling this method will drop all connections that are dead.  This is
  tested by calling the ping() method on the connections.  If the ping()
  method exists and returns a FALSE value, then the connection is
  dropped.
  
  =item $cache->get_types
  
  This returns all the 'type' fields used for the currently cached
  connections.
  
  =item $cache->get_connections( [$type] )
  
  This returns all connection objects of the specified type.  If no type
  is specified then all connections are returned.  In scalar context the
  number of cached connections of the specified type is returned.
  
  =back
  
  
  The following methods are called by low-level protocol modules to
  try to save away connections and to get them back.
  
  =over
  
  =item $cache->deposit($type, $key, $conn)
  
  This method adds a new connection to the cache.  As a result other
  already cached connections might be dropped.  Multiple connections with
  the same $type/$key might added.
  
  =item $conn = $cache->withdraw($type, $key)
  
  This method tries to fetch back a connection that was previously
  deposited.  If no cached connection with the specified $type/$key is
  found, then C<undef> is returned.  There is not guarantee that a
  deposited connection can be withdrawn, as the cache manger is free to
  drop connections at any time.
  
  =back
  
  The following methods are called internally.  Subclasses might want to
  override them.
  
  =over
  
  =item $conn->enforce_limits([$type])
  
  This method is called with after a new connection is added (deposited)
  in the cache or capacity limits are adjusted.  The default
  implementation drops connections until the specified capacity limits
  are not exceeded.
  
  =item $conn->dropping($conn_record, $reason)
  
  This method is called when a connection is dropped.  The record
  belonging to the dropped connection is passed as the first argument
  and a string describing the reason for the drop is passed as the
  second argument.  The default implementation makes some noise if the
  $LWP::ConnCache::DEBUG variable is set and nothing more.
  
  =back
  
  =head1 SUBCLASSING
  
  For specialized cache policy it makes sense to subclass
  C<LWP::ConnCache> and perhaps override the deposit(), enforce_limits()
  and dropping() methods.
  
  The object itself is a hash.  Keys prefixed with C<cc_> are reserved
  for the base class.
  
  =head1 SEE ALSO
  
  L<LWP::UserAgent>
  
  =head1 COPYRIGHT
  
  Copyright 2001 Gisle Aas.
  
  This library is free software; you can redistribute it and/or
  modify it under the same terms as Perl itself.
LWP_CONNCACHE

$fatpacked{"LWP/Debug.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'LWP_DEBUG';
  package LWP::Debug;  # legacy
  
  require Exporter;
  @ISA = qw(Exporter);
  @EXPORT_OK = qw(level trace debug conns);
  
  use Carp ();
  
  my @levels = qw(trace debug conns);
  %current_level = ();
  
  
  sub import
  {
      my $pack = shift;
      my $callpkg = caller(0);
      my @symbols = ();
      my @levels = ();
      for (@_) {
  	if (/^[-+]/) {
  	    push(@levels, $_);
  	}
  	else {
  	    push(@symbols, $_);
  	}
      }
      Exporter::export($pack, $callpkg, @symbols);
      level(@levels);
  }
  
  
  sub level
  {
      for (@_) {
  	if ($_ eq '+') {              # all on
  	    # switch on all levels
  	    %current_level = map { $_ => 1 } @levels;
  	}
  	elsif ($_ eq '-') {           # all off
  	    %current_level = ();
  	}
  	elsif (/^([-+])(\w+)$/) {
  	    $current_level{$2} = $1 eq '+';
  	}
  	else {
  	    Carp::croak("Illegal level format $_");
  	}
      }
  }
  
  
  sub trace  { _log(@_) if $current_level{'trace'}; }
  sub debug  { _log(@_) if $current_level{'debug'}; }
  sub conns  { _log(@_) if $current_level{'conns'}; }
  
  
  sub _log
  {
      my $msg = shift;
      $msg .= "\n" unless $msg =~ /\n$/;  # ensure trailing "\n"
  
      my($package,$filename,$line,$sub) = caller(2);
      print STDERR "$sub: $msg";
  }
  
  1;
  
  __END__
  
  =head1 NAME
  
  LWP::Debug - deprecated
  
  =head1 DESCRIPTION
  
  LWP::Debug used to provide tracing facilities, but these are not used
  by LWP any more.  The code in this module is kept around
  (undocumented) so that 3rd party code that happen to use the old
  interfaces continue to run.
  
  One useful feature that LWP::Debug provided (in an imprecise and
  troublesome way) was network traffic monitoring.  The following
  section provide some hints about recommened replacements.
  
  =head2 Network traffic monitoring
  
  The best way to monitor the network traffic that LWP generates is to
  use an external TCP monitoring program.  The Wireshark program
  (L<http://www.wireshark.org/>) is higly recommended for this.
  
  Another approach it to use a debugging HTTP proxy server and make
  LWP direct all its traffic via this one.  Call C<< $ua->proxy >> to
  set it up and then just use LWP as before.
  
  For less precise monitoring needs just setting up a few simple
  handlers might do.  The following example sets up handlers to dump the
  request and response objects that pass through LWP:
  
    use LWP::UserAgent;
    $ua = LWP::UserAgent->new;
    $ua->default_header('Accept-Encoding' => scalar HTTP::Message::decodable());
  
    $ua->add_handler("request_send",  sub { shift->dump; return });
    $ua->add_handler("response_done", sub { shift->dump; return });
  
    $ua->get("http://www.example.com");
  
  =head1 SEE ALSO
  
  L<LWP::UserAgent>
LWP_DEBUG

$fatpacked{"LWP/DebugFile.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'LWP_DEBUGFILE';
  package LWP::DebugFile;
  
  # legacy stub
  
  1;
LWP_DEBUGFILE

$fatpacked{"LWP/MemberMixin.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'LWP_MEMBERMIXIN';
  package LWP::MemberMixin;
  
  sub _elem
  {
      my $self = shift;
      my $elem = shift;
      my $old = $self->{$elem};
      $self->{$elem} = shift if @_;
      return $old;
  }
  
  1;
  
  __END__
  
  =head1 NAME
  
  LWP::MemberMixin - Member access mixin class
  
  =head1 SYNOPSIS
  
   package Foo;
   require LWP::MemberMixin;
   @ISA=qw(LWP::MemberMixin);
  
  =head1 DESCRIPTION
  
  A mixin class to get methods that provide easy access to member
  variables in the %$self.
  Ideally there should be better Perl language support for this.
  
  There is only one method provided:
  
  =over 4
  
  =item _elem($elem [, $val])
  
  Internal method to get/set the value of member variable
  C<$elem>. If C<$val> is present it is used as the new value
  for the member variable.  If it is not present the current
  value is not touched. In both cases the previous value of
  the member variable is returned.
  
  =back
LWP_MEMBERMIXIN

$fatpacked{"LWP/Protocol.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'LWP_PROTOCOL';
  package LWP::Protocol;
  
  require LWP::MemberMixin;
  @ISA = qw(LWP::MemberMixin);
  $VERSION = "6.00";
  
  use strict;
  use Carp ();
  use HTTP::Status ();
  use HTTP::Response;
  
  my %ImplementedBy = (); # scheme => classname
  
  
  
  sub new
  {
      my($class, $scheme, $ua) = @_;
  
      my $self = bless {
  	scheme => $scheme,
  	ua => $ua,
  
  	# historical/redundant
          max_size => $ua->{max_size},
      }, $class;
  
      $self;
  }
  
  
  sub create
  {
      my($scheme, $ua) = @_;
      my $impclass = LWP::Protocol::implementor($scheme) or
  	Carp::croak("Protocol scheme '$scheme' is not supported");
  
      # hand-off to scheme specific implementation sub-class
      my $protocol = $impclass->new($scheme, $ua);
  
      return $protocol;
  }
  
  
  sub implementor
  {
      my($scheme, $impclass) = @_;
  
      if ($impclass) {
  	$ImplementedBy{$scheme} = $impclass;
      }
      my $ic = $ImplementedBy{$scheme};
      return $ic if $ic;
  
      return '' unless $scheme =~ /^([.+\-\w]+)$/;  # check valid URL schemes
      $scheme = $1; # untaint
      $scheme =~ s/[.+\-]/_/g;  # make it a legal module name
  
      # scheme not yet known, look for a 'use'd implementation
      $ic = "LWP::Protocol::$scheme";  # default location
      $ic = "LWP::Protocol::nntp" if $scheme eq 'news'; #XXX ugly hack
      no strict 'refs';
      # check we actually have one for the scheme:
      unless (@{"${ic}::ISA"}) {
  	# try to autoload it
  	eval "require $ic";
  	if ($@) {
  	    if ($@ =~ /Can't locate/) { #' #emacs get confused by '
  		$ic = '';
  	    }
  	    else {
  		die "$@\n";
  	    }
  	}
      }
      $ImplementedBy{$scheme} = $ic if $ic;
      $ic;
  }
  
  
  sub request
  {
      my($self, $request, $proxy, $arg, $size, $timeout) = @_;
      Carp::croak('LWP::Protocol::request() needs to be overridden in subclasses');
  }
  
  
  # legacy
  sub timeout    { shift->_elem('timeout',    @_); }
  sub max_size   { shift->_elem('max_size',   @_); }
  
  
  sub collect
  {
      my ($self, $arg, $response, $collector) = @_;
      my $content;
      my($ua, $max_size) = @{$self}{qw(ua max_size)};
  
      eval {
  	local $\; # protect the print below from surprises
          if (!defined($arg) || !$response->is_success) {
              $response->{default_add_content} = 1;
          }
          elsif (!ref($arg) && length($arg)) {
              open(my $fh, ">", $arg) or die "Can't write to '$arg': $!";
  	    binmode($fh);
              push(@{$response->{handlers}{response_data}}, {
                  callback => sub {
                      print $fh $_[3] or die "Can't write to '$arg': $!";
                      1;
                  },
              });
              push(@{$response->{handlers}{response_done}}, {
                  callback => sub {
  		    close($fh) or die "Can't write to '$arg': $!";
  		    undef($fh);
  		},
  	    });
          }
          elsif (ref($arg) eq 'CODE') {
              push(@{$response->{handlers}{response_data}}, {
                  callback => sub {
  		    &$arg($_[3], $_[0], $self);
  		    1;
                  },
              });
          }
          else {
              die "Unexpected collect argument '$arg'";
          }
  
          $ua->run_handlers("response_header", $response);
  
          if (delete $response->{default_add_content}) {
              push(@{$response->{handlers}{response_data}}, {
  		callback => sub {
  		    $_[0]->add_content($_[3]);
  		    1;
  		},
  	    });
          }
  
  
          my $content_size = 0;
          my $length = $response->content_length;
          my %skip_h;
  
          while ($content = &$collector, length $$content) {
              for my $h ($ua->handlers("response_data", $response)) {
                  next if $skip_h{$h};
                  unless ($h->{callback}->($response, $ua, $h, $$content)) {
                      # XXX remove from $response->{handlers}{response_data} if present
                      $skip_h{$h}++;
                  }
              }
              $content_size += length($$content);
              $ua->progress(($length ? ($content_size / $length) : "tick"), $response);
              if (defined($max_size) && $content_size > $max_size) {
                  $response->push_header("Client-Aborted", "max_size");
                  last;
              }
          }
      };
      my $err = $@;
      delete $response->{handlers}{response_data};
      delete $response->{handlers} unless %{$response->{handlers}};
      if ($err) {
          chomp($err);
          $response->push_header('X-Died' => $err);
          $response->push_header("Client-Aborted", "die");
          return $response;
      }
  
      return $response;
  }
  
  
  sub collect_once
  {
      my($self, $arg, $response) = @_;
      my $content = \ $_[3];
      my $first = 1;
      $self->collect($arg, $response, sub {
  	return $content if $first--;
  	return \ "";
      });
  }
  
  1;
  
  
  __END__
  
  =head1 NAME
  
  LWP::Protocol - Base class for LWP protocols
  
  =head1 SYNOPSIS
  
   package LWP::Protocol::foo;
   require LWP::Protocol;
   @ISA=qw(LWP::Protocol);
  
  =head1 DESCRIPTION
  
  This class is used a the base class for all protocol implementations
  supported by the LWP library.
  
  When creating an instance of this class using
  C<LWP::Protocol::create($url)>, and you get an initialised subclass
  appropriate for that access method. In other words, the
  LWP::Protocol::create() function calls the constructor for one of its
  subclasses.
  
  All derived LWP::Protocol classes need to override the request()
  method which is used to service a request. The overridden method can
  make use of the collect() function to collect together chunks of data
  as it is received.
  
  The following methods and functions are provided:
  
  =over 4
  
  =item $prot = LWP::Protocol->new()
  
  The LWP::Protocol constructor is inherited by subclasses. As this is a
  virtual base class this method should B<not> be called directly.
  
  =item $prot = LWP::Protocol::create($scheme)
  
  Create an object of the class implementing the protocol to handle the
  given scheme. This is a function, not a method. It is more an object
  factory than a constructor. This is the function user agents should
  use to access protocols.
  
  =item $class = LWP::Protocol::implementor($scheme, [$class])
  
  Get and/or set implementor class for a scheme.  Returns '' if the
  specified scheme is not supported.
  
  =item $prot->request(...)
  
   $response = $protocol->request($request, $proxy, undef);
   $response = $protocol->request($request, $proxy, '/tmp/sss');
   $response = $protocol->request($request, $proxy, \&callback, 1024);
  
  Dispatches a request over the protocol, and returns a response
  object. This method needs to be overridden in subclasses.  Refer to
  L<LWP::UserAgent> for description of the arguments.
  
  =item $prot->collect($arg, $response, $collector)
  
  Called to collect the content of a request, and process it
  appropriately into a scalar, file, or by calling a callback.  If $arg
  is undefined, then the content is stored within the $response.  If
  $arg is a simple scalar, then $arg is interpreted as a file name and
  the content is written to this file.  If $arg is a reference to a
  routine, then content is passed to this routine.
  
  The $collector is a routine that will be called and which is
  responsible for returning pieces (as ref to scalar) of the content to
  process.  The $collector signals EOF by returning a reference to an
  empty sting.
  
  The return value from collect() is the $response object reference.
  
  B<Note:> We will only use the callback or file argument if
  $response->is_success().  This avoids sending content data for
  redirects and authentication responses to the callback which would be
  confusing.
  
  =item $prot->collect_once($arg, $response, $content)
  
  Can be called when the whole response content is available as
  $content.  This will invoke collect() with a collector callback that
  returns a reference to $content the first time and an empty string the
  next.
  
  =back
  
  =head1 SEE ALSO
  
  Inspect the F<LWP/Protocol/file.pm> and F<LWP/Protocol/http.pm> files
  for examples of usage.
  
  =head1 COPYRIGHT
  
  Copyright 1995-2001 Gisle Aas.
  
  This library is free software; you can redistribute it and/or
  modify it under the same terms as Perl itself.
LWP_PROTOCOL

$fatpacked{"LWP/Protocol/GHTTP.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'LWP_PROTOCOL_GHTTP';
  package LWP::Protocol::GHTTP;
  
  # You can tell LWP to use this module for 'http' requests by running
  # code like this before you make requests:
  #
  #    require LWP::Protocol::GHTTP;
  #    LWP::Protocol::implementor('http', 'LWP::Protocol::GHTTP');
  #
  
  use strict;
  use vars qw(@ISA);
  
  require LWP::Protocol;
  @ISA=qw(LWP::Protocol);
  
  require HTTP::Response;
  require HTTP::Status;
  
  use HTTP::GHTTP qw(METHOD_GET METHOD_HEAD METHOD_POST);
  
  my %METHOD =
  (
   GET  => METHOD_GET,
   HEAD => METHOD_HEAD,
   POST => METHOD_POST,
  );
  
  sub request
  {
      my($self, $request, $proxy, $arg, $size, $timeout) = @_;
  
      my $method = $request->method;
      unless (exists $METHOD{$method}) {
  	return HTTP::Response->new(&HTTP::Status::RC_BAD_REQUEST,
  				   "Bad method '$method'");
      }
  
      my $r = HTTP::GHTTP->new($request->uri);
  
      # XXX what headers for repeated headers here?
      $request->headers->scan(sub { $r->set_header(@_)});
  
      $r->set_type($METHOD{$method});
  
      # XXX should also deal with subroutine content.
      my $cref = $request->content_ref;
      $r->set_body($$cref) if length($$cref);
  
      # XXX is this right
      $r->set_proxy($proxy->as_string) if $proxy;
  
      $r->process_request;
  
      my $response = HTTP::Response->new($r->get_status);
  
      # XXX How can get the headers out of $r??  This way is too stupid.
      my @headers;
      eval {
  	# Wrapped in eval because this method is not always available
  	@headers = $r->get_headers;
      };
      @headers = qw(Date Connection Server Content-type
                    Accept-Ranges Server
                    Content-Length Last-Modified ETag) if $@;
      for (@headers) {
  	my $v = $r->get_header($_);
  	$response->header($_ => $v) if defined $v;
      }
  
      return $self->collect_once($arg, $response, $r->get_body);
  }
  
  1;
LWP_PROTOCOL_GHTTP

$fatpacked{"LWP/Protocol/cpan.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'LWP_PROTOCOL_CPAN';
  package LWP::Protocol::cpan;
  
  use strict;
  use vars qw(@ISA);
  
  require LWP::Protocol;
  @ISA = qw(LWP::Protocol);
  
  require URI;
  require HTTP::Status;
  require HTTP::Response;
  
  our $CPAN;
  
  unless ($CPAN) {
      # Try to find local CPAN mirror via $CPAN::Config
      eval {
  	require CPAN::Config;
  	if($CPAN::Config) {
  	    my $urls = $CPAN::Config->{urllist};
  	    if (ref($urls) eq "ARRAY") {
  		my $file;
  		for (@$urls) {
  		    if (/^file:/) {
  			$file = $_;
  			last;
  		    }
  		}
  
  		if ($file) {
  		    $CPAN = $file;
  		}
  		else {
  		    $CPAN = $urls->[0];
  		}
  	    }
  	}
      };
  
      $CPAN ||= "http://cpan.org/";  # last resort
  }
  
  # ensure that we don't chop of last part
  $CPAN .= "/" unless $CPAN =~ m,/$,;
  
  
  sub request {
      my($self, $request, $proxy, $arg, $size) = @_;
      # check proxy
      if (defined $proxy)
      {
  	return HTTP::Response->new(&HTTP::Status::RC_BAD_REQUEST,
  				   'You can not proxy with cpan');
      }
  
      # check method
      my $method = $request->method;
      unless ($method eq 'GET' || $method eq 'HEAD') {
  	return HTTP::Response->new(&HTTP::Status::RC_BAD_REQUEST,
  				   'Library does not allow method ' .
  				   "$method for 'cpan:' URLs");
      }
  
      my $path = $request->uri->path;
      $path =~ s,^/,,;
  
      my $response = HTTP::Response->new(&HTTP::Status::RC_FOUND);
      $response->header("Location" => URI->new_abs($path, $CPAN));
      $response;
  }
  
  1;
LWP_PROTOCOL_CPAN

$fatpacked{"LWP/Protocol/data.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'LWP_PROTOCOL_DATA';
  package LWP::Protocol::data;
  
  # Implements access to data:-URLs as specified in RFC 2397
  
  use strict;
  use vars qw(@ISA);
  
  require HTTP::Response;
  require HTTP::Status;
  
  require LWP::Protocol;
  @ISA = qw(LWP::Protocol);
  
  use HTTP::Date qw(time2str);
  require LWP;  # needs version number
  
  sub request
  {
      my($self, $request, $proxy, $arg, $size) = @_;
  
      # check proxy
      if (defined $proxy)
      {
  	return HTTP::Response->new( &HTTP::Status::RC_BAD_REQUEST,
  				  'You can not proxy with data');
      }
  
      # check method
      my $method = $request->method;
      unless ($method eq 'GET' || $method eq 'HEAD') {
  	return HTTP::Response->new( &HTTP::Status::RC_BAD_REQUEST,
  				  'Library does not allow method ' .
  				  "$method for 'data:' URLs");
      }
  
      my $url = $request->uri;
      my $response = HTTP::Response->new( &HTTP::Status::RC_OK, "Document follows");
  
      my $media_type = $url->media_type;
  
      my $data = $url->data;
      $response->header('Content-Type'   => $media_type,
  		      'Content-Length' => length($data),
  		      'Date'           => time2str(time),
  		      'Server'         => "libwww-perl-internal/$LWP::VERSION"
  		     );
  
      $data = "" if $method eq "HEAD";
      return $self->collect_once($arg, $response, $data);
  }
  
  1;
LWP_PROTOCOL_DATA

$fatpacked{"LWP/Protocol/file.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'LWP_PROTOCOL_FILE';
  package LWP::Protocol::file;
  
  require LWP::Protocol;
  @ISA = qw(LWP::Protocol);
  
  use strict;
  
  require LWP::MediaTypes;
  require HTTP::Request;
  require HTTP::Response;
  require HTTP::Status;
  require HTTP::Date;
  
  
  sub request
  {
      my($self, $request, $proxy, $arg, $size) = @_;
  
      $size = 4096 unless defined $size and $size > 0;
  
      # check proxy
      if (defined $proxy)
      {
  	return HTTP::Response->new( &HTTP::Status::RC_BAD_REQUEST,
  				  'You can not proxy through the filesystem');
      }
  
      # check method
      my $method = $request->method;
      unless ($method eq 'GET' || $method eq 'HEAD') {
  	return HTTP::Response->new( &HTTP::Status::RC_BAD_REQUEST,
  				  'Library does not allow method ' .
  				  "$method for 'file:' URLs");
      }
  
      # check url
      my $url = $request->uri;
  
      my $scheme = $url->scheme;
      if ($scheme ne 'file') {
  	return HTTP::Response->new( &HTTP::Status::RC_INTERNAL_SERVER_ERROR,
  			   "LWP::Protocol::file::request called for '$scheme'");
      }
  
      # URL OK, look at file
      my $path  = $url->file;
  
      # test file exists and is readable
      unless (-e $path) {
  	return HTTP::Response->new( &HTTP::Status::RC_NOT_FOUND,
  				  "File `$path' does not exist");
      }
      unless (-r _) {
  	return HTTP::Response->new( &HTTP::Status::RC_FORBIDDEN,
  				  'User does not have read permission');
      }
  
      # looks like file exists
      my($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$filesize,
         $atime,$mtime,$ctime,$blksize,$blocks)
  	    = stat(_);
  
      # XXX should check Accept headers?
  
      # check if-modified-since
      my $ims = $request->header('If-Modified-Since');
      if (defined $ims) {
  	my $time = HTTP::Date::str2time($ims);
  	if (defined $time and $time >= $mtime) {
  	    return HTTP::Response->new( &HTTP::Status::RC_NOT_MODIFIED,
  				      "$method $path");
  	}
      }
  
      # Ok, should be an OK response by now...
      my $response = HTTP::Response->new( &HTTP::Status::RC_OK );
  
      # fill in response headers
      $response->header('Last-Modified', HTTP::Date::time2str($mtime));
  
      if (-d _) {         # If the path is a directory, process it
  	# generate the HTML for directory
  	opendir(D, $path) or
  	   return HTTP::Response->new( &HTTP::Status::RC_INTERNAL_SERVER_ERROR,
  				     "Cannot read directory '$path': $!");
  	my(@files) = sort readdir(D);
  	closedir(D);
  
  	# Make directory listing
  	require URI::Escape;
  	require HTML::Entities;
          my $pathe = $path . ( $^O eq 'MacOS' ? ':' : '/');
  	for (@files) {
  	    my $furl = URI::Escape::uri_escape($_);
              if ( -d "$pathe$_" ) {
                  $furl .= '/';
                  $_ .= '/';
              }
  	    my $desc = HTML::Entities::encode($_);
  	    $_ = qq{<LI><A HREF="$furl">$desc</A>};
  	}
  	# Ensure that the base URL is "/" terminated
  	my $base = $url->clone;
  	unless ($base->path =~ m|/$|) {
  	    $base->path($base->path . "/");
  	}
  	my $html = join("\n",
  			"<HTML>\n<HEAD>",
  			"<TITLE>Directory $path</TITLE>",
  			"<BASE HREF=\"$base\">",
  			"</HEAD>\n<BODY>",
  			"<H1>Directory listing of $path</H1>",
  			"<UL>", @files, "</UL>",
  			"</BODY>\n</HTML>\n");
  
  	$response->header('Content-Type',   'text/html');
  	$response->header('Content-Length', length $html);
  	$html = "" if $method eq "HEAD";
  
  	return $self->collect_once($arg, $response, $html);
  
      }
  
      # path is a regular file
      $response->header('Content-Length', $filesize);
      LWP::MediaTypes::guess_media_type($path, $response);
  
      # read the file
      if ($method ne "HEAD") {
  	open(F, $path) or return new
  	    HTTP::Response(&HTTP::Status::RC_INTERNAL_SERVER_ERROR,
  			   "Cannot read file '$path': $!");
  	binmode(F);
  	$response =  $self->collect($arg, $response, sub {
  	    my $content = "";
  	    my $bytes = sysread(F, $content, $size);
  	    return \$content if $bytes > 0;
  	    return \ "";
  	});
  	close(F);
      }
  
      $response;
  }
  
  1;
LWP_PROTOCOL_FILE

$fatpacked{"LWP/Protocol/ftp.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'LWP_PROTOCOL_FTP';
  package LWP::Protocol::ftp;
  
  # Implementation of the ftp protocol (RFC 959). We let the Net::FTP
  # package do all the dirty work.
  
  use Carp ();
  
  use HTTP::Status ();
  use HTTP::Negotiate ();
  use HTTP::Response ();
  use LWP::MediaTypes ();
  use File::Listing ();
  
  require LWP::Protocol;
  @ISA = qw(LWP::Protocol);
  
  use strict;
  eval {
      package LWP::Protocol::MyFTP;
  
      require Net::FTP;
      Net::FTP->require_version(2.00);
  
      use vars qw(@ISA);
      @ISA=qw(Net::FTP);
  
      sub new {
  	my $class = shift;
  
  	my $self = $class->SUPER::new(@_) || return undef;
  
  	my $mess = $self->message;  # welcome message
  	$mess =~ s|\n.*||s; # only first line left
  	$mess =~ s|\s*ready\.?$||;
  	# Make the version number more HTTP like
  	$mess =~ s|\s*\(Version\s*|/| and $mess =~ s|\)$||;
  	${*$self}{myftp_server} = $mess;
  	#$response->header("Server", $mess);
  
  	$self;
      }
  
      sub http_server {
  	my $self = shift;
  	${*$self}{myftp_server};
      }
  
      sub home {
  	my $self = shift;
  	my $old = ${*$self}{myftp_home};
  	if (@_) {
  	    ${*$self}{myftp_home} = shift;
  	}
  	$old;
      }
  
      sub go_home {
  	my $self = shift;
  	$self->cwd(${*$self}{myftp_home});
      }
  
      sub request_count {
  	my $self = shift;
  	++${*$self}{myftp_reqcount};
      }
  
      sub ping {
  	my $self = shift;
  	return $self->go_home;
      }
  
  };
  my $init_failed = $@;
  
  
  sub _connect {
      my($self, $host, $port, $user, $account, $password, $timeout) = @_;
  
      my $key;
      my $conn_cache = $self->{ua}{conn_cache};
      if ($conn_cache) {
  	$key = "$host:$port:$user";
  	$key .= ":$account" if defined($account);
  	if (my $ftp = $conn_cache->withdraw("ftp", $key)) {
  	    if ($ftp->ping) {
  		# save it again
  		$conn_cache->deposit("ftp", $key, $ftp);
  		return $ftp;
  	    }
  	}
      }
  
      # try to make a connection
      my $ftp = LWP::Protocol::MyFTP->new($host,
  					Port => $port,
  					Timeout => $timeout,
  					LocalAddr => $self->{ua}{local_address},
  				       );
      # XXX Should be some what to pass on 'Passive' (header??)
      unless ($ftp) {
  	$@ =~ s/^Net::FTP: //;
  	return HTTP::Response->new(&HTTP::Status::RC_INTERNAL_SERVER_ERROR, $@);
      }
  
      unless ($ftp->login($user, $password, $account)) {
  	# Unauthorized.  Let's fake a RC_UNAUTHORIZED response
  	my $mess = scalar($ftp->message);
  	$mess =~ s/\n$//;
  	my $res =  HTTP::Response->new(&HTTP::Status::RC_UNAUTHORIZED, $mess);
  	$res->header("Server", $ftp->http_server);
  	$res->header("WWW-Authenticate", qq(Basic Realm="FTP login"));
  	return $res;
      }
  
      my $home = $ftp->pwd;
      $ftp->home($home);
  
      $conn_cache->deposit("ftp", $key, $ftp) if $conn_cache;
  
      return $ftp;
  }
  
  
  sub request
  {
      my($self, $request, $proxy, $arg, $size, $timeout) = @_;
  
      $size = 4096 unless $size;
  
      # check proxy
      if (defined $proxy)
      {
  	return HTTP::Response->new(&HTTP::Status::RC_BAD_REQUEST,
  				   'You can not proxy through the ftp');
      }
  
      my $url = $request->uri;
      if ($url->scheme ne 'ftp') {
  	my $scheme = $url->scheme;
  	return HTTP::Response->new(&HTTP::Status::RC_INTERNAL_SERVER_ERROR,
  		       "LWP::Protocol::ftp::request called for '$scheme'");
      }
  
      # check method
      my $method = $request->method;
  
      unless ($method eq 'GET' || $method eq 'HEAD' || $method eq 'PUT') {
  	return HTTP::Response->new(&HTTP::Status::RC_BAD_REQUEST,
  				   'Library does not allow method ' .
  				   "$method for 'ftp:' URLs");
      }
  
      if ($init_failed) {
  	return HTTP::Response->new(&HTTP::Status::RC_INTERNAL_SERVER_ERROR,
  				   $init_failed);
      }
  
      my $host     = $url->host;
      my $port     = $url->port;
      my $user     = $url->user;
      my $password = $url->password;
  
      # If a basic autorization header is present than we prefer these over
      # the username/password specified in the URL.
      {
  	my($u,$p) = $request->authorization_basic;
  	if (defined $u) {
  	    $user = $u;
  	    $password = $p;
  	}
      }
  
      # We allow the account to be specified in the "Account" header
      my $account = $request->header('Account');
  
      my $ftp = $self->_connect($host, $port, $user, $account, $password, $timeout);
      return $ftp if ref($ftp) eq "HTTP::Response"; # ugh!
  
      # Create an initial response object
      my $response = HTTP::Response->new(&HTTP::Status::RC_OK, "OK");
      $response->header(Server => $ftp->http_server);
      $response->header('Client-Request-Num' => $ftp->request_count);
      $response->request($request);
  
      # Get & fix the path
      my @path =  grep { length } $url->path_segments;
      my $remote_file = pop(@path);
      $remote_file = '' unless defined $remote_file;
  
      my $type;
      if (ref $remote_file) {
  	my @params;
  	($remote_file, @params) = @$remote_file;
  	for (@params) {
  	    $type = $_ if s/^type=//;
  	}
      }
  
      if ($type && $type eq 'a') {
  	$ftp->ascii;
      }
      else {
  	$ftp->binary;
      }
  
      for (@path) {
  	unless ($ftp->cwd($_)) {
  	    return HTTP::Response->new(&HTTP::Status::RC_NOT_FOUND,
  				       "Can't chdir to $_");
  	}
      }
  
      if ($method eq 'GET' || $method eq 'HEAD') {
  	if (my $mod_time = $ftp->mdtm($remote_file)) {
  	    $response->last_modified($mod_time);
  	    if (my $ims = $request->if_modified_since) {
  		if ($mod_time <= $ims) {
  		    $response->code(&HTTP::Status::RC_NOT_MODIFIED);
  		    $response->message("Not modified");
  		    return $response;
  		}
  	    }
  	}
  
  	# We'll use this later to abort the transfer if necessary. 
  	# if $max_size is defined, we need to abort early. Otherwise, it's
        # a normal transfer
  	my $max_size = undef;
  
  	# Set resume location, if the client requested it
  	if ($request->header('Range') && $ftp->supported('REST'))
  	{
  		my $range_info = $request->header('Range');
  
  		# Change bytes=2772992-6781209 to just 2772992
  		my ($start_byte,$end_byte) = $range_info =~ /.*=\s*(\d+)-(\d+)?/;
  		if ( defined $start_byte && !defined $end_byte ) {
  
  		  # open range -- only the start is specified
  
  		  $ftp->restart( $start_byte );
  		  # don't define $max_size, we don't want to abort early
  		}
  		elsif ( defined $start_byte && defined $end_byte &&
  			$start_byte >= 0 && $end_byte >= $start_byte ) {
  
  		  $ftp->restart( $start_byte );
  		  $max_size = $end_byte - $start_byte;
  		}
  		else {
  
  		  return HTTP::Response->new(&HTTP::Status::RC_BAD_REQUEST,
  		     'Incorrect syntax for Range request');
  		}
  	}
  	elsif ($request->header('Range') && !$ftp->supported('REST'))
  	{
  		return HTTP::Response->new(&HTTP::Status::RC_NOT_IMPLEMENTED,
  	         "Server does not support resume.");
  	}
  
  	my $data;  # the data handle
  	if (length($remote_file) and $data = $ftp->retr($remote_file)) {
  	    my($type, @enc) = LWP::MediaTypes::guess_media_type($remote_file);
  	    $response->header('Content-Type',   $type) if $type;
  	    for (@enc) {
  		$response->push_header('Content-Encoding', $_);
  	    }
  	    my $mess = $ftp->message;
  	    if ($mess =~ /\((\d+)\s+bytes\)/) {
  		$response->header('Content-Length', "$1");
  	    }
  
  	    if ($method ne 'HEAD') {
  		# Read data from server
  		$response = $self->collect($arg, $response, sub {
  		    my $content = '';
  		    my $result = $data->read($content, $size);
  
                      # Stop early if we need to.
                      if (defined $max_size)
                      {
                        # We need an interface to Net::FTP::dataconn for getting
                        # the number of bytes already read
                        my $bytes_received = $data->bytes_read();
  
                        # We were already over the limit. (Should only happen
                        # once at the end.)
                        if ($bytes_received - length($content) > $max_size)
                        {
                          $content = '';
                        }
                        # We just went over the limit
                        elsif ($bytes_received  > $max_size)
                        {
                          # Trim content
                          $content = substr($content, 0,
                            $max_size - ($bytes_received - length($content)) );
                        }
                        # We're under the limit
                        else
                        {
                        }
                      }
  
  		    return \$content;
  		} );
  	    }
  	    # abort is needed for HEAD, it's == close if the transfer has
  	    # already completed.
  	    unless ($data->abort) {
  		# Something did not work too well.  Note that we treat
  		# responses to abort() with code 0 in case of HEAD as ok
  		# (at least wu-ftpd 2.6.1(1) does that).
  		if ($method ne 'HEAD' || $ftp->code != 0) {
  		    $response->code(&HTTP::Status::RC_INTERNAL_SERVER_ERROR);
  		    $response->message("FTP close response: " . $ftp->code .
  				       " " . $ftp->message);
  		}
  	    }
  	}
  	elsif (!length($remote_file) || ( $ftp->code >= 400 && $ftp->code < 600 )) {
  	    # not a plain file, try to list instead
  	    if (length($remote_file) && !$ftp->cwd($remote_file)) {
  		return HTTP::Response->new(&HTTP::Status::RC_NOT_FOUND,
  					   "File '$remote_file' not found");
  	    }
  
  	    # It should now be safe to try to list the directory
  	    my @lsl = $ftp->dir;
  
  	    # Try to figure out if the user want us to convert the
  	    # directory listing to HTML.
  	    my @variants =
  	      (
  	       ['html',  0.60, 'text/html'            ],
  	       ['dir',   1.00, 'text/ftp-dir-listing' ]
  	      );
  	    #$HTTP::Negotiate::DEBUG=1;
  	    my $prefer = HTTP::Negotiate::choose(\@variants, $request);
  
  	    my $content = '';
  
  	    if (!defined($prefer)) {
  		return HTTP::Response->new(&HTTP::Status::RC_NOT_ACCEPTABLE,
  			       "Neither HTML nor directory listing wanted");
  	    }
  	    elsif ($prefer eq 'html') {
  		$response->header('Content-Type' => 'text/html');
  		$content = "<HEAD><TITLE>File Listing</TITLE>\n";
  		my $base = $request->uri->clone;
  		my $path = $base->path;
  		$base->path("$path/") unless $path =~ m|/$|;
  		$content .= qq(<BASE HREF="$base">\n</HEAD>\n);
  		$content .= "<BODY>\n<UL>\n";
  		for (File::Listing::parse_dir(\@lsl, 'GMT')) {
  		    my($name, $type, $size, $mtime, $mode) = @$_;
  		    $content .= qq(  <LI> <a href="$name">$name</a>);
  		    $content .= " $size bytes" if $type eq 'f';
  		    $content .= "\n";
  		}
  		$content .= "</UL></body>\n";
  	    }
  	    else {
  		$response->header('Content-Type', 'text/ftp-dir-listing');
  		$content = join("\n", @lsl, '');
  	    }
  
  	    $response->header('Content-Length', length($content));
  
  	    if ($method ne 'HEAD') {
  		$response = $self->collect_once($arg, $response, $content);
  	    }
  	}
  	else {
  	    my $res = HTTP::Response->new(&HTTP::Status::RC_BAD_REQUEST,
  			  "FTP return code " . $ftp->code);
  	    $res->content_type("text/plain");
  	    $res->content($ftp->message);
  	    return $res;
  	}
      }
      elsif ($method eq 'PUT') {
  	# method must be PUT
  	unless (length($remote_file)) {
  	    return HTTP::Response->new(&HTTP::Status::RC_BAD_REQUEST,
  				       "Must have a file name to PUT to");
  	}
  	my $data;
  	if ($data = $ftp->stor($remote_file)) {
  	    my $content = $request->content;
  	    my $bytes = 0;
  	    if (defined $content) {
  		if (ref($content) eq 'SCALAR') {
  		    $bytes = $data->write($$content, length($$content));
  		}
  		elsif (ref($content) eq 'CODE') {
  		    my($buf, $n);
  		    while (length($buf = &$content)) {
  			$n = $data->write($buf, length($buf));
  			last unless $n;
  			$bytes += $n;
  		    }
  		}
  		elsif (!ref($content)) {
  		    if (defined $content && length($content)) {
  			$bytes = $data->write($content, length($content));
  		    }
  		}
  		else {
  		    die "Bad content";
  		}
  	    }
  	    $data->close;
  
  	    $response->code(&HTTP::Status::RC_CREATED);
  	    $response->header('Content-Type', 'text/plain');
  	    $response->content("$bytes bytes stored as $remote_file on $host\n")
  
  	}
  	else {
  	    my $res = HTTP::Response->new(&HTTP::Status::RC_BAD_REQUEST,
  					  "FTP return code " . $ftp->code);
  	    $res->content_type("text/plain");
  	    $res->content($ftp->message);
  	    return $res;
  	}
      }
      else {
  	return HTTP::Response->new(&HTTP::Status::RC_BAD_REQUEST,
  				   "Illegal method $method");
      }
  
      $response;
  }
  
  1;
  
  __END__
  
  # This is what RFC 1738 has to say about FTP access:
  # --------------------------------------------------
  #
  # 3.2. FTP
  #
  #    The FTP URL scheme is used to designate files and directories on
  #    Internet hosts accessible using the FTP protocol (RFC959).
  #
  #    A FTP URL follow the syntax described in Section 3.1.  If :<port> is
  #    omitted, the port defaults to 21.
  #
  # 3.2.1. FTP Name and Password
  #
  #    A user name and password may be supplied; they are used in the ftp
  #    "USER" and "PASS" commands after first making the connection to the
  #    FTP server.  If no user name or password is supplied and one is
  #    requested by the FTP server, the conventions for "anonymous" FTP are
  #    to be used, as follows:
  #
  #         The user name "anonymous" is supplied.
  #
  #         The password is supplied as the Internet e-mail address
  #         of the end user accessing the resource.
  #
  #    If the URL supplies a user name but no password, and the remote
  #    server requests a password, the program interpreting the FTP URL
  #    should request one from the user.
  #
  # 3.2.2. FTP url-path
  #
  #    The url-path of a FTP URL has the following syntax:
  #
  #         <cwd1>/<cwd2>/.../<cwdN>/<name>;type=<typecode>
  #
  #    Where <cwd1> through <cwdN> and <name> are (possibly encoded) strings
  #    and <typecode> is one of the characters "a", "i", or "d".  The part
  #    ";type=<typecode>" may be omitted. The <cwdx> and <name> parts may be
  #    empty. The whole url-path may be omitted, including the "/"
  #    delimiting it from the prefix containing user, password, host, and
  #    port.
  #
  #    The url-path is interpreted as a series of FTP commands as follows:
  #
  #       Each of the <cwd> elements is to be supplied, sequentially, as the
  #       argument to a CWD (change working directory) command.
  #
  #       If the typecode is "d", perform a NLST (name list) command with
  #       <name> as the argument, and interpret the results as a file
  #       directory listing.
  #
  #       Otherwise, perform a TYPE command with <typecode> as the argument,
  #       and then access the file whose name is <name> (for example, using
  #       the RETR command.)
  #
  #    Within a name or CWD component, the characters "/" and ";" are
  #    reserved and must be encoded. The components are decoded prior to
  #    their use in the FTP protocol.  In particular, if the appropriate FTP
  #    sequence to access a particular file requires supplying a string
  #    containing a "/" as an argument to a CWD or RETR command, it is
  #    necessary to encode each "/".
  #
  #    For example, the URL <URL:ftp://myname@host.dom/%2Fetc/motd> is
  #    interpreted by FTP-ing to "host.dom", logging in as "myname"
  #    (prompting for a password if it is asked for), and then executing
  #    "CWD /etc" and then "RETR motd". This has a different meaning from
  #    <URL:ftp://myname@host.dom/etc/motd> which would "CWD etc" and then
  #    "RETR motd"; the initial "CWD" might be executed relative to the
  #    default directory for "myname". On the other hand,
  #    <URL:ftp://myname@host.dom//etc/motd>, would "CWD " with a null
  #    argument, then "CWD etc", and then "RETR motd".
  #
  #    FTP URLs may also be used for other operations; for example, it is
  #    possible to update a file on a remote file server, or infer
  #    information about it from the directory listings. The mechanism for
  #    doing so is not spelled out here.
  #
  # 3.2.3. FTP Typecode is Optional
  #
  #    The entire ;type=<typecode> part of a FTP URL is optional. If it is
  #    omitted, the client program interpreting the URL must guess the
  #    appropriate mode to use. In general, the data content type of a file
  #    can only be guessed from the name, e.g., from the suffix of the name;
  #    the appropriate type code to be used for transfer of the file can
  #    then be deduced from the data content of the file.
  #
  # 3.2.4 Hierarchy
  #
  #    For some file systems, the "/" used to denote the hierarchical
  #    structure of the URL corresponds to the delimiter used to construct a
  #    file name hierarchy, and thus, the filename will look similar to the
  #    URL path. This does NOT mean that the URL is a Unix filename.
  #
  # 3.2.5. Optimization
  #
  #    Clients accessing resources via FTP may employ additional heuristics
  #    to optimize the interaction. For some FTP servers, for example, it
  #    may be reasonable to keep the control connection open while accessing
  #    multiple URLs from the same server. However, there is no common
  #    hierarchical model to the FTP protocol, so if a directory change
  #    command has been given, it is impossible in general to deduce what
  #    sequence should be given to navigate to another directory for a
  #    second retrieval, if the paths are different.  The only reliable
  #    algorithm is to disconnect and reestablish the control connection.
LWP_PROTOCOL_FTP

$fatpacked{"LWP/Protocol/gopher.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'LWP_PROTOCOL_GOPHER';
  package LWP::Protocol::gopher;
  
  # Implementation of the gopher protocol (RFC 1436)
  #
  # This code is based on 'wwwgopher.pl,v 0.10 1994/10/17 18:12:34 shelden'
  # which in turn is a vastly modified version of Oscar's http'get()
  # dated 28/3/94 in <ftp://cui.unige.ch/PUBLIC/oscar/scripts/http.pl>
  # including contributions from Marc van Heyningen and Martijn Koster.
  
  use strict;
  use vars qw(@ISA);
  
  require HTTP::Response;
  require HTTP::Status;
  require IO::Socket;
  require IO::Select;
  
  require LWP::Protocol;
  @ISA = qw(LWP::Protocol);
  
  
  my %gopher2mimetype = (
      '0' => 'text/plain',                # 0 file
      '1' => 'text/html',                 # 1 menu
  					# 2 CSO phone-book server
  					# 3 Error
      '4' => 'application/mac-binhex40',  # 4 BinHexed Macintosh file
      '5' => 'application/zip',           # 5 DOS binary archive of some sort
      '6' => 'application/octet-stream',  # 6 UNIX uuencoded file.
      '7' => 'text/html',                 # 7 Index-Search server
  					# 8 telnet session
      '9' => 'application/octet-stream',  # 9 binary file
      'h' => 'text/html',                 # html
      'g' => 'image/gif',                 # gif
      'I' => 'image/*',                   # some kind of image
  );
  
  my %gopher2encoding = (
      '6' => 'x_uuencode',                # 6 UNIX uuencoded file.
  );
  
  sub request
  {
      my($self, $request, $proxy, $arg, $size, $timeout) = @_;
  
      $size = 4096 unless $size;
  
      # check proxy
      if (defined $proxy) {
  	return HTTP::Response->new(&HTTP::Status::RC_BAD_REQUEST,
  				   'You can not proxy through the gopher');
      }
  
      my $url = $request->uri;
      die "bad scheme" if $url->scheme ne 'gopher';
  
  
      my $method = $request->method;
      unless ($method eq 'GET' || $method eq 'HEAD') {
  	return HTTP::Response->new(&HTTP::Status::RC_BAD_REQUEST,
  				   'Library does not allow method ' .
  				   "$method for 'gopher:' URLs");
      }
  
      my $gophertype = $url->gopher_type;
      unless (exists $gopher2mimetype{$gophertype}) {
  	return HTTP::Response->new(&HTTP::Status::RC_NOT_IMPLEMENTED,
  				   'Library does not support gophertype ' .
  				   $gophertype);
      }
  
      my $response = HTTP::Response->new(&HTTP::Status::RC_OK, "OK");
      $response->header('Content-type' => $gopher2mimetype{$gophertype}
  					|| 'text/plain');
      $response->header('Content-Encoding' => $gopher2encoding{$gophertype})
  	if exists $gopher2encoding{$gophertype};
  
      if ($method eq 'HEAD') {
  	# XXX: don't even try it so we set this header
  	$response->header('Client-Warning' => 'Client answer only');
  	return $response;
      }
      
      if ($gophertype eq '7' && ! $url->search) {
        # the url is the prompt for a gopher search; supply boiler-plate
        return $self->collect_once($arg, $response, <<"EOT");
  <HEAD>
  <TITLE>Gopher Index</TITLE>
  <ISINDEX>
  </HEAD>
  <BODY>
  <H1>$url<BR>Gopher Search</H1>
  This is a searchable Gopher index.
  Use the search function of your browser to enter search terms.
  </BODY>
  EOT
      }
  
      my $host = $url->host;
      my $port = $url->port;
  
      my $requestLine = "";
  
      my $selector = $url->selector;
      if (defined $selector) {
  	$requestLine .= $selector;
  	my $search = $url->search;
  	if (defined $search) {
  	    $requestLine .= "\t$search";
  	    my $string = $url->string;
  	    if (defined $string) {
  		$requestLine .= "\t$string";
  	    }
  	}
      }
      $requestLine .= "\015\012";
  
      # potential request headers are just ignored
  
      # Ok, lets make the request
      my $socket = IO::Socket::INET->new(PeerAddr => $host,
  				       PeerPort => $port,
  				       LocalAddr => $self->{ua}{local_address},
  				       Proto    => 'tcp',
  				       Timeout  => $timeout);
      die "Can't connect to $host:$port" unless $socket;
      my $sel = IO::Select->new($socket);
  
      {
  	die "write timeout" if $timeout && !$sel->can_write($timeout);
  	my $n = syswrite($socket, $requestLine, length($requestLine));
  	die $! unless defined($n);
  	die "short write" if $n != length($requestLine);
      }
  
      my $user_arg = $arg;
  
      # must handle menus in a special way since they are to be
      # converted to HTML.  Undefing $arg ensures that the user does
      # not see the data before we get a change to convert it.
      $arg = undef if $gophertype eq '1' || $gophertype eq '7';
  
      # collect response
      my $buf = '';
      $response = $self->collect($arg, $response, sub {
  	die "read timeout" if $timeout && !$sel->can_read($timeout);
          my $n = sysread($socket, $buf, $size);
  	die $! unless defined($n);
  	return \$buf;
        } );
  
      # Convert menu to HTML and return data to user.
      if ($gophertype eq '1' || $gophertype eq '7') {
  	my $content = menu2html($response->content);
  	if (defined $user_arg) {
  	    $response = $self->collect_once($user_arg, $response, $content);
  	}
  	else {
  	    $response->content($content);
  	}
      }
  
      $response;
  }
  
  
  sub gopher2url
  {
      my($gophertype, $path, $host, $port) = @_;
  
      my $url;
  
      if ($gophertype eq '8' || $gophertype eq 'T') {
  	# telnet session
  	$url = $HTTP::URI_CLASS->new($gophertype eq '8' ? 'telnet:':'tn3270:');
  	$url->user($path) if defined $path;
      }
      else {
  	$path = URI::Escape::uri_escape($path);
  	$url = $HTTP::URI_CLASS->new("gopher:/$gophertype$path");
      }
      $url->host($host);
      $url->port($port);
      $url;
  }
  
  sub menu2html {
      my($menu) = @_;
  
      $menu =~ s/\015//g;  # remove carriage return
      my $tmp = <<"EOT";
  <HTML>
  <HEAD>
     <TITLE>Gopher menu</TITLE>
  </HEAD>
  <BODY>
  <H1>Gopher menu</H1>
  EOT
      for (split("\n", $menu)) {
  	last if /^\./;
  	my($pretty, $path, $host, $port) = split("\t");
  
  	$pretty =~ s/^(.)//;
  	my $type = $1;
  
  	my $url = gopher2url($type, $path, $host, $port)->as_string;
  	$tmp .= qq{<A HREF="$url">$pretty</A><BR>\n};
      }
      $tmp .= "</BODY>\n</HTML>\n";
      $tmp;
  }
  
  1;
LWP_PROTOCOL_GOPHER

$fatpacked{"LWP/Protocol/http.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'LWP_PROTOCOL_HTTP';
  package LWP::Protocol::http;
  
  use strict;
  
  require HTTP::Response;
  require HTTP::Status;
  require Net::HTTP;
  
  use vars qw(@ISA @EXTRA_SOCK_OPTS);
  
  require LWP::Protocol;
  @ISA = qw(LWP::Protocol);
  
  my $CRLF = "\015\012";
  
  sub _new_socket
  {
      my($self, $host, $port, $timeout) = @_;
      my $conn_cache = $self->{ua}{conn_cache};
      if ($conn_cache) {
  	if (my $sock = $conn_cache->withdraw($self->socket_type, "$host:$port")) {
  	    return $sock if $sock && !$sock->can_read(0);
  	    # if the socket is readable, then either the peer has closed the
  	    # connection or there are some garbage bytes on it.  In either
  	    # case we abandon it.
  	    $sock->close;
  	}
      }
  
      local($^W) = 0;  # IO::Socket::INET can be noisy
      my $sock = $self->socket_class->new(PeerAddr => $host,
  					PeerPort => $port,
  					LocalAddr => $self->{ua}{local_address},
  					Proto    => 'tcp',
  					Timeout  => $timeout,
  					KeepAlive => !!$conn_cache,
  					SendTE    => 1,
  					$self->_extra_sock_opts($host, $port),
  				       );
  
      unless ($sock) {
  	# IO::Socket::INET leaves additional error messages in $@
  	my $status = "Can't connect to $host:$port";
  	if ($@ =~ /\bconnect: (.*)/ ||
  	    $@ =~ /\b(Bad hostname)\b/ ||
  	    $@ =~ /\b(certificate verify failed)\b/ ||
  	    $@ =~ /\b(Crypt-SSLeay can't verify hostnames)\b/
  	) {
  	    $status .= " ($1)";
  	}
  	die "$status\n\n$@";
      }
  
      # perl 5.005's IO::Socket does not have the blocking method.
      eval { $sock->blocking(0); };
  
      $sock;
  }
  
  sub socket_type
  {
      return "http";
  }
  
  sub socket_class
  {
      my $self = shift;
      (ref($self) || $self) . "::Socket";
  }
  
  sub _extra_sock_opts  # to be overridden by subclass
  {
      return @EXTRA_SOCK_OPTS;
  }
  
  sub _check_sock
  {
      #my($self, $req, $sock) = @_;
  }
  
  sub _get_sock_info
  {
      my($self, $res, $sock) = @_;
      if (defined(my $peerhost = $sock->peerhost)) {
          $res->header("Client-Peer" => "$peerhost:" . $sock->peerport);
      }
  }
  
  sub _fixup_header
  {
      my($self, $h, $url, $proxy) = @_;
  
      # Extract 'Host' header
      my $hhost = $url->authority;
      if ($hhost =~ s/^([^\@]*)\@//) {  # get rid of potential "user:pass@"
  	# add authorization header if we need them.  HTTP URLs do
  	# not really support specification of user and password, but
  	# we allow it.
  	if (defined($1) && not $h->header('Authorization')) {
  	    require URI::Escape;
  	    $h->authorization_basic(map URI::Escape::uri_unescape($_),
  				    split(":", $1, 2));
  	}
      }
      $h->init_header('Host' => $hhost);
  
      if ($proxy) {
  	# Check the proxy URI's userinfo() for proxy credentials
  	# export http_proxy="http://proxyuser:proxypass@proxyhost:port"
  	my $p_auth = $proxy->userinfo();
  	if(defined $p_auth) {
  	    require URI::Escape;
  	    $h->proxy_authorization_basic(map URI::Escape::uri_unescape($_),
  					  split(":", $p_auth, 2))
  	}
      }
  }
  
  sub hlist_remove {
      my($hlist, $k) = @_;
      $k = lc $k;
      for (my $i = @$hlist - 2; $i >= 0; $i -= 2) {
  	next unless lc($hlist->[$i]) eq $k;
  	splice(@$hlist, $i, 2);
      }
  }
  
  sub request
  {
      my($self, $request, $proxy, $arg, $size, $timeout) = @_;
  
      $size ||= 4096;
  
      # check method
      my $method = $request->method;
      unless ($method =~ /^[A-Za-z0-9_!\#\$%&\'*+\-.^\`|~]+$/) {  # HTTP token
  	return HTTP::Response->new( &HTTP::Status::RC_BAD_REQUEST,
  				  'Library does not allow method ' .
  				  "$method for 'http:' URLs");
      }
  
      my $url = $request->uri;
      my($host, $port, $fullpath);
  
      # Check if we're proxy'ing
      if (defined $proxy) {
  	# $proxy is an URL to an HTTP server which will proxy this request
  	$host = $proxy->host;
  	$port = $proxy->port;
  	$fullpath = $method eq "CONNECT" ?
                         ($url->host . ":" . $url->port) :
                         $url->as_string;
      }
      else {
  	$host = $url->host;
  	$port = $url->port;
  	$fullpath = $url->path_query;
  	$fullpath = "/$fullpath" unless $fullpath =~ m,^/,;
      }
  
      # connect to remote site
      my $socket = $self->_new_socket($host, $port, $timeout);
  
      my $http_version = "";
      if (my $proto = $request->protocol) {
  	if ($proto =~ /^(?:HTTP\/)?(1.\d+)$/) {
  	    $http_version = $1;
  	    $socket->http_version($http_version);
  	    $socket->send_te(0) if $http_version eq "1.0";
  	}
      }
  
      $self->_check_sock($request, $socket);
  
      my @h;
      my $request_headers = $request->headers->clone;
      $self->_fixup_header($request_headers, $url, $proxy);
  
      $request_headers->scan(sub {
  			       my($k, $v) = @_;
  			       $k =~ s/^://;
  			       $v =~ s/\n/ /g;
  			       push(@h, $k, $v);
  			   });
  
      my $content_ref = $request->content_ref;
      $content_ref = $$content_ref if ref($$content_ref);
      my $chunked;
      my $has_content;
  
      if (ref($content_ref) eq 'CODE') {
  	my $clen = $request_headers->header('Content-Length');
  	$has_content++ if $clen;
  	unless (defined $clen) {
  	    push(@h, "Transfer-Encoding" => "chunked");
  	    $has_content++;
  	    $chunked++;
  	}
      }
      else {
  	# Set (or override) Content-Length header
  	my $clen = $request_headers->header('Content-Length');
  	if (defined($$content_ref) && length($$content_ref)) {
  	    $has_content = length($$content_ref);
  	    if (!defined($clen) || $clen ne $has_content) {
  		if (defined $clen) {
  		    warn "Content-Length header value was wrong, fixed";
  		    hlist_remove(\@h, 'Content-Length');
  		}
  		push(@h, 'Content-Length' => $has_content);
  	    }
  	}
  	elsif ($clen) {
  	    warn "Content-Length set when there is no content, fixed";
  	    hlist_remove(\@h, 'Content-Length');
  	}
      }
  
      my $write_wait = 0;
      $write_wait = 2
  	if ($request_headers->header("Expect") || "") =~ /100-continue/;
  
      my $req_buf = $socket->format_request($method, $fullpath, @h);
      #print "------\n$req_buf\n------\n";
  
      if (!$has_content || $write_wait || $has_content > 8*1024) {
        WRITE:
          {
              # Since this just writes out the header block it should almost
              # always succeed to send the whole buffer in a single write call.
              my $n = $socket->syswrite($req_buf, length($req_buf));
              unless (defined $n) {
                  redo WRITE if $!{EINTR};
                  if ($!{EAGAIN}) {
                      select(undef, undef, undef, 0.1);
                      redo WRITE;
                  }
                  die "write failed: $!";
              }
              if ($n) {
                  substr($req_buf, 0, $n, "");
              }
              else {
                  select(undef, undef, undef, 0.5);
              }
              redo WRITE if length $req_buf;
          }
      }
  
      my($code, $mess, @junk);
      my $drop_connection;
  
      if ($has_content) {
  	my $eof;
  	my $wbuf;
  	my $woffset = 0;
        INITIAL_READ:
  	if ($write_wait) {
  	    # skip filling $wbuf when waiting for 100-continue
  	    # because if the response is a redirect or auth required
  	    # the request will be cloned and there is no way
  	    # to reset the input stream
  	    # return here via the label after the 100-continue is read
  	}
  	elsif (ref($content_ref) eq 'CODE') {
  	    my $buf = &$content_ref();
  	    $buf = "" unless defined($buf);
  	    $buf = sprintf "%x%s%s%s", length($buf), $CRLF, $buf, $CRLF
  		if $chunked;
  	    substr($buf, 0, 0) = $req_buf if $req_buf;
  	    $wbuf = \$buf;
  	}
  	else {
  	    if ($req_buf) {
  		my $buf = $req_buf . $$content_ref;
  		$wbuf = \$buf;
  	    }
  	    else {
  		$wbuf = $content_ref;
  	    }
  	    $eof = 1;
  	}
  
  	my $fbits = '';
  	vec($fbits, fileno($socket), 1) = 1;
  
        WRITE:
  	while ($write_wait || $woffset < length($$wbuf)) {
  
  	    my $sel_timeout = $timeout;
  	    if ($write_wait) {
  		$sel_timeout = $write_wait if $write_wait < $sel_timeout;
  	    }
  	    my $time_before;
              $time_before = time if $sel_timeout;
  
  	    my $rbits = $fbits;
  	    my $wbits = $write_wait ? undef : $fbits;
              my $sel_timeout_before = $sel_timeout;
            SELECT:
              {
                  my $nfound = select($rbits, $wbits, undef, $sel_timeout);
                  if ($nfound < 0) {
                      if ($!{EINTR} || $!{EAGAIN}) {
                          if ($time_before) {
                              $sel_timeout = $sel_timeout_before - (time - $time_before);
                              $sel_timeout = 0 if $sel_timeout < 0;
                          }
                          redo SELECT;
                      }
                      die "select failed: $!";
                  }
  	    }
  
  	    if ($write_wait) {
  		$write_wait -= time - $time_before;
  		$write_wait = 0 if $write_wait < 0;
  	    }
  
  	    if (defined($rbits) && $rbits =~ /[^\0]/) {
  		# readable
  		my $buf = $socket->_rbuf;
  		my $n = $socket->sysread($buf, 1024, length($buf));
                  unless (defined $n) {
                      die "read failed: $!" unless  $!{EINTR} || $!{EAGAIN};
                      # if we get here the rest of the block will do nothing
                      # and we will retry the read on the next round
                  }
  		elsif ($n == 0) {
                      # the server closed the connection before we finished
                      # writing all the request content.  No need to write any more.
                      $drop_connection++;
                      last WRITE;
  		}
  		$socket->_rbuf($buf);
  		if (!$code && $buf =~ /\015?\012\015?\012/) {
  		    # a whole response header is present, so we can read it without blocking
  		    ($code, $mess, @h) = $socket->read_response_headers(laxed => 1,
  									junk_out => \@junk,
  								       );
  		    if ($code eq "100") {
  			$write_wait = 0;
  			undef($code);
  			goto INITIAL_READ;
  		    }
  		    else {
  			$drop_connection++;
  			last WRITE;
  			# XXX should perhaps try to abort write in a nice way too
  		    }
  		}
  	    }
  	    if (defined($wbits) && $wbits =~ /[^\0]/) {
  		my $n = $socket->syswrite($$wbuf, length($$wbuf), $woffset);
                  unless (defined $n) {
                      die "write failed: $!" unless $!{EINTR} || $!{EAGAIN};
                      $n = 0;  # will retry write on the next round
                  }
                  elsif ($n == 0) {
  		    die "write failed: no bytes written";
  		}
  		$woffset += $n;
  
  		if (!$eof && $woffset >= length($$wbuf)) {
  		    # need to refill buffer from $content_ref code
  		    my $buf = &$content_ref();
  		    $buf = "" unless defined($buf);
  		    $eof++ unless length($buf);
  		    $buf = sprintf "%x%s%s%s", length($buf), $CRLF, $buf, $CRLF
  			if $chunked;
  		    $wbuf = \$buf;
  		    $woffset = 0;
  		}
  	    }
  	} # WRITE
      }
  
      ($code, $mess, @h) = $socket->read_response_headers(laxed => 1, junk_out => \@junk)
  	unless $code;
      ($code, $mess, @h) = $socket->read_response_headers(laxed => 1, junk_out => \@junk)
  	if $code eq "100";
  
      my $response = HTTP::Response->new($code, $mess);
      my $peer_http_version = $socket->peer_http_version;
      $response->protocol("HTTP/$peer_http_version");
      {
  	local $HTTP::Headers::TRANSLATE_UNDERSCORE;
  	$response->push_header(@h);
      }
      $response->push_header("Client-Junk" => \@junk) if @junk;
  
      $response->request($request);
      $self->_get_sock_info($response, $socket);
  
      if ($method eq "CONNECT") {
  	$response->{client_socket} = $socket;  # so it can be picked up
  	return $response;
      }
  
      if (my @te = $response->remove_header('Transfer-Encoding')) {
  	$response->push_header('Client-Transfer-Encoding', \@te);
      }
      $response->push_header('Client-Response-Num', scalar $socket->increment_response_count);
  
      my $complete;
      $response = $self->collect($arg, $response, sub {
  	my $buf = ""; #prevent use of uninitialized value in SSLeay.xs
  	my $n;
        READ:
  	{
  	    $n = $socket->read_entity_body($buf, $size);
              unless (defined $n) {
                  redo READ if $!{EINTR} || $!{EAGAIN};
                  die "read failed: $!";
              }
  	    redo READ if $n == -1;
  	}
  	$complete++ if !$n;
          return \$buf;
      } );
      $drop_connection++ unless $complete;
  
      @h = $socket->get_trailers;
      if (@h) {
  	local $HTTP::Headers::TRANSLATE_UNDERSCORE;
  	$response->push_header(@h);
      }
  
      # keep-alive support
      unless ($drop_connection) {
  	if (my $conn_cache = $self->{ua}{conn_cache}) {
  	    my %connection = map { (lc($_) => 1) }
  		             split(/\s*,\s*/, ($response->header("Connection") || ""));
  	    if (($peer_http_version eq "1.1" && !$connection{close}) ||
  		$connection{"keep-alive"})
  	    {
  		$conn_cache->deposit($self->socket_type, "$host:$port", $socket);
  	    }
  	}
      }
  
      $response;
  }
  
  
  #-----------------------------------------------------------
  package LWP::Protocol::http::SocketMethods;
  
  sub ping {
      my $self = shift;
      !$self->can_read(0);
  }
  
  sub increment_response_count {
      my $self = shift;
      return ++${*$self}{'myhttp_response_count'};
  }
  
  #-----------------------------------------------------------
  package LWP::Protocol::http::Socket;
  use vars qw(@ISA);
  @ISA = qw(LWP::Protocol::http::SocketMethods Net::HTTP);
  
  1;
LWP_PROTOCOL_HTTP

$fatpacked{"LWP/Protocol/loopback.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'LWP_PROTOCOL_LOOPBACK';
  package LWP::Protocol::loopback;
  
  use strict;
  use vars qw(@ISA);
  require HTTP::Response;
  
  require LWP::Protocol;
  @ISA = qw(LWP::Protocol);
  
  sub request {
      my($self, $request, $proxy, $arg, $size, $timeout) = @_;
  
      my $response = HTTP::Response->new(200, "OK");
      $response->content_type("message/http; msgtype=request");
  
      $response->header("Via", "loopback/1.0 $proxy")
  	if $proxy;
  
      $response->header("X-Arg", $arg);
      $response->header("X-Read-Size", $size);
      $response->header("X-Timeout", $timeout);
  
      return $self->collect_once($arg, $response, $request->as_string);
  }
  
  1;
LWP_PROTOCOL_LOOPBACK

$fatpacked{"LWP/Protocol/mailto.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'LWP_PROTOCOL_MAILTO';
  package LWP::Protocol::mailto;
  
  # This module implements the mailto protocol.  It is just a simple
  # frontend to the Unix sendmail program except on MacOS, where it uses
  # Mail::Internet.
  
  require LWP::Protocol;
  require HTTP::Request;
  require HTTP::Response;
  require HTTP::Status;
  
  use Carp;
  use strict;
  use vars qw(@ISA $SENDMAIL);
  
  @ISA = qw(LWP::Protocol);
  
  unless ($SENDMAIL = $ENV{SENDMAIL}) {
      for my $sm (qw(/usr/sbin/sendmail
  		   /usr/lib/sendmail
  		   /usr/ucblib/sendmail
  		  ))
      {
  	if (-x $sm) {
  	    $SENDMAIL = $sm;
  	    last;
  	}
      }
      die "Can't find the 'sendmail' program" unless $SENDMAIL;
  }
  
  sub request
  {
      my($self, $request, $proxy, $arg, $size) = @_;
  
      my ($mail, $addr) if $^O eq "MacOS";
      my @text = () if $^O eq "MacOS";
  
      # check proxy
      if (defined $proxy)
      {
  	return HTTP::Response->new(&HTTP::Status::RC_BAD_REQUEST,
  				  'You can not proxy with mail');
      }
  
      # check method
      my $method = $request->method;
  
      if ($method ne 'POST') {
  	return HTTP::Response->new( &HTTP::Status::RC_BAD_REQUEST,
  				  'Library does not allow method ' .
  				  "$method for 'mailto:' URLs");
      }
  
      # check url
      my $url = $request->uri;
  
      my $scheme = $url->scheme;
      if ($scheme ne 'mailto') {
  	return HTTP::Response->new( &HTTP::Status::RC_INTERNAL_SERVER_ERROR,
  			 "LWP::Protocol::mailto::request called for '$scheme'");
      }
      if ($^O eq "MacOS") {
  	eval {
  	    require Mail::Internet;
  	};
  	if($@) {
  	    return HTTP::Response->new( &HTTP::Status::RC_INTERNAL_SERVER_ERROR,
  	               "You don't have MailTools installed");
  	}
  	unless ($ENV{SMTPHOSTS}) {
  	    return HTTP::Response->new( &HTTP::Status::RC_INTERNAL_SERVER_ERROR,
  	               "You don't have SMTPHOSTS defined");
  	}
      }
      else {
  	unless (-x $SENDMAIL) {
  	    return HTTP::Response->new( &HTTP::Status::RC_INTERNAL_SERVER_ERROR,
  	               "You don't have $SENDMAIL");
      }
      }
      if ($^O eq "MacOS") {
  	    $mail = Mail::Internet->new or
  	    return HTTP::Response->new( &HTTP::Status::RC_INTERNAL_SERVER_ERROR,
  	    "Can't get a Mail::Internet object");
      }
      else {
  	open(SENDMAIL, "| $SENDMAIL -oi -t") or
  	    return HTTP::Response->new( &HTTP::Status::RC_INTERNAL_SERVER_ERROR,
  	               "Can't run $SENDMAIL: $!");
      }
      if ($^O eq "MacOS") {
  	$addr = $url->encoded822addr;
      }
      else {
  	$request = $request->clone;  # we modify a copy
  	my @h = $url->headers;  # URL headers override those in the request
  	while (@h) {
  	    my $k = shift @h;
  	    my $v = shift @h;
  	    next unless defined $v;
  	    if (lc($k) eq "body") {
  		$request->content($v);
  	    }
  	    else {
  		$request->push_header($k => $v);
  	    }
  	}
      }
      if ($^O eq "MacOS") {
  	$mail->add(To => $addr);
  	$mail->add(split(/[:\n]/,$request->headers_as_string));
      }
      else {
  	print SENDMAIL $request->headers_as_string;
  	print SENDMAIL "\n";
      }
      my $content = $request->content;
      if (defined $content) {
  	my $contRef = ref($content) ? $content : \$content;
  	if (ref($contRef) eq 'SCALAR') {
  	    if ($^O eq "MacOS") {
  		@text = split("\n",$$contRef);
  		foreach (@text) {
  		    $_ .= "\n";
  		}
  	    }
  	    else {
  	    print SENDMAIL $$contRef;
  	    }
  
  	}
  	elsif (ref($contRef) eq 'CODE') {
  	    # Callback provides data
  	    my $d;
  	    if ($^O eq "MacOS") {
  		my $stuff = "";
  		while (length($d = &$contRef)) {
  		    $stuff .= $d;
  		}
  		@text = split("\n",$stuff);
  		foreach (@text) {
  		    $_ .= "\n";
  		}
  	    }
  	    else {
  		print SENDMAIL $d;
  	    }
  	}
      }
      if ($^O eq "MacOS") {
  	$mail->body(\@text);
  	unless ($mail->smtpsend) {
  	    return HTTP::Response->new(&HTTP::Status::RC_INTERNAL_SERVER_ERROR,
  				       "Mail::Internet->smtpsend unable to send message to <$addr>");
  	}
      }
      else {
  	unless (close(SENDMAIL)) {
  	    my $err = $! ? "$!" : "Exit status $?";
  	    return HTTP::Response->new(&HTTP::Status::RC_INTERNAL_SERVER_ERROR,
  				       "$SENDMAIL: $err");
  	}
      }
  
  
      my $response = HTTP::Response->new(&HTTP::Status::RC_ACCEPTED,
  				       "Mail accepted");
      $response->header('Content-Type', 'text/plain');
      if ($^O eq "MacOS") {
  	$response->header('Server' => "Mail::Internet $Mail::Internet::VERSION");
  	$response->content("Message sent to <$addr>\n");
      }
      else {
  	$response->header('Server' => $SENDMAIL);
  	my $to = $request->header("To");
  	$response->content("Message sent to <$to>\n");
      }
  
      return $response;
  }
  
  1;
LWP_PROTOCOL_MAILTO

$fatpacked{"LWP/Protocol/nntp.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'LWP_PROTOCOL_NNTP';
  package LWP::Protocol::nntp;
  
  # Implementation of the Network News Transfer Protocol (RFC 977)
  
  require LWP::Protocol;
  @ISA = qw(LWP::Protocol);
  
  require HTTP::Response;
  require HTTP::Status;
  require Net::NNTP;
  
  use strict;
  
  
  sub request
  {
      my($self, $request, $proxy, $arg, $size, $timeout) = @_;
  
      $size = 4096 unless $size;
  
      # Check for proxy
      if (defined $proxy) {
  	return HTTP::Response->new(&HTTP::Status::RC_BAD_REQUEST,
  				   'You can not proxy through NNTP');
      }
  
      # Check that the scheme is as expected
      my $url = $request->uri;
      my $scheme = $url->scheme;
      unless ($scheme eq 'news' || $scheme eq 'nntp') {
  	return HTTP::Response->new(&HTTP::Status::RC_INTERNAL_SERVER_ERROR,
  				   "LWP::Protocol::nntp::request called for '$scheme'");
      }
  
      # check for a valid method
      my $method = $request->method;
      unless ($method eq 'GET' || $method eq 'HEAD' || $method eq 'POST') {
  	return HTTP::Response->new(&HTTP::Status::RC_BAD_REQUEST,
  				   'Library does not allow method ' .
  				   "$method for '$scheme:' URLs");
      }
  
      # extract the identifier and check against posting to an article
      my $groupart = $url->_group;
      my $is_art = $groupart =~ /@/;
  
      if ($is_art && $method eq 'POST') {
  	return HTTP::Response->new(&HTTP::Status::RC_BAD_REQUEST,
  				   "Can't post to an article <$groupart>");
      }
  
      my $nntp = Net::NNTP->new($url->host,
  			      #Port    => 18574,
  			      Timeout => $timeout,
  			      #Debug   => 1,
  			     );
      die "Can't connect to nntp server" unless $nntp;
  
      # Check the initial welcome message from the NNTP server
      if ($nntp->status != 2) {
  	return HTTP::Response->new(&HTTP::Status::RC_SERVICE_UNAVAILABLE,
  				   $nntp->message);
      }
      my $response = HTTP::Response->new(&HTTP::Status::RC_OK, "OK");
  
      my $mess = $nntp->message;
  
      # Try to extract server name from greeting message.
      # Don't know if this works well for a large class of servers, but
      # this works for our server.
      $mess =~ s/\s+ready\b.*//;
      $mess =~ s/^\S+\s+//;
      $response->header(Server => $mess);
  
      # First we handle posting of articles
      if ($method eq 'POST') {
  	$nntp->quit; $nntp = undef;
  	$response->code(&HTTP::Status::RC_NOT_IMPLEMENTED);
  	$response->message("POST not implemented yet");
  	return $response;
      }
  
      # The method must be "GET" or "HEAD" by now
      if (!$is_art) {
  	if (!$nntp->group($groupart)) {
  	    $response->code(&HTTP::Status::RC_NOT_FOUND);
  	    $response->message($nntp->message);
  	}
  	$nntp->quit; $nntp = undef;
  	# HEAD: just check if the group exists
  	if ($method eq 'GET' && $response->is_success) {
  	    $response->code(&HTTP::Status::RC_NOT_IMPLEMENTED);
  	    $response->message("GET newsgroup not implemented yet");
  	}
  	return $response;
      }
  
      # Send command to server to retrieve an article (or just the headers)
      my $get = $method eq 'HEAD' ? "head" : "article";
      my $art = $nntp->$get("<$groupart>");
      unless ($art) {
  	$nntp->quit; $nntp = undef;
  	$response->code(&HTTP::Status::RC_NOT_FOUND);
  	$response->message($nntp->message);
  	return $response;
      }
  
      # Parse headers
      my($key, $val);
      local $_;
      while ($_ = shift @$art) {
  	if (/^\s+$/) {
  	    last;  # end of headers
  	}
  	elsif (/^(\S+):\s*(.*)/) {
  	    $response->push_header($key, $val) if $key;
  	    ($key, $val) = ($1, $2);
  	}
  	elsif (/^\s+(.*)/) {
  	    next unless $key;
  	    $val .= $1;
  	}
  	else {
  	    unshift(@$art, $_);
  	    last;
  	}
      }
      $response->push_header($key, $val) if $key;
  
      # Ensure that there is a Content-Type header
      $response->header("Content-Type", "text/plain")
  	unless $response->header("Content-Type");
  
      # Collect the body
      $response = $self->collect_once($arg, $response, join("", @$art))
        if @$art;
  
      # Say goodbye to the server
      $nntp->quit;
      $nntp = undef;
  
      $response;
  }
  
  1;
LWP_PROTOCOL_NNTP

$fatpacked{"LWP/Protocol/nogo.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'LWP_PROTOCOL_NOGO';
  package LWP::Protocol::nogo;
  # If you want to disable access to a particular scheme, use this
  # class and then call
  #   LWP::Protocol::implementor(that_scheme, 'LWP::Protocol::nogo');
  # For then on, attempts to access URLs with that scheme will generate
  # a 500 error.
  
  use strict;
  use vars qw(@ISA);
  require HTTP::Response;
  require HTTP::Status;
  require LWP::Protocol;
  @ISA = qw(LWP::Protocol);
  
  sub request {
      my($self, $request) = @_;
      my $scheme = $request->uri->scheme;
      
      return HTTP::Response->new(
        &HTTP::Status::RC_INTERNAL_SERVER_ERROR,
        "Access to \'$scheme\' URIs has been disabled"
      );
  }
  1;
LWP_PROTOCOL_NOGO

$fatpacked{"LWP/RobotUA.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'LWP_ROBOTUA';
  package LWP::RobotUA;
  
  require LWP::UserAgent;
  @ISA = qw(LWP::UserAgent);
  $VERSION = "6.03";
  
  require WWW::RobotRules;
  require HTTP::Request;
  require HTTP::Response;
  
  use Carp ();
  use HTTP::Status ();
  use HTTP::Date qw(time2str);
  use strict;
  
  
  #
  # Additional attributes in addition to those found in LWP::UserAgent:
  #
  # $self->{'delay'}    Required delay between request to the same
  #                     server in minutes.
  #
  # $self->{'rules'}     A WWW::RobotRules object
  #
  
  sub new
  {
      my $class = shift;
      my %cnf;
      if (@_ < 4) {
  	# legacy args
  	@cnf{qw(agent from rules)} = @_;
      }
      else {
  	%cnf = @_;
      }
  
      Carp::croak('LWP::RobotUA agent required') unless $cnf{agent};
      Carp::croak('LWP::RobotUA from address required')
  	unless $cnf{from} && $cnf{from} =~ m/\@/;
  
      my $delay = delete $cnf{delay} || 1;
      my $use_sleep = delete $cnf{use_sleep};
      $use_sleep = 1 unless defined($use_sleep);
      my $rules = delete $cnf{rules};
  
      my $self = LWP::UserAgent->new(%cnf);
      $self = bless $self, $class;
  
      $self->{'delay'} = $delay;   # minutes
      $self->{'use_sleep'} = $use_sleep;
  
      if ($rules) {
  	$rules->agent($cnf{agent});
  	$self->{'rules'} = $rules;
      }
      else {
  	$self->{'rules'} = WWW::RobotRules->new($cnf{agent});
      }
  
      $self;
  }
  
  
  sub delay     { shift->_elem('delay',     @_); }
  sub use_sleep { shift->_elem('use_sleep', @_); }
  
  
  sub agent
  {
      my $self = shift;
      my $old = $self->SUPER::agent(@_);
      if (@_) {
  	# Changing our name means to start fresh
  	$self->{'rules'}->agent($self->{'agent'}); 
      }
      $old;
  }
  
  
  sub rules {
      my $self = shift;
      my $old = $self->_elem('rules', @_);
      $self->{'rules'}->agent($self->{'agent'}) if @_;
      $old;
  }
  
  
  sub no_visits
  {
      my($self, $netloc) = @_;
      $self->{'rules'}->no_visits($netloc) || 0;
  }
  
  *host_count = \&no_visits;  # backwards compatibility with LWP-5.02
  
  
  sub host_wait
  {
      my($self, $netloc) = @_;
      return undef unless defined $netloc;
      my $last = $self->{'rules'}->last_visit($netloc);
      if ($last) {
  	my $wait = int($self->{'delay'} * 60 - (time - $last));
  	$wait = 0 if $wait < 0;
  	return $wait;
      }
      return 0;
  }
  
  
  sub simple_request
  {
      my($self, $request, $arg, $size) = @_;
  
      # Do we try to access a new server?
      my $allowed = $self->{'rules'}->allowed($request->uri);
  
      if ($allowed < 0) {
  	# Host is not visited before, or robots.txt expired; fetch "robots.txt"
  	my $robot_url = $request->uri->clone;
  	$robot_url->path("robots.txt");
  	$robot_url->query(undef);
  
  	# make access to robot.txt legal since this will be a recursive call
  	$self->{'rules'}->parse($robot_url, ""); 
  
  	my $robot_req = HTTP::Request->new('GET', $robot_url);
  	my $parse_head = $self->parse_head(0);
  	my $robot_res = $self->request($robot_req);
  	$self->parse_head($parse_head);
  	my $fresh_until = $robot_res->fresh_until;
  	my $content = "";
  	if ($robot_res->is_success && $robot_res->content_is_text) {
  	    $content = $robot_res->decoded_content;
  	    $content = "" unless $content && $content =~ /^\s*Disallow\s*:/mi;
  	}
  	$self->{'rules'}->parse($robot_url, $content, $fresh_until);
  
  	# recalculate allowed...
  	$allowed = $self->{'rules'}->allowed($request->uri);
      }
  
      # Check rules
      unless ($allowed) {
  	my $res = HTTP::Response->new(
  	  &HTTP::Status::RC_FORBIDDEN, 'Forbidden by robots.txt');
  	$res->request( $request ); # bind it to that request
  	return $res;
      }
  
      my $netloc = eval { local $SIG{__DIE__}; $request->uri->host_port; };
      my $wait = $self->host_wait($netloc);
  
      if ($wait) {
  	if ($self->{'use_sleep'}) {
  	    sleep($wait)
  	}
  	else {
  	    my $res = HTTP::Response->new(
  	      &HTTP::Status::RC_SERVICE_UNAVAILABLE, 'Please, slow down');
  	    $res->header('Retry-After', time2str(time + $wait));
  	    $res->request( $request ); # bind it to that request
  	    return $res;
  	}
      }
  
      # Perform the request
      my $res = $self->SUPER::simple_request($request, $arg, $size);
  
      $self->{'rules'}->visit($netloc);
  
      $res;
  }
  
  
  sub as_string
  {
      my $self = shift;
      my @s;
      push(@s, "Robot: $self->{'agent'} operated by $self->{'from'}  [$self]");
      push(@s, "    Minimum delay: " . int($self->{'delay'}*60) . "s");
      push(@s, "    Will sleep if too early") if $self->{'use_sleep'};
      push(@s, "    Rules = $self->{'rules'}");
      join("\n", @s, '');
  }
  
  1;
  
  
  __END__
  
  =head1 NAME
  
  LWP::RobotUA - a class for well-behaved Web robots
  
  =head1 SYNOPSIS
  
    use LWP::RobotUA;
    my $ua = LWP::RobotUA->new('my-robot/0.1', 'me@foo.com');
    $ua->delay(10);  # be very nice -- max one hit every ten minutes!
    ...
  
    # Then just use it just like a normal LWP::UserAgent:
    my $response = $ua->get('http://whatever.int/...');
    ...
  
  =head1 DESCRIPTION
  
  This class implements a user agent that is suitable for robot
  applications.  Robots should be nice to the servers they visit.  They
  should consult the F</robots.txt> file to ensure that they are welcomed
  and they should not make requests too frequently.
  
  But before you consider writing a robot, take a look at
  <URL:http://www.robotstxt.org/>.
  
  When you use a I<LWP::RobotUA> object as your user agent, then you do not
  really have to think about these things yourself; C<robots.txt> files
  are automatically consulted and obeyed, the server isn't queried
  too rapidly, and so on.  Just send requests
  as you do when you are using a normal I<LWP::UserAgent>
  object (using C<< $ua->get(...) >>, C<< $ua->head(...) >>,
  C<< $ua->request(...) >>, etc.), and this
  special agent will make sure you are nice.
  
  =head1 METHODS
  
  The LWP::RobotUA is a sub-class of LWP::UserAgent and implements the
  same methods. In addition the following methods are provided:
  
  =over 4
  
  =item $ua = LWP::RobotUA->new( %options )
  
  =item $ua = LWP::RobotUA->new( $agent, $from )
  
  =item $ua = LWP::RobotUA->new( $agent, $from, $rules )
  
  The LWP::UserAgent options C<agent> and C<from> are mandatory.  The
  options C<delay>, C<use_sleep> and C<rules> initialize attributes
  private to the RobotUA.  If C<rules> are not provided, then
  C<WWW::RobotRules> is instantiated providing an internal database of
  F<robots.txt>.
  
  It is also possible to just pass the value of C<agent>, C<from> and
  optionally C<rules> as plain positional arguments.
  
  =item $ua->delay
  
  =item $ua->delay( $minutes )
  
  Get/set the minimum delay between requests to the same server, in
  I<minutes>.  The default is 1 minute.  Note that this number doesn't
  have to be an integer; for example, this sets the delay to 10 seconds:
  
      $ua->delay(10/60);
  
  =item $ua->use_sleep
  
  =item $ua->use_sleep( $boolean )
  
  Get/set a value indicating whether the UA should sleep() if requests
  arrive too fast, defined as $ua->delay minutes not passed since
  last request to the given server.  The default is TRUE.  If this value is
  FALSE then an internal SERVICE_UNAVAILABLE response will be generated.
  It will have an Retry-After header that indicates when it is OK to
  send another request to this server.
  
  =item $ua->rules
  
  =item $ua->rules( $rules )
  
  Set/get which I<WWW::RobotRules> object to use.
  
  =item $ua->no_visits( $netloc )
  
  Returns the number of documents fetched from this server host. Yeah I
  know, this method should probably have been named num_visits() or
  something like that. :-(
  
  =item $ua->host_wait( $netloc )
  
  Returns the number of I<seconds> (from now) you must wait before you can
  make a new request to this host.
  
  =item $ua->as_string
  
  Returns a string that describes the state of the UA.
  Mainly useful for debugging.
  
  =back
  
  =head1 SEE ALSO
  
  L<LWP::UserAgent>, L<WWW::RobotRules>
  
  =head1 COPYRIGHT
  
  Copyright 1996-2004 Gisle Aas.
  
  This library is free software; you can redistribute it and/or
  modify it under the same terms as Perl itself.
LWP_ROBOTUA

$fatpacked{"LWP/Simple.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'LWP_SIMPLE';
  package LWP::Simple;
  
  use strict;
  use vars qw($ua %loop_check $FULL_LWP @EXPORT @EXPORT_OK $VERSION);
  
  require Exporter;
  
  @EXPORT = qw(get head getprint getstore mirror);
  @EXPORT_OK = qw($ua);
  
  # I really hate this.  I was a bad idea to do it in the first place.
  # Wonder how to get rid of it???  (It even makes LWP::Simple 7% slower
  # for trivial tests)
  use HTTP::Status;
  push(@EXPORT, @HTTP::Status::EXPORT);
  
  $VERSION = "6.00";
  
  sub import
  {
      my $pkg = shift;
      my $callpkg = caller;
      Exporter::export($pkg, $callpkg, @_);
  }
  
  use LWP::UserAgent ();
  use HTTP::Status ();
  use HTTP::Date ();
  $ua = LWP::UserAgent->new;  # we create a global UserAgent object
  $ua->agent("LWP::Simple/$VERSION ");
  $ua->env_proxy;
  
  
  sub get ($)
  {
      my $response = $ua->get(shift);
      return $response->decoded_content if $response->is_success;
      return undef;
  }
  
  
  sub head ($)
  {
      my($url) = @_;
      my $request = HTTP::Request->new(HEAD => $url);
      my $response = $ua->request($request);
  
      if ($response->is_success) {
  	return $response unless wantarray;
  	return (scalar $response->header('Content-Type'),
  		scalar $response->header('Content-Length'),
  		HTTP::Date::str2time($response->header('Last-Modified')),
  		HTTP::Date::str2time($response->header('Expires')),
  		scalar $response->header('Server'),
  	       );
      }
      return;
  }
  
  
  sub getprint ($)
  {
      my($url) = @_;
      my $request = HTTP::Request->new(GET => $url);
      local($\) = ""; # ensure standard $OUTPUT_RECORD_SEPARATOR
      my $callback = sub { print $_[0] };
      if ($^O eq "MacOS") {
  	$callback = sub { $_[0] =~ s/\015?\012/\n/g; print $_[0] }
      }
      my $response = $ua->request($request, $callback);
      unless ($response->is_success) {
  	print STDERR $response->status_line, " <URL:$url>\n";
      }
      $response->code;
  }
  
  
  sub getstore ($$)
  {
      my($url, $file) = @_;
      my $request = HTTP::Request->new(GET => $url);
      my $response = $ua->request($request, $file);
  
      $response->code;
  }
  
  
  sub mirror ($$)
  {
      my($url, $file) = @_;
      my $response = $ua->mirror($url, $file);
      $response->code;
  }
  
  
  1;
  
  __END__
  
  =head1 NAME
  
  LWP::Simple - simple procedural interface to LWP
  
  =head1 SYNOPSIS
  
   perl -MLWP::Simple -e 'getprint "http://www.sn.no"'
  
   use LWP::Simple;
   $content = get("http://www.sn.no/");
   die "Couldn't get it!" unless defined $content;
  
   if (mirror("http://www.sn.no/", "foo") == RC_NOT_MODIFIED) {
       ...
   }
  
   if (is_success(getprint("http://www.sn.no/"))) {
       ...
   }
  
  =head1 DESCRIPTION
  
  This module is meant for people who want a simplified view of the
  libwww-perl library.  It should also be suitable for one-liners.  If
  you need more control or access to the header fields in the requests
  sent and responses received, then you should use the full object-oriented
  interface provided by the C<LWP::UserAgent> module.
  
  The following functions are provided (and exported) by this module:
  
  =over 3
  
  =item get($url)
  
  The get() function will fetch the document identified by the given URL
  and return it.  It returns C<undef> if it fails.  The $url argument can
  be either a string or a reference to a URI object.
  
  You will not be able to examine the response code or response headers
  (like 'Content-Type') when you are accessing the web using this
  function.  If you need that information you should use the full OO
  interface (see L<LWP::UserAgent>).
  
  =item head($url)
  
  Get document headers. Returns the following 5 values if successful:
  ($content_type, $document_length, $modified_time, $expires, $server)
  
  Returns an empty list if it fails.  In scalar context returns TRUE if
  successful.
  
  =item getprint($url)
  
  Get and print a document identified by a URL. The document is printed
  to the selected default filehandle for output (normally STDOUT) as
  data is received from the network.  If the request fails, then the
  status code and message are printed on STDERR.  The return value is
  the HTTP response code.
  
  =item getstore($url, $file)
  
  Gets a document identified by a URL and stores it in the file. The
  return value is the HTTP response code.
  
  =item mirror($url, $file)
  
  Get and store a document identified by a URL, using
  I<If-modified-since>, and checking the I<Content-Length>.  Returns
  the HTTP response code.
  
  =back
  
  This module also exports the HTTP::Status constants and procedures.
  You can use them when you check the response code from getprint(),
  getstore() or mirror().  The constants are:
  
     RC_CONTINUE
     RC_SWITCHING_PROTOCOLS
     RC_OK
     RC_CREATED
     RC_ACCEPTED
     RC_NON_AUTHORITATIVE_INFORMATION
     RC_NO_CONTENT
     RC_RESET_CONTENT
     RC_PARTIAL_CONTENT
     RC_MULTIPLE_CHOICES
     RC_MOVED_PERMANENTLY
     RC_MOVED_TEMPORARILY
     RC_SEE_OTHER
     RC_NOT_MODIFIED
     RC_USE_PROXY
     RC_BAD_REQUEST
     RC_UNAUTHORIZED
     RC_PAYMENT_REQUIRED
     RC_FORBIDDEN
     RC_NOT_FOUND
     RC_METHOD_NOT_ALLOWED
     RC_NOT_ACCEPTABLE
     RC_PROXY_AUTHENTICATION_REQUIRED
     RC_REQUEST_TIMEOUT
     RC_CONFLICT
     RC_GONE
     RC_LENGTH_REQUIRED
     RC_PRECONDITION_FAILED
     RC_REQUEST_ENTITY_TOO_LARGE
     RC_REQUEST_URI_TOO_LARGE
     RC_UNSUPPORTED_MEDIA_TYPE
     RC_INTERNAL_SERVER_ERROR
     RC_NOT_IMPLEMENTED
     RC_BAD_GATEWAY
     RC_SERVICE_UNAVAILABLE
     RC_GATEWAY_TIMEOUT
     RC_HTTP_VERSION_NOT_SUPPORTED
  
  The HTTP::Status classification functions are:
  
  =over 3
  
  =item is_success($rc)
  
  True if response code indicated a successful request.
  
  =item is_error($rc)
  
  True if response code indicated that an error occurred.
  
  =back
  
  The module will also export the LWP::UserAgent object as C<$ua> if you
  ask for it explicitly.
  
  The user agent created by this module will identify itself as
  "LWP::Simple/#.##"
  and will initialize its proxy defaults from the environment (by
  calling $ua->env_proxy).
  
  =head1 CAVEAT
  
  Note that if you are using both LWP::Simple and the very popular CGI.pm
  module, you may be importing a C<head> function from each module,
  producing a warning like "Prototype mismatch: sub main::head ($) vs
  none". Get around this problem by just not importing LWP::Simple's
  C<head> function, like so:
  
          use LWP::Simple qw(!head);
          use CGI qw(:standard);  # then only CGI.pm defines a head()
  
  Then if you do need LWP::Simple's C<head> function, you can just call
  it as C<LWP::Simple::head($url)>.
  
  =head1 SEE ALSO
  
  L<LWP>, L<lwpcook>, L<LWP::UserAgent>, L<HTTP::Status>, L<lwp-request>,
  L<lwp-mirror>
LWP_SIMPLE

$fatpacked{"LWP/UserAgent.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'LWP_USERAGENT';
  package LWP::UserAgent;
  
  use strict;
  use vars qw(@ISA $VERSION);
  
  require LWP::MemberMixin;
  @ISA = qw(LWP::MemberMixin);
  $VERSION = "6.05";
  
  use HTTP::Request ();
  use HTTP::Response ();
  use HTTP::Date ();
  
  use LWP ();
  use LWP::Protocol ();
  
  use Carp ();
  
  
  sub new
  {
      # Check for common user mistake
      Carp::croak("Options to LWP::UserAgent should be key/value pairs, not hash reference") 
          if ref($_[1]) eq 'HASH'; 
  
      my($class, %cnf) = @_;
  
      my $agent = delete $cnf{agent};
      my $from  = delete $cnf{from};
      my $def_headers = delete $cnf{default_headers};
      my $timeout = delete $cnf{timeout};
      $timeout = 3*60 unless defined $timeout;
      my $local_address = delete $cnf{local_address};
      my $ssl_opts = delete $cnf{ssl_opts} || {};
      unless (exists $ssl_opts->{verify_hostname}) {
  	# The processing of HTTPS_CA_* below is for compatibility with Crypt::SSLeay
  	if (exists $ENV{PERL_LWP_SSL_VERIFY_HOSTNAME}) {
  	    $ssl_opts->{verify_hostname} = $ENV{PERL_LWP_SSL_VERIFY_HOSTNAME};
  	}
  	elsif ($ENV{HTTPS_CA_FILE} || $ENV{HTTPS_CA_DIR}) {
  	    # Crypt-SSLeay compatibility (verify peer certificate; but not the hostname)
  	    $ssl_opts->{verify_hostname} = 0;
  	    $ssl_opts->{SSL_verify_mode} = 1;
  	}
  	else {
  	    $ssl_opts->{verify_hostname} = 1;
  	}
      }
      unless (exists $ssl_opts->{SSL_ca_file}) {
  	if (my $ca_file = $ENV{PERL_LWP_SSL_CA_FILE} || $ENV{HTTPS_CA_FILE}) {
  	    $ssl_opts->{SSL_ca_file} = $ca_file;
  	}
      }
      unless (exists $ssl_opts->{SSL_ca_path}) {
  	if (my $ca_path = $ENV{PERL_LWP_SSL_CA_PATH} || $ENV{HTTPS_CA_DIR}) {
  	    $ssl_opts->{SSL_ca_path} = $ca_path;
  	}
      }
      my $use_eval = delete $cnf{use_eval};
      $use_eval = 1 unless defined $use_eval;
      my $parse_head = delete $cnf{parse_head};
      $parse_head = 1 unless defined $parse_head;
      my $show_progress = delete $cnf{show_progress};
      my $max_size = delete $cnf{max_size};
      my $max_redirect = delete $cnf{max_redirect};
      $max_redirect = 7 unless defined $max_redirect;
      my $env_proxy = exists $cnf{env_proxy} ? delete $cnf{env_proxy} : $ENV{PERL_LWP_ENV_PROXY};
  
      my $cookie_jar = delete $cnf{cookie_jar};
      my $conn_cache = delete $cnf{conn_cache};
      my $keep_alive = delete $cnf{keep_alive};
      
      Carp::croak("Can't mix conn_cache and keep_alive")
  	  if $conn_cache && $keep_alive;
  
      my $protocols_allowed   = delete $cnf{protocols_allowed};
      my $protocols_forbidden = delete $cnf{protocols_forbidden};
      
      my $requests_redirectable = delete $cnf{requests_redirectable};
      $requests_redirectable = ['GET', 'HEAD']
        unless defined $requests_redirectable;
  
      # Actually ""s are just as good as 0's, but for concision we'll just say:
      Carp::croak("protocols_allowed has to be an arrayref or 0, not \"$protocols_allowed\"!")
        if $protocols_allowed and ref($protocols_allowed) ne 'ARRAY';
      Carp::croak("protocols_forbidden has to be an arrayref or 0, not \"$protocols_forbidden\"!")
        if $protocols_forbidden and ref($protocols_forbidden) ne 'ARRAY';
      Carp::croak("requests_redirectable has to be an arrayref or 0, not \"$requests_redirectable\"!")
        if $requests_redirectable and ref($requests_redirectable) ne 'ARRAY';
  
  
      if (%cnf && $^W) {
  	Carp::carp("Unrecognized LWP::UserAgent options: @{[sort keys %cnf]}");
      }
  
      my $self = bless {
  		      def_headers  => $def_headers,
  		      timeout      => $timeout,
  		      local_address => $local_address,
  		      ssl_opts     => $ssl_opts,
  		      use_eval     => $use_eval,
                        show_progress=> $show_progress,
  		      max_size     => $max_size,
  		      max_redirect => $max_redirect,
                        proxy        => {},
  		      no_proxy     => [],
                        protocols_allowed     => $protocols_allowed,
                        protocols_forbidden   => $protocols_forbidden,
                        requests_redirectable => $requests_redirectable,
  		     }, $class;
  
      $self->agent(defined($agent) ? $agent : $class->_agent)
  	if defined($agent) || !$def_headers || !$def_headers->header("User-Agent");
      $self->from($from) if $from;
      $self->cookie_jar($cookie_jar) if $cookie_jar;
      $self->parse_head($parse_head);
      $self->env_proxy if $env_proxy;
  
      $self->protocols_allowed(  $protocols_allowed  ) if $protocols_allowed;
      $self->protocols_forbidden($protocols_forbidden) if $protocols_forbidden;
  
      if ($keep_alive) {
  	$conn_cache ||= { total_capacity => $keep_alive };
      }
      $self->conn_cache($conn_cache) if $conn_cache;
  
      return $self;
  }
  
  
  sub send_request
  {
      my($self, $request, $arg, $size) = @_;
      my($method, $url) = ($request->method, $request->uri);
      my $scheme = $url->scheme;
  
      local($SIG{__DIE__});  # protect against user defined die handlers
  
      $self->progress("begin", $request);
  
      my $response = $self->run_handlers("request_send", $request);
  
      unless ($response) {
          my $protocol;
  
          {
              # Honor object-specific restrictions by forcing protocol objects
              #  into class LWP::Protocol::nogo.
              my $x;
              if($x = $self->protocols_allowed) {
                  if (grep lc($_) eq $scheme, @$x) {
                  }
                  else {
                      require LWP::Protocol::nogo;
                      $protocol = LWP::Protocol::nogo->new;
                  }
              }
              elsif ($x = $self->protocols_forbidden) {
                  if(grep lc($_) eq $scheme, @$x) {
                      require LWP::Protocol::nogo;
                      $protocol = LWP::Protocol::nogo->new;
                  }
              }
              # else fall thru and create the protocol object normally
          }
  
          # Locate protocol to use
          my $proxy = $request->{proxy};
          if ($proxy) {
              $scheme = $proxy->scheme;
          }
  
          unless ($protocol) {
              $protocol = eval { LWP::Protocol::create($scheme, $self) };
              if ($@) {
                  $@ =~ s/ at .* line \d+.*//s;  # remove file/line number
                  $response =  _new_response($request, &HTTP::Status::RC_NOT_IMPLEMENTED, $@);
                  if ($scheme eq "https") {
                      $response->message($response->message . " (LWP::Protocol::https not installed)");
                      $response->content_type("text/plain");
                      $response->content(<<EOT);
  LWP will support https URLs if the LWP::Protocol::https module
  is installed.
  EOT
                  }
              }
          }
  
          if (!$response && $self->{use_eval}) {
              # we eval, and turn dies into responses below
              eval {
                  $response = $protocol->request($request, $proxy, $arg, $size, $self->{timeout}) ||
  		    die "No response returned by $protocol";
              };
              if ($@) {
                  if (UNIVERSAL::isa($@, "HTTP::Response")) {
                      $response = $@;
                      $response->request($request);
                  }
                  else {
                      my $full = $@;
                      (my $status = $@) =~ s/\n.*//s;
                      $status =~ s/ at .* line \d+.*//s;  # remove file/line number
                      my $code = ($status =~ s/^(\d\d\d)\s+//) ? $1 : &HTTP::Status::RC_INTERNAL_SERVER_ERROR;
                      $response = _new_response($request, $code, $status, $full);
                  }
              }
          }
          elsif (!$response) {
              $response = $protocol->request($request, $proxy,
                                             $arg, $size, $self->{timeout});
              # XXX: Should we die unless $response->is_success ???
          }
      }
  
      $response->request($request);  # record request for reference
      $response->header("Client-Date" => HTTP::Date::time2str(time));
  
      $self->run_handlers("response_done", $response);
  
      $self->progress("end", $response);
      return $response;
  }
  
  
  sub prepare_request
  {
      my($self, $request) = @_;
      die "Method missing" unless $request->method;
      my $url = $request->uri;
      die "URL missing" unless $url;
      die "URL must be absolute" unless $url->scheme;
  
      $self->run_handlers("request_preprepare", $request);
  
      if (my $def_headers = $self->{def_headers}) {
  	for my $h ($def_headers->header_field_names) {
  	    $request->init_header($h => [$def_headers->header($h)]);
  	}
      }
  
      $self->run_handlers("request_prepare", $request);
  
      return $request;
  }
  
  
  sub simple_request
  {
      my($self, $request, $arg, $size) = @_;
  
      # sanity check the request passed in
      if (defined $request) {
  	if (ref $request) {
  	    Carp::croak("You need a request object, not a " . ref($request) . " object")
  	      if ref($request) eq 'ARRAY' or ref($request) eq 'HASH' or
  		 !$request->can('method') or !$request->can('uri');
  	}
  	else {
  	    Carp::croak("You need a request object, not '$request'");
  	}
      }
      else {
          Carp::croak("No request object passed in");
      }
  
      eval {
  	$request = $self->prepare_request($request);
      };
      if ($@) {
  	$@ =~ s/ at .* line \d+.*//s;  # remove file/line number
  	return _new_response($request, &HTTP::Status::RC_BAD_REQUEST, $@);
      }
      return $self->send_request($request, $arg, $size);
  }
  
  
  sub request
  {
      my($self, $request, $arg, $size, $previous) = @_;
  
      my $response = $self->simple_request($request, $arg, $size);
      $response->previous($previous) if $previous;
  
      if ($response->redirects >= $self->{max_redirect}) {
          $response->header("Client-Warning" =>
                            "Redirect loop detected (max_redirect = $self->{max_redirect})");
          return $response;
      }
  
      if (my $req = $self->run_handlers("response_redirect", $response)) {
          return $self->request($req, $arg, $size, $response);
      }
  
      my $code = $response->code;
  
      if ($code == &HTTP::Status::RC_MOVED_PERMANENTLY or
  	$code == &HTTP::Status::RC_FOUND or
  	$code == &HTTP::Status::RC_SEE_OTHER or
  	$code == &HTTP::Status::RC_TEMPORARY_REDIRECT)
      {
  	my $referral = $request->clone;
  
  	# These headers should never be forwarded
  	$referral->remove_header('Host', 'Cookie');
  	
  	if ($referral->header('Referer') &&
  	    $request->uri->scheme eq 'https' &&
  	    $referral->uri->scheme eq 'http')
  	{
  	    # RFC 2616, section 15.1.3.
  	    # https -> http redirect, suppressing Referer
  	    $referral->remove_header('Referer');
  	}
  
  	if ($code == &HTTP::Status::RC_SEE_OTHER ||
  	    $code == &HTTP::Status::RC_FOUND) 
          {
  	    my $method = uc($referral->method);
  	    unless ($method eq "GET" || $method eq "HEAD") {
  		$referral->method("GET");
  		$referral->content("");
  		$referral->remove_content_headers;
  	    }
  	}
  
  	# And then we update the URL based on the Location:-header.
  	my $referral_uri = $response->header('Location');
  	{
  	    # Some servers erroneously return a relative URL for redirects,
  	    # so make it absolute if it not already is.
  	    local $URI::ABS_ALLOW_RELATIVE_SCHEME = 1;
  	    my $base = $response->base;
  	    $referral_uri = "" unless defined $referral_uri;
  	    $referral_uri = $HTTP::URI_CLASS->new($referral_uri, $base)
  		            ->abs($base);
  	}
  	$referral->uri($referral_uri);
  
  	return $response unless $self->redirect_ok($referral, $response);
  	return $self->request($referral, $arg, $size, $response);
  
      }
      elsif ($code == &HTTP::Status::RC_UNAUTHORIZED ||
  	     $code == &HTTP::Status::RC_PROXY_AUTHENTICATION_REQUIRED
  	    )
      {
  	my $proxy = ($code == &HTTP::Status::RC_PROXY_AUTHENTICATION_REQUIRED);
  	my $ch_header = $proxy ?  "Proxy-Authenticate" : "WWW-Authenticate";
  	my @challenge = $response->header($ch_header);
  	unless (@challenge) {
  	    $response->header("Client-Warning" => 
  			      "Missing Authenticate header");
  	    return $response;
  	}
  
  	require HTTP::Headers::Util;
  	CHALLENGE: for my $challenge (@challenge) {
  	    $challenge =~ tr/,/;/;  # "," is used to separate auth-params!!
  	    ($challenge) = HTTP::Headers::Util::split_header_words($challenge);
  	    my $scheme = shift(@$challenge);
  	    shift(@$challenge); # no value
  	    $challenge = { @$challenge };  # make rest into a hash
  
  	    unless ($scheme =~ /^([a-z]+(?:-[a-z]+)*)$/) {
  		$response->header("Client-Warning" => 
  				  "Bad authentication scheme '$scheme'");
  		return $response;
  	    }
  	    $scheme = $1;  # untainted now
  	    my $class = "LWP::Authen::\u$scheme";
  	    $class =~ s/-/_/g;
  
  	    no strict 'refs';
  	    unless (%{"$class\::"}) {
  		# try to load it
  		eval "require $class";
  		if ($@) {
  		    if ($@ =~ /^Can\'t locate/) {
  			$response->header("Client-Warning" =>
  					  "Unsupported authentication scheme '$scheme'");
  		    }
  		    else {
  			$response->header("Client-Warning" => $@);
  		    }
  		    next CHALLENGE;
  		}
  	    }
  	    unless ($class->can("authenticate")) {
  		$response->header("Client-Warning" =>
  				  "Unsupported authentication scheme '$scheme'");
  		next CHALLENGE;
  	    }
  	    return $class->authenticate($self, $proxy, $challenge, $response,
  					$request, $arg, $size);
  	}
  	return $response;
      }
      return $response;
  }
  
  
  #
  # Now the shortcuts...
  #
  sub get {
      require HTTP::Request::Common;
      my($self, @parameters) = @_;
      my @suff = $self->_process_colonic_headers(\@parameters,1);
      return $self->request( HTTP::Request::Common::GET( @parameters ), @suff );
  }
  
  
  sub post {
      require HTTP::Request::Common;
      my($self, @parameters) = @_;
      my @suff = $self->_process_colonic_headers(\@parameters, (ref($parameters[1]) ? 2 : 1));
      return $self->request( HTTP::Request::Common::POST( @parameters ), @suff );
  }
  
  
  sub head {
      require HTTP::Request::Common;
      my($self, @parameters) = @_;
      my @suff = $self->_process_colonic_headers(\@parameters,1);
      return $self->request( HTTP::Request::Common::HEAD( @parameters ), @suff );
  }
  
  
  sub put {
      require HTTP::Request::Common;
      my($self, @parameters) = @_;
      my @suff = $self->_process_colonic_headers(\@parameters, (ref($parameters[1]) ? 2 : 1));
      return $self->request( HTTP::Request::Common::PUT( @parameters ), @suff );
  }
  
  
  sub delete {
      require HTTP::Request::Common;
      my($self, @parameters) = @_;
      my @suff = $self->_process_colonic_headers(\@parameters,1);
      return $self->request( HTTP::Request::Common::DELETE( @parameters ), @suff );
  }
  
  
  sub _process_colonic_headers {
      # Process :content_cb / :content_file / :read_size_hint headers.
      my($self, $args, $start_index) = @_;
  
      my($arg, $size);
      for(my $i = $start_index; $i < @$args; $i += 2) {
  	next unless defined $args->[$i];
  
  	#printf "Considering %s => %s\n", $args->[$i], $args->[$i + 1];
  
  	if($args->[$i] eq ':content_cb') {
  	    # Some sanity-checking...
  	    $arg = $args->[$i + 1];
  	    Carp::croak("A :content_cb value can't be undef") unless defined $arg;
  	    Carp::croak("A :content_cb value must be a coderef")
  		unless ref $arg and UNIVERSAL::isa($arg, 'CODE');
  	    
  	}
  	elsif ($args->[$i] eq ':content_file') {
  	    $arg = $args->[$i + 1];
  
  	    # Some sanity-checking...
  	    Carp::croak("A :content_file value can't be undef")
  		unless defined $arg;
  	    Carp::croak("A :content_file value can't be a reference")
  		if ref $arg;
  	    Carp::croak("A :content_file value can't be \"\"")
  		unless length $arg;
  
  	}
  	elsif ($args->[$i] eq ':read_size_hint') {
  	    $size = $args->[$i + 1];
  	    # Bother checking it?
  
  	}
  	else {
  	    next;
  	}
  	splice @$args, $i, 2;
  	$i -= 2;
      }
  
      # And return a suitable suffix-list for request(REQ,...)
  
      return             unless defined $arg;
      return $arg, $size if     defined $size;
      return $arg;
  }
  
  
  sub is_online {
      my $self = shift;
      return 1 if $self->get("http://www.msftncsi.com/ncsi.txt")->content eq "Microsoft NCSI";
      return 1 if $self->get("http://www.apple.com")->content =~ m,<title>Apple</title>,;
      return 0;
  }
  
  
  my @ANI = qw(- \ | /);
  
  sub progress {
      my($self, $status, $m) = @_;
      return unless $self->{show_progress};
  
      local($,, $\);
      if ($status eq "begin") {
          print STDERR "** ", $m->method, " ", $m->uri, " ==> ";
          $self->{progress_start} = time;
          $self->{progress_lastp} = "";
          $self->{progress_ani} = 0;
      }
      elsif ($status eq "end") {
          delete $self->{progress_lastp};
          delete $self->{progress_ani};
          print STDERR $m->status_line;
          my $t = time - delete $self->{progress_start};
          print STDERR " (${t}s)" if $t;
          print STDERR "\n";
      }
      elsif ($status eq "tick") {
          print STDERR "$ANI[$self->{progress_ani}++]\b";
          $self->{progress_ani} %= @ANI;
      }
      else {
          my $p = sprintf "%3.0f%%", $status * 100;
          return if $p eq $self->{progress_lastp};
          print STDERR "$p\b\b\b\b";
          $self->{progress_lastp} = $p;
      }
      STDERR->flush;
  }
  
  
  #
  # This whole allow/forbid thing is based on man 1 at's way of doing things.
  #
  sub is_protocol_supported
  {
      my($self, $scheme) = @_;
      if (ref $scheme) {
  	# assume we got a reference to an URI object
  	$scheme = $scheme->scheme;
      }
      else {
  	Carp::croak("Illegal scheme '$scheme' passed to is_protocol_supported")
  	    if $scheme =~ /\W/;
  	$scheme = lc $scheme;
      }
  
      my $x;
      if(ref($self) and $x       = $self->protocols_allowed) {
        return 0 unless grep lc($_) eq $scheme, @$x;
      }
      elsif (ref($self) and $x = $self->protocols_forbidden) {
        return 0 if grep lc($_) eq $scheme, @$x;
      }
  
      local($SIG{__DIE__});  # protect against user defined die handlers
      $x = LWP::Protocol::implementor($scheme);
      return 1 if $x and $x ne 'LWP::Protocol::nogo';
      return 0;
  }
  
  
  sub protocols_allowed      { shift->_elem('protocols_allowed'    , @_) }
  sub protocols_forbidden    { shift->_elem('protocols_forbidden'  , @_) }
  sub requests_redirectable  { shift->_elem('requests_redirectable', @_) }
  
  
  sub redirect_ok
  {
      # RFC 2616, section 10.3.2 and 10.3.3 say:
      #  If the 30[12] status code is received in response to a request other
      #  than GET or HEAD, the user agent MUST NOT automatically redirect the
      #  request unless it can be confirmed by the user, since this might
      #  change the conditions under which the request was issued.
  
      # Note that this routine used to be just:
      #  return 0 if $_[1]->method eq "POST";  return 1;
  
      my($self, $new_request, $response) = @_;
      my $method = $response->request->method;
      return 0 unless grep $_ eq $method,
        @{ $self->requests_redirectable || [] };
      
      if ($new_request->uri->scheme eq 'file') {
        $response->header("Client-Warning" =>
  			"Can't redirect to a file:// URL!");
        return 0;
      }
      
      # Otherwise it's apparently okay...
      return 1;
  }
  
  
  sub credentials
  {
      my $self = shift;
      my $netloc = lc(shift);
      my $realm = shift || "";
      my $old = $self->{basic_authentication}{$netloc}{$realm};
      if (@_) {
          $self->{basic_authentication}{$netloc}{$realm} = [@_];
      }
      return unless $old;
      return @$old if wantarray;
      return join(":", @$old);
  }
  
  
  sub get_basic_credentials
  {
      my($self, $realm, $uri, $proxy) = @_;
      return if $proxy;
      return $self->credentials($uri->host_port, $realm);
  }
  
  
  sub timeout      { shift->_elem('timeout',      @_); }
  sub local_address{ shift->_elem('local_address',@_); }
  sub max_size     { shift->_elem('max_size',     @_); }
  sub max_redirect { shift->_elem('max_redirect', @_); }
  sub show_progress{ shift->_elem('show_progress', @_); }
  
  sub ssl_opts {
      my $self = shift;
      if (@_ == 1) {
  	my $k = shift;
  	return $self->{ssl_opts}{$k};
      }
      if (@_) {
  	my $old;
  	while (@_) {
  	    my($k, $v) = splice(@_, 0, 2);
  	    $old = $self->{ssl_opts}{$k} unless @_;
  	    if (defined $v) {
  		$self->{ssl_opts}{$k} = $v;
  	    }
  	    else {
  		delete $self->{ssl_opts}{$k};
  	    }
  	}
  	%{$self->{ssl_opts}} = (%{$self->{ssl_opts}}, @_);
  	return $old;
      }
  
      return keys %{$self->{ssl_opts}};
  }
  
  sub parse_head {
      my $self = shift;
      if (@_) {
          my $flag = shift;
          my $parser;
          my $old = $self->set_my_handler("response_header", $flag ? sub {
                 my($response, $ua) = @_;
                 require HTML::HeadParser;
                 $parser = HTML::HeadParser->new;
                 $parser->xml_mode(1) if $response->content_is_xhtml;
                 $parser->utf8_mode(1) if $] >= 5.008 && $HTML::Parser::VERSION >= 3.40;
  
                 push(@{$response->{handlers}{response_data}}, {
  		   callback => sub {
  		       return unless $parser;
  		       unless ($parser->parse($_[3])) {
  			   my $h = $parser->header;
  			   my $r = $_[0];
  			   for my $f ($h->header_field_names) {
  			       $r->init_header($f, [$h->header($f)]);
  			   }
  			   undef($parser);
  		       }
  		   },
  	       });
  
              } : undef,
              m_media_type => "html",
          );
          return !!$old;
      }
      else {
          return !!$self->get_my_handler("response_header");
      }
  }
  
  sub cookie_jar {
      my $self = shift;
      my $old = $self->{cookie_jar};
      if (@_) {
  	my $jar = shift;
  	if (ref($jar) eq "HASH") {
  	    require HTTP::Cookies;
  	    $jar = HTTP::Cookies->new(%$jar);
  	}
  	$self->{cookie_jar} = $jar;
          $self->set_my_handler("request_prepare",
              $jar ? sub { $jar->add_cookie_header($_[0]); } : undef,
          );
          $self->set_my_handler("response_done",
              $jar ? sub { $jar->extract_cookies($_[0]); } : undef,
          );
      }
      $old;
  }
  
  sub default_headers {
      my $self = shift;
      my $old = $self->{def_headers} ||= HTTP::Headers->new;
      if (@_) {
  	Carp::croak("default_headers not set to HTTP::Headers compatible object")
  	    unless @_ == 1 && $_[0]->can("header_field_names");
  	$self->{def_headers} = shift;
      }
      return $old;
  }
  
  sub default_header {
      my $self = shift;
      return $self->default_headers->header(@_);
  }
  
  sub _agent       { "libwww-perl/$LWP::VERSION" }
  
  sub agent {
      my $self = shift;
      if (@_) {
  	my $agent = shift;
          if ($agent) {
              $agent .= $self->_agent if $agent =~ /\s+$/;
          }
          else {
              undef($agent)
          }
          return $self->default_header("User-Agent", $agent);
      }
      return $self->default_header("User-Agent");
  }
  
  sub from {  # legacy
      my $self = shift;
      return $self->default_header("From", @_);
  }
  
  
  sub conn_cache {
      my $self = shift;
      my $old = $self->{conn_cache};
      if (@_) {
  	my $cache = shift;
  	if (ref($cache) eq "HASH") {
  	    require LWP::ConnCache;
  	    $cache = LWP::ConnCache->new(%$cache);
  	}
  	$self->{conn_cache} = $cache;
      }
      $old;
  }
  
  
  sub add_handler {
      my($self, $phase, $cb, %spec) = @_;
      $spec{line} ||= join(":", (caller)[1,2]);
      my $conf = $self->{handlers}{$phase} ||= do {
          require HTTP::Config;
          HTTP::Config->new;
      };
      $conf->add(%spec, callback => $cb);
  }
  
  sub set_my_handler {
      my($self, $phase, $cb, %spec) = @_;
      $spec{owner} = (caller(1))[3] unless exists $spec{owner};
      $self->remove_handler($phase, %spec);
      $spec{line} ||= join(":", (caller)[1,2]);
      $self->add_handler($phase, $cb, %spec) if $cb;
  }
  
  sub get_my_handler {
      my $self = shift;
      my $phase = shift;
      my $init = pop if @_ % 2;
      my %spec = @_;
      my $conf = $self->{handlers}{$phase};
      unless ($conf) {
          return unless $init;
          require HTTP::Config;
          $conf = $self->{handlers}{$phase} = HTTP::Config->new;
      }
      $spec{owner} = (caller(1))[3] unless exists $spec{owner};
      my @h = $conf->find(%spec);
      if (!@h && $init) {
          if (ref($init) eq "CODE") {
              $init->(\%spec);
          }
          elsif (ref($init) eq "HASH") {
              while (my($k, $v) = each %$init) {
                  $spec{$k} = $v;
              }
          }
          $spec{callback} ||= sub {};
          $spec{line} ||= join(":", (caller)[1,2]);
          $conf->add(\%spec);
          return \%spec;
      }
      return wantarray ? @h : $h[0];
  }
  
  sub remove_handler {
      my($self, $phase, %spec) = @_;
      if ($phase) {
          my $conf = $self->{handlers}{$phase} || return;
          my @h = $conf->remove(%spec);
          delete $self->{handlers}{$phase} if $conf->empty;
          return @h;
      }
  
      return unless $self->{handlers};
      return map $self->remove_handler($_), sort keys %{$self->{handlers}};
  }
  
  sub handlers {
      my($self, $phase, $o) = @_;
      my @h;
      if ($o->{handlers} && $o->{handlers}{$phase}) {
          push(@h, @{$o->{handlers}{$phase}});
      }
      if (my $conf = $self->{handlers}{$phase}) {
          push(@h, $conf->matching($o));
      }
      return @h;
  }
  
  sub run_handlers {
      my($self, $phase, $o) = @_;
      if (defined(wantarray)) {
          for my $h ($self->handlers($phase, $o)) {
              my $ret = $h->{callback}->($o, $self, $h);
              return $ret if $ret;
          }
          return undef;
      }
  
      for my $h ($self->handlers($phase, $o)) {
          $h->{callback}->($o, $self, $h);
      }
  }
  
  
  # deprecated
  sub use_eval   { shift->_elem('use_eval',  @_); }
  sub use_alarm
  {
      Carp::carp("LWP::UserAgent->use_alarm(BOOL) is a no-op")
  	if @_ > 1 && $^W;
      "";
  }
  
  
  sub clone
  {
      my $self = shift;
      my $copy = bless { %$self }, ref $self;  # copy most fields
  
      delete $copy->{handlers};
      delete $copy->{conn_cache};
  
      # copy any plain arrays and hashes; known not to need recursive copy
      for my $k (qw(proxy no_proxy requests_redirectable ssl_opts)) {
          next unless $copy->{$k};
          if (ref($copy->{$k}) eq "ARRAY") {
              $copy->{$k} = [ @{$copy->{$k}} ];
          }
          elsif (ref($copy->{$k}) eq "HASH") {
              $copy->{$k} = { %{$copy->{$k}} };
          }
      }
  
      if ($self->{def_headers}) {
          $copy->{def_headers} = $self->{def_headers}->clone;
      }
  
      # re-enable standard handlers
      $copy->parse_head($self->parse_head);
  
      # no easy way to clone the cookie jar; so let's just remove it for now
      $copy->cookie_jar(undef);
  
      $copy;
  }
  
  
  sub mirror
  {
      my($self, $url, $file) = @_;
  
      my $request = HTTP::Request->new('GET', $url);
  
      # If the file exists, add a cache-related header
      if ( -e $file ) {
          my ($mtime) = ( stat($file) )[9];
          if ($mtime) {
              $request->header( 'If-Modified-Since' => HTTP::Date::time2str($mtime) );
          }
      }
      my $tmpfile = "$file-$$";
  
      my $response = $self->request($request, $tmpfile);
      if ( $response->header('X-Died') ) {
  	die $response->header('X-Died');
      }
  
      # Only fetching a fresh copy of the would be considered success.
      # If the file was not modified, "304" would returned, which 
      # is considered by HTTP::Status to be a "redirect", /not/ "success"
      if ( $response->is_success ) {
          my @stat        = stat($tmpfile) or die "Could not stat tmpfile '$tmpfile': $!";
          my $file_length = $stat[7];
          my ($content_length) = $response->header('Content-length');
  
          if ( defined $content_length and $file_length < $content_length ) {
              unlink($tmpfile);
              die "Transfer truncated: " . "only $file_length out of $content_length bytes received\n";
          }
          elsif ( defined $content_length and $file_length > $content_length ) {
              unlink($tmpfile);
              die "Content-length mismatch: " . "expected $content_length bytes, got $file_length\n";
          }
          # The file was the expected length. 
          else {
              # Replace the stale file with a fresh copy
              if ( -e $file ) {
                  # Some dosish systems fail to rename if the target exists
                  chmod 0777, $file;
                  unlink $file;
              }
              rename( $tmpfile, $file )
                  or die "Cannot rename '$tmpfile' to '$file': $!\n";
  
              # make sure the file has the same last modification time
              if ( my $lm = $response->last_modified ) {
                  utime $lm, $lm, $file;
              }
          }
      }
      # The local copy is fresh enough, so just delete the temp file  
      else {
  	unlink($tmpfile);
      }
      return $response;
  }
  
  
  sub _need_proxy {
      my($req, $ua) = @_;
      return if exists $req->{proxy};
      my $proxy = $ua->{proxy}{$req->uri->scheme} || return;
      if ($ua->{no_proxy}) {
          if (my $host = eval { $req->uri->host }) {
              for my $domain (@{$ua->{no_proxy}}) {
                  if ($host =~ /\Q$domain\E$/) {
                      return;
                  }
              }
          }
      }
      $req->{proxy} = $HTTP::URI_CLASS->new($proxy);
  }
  
  
  sub proxy
  {
      my $self = shift;
      my $key  = shift;
      return map $self->proxy($_, @_), @$key if ref $key;
  
      Carp::croak("'$key' is not a valid URI scheme") unless $key =~ /^$URI::scheme_re\z/;
      my $old = $self->{'proxy'}{$key};
      if (@_) {
          my $url = shift;
          if (defined($url) && length($url)) {
              Carp::croak("Proxy must be specified as absolute URI; '$url' is not") unless $url =~ /^$URI::scheme_re:/;
              Carp::croak("Bad http proxy specification '$url'") if $url =~ /^https?:/ && $url !~ m,^https?://\w,;
          }
          $self->{proxy}{$key} = $url;
          $self->set_my_handler("request_preprepare", \&_need_proxy)
      }
      return $old;
  }
  
  
  sub env_proxy {
      my ($self) = @_;
      require Encode;
      require Encode::Locale;
      my($k,$v);
      while(($k, $v) = each %ENV) {
  	if ($ENV{REQUEST_METHOD}) {
  	    # Need to be careful when called in the CGI environment, as
  	    # the HTTP_PROXY variable is under control of that other guy.
  	    next if $k =~ /^HTTP_/;
  	    $k = "HTTP_PROXY" if $k eq "CGI_HTTP_PROXY";
  	}
  	$k = lc($k);
  	next unless $k =~ /^(.*)_proxy$/;
  	$k = $1;
  	if ($k eq 'no') {
  	    $self->no_proxy(split(/\s*,\s*/, $v));
  	}
  	else {
              # Ignore random _proxy variables, allow only valid schemes
              next unless $k =~ /^$URI::scheme_re\z/;
              # Ignore xxx_proxy variables if xxx isn't a supported protocol
              next unless LWP::Protocol::implementor($k);
  	    $self->proxy($k, Encode::decode(locale => $v));
  	}
      }
  }
  
  
  sub no_proxy {
      my($self, @no) = @_;
      if (@no) {
  	push(@{ $self->{'no_proxy'} }, @no);
      }
      else {
  	$self->{'no_proxy'} = [];
      }
  }
  
  
  sub _new_response {
      my($request, $code, $message, $content) = @_;
      $message ||= HTTP::Status::status_message($code);
      my $response = HTTP::Response->new($code, $message);
      $response->request($request);
      $response->header("Client-Date" => HTTP::Date::time2str(time));
      $response->header("Client-Warning" => "Internal response");
      $response->header("Content-Type" => "text/plain");
      $response->content($content || "$code $message\n");
      return $response;
  }
  
  
  1;
  
  __END__
  
  =head1 NAME
  
  LWP::UserAgent - Web user agent class
  
  =head1 SYNOPSIS
  
   require LWP::UserAgent;
   
   my $ua = LWP::UserAgent->new;
   $ua->timeout(10);
   $ua->env_proxy;
   
   my $response = $ua->get('http://search.cpan.org/');
   
   if ($response->is_success) {
       print $response->decoded_content;  # or whatever
   }
   else {
       die $response->status_line;
   }
  
  =head1 DESCRIPTION
  
  The C<LWP::UserAgent> is a class implementing a web user agent.
  C<LWP::UserAgent> objects can be used to dispatch web requests.
  
  In normal use the application creates an C<LWP::UserAgent> object, and
  then configures it with values for timeouts, proxies, name, etc. It
  then creates an instance of C<HTTP::Request> for the request that
  needs to be performed. This request is then passed to one of the
  request method the UserAgent, which dispatches it using the relevant
  protocol, and returns a C<HTTP::Response> object.  There are
  convenience methods for sending the most common request types: get(),
  head(), post(), put() and delete().  When using these methods then the
  creation of the request object is hidden as shown in the synopsis above.
  
  The basic approach of the library is to use HTTP style communication
  for all protocol schemes.  This means that you will construct
  C<HTTP::Request> objects and receive C<HTTP::Response> objects even
  for non-HTTP resources like I<gopher> and I<ftp>.  In order to achieve
  even more similarity to HTTP style communications, gopher menus and
  file directories are converted to HTML documents.
  
  =head1 CONSTRUCTOR METHODS
  
  The following constructor methods are available:
  
  =over 4
  
  =item $ua = LWP::UserAgent->new( %options )
  
  This method constructs a new C<LWP::UserAgent> object and returns it.
  Key/value pair arguments may be provided to set up the initial state.
  The following options correspond to attribute methods described below:
  
     KEY                     DEFAULT
     -----------             --------------------
     agent                   "libwww-perl/#.###"
     from                    undef
     conn_cache              undef
     cookie_jar              undef
     default_headers         HTTP::Headers->new
     local_address           undef
     ssl_opts		   { verify_hostname => 1 }
     max_size                undef
     max_redirect            7
     parse_head              1
     protocols_allowed       undef
     protocols_forbidden     undef
     requests_redirectable   ['GET', 'HEAD']
     timeout                 180
  
  The following additional options are also accepted: If the C<env_proxy> option
  is passed in with a TRUE value, then proxy settings are read from environment
  variables (see env_proxy() method below).  If C<env_proxy> isn't provided the
  C<PERL_LWP_ENV_PROXY> environment variable controls if env_proxy() is called
  during initialization.  If the C<keep_alive> option is passed in, then a
  C<LWP::ConnCache> is set up (see conn_cache() method below).  The C<keep_alive>
  value is passed on as the C<total_capacity> for the connection cache.
  
  =item $ua->clone
  
  Returns a copy of the LWP::UserAgent object.
  
  =back
  
  =head1 ATTRIBUTES
  
  The settings of the configuration attributes modify the behaviour of the
  C<LWP::UserAgent> when it dispatches requests.  Most of these can also
  be initialized by options passed to the constructor method.
  
  The following attribute methods are provided.  The attribute value is
  left unchanged if no argument is given.  The return value from each
  method is the old attribute value.
  
  =over
  
  =item $ua->agent
  
  =item $ua->agent( $product_id )
  
  Get/set the product token that is used to identify the user agent on
  the network.  The agent value is sent as the "User-Agent" header in
  the requests.  The default is the string returned by the _agent()
  method (see below).
  
  If the $product_id ends with space then the _agent() string is
  appended to it.
  
  The user agent string should be one or more simple product identifiers
  with an optional version number separated by the "/" character.
  Examples are:
  
    $ua->agent('Checkbot/0.4 ' . $ua->_agent);
    $ua->agent('Checkbot/0.4 ');    # same as above
    $ua->agent('Mozilla/5.0');
    $ua->agent("");                 # don't identify
  
  =item $ua->_agent
  
  Returns the default agent identifier.  This is a string of the form
  "libwww-perl/#.###", where "#.###" is substituted with the version number
  of this library.
  
  =item $ua->from
  
  =item $ua->from( $email_address )
  
  Get/set the e-mail address for the human user who controls
  the requesting user agent.  The address should be machine-usable, as
  defined in RFC 822.  The C<from> value is send as the "From" header in
  the requests.  Example:
  
    $ua->from('gaas@cpan.org');
  
  The default is to not send a "From" header.  See the default_headers()
  method for the more general interface that allow any header to be defaulted.
  
  =item $ua->cookie_jar
  
  =item $ua->cookie_jar( $cookie_jar_obj )
  
  Get/set the cookie jar object to use.  The only requirement is that
  the cookie jar object must implement the extract_cookies($request) and
  add_cookie_header($response) methods.  These methods will then be
  invoked by the user agent as requests are sent and responses are
  received.  Normally this will be a C<HTTP::Cookies> object or some
  subclass.
  
  The default is to have no cookie_jar, i.e. never automatically add
  "Cookie" headers to the requests.
  
  Shortcut: If a reference to a plain hash is passed in as the
  $cookie_jar_object, then it is replaced with an instance of
  C<HTTP::Cookies> that is initialized based on the hash.  This form also
  automatically loads the C<HTTP::Cookies> module.  It means that:
  
    $ua->cookie_jar({ file => "$ENV{HOME}/.cookies.txt" });
  
  is really just a shortcut for:
  
    require HTTP::Cookies;
    $ua->cookie_jar(HTTP::Cookies->new(file => "$ENV{HOME}/.cookies.txt"));
  
  =item $ua->default_headers
  
  =item $ua->default_headers( $headers_obj )
  
  Get/set the headers object that will provide default header values for
  any requests sent.  By default this will be an empty C<HTTP::Headers>
  object.
  
  =item $ua->default_header( $field )
  
  =item $ua->default_header( $field => $value )
  
  This is just a short-cut for $ua->default_headers->header( $field =>
  $value ). Example:
  
    $ua->default_header('Accept-Encoding' => scalar HTTP::Message::decodable());
    $ua->default_header('Accept-Language' => "no, en");
  
  =item $ua->conn_cache
  
  =item $ua->conn_cache( $cache_obj )
  
  Get/set the C<LWP::ConnCache> object to use.  See L<LWP::ConnCache>
  for details.
  
  =item $ua->credentials( $netloc, $realm )
  
  =item $ua->credentials( $netloc, $realm, $uname, $pass )
  
  Get/set the user name and password to be used for a realm.
  
  The $netloc is a string of the form "<host>:<port>".  The username and
  password will only be passed to this server.  Example:
  
    $ua->credentials("www.example.com:80", "Some Realm", "foo", "secret");
  
  =item $ua->local_address
  
  =item $ua->local_address( $address )
  
  Get/set the local interface to bind to for network connections.  The interface
  can be specified as a hostname or an IP address.  This value is passed as the
  C<LocalAddr> argument to L<IO::Socket::INET>.
  
  =item $ua->max_size
  
  =item $ua->max_size( $bytes )
  
  Get/set the size limit for response content.  The default is C<undef>,
  which means that there is no limit.  If the returned response content
  is only partial, because the size limit was exceeded, then a
  "Client-Aborted" header will be added to the response.  The content
  might end up longer than C<max_size> as we abort once appending a
  chunk of data makes the length exceed the limit.  The "Content-Length"
  header, if present, will indicate the length of the full content and
  will normally not be the same as C<< length($res->content) >>.
  
  =item $ua->max_redirect
  
  =item $ua->max_redirect( $n )
  
  This reads or sets the object's limit of how many times it will obey
  redirection responses in a given request cycle.
  
  By default, the value is 7. This means that if you call request()
  method and the response is a redirect elsewhere which is in turn a
  redirect, and so on seven times, then LWP gives up after that seventh
  request.
  
  =item $ua->parse_head
  
  =item $ua->parse_head( $boolean )
  
  Get/set a value indicating whether we should initialize response
  headers from the E<lt>head> section of HTML documents. The default is
  TRUE.  Do not turn this off, unless you know what you are doing.
  
  =item $ua->protocols_allowed
  
  =item $ua->protocols_allowed( \@protocols )
  
  This reads (or sets) this user agent's list of protocols that the
  request methods will exclusively allow.  The protocol names are case
  insensitive.
  
  For example: C<$ua-E<gt>protocols_allowed( [ 'http', 'https'] );>
  means that this user agent will I<allow only> those protocols,
  and attempts to use this user agent to access URLs with any other
  schemes (like "ftp://...") will result in a 500 error.
  
  To delete the list, call: C<$ua-E<gt>protocols_allowed(undef)>
  
  By default, an object has neither a C<protocols_allowed> list, nor a
  C<protocols_forbidden> list.
  
  Note that having a C<protocols_allowed> list causes any
  C<protocols_forbidden> list to be ignored.
  
  =item $ua->protocols_forbidden
  
  =item $ua->protocols_forbidden( \@protocols )
  
  This reads (or sets) this user agent's list of protocols that the
  request method will I<not> allow. The protocol names are case
  insensitive.
  
  For example: C<$ua-E<gt>protocols_forbidden( [ 'file', 'mailto'] );>
  means that this user agent will I<not> allow those protocols, and
  attempts to use this user agent to access URLs with those schemes
  will result in a 500 error.
  
  To delete the list, call: C<$ua-E<gt>protocols_forbidden(undef)>
  
  =item $ua->requests_redirectable
  
  =item $ua->requests_redirectable( \@requests )
  
  This reads or sets the object's list of request names that
  C<$ua-E<gt>redirect_ok(...)> will allow redirection for.  By
  default, this is C<['GET', 'HEAD']>, as per RFC 2616.  To
  change to include 'POST', consider:
  
     push @{ $ua->requests_redirectable }, 'POST';
  
  =item $ua->show_progress
  
  =item $ua->show_progress( $boolean )
  
  Get/set a value indicating whether a progress bar should be displayed
  on on the terminal as requests are processed. The default is FALSE.
  
  =item $ua->timeout
  
  =item $ua->timeout( $secs )
  
  Get/set the timeout value in seconds. The default timeout() value is
  180 seconds, i.e. 3 minutes.
  
  The requests is aborted if no activity on the connection to the server
  is observed for C<timeout> seconds.  This means that the time it takes
  for the complete transaction and the request() method to actually
  return might be longer.
  
  =item $ua->ssl_opts
  
  =item $ua->ssl_opts( $key )
  
  =item $ua->ssl_opts( $key => $value )
  
  Get/set the options for SSL connections.  Without argument return the list
  of options keys currently set.  With a single argument return the current
  value for the given option.  With 2 arguments set the option value and return
  the old.  Setting an option to the value C<undef> removes this option.
  
  The options that LWP relates to are:
  
  =over
  
  =item C<verify_hostname> => $bool
  
  When TRUE LWP will for secure protocol schemes ensure it connects to servers
  that have a valid certificate matching the expected hostname.  If FALSE no
  checks are made and you can't be sure that you communicate with the expected peer.
  The no checks behaviour was the default for libwww-perl-5.837 and earlier releases.
  
  This option is initialized from the L<PERL_LWP_SSL_VERIFY_HOSTNAME> environment
  variable.  If this environment variable isn't set; then C<verify_hostname>
  defaults to 1.
  
  =item C<SSL_ca_file> => $path
  
  The path to a file containing Certificate Authority certificates.
  A default setting for this option is provided by checking the environment
  variables C<PERL_LWP_SSL_CA_FILE> and C<HTTPS_CA_FILE> in order.
  
  =item C<SSL_ca_path> => $path
  
  The path to a directory containing files containing Certificate Authority
  certificates.
  A default setting for this option is provided by checking the environment
  variables C<PERL_LWP_SSL_CA_PATH> and C<HTTPS_CA_DIR> in order.
  
  =back
  
  Other options can be set and are processed directly by the SSL Socket implementation
  in use.  See L<IO::Socket::SSL> or L<Net::SSL> for details.
  
  The libwww-perl core no longer bundles protocol plugins for SSL.  You will need
  to install L<LWP::Protocol::https> separately to enable support for processing
  https-URLs.
  
  =back
  
  =head2 Proxy attributes
  
  The following methods set up when requests should be passed via a
  proxy server.
  
  =over
  
  =item $ua->proxy(\@schemes, $proxy_url)
  
  =item $ua->proxy($scheme, $proxy_url)
  
  Set/retrieve proxy URL for a scheme:
  
   $ua->proxy(['http', 'ftp'], 'http://proxy.sn.no:8001/');
   $ua->proxy('gopher', 'http://proxy.sn.no:8001/');
  
  The first form specifies that the URL is to be used for proxying of
  access methods listed in the list in the first method argument,
  i.e. 'http' and 'ftp'.
  
  The second form shows a shorthand form for specifying
  proxy URL for a single access scheme.
  
  =item $ua->no_proxy( $domain, ... )
  
  Do not proxy requests to the given domains.  Calling no_proxy without
  any domains clears the list of domains. Eg:
  
   $ua->no_proxy('localhost', 'example.com');
  
  =item $ua->env_proxy
  
  Load proxy settings from *_proxy environment variables.  You might
  specify proxies like this (sh-syntax):
  
    gopher_proxy=http://proxy.my.place/
    wais_proxy=http://proxy.my.place/
    no_proxy="localhost,example.com"
    export gopher_proxy wais_proxy no_proxy
  
  csh or tcsh users should use the C<setenv> command to define these
  environment variables.
  
  On systems with case insensitive environment variables there exists a
  name clash between the CGI environment variables and the C<HTTP_PROXY>
  environment variable normally picked up by env_proxy().  Because of
  this C<HTTP_PROXY> is not honored for CGI scripts.  The
  C<CGI_HTTP_PROXY> environment variable can be used instead.
  
  =back
  
  =head2 Handlers
  
  Handlers are code that injected at various phases during the
  processing of requests.  The following methods are provided to manage
  the active handlers:
  
  =over
  
  =item $ua->add_handler( $phase => \&cb, %matchspec )
  
  Add handler to be invoked in the given processing phase.  For how to
  specify %matchspec see L<HTTP::Config/"Matching">.
  
  The possible values $phase and the corresponding callback signatures are:
  
  =over
  
  =item request_preprepare => sub { my($request, $ua, $h) = @_; ... }
  
  The handler is called before the C<request_prepare> and other standard
  initialization of of the request.  This can be used to set up headers
  and attributes that the C<request_prepare> handler depends on.  Proxy
  initialization should take place here; but in general don't register
  handlers for this phase.
  
  =item request_prepare => sub { my($request, $ua, $h) = @_; ... }
  
  The handler is called before the request is sent and can modify the
  request any way it see fit.  This can for instance be used to add
  certain headers to specific requests.
  
  The method can assign a new request object to $_[0] to replace the
  request that is sent fully.
  
  The return value from the callback is ignored.  If an exception is
  raised it will abort the request and make the request method return a
  "400 Bad request" response.
  
  =item request_send => sub { my($request, $ua, $h) = @_; ... }
  
  This handler gets a chance of handling requests before they're sent to the
  protocol handlers.  It should return an HTTP::Response object if it
  wishes to terminate the processing; otherwise it should return nothing.
  
  The C<response_header> and C<response_data> handlers will not be
  invoked for this response, but the C<response_done> will be.
  
  =item response_header => sub { my($response, $ua, $h) = @_; ... }
  
  This handler is called right after the response headers have been
  received, but before any content data.  The handler might set up
  handlers for data and might croak to abort the request.
  
  The handler might set the $response->{default_add_content} value to
  control if any received data should be added to the response object
  directly.  This will initially be false if the $ua->request() method
  was called with a $content_file or $content_cb argument; otherwise true.
  
  =item response_data => sub { my($response, $ua, $h, $data) = @_; ... }
  
  This handler is called for each chunk of data received for the
  response.  The handler might croak to abort the request.
  
  This handler needs to return a TRUE value to be called again for
  subsequent chunks for the same request.
  
  =item response_done => sub { my($response, $ua, $h) = @_; ... }
  
  The handler is called after the response has been fully received, but
  before any redirect handling is attempted.  The handler can be used to
  extract information or modify the response.
  
  =item response_redirect => sub { my($response, $ua, $h) = @_; ... }
  
  The handler is called in $ua->request after C<response_done>.  If the
  handler returns an HTTP::Request object we'll start over with processing
  this request instead.
  
  =back
  
  =item $ua->remove_handler( undef, %matchspec )
  
  =item $ua->remove_handler( $phase, %matchspec )
  
  Remove handlers that match the given %matchspec.  If $phase is not
  provided remove handlers from all phases.
  
  Be careful as calling this function with %matchspec that is not not
  specific enough can remove handlers not owned by you.  It's probably
  better to use the set_my_handler() method instead.
  
  The removed handlers are returned.
  
  =item $ua->set_my_handler( $phase, $cb, %matchspec )
  
  Set handlers private to the executing subroutine.  Works by defaulting
  an C<owner> field to the %matchspec that holds the name of the called
  subroutine.  You might pass an explicit C<owner> to override this.
  
  If $cb is passed as C<undef>, remove the handler.
  
  =item $ua->get_my_handler( $phase, %matchspec )
  
  =item $ua->get_my_handler( $phase, %matchspec, $init )
  
  Will retrieve the matching handler as hash ref.
  
  If C<$init> is passed passed as a TRUE value, create and add the
  handler if it's not found.  If $init is a subroutine reference, then
  it's called with the created handler hash as argument.  This sub might
  populate the hash with extra fields; especially the callback.  If
  $init is a hash reference, merge the hashes.
  
  =item $ua->handlers( $phase, $request )
  
  =item $ua->handlers( $phase, $response )
  
  Returns the handlers that apply to the given request or response at
  the given processing phase.
  
  =back
  
  =head1 REQUEST METHODS
  
  The methods described in this section are used to dispatch requests
  via the user agent.  The following request methods are provided:
  
  =over
  
  =item $ua->get( $url )
  
  =item $ua->get( $url , $field_name => $value, ... )
  
  This method will dispatch a C<GET> request on the given $url.  Further
  arguments can be given to initialize the headers of the request. These
  are given as separate name/value pairs.  The return value is a
  response object.  See L<HTTP::Response> for a description of the
  interface it provides.
  
  There will still be a response object returned when LWP can't connect to the
  server specified in the URL or when other failures in protocol handlers occur.
  These internal responses use the standard HTTP status codes, so the responses
  can't be differentiated by testing the response status code alone.  Error
  responses that LWP generates internally will have the "Client-Warning" header
  set to the value "Internal response".  If you need to differentiate these
  internal responses from responses that a remote server actually generates, you
  need to test this header value.
  
  Fields names that start with ":" are special.  These will not
  initialize headers of the request but will determine how the response
  content is treated.  The following special field names are recognized:
  
      :content_file   => $filename
      :content_cb     => \&callback
      :read_size_hint => $bytes
  
  If a $filename is provided with the C<:content_file> option, then the
  response content will be saved here instead of in the response
  object.  If a callback is provided with the C<:content_cb> option then
  this function will be called for each chunk of the response content as
  it is received from the server.  If neither of these options are
  given, then the response content will accumulate in the response
  object itself.  This might not be suitable for very large response
  bodies.  Only one of C<:content_file> or C<:content_cb> can be
  specified.  The content of unsuccessful responses will always
  accumulate in the response object itself, regardless of the
  C<:content_file> or C<:content_cb> options passed in.
  
  The C<:read_size_hint> option is passed to the protocol module which
  will try to read data from the server in chunks of this size.  A
  smaller value for the C<:read_size_hint> will result in a higher
  number of callback invocations.
  
  The callback function is called with 3 arguments: a chunk of data, a
  reference to the response object, and a reference to the protocol
  object.  The callback can abort the request by invoking die().  The
  exception message will show up as the "X-Died" header field in the
  response returned by the get() function.
  
  =item $ua->head( $url )
  
  =item $ua->head( $url , $field_name => $value, ... )
  
  This method will dispatch a C<HEAD> request on the given $url.
  Otherwise it works like the get() method described above.
  
  =item $ua->post( $url, \%form )
  
  =item $ua->post( $url, \@form )
  
  =item $ua->post( $url, \%form, $field_name => $value, ... )
  
  =item $ua->post( $url, $field_name => $value,... Content => \%form )
  
  =item $ua->post( $url, $field_name => $value,... Content => \@form )
  
  =item $ua->post( $url, $field_name => $value,... Content => $content )
  
  This method will dispatch a C<POST> request on the given $url, with
  %form or @form providing the key/value pairs for the fill-in form
  content. Additional headers and content options are the same as for
  the get() method.
  
  This method will use the POST() function from C<HTTP::Request::Common>
  to build the request.  See L<HTTP::Request::Common> for a details on
  how to pass form content and other advanced features.
  
  =item $ua->put( $url, \%form )
  
  =item $ua->put( $url, \@form )
  
  =item $ua->put( $url, \%form, $field_name => $value, ... )
  
  =item $ua->put( $url, $field_name => $value,... Content => \%form )
  
  =item $ua->put( $url, $field_name => $value,... Content => \@form )
  
  =item $ua->put( $url, $field_name => $value,... Content => $content )
  
  This method will dispatch a C<PUT> request on the given $url, with
  %form or @form providing the key/value pairs for the fill-in form
  content. Additional headers and content options are the same as for
  the get() method.
  
  This method will use the PUT() function from C<HTTP::Request::Common>
  to build the request.  See L<HTTP::Request::Common> for a details on
  how to pass form content and other advanced features.
  
  =item $ua->delete( $url )
  
  =item $ua->delete( $url, $field_name => $value, ... )
  
  This method will dispatch a C<DELETE> request on the given $url.  Additional
  headers and content options are the same as for the get() method.
  
  This method will use the DELETE() function from C<HTTP::Request::Common>
  to build the request.  See L<HTTP::Request::Common> for a details on
  how to pass form content and other advanced features.
  
  =item $ua->mirror( $url, $filename )
  
  This method will get the document identified by $url and store it in
  file called $filename.  If the file already exists, then the request
  will contain an "If-Modified-Since" header matching the modification
  time of the file.  If the document on the server has not changed since
  this time, then nothing happens.  If the document has been updated, it
  will be downloaded again.  The modification time of the file will be
  forced to match that of the server.
  
  The return value is the the response object.
  
  =item $ua->request( $request )
  
  =item $ua->request( $request, $content_file )
  
  =item $ua->request( $request, $content_cb )
  
  =item $ua->request( $request, $content_cb, $read_size_hint )
  
  This method will dispatch the given $request object.  Normally this
  will be an instance of the C<HTTP::Request> class, but any object with
  a similar interface will do.  The return value is a response object.
  See L<HTTP::Request> and L<HTTP::Response> for a description of the
  interface provided by these classes.
  
  The request() method will process redirects and authentication
  responses transparently.  This means that it may actually send several
  simple requests via the simple_request() method described below.
  
  The request methods described above; get(), head(), post() and
  mirror(), will all dispatch the request they build via this method.
  They are convenience methods that simply hides the creation of the
  request object for you.
  
  The $content_file, $content_cb and $read_size_hint all correspond to
  options described with the get() method above.
  
  You are allowed to use a CODE reference as C<content> in the request
  object passed in.  The C<content> function should return the content
  when called.  The content can be returned in chunks.  The content
  function will be invoked repeatedly until it return an empty string to
  signal that there is no more content.
  
  =item $ua->simple_request( $request )
  
  =item $ua->simple_request( $request, $content_file )
  
  =item $ua->simple_request( $request, $content_cb )
  
  =item $ua->simple_request( $request, $content_cb, $read_size_hint )
  
  This method dispatches a single request and returns the response
  received.  Arguments are the same as for request() described above.
  
  The difference from request() is that simple_request() will not try to
  handle redirects or authentication responses.  The request() method
  will in fact invoke this method for each simple request it sends.
  
  =item $ua->is_online
  
  Tries to determine if you have access to the Internet.  Returns
  TRUE if the built-in heuristics determine that the user agent is
  able to access the Internet (over HTTP).  See also L<LWP::Online>.
  
  =item $ua->is_protocol_supported( $scheme )
  
  You can use this method to test whether this user agent object supports the
  specified C<scheme>.  (The C<scheme> might be a string (like 'http' or
  'ftp') or it might be an URI object reference.)
  
  Whether a scheme is supported, is determined by the user agent's
  C<protocols_allowed> or C<protocols_forbidden> lists (if any), and by
  the capabilities of LWP.  I.e., this will return TRUE only if LWP
  supports this protocol I<and> it's permitted for this particular
  object.
  
  =back
  
  =head2 Callback methods
  
  The following methods will be invoked as requests are processed. These
  methods are documented here because subclasses of C<LWP::UserAgent>
  might want to override their behaviour.
  
  =over
  
  =item $ua->prepare_request( $request )
  
  This method is invoked by simple_request().  Its task is to modify the
  given $request object by setting up various headers based on the
  attributes of the user agent. The return value should normally be the
  $request object passed in.  If a different request object is returned
  it will be the one actually processed.
  
  The headers affected by the base implementation are; "User-Agent",
  "From", "Range" and "Cookie".
  
  =item $ua->redirect_ok( $prospective_request, $response )
  
  This method is called by request() before it tries to follow a
  redirection to the request in $response.  This should return a TRUE
  value if this redirection is permissible.  The $prospective_request
  will be the request to be sent if this method returns TRUE.
  
  The base implementation will return FALSE unless the method
  is in the object's C<requests_redirectable> list,
  FALSE if the proposed redirection is to a "file://..."
  URL, and TRUE otherwise.
  
  =item $ua->get_basic_credentials( $realm, $uri, $isproxy )
  
  This is called by request() to retrieve credentials for documents
  protected by Basic or Digest Authentication.  The arguments passed in
  is the $realm provided by the server, the $uri requested and a boolean
  flag to indicate if this is authentication against a proxy server.
  
  The method should return a username and password.  It should return an
  empty list to abort the authentication resolution attempt.  Subclasses
  can override this method to prompt the user for the information. An
  example of this can be found in C<lwp-request> program distributed
  with this library.
  
  The base implementation simply checks a set of pre-stored member
  variables, set up with the credentials() method.
  
  =item $ua->progress( $status, $request_or_response )
  
  This is called frequently as the response is received regardless of
  how the content is processed.  The method is called with $status
  "begin" at the start of processing the request and with $state "end"
  before the request method returns.  In between these $status will be
  the fraction of the response currently received or the string "tick"
  if the fraction can't be calculated.
  
  When $status is "begin" the second argument is the request object,
  otherwise it is the response object.
  
  =back
  
  =head1 SEE ALSO
  
  See L<LWP> for a complete overview of libwww-perl5.  See L<lwpcook>
  and the scripts F<lwp-request> and F<lwp-download> for examples of
  usage.
  
  See L<HTTP::Request> and L<HTTP::Response> for a description of the
  message objects dispatched and received.  See L<HTTP::Request::Common>
  and L<HTML::Form> for other ways to build request objects.
  
  See L<WWW::Mechanize> and L<WWW::Search> for examples of more
  specialized user agents based on C<LWP::UserAgent>.
  
  =head1 COPYRIGHT
  
  Copyright 1995-2009 Gisle Aas.
  
  This library is free software; you can redistribute it and/or
  modify it under the same terms as Perl itself.
LWP_USERAGENT

$fatpacked{"Net/OAuth.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'NET_OAUTH';
  package Net::OAuth;
  use warnings;
  use strict;
  use Carp;
  
  sub PROTOCOL_VERSION_1_0() {1}
  sub PROTOCOL_VERSION_1_0A() {1.001}
  
  sub OAUTH_VERSION() {'1.0'}
  
  our $VERSION = '0.28';
  our $SKIP_UTF8_DOUBLE_ENCODE_CHECK = 0;
  our $PROTOCOL_VERSION = PROTOCOL_VERSION_1_0;
  
  sub request {
      my $self = shift;
      my $what = shift;
      return $self->message($what . ' Request');
  }
  
  sub response {
      my $self = shift;
      my $what = shift;
      return $self->message($what . ' Response');
  }
  
  sub message {
      my $self = shift;
      my $base_class = ref $self || $self;
      my $type = camel(shift);
      my $class = $base_class . '::' . $type;
      smart_require($class, 1);
      return $class;
  }
  
  sub camel {
      my @words;
      foreach (@_) {
          while (/([A-Za-z0-9]+)/g) {
              (my $word = $1) =~ s/authentication/auth/i;
              push @words, $word;
          }
      }
      my $name = join('', map("\u$_", @words));
  }
  
  our %ALREADY_REQUIRED = (); # class_name => rv of ->require
  
  sub smart_require {
      my $required_class = shift;
      my $croak_on_error = shift || 0;
      unless (exists $ALREADY_REQUIRED{$required_class}) {
          $ALREADY_REQUIRED{$required_class} = eval "require $required_class";
          croak $@ if $@ and $croak_on_error;
      }
      return $ALREADY_REQUIRED{$required_class};
  }
  
  =head1 NAME
  
  Net::OAuth - OAuth 1.0 for Perl
  
  =head1 SYNOPSIS
  
    # Web Server Example (Dancer)
  
    # This example is simplified for illustrative purposes, see the complete code in /demo
  
    # Note that client_id is the Consumer Key and client_secret is the Consumer Secret
  
    use Dancer;
    use Net::OAuth::Client;
  
    sub client {
    	Net::OAuth::Client->new(
    		config->{client_id},
    		config->{client_secret},
    		site => 'https://www.google.com/',
    		request_token_path => '/accounts/OAuthGetRequestToken?scope=https%3A%2F%2Fwww.google.com%2Fm8%2Ffeeds%2F',
    		authorize_path => '/accounts/OAuthAuthorizeToken',
    		access_token_path => '/accounts/OAuthGetAccessToken',
    		callback => uri_for("/auth/google/callback"),
    		session => \&session,
    	);
    }
  
    # Send user to authorize with service provider
    get '/auth/google' => sub {
    	redirect client->authorize_url;
    };
  
    # User has returned with token and verifier appended to the URL.
    get '/auth/google/callback' => sub {
  
    	# Use the auth code to fetch the access token
    	my $access_token =  client->get_access_token(params->{oauth_token}, params->{oauth_verifier});
  
    	# Use the access token to fetch a protected resource
    	my $response = $access_token->get('/m8/feeds/contacts/default/full');
  
    	# Do something with said resource...
  
    	if ($response->is_success) {
    	  return "Yay, it worked: " . $response->decoded_content;
    	}
    	else {
    	  return "Error: " . $response->status_line;
    	}
    };
  
    dance;
  
  =head1 IMPORTANT
  
  Net::OAuth provides a low-level API for reading and writing OAuth messages.
  
  You probably should start with L<Net::OAuth::Client>.
  
  =head1 ABSTRACT
  
  OAuth is 
  
  "An open protocol to allow secure API authentication in a simple and standard method from desktop and web applications."
  
  In practical terms, OAuth is a mechanism for a Consumer to request protected resources from a Service Provider on behalf of a user.
  
  Please refer to the OAuth spec: L<http://oauth.net/documentation/spec>
  
  Net::OAuth provides:
  
  =over
  
  =item * classes that encapsulate OAuth messages (requests and responses).  
  
  =item * message signing
  
  =item * message serialization and parsing.
  
  =item * 2-legged requests (aka. tokenless requests, aka. consumer requests), see L</"CONSUMER REQUESTS"> 
  
  =back
  
  Net::OAuth does not provide:
  
  =over
  
  =item * Consumer or Service Provider encapsulation  
  
  =item * token/nonce/key storage/management
  
  =back
  
  =head1 DESCRIPTION
  
  =head2 OAUTH MESSAGES
  
  An OAuth message is a set of key-value pairs.  The following message types are supported:
  
  Requests
  
  =over
  
  =item * Request Token (Net::OAuth::RequestTokenRequest)
  
  =item * Access Token (Net::OAuth::AccessTokenRequest)
  
  =item * User Authentication (Net::OAuth::UserAuthRequest)
  
  =item * Protected Resource (Net::OAuth::ProtectedResourceRequest)
  
  =item * Consumer Request (Net::OAuth::ConsumerRequest) (2-legged / token-less request)
  
  =back
  
  Responses
  
  =over
  
  =item * Request Token (Net::OAuth::RequestTokenResponse)
  
  =item * Access Token (Net::OAuth:AccessTokenResponse)
  
  =item * User Authentication (Net::OAuth::UserAuthResponse)
  
  =back
  
  Each OAuth message type has one or more required parameters, zero or more optional parameters, and most allow arbitrary parameters.
  
  All OAuth requests must be signed by the Consumer.  Responses from the Service Provider, however, are not signed.
  
  To create a message, the easiest way is to use the factory methods (Net::OAuth->request, Net::OAuth->response, Net::OAuth->message).  The following method invocations are all equivalent:
  
   $request = Net::OAuth->request('user authentication')->new(%params);
   $request = Net::OAuth->request('user_auth')->new(%params);
   $request = Net::OAuth->request('UserAuth')->new(%params);
   $request = Net::OAuth->message('UserAuthRequest')->new(%params);
  
  The more verbose way is to use the class directly:
  
   use Net::OAuth::UserAuthRequest; 
   $request = Net::OAuth::UserAuthRequest->new(%params);
  
  You can also create a message by deserializing it from a Authorization header, URL, query hash, or POST body
  
   $request = Net::OAuth->request('protected resource')->from_authorization_header($ENV{HTTP_AUTHORIZATION}, %api_params);
   $request = Net::OAuth->request('protected resource')->from_url($url, %api_params);
   $request = Net::OAuth->request('protected resource')->from_hash({$q->Vars}, %api_params); # CGI
   $request = Net::OAuth->request('protected resource')->from_hash($c->request->params, %api_params); # Catalyst
   $response = Net::OAuth->response('request token')->from_post_body($response_content, %api_params);
  
  Note that the deserialization methods (as opposed to new()) expect OAuth protocol parameters to be prefixed with 'oauth_', as you would expect in a valid OAuth message.
  
  Before sending a request, the Consumer must first sign it:
  
   $request->sign;
  
  When receiving a request, the Service Provider should first verify the signature:
  
   die "Signature verification failed" unless $request->verify;
  
  When sending a message the last step is to serialize it and send it to wherever it needs to go.  The following serialization methods are available:
  
   $response->to_post_body # a application/x-www-form-urlencoded POST body
  
   $request->to_url # the query string of a URL
  
   $request->to_authorization_header # the value of an HTTP Authorization header
  
   $request->to_hash # a hash that could be used for some other serialization
  
  =head2 API PARAMETERS vs MESSAGE PARAMETERS
  
  Net::OAuth defines 'message parameters' as parameters that are part of the transmitted OAuth message.  These include any protocol parameter (prefixed with 'oauth_' in the message), and any additional message parameters (the extra_params hash).
  
  'API parameters' are parameters required to build a message object that are not transmitted with the message, e.g. consumer_secret, token_secret, request_url, request_method.
  
  There are various methods to inspect a message class to see what parameters are defined:
  
   $request->required_message_params;
   $request->optional_message_params;
   $request->all_message_params;
   $request->required_api_params;
   $request->optional_api_params;
   $request->all_api_params;
   $request->all_params;
  
  E.g.
  
   use Net::OAuth;
   use Data::Dumper;
   print Dumper(Net::OAuth->request("protected resource")->required_message_params);
  
   $VAR1 = [
            'consumer_key',
            'signature_method',
            'timestamp',
            'nonce',
            'token'
          ];
  
  =head2 ACCESSING PARAMETERS
  
  All parameters can be get/set using accessor methods. E.g.
  
   my $consumer_key = $request->consumer_key;
   $request->request_method('POST');
  
  =head2 THE REQUEST_URL PARAMETER
  
  Any query parameters in the request_url are removed and added to the extra_params hash when generating the signature.
  
  E.g. the following requests are pretty much equivalent:
  
   my $request = Net::OAuth->request('Request Token')->new(
    %params,
    request_url => 'https://photos.example.net/request_token',
    extra_params => {
     foo => 'bar'
    },
  );
  
   my $request = Net::OAuth->request('Request Token')->new(
    %params,
    request_url => 'https://photos.example.net/request_token?foo=bar',
   );
  
  Calling $request->request_url will still return whatever you set it to originally. If you want to get the request_url with the query parameters removed, you can do:
  
      my $url = $request->normalized_request_url;
  
  =head2 SIGNATURE METHODS
  
  The following signature methods are supported:
  
  =over
  
  =item * PLAINTEXT
  
  =item * HMAC-SHA1
  
  =item * HMAC-SHA256
  
  =item * RSA-SHA1
  
  =back
  
  The signature method is determined by the value of the signature_method parameter that is passed to the message constructor.
  
  If an unknown signature method is specified, the signing/verification will throw an exception.
  
  =head3 PLAINTEXT SIGNATURES
  
  This method is a trivial signature which adds no security.  Not recommended.
  
  =head3 HMAC-SHA1 SIGNATURES
  
  This method is available if you have Digest::HMAC_SHA1 installed.  This is by far the most commonly used method.
  
  =head3 HMAC-SHA256 SIGNATURES
  
  This method is available if you have Digest::SHA installed.
  
  =head3 RSA-SHA1 SIGNATURES
  
  To use RSA-SHA1 signatures, pass in a Crypt::OpenSSL::RSA object (or any object that can do $o->sign($str) and/or $o->verify($str, $sig))
  
  E.g.
  
  Consumer:
  
   use Crypt::OpenSSL::RSA;
   use File::Slurp;
   $keystring = read_file('private_key.pem');
   $private_key = Crypt::OpenSSL::RSA->new_private_key($keystring);
   $request = Net::OAuth->request('request token')->new(%params);
   $request->sign($private_key);
   
  Service Provider:
  
   use Crypt::OpenSSL::RSA;
   use File::Slurp;
   $keystring = read_file('public_key.pem');
   $public_key = Crypt::OpenSSL::RSA->new_public_key($keystring);
   $request = Net::OAuth->request('request token')->new(%params);
   if (!$request->verify($public_key)) {
   	die "Signature verification failed";
   }
  
  Note that you can pass the key in as a parameter called 'signature_key' to the message constructor, rather than passing it to the sign/verify method, if you like.
  
  =head2 CONSUMER REQUESTS
  
  To send a request without including a token, use a Consumer Request:
  
      my $request = Net::OAuth->request('consumer')->new(
              consumer_key => 'dpf43f3p2l4k3l03',
              consumer_secret => 'kd94hf93k423kf44',
              request_url => 'http://provider.example.net/profile',
              request_method => 'GET',
              signature_method => 'HMAC-SHA1',
              timestamp => '1191242096',
              nonce => 'kllo9940pd9333jh',
      );
  
      $request->sign;
  
  See L<Net::OAuth::ConsumerRequest>
  
  =head2 I18N
  
  Per the OAuth spec, when making the signature Net::OAuth first encodes parameters to UTF-8. This means that any parameters you pass to Net::OAuth, if they might be outside of ASCII character set, should be run through Encode::decode() (or an equivalent PerlIO layer) first to decode them to Perl's internal character sructure.
  
  =head2 OAUTH 1.0A
  
  Background:
  
  L<http://mojodna.net/2009/05/20/an-idiots-guide-to-oauth-10a.html>
  
  L<http://oauth.googlecode.com/svn/spec/core/1.0a/drafts/3/oauth-core-1_0a.html>
  
  Net::OAuth defaults to OAuth 1.0 spec compliance, and supports OAuth 1.0 Rev A with an optional switch:
  
   use Net::OAuth
   $Net::OAuth::PROTOCOL_VERSION = Net::OAuth::PROTOCOL_VERSION_1_0A;
  
  It is recommended that any new projects use this switch if possible, and existing projects move to supporting this switch as soon as possible.  Probably the easiest way for existing projects to do this is to turn on the switch and run your test suite.  The Net::OAuth constructor will throw an exception where the new protocol parameters (callback, callback_confirmed, verifier) are missing.
  
  Internally, the Net::OAuth::Message constructor checks $Net::OAuth::PROTOCOL_VERSION and attempts to load the equivalent subclass in the Net::OAuth::V1_0A:: namespace.  So if you instantiate a Net::OAuth::RequestTokenRequest object, you will end up with a Net::OAuth::V1_0A::RequestTokenRequest (a subclass of Net::OAuth::RequestTokenRequest) if the protocol version is set to PROTOCOL_VERSION_1_0A.  You can also select a 1.0a subclass on a per-message basis by passing 
      
      protocol_version => Net::OAuth::PROTOCOL_VERSION_1_0A
  
  in the API parameters hash.
  
  If you are not sure whether the entity you are communicating with is 1.0A compliant, you can try instantiating a 1.0A message first and then fall back to 1.0 if that fails:
  
      use Net::OAuth
      $Net::OAuth::PROTOCOL_VERSION = Net::OAuth::PROTOCOL_VERSION_1_0A;
      my $is_oauth_1_0 = 0;
      my $response = eval{Net::OAuth->response('request token')->from_post_body($res->content)};
      if ($@) {
          if ($@ =~ /Missing required parameter 'callback_confirmed'/) {
              # fall back to OAuth 1.0
              $response = Net::OAuth->response('request token')->from_post_body(
                  $res->content, 
                  protocol_version => Net::OAuth::PROTOCOL_VERSION_1_0
              );
              $is_oauth_1_0 = 1; # from now on treat the server as OAuth 1.0 compliant
          }
          else {
              die $@;
          }
      }
  
  At some point in the future, Net::OAuth will default to Net::OAuth::PROTOCOL_VERSION_1_0A.
  
  =head1 DEMO
  
  There is a demo Consumer CGI in this package, also available online at L<http://oauth.kg23.com/>
  
  =head1 SEE ALSO
  
  L<http://oauth.net>
  
  Check out L<Net::OAuth::Simple> - it has a simpler API that may be more to your liking
  
  Check out L<Net::Twitter::OAuth> for a Twitter-specific OAuth API
  
  Check out L<WWW::Netflix::API> for a Netflix-specific OAuth API
  
  =head1 TODO
  
  =over
  
  =item * Support for repeating/multivalued parameters
  
  =item * Add convenience methods for SPs
  
  Something like:
      
      # direct from CGI.pm object
      $request = Net::OAuth->request('Request Token')->from_cgi_query($cgi, %api_params);
      
      # direct from Catalyst::Request object
      $request = Net::OAuth->request('Request Token')->from_catalyst_request($c->req, %api_params); 
      
      # from Auth header and GET and POST params in one
      local $/;
      my $post_body = <STDIN>;
      $request = Net::OAuth->request('Request Token')->from_auth_get_and_post(
          $ENV{HTTP_AUTHORIZATION}, 
          $ENV{QUERY_STRING},
          $post_body,
          %api_params
      );
  
  =back
  
  =head1 AUTHOR
  
  Keith Grennan, C<< <kgrennan at cpan.org> >>
  
  =head1 COPYRIGHT & LICENSE
  
  Copyright 2009 Keith Grennan, all rights reserved.
  
  This program is free software; you can redistribute it and/or modify it
  under the same terms as Perl itself.
  
  =cut
  
  1;
NET_OAUTH

$fatpacked{"Net/OAuth/AccessToken.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'NET_OAUTH_ACCESSTOKEN';
  package Net::OAuth::AccessToken;
  use warnings;
  use strict;
  use base qw(Class::Accessor::Fast);
  __PACKAGE__->mk_accessors(qw/client token token_secret session_handle expires_in authorization_expires_in/);
  
  sub new {
    my $class = shift;
    my %opts = @_;
    my $self = bless \%opts, $class;
    return $self;
  }
  
  sub request {
    my $self = shift;
    my ($method, $uri, $header, $content, %params) = @_;
    my $oauth_req = $self->client->_make_request(
      'protected resource', 
      request_method => $method,
      request_url => $self->client->site_url($uri),
      token => $self->token,
      token_secret => $self->token_secret,
      %params,
    );
    $oauth_req->sign;
  
    return $self->client->request(HTTP::Request->new(
      $method => $oauth_req->to_url, $header, $content
    ));
  }
  
  sub get {
  	return shift->request('GET', @_);
  }
  
  sub post {
  	return shift->request('POST', @_);
  }
  
  sub delete {
  	return shift->request('DELETE', @_);
  }
  
  sub put {
  	return shift->request('PUT', @_);
  }
  
  =head1 NAME
  
  Net::OAuth::AccessToken - OAuth Access Token
  
  =head1 DESCRIPTION
  
  WARNING: Net::OAuth::AccessToken is alpha code.  The rest of Net::OAuth is quite
  stable but this particular module is new, and is under-documented and under-tested.
  
  =head1 SEE ALSO
  
  L<Net::OAuth>
  
  =head1 LICENSE AND COPYRIGHT
  
  Copyright 2011 Keith Grennan.
  
  This program is free software; you can redistribute it and/or modify it
  under the terms of either: the GNU General Public License as published
  by the Free Software Foundation; or the Artistic License.
  
  See http://dev.perl.org/licenses/ for more information.
  
  =cut
  
  
  1;
NET_OAUTH_ACCESSTOKEN

$fatpacked{"Net/OAuth/AccessTokenRequest.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'NET_OAUTH_ACCESSTOKENREQUEST';
  package Net::OAuth::AccessTokenRequest;
  use warnings;
  use strict;
  use base 'Net::OAuth::Request';
  
  __PACKAGE__->add_required_message_params(qw/token/);
  __PACKAGE__->add_required_api_params(qw/token_secret/);
  sub allow_extra_params {0}
  sub sign_message {1}
  
  =head1 NAME
  
  Net::OAuth::AccessTokenRequest - An OAuth protocol request for an Access Token
  
  =head1 SEE ALSO
  
  L<Net::OAuth>, L<http://oauth.net>
  
  =head1 AUTHOR
  
  Keith Grennan, C<< <kgrennan at cpan.org> >>
  
  =head1 COPYRIGHT & LICENSE
  
  Copyright 2007 Keith Grennan, all rights reserved.
  
  This program is free software; you can redistribute it and/or modify it
  under the same terms as Perl itself.
  
  =cut
  
  1;
NET_OAUTH_ACCESSTOKENREQUEST

$fatpacked{"Net/OAuth/AccessTokenResponse.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'NET_OAUTH_ACCESSTOKENRESPONSE';
  package Net::OAuth::AccessTokenResponse;
  use warnings;
  use strict;
  use base 'Net::OAuth::Response';
  
  __PACKAGE__->add_required_message_params(qw/token_secret/);
  sub allow_extra_params {1}
  
  =head1 NAME
  
  Net::OAuth::AccessTokenResponse - An OAuth protocol response for an Access Token
  
  =head1 SEE ALSO
  
  L<Net::OAuth>, L<http://oauth.net>
  
  =head1 AUTHOR
  
  Keith Grennan, C<< <kgrennan at cpan.org> >>
  
  =head1 COPYRIGHT & LICENSE
  
  Copyright 2007 Keith Grennan, all rights reserved.
  
  This program is free software; you can redistribute it and/or modify it
  under the same terms as Perl itself.
  
  =cut
  
  1;
NET_OAUTH_ACCESSTOKENRESPONSE

$fatpacked{"Net/OAuth/Client.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'NET_OAUTH_CLIENT';
  package Net::OAuth::Client;
  use warnings;
  use strict;
  use base qw(Class::Accessor::Fast);
  __PACKAGE__->mk_accessors(qw/id secret callback is_v1a user_agent site debug session/);
  use LWP::UserAgent;
  use URI;
  use Net::OAuth;
  use Net::OAuth::Message;
  use Net::OAuth::AccessToken;
  use Carp;
  
  =head1 NAME
  
  Net::OAuth::Client - OAuth 1.0A Client
  
  =head1 SYNOPSIS
  
    # Web Server Example (Dancer)
  
    # This example is simplified for illustrative purposes, see the complete code in /demo
  
    # Note that client_id is the Consumer Key and client_secret is the Consumer Secret
  
    use Dancer;
    use Net::OAuth::Client;
  
    sub client {
    	Net::OAuth::Client->new(
    		config->{client_id},
    		config->{client_secret},
    		site => 'https://www.google.com/',
    		request_token_path => '/accounts/OAuthGetRequestToken?scope=https%3A%2F%2Fwww.google.com%2Fm8%2Ffeeds%2F',
    		authorize_path => '/accounts/OAuthAuthorizeToken',
    		access_token_path => '/accounts/OAuthGetAccessToken',
    		callback => uri_for("/auth/google/callback"),
    		session => \&session,
    	);
    }
  
    # Send user to authorize with service provider
    get '/auth/google' => sub {
    	redirect client->authorize_url;
    };
  
    # User has returned with token and verifier appended to the URL.
    get '/auth/google/callback' => sub {
  
    	# Use the auth code to fetch the access token
    	my $access_token =  client->get_access_token(params->{oauth_token}, params->{oauth_verifier});
  
    	# Use the access token to fetch a protected resource
    	my $response = $access_token->get('/m8/feeds/contacts/default/full');
  
    	# Do something with said resource...
  
    	if ($response->is_success) {
    	  return "Yay, it worked: " . $response->decoded_content;
    	}
    	else {
    	  return "Error: " . $response->status_line;
    	}
    };
  
    dance;
  
  =head1 DESCRIPTION
  
  Net::OAuth::Client represents an OAuth client or consumer.
  
  WARNING: Net::OAuth::Client is alpha code.  The rest of Net::OAuth is quite
  stable but this particular module is new, and is under-documented and under-tested.
  
    
  =head1 METHODS
  
  =over
  
  =item new($client_id, $client_secret, %params)
  
  Create a new Client
  
  =over 
  
  =item * $client_id
  
  AKA Consumer Key - you get this from the service provider when you register your application.
  
  =item * $client_secret
  
  AKA Consumer Secret - you get this from the service provider when you register your application.
  
  =item * $params{site}
  
  =item * $params{request_token_path}
  
  =item * $params{authorize_path}
  
  =item * $params{access_token_path}
  
  =item * $params{callback}
  
  =item * $params{session}
  
  =back
  
  =back
  
  =cut
  
  sub new {
    my $class = shift;
    my $client_id = shift;
    my $client_secret = shift;
    my %opts = @_;
    $opts{user_agent} ||= LWP::UserAgent->new;
    $opts{id} = $client_id;
    $opts{secret} = $client_secret;
    $opts{is_v1a} = defined $opts{callback};
    my $self = bless \%opts, $class;
    return $self;
  }
  
  sub request {
    my $self = shift;
    my $response = $self->user_agent->request(@_);
  }
  
  sub _parse_oauth_response {
    my $self = shift;
    my $do_what = shift;
    my $http_res = shift;
    my $msg = "Unable to $do_what: Request for " . $http_res->request->uri . " failed";
    unless ($http_res->is_success) {
      if ($self->debug) { 
        $msg .= "," . $http_res->as_string . " ";      
      }
      elsif (
        $http_res->content_type eq 'application/x-www-form-urlencoded'
        and $http_res->decoded_content =~ /\boauth_problem=(\w+)/
        ) { 
        $msg .= ", reason: " . $1;      
      }
      else {
        $msg .= ": " . $http_res->status_line . " (pass debug=>1 to Net::OAuth::Client->new to dump the entire response)";
      }
      croak $msg;
    }
    my $oauth_res = _parse_url_encoding($http_res->decoded_content);
    foreach my $k (qw/token token_secret/) {
      croak "Unable to $do_what: server response is missing '$k'" unless defined $oauth_res->{$k};
    }
    return $oauth_res;
    
  }
  
  sub _parse_url_encoding {
    my $str = shift;
    my @pairs = split '&', $str;
    my %params;
  	foreach my $pair (@pairs) {
          my ($k,$v) = split /=/, $pair;
          if (defined $k and defined $v) {
              $v =~ s/(^"|"$)//g;
              ($k,$v) = map Net::OAuth::Message::decode($_), $k, $v;
              $k =~ s/^oauth_//;
              $params{$k} = $v;
          }
      }
  	return \%params;
  }
  
  sub get_request_token {
    my $self = shift;
    my %params = @_;
    my $oauth_req = $self->_make_request(
      "request token", 
      request_method => $self->request_token_method,
      request_url => $self->_make_url("request_token"),
      %params
    );
    $oauth_req->sign;
    my $http_res = $self->request(HTTP::Request->new(
      $self->request_token_method => $oauth_req->to_url
    ));
    my $oauth_res = $self->_parse_oauth_response('get a request token', $http_res);
    $self->is_v1a(0) unless defined $oauth_res->{callback_confirmed};
    return $oauth_res;
  }
  
  sub authorize_url {
    my $self = shift;
    my %params = @_;
    # allow user to get request token their own way
    unless (defined $params{token} and defined $params{token_secret}) {
      my $request_token = $self->get_request_token;
      $params{token} = $request_token->{token};
      $params{token_secret} = $request_token->{token_secret};
    }
    if (defined $self->session) {
      $self->session->($params{token} => $params{token_secret});
    }
    my $oauth_req = $self->_make_request(
      'user auth',
      %params
    );
    return $oauth_req->to_url($self->_make_url('authorize'));
  }
  
  sub get_access_token {
    my $self = shift;
    my $token = shift;
    my $verifier = shift;
    my %params = @_;
    
    if (defined $self->session) {
      $params{token_secret} = $self->session->($token);
    }
  
    my $oauth_req = $self->_make_request(
      'access token', 
      request_method => $self->access_token_method,
      request_url => $self->_make_url('access_token'),
      token => $token,
      verifier => $verifier,
      %params
    );
    $oauth_req->sign;
    
    my $http_res = $self->request(HTTP::Request->new(
      $self->access_token_method => $oauth_req->to_url
    ));
  
    my $oauth_res = $self->_parse_oauth_response('get an access token', $http_res);
    
    return Net::OAuth::AccessToken->new(%$oauth_res, client => $self);
  }
  
  sub access_token_url {
    return shift->_make_url('access_token', @_);
  }
  
  sub request_token_url {
    return shift->_make_url('request_token', @_);
  }
  
  sub access_token_method {
    return shift->{access_token_method} || 'GET';
  }
  
  sub request_token_method {
    return shift->{request_token_method} || 'GET';
  }
  
  sub _make_request {
    my $self = shift;
    my $type = shift;
    my %params = @_;
    my %defaults = (
      nonce => int( rand( 2**32 ) ),
      timestamp => time,
      consumer_key => $self->id,
      consumer_secret => $self->secret,
      callback => $self->callback,
      signature_method => 'HMAC-SHA1',
      request_method => 'GET',
    );
    $defaults{protocol_version} = Net::OAuth::PROTOCOL_VERSION_1_0A if $self->is_v1a;
    my $req = Net::OAuth->request($type)->new(
      %defaults,
      %params
    );
    return $req;
  }
  
  sub _make_url {
    my $self = shift;
    my $thing = shift;
    my $path = $self->{"${thing}_url"} || $self->{"${thing}_path"} || "/oauth/${thing}";
    return $self->site_url($path, @_);
  }
  
  sub site_url {
    my $self = shift;
    my $path = shift;
    my %params = @_;
    my $url;
    if (defined $self->{site}) {
      $url = URI->new_abs($path, $self->{site});
    }
    else {
      $url = URI->new($path);
    }
    if (@_) {
      $url->query_form($url->query_form , %params);
    }
    return $url;
  }
  
  
  
  =head1 LICENSE AND COPYRIGHT
  
  Copyright 2011 Keith Grennan.
  
  This program is free software; you can redistribute it and/or modify it
  under the terms of either: the GNU General Public License as published
  by the Free Software Foundation; or the Artistic License.
  
  See http://dev.perl.org/licenses/ for more information.
  
  =cut
  
  
  1;
  
  
  1;
NET_OAUTH_CLIENT

$fatpacked{"Net/OAuth/ConsumerRequest.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'NET_OAUTH_CONSUMERREQUEST';
  package Net::OAuth::ConsumerRequest;
  use warnings;
  use strict;
  use base 'Net::OAuth::Request';
  
  sub allow_extra_params {1}
  sub sign_message {1}
  
  =head1 NAME
  
  Net::OAuth::ConsumerRequest - An OAuth Consumer Request
  
  =head1 NOTE
  
  Consumer Requests are a proposed extension to OAuth, so other
  OAuth implementations may or may not support them.
  
  =head1 SEE ALSO
  
  Consumer Request Extension Draft:
  
  L<http://oauth.googlecode.com/svn/spec/ext/consumer_request/1.0/drafts/1/spec.html>
  
  L<Net::OAuth>, L<http://oauth.net>
  
  =head1 AUTHOR
  
  Keith Grennan, C<< <kgrennan at cpan.org> >>
  
  =head1 COPYRIGHT & LICENSE
  
  Copyright 2007 Keith Grennan, all rights reserved.
  
  This program is free software; you can redistribute it and/or modify it
  under the same terms as Perl itself.
  
  =cut
  
  
  1;
NET_OAUTH_CONSUMERREQUEST

$fatpacked{"Net/OAuth/Message.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'NET_OAUTH_MESSAGE';
  package Net::OAuth::Message;
  use warnings;
  use strict;
  use base qw/Class::Data::Inheritable Class::Accessor/;
  use URI::Escape;
  use Net::OAuth;
  use URI;
  use URI::QueryParam;
  use Carp;
  
  use constant OAUTH_PREFIX => 'oauth_';
  
  our $OAUTH_PREFIX_RE = do {my $p = OAUTH_PREFIX; qr/^$p/};
  
  __PACKAGE__->mk_classdata(extension_param_patterns => []);
  
  sub add_required_message_params {
      my $class = shift;
      $class->required_message_params([@{$class->required_message_params}, @_]);
      $class->all_message_params([@{$class->all_message_params}, @_]);
      $class->all_params([@{$class->all_params}, @_]);
      $class->mk_accessors(@_);
  }
  
  sub add_optional_message_params {
      my $class = shift;
      $class->optional_message_params([@{$class->optional_message_params}, @_]);
      $class->all_message_params([@{$class->all_message_params}, @_]);
      $class->all_params([@{$class->all_params}, @_]);
      $class->mk_accessors(@_);
  }
  
  sub add_required_api_params {
      my $class = shift;
      $class->required_api_params([@{$class->required_api_params}, @_]);
      $class->all_api_params([@{$class->all_api_params}, @_]);
      $class->all_params([@{$class->all_params}, @_]);
      $class->mk_accessors(@_);
  }
  
  sub add_extension_param_pattern {
      my $class = shift;
      $class->extension_param_patterns([@{$class->extension_param_patterns}, @_]);
  }
  
  sub add_to_signature {
      my $class = shift;
      $class->signature_elements([@{$class->signature_elements}, @_]);
  }
  
  sub new {
      my $proto = shift;
      my $class = ref $proto || $proto;
      my %params = @_;
      $class = get_versioned_class($class, \%params);
      my $self = bless \%params, $class;
      $self->set_defaults;
      $self->check;
      return $self;
  }
  
  sub get_versioned_class {
      my $class = shift;
      my $params = shift;
      my $protocol_version = $params->{protocol_version} || $Net::OAuth::PROTOCOL_VERSION;
      if (defined $protocol_version and $protocol_version == Net::OAuth::PROTOCOL_VERSION_1_0A and $class !~ /\::V1_0A\::/) {
          (my $versioned_class = $class) =~ s/::(\w+)$/::V1_0A::$1/;
          return $versioned_class if Net::OAuth::smart_require($versioned_class);
      }
      return $class;
  }
  
  sub set_defaults {
      my $self = shift;
      $self->{extra_params} ||= {};
      $self->{version} ||= Net::OAuth::OAUTH_VERSION unless $self->{from_hash};
  }
  
  sub is_extension_param {
      my $self = shift;
      my $param = shift;
      return grep ($param =~ $_, @{$self->extension_param_patterns});
  }
  
  sub check {
      my $self = shift;
      foreach my $k (@{$self->required_message_params}, @{$self->required_api_params}) {
          if (not defined $self->{$k}) {
              croak "Missing required parameter '$k'";
          }
      }
      if ($self->{extra_params} and $self->allow_extra_params) {
          foreach my $k (keys %{$self->{extra_params}}) {
              if ($k =~ $OAUTH_PREFIX_RE) {
                  croak "Parameter '$k' not allowed in arbitrary params"
              }
          }
      }
  }
  
  sub encode {
      my $str = shift;
      $str = "" unless defined $str;
      unless($Net::OAuth::SKIP_UTF8_DOUBLE_ENCODE_CHECK) {
          if ($str =~ /[\x80-\xFF]/ and !utf8::is_utf8($str)) {
              warn "Net::OAuth warning: your OAuth message appears to contain some multi-byte characters that need to be decoded via Encode.pm or a PerlIO layer first.  This may result in an incorrect signature.";
          }
      }    
      return URI::Escape::uri_escape_utf8($str,'^\w.~-');
  }
  
  sub decode {
      my $str = shift;
      return uri_unescape($str);
  }
  
  sub allow_extra_params {1}
  
  sub sign_message {0}
  
  sub gather_message_parameters {
      my $self = shift;
      my %opts = @_;
      $opts{quote} = "" unless defined $opts{quote};
      $opts{params} ||= [];
      my %params;
      foreach my $k (@{$self->required_message_params}, @{$self->optional_message_params}, @{$opts{add}}) {
          next if $k eq 'signature' and (!$self->sign_message or !grep ($_ eq 'signature', @{$opts{add}}));
          my $message_key = $self->is_extension_param($k) ? $k : OAUTH_PREFIX . $k;
          my $v = $self->$k;
          $params{$message_key} = $v if defined $v;
      }
      if ($self->{extra_params} and !$opts{no_extra} and $self->allow_extra_params) {
          foreach my $k (keys %{$self->{extra_params}}) {
              $params{$k} = $self->{extra_params}{$k};
          }
          if ($self->can('request_url')) {
              my $url = $self->request_url;
              _ensure_uri_object($url);         
              foreach my $k ($url->query_param) {
                  $params{$k} = $url->query_param($k);
              }
          }
      }
      if ($opts{hash}) {
          return \%params;
      }
      my @pairs;
      while (my ($k,$v) = each %params) {
          push @pairs, join('=', encode($k), $opts{quote} . encode($v) . $opts{quote});
      }
      return sort(@pairs);
  }
  
  sub normalized_message_parameters {
      my $self = shift;
      return join('&',  $self->gather_message_parameters);
  }
  
  sub signature_base_string {
      my $self = shift;
      return join('&', map(encode($self->$_), @{$self->signature_elements}));
  }
  
  sub sign {
      my $self = shift;
      my $class = $self->_signature_method_class;
      $self->signature($class->sign($self, @_));
  }
  
  sub verify {
      my $self = shift;
      my $class = $self->_signature_method_class;
      return $class->verify($self, @_);
  }
  
  sub _signature_method_class {
      my $self = shift;
      (my $signature_method = $self->signature_method) =~ s/\W+/_/g;
      my $sm_class = 'Net::OAuth::SignatureMethod::' . $signature_method;
      croak "Unable to load $signature_method plugin" unless Net::OAuth::smart_require($sm_class);
      return $sm_class;
  }
  
  sub to_authorization_header {
      my $self = shift;
      my $realm = shift;
      my $sep = shift || ",";
      if (defined $realm) {
          $realm = "realm=\"$realm\"$sep";
      }
      else {
          $realm = "";
      }
      return "OAuth $realm" .
          join($sep, $self->gather_message_parameters(quote => '"', add => [qw/signature/], no_extra => 1));
  }
  
  sub from_authorization_header {
      my $proto = shift;
      my $header = shift;
      my $class = ref $proto || $proto;
      croak "Header must start with \"OAuth \"" unless $header =~ s/OAuth //;
      my @header = split /[\s]*,[\s]*/, $header;
      shift @header if $header[0] =~ /^realm=/i;
      return $class->_from_pairs(\@header, @_)
  }
  
  sub _from_pairs() {
  	my $class = shift;
  	my $pairs = shift;
  	if (ref $pairs ne 'ARRAY') {
  		croak 'Expected an array!';
  	}
  	my %params;
  	foreach my $pair (@$pairs) {
          my ($k,$v) = split /=/, $pair;
          if (defined $k and defined $v) {
              $v =~ s/(^"|"$)//g;
              ($k,$v) = map decode($_), $k, $v;
              $params{$k} = $v;
          }
      }
      return $class->from_hash(\%params, @_);
  }
  
  sub from_hash {
      my $proto = shift;
      my $class = ref $proto || $proto;
      my $hash = shift;
  	if (ref $hash ne 'HASH') {
  		croak 'Expected a hash!';
  	}
      my %api_params = @_;
      # need to do this earlier than Message->new because
      # the below validation step needs the correct class.
      # https://rt.cpan.org/Public/Bug/Display.html?id=47293
      $class = get_versioned_class($class, \%api_params);
      my %msg_params;
      foreach my $k (keys %$hash) {
          if ($k =~ s/$OAUTH_PREFIX_RE//) {
              if (!grep ($_ eq $k, @{$class->all_message_params})) {
                 croak "Parameter ". OAUTH_PREFIX ."$k not valid for a message of type $class";
              }
              else {
                  $msg_params{$k} = $hash->{OAUTH_PREFIX . $k};
              }
          }
          elsif ($class->is_extension_param($k)) {
              if (!grep ($_ eq $k, @{$class->all_message_params})) {
                  croak "Parameter $k not valid for a message of type $class";
              }
              else {
                  $msg_params{$k} = $hash->{$k};
              }
          }
          else {
              $msg_params{extra_params}->{$k} = $hash->{$k};
          }
      }
      $api_params{from_hash} = 1;
      return $class->new(%msg_params, %api_params);
  }
  
  sub _ensure_uri_object {
      $_[0] = UNIVERSAL::isa($_[0], 'URI') ? $_[0] : URI->new($_[0]);
  }
  
  sub from_url {
  	my $proto = shift;
      my $class = ref $proto || $proto;
      my $url = shift;
  	_ensure_uri_object($url);
  	return $class->from_hash($url->query_form_hash, @_);
  }
  
  sub to_post_body {
      my $self = shift;
      return join('&', $self->gather_message_parameters(add => [qw/signature/]));
  }
  
  sub from_post_body {
  	my $proto = shift;
      my $class = ref $proto || $proto;
      my @pairs = split '&', shift;
  	return $class->_from_pairs(\@pairs, @_);
  }
  
  sub to_hash {
      my $self = shift;
      return $self->gather_message_parameters(hash => 1, add => [qw/signature/]);
  }
  
  sub to_url {
  	my $self = shift;
  	my $url = shift;
  	if (!defined $url and $self->can('request_url') and defined $self->request_url) {
  		$url = $self->request_url;
  	}
  	if (defined $url) {
          _ensure_uri_object($url);
          $url = $url->clone; # don't modify the URL that was passed in
          $url->query(undef); # remove any existing query params, as these may cause the signature to break	
  		my $params = $self->to_hash;
  		my $sep = '?';
  		foreach my $k (sort keys %$params) {
  		    $url .= $sep . encode($k) . '=' . encode( $params->{$k} );
              $sep = '&' if $sep eq '?';
  		}
  		return $url;
  	}
  	else {
  		return $self->to_post_body;
  	}
  }
  
  =head1 NAME
  
  Net::OAuth::Message - base class for OAuth messages
  
  =head1 SEE ALSO
  
  L<Net::OAuth>, L<http://oauth.net>
  
  =head1 AUTHOR
  
  Keith Grennan, C<< <kgrennan at cpan.org> >>
  
  =head1 COPYRIGHT & LICENSE
  
  Copyright 2007 Keith Grennan, all rights reserved.
  
  This program is free software; you can redistribute it and/or modify it
  under the same terms as Perl itself.
  
  =cut
  
  1;
NET_OAUTH_MESSAGE

$fatpacked{"Net/OAuth/ProtectedResourceRequest.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'NET_OAUTH_PROTECTEDRESOURCEREQUEST';
  package Net::OAuth::ProtectedResourceRequest;
  use warnings;
  use strict;
  use base 'Net::OAuth::Request';
  
  __PACKAGE__->add_required_message_params(qw/token/);
  __PACKAGE__->add_required_api_params(qw/token_secret/);
  sub allow_extra_params {1}
  sub sign_message {1}
  
  
  =head1 NAME
  
  Net::OAuth::ProtectedResourceRequest - An OAuth protocol request for a Protected Resource
  
  =head1 SEE ALSO
  
  L<Net::OAuth>, L<http://oauth.net>
  
  =head1 AUTHOR
  
  Keith Grennan, C<< <kgrennan at cpan.org> >>
  
  =head1 COPYRIGHT & LICENSE
  
  Copyright 2007 Keith Grennan, all rights reserved.
  
  This program is free software; you can redistribute it and/or modify it
  under the same terms as Perl itself.
  
  =cut
  
  
  1;
NET_OAUTH_PROTECTEDRESOURCEREQUEST

$fatpacked{"Net/OAuth/Request.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'NET_OAUTH_REQUEST';
  package Net::OAuth::Request;
  use warnings;
  use strict;
  use base qw/Net::OAuth::Message/;
  use URI;
  use URI::QueryParam;
  
  use Net::OAuth;
  our $VERSION = '0.28';
  
  __PACKAGE__->mk_classdata(required_message_params => [qw/
      consumer_key
      signature_method
      timestamp
      nonce
      /]);
  
  __PACKAGE__->mk_classdata(optional_message_params => [qw/
      version
      signature
      /]);
  
  __PACKAGE__->mk_classdata(required_api_params => [qw/
      request_method
      request_url
      consumer_secret
      /]);
  
  __PACKAGE__->mk_classdata(optional_api_params => [qw/
      signature_key
      token_secret
      extra_params
      protocol_version
      /]);
  
  __PACKAGE__->mk_classdata(signature_elements => [qw/
      request_method
      normalized_request_url
      normalized_message_parameters
      /]);
  
  __PACKAGE__->mk_classdata(all_message_params => [
      @{__PACKAGE__->required_message_params},
      @{__PACKAGE__->optional_message_params},
  	]);
  
  __PACKAGE__->mk_classdata(all_api_params => [
      @{__PACKAGE__->required_api_params},
      @{__PACKAGE__->optional_api_params},	
  	]);
  
  __PACKAGE__->mk_classdata(all_params => [
      @{__PACKAGE__->all_api_params},
      @{__PACKAGE__->all_message_params},	
  	]);
  
  __PACKAGE__->mk_accessors(
      @{__PACKAGE__->all_params},
      );
  
  sub signature_key {
      my $self = shift;
      # For some sig methods (I.e. RSA), users will pass in their own key
      my $key = $self->get('signature_key');
      unless (defined $key) {
          $key = Net::OAuth::Message::encode($self->consumer_secret) . '&';
          $key .= Net::OAuth::Message::encode($self->token_secret) if $self->can('token_secret');
      }
      return $key;
  }
  
  sub normalized_request_url {
      my $self = shift;
      my $url = $self->request_url;
      Net::OAuth::Message::_ensure_uri_object($url);
      $url = $url->clone;
      $url->query(undef);
      return $url;
  }
  
  
  =head1 NAME
  
  Net::OAuth::Request - base class for OAuth requests
  
  =head1 SEE ALSO
  
  L<Net::OAuth>, L<http://oauth.net>
  
  =head1 AUTHOR
  
  Keith Grennan, C<< <kgrennan at cpan.org> >>
  
  =head1 COPYRIGHT & LICENSE
  
  Copyright 2007 Keith Grennan, all rights reserved.
  
  This program is free software; you can redistribute it and/or modify it
  under the same terms as Perl itself.
  
  =cut
  
  1;
NET_OAUTH_REQUEST

$fatpacked{"Net/OAuth/RequestTokenRequest.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'NET_OAUTH_REQUESTTOKENREQUEST';
  package Net::OAuth::RequestTokenRequest;
  use warnings;
  use strict;
  use base 'Net::OAuth::Request';
  
  sub sign_message {1}
  
  =head1 NAME
  
  Net::OAuth::RequestTokenRequest - An OAuth protocol request for a Request Token
  
  =head1 SEE ALSO
  
  L<Net::OAuth>, L<http://oauth.net>
  
  =head1 AUTHOR
  
  Keith Grennan, C<< <kgrennan at cpan.org> >>
  
  =head1 COPYRIGHT & LICENSE
  
  Copyright 2007 Keith Grennan, all rights reserved.
  
  This program is free software; you can redistribute it and/or modify it
  under the same terms as Perl itself.
  
  =cut
  
  1;
NET_OAUTH_REQUESTTOKENREQUEST

$fatpacked{"Net/OAuth/RequestTokenResponse.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'NET_OAUTH_REQUESTTOKENRESPONSE';
  package Net::OAuth::RequestTokenResponse;
  use warnings;
  use strict;
  use base 'Net::OAuth::Response';
  
  __PACKAGE__->add_required_message_params(qw/token_secret/);
  sub allow_extra_params {1}
  
  =head1 NAME
  
  Net::OAuth::RequestTokenResponse - An OAuth protocol response for an Request Token
  
  =head1 SEE ALSO
  
  L<Net::OAuth>, L<http://oauth.net>
  
  =head1 AUTHOR
  
  Keith Grennan, C<< <kgrennan at cpan.org> >>
  
  =head1 COPYRIGHT & LICENSE
  
  Copyright 2007 Keith Grennan, all rights reserved.
  
  This program is free software; you can redistribute it and/or modify it
  under the same terms as Perl itself.
  
  =cut
  
  1;
NET_OAUTH_REQUESTTOKENRESPONSE

$fatpacked{"Net/OAuth/Response.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'NET_OAUTH_RESPONSE';
  package Net::OAuth::Response;
  use warnings;
  use strict;
  use base qw/Net::OAuth::Message/;
  
  __PACKAGE__->mk_classdata(required_message_params => [qw/
  	token
      /]);
  
  __PACKAGE__->mk_classdata(optional_message_params => [qw/
      /]);
  
  __PACKAGE__->mk_classdata(required_api_params => [qw/
      /]);
  
  __PACKAGE__->mk_classdata(optional_api_params => [qw/
  	extra_params
  	protocol_version
  	/]);
  
  __PACKAGE__->mk_classdata(signature_elements => [qw/
      /]);
  
  __PACKAGE__->mk_classdata(all_message_params => [
      @{__PACKAGE__->required_message_params},
      @{__PACKAGE__->optional_message_params},
  	]);
  
  __PACKAGE__->mk_classdata(all_api_params => [
      @{__PACKAGE__->required_api_params},
      @{__PACKAGE__->optional_api_params},	
  	]);
  	
  __PACKAGE__->mk_classdata(all_params => [
      @{__PACKAGE__->all_api_params},
      @{__PACKAGE__->all_message_params},	
  	]);
  
  __PACKAGE__->mk_accessors(
      @{__PACKAGE__->all_params},
      );
  
  =head1 NAME
  
  Net::OAuth::Response - base class for OAuth responses
  
  =head1 SEE ALSO
  
  L<Net::OAuth>, L<http://oauth.net>
  
  =head1 AUTHOR
  
  Keith Grennan, C<< <kgrennan at cpan.org> >>
  
  =head1 COPYRIGHT & LICENSE
  
  Copyright 2007 Keith Grennan, all rights reserved.
  
  This program is free software; you can redistribute it and/or modify it
  under the same terms as Perl itself.
  
  =cut
  
  1;
NET_OAUTH_RESPONSE

$fatpacked{"Net/OAuth/SignatureMethod/HMAC_SHA1.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'NET_OAUTH_SIGNATUREMETHOD_HMAC_SHA1';
  package Net::OAuth::SignatureMethod::HMAC_SHA1;
  use warnings;
  use strict;
  use Digest::HMAC_SHA1;
  use MIME::Base64;
  
  sub sign {
      my $self = shift;
      my $request = shift;
      my $hmac = Digest::HMAC_SHA1->new($request->signature_key);
      $hmac->add($request->signature_base_string);
      return encode_base64($hmac->digest, '');
  }
  
  sub verify {
      my $self = shift;
      my $request = shift;
      return $request->signature eq $self->sign($request);
  }
  
  =head1 NAME
  
  Net::OAuth::SignatureMethod::HMAC_SHA1 - HMAC_SHA1 Signature Method for OAuth protocol
  
  =head1 SEE ALSO
  
  L<Net::OAuth>, L<http://oauth.net>
  
  =head1 AUTHOR
  
  Keith Grennan, C<< <kgrennan at cpan.org> >>
  
  =head1 COPYRIGHT & LICENSE
  
  Copyright 2007 Keith Grennan, all rights reserved.
  
  This program is free software; you can redistribute it and/or modify it
  under the same terms as Perl itself.
  
  =cut
  
  1;
NET_OAUTH_SIGNATUREMETHOD_HMAC_SHA1

$fatpacked{"Net/OAuth/SignatureMethod/HMAC_SHA256.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'NET_OAUTH_SIGNATUREMETHOD_HMAC_SHA256';
  package Net::OAuth::SignatureMethod::HMAC_SHA256;
  use warnings;
  use strict;
  use Digest::SHA  ();
  use MIME::Base64 ();
  
  sub sign {
      my $self = shift;
      my $request = shift;
      my $hmac_digest = Digest::SHA::hmac_sha256(
          $request->signature_base_string, $request->signature_key
      );
      return MIME::Base64::encode_base64($hmac_digest, '');
  }
  
  sub verify {
      my $self = shift;
      my $request = shift;
      return $request->signature eq $self->sign($request);
  }
  
  =head1 NAME
  
  Net::OAuth::SignatureMethod::HMAC_SHA256 - HMAC_SHA256 Signature Method for OAuth protocol
  
  =head1 SEE ALSO
  
  L<Net::OAuth>, L<http://oauth.net>
  
  =head1 AUTHOR
  
  Keith Grennan, C<< <kgrennan at cpan.org> >>
  
  =head1 COPYRIGHT & LICENSE
  
  Copyright 2012 Keith Grennan, all rights reserved.
  
  This program is free software; you can redistribute it and/or modify it
  under the same terms as Perl itself.
  
  =cut
  
  1;
NET_OAUTH_SIGNATUREMETHOD_HMAC_SHA256

$fatpacked{"Net/OAuth/SignatureMethod/PLAINTEXT.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'NET_OAUTH_SIGNATUREMETHOD_PLAINTEXT';
  package Net::OAuth::SignatureMethod::PLAINTEXT;
  use warnings;
  use strict;
  
  sub sign {
      my $self = shift;
      my $request = shift;
      return $request->signature_key;
  }
  
  sub verify {
      my $self = shift;
      my $request = shift;
      return $request->signature eq $self->sign($request);
  }
  
  =head1 NAME
  
  Net::OAuth::SignatureMethod::PLAINTEXT - PLAINTEXT Signature Method for OAuth protocol
  
  =head1 SEE ALSO
  
  L<Net::OAuth>, L<http://oauth.net>
  
  =head1 AUTHOR
  
  Keith Grennan, C<< <kgrennan at cpan.org> >>
  
  =head1 COPYRIGHT & LICENSE
  
  Copyright 2007 Keith Grennan, all rights reserved.
  
  This program is free software; you can redistribute it and/or modify it
  under the same terms as Perl itself.
  
  =cut
  
  1;
NET_OAUTH_SIGNATUREMETHOD_PLAINTEXT

$fatpacked{"Net/OAuth/SignatureMethod/RSA_SHA1.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'NET_OAUTH_SIGNATUREMETHOD_RSA_SHA1';
  package Net::OAuth::SignatureMethod::RSA_SHA1;
  use warnings;
  use strict;
  use MIME::Base64;
  
  sub sign {
      my $self = shift;
      my $request = shift;
  	my $key = shift || $request->signature_key;
      die '$request->signature_key must be an RSA key object (e.g. Crypt::OpenSSL::RSA) that can sign($text)'
          unless UNIVERSAL::can($key, 'sign');
      return encode_base64($key->sign($request->signature_base_string), "");
  }
  
  sub verify {
      my $self = shift;
      my $request = shift;
      my $key = shift || $request->signature_key;
      die 'You must pass an RSA key object (e.g. Crypt::OpenSSL::RSA) that can verify($text,$sig)'
          unless UNIVERSAL::can($key, 'verify');
      return $key->verify($request->signature_base_string, decode_base64($request->signature));
  }
  
  =head1 NAME
  
  Net::OAuth::SignatureMethod::RSA_SHA1 - RSA_SHA1 Signature Method for OAuth protocol
  
  =head1 SEE ALSO
  
  L<Net::OAuth>, L<http://oauth.net>
  
  =head1 AUTHOR
  
  Keith Grennan, C<< <kgrennan at cpan.org> >>
  
  =head1 COPYRIGHT & LICENSE
  
  Copyright 2007 Keith Grennan, all rights reserved.
  
  This program is free software; you can redistribute it and/or modify it
  under the same terms as Perl itself.
  
  =cut
  
  1;
NET_OAUTH_SIGNATUREMETHOD_RSA_SHA1

$fatpacked{"Net/OAuth/UserAuthRequest.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'NET_OAUTH_USERAUTHREQUEST';
  package Net::OAuth::UserAuthRequest;
  use warnings;
  use strict;
  use base qw/Net::OAuth::Message/;
  
  __PACKAGE__->mk_classdata(required_message_params => [qw/
      /]);
  
  __PACKAGE__->mk_classdata(optional_message_params => [qw/
      token
      callback
      /]);
  
  __PACKAGE__->mk_classdata(required_api_params => [qw/
      /]);
  
  __PACKAGE__->mk_classdata(optional_api_params => [qw/
      extra_params
      /]);
  
  __PACKAGE__->mk_classdata(signature_elements => [qw/
      /]);
      
  __PACKAGE__->mk_classdata(all_message_params => [
      @{__PACKAGE__->required_message_params},
      @{__PACKAGE__->optional_message_params},
  	]);
  
  __PACKAGE__->mk_classdata(all_api_params => [
      @{__PACKAGE__->required_api_params},
      @{__PACKAGE__->optional_api_params},	
  	]);
  
  __PACKAGE__->mk_classdata(all_params => [
      @{__PACKAGE__->all_api_params},
      @{__PACKAGE__->all_message_params},	
  	]);
  
  __PACKAGE__->mk_accessors(
      @{__PACKAGE__->all_params},
      );
  
  =head1 NAME
  
  Net::OAuth::UserAuthRequest - request for OAuth User Authentication
  
  =head1 SEE ALSO
  
  L<Net::OAuth>, L<http://oauth.net>
  
  =head1 AUTHOR
  
  Keith Grennan, C<< <kgrennan at cpan.org> >>
  
  =head1 COPYRIGHT & LICENSE
  
  Copyright 2007 Keith Grennan, all rights reserved.
  
  This program is free software; you can redistribute it and/or modify it
  under the same terms as Perl itself.
  
  =cut
  
  1;
NET_OAUTH_USERAUTHREQUEST

$fatpacked{"Net/OAuth/UserAuthResponse.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'NET_OAUTH_USERAUTHRESPONSE';
  package Net::OAuth::UserAuthResponse;
  use warnings;
  use strict;
  use base 'Net::OAuth::Response';
  use Net::OAuth;
  
  sub allow_extra_params {1}
  
  =head1 NAME
  
  Net::OAuth::UserAuthResponse - An OAuth protocol response for an Access Token
  
  =head1 SEE ALSO
  
  L<Net::OAuth>, L<http://oauth.net>
  
  =head1 AUTHOR
  
  Keith Grennan, C<< <kgrennan at cpan.org> >>
  
  =head1 COPYRIGHT & LICENSE
  
  Copyright 2007 Keith Grennan, all rights reserved.
  
  This program is free software; you can redistribute it and/or modify it
  under the same terms as Perl itself.
  
  =cut
  
  1;
NET_OAUTH_USERAUTHRESPONSE

$fatpacked{"Net/OAuth/V1_0A/AccessTokenRequest.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'NET_OAUTH_V1_0A_ACCESSTOKENREQUEST';
  package Net::OAuth::V1_0A::AccessTokenRequest;
  use warnings;
  use strict;
  use base 'Net::OAuth::AccessTokenRequest';
  
  __PACKAGE__->add_required_message_params(qw/verifier/);
  
  =head1 NAME
  
  Net::OAuth::V1_0A::AccessTokenRequest - An OAuth protocol request for an Access Token
  
  =head1 SEE ALSO
  
  L<Net::OAuth>, L<http://oauth.net>
  
  =head1 AUTHOR
  
  Keith Grennan, C<< <kgrennan at cpan.org> >>
  
  =head1 COPYRIGHT & LICENSE
  
  Copyright 2007 Keith Grennan, all rights reserved.
  
  This program is free software; you can redistribute it and/or modify it
  under the same terms as Perl itself.
  
  =cut
  
  1;
NET_OAUTH_V1_0A_ACCESSTOKENREQUEST

$fatpacked{"Net/OAuth/V1_0A/RequestTokenRequest.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'NET_OAUTH_V1_0A_REQUESTTOKENREQUEST';
  package Net::OAuth::V1_0A::RequestTokenRequest;
  use warnings;
  use strict;
  use base 'Net::OAuth::RequestTokenRequest';
  
  __PACKAGE__->add_required_message_params(qw/callback/);
  
  =head1 NAME
  
  Net::OAuth::V1_0A::RequestTokenRequest - An OAuth protocol request for a Request Token
  
  =head1 SEE ALSO
  
  L<Net::OAuth>, L<http://oauth.net>
  
  =head1 AUTHOR
  
  Keith Grennan, C<< <kgrennan at cpan.org> >>
  
  =head1 COPYRIGHT & LICENSE
  
  Copyright 2007 Keith Grennan, all rights reserved.
  
  This program is free software; you can redistribute it and/or modify it
  under the same terms as Perl itself.
  
  =cut
  
  1;
NET_OAUTH_V1_0A_REQUESTTOKENREQUEST

$fatpacked{"Net/OAuth/V1_0A/RequestTokenResponse.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'NET_OAUTH_V1_0A_REQUESTTOKENRESPONSE';
  package Net::OAuth::V1_0A::RequestTokenResponse;
  use warnings;
  use strict;
  use base 'Net::OAuth::RequestTokenResponse';
  
  __PACKAGE__->add_required_message_params(qw/callback_confirmed/);
  
  =head1 NAME
  
  Net::OAuth::V1_0A::RequestTokenResponse - An OAuth protocol response for an Request Token
  
  =head1 SEE ALSO
  
  L<Net::OAuth>, L<http://oauth.net>
  
  =head1 AUTHOR
  
  Keith Grennan, C<< <kgrennan at cpan.org> >>
  
  =head1 COPYRIGHT & LICENSE
  
  Copyright 2007 Keith Grennan, all rights reserved.
  
  This program is free software; you can redistribute it and/or modify it
  under the same terms as Perl itself.
  
  =cut
  
  1;
NET_OAUTH_V1_0A_REQUESTTOKENRESPONSE

$fatpacked{"Net/OAuth/V1_0A/UserAuthResponse.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'NET_OAUTH_V1_0A_USERAUTHRESPONSE';
  package Net::OAuth::V1_0A::UserAuthResponse;
  use warnings;
  use strict;
  use base 'Net::OAuth::UserAuthResponse';
  
  __PACKAGE__->add_required_message_params(qw/verifier/);
  
  =head1 NAME
  
  Net::OAuth::V1_0A::UserAuthResponse - An OAuth protocol response for an Access Token
  
  =head1 SEE ALSO
  
  L<Net::OAuth>, L<http://oauth.net>
  
  =head1 AUTHOR
  
  Keith Grennan, C<< <kgrennan at cpan.org> >>
  
  =head1 COPYRIGHT & LICENSE
  
  Copyright 2007 Keith Grennan, all rights reserved.
  
  This program is free software; you can redistribute it and/or modify it
  under the same terms as Perl itself.
  
  =cut
  
  1;
NET_OAUTH_V1_0A_USERAUTHRESPONSE

$fatpacked{"Net/OAuth/XauthAccessTokenRequest.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'NET_OAUTH_XAUTHACCESSTOKENREQUEST';
  package Net::OAuth::XauthAccessTokenRequest;
  use warnings;
  use strict;
  use base 'Net::OAuth::Request';
  
  __PACKAGE__->add_extension_param_pattern(qr/x_auth_/);
  __PACKAGE__->add_required_message_params(qw/x_auth_username x_auth_password x_auth_mode/);
  sub allow_extra_params {0}
  sub sign_message {1}
  
  =head1 NAME
  
  Net::OAuth::xAuthAccessTokenRequest - xAuth extension
  
  =head1 SEE ALSO
  
  L<http://apiwiki.twitter.com/Twitter-REST-API-Method:-oauth-access_token-for-xAuth>
  
  =head1 AUTHOR
  
  Keith Grennan, C<< <kgrennan at cpan.org> >>
  
  =head1 CONTRIBUTORS
  
  Masayoshi Sekimura
  
  Simon Wistow
  
  =head1 COPYRIGHT & LICENSE
  
  Copyright 2010 Keith Grennan, all rights reserved.
  
  This program is free software; you can redistribute it and/or modify it
  under the same terms as Perl itself.
  
  =cut
  
  1;
NET_OAUTH_XAUTHACCESSTOKENREQUEST

$fatpacked{"Net/OAuth/YahooAccessTokenRefreshRequest.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'NET_OAUTH_YAHOOACCESSTOKENREFRESHREQUEST';
  package Net::OAuth::YahooAccessTokenRefreshRequest;
  use warnings;
  use strict;
  use base 'Net::OAuth::AccessTokenRequest';
  
  __PACKAGE__->add_required_message_params(qw/session_handle/);
  sub allow_extra_params {0}
  sub sign_message {1}
  
  =head1 NAME
  
  Net::OAuth::YahooAccessTokenRefreshRequest - Yahoo OAuth Extension
  
  =head1 SEE ALSO
  
  L<http://developer.yahoo.com/oauth/guide/oauth-auth-flow.html>
  
  =head1 AUTHOR
  
  Keith Grennan, C<< <kgrennan at cpan.org> >>
  
  =head1 CONTRIBUTORS
  
  Marc Mims
  
  =head1 COPYRIGHT & LICENSE
  
  Copyright 2010 Keith Grennan, all rights reserved.
  
  This program is free software; you can redistribute it and/or modify it
  under the same terms as Perl itself.
  
  =cut
  
  1;
NET_OAUTH_YAHOOACCESSTOKENREFRESHREQUEST

$fatpacked{"String/Random.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'STRING_RANDOM';
  # String::Random - Generates a random string from a pattern
  # Copyright (C) 1999-2006 Steven Pritchard <steve@silug.org>
  #
  # This program is free software; you can redistribute it
  # and/or modify it under the same terms as Perl itself.
  #
  # This program is distributed in the hope that it will be useful,
  # but WITHOUT ANY WARRANTY; without even the implied warranty of
  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  #
  # $Id: Random.pm,v 1.4 2006/09/21 17:34:07 steve Exp $
  
  package String::Random;
  
  require 5.006_001;
  
  use strict;
  use warnings;
  
  use Carp;
  use Exporter ();
  
  our @ISA = qw(Exporter);
  our %EXPORT_TAGS = ( 'all' => [ qw(
      &random_string
      &random_regex
  ) ] );
  our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );
  our @EXPORT = ();
  our $VERSION = '0.26';
  
  # These are the various character sets.
  our @upper=("A".."Z");
  our @lower=("a".."z");
  our @digit=("0".."9");
  our @punct=map { chr($_); } (33..47,58..64,91..96,123..126);
  our @any=(@upper, @lower, @digit, @punct);
  our @salt=(@upper, @lower, @digit, ".", "/");
  our @binary=map { chr($_) } (0..255);
  
  # What's important is how they relate to the pattern characters.
  # These are the old patterns for randpattern/random_string.
  our %old_patterns = (
      'C' => [ @upper ],
      'c' => [ @lower ],
      'n' => [ @digit ],
      '!' => [ @punct ],
      '.' => [ @any ],
      's' => [ @salt ],
      'b' => [ @binary ],
  );
  
  # These are the regex-based patterns.
  our %patterns = (
      # These are the regex-equivalents.
      '.' => [ @any ],
      '\d' => [ @digit ],
      '\D' => [ @upper, @lower, @punct ],
      '\w' => [ @upper, @lower, @digit, "_" ],
      '\W' => [ grep { $_ ne "_" } @punct ],
      '\s' => [ " ", "\t" ], # Would anything else make sense?
      '\S' => [ @upper, @lower, @digit, @punct ],
  
      # These are translated to their double quoted equivalents.
      '\t' => [ "\t" ],
      '\n' => [ "\n" ],
      '\r' => [ "\r" ],
      '\f' => [ "\f" ],
      '\a' => [ "\a" ],
      '\e' => [ "\e" ],
  );
  
  # These characters are treated specially in randregex().
  our %regch = (
     "\\" => sub {
                 my ($self, $ch, $chars, $string)=@_;
                 if (@{$chars}) {
                     my $tmp=shift(@{$chars});
                     if ($tmp eq "x") {
                         # This is supposed to be a number in hex, so
                         # there had better be at least 2 characters left.
                         $tmp=shift(@{$chars}) . shift(@{$chars});
                         push(@{$string}, [chr(hex($tmp))]);
                     } elsif ($tmp=~/[0-7]/) {
                         carp "octal parsing not implemented.  treating literally.";
                         push(@{$string}, [$tmp]);
                     } elsif (defined($patterns{"\\$tmp"})) {
                         $ch.=$tmp;
                         push(@{$string}, $patterns{$ch});
                     }
                     else {
                         if ($tmp =~ /\w/) {
                             carp "'\\$tmp' being treated as literal '$tmp'";
                         }
                         push(@{$string}, [$tmp]);
                     }
                 } else {
                     croak "regex not terminated";
                 }
             },
      '.' => sub {
                 my ($self, $ch, $chars, $string)=@_;
                 push(@{$string}, $patterns{$ch});
             },
      '[' => sub {
                 my ($self, $ch, $chars, $string)=@_;
                 my @tmp;
                 while (defined($ch=shift(@{$chars})) && ($ch ne "]")) {
                     if (($ch eq "-") && @{$chars} && @tmp) {
                         $ch=shift(@{$chars});
                         for (my $n=ord($tmp[$#tmp]);$n<ord($ch);$n++) {
                             push(@tmp, chr($n+1));
                         }
                     } else {
                         carp "'$ch' will be treated literally inside []"
                             if ($ch=~/\W/);
                         push(@tmp, $ch);
                     }
                 }
                 croak "unmatched []" if ($ch ne "]");
                 push(@{$string}, \@tmp);
             },
      '*' => sub {
                 my ($self, $ch, $chars, $string)=@_;
                 unshift(@{$chars}, split("", "{0,}"));
             },
      '+' => sub {
                 my ($self, $ch, $chars, $string)=@_;
                 unshift(@{$chars}, split("", "{1,}"));
             },
      '?' => sub {
                 my ($self, $ch, $chars, $string)=@_;
                 unshift(@{$chars}, split("", "{0,1}"));
             },
      '{' => sub {
                 my ($self, $ch, $chars, $string)=@_;
                 my ($n, $closed);
                 for ($n=0;$n<scalar(@{$chars});$n++) {
                     if ($chars->[$n] eq "}") {
                         $closed++;
                         last;
                     }
                 }
                 if ($closed) {
                     my $tmp;
                     while (defined($ch=shift(@{$chars})) && ($ch ne "}")) {
                         croak "'$ch' inside {} not supported" if ($ch!~/[\d,]/);
                         $tmp.=$ch;
                     }
                     if ($tmp=~/,/) {
                         if (my ($min,$max) = $tmp =~ /^(\d*),(\d*)$/) {
                             $min = 0 if (!length($min));
                             $max = $self->{'_max'} if (!length($max));
                             croak "bad range {$tmp}" if ($min>$max);
                             if ($min == $max) {
                                 $tmp = $min;
                             } else {
                                 $tmp = $min + int(rand($max - $min +1));
                             }
                         } else {
                             croak "malformed range {$tmp}";
                         }
                     }
                     if ($tmp) {
                         my $last=$string->[$#{$string}];
                         for ($n=0;$n<($tmp-1);$n++) {
                             push(@{$string}, $last);
                         }
                     } else {
                         pop(@{$string});
                     }
                 } else {
                     # { isn't closed, so treat it literally.
                     push(@{$string}, [$ch]);
                 }
             },
  );
  
  sub new {
      my $proto=shift;
      my $class=ref($proto) || $proto;
      my $self;
      $self={ %old_patterns }; # makes $self refer to a copy of %old_patterns
      my %args=();
      %args=@_ if (@_);
      if (defined($args{'max'})) {
          $self->{'_max'}=$args{'max'};
      } else {
          $self->{'_max'}=10;
      }
      return bless($self, $class);
  }
  
  # Returns a random string for each regular expression given as an
  # argument, or the strings concatenated when used in a scalar context.
  sub randregex {
      my $self=shift;
      croak "called without a reference" if (!ref($self));
  
      my @strings=();
  
      while (defined(my $pattern=shift)) {
          my $ch;
          my @string=();
          my $string='';
  
          # Split the characters in the pattern
          # up into a list for easier parsing.
          my @chars=split(//, $pattern);
  
          while (defined($ch=shift(@chars))) {
              if (defined($regch{$ch})) {
                  $regch{$ch}->($self, $ch, \@chars, \@string);
              } elsif ($ch=~/[\$\^\*\(\)\+\{\}\]\|\?]/) {
                  # At least some of these probably should have special meaning.
                  carp "'$ch' not implemented.  treating literally.";
                  push(@string, [$ch]);
              } else {
                  push(@string, [$ch]);
              }
          }
  
          foreach $ch (@string) {
              $string.=$ch->[int(rand(scalar(@{$ch})))];
          }
  
          push(@strings, $string);
      }
  
      return wantarray ? @strings : join("", @strings);
  }
  
  # For compatibility with an ancient version, please ignore...
  sub from_pattern {
      my $self=shift;
      croak "called without a reference" if (!ref($self));
  
      return $self->randpattern(@_);
  }
  
  sub randpattern {
      my $self=shift;
      croak "called without a reference" if (!ref($self));
  
      my @strings=();
  
      while (defined(my $pattern=shift)) {
          my $string='';
  
          for my $ch (split(//, $pattern)) {
              if (defined($self->{$ch})) {
                  $string.=$self->{$ch}->[int(rand(scalar(@{$self->{$ch}})))];
              } else {
                  croak qq(Unknown pattern character "$ch"!);
              }
          }
          push(@strings, $string);
      }
  
      return wantarray ? @strings : join("", @strings);
  }
  
  sub random_regex {
      my $foo=new String::Random;
      return $foo->randregex(@_);
  }
  
  sub random_string {
      my($pattern,@list)=@_;
  
      my($n,$foo);
  
      $foo=new String::Random;
  
      for ($n=0;$n<=$#list;$n++) {
          @{$foo->{$n}}=@{$list[$n]};
      }
  
      return $foo->randpattern($pattern);
  }
  
  1;
  __END__
  
  =encoding utf8
  
  =head1 NAME
  
  String::Random - Perl module to generate random strings based on a pattern
  
  =head1 SYNOPSIS
  
      use String::Random;
      my $string_gen = String::Random->new;
      print $string_gen->randregex('\d\d\d'); # Prints 3 random digits
      # Prints 3 random printable characters
      print $string_gen->randpattern("...");
  
  I<or>
  
      use String::Random qw(random_regex random_string);
      print random_regex('\d\d\d'); # Also prints 3 random digits
      print random_string("...");   # Also prints 3 random printable characters
  
  =head1 DESCRIPTION
  
  This module makes it trivial to generate random strings.
  
  As an example, let's say you are writing a script that needs to generate a
  random password for a user.  The relevant code might look something like
  this:
  
      use String::Random;
      my $pass = String::Random->new;
      print "Your password is ", $pass->randpattern("CCcc!ccn"), "\n";
  
  This would output something like this:
  
    Your password is UDwp$tj5
  
  B<NOTE!!!>: currently, String::Random uses Perl's built-in predictable random
  number generator so the passwords generated by it are insecure.
  
  If you are more comfortable dealing with regular expressions, the following
  code would have a similar result:
  
    use String::Random;
    my $pass = String::Random->new;
    print "Your password is ",
        $pass->randregex('[A-Z]{2}[a-z]{2}.[a-z]{2}\d'), "\n";
  
  =head2 Patterns
  
  The pre-defined patterns (for use with C<randpattern()> and C<random_pattern()>)
  are as follows:
  
    c        Any Latin lowercase character [a-z]
    C        Any Latin uppercase character [A-Z]
    n        Any digit [0-9]
    !        A punctuation character [~`!@$%^&*()-_+={}[]|\:;"'.<>?/#,]
    .        Any of the above
    s        A "salt" character [A-Za-z0-9./]
    b        Any binary data
  
  These can be modified, but if you need a different pattern it is better to
  create another pattern, possibly using one of the pre-defined as a base.
  For example, if you wanted a pattern C<A> that contained all upper and lower
  case letters (C<[A-Za-z]>), the following would work:
  
    my $gen = String::Random->new;
    $gen->{'A'} = [ 'A'..'Z', 'a'..'z' ];
  
  I<or>
  
    my $gen = String::Random->new;
    $gen->{'A'} = [ @{$gen->{'C'}}, @{$gen->{'c'}} ];
  
  The random_string function, described below, has an alternative interface
  for adding patterns.
  
  =head2 Methods
  
  =over 8
  
  =item new
  
  =item new max =E<gt> I<number>
  
  Create a new String::Random object.
  
  Optionally a parameter C<max> can be included to specify the maximum number
  of characters to return for C<*> and other regular expression patterns that
  do not return a fixed number of characters.
  
  =item randpattern LIST
  
  The randpattern method returns a random string based on the concatenation
  of all the pattern strings in the list.
  
  It will return a list of random strings corresponding to the pattern
  strings when used in list context.
  
  =item randregex LIST
  
  The randregex method returns a random string that will match the regular
  expression passed in the list argument.
  
  Please note that the arguments to randregex are not real regular
  expressions.  Only a small subset of regular expression syntax is actually
  supported.  So far, the following regular expression elements are
  supported:
  
    \w    Alphanumeric + "_".
    \d    Digits.
    \W    Printable characters other than those in \w.
    \D    Printable characters other than those in \d.
    .     Printable characters.
    []    Character classes.
    {}    Repetition.
    *     Same as {0,}.
    ?     Same as {0,1}.
    +     Same as {1,}.
  
  Regular expression support is still somewhat incomplete.  Currently special
  characters inside [] are not supported (with the exception of "-" to denote
  ranges of characters).  The parser doesn't care for spaces in the "regular
  expression" either.
  
  =back
  
  =head2 Functions
  
  =over 8
  
  =item random_string PATTERN,LIST
  
  =item random_string PATTERN
  
  When called with a single scalar argument, random_string returns a random
  string using that scalar as a pattern.  Optionally, references to lists
  containing other patterns can be passed to the function.  Those lists will
  be used for 0 through 9 in the pattern (meaning the maximum number of lists
  that can be passed is 10).  For example, the following code:
  
      print random_string("0101",
                          ["a", "b", "c"],
                          ["d", "e", "f"]), "\n";
  
  would print something like this:
  
      cebd
  
  =back
  
  =head1 BUGS
  
  This is Bug Free™ code.  (At least until somebody finds one…)
  
  Please report bugs here:
  
  L<https://rt.cpan.org/Public/Dist/Display.html?Name=String-Random> .
  
  =head1 AUTHOR
  
  Original Author: Steven Pritchard C<< steve@silug.org >>
  
  Now maintained by: Shlomi Fish ( L<http://www.shlomifish.org/> ).
  
  =head1 LICENSE
  
  This program is free software; you can redistribute it and/or modify it
  under the same terms as Perl itself.
  
  =head1 SEE ALSO
  
  perl(1).
  
  =cut
  
  # vi: set ai et:
STRING_RANDOM

$fatpacked{"Test/YAML.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'TEST_YAML';
  package Test::YAML;
  
  use Test::Base 0.47 -Base;
  use lib 'lib';
  
  our $VERSION = '0.88';
  
  our $YAML    = 'YAML';
  our @EXPORT  = qw(
      no_diff
      run_yaml_tests
      run_roundtrip_nyn roundtrip_nyn
      run_load_passes load_passes
      dumper Load Dump LoadFile DumpFile
      XXX
  );
  
  delimiters('===', '+++');
  
  sub Dump     () { YAML(Dump => @_)     }
  sub Load     () { YAML(Load => @_)     }
  sub DumpFile () { YAML(DumpFile => @_) }
  sub LoadFile () { YAML(LoadFile => @_) }
  
  sub YAML () {
      load_yaml_pm();
      my $meth = shift;
      my $code = $YAML->can($meth) or die "$YAML cannot do $meth";
      goto &$code;
  }
  
  sub load_yaml_pm {
      my $file = "$YAML.pm";
      $file =~ s{::}{/}g;
      require $file;
  }
  
  sub run_yaml_tests() {
      run {
          my $block = shift;
          &{_get_function($block)}($block) unless
            _skip_tests_for_now($block) or
            _skip_yaml_tests($block);
      };
  }
  
  sub run_roundtrip_nyn() {
      my @options = @_;
      run {
          my $block = shift;
          roundtrip_nyn($block, @options);
      };
  }
  
  sub roundtrip_nyn() {
      my $block = shift;
      my $option = shift || '';
      die "'perl' data section required"
          unless exists $block->{perl};
      my @values = eval $block->perl;
      die "roundtrip_nyn eval perl error: $@" if $@;
      my $config = $block->config || '';
      my $result = eval "$config; Dump(\@values)";
      die "roundtrip_nyn YAML::Dump error: $@" if $@;
      if (exists $block->{yaml}) {
          is $result, $block->yaml,
              $block->description . ' (n->y)';
      }
      else {
          pass $block->description . ' (n->y)';
      }
  
      return if exists $block->{no_round_trip} or
          not exists $block->{yaml};
  
      if ($option eq 'dumper') {
          is dumper(Load($block->yaml)), dumper(@values),
              $block->description . ' (y->n)';
      }
      else {
          is_deeply [Load($block->yaml)], [@values],
              $block->description . ' (y->n)';
      }
  }
  
  sub count_roundtrip_nyn() {
      my $block = shift or die "Bad call to count_roundtrip_nyn";
      return 1 if exists $block->{skip_this_for_now};
      my $count = 0;
      $count++ if exists $block->{perl};
      $count++ unless exists $block->{no_round_trip} or
          not exists $block->{yaml};
      die "Invalid test definition" unless $count;
      return $count;
  }
  
  sub run_load_passes() {
      run {
          my $block = shift;
          my $yaml = $block->yaml;
          eval { YAML(Load => $yaml) };
          is("$@", "");
      };
  }
  
  sub load_passes() {
      my $block = shift;
      my $yaml = $block->yaml;
      eval { YAML(Load => $yaml) };
      is "$@", "", $block->description;
  }
  
  sub count_load_passes() {1}
  
  sub dumper() {
      require Data::Dumper;
      $Data::Dumper::Sortkeys = 1;
      $Data::Dumper::Terse = 1;
      $Data::Dumper::Indent = 1;
      return Data::Dumper::Dumper(@_);
  }
  
  sub _count_tests() {
      my $block = shift or die "Bad call to _count_tests";
      no strict 'refs';
      &{'count_' . _get_function_name($block)}($block);
  }
  
  sub _get_function_name() {
      my $block = shift;
      return $block->function || 'roundtrip_nyn';
  }
  
  sub _get_function() {
      my $block = shift;
      no strict 'refs';
      \ &{_get_function_name($block)};
  }
  
  sub _skip_tests_for_now() {
      my $block = shift;
      if (exists $block->{skip_this_for_now}) {
          _skip_test(
              $block->description,
              _count_tests($block),
          );
          return 1;
      }
      return 0;
  }
  
  sub _skip_yaml_tests() {
      my $block = shift;
      if ($block->skip_unless_modules) {
          my @modules = split /[\s\,]+/, $block->skip_unless_modules;
          for my $module (@modules) {
              eval "require $module";
              if ($@) {
                  _skip_test(
                      "This test requires the '$module' module",
                      _count_tests($block),
                  );
                  return 1;
              }
          }
      }
      return 0;
  }
  
  sub _skip_test() {
      my ($message, $count) = @_;
      SKIP: {
          skip($message, $count);
      }
  }
  
  #-------------------------------------------------------------------------------
  package Test::YAML::Filter;
  
  use Test::Base::Filter ();
  
  our @ISA = 'Test::Base::Filter';
  
  sub yaml_dump {
      Test::YAML::Dump(@_);
  }
  
  sub yaml_load {
      Test::YAML::Load(@_);
  }
  
  sub Dump { goto &Test::YAML::Dump }
  sub Load { goto &Test::YAML::Load }
  sub DumpFile { goto &Test::YAML::DumpFile }
  sub LoadFile { goto &Test::YAML::LoadFile }
  
  sub yaml_load_or_fail {
      my ($result, $error, $warning) =
        $self->_yaml_load_result_error_warning(@_);
      return $error || $result;
  }
  
  sub yaml_load_error_or_warning {
      my ($result, $error, $warning) =
        $self->_yaml_load_result_error_warning(@_);
      return $error || $warning || '';
  }
  
  sub perl_eval_error_or_warning {
      my ($result, $error, $warning) =
        $self->_perl_eval_result_error_warning(@_);
      return $error || $warning || '';
  }
  
  sub _yaml_load_result_error_warning {
      $self->assert_scalar(@_);
      my $yaml = shift;
      my $warning = '';
      local $SIG{__WARN__} = sub { $warning = join '', @_ };
      my $result = eval {
          $self->yaml_load($yaml);
      };
      return ($result, $@, $warning);
  }
  
  sub _perl_eval_result_error_warning {
      $self->assert_scalar(@_);
      my $perl = shift;
      my $warning = '';
      local $SIG{__WARN__} = sub { $warning = join '', @_ };
      my $result = eval $perl;
      return ($result, $@, $warning);
  }
  
  1;
  
  __END__
  
  =encoding UTF-8
  
  =head1 NAME
  
  Test::YAML - Testing Module for YAML Implementations
  
  =head1 SYNOPSIS
  
      use Test::YAML tests => 1;
  
      pass;
  
  =head1 DESCRIPTION
  
  Test::YAML is a subclass of Test::Base with YAML specific support.
  
  =head1 AUTHOR
  
  Ingy döt Net <ingy@cpan.org>
  
  =head1 COPYRIGHT
  
  Copyright (c) 2006, 2011-2013. Ingy döt Net.
  
  This program is free software; you can redistribute it and/or modify it
  under the same terms as Perl itself.
  
  See L<http://www.perl.com/perl/misc/Artistic.html>
  
  =cut
TEST_YAML

$fatpacked{"Types/Serialiser.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'TYPES_SERIALISER';
  =head1 NAME
  
  Types::Serialiser - simple data types for common serialisation formats
  
  =encoding utf-8
  
  =head1 SYNOPSIS
  
  =head1 DESCRIPTION
  
  This module provides some extra datatypes that are used by common
  serialisation formats such as JSON or CBOR. The idea is to have a
  repository of simple/small constants and containers that can be shared by
  different implementations so they become interoperable between each other.
  
  =cut
  
  package Types::Serialiser;
  
  use common::sense; # required to suppress annoying warnings
  
  our $VERSION = '1.0';
  
  =head1 SIMPLE SCALAR CONSTANTS
  
  Simple scalar constants are values that are overloaded to act like simple
  Perl values, but have (class) type to differentiate them from normal Perl
  scalars. This is necessary because these have different representations in
  the serialisation formats.
  
  =head2 BOOLEANS (Types::Serialiser::Boolean class)
  
  This type has only two instances, true and false. A natural representation
  for these in Perl is C<1> and C<0>, but serialisation formats need to be
  able to differentiate between them and mere numbers.
  
  =over 4
  
  =item $Types::Serialiser::true, Types::Serialiser::true
  
  This value represents the "true" value. In most contexts is acts like
  the number C<1>. It is up to you whether you use the variable form
  (C<$Types::Serialiser::true>) or the constant form (C<Types::Serialiser::true>).
  
  The constant is represented as a reference to a scalar containing C<1> -
  implementations are allowed to directly test for this.
  
  =item $Types::Serialiser::false, Types::Serialiser::false
  
  This value represents the "false" value. In most contexts is acts like
  the number C<0>. It is up to you whether you use the variable form
  (C<$Types::Serialiser::false>) or the constant form (C<Types::Serialiser::false>).
  
  The constant is represented as a reference to a scalar containing C<0> -
  implementations are allowed to directly test for this.
  
  =item $is_bool = Types::Serialiser::is_bool $value
  
  Returns true iff the C<$value> is either C<$Types::Serialiser::true> or
  C<$Types::Serialiser::false>.
  
  For example, you could differentiate between a perl true value and a
  C<Types::Serialiser::true> by using this:
  
     $value && Types::Serialiser::is_bool $value
  
  =item $is_true = Types::Serialiser::is_true $value
  
  Returns true iff C<$value> is C<$Types::Serialiser::true>.
  
  =item $is_false = Types::Serialiser::is_false $value
  
  Returns false iff C<$value> is C<$Types::Serialiser::false>.
  
  =back
  
  =head2 ERROR (Types::Serialiser::Error class)
  
  This class has only a single instance, C<error>. It is used to signal
  an encoding or decoding error. In CBOR for example, and object that
  couldn't be encoded will be represented by a CBOR undefined value, which
  is represented by the error value in Perl.
  
  =over 4
  
  =item $Types::Serialiser::error, Types::Serialiser::error
  
  This value represents the "error" value. Accessing values of this type
  will throw an exception.
  
  The constant is represented as a reference to a scalar containing C<undef>
  - implementations are allowed to directly test for this.
  
  =item $is_error = Types::Serialiser::is_error $value
  
  Returns false iff C<$value> is C<$Types::Serialiser::error>.
  
  =back
  
  =cut
  
  BEGIN {
     # for historical reasons, and to avoid extra dependencies in JSON::PP,
     # we alias *Types::Serialiser::Boolean with JSON::PP::Boolean.
     package JSON::PP::Boolean;
  
     *Types::Serialiser::Boolean:: = *JSON::PP::Boolean::;
  }
  
  {
     # this must done before blessing to work around bugs
     # in perl < 5.18 (it seems to be fixed in 5.18).
     package Types::Serialiser::BooleanBase;
  
     use overload
        "0+"     => sub { ${$_[0]} },
        "++"     => sub { $_[0] = ${$_[0]} + 1 },
        "--"     => sub { $_[0] = ${$_[0]} - 1 },
        fallback => 1;
  
     @Types::Serialiser::Boolean::ISA = Types::Serialiser::BooleanBase::;
  }
  
  our $true  = do { bless \(my $dummy = 1), Types::Serialiser::Boolean:: };
  our $false = do { bless \(my $dummy = 0), Types::Serialiser::Boolean:: };
  our $error = do { bless \(my $dummy    ), Types::Serialiser::Error::   };
  
  sub true  () { $true  }
  sub false () { $false }
  sub error () { $error }
  
  sub is_bool  ($) {           UNIVERSAL::isa $_[0], Types::Serialiser::Boolean:: }
  sub is_true  ($) {  $_[0] && UNIVERSAL::isa $_[0], Types::Serialiser::Boolean:: }
  sub is_false ($) { !$_[0] && UNIVERSAL::isa $_[0], Types::Serialiser::Boolean:: }
  sub is_error ($) {           UNIVERSAL::isa $_[0], Types::Serialiser::Error::   }
  
  package Types::Serialiser::Error;
  
  sub error {
     require Carp;
     Carp::croak ("caught attempt to use the Types::Serialiser::error value");
  };
  
  use overload
     "0+"     => \&error,
     "++"     => \&error,
     "--"     => \&error,
     fallback => 1;
  
  =head1 NOTES FOR XS USERS
  
  The recommended way to detect whether a scalar is one of these objects
  is to check whether the stash is the C<Types::Serialiser::Boolean> or
  C<Types::Serialiser::Error> stash, and then follow the scalar reference to
  see if it's C<1> (true), C<0> (false) or C<undef> (error).
  
  While it is possible to use an isa test, directly comparing stash pointers
  is faster and guaranteed to work.
  
  For historical reasons, the C<Types::Serialiser::Boolean> stash is
  just an alias for C<JSON::PP::Boolean>. When printed, the classname
  with usually be C<JSON::PP::Boolean>, but isa tests and stash pointer
  comparison will normally work correctly (i.e. Types::Serialiser::true ISA
  JSON::PP::Boolean, but also ISA Types::Serialiser::Boolean).
  
  =head1 A GENERIC OBJECT SERIALIATION PROTOCOL
  
  This section explains the object serialisation protocol used by
  L<CBOR::XS>. It is meant to be generic enough to support any kind of
  generic object serialiser.
  
  This protocol is called "the Types::Serialiser object serialisation
  protocol".
  
  =head2 ENCODING
  
  When the encoder encounters an object that it cannot otherwise encode (for
  example, L<CBOR::XS> can encode a few special types itself, and will first
  attempt to use the special C<TO_CBOR> serialisation protocol), it will
  look up the C<FREEZE> method on the object.
  
  Note that the C<FREEZE> method will normally be called I<during> encoding,
  and I<MUST NOT> change the data structure that is being encoded in any
  way, or it might cause memory corruption or worse.
  
  If it exists, it will call it with two arguments: the object to serialise,
  and a constant string that indicates the name of the data model. For
  example L<CBOR::XS> uses C<CBOR>, and the L<JSON> and L<JSON::XS> modules
  (or any other JSON serialiser), would use C<JSON> as second argument.
  
  The C<FREEZE> method can then return zero or more values to identify the
  object instance. The serialiser is then supposed to encode the class name
  and all of these return values (which must be encodable in the format)
  using the relevant form for Perl objects. In CBOR for example, there is a
  registered tag number for encoded perl objects.
  
  The values that C<FREEZE> returns must be serialisable with the serialiser
  that calls it. Therefore, it is recommended to use simple types such as
  strings and numbers, and maybe array references and hashes (basically, the
  JSON data model). You can always use a more complex format for a specific
  data model by checking the second argument, the data model.
  
  The "data model" is not the same as the "data format" - the data model
  indicates what types and kinds of return values can be returned from
  C<FREEZE>. For example, in C<CBOR> it is permissible to return tagged CBOR
  values, while JSON does not support these at all, so C<JSON> would be a
  valid (but too limited) data model name for C<CBOR::XS>. similarly, a
  serialising format that supports more or less the same data model as JSON
  could use C<JSON> as data model without losing anything.
  
  =head2 DECODING
  
  When the decoder then encounters such an encoded perl object, it should
  look up the C<THAW> method on the stored classname, and invoke it with the
  classname, the constant string to identify the data model/data format, and
  all the return values returned by C<FREEZE>.
  
  =head2 EXAMPLES
  
  See the C<OBJECT SERIALISATION> section in the L<CBOR::XS> manpage for
  more details, an example implementation, and code examples.
  
  Here is an example C<FREEZE>/C<THAW> method pair:
  
     sub My::Object::FREEZE {
        my ($self, $model) = @_;
  
        ($self->{type}, $self->{id}, $self->{variant})
     }
  
     sub My::Object::THAW {
        my ($class, $model, $type, $id, $variant) = @_;
  
        $class->new (type => $type, id => $id, variant => $variant)
     }
  
  =head1 BUGS
  
  The use of L<overload> makes this module much heavier than it should be
  (on my system, this module: 4kB RSS, overload: 260kB RSS).
  
  =head1 SEE ALSO
  
  Currently, L<JSON::XS> and L<CBOR::XS> use these types.
  
  =head1 AUTHOR
  
   Marc Lehmann <schmorp@schmorp.de>
   http://home.schmorp.de/
  
  =cut
  
  1
  
TYPES_SERIALISER

$fatpacked{"Types/Serialiser/Error.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'TYPES_SERIALISER_ERROR';
  =head1 NAME
  
  Types::Serialiser::Error - dummy module for Types::Serialiser
  
  =head1 SYNOPSIS
  
   # do not "use" yourself
  
  =head1 DESCRIPTION
  
  This module exists only to provide overload resolution for Storable and
  similar modules that assume that class name equals module name. See
  L<Types::Serialiser> for more info about this class.
  
  =cut
  
  use Types::Serialiser ();
  
  =head1 AUTHOR
  
   Marc Lehmann <schmorp@schmorp.de>
   http://home.schmorp.de/
  
  =cut
  
  1
  
TYPES_SERIALISER_ERROR

$fatpacked{"URI.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI';
  package URI;
  
  use strict;
  use vars qw($VERSION);
  $VERSION = "1.60";
  
  use vars qw($ABS_REMOTE_LEADING_DOTS $ABS_ALLOW_RELATIVE_SCHEME $DEFAULT_QUERY_FORM_DELIMITER);
  
  my %implements;  # mapping from scheme to implementor class
  
  # Some "official" character classes
  
  use vars qw($reserved $mark $unreserved $uric $scheme_re);
  $reserved   = q(;/?:@&=+$,[]);
  $mark       = q(-_.!~*'());                                    #'; emacs
  $unreserved = "A-Za-z0-9\Q$mark\E";
  $uric       = quotemeta($reserved) . $unreserved . "%";
  
  $scheme_re  = '[a-zA-Z][a-zA-Z0-9.+\-]*';
  
  use Carp ();
  use URI::Escape ();
  
  use overload ('""'     => sub { ${$_[0]} },
                '=='     => sub { _obj_eq(@_) },
                '!='     => sub { !_obj_eq(@_) },
                fallback => 1,
               );
  
  # Check if two objects are the same object
  sub _obj_eq {
      return overload::StrVal($_[0]) eq overload::StrVal($_[1]);
  }
  
  sub new
  {
      my($class, $uri, $scheme) = @_;
  
      $uri = defined ($uri) ? "$uri" : "";   # stringify
      # Get rid of potential wrapping
      $uri =~ s/^<(?:URL:)?(.*)>$/$1/;  # 
      $uri =~ s/^"(.*)"$/$1/;
      $uri =~ s/^\s+//;
      $uri =~ s/\s+$//;
  
      my $impclass;
      if ($uri =~ m/^($scheme_re):/so) {
  	$scheme = $1;
      }
      else {
  	if (($impclass = ref($scheme))) {
  	    $scheme = $scheme->scheme;
  	}
  	elsif ($scheme && $scheme =~ m/^($scheme_re)(?::|$)/o) {
  	    $scheme = $1;
          }
      }
      $impclass ||= implementor($scheme) ||
  	do {
  	    require URI::_foreign;
  	    $impclass = 'URI::_foreign';
  	};
  
      return $impclass->_init($uri, $scheme);
  }
  
  
  sub new_abs
  {
      my($class, $uri, $base) = @_;
      $uri = $class->new($uri, $base);
      $uri->abs($base);
  }
  
  
  sub _init
  {
      my $class = shift;
      my($str, $scheme) = @_;
      # find all funny characters and encode the bytes.
      $str = $class->_uric_escape($str);
      $str = "$scheme:$str" unless $str =~ /^$scheme_re:/o ||
                                   $class->_no_scheme_ok;
      my $self = bless \$str, $class;
      $self;
  }
  
  
  sub _uric_escape
  {
      my($class, $str) = @_;
      $str =~ s*([^$uric\#])* URI::Escape::escape_char($1) *ego;
      utf8::downgrade($str);
      return $str;
  }
  
  
  sub implementor
  {
      my($scheme, $impclass) = @_;
      if (!$scheme || $scheme !~ /\A$scheme_re\z/o) {
  	require URI::_generic;
  	return "URI::_generic";
      }
  
      $scheme = lc($scheme);
  
      if ($impclass) {
  	# Set the implementor class for a given scheme
          my $old = $implements{$scheme};
          $impclass->_init_implementor($scheme);
          $implements{$scheme} = $impclass;
          return $old;
      }
  
      my $ic = $implements{$scheme};
      return $ic if $ic;
  
      # scheme not yet known, look for internal or
      # preloaded (with 'use') implementation
      $ic = "URI::$scheme";  # default location
  
      # turn scheme into a valid perl identifier by a simple transformation...
      $ic =~ s/\+/_P/g;
      $ic =~ s/\./_O/g;
      $ic =~ s/\-/_/g;
  
      no strict 'refs';
      # check we actually have one for the scheme:
      unless (@{"${ic}::ISA"}) {
          # Try to load it
          eval "require $ic";
          die $@ if $@ && $@ !~ /Can\'t locate.*in \@INC/;
          return unless @{"${ic}::ISA"};
      }
  
      $ic->_init_implementor($scheme);
      $implements{$scheme} = $ic;
      $ic;
  }
  
  
  sub _init_implementor
  {
      my($class, $scheme) = @_;
      # Remember that one implementor class may actually
      # serve to implement several URI schemes.
  }
  
  
  sub clone
  {
      my $self = shift;
      my $other = $$self;
      bless \$other, ref $self;
  }
  
  
  sub _no_scheme_ok { 0 }
  
  sub _scheme
  {
      my $self = shift;
  
      unless (@_) {
  	return unless $$self =~ /^($scheme_re):/o;
  	return $1;
      }
  
      my $old;
      my $new = shift;
      if (defined($new) && length($new)) {
  	Carp::croak("Bad scheme '$new'") unless $new =~ /^$scheme_re$/o;
  	$old = $1 if $$self =~ s/^($scheme_re)://o;
  	my $newself = URI->new("$new:$$self");
  	$$self = $$newself; 
  	bless $self, ref($newself);
      }
      else {
  	if ($self->_no_scheme_ok) {
  	    $old = $1 if $$self =~ s/^($scheme_re)://o;
  	    Carp::carp("Oops, opaque part now look like scheme")
  		if $^W && $$self =~ m/^$scheme_re:/o
  	}
  	else {
  	    $old = $1 if $$self =~ m/^($scheme_re):/o;
  	}
      }
  
      return $old;
  }
  
  sub scheme
  {
      my $scheme = shift->_scheme(@_);
      return unless defined $scheme;
      lc($scheme);
  }
  
  
  sub opaque
  {
      my $self = shift;
  
      unless (@_) {
  	$$self =~ /^(?:$scheme_re:)?([^\#]*)/o or die;
  	return $1;
      }
  
      $$self =~ /^($scheme_re:)?    # optional scheme
  	        ([^\#]*)          # opaque
                  (\#.*)?           # optional fragment
                $/sx or die;
  
      my $old_scheme = $1;
      my $old_opaque = $2;
      my $old_frag   = $3;
  
      my $new_opaque = shift;
      $new_opaque = "" unless defined $new_opaque;
      $new_opaque =~ s/([^$uric])/ URI::Escape::escape_char($1)/ego;
      utf8::downgrade($new_opaque);
  
      $$self = defined($old_scheme) ? $old_scheme : "";
      $$self .= $new_opaque;
      $$self .= $old_frag if defined $old_frag;
  
      $old_opaque;
  }
  
  *path = \&opaque;  # alias
  
  
  sub fragment
  {
      my $self = shift;
      unless (@_) {
  	return unless $$self =~ /\#(.*)/s;
  	return $1;
      }
  
      my $old;
      $old = $1 if $$self =~ s/\#(.*)//s;
  
      my $new_frag = shift;
      if (defined $new_frag) {
  	$new_frag =~ s/([^$uric])/ URI::Escape::escape_char($1) /ego;
  	utf8::downgrade($new_frag);
  	$$self .= "#$new_frag";
      }
      $old;
  }
  
  
  sub as_string
  {
      my $self = shift;
      $$self;
  }
  
  
  sub as_iri
  {
      my $self = shift;
      my $str = $$self;
      if ($str =~ s/%([89a-fA-F][0-9a-fA-F])/chr(hex($1))/eg) {
  	# All this crap because the more obvious:
  	#
  	#   Encode::decode("UTF-8", $str, sub { sprintf "%%%02X", shift })
  	#
  	# doesn't work before Encode 2.39.  Wait for a standard release
  	# to bundle that version.
  
  	require Encode;
  	my $enc = Encode::find_encoding("UTF-8");
  	my $u = "";
  	while (length $str) {
  	    $u .= $enc->decode($str, Encode::FB_QUIET());
  	    if (length $str) {
  		# escape next char
  		$u .= URI::Escape::escape_char(substr($str, 0, 1, ""));
  	    }
  	}
  	$str = $u;
      }
      return $str;
  }
  
  
  sub canonical
  {
      # Make sure scheme is lowercased, that we don't escape unreserved chars,
      # and that we use upcase escape sequences.
  
      my $self = shift;
      my $scheme = $self->_scheme || "";
      my $uc_scheme = $scheme =~ /[A-Z]/;
      my $esc = $$self =~ /%[a-fA-F0-9]{2}/;
      return $self unless $uc_scheme || $esc;
  
      my $other = $self->clone;
      if ($uc_scheme) {
  	$other->_scheme(lc $scheme);
      }
      if ($esc) {
  	$$other =~ s{%([0-9a-fA-F]{2})}
  	            { my $a = chr(hex($1));
                        $a =~ /^[$unreserved]\z/o ? $a : "%\U$1"
                      }ge;
      }
      return $other;
  }
  
  # Compare two URIs, subclasses will provide a more correct implementation
  sub eq {
      my($self, $other) = @_;
      $self  = URI->new($self, $other) unless ref $self;
      $other = URI->new($other, $self) unless ref $other;
      ref($self) eq ref($other) &&                # same class
  	$self->canonical->as_string eq $other->canonical->as_string;
  }
  
  # generic-URI transformation methods
  sub abs { $_[0]; }
  sub rel { $_[0]; }
  
  sub secure { 0 }
  
  # help out Storable
  sub STORABLE_freeze {
         my($self, $cloning) = @_;
         return $$self;
  }
  
  sub STORABLE_thaw {
         my($self, $cloning, $str) = @_;
         $$self = $str;
  }
  
  1;
  
  __END__
  
  =head1 NAME
  
  URI - Uniform Resource Identifiers (absolute and relative)
  
  =head1 SYNOPSIS
  
   $u1 = URI->new("http://www.perl.com");
   $u2 = URI->new("foo", "http");
   $u3 = $u2->abs($u1);
   $u4 = $u3->clone;
   $u5 = URI->new("HTTP://WWW.perl.com:80")->canonical;
  
   $str = $u->as_string;
   $str = "$u";
  
   $scheme = $u->scheme;
   $opaque = $u->opaque;
   $path   = $u->path;
   $frag   = $u->fragment;
  
   $u->scheme("ftp");
   $u->host("ftp.perl.com");
   $u->path("cpan/");
  
  =head1 DESCRIPTION
  
  This module implements the C<URI> class.  Objects of this class
  represent "Uniform Resource Identifier references" as specified in RFC
  2396 (and updated by RFC 2732).
  
  A Uniform Resource Identifier is a compact string of characters that
  identifies an abstract or physical resource.  A Uniform Resource
  Identifier can be further classified as either a Uniform Resource Locator
  (URL) or a Uniform Resource Name (URN).  The distinction between URL
  and URN does not matter to the C<URI> class interface. A
  "URI-reference" is a URI that may have additional information attached
  in the form of a fragment identifier.
  
  An absolute URI reference consists of three parts:  a I<scheme>, a
  I<scheme-specific part> and a I<fragment> identifier.  A subset of URI
  references share a common syntax for hierarchical namespaces.  For
  these, the scheme-specific part is further broken down into
  I<authority>, I<path> and I<query> components.  These URIs can also
  take the form of relative URI references, where the scheme (and
  usually also the authority) component is missing, but implied by the
  context of the URI reference.  The three forms of URI reference
  syntax are summarized as follows:
  
    <scheme>:<scheme-specific-part>#<fragment>
    <scheme>://<authority><path>?<query>#<fragment>
    <path>?<query>#<fragment>
  
  The components into which a URI reference can be divided depend on the
  I<scheme>.  The C<URI> class provides methods to get and set the
  individual components.  The methods available for a specific
  C<URI> object depend on the scheme.
  
  =head1 CONSTRUCTORS
  
  The following methods construct new C<URI> objects:
  
  =over 4
  
  =item $uri = URI->new( $str )
  
  =item $uri = URI->new( $str, $scheme )
  
  Constructs a new URI object.  The string
  representation of a URI is given as argument, together with an optional
  scheme specification.  Common URI wrappers like "" and <>, as well as
  leading and trailing white space, are automatically removed from
  the $str argument before it is processed further.
  
  The constructor determines the scheme, maps this to an appropriate
  URI subclass, constructs a new object of that class and returns it.
  
  The $scheme argument is only used when $str is a
  relative URI.  It can be either a simple string that
  denotes the scheme, a string containing an absolute URI reference, or
  an absolute C<URI> object.  If no $scheme is specified for a relative
  URI $str, then $str is simply treated as a generic URI (no scheme-specific
  methods available).
  
  The set of characters available for building URI references is
  restricted (see L<URI::Escape>).  Characters outside this set are
  automatically escaped by the URI constructor.
  
  =item $uri = URI->new_abs( $str, $base_uri )
  
  Constructs a new absolute URI object.  The $str argument can
  denote a relative or absolute URI.  If relative, then it is
  absolutized using $base_uri as base. The $base_uri must be an absolute
  URI.
  
  =item $uri = URI::file->new( $filename )
  
  =item $uri = URI::file->new( $filename, $os )
  
  Constructs a new I<file> URI from a file name.  See L<URI::file>.
  
  =item $uri = URI::file->new_abs( $filename )
  
  =item $uri = URI::file->new_abs( $filename, $os )
  
  Constructs a new absolute I<file> URI from a file name.  See
  L<URI::file>.
  
  =item $uri = URI::file->cwd
  
  Returns the current working directory as a I<file> URI.  See
  L<URI::file>.
  
  =item $uri->clone
  
  Returns a copy of the $uri.
  
  =back
  
  =head1 COMMON METHODS
  
  The methods described in this section are available for all C<URI>
  objects.
  
  Methods that give access to components of a URI always return the
  old value of the component.  The value returned is C<undef> if the
  component was not present.  There is generally a difference between a
  component that is empty (represented as C<"">) and a component that is
  missing (represented as C<undef>).  If an accessor method is given an
  argument, it updates the corresponding component in addition to
  returning the old value of the component.  Passing an undefined
  argument removes the component (if possible).  The description of
  each accessor method indicates whether the component is passed as
  an escaped (percent-encoded) or an unescaped string.  A component that can be further
  divided into sub-parts are usually passed escaped, as unescaping might
  change its semantics.
  
  The common methods available for all URI are:
  
  =over 4
  
  =item $uri->scheme
  
  =item $uri->scheme( $new_scheme )
  
  Sets and returns the scheme part of the $uri.  If the $uri is
  relative, then $uri->scheme returns C<undef>.  If called with an
  argument, it updates the scheme of $uri, possibly changing the
  class of $uri, and returns the old scheme value.  The method croaks
  if the new scheme name is illegal; a scheme name must begin with a
  letter and must consist of only US-ASCII letters, numbers, and a few
  special marks: ".", "+", "-".  This restriction effectively means
  that the scheme must be passed unescaped.  Passing an undefined
  argument to the scheme method makes the URI relative (if possible).
  
  Letter case does not matter for scheme names.  The string
  returned by $uri->scheme is always lowercase.  If you want the scheme
  just as it was written in the URI in its original case,
  you can use the $uri->_scheme method instead.
  
  =item $uri->opaque
  
  =item $uri->opaque( $new_opaque )
  
  Sets and returns the scheme-specific part of the $uri
  (everything between the scheme and the fragment)
  as an escaped string.
  
  =item $uri->path
  
  =item $uri->path( $new_path )
  
  Sets and returns the same value as $uri->opaque unless the URI
  supports the generic syntax for hierarchical namespaces.
  In that case the generic method is overridden to set and return
  the part of the URI between the I<host name> and the I<fragment>.
  
  =item $uri->fragment
  
  =item $uri->fragment( $new_frag )
  
  Returns the fragment identifier of a URI reference
  as an escaped string.
  
  =item $uri->as_string
  
  Returns a URI object to a plain ASCII string.  URI objects are
  also converted to plain strings automatically by overloading.  This
  means that $uri objects can be used as plain strings in most Perl
  constructs.
  
  =item $uri->as_iri
  
  Returns a Unicode string representing the URI.  Escaped UTF-8 sequences
  representing non-ASCII characters are turned into their corresponding Unicode
  code point.
  
  =item $uri->canonical
  
  Returns a normalized version of the URI.  The rules
  for normalization are scheme-dependent.  They usually involve
  lowercasing the scheme and Internet host name components,
  removing the explicit port specification if it matches the default port,
  uppercasing all escape sequences, and unescaping octets that can be
  better represented as plain characters.
  
  For efficiency reasons, if the $uri is already in normalized form,
  then a reference to it is returned instead of a copy.
  
  =item $uri->eq( $other_uri )
  
  =item URI::eq( $first_uri, $other_uri )
  
  Tests whether two URI references are equal.  URI references
  that normalize to the same string are considered equal.  The method
  can also be used as a plain function which can also test two string
  arguments.
  
  If you need to test whether two C<URI> object references denote the
  same object, use the '==' operator.
  
  =item $uri->abs( $base_uri )
  
  Returns an absolute URI reference.  If $uri is already
  absolute, then a reference to it is simply returned.  If the $uri
  is relative, then a new absolute URI is constructed by combining the
  $uri and the $base_uri, and returned.
  
  =item $uri->rel( $base_uri )
  
  Returns a relative URI reference if it is possible to
  make one that denotes the same resource relative to $base_uri.
  If not, then $uri is simply returned.
  
  =item $uri->secure
  
  Returns a TRUE value if the URI is considered to point to a resource on
  a secure channel, such as an SSL or TLS encrypted one.
  
  =back
  
  =head1 GENERIC METHODS
  
  The following methods are available to schemes that use the
  common/generic syntax for hierarchical namespaces.  The descriptions of
  schemes below indicate which these are.  Unknown schemes are
  assumed to support the generic syntax, and therefore the following
  methods:
  
  =over 4
  
  =item $uri->authority
  
  =item $uri->authority( $new_authority )
  
  Sets and returns the escaped authority component
  of the $uri.
  
  =item $uri->path
  
  =item $uri->path( $new_path )
  
  Sets and returns the escaped path component of
  the $uri (the part between the host name and the query or fragment).
  The path can never be undefined, but it can be the empty string.
  
  =item $uri->path_query
  
  =item $uri->path_query( $new_path_query )
  
  Sets and returns the escaped path and query
  components as a single entity.  The path and the query are
  separated by a "?" character, but the query can itself contain "?".
  
  =item $uri->path_segments
  
  =item $uri->path_segments( $segment, ... )
  
  Sets and returns the path.  In a scalar context, it returns
  the same value as $uri->path.  In a list context, it returns the
  unescaped path segments that make up the path.  Path segments that
  have parameters are returned as an anonymous array.  The first element
  is the unescaped path segment proper;  subsequent elements are escaped
  parameter strings.  Such an anonymous array uses overloading so it can
  be treated as a string too, but this string does not include the
  parameters.
  
  Note that absolute paths have the empty string as their first
  I<path_segment>, i.e. the I<path> C</foo/bar> have 3
  I<path_segments>; "", "foo" and "bar".
  
  =item $uri->query
  
  =item $uri->query( $new_query )
  
  Sets and returns the escaped query component of
  the $uri.
  
  =item $uri->query_form
  
  =item $uri->query_form( $key1 => $val1, $key2 => $val2, ... )
  
  =item $uri->query_form( $key1 => $val1, $key2 => $val2, ..., $delim )
  
  =item $uri->query_form( \@key_value_pairs )
  
  =item $uri->query_form( \@key_value_pairs, $delim )
  
  =item $uri->query_form( \%hash )
  
  =item $uri->query_form( \%hash, $delim )
  
  Sets and returns query components that use the
  I<application/x-www-form-urlencoded> format.  Key/value pairs are
  separated by "&", and the key is separated from the value by a "="
  character.
  
  The form can be set either by passing separate key/value pairs, or via
  an array or hash reference.  Passing an empty array or an empty hash
  removes the query component, whereas passing no arguments at all leaves
  the component unchanged.  The order of keys is undefined if a hash
  reference is passed.  The old value is always returned as a list of
  separate key/value pairs.  Assigning this list to a hash is unwise as
  the keys returned might repeat.
  
  The values passed when setting the form can be plain strings or
  references to arrays of strings.  Passing an array of values has the
  same effect as passing the key repeatedly with one value at a time.
  All the following statements have the same effect:
  
      $uri->query_form(foo => 1, foo => 2);
      $uri->query_form(foo => [1, 2]);
      $uri->query_form([ foo => 1, foo => 2 ]);
      $uri->query_form([ foo => [1, 2] ]);
      $uri->query_form({ foo => [1, 2] });
  
  The $delim parameter can be passed as ";" to force the key/value pairs
  to be delimited by ";" instead of "&" in the query string.  This
  practice is often recommended for URLs embedded in HTML or XML
  documents as this avoids the trouble of escaping the "&" character.
  You might also set the $URI::DEFAULT_QUERY_FORM_DELIMITER variable to
  ";" for the same global effect.
  
  The C<URI::QueryParam> module can be loaded to add further methods to
  manipulate the form of a URI.  See L<URI::QueryParam> for details.
  
  =item $uri->query_keywords
  
  =item $uri->query_keywords( $keywords, ... )
  
  =item $uri->query_keywords( \@keywords )
  
  Sets and returns query components that use the
  keywords separated by "+" format.
  
  The keywords can be set either by passing separate keywords directly
  or by passing a reference to an array of keywords.  Passing an empty
  array removes the query component, whereas passing no arguments at
  all leaves the component unchanged.  The old value is always returned
  as a list of separate words.
  
  =back
  
  =head1 SERVER METHODS
  
  For schemes where the I<authority> component denotes an Internet host,
  the following methods are available in addition to the generic
  methods.
  
  =over 4
  
  =item $uri->userinfo
  
  =item $uri->userinfo( $new_userinfo )
  
  Sets and returns the escaped userinfo part of the
  authority component.
  
  For some schemes this is a user name and a password separated by
  a colon.  This practice is not recommended. Embedding passwords in
  clear text (such as URI) has proven to be a security risk in almost
  every case where it has been used.
  
  =item $uri->host
  
  =item $uri->host( $new_host )
  
  Sets and returns the unescaped hostname.
  
  If the $new_host string ends with a colon and a number, then this
  number also sets the port.
  
  For IPv6 addresses the brackets around the raw address is removed in the return
  value from $uri->host.  When setting the host attribute to an IPv6 address you
  can use a raw address or one enclosed in brackets.  The address needs to be
  enclosed in brackets if you want to pass in a new port value as well.
  
  =item $uri->ihost
  
  Returns the host in Unicode form.  Any IDNA A-labels are turned into U-labels.
  
  =item $uri->port
  
  =item $uri->port( $new_port )
  
  Sets and returns the port.  The port is a simple integer
  that should be greater than 0.
  
  If a port is not specified explicitly in the URI, then the URI scheme's default port
  is returned. If you don't want the default port
  substituted, then you can use the $uri->_port method instead.
  
  =item $uri->host_port
  
  =item $uri->host_port( $new_host_port )
  
  Sets and returns the host and port as a single
  unit.  The returned value includes a port, even if it matches the
  default port.  The host part and the port part are separated by a
  colon: ":".
  
  For IPv6 addresses the bracketing is preserved; thus
  URI->new("http://[::1]/")->host_port returns "[::1]:80".  Contrast this with
  $uri->host which will remove the brackets.
  
  =item $uri->default_port
  
  Returns the default port of the URI scheme to which $uri
  belongs.  For I<http> this is the number 80, for I<ftp> this
  is the number 21, etc.  The default port for a scheme can not be
  changed.
  
  =back
  
  =head1 SCHEME-SPECIFIC SUPPORT
  
  Scheme-specific support is provided for the following URI schemes.  For C<URI>
  objects that do not belong to one of these, you can only use the common and
  generic methods.
  
  =over 4
  
  =item B<data>:
  
  The I<data> URI scheme is specified in RFC 2397.  It allows inclusion
  of small data items as "immediate" data, as if it had been included
  externally.
  
  C<URI> objects belonging to the data scheme support the common methods
  and two new methods to access their scheme-specific components:
  $uri->media_type and $uri->data.  See L<URI::data> for details.
  
  =item B<file>:
  
  An old specification of the I<file> URI scheme is found in RFC 1738.
  A new RFC 2396 based specification in not available yet, but file URI
  references are in common use.
  
  C<URI> objects belonging to the file scheme support the common and
  generic methods.  In addition, they provide two methods for mapping file URIs
  back to local file names; $uri->file and $uri->dir.  See L<URI::file>
  for details.
  
  =item B<ftp>:
  
  An old specification of the I<ftp> URI scheme is found in RFC 1738.  A
  new RFC 2396 based specification in not available yet, but ftp URI
  references are in common use.
  
  C<URI> objects belonging to the ftp scheme support the common,
  generic and server methods.  In addition, they provide two methods for
  accessing the userinfo sub-components: $uri->user and $uri->password.
  
  =item B<gopher>:
  
  The I<gopher> URI scheme is specified in
  <draft-murali-url-gopher-1996-12-04> and will hopefully be available
  as a RFC 2396 based specification.
  
  C<URI> objects belonging to the gopher scheme support the common,
  generic and server methods. In addition, they support some methods for
  accessing gopher-specific path components: $uri->gopher_type,
  $uri->selector, $uri->search, $uri->string.
  
  =item B<http>:
  
  The I<http> URI scheme is specified in RFC 2616.
  The scheme is used to reference resources hosted by HTTP servers.
  
  C<URI> objects belonging to the http scheme support the common,
  generic and server methods.
  
  =item B<https>:
  
  The I<https> URI scheme is a Netscape invention which is commonly
  implemented.  The scheme is used to reference HTTP servers through SSL
  connections.  Its syntax is the same as http, but the default
  port is different.
  
  =item B<ldap>:
  
  The I<ldap> URI scheme is specified in RFC 2255.  LDAP is the
  Lightweight Directory Access Protocol.  An ldap URI describes an LDAP
  search operation to perform to retrieve information from an LDAP
  directory.
  
  C<URI> objects belonging to the ldap scheme support the common,
  generic and server methods as well as ldap-specific methods: $uri->dn,
  $uri->attributes, $uri->scope, $uri->filter, $uri->extensions.  See
  L<URI::ldap> for details.
  
  =item B<ldapi>:
  
  Like the I<ldap> URI scheme, but uses a UNIX domain socket.  The
  server methods are not supported, and the local socket path is
  available as $uri->un_path.  The I<ldapi> scheme is used by the
  OpenLDAP package.  There is no real specification for it, but it is
  mentioned in various OpenLDAP manual pages.
  
  =item B<ldaps>:
  
  Like the I<ldap> URI scheme, but uses an SSL connection.  This
  scheme is deprecated, as the preferred way is to use the I<start_tls>
  mechanism.
  
  =item B<mailto>:
  
  The I<mailto> URI scheme is specified in RFC 2368.  The scheme was
  originally used to designate the Internet mailing address of an
  individual or service.  It has (in RFC 2368) been extended to allow
  setting of other mail header fields and the message body.
  
  C<URI> objects belonging to the mailto scheme support the common
  methods and the generic query methods.  In addition, they support the
  following mailto-specific methods: $uri->to, $uri->headers.
  
  Note that the "foo@example.com" part of a mailto is I<not> the
  C<userinfo> and C<host> but instead the C<path>.  This allows a
  mailto URI to contain multiple comma separated email addresses.
  
  =item B<mms>:
  
  The I<mms> URL specification can be found at L<http://sdp.ppona.com/>.
  C<URI> objects belonging to the mms scheme support the common,
  generic, and server methods, with the exception of userinfo and
  query-related sub-components.
  
  =item B<news>:
  
  The I<news>, I<nntp> and I<snews> URI schemes are specified in
  <draft-gilman-news-url-01> and will hopefully be available as an RFC
  2396 based specification soon.
  
  C<URI> objects belonging to the news scheme support the common,
  generic and server methods.  In addition, they provide some methods to
  access the path: $uri->group and $uri->message.
  
  =item B<nntp>:
  
  See I<news> scheme.
  
  =item B<pop>:
  
  The I<pop> URI scheme is specified in RFC 2384. The scheme is used to
  reference a POP3 mailbox.
  
  C<URI> objects belonging to the pop scheme support the common, generic
  and server methods.  In addition, they provide two methods to access the
  userinfo components: $uri->user and $uri->auth
  
  =item B<rlogin>:
  
  An old specification of the I<rlogin> URI scheme is found in RFC
  1738. C<URI> objects belonging to the rlogin scheme support the
  common, generic and server methods.
  
  =item B<rtsp>:
  
  The I<rtsp> URL specification can be found in section 3.2 of RFC 2326.
  C<URI> objects belonging to the rtsp scheme support the common,
  generic, and server methods, with the exception of userinfo and
  query-related sub-components.
  
  =item B<rtspu>:
  
  The I<rtspu> URI scheme is used to talk to RTSP servers over UDP
  instead of TCP.  The syntax is the same as rtsp.
  
  =item B<rsync>:
  
  Information about rsync is available from L<http://rsync.samba.org/>.
  C<URI> objects belonging to the rsync scheme support the common,
  generic and server methods.  In addition, they provide methods to
  access the userinfo sub-components: $uri->user and $uri->password.
  
  =item B<sip>:
  
  The I<sip> URI specification is described in sections 19.1 and 25
  of RFC 3261.  C<URI> objects belonging to the sip scheme support the
  common, generic, and server methods with the exception of path related
  sub-components.  In addition, they provide two methods to get and set
  I<sip> parameters: $uri->params_form and $uri->params.
  
  =item B<sips>:
  
  See I<sip> scheme.  Its syntax is the same as sip, but the default
  port is different.
  
  =item B<snews>:
  
  See I<news> scheme.  Its syntax is the same as news, but the default
  port is different.
  
  =item B<telnet>:
  
  An old specification of the I<telnet> URI scheme is found in RFC
  1738. C<URI> objects belonging to the telnet scheme support the
  common, generic and server methods.
  
  =item B<tn3270>:
  
  These URIs are used like I<telnet> URIs but for connections to IBM
  mainframes.  C<URI> objects belonging to the tn3270 scheme support the
  common, generic and server methods.
  
  =item B<ssh>:
  
  Information about ssh is available at L<http://www.openssh.com/>.
  C<URI> objects belonging to the ssh scheme support the common,
  generic and server methods. In addition, they provide methods to
  access the userinfo sub-components: $uri->user and $uri->password.
  
  =item B<urn>:
  
  The syntax of Uniform Resource Names is specified in RFC 2141.  C<URI>
  objects belonging to the urn scheme provide the common methods, and also the
  methods $uri->nid and $uri->nss, which return the Namespace Identifier
  and the Namespace-Specific String respectively.
  
  The Namespace Identifier basically works like the Scheme identifier of
  URIs, and further divides the URN namespace.  Namespace Identifier
  assignments are maintained at
  L<http://www.iana.org/assignments/urn-namespaces>.
  
  Letter case is not significant for the Namespace Identifier.  It is
  always returned in lower case by the $uri->nid method.  The $uri->_nid
  method can be used if you want it in its original case.
  
  =item B<urn>:B<isbn>:
  
  The C<urn:isbn:> namespace contains International Standard Book
  Numbers (ISBNs) and is described in RFC 3187.  A C<URI> object belonging
  to this namespace has the following extra methods (if the
  Business::ISBN module is available): $uri->isbn,
  $uri->isbn_publisher_code, $uri->isbn_group_code (formerly isbn_country_code,
  which is still supported by issues a deprecation warning), $uri->isbn_as_ean.
  
  =item B<urn>:B<oid>:
  
  The C<urn:oid:> namespace contains Object Identifiers (OIDs) and is
  described in RFC 3061.  An object identifier consists of sequences of digits
  separated by dots.  A C<URI> object belonging to this namespace has an
  additional method called $uri->oid that can be used to get/set the oid
  value.  In a list context, oid numbers are returned as separate elements.
  
  =back
  
  =head1 CONFIGURATION VARIABLES
  
  The following configuration variables influence how the class and its
  methods behave:
  
  =over 4
  
  =item $URI::ABS_ALLOW_RELATIVE_SCHEME
  
  Some older parsers used to allow the scheme name to be present in the
  relative URL if it was the same as the base URL scheme.  RFC 2396 says
  that this should be avoided, but you can enable this old behaviour by
  setting the $URI::ABS_ALLOW_RELATIVE_SCHEME variable to a TRUE value.
  The difference is demonstrated by the following examples:
  
    URI->new("http:foo")->abs("http://host/a/b")
        ==>  "http:foo"
  
    local $URI::ABS_ALLOW_RELATIVE_SCHEME = 1;
    URI->new("http:foo")->abs("http://host/a/b")
        ==>  "http:/host/a/foo"
  
  
  =item $URI::ABS_REMOTE_LEADING_DOTS
  
  You can also have the abs() method ignore excess ".."
  segments in the relative URI by setting $URI::ABS_REMOTE_LEADING_DOTS
  to a TRUE value.  The difference is demonstrated by the following
  examples:
  
    URI->new("../../../foo")->abs("http://host/a/b")
        ==> "http://host/../../foo"
  
    local $URI::ABS_REMOTE_LEADING_DOTS = 1;
    URI->new("../../../foo")->abs("http://host/a/b")
        ==> "http://host/foo"
  
  =item $URI::DEFAULT_QUERY_FORM_DELIMITER
  
  This value can be set to ";" to have the query form C<key=value> pairs
  delimited by ";" instead of "&" which is the default.
  
  =back
  
  =head1 BUGS
  
  There are some things that are not quite right:
  
  =over
  
  =item *
  
  Using regexp variables like $1 directly as arguments to the URI accessor methods
  does not work too well with current perl implementations.  I would argue
  that this is actually a bug in perl.  The workaround is to quote
  them. Example:
  
     /(...)/ || die;
     $u->query("$1");
  
  
  =item *
  
  The escaping (percent encoding) of chars in the 128 .. 255 range passed to the
  URI constructor or when setting URI parts using the accessor methods depend on
  the state of the internal UTF8 flag (see utf8::is_utf8) of the string passed.
  If the UTF8 flag is set the UTF-8 encoded version of the character is percent
  encoded.  If the UTF8 flag isn't set the Latin-1 version (byte) of the
  character is percent encoded.  This basically exposes the internal encoding of
  Perl strings.
  
  =back
  
  =head1 PARSING URIs WITH REGEXP
  
  As an alternative to this module, the following (official) regular
  expression can be used to decode a URI:
  
    my($scheme, $authority, $path, $query, $fragment) =
    $uri =~ m|(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?|;
  
  The C<URI::Split> module provides the function uri_split() as a
  readable alternative.
  
  =head1 SEE ALSO
  
  L<URI::file>, L<URI::WithBase>, L<URI::QueryParam>, L<URI::Escape>,
  L<URI::Split>, L<URI::Heuristic>
  
  RFC 2396: "Uniform Resource Identifiers (URI): Generic Syntax",
  Berners-Lee, Fielding, Masinter, August 1998.
  
  L<http://www.iana.org/assignments/uri-schemes>
  
  L<http://www.iana.org/assignments/urn-namespaces>
  
  L<http://www.w3.org/Addressing/>
  
  =head1 COPYRIGHT
  
  Copyright 1995-2009 Gisle Aas.
  
  Copyright 1995 Martijn Koster.
  
  This program is free software; you can redistribute it and/or modify
  it under the same terms as Perl itself.
  
  =head1 AUTHORS / ACKNOWLEDGMENTS
  
  This module is based on the C<URI::URL> module, which in turn was
  (distantly) based on the C<wwwurl.pl> code in the libwww-perl for
  perl4 developed by Roy Fielding, as part of the Arcadia project at the
  University of California, Irvine, with contributions from Brooks
  Cutter.
  
  C<URI::URL> was developed by Gisle Aas, Tim Bunce, Roy Fielding and
  Martijn Koster with input from other people on the libwww-perl mailing
  list.
  
  C<URI> and related subclasses was developed by Gisle Aas.
  
  =cut
URI

$fatpacked{"URI/Escape.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI_ESCAPE';
  package URI::Escape;
  use strict;
  
  =head1 NAME
  
  URI::Escape - Percent-encode and percent-decode unsafe characters
  
  =head1 SYNOPSIS
  
   use URI::Escape;
   $safe = uri_escape("10% is enough\n");
   $verysafe = uri_escape("foo", "\0-\377");
   $str  = uri_unescape($safe);
  
  =head1 DESCRIPTION
  
  This module provides functions to percent-encode and percent-decode URI strings as
  defined by RFC 3986. Percent-encoding URI's is informally called "URI escaping".
  This is the terminology used by this module, which predates the formalization of the
  terms by the RFC by several years.
  
  A URI consists of a restricted set of characters.  The restricted set
  of characters consists of digits, letters, and a few graphic symbols
  chosen from those common to most of the character encodings and input
  facilities available to Internet users.  They are made up of the
  "unreserved" and "reserved" character sets as defined in RFC 3986.
  
     unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~"
     reserved      = ":" / "/" / "?" / "#" / "[" / "]" / "@"
                     "!" / "$" / "&" / "'" / "(" / ")"
                   / "*" / "+" / "," / ";" / "="
  
  In addition, any byte (octet) can be represented in a URI by an escape
  sequence: a triplet consisting of the character "%" followed by two
  hexadecimal digits.  A byte can also be represented directly by a
  character, using the US-ASCII character for that octet.
  
  Some of the characters are I<reserved> for use as delimiters or as
  part of certain URI components.  These must be escaped if they are to
  be treated as ordinary data.  Read RFC 3986 for further details.
  
  The functions provided (and exported by default) from this module are:
  
  =over 4
  
  =item uri_escape( $string )
  
  =item uri_escape( $string, $unsafe )
  
  Replaces each unsafe character in the $string with the corresponding
  escape sequence and returns the result.  The $string argument should
  be a string of bytes.  The uri_escape() function will croak if given a
  characters with code above 255.  Use uri_escape_utf8() if you know you
  have such chars or/and want chars in the 128 .. 255 range treated as
  UTF-8.
  
  The uri_escape() function takes an optional second argument that
  overrides the set of characters that are to be escaped.  The set is
  specified as a string that can be used in a regular expression
  character class (between [ ]).  E.g.:
  
    "\x00-\x1f\x7f-\xff"          # all control and hi-bit characters
    "a-z"                         # all lower case characters
    "^A-Za-z"                     # everything not a letter
  
  The default set of characters to be escaped is all those which are
  I<not> part of the C<unreserved> character class shown above as well
  as the reserved characters.  I.e. the default is:
  
      "^A-Za-z0-9\-\._~"
  
  =item uri_escape_utf8( $string )
  
  =item uri_escape_utf8( $string, $unsafe )
  
  Works like uri_escape(), but will encode chars as UTF-8 before
  escaping them.  This makes this function able to deal with characters
  with code above 255 in $string.  Note that chars in the 128 .. 255
  range will be escaped differently by this function compared to what
  uri_escape() would.  For chars in the 0 .. 127 range there is no
  difference.
  
  Equivalent to:
  
      utf8::encode($string);
      my $uri = uri_escape($string);
  
  Note: JavaScript has a function called escape() that produces the
  sequence "%uXXXX" for chars in the 256 .. 65535 range.  This function
  has really nothing to do with URI escaping but some folks got confused
  since it "does the right thing" in the 0 .. 255 range.  Because of
  this you sometimes see "URIs" with these kind of escapes.  The
  JavaScript encodeURIComponent() function is similar to uri_escape_utf8().
  
  =item uri_unescape($string,...)
  
  Returns a string with each %XX sequence replaced with the actual byte
  (octet).
  
  This does the same as:
  
     $string =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;
  
  but does not modify the string in-place as this RE would.  Using the
  uri_unescape() function instead of the RE might make the code look
  cleaner and is a few characters less to type.
  
  In a simple benchmark test I did,
  calling the function (instead of the inline RE above) if a few chars
  were unescaped was something like 40% slower, and something like 700% slower if none were.  If
  you are going to unescape a lot of times it might be a good idea to
  inline the RE.
  
  If the uri_unescape() function is passed multiple strings, then each
  one is returned unescaped.
  
  =back
  
  The module can also export the C<%escapes> hash, which contains the
  mapping from all 256 bytes to the corresponding escape codes.  Lookup
  in this hash is faster than evaluating C<sprintf("%%%02X", ord($byte))>
  each time.
  
  =head1 SEE ALSO
  
  L<URI>
  
  
  =head1 COPYRIGHT
  
  Copyright 1995-2004 Gisle Aas.
  
  This program is free software; you can redistribute it and/or modify
  it under the same terms as Perl itself.
  
  =cut
  
  require Exporter;
  our @ISA = qw(Exporter);
  our %escapes;
  our @EXPORT = qw(uri_escape uri_unescape uri_escape_utf8);
  our @EXPORT_OK = qw(%escapes);
  our $VERSION = "3.31";
  
  use Carp ();
  
  # Build a char->hex map
  for (0..255) {
      $escapes{chr($_)} = sprintf("%%%02X", $_);
  }
  
  my %subst;  # compiled patterns
  
  my %Unsafe = (
      RFC2732 => qr/[^A-Za-z0-9\-_.!~*'()]/,
      RFC3986 => qr/[^A-Za-z0-9\-\._~]/,
  );
  
  sub uri_escape {
      my($text, $patn) = @_;
      return undef unless defined $text;
      if (defined $patn){
          unless (exists  $subst{$patn}) {
              # Because we can't compile the regex we fake it with a cached sub
              (my $tmp = $patn) =~ s,/,\\/,g;
              eval "\$subst{\$patn} = sub {\$_[0] =~ s/([$tmp])/\$escapes{\$1} || _fail_hi(\$1)/ge; }";
              Carp::croak("uri_escape: $@") if $@;
          }
          &{$subst{$patn}}($text);
      } else {
          $text =~ s/($Unsafe{RFC3986})/$escapes{$1} || _fail_hi($1)/ge;
      }
      $text;
  }
  
  sub _fail_hi {
      my $chr = shift;
      Carp::croak(sprintf "Can't escape \\x{%04X}, try uri_escape_utf8() instead", ord($chr));
  }
  
  sub uri_escape_utf8 {
      my $text = shift;
      utf8::encode($text);
      return uri_escape($text, @_);
  }
  
  sub uri_unescape {
      # Note from RFC1630:  "Sequences which start with a percent sign
      # but are not followed by two hexadecimal characters are reserved
      # for future extension"
      my $str = shift;
      if (@_ && wantarray) {
          # not executed for the common case of a single argument
          my @str = ($str, @_);  # need to copy
          for (@str) {
              s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;
          }
          return @str;
      }
      $str =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg if defined $str;
      $str;
  }
  
  sub escape_char {
      return join '', @URI::Escape::escapes{$_[0] =~ /(\C)/g};
  }
  
  1;
URI_ESCAPE

$fatpacked{"URI/Heuristic.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI_HEURISTIC';
  package URI::Heuristic;
  
  =head1 NAME
  
  URI::Heuristic - Expand URI using heuristics
  
  =head1 SYNOPSIS
  
   use URI::Heuristic qw(uf_uristr);
   $u = uf_uristr("perl");             # http://www.perl.com
   $u = uf_uristr("www.sol.no/sol");   # http://www.sol.no/sol
   $u = uf_uristr("aas");              # http://www.aas.no
   $u = uf_uristr("ftp.funet.fi");     # ftp://ftp.funet.fi
   $u = uf_uristr("/etc/passwd");      # file:/etc/passwd
  
  =head1 DESCRIPTION
  
  This module provides functions that expand strings into real absolute
  URIs using some built-in heuristics.  Strings that already represent
  absolute URIs (i.e. that start with a C<scheme:> part) are never modified
  and are returned unchanged.  The main use of these functions is to
  allow abbreviated URIs similar to what many web browsers allow for URIs
  typed in by the user.
  
  The following functions are provided:
  
  =over 4
  
  =item uf_uristr($str)
  
  Tries to make the argument string
  into a proper absolute URI string.  The "uf_" prefix stands for "User 
  Friendly".  Under MacOS, it assumes that any string with a common URL 
  scheme (http, ftp, etc.) is a URL rather than a local path.  So don't name 
  your volumes after common URL schemes and expect uf_uristr() to construct 
  valid file: URL's on those volumes for you, because it won't.
  
  =item uf_uri($str)
  
  Works the same way as uf_uristr() but
  returns a C<URI> object.
  
  =back
  
  =head1 ENVIRONMENT
  
  If the hostname portion of a URI does not contain any dots, then
  certain qualified guesses are made.  These guesses are governed by
  the following environment variables:
  
  =over 10
  
  =item COUNTRY
  
  The two-letter country code (ISO 3166) for your location.  If
  the domain name of your host ends with two letters, then it is taken
  to be the default country. See also L<Locale::Country>.
  
  =item HTTP_ACCEPT_LANGUAGE, LC_ALL, LANG
  
  If COUNTRY is not set, these standard environment variables are
  examined and country (not language) information possibly found in them
  is used as the default country.
  
  =item URL_GUESS_PATTERN
  
  Contains a space-separated list of URL patterns to try.  The string
  "ACME" is for some reason used as a placeholder for the host name in
  the URL provided.  Example:
  
   URL_GUESS_PATTERN="www.ACME.no www.ACME.se www.ACME.com"
   export URL_GUESS_PATTERN
  
  Specifying URL_GUESS_PATTERN disables any guessing rules based on
  country.  An empty URL_GUESS_PATTERN disables any guessing that
  involves host name lookups.
  
  =back
  
  =head1 COPYRIGHT
  
  Copyright 1997-1998, Gisle Aas
  
  This library is free software; you can redistribute it and/or
  modify it under the same terms as Perl itself.
  
  =cut
  
  use strict;
  
  use vars qw(@EXPORT_OK $VERSION $MY_COUNTRY %LOCAL_GUESSING $DEBUG);
  
  require Exporter;
  *import = \&Exporter::import;
  @EXPORT_OK = qw(uf_uri uf_uristr uf_url uf_urlstr);
  $VERSION = "4.20";
  
  sub MY_COUNTRY() {
      for ($MY_COUNTRY) {
  	return $_ if defined;
  
  	# First try the environment.
  	$_ = $ENV{COUNTRY};
  	return $_ if defined;
  
  	# Try the country part of LC_ALL and LANG from environment
  	my @srcs = ($ENV{LC_ALL}, $ENV{LANG});
  	# ...and HTTP_ACCEPT_LANGUAGE before those if present
  	if (my $httplang = $ENV{HTTP_ACCEPT_LANGUAGE}) {
  	    # TODO: q-value processing/ordering
  	    for $httplang (split(/\s*,\s*/, $httplang)) {
  		if ($httplang =~ /^\s*([a-zA-Z]+)[_-]([a-zA-Z]{2})\s*$/) {
  		    unshift(@srcs, "${1}_${2}");
  		    last;
  		}
  	    }
  	}
  	for (@srcs) {
  	    next unless defined;
  	    return lc($1) if /^[a-zA-Z]+_([a-zA-Z]{2})(?:[.@]|$)/;
  	}
  
  	# Last bit of domain name.  This may access the network.
  	require Net::Domain;
  	my $fqdn = Net::Domain::hostfqdn();
  	$_ = lc($1) if $fqdn =~ /\.([a-zA-Z]{2})$/;
  	return $_ if defined;
  
  	# Give up.  Defined but false.
  	return ($_ = 0);
      }
  }
  
  %LOCAL_GUESSING =
  (
   'us' => [qw(www.ACME.gov www.ACME.mil)],
   'gb' => [qw(www.ACME.co.uk www.ACME.org.uk www.ACME.ac.uk)],
   'au' => [qw(www.ACME.com.au www.ACME.org.au www.ACME.edu.au)],
   'il' => [qw(www.ACME.co.il www.ACME.org.il www.ACME.net.il)],
   # send corrections and new entries to <gisle@aas.no>
  );
  # Backwards compatibility; uk != United Kingdom in ISO 3166
  $LOCAL_GUESSING{uk} = $LOCAL_GUESSING{gb};
  
  
  sub uf_uristr ($)
  {
      local($_) = @_;
      print STDERR "uf_uristr: resolving $_\n" if $DEBUG;
      return unless defined;
  
      s/^\s+//;
      s/\s+$//;
  
      if (/^(www|web|home)[a-z0-9-]*(?:\.|$)/i) {
  	$_ = "http://$_";
  
      } elsif (/^(ftp|gopher|news|wais|https|http)[a-z0-9-]*(?:\.|$)/i) {
  	$_ = lc($1) . "://$_";
  
      } elsif ($^O ne "MacOS" && 
  	    (m,^/,      ||          # absolute file name
  	     m,^\.\.?/, ||          # relative file name
  	     m,^[a-zA-Z]:[/\\],)    # dosish file name
  	    )
      {
  	$_ = "file:$_";
  
      } elsif ($^O eq "MacOS" && m/:/) {
          # potential MacOS file name
  	unless (m/^(ftp|gopher|news|wais|http|https|mailto):/) {
  	    require URI::file;
  	    my $a = URI::file->new($_)->as_string;
  	    $_ = ($a =~ m/^file:/) ? $a : "file:$a";
  	}
      } elsif (/^\w+([\.\-]\w+)*\@(\w+\.)+\w{2,3}$/) {
  	$_ = "mailto:$_";
  
      } elsif (!/^[a-zA-Z][a-zA-Z0-9.+\-]*:/) {      # no scheme specified
  	if (s/^([-\w]+(?:\.[-\w]+)*)([\/:\?\#]|$)/$2/) {
  	    my $host = $1;
  
  	    my $scheme = "http";
  	    if (/^:(\d+)\b/) {
  		# Some more or less well known ports
  		if ($1 =~ /^[56789]?443$/) {
  		    $scheme = "https";
  		} elsif ($1 eq "21") {
  		    $scheme = "ftp";
  		}
  	    }
  
  	    if ($host !~ /\./ && $host ne "localhost") {
  		my @guess;
  		if (exists $ENV{URL_GUESS_PATTERN}) {
  		    @guess = map { s/\bACME\b/$host/; $_ }
  		             split(' ', $ENV{URL_GUESS_PATTERN});
  		} else {
  		    if (MY_COUNTRY()) {
  			my $special = $LOCAL_GUESSING{MY_COUNTRY()};
  			if ($special) {
  			    my @special = @$special;
  			    push(@guess, map { s/\bACME\b/$host/; $_ }
                                                 @special);
  			} else {
  			    push(@guess, "www.$host." . MY_COUNTRY());
  			}
  		    }
  		    push(@guess, map "www.$host.$_",
  			             "com", "org", "net", "edu", "int");
  		}
  
  
  		my $guess;
  		for $guess (@guess) {
  		    print STDERR "uf_uristr: gethostbyname('$guess.')..."
  		      if $DEBUG;
  		    if (gethostbyname("$guess.")) {
  			print STDERR "yes\n" if $DEBUG;
  			$host = $guess;
  			last;
  		    }
  		    print STDERR "no\n" if $DEBUG;
  		}
  	    }
  	    $_ = "$scheme://$host$_";
  
  	} else {
  	    # pure junk, just return it unchanged...
  
  	}
      }
      print STDERR "uf_uristr: ==> $_\n" if $DEBUG;
  
      $_;
  }
  
  sub uf_uri ($)
  {
      require URI;
      URI->new(uf_uristr($_[0]));
  }
  
  # legacy
  *uf_urlstr = \*uf_uristr;
  
  sub uf_url ($)
  {
      require URI::URL;
      URI::URL->new(uf_uristr($_[0]));
  }
  
  1;
URI_HEURISTIC

$fatpacked{"URI/IRI.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI_IRI';
  package URI::IRI;
  
  # Experimental
  
  use strict;
  use URI ();
  
  use overload '""' => sub { shift->as_string };
  
  sub new {
      my($class, $uri, $scheme) = @_;
      utf8::upgrade($uri);
      return bless {
  	uri => URI->new($uri, $scheme),
      }, $class;
  }
  
  sub clone {
      my $self = shift;
      return bless {
  	uri => $self->{uri}->clone,
      }, ref($self);
  }
  
  sub as_string {
      my $self = shift;
      return $self->{uri}->as_iri;
  }
  
  sub AUTOLOAD
  {
      use vars qw($AUTOLOAD);
      my $method = substr($AUTOLOAD, rindex($AUTOLOAD, '::')+2);
  
      # We create the function here so that it will not need to be
      # autoloaded the next time.
      no strict 'refs';
      *$method = sub { shift->{uri}->$method(@_) };
      goto &$method;
  }
  
  sub DESTROY {}   # avoid AUTOLOADing it
  
  1;
URI_IRI

$fatpacked{"URI/QueryParam.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI_QUERYPARAM';
  package URI::QueryParam;
  
  use strict;
  
  sub URI::_query::query_param {
      my $self = shift;
      my @old = $self->query_form;
  
      if (@_ == 0) {
  	# get keys
  	my (%seen, $i);
  	return grep !($i++ % 2 || $seen{$_}++), @old;
      }
  
      my $key = shift;
      my @i = grep $_ % 2 == 0 && $old[$_] eq $key, 0 .. $#old;
  
      if (@_) {
  	my @new = @old;
  	my @new_i = @i;
  	my @vals = map { ref($_) eq 'ARRAY' ? @$_ : $_ } @_;
  
  	while (@new_i > @vals) {
  	    splice @new, pop @new_i, 2;
  	}
  	if (@vals > @new_i) {
  	    my $i = @new_i ? $new_i[-1] + 2 : @new;
  	    my @splice = splice @vals, @new_i, @vals - @new_i;
  
  	    splice @new, $i, 0, map { $key => $_ } @splice;
  	}
  	if (@vals) {
  	    #print "SET $new_i[0]\n";
  	    @new[ map $_ + 1, @new_i ] = @vals;
  	}
  
  	$self->query_form(\@new);
      }
  
      return wantarray ? @old[map $_+1, @i] : @i ? $old[$i[0]+1] : undef;
  }
  
  sub URI::_query::query_param_append {
      my $self = shift;
      my $key = shift;
      my @vals = map { ref $_ eq 'ARRAY' ? @$_ : $_ } @_;
      $self->query_form($self->query_form, $key => \@vals);  # XXX
      return;
  }
  
  sub URI::_query::query_param_delete {
      my $self = shift;
      my $key = shift;
      my @old = $self->query_form;
      my @vals;
  
      for (my $i = @old - 2; $i >= 0; $i -= 2) {
  	next if $old[$i] ne $key;
  	push(@vals, (splice(@old, $i, 2))[1]);
      }
      $self->query_form(\@old) if @vals;
      return wantarray ? reverse @vals : $vals[-1];
  }
  
  sub URI::_query::query_form_hash {
      my $self = shift;
      my @old = $self->query_form;
      if (@_) {
  	$self->query_form(@_ == 1 ? %{shift(@_)} : @_);
      }
      my %hash;
      while (my($k, $v) = splice(@old, 0, 2)) {
  	if (exists $hash{$k}) {
  	    for ($hash{$k}) {
  		$_ = [$_] unless ref($_) eq "ARRAY";
  		push(@$_, $v);
  	    }
  	}
  	else {
  	    $hash{$k} = $v;
  	}
      }
      return \%hash;
  }
  
  1;
  
  __END__
  
  =head1 NAME
  
  URI::QueryParam - Additional query methods for URIs
  
  =head1 SYNOPSIS
  
    use URI;
    use URI::QueryParam;
  
    $u = URI->new("", "http");
    $u->query_param(foo => 1, 2, 3);
    print $u->query;    # prints foo=1&foo=2&foo=3
  
    for my $key ($u->query_param) {
        print "$key: ", join(", ", $u->query_param($key)), "\n";
    }
  
  =head1 DESCRIPTION
  
  Loading the C<URI::QueryParam> module adds some extra methods to
  URIs that support query methods.  These methods provide an alternative
  interface to the $u->query_form data.
  
  The query_param_* methods have deliberately been made identical to the
  interface of the corresponding C<CGI.pm> methods.
  
  The following additional methods are made available:
  
  =over
  
  =item @keys = $u->query_param
  
  =item @values = $u->query_param( $key )
  
  =item $first_value = $u->query_param( $key )
  
  =item $u->query_param( $key, $value,... )
  
  If $u->query_param is called with no arguments, it returns all the
  distinct parameter keys of the URI.  In a scalar context it returns the
  number of distinct keys.
  
  When a $key argument is given, the method returns the parameter values with the
  given key.  In a scalar context, only the first parameter value is
  returned.
  
  If additional arguments are given, they are used to update successive
  parameters with the given key.  If any of the values provided are
  array references, then the array is dereferenced to get the actual
  values.
  
  =item $u->query_param_append($key, $value,...)
  
  Adds new parameters with the given
  key without touching any old parameters with the same key.  It
  can be explained as a more efficient version of:
  
     $u->query_param($key,
                     $u->query_param($key),
                     $value,...);
  
  One difference is that this expression would return the old values
  of $key, whereas the query_param_append() method does not.
  
  =item @values = $u->query_param_delete($key)
  
  =item $first_value = $u->query_param_delete($key)
  
  Deletes all key/value pairs with the given key.
  The old values are returned.  In a scalar context, only the first value
  is returned.
  
  Using the query_param_delete() method is slightly more efficient than
  the equivalent:
  
     $u->query_param($key, []);
  
  =item $hashref = $u->query_form_hash
  
  =item $u->query_form_hash( \%new_form )
  
  Returns a reference to a hash that represents the
  query form's key/value pairs.  If a key occurs multiple times, then the hash
  value becomes an array reference.
  
  Note that sequence information is lost.  This means that:
  
     $u->query_form_hash($u->query_form_hash);
  
  is not necessarily a no-op, as it may reorder the key/value pairs.
  The values returned by the query_param() method should stay the same
  though.
  
  =back
  
  =head1 SEE ALSO
  
  L<URI>, L<CGI>
  
  =head1 COPYRIGHT
  
  Copyright 2002 Gisle Aas.
  
  =cut
URI_QUERYPARAM

$fatpacked{"URI/Split.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI_SPLIT';
  package URI::Split;
  
  use strict;
  
  use vars qw(@ISA @EXPORT_OK);
  require Exporter;
  @ISA = qw(Exporter);
  @EXPORT_OK = qw(uri_split uri_join);
  
  use URI::Escape ();
  
  sub uri_split {
       return $_[0] =~ m,(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?,;
  }
  
  sub uri_join {
      my($scheme, $auth, $path, $query, $frag) = @_;
      my $uri = defined($scheme) ? "$scheme:" : "";
      $path = "" unless defined $path;
      if (defined $auth) {
  	$auth =~ s,([/?\#]), URI::Escape::escape_char($1),eg;
  	$uri .= "//$auth";
  	$path = "/$path" if length($path) && $path !~ m,^/,;
      }
      elsif ($path =~ m,^//,) {
  	$uri .= "//";  # XXX force empty auth
      }
      unless (length $uri) {
  	$path =~ s,(:), URI::Escape::escape_char($1),e while $path =~ m,^[^:/?\#]+:,;
      }
      $path =~ s,([?\#]), URI::Escape::escape_char($1),eg;
      $uri .= $path;
      if (defined $query) {
  	$query =~ s,(\#), URI::Escape::escape_char($1),eg;
  	$uri .= "?$query";
      }
      $uri .= "#$frag" if defined $frag;
      $uri;
  }
  
  1;
  
  __END__
  
  =head1 NAME
  
  URI::Split - Parse and compose URI strings
  
  =head1 SYNOPSIS
  
   use URI::Split qw(uri_split uri_join);
   ($scheme, $auth, $path, $query, $frag) = uri_split($uri);
   $uri = uri_join($scheme, $auth, $path, $query, $frag);
  
  =head1 DESCRIPTION
  
  Provides functions to parse and compose URI
  strings.  The following functions are provided:
  
  =over
  
  =item ($scheme, $auth, $path, $query, $frag) = uri_split($uri)
  
  Breaks up a URI string into its component
  parts.  An C<undef> value is returned for those parts that are not
  present.  The $path part is always present (but can be the empty
  string) and is thus never returned as C<undef>.
  
  No sensible value is returned if this function is called in a scalar
  context.
  
  =item $uri = uri_join($scheme, $auth, $path, $query, $frag)
  
  Puts together a URI string from its parts.
  Missing parts are signaled by passing C<undef> for the corresponding
  argument.
  
  Minimal escaping is applied to parts that contain reserved chars
  that would confuse a parser.  For instance, any occurrence of '?' or '#'
  in $path is always escaped, as it would otherwise be parsed back
  as a query or fragment.
  
  =back
  
  =head1 SEE ALSO
  
  L<URI>, L<URI::Escape>
  
  =head1 COPYRIGHT
  
  Copyright 2003, Gisle Aas
  
  This library is free software; you can redistribute it and/or
  modify it under the same terms as Perl itself.
  
  =cut
URI_SPLIT

$fatpacked{"URI/URL.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI_URL';
  package URI::URL;
  
  require URI::WithBase;
  @ISA=qw(URI::WithBase);
  
  use strict;
  use vars qw(@EXPORT $VERSION);
  
  $VERSION = "5.04";
  
  # Provide as much as possible of the old URI::URL interface for backwards
  # compatibility...
  
  require Exporter;
  *import = \&Exporter::import;
  @EXPORT = qw(url);
  
  # Easy to use constructor
  sub url ($;$) { URI::URL->new(@_); }
  
  use URI::Escape qw(uri_unescape);
  
  sub new
  {
      my $class = shift;
      my $self = $class->SUPER::new(@_);
      $self->[0] = $self->[0]->canonical;
      $self;
  }
  
  sub newlocal
  {
      my $class = shift;
      require URI::file;
      bless [URI::file->new_abs(shift)], $class;
  }
  
  {package URI::_foreign;
      sub _init  # hope it is not defined
      {
  	my $class = shift;
  	die "Unknown URI::URL scheme $_[1]:" if $URI::URL::STRICT;
  	$class->SUPER::_init(@_);
      }
  }
  
  sub strict
  {
      my $old = $URI::URL::STRICT;
      $URI::URL::STRICT = shift if @_;
      $old;
  }
  
  sub print_on
  {
      my $self = shift;
      require Data::Dumper;
      print STDERR Data::Dumper::Dumper($self);
  }
  
  sub _try
  {
      my $self = shift;
      my $method = shift;
      scalar(eval { $self->$method(@_) });
  }
  
  sub crack
  {
      # should be overridden by subclasses
      my $self = shift;
      (scalar($self->scheme),
       $self->_try("user"),
       $self->_try("password"),
       $self->_try("host"),
       $self->_try("port"),
       $self->_try("path"),
       $self->_try("params"),
       $self->_try("query"),
       scalar($self->fragment),
      )
  }
  
  sub full_path
  {
      my $self = shift;
      my $path = $self->path_query;
      $path = "/" unless length $path;
      $path;
  }
  
  sub netloc
  {
      shift->authority(@_);
  }
  
  sub epath
  {
      my $path = shift->SUPER::path(@_);
      $path =~ s/;.*//;
      $path;
  }
  
  sub eparams
  {
      my $self = shift;
      my @p = $self->path_segments;
      return unless ref($p[-1]);
      @p = @{$p[-1]};
      shift @p;
      join(";", @p);
  }
  
  sub params { shift->eparams(@_); }
  
  sub path {
      my $self = shift;
      my $old = $self->epath(@_);
      return unless defined wantarray;
      return '/' if !defined($old) || !length($old);
      Carp::croak("Path components contain '/' (you must call epath)")
  	if $old =~ /%2[fF]/ and !@_;
      $old = "/$old" if $old !~ m|^/| && defined $self->netloc;
      return uri_unescape($old);
  }
  
  sub path_components {
      shift->path_segments(@_);
  }
  
  sub query {
      my $self = shift;
      my $old = $self->equery(@_);
      if (defined(wantarray) && defined($old)) {
  	if ($old =~ /%(?:26|2[bB]|3[dD])/) {  # contains escaped '=' '&' or '+'
  	    my $mess;
  	    for ($old) {
  		$mess = "Query contains both '+' and '%2B'"
  		  if /\+/ && /%2[bB]/;
  		$mess = "Form query contains escaped '=' or '&'"
  		  if /=/  && /%(?:3[dD]|26)/;
  	    }
  	    if ($mess) {
  		Carp::croak("$mess (you must call equery)");
  	    }
  	}
  	# Now it should be safe to unescape the string without loosing
  	# information
  	return uri_unescape($old);
      }
      undef;
  
  }
  
  sub abs
  {
      my $self = shift;
      my $base = shift;
      my $allow_scheme = shift;
      $allow_scheme = $URI::URL::ABS_ALLOW_RELATIVE_SCHEME
  	unless defined $allow_scheme;
      local $URI::ABS_ALLOW_RELATIVE_SCHEME = $allow_scheme;
      local $URI::ABS_REMOTE_LEADING_DOTS = $URI::URL::ABS_REMOTE_LEADING_DOTS;
      $self->SUPER::abs($base);
  }
  
  sub frag { shift->fragment(@_); }
  sub keywords { shift->query_keywords(@_); }
  
  # file:
  sub local_path { shift->file; }
  sub unix_path  { shift->file("unix"); }
  sub dos_path   { shift->file("dos");  }
  sub mac_path   { shift->file("mac");  }
  sub vms_path   { shift->file("vms");  }
  
  # mailto:
  sub address { shift->to(@_); }
  sub encoded822addr { shift->to(@_); }
  sub URI::mailto::authority { shift->to(@_); }  # make 'netloc' method work
  
  # news:
  sub groupart { shift->_group(@_); }
  sub article  { shift->message(@_); }
  
  1;
  
  __END__
  
  =head1 NAME
  
  URI::URL - Uniform Resource Locators
  
  =head1 SYNOPSIS
  
   $u1 = URI::URL->new($str, $base);
   $u2 = $u1->abs;
  
  =head1 DESCRIPTION
  
  This module is provided for backwards compatibility with modules that
  depend on the interface provided by the C<URI::URL> class that used to
  be distributed with the libwww-perl library.
  
  The following differences exist compared to the C<URI> class interface:
  
  =over 3
  
  =item *
  
  The URI::URL module exports the url() function as an alternate
  constructor interface.
  
  =item *
  
  The constructor takes an optional $base argument.  The C<URI::URL>
  class is a subclass of C<URI::WithBase>.
  
  =item *
  
  The URI::URL->newlocal class method is the same as URI::file->new_abs.
  
  =item *
  
  URI::URL::strict(1)
  
  =item *
  
  $url->print_on method
  
  =item *
  
  $url->crack method
  
  =item *
  
  $url->full_path: same as ($uri->abs_path || "/")
  
  =item *
  
  $url->netloc: same as $uri->authority
  
  =item *
  
  $url->epath, $url->equery: same as $uri->path, $uri->query
  
  =item *
  
  $url->path and $url->query pass unescaped strings.
  
  =item *
  
  $url->path_components: same as $uri->path_segments (if you don't
  consider path segment parameters)
  
  =item *
  
  $url->params and $url->eparams methods
  
  =item *
  
  $url->base method.  See L<URI::WithBase>.
  
  =item *
  
  $url->abs and $url->rel have an optional $base argument.  See
  L<URI::WithBase>.
  
  =item *
  
  $url->frag: same as $uri->fragment
  
  =item *
  
  $url->keywords: same as $uri->query_keywords
  
  =item *
  
  $url->localpath and friends map to $uri->file.
  
  =item *
  
  $url->address and $url->encoded822addr: same as $uri->to for mailto URI
  
  =item *
  
  $url->groupart method for news URI
  
  =item *
  
  $url->article: same as $uri->message
  
  =back
  
  
  
  =head1 SEE ALSO
  
  L<URI>, L<URI::WithBase>
  
  =head1 COPYRIGHT
  
  Copyright 1998-2000 Gisle Aas.
  
  =cut
URI_URL

$fatpacked{"URI/WithBase.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI_WITHBASE';
  package URI::WithBase;
  
  use strict;
  use vars qw($AUTOLOAD $VERSION);
  use URI;
  
  $VERSION = "2.20";
  
  use overload '""' => "as_string", fallback => 1;
  
  sub as_string;  # help overload find it
  
  sub new
  {
      my($class, $uri, $base) = @_;
      my $ibase = $base;
      if ($base && ref($base) && UNIVERSAL::isa($base, __PACKAGE__)) {
  	$base = $base->abs;
  	$ibase = $base->[0];
      }
      bless [URI->new($uri, $ibase), $base], $class;
  }
  
  sub new_abs
  {
      my $class = shift;
      my $self = $class->new(@_);
      $self->abs;
  }
  
  sub _init
  {
      my $class = shift;
      my($str, $scheme) = @_;
      bless [URI->new($str, $scheme), undef], $class;
  }
  
  sub eq
  {
      my($self, $other) = @_;
      $other = $other->[0] if UNIVERSAL::isa($other, __PACKAGE__);
      $self->[0]->eq($other);
  }
  
  sub AUTOLOAD
  {
      my $self = shift;
      my $method = substr($AUTOLOAD, rindex($AUTOLOAD, '::')+2);
      return if $method eq "DESTROY";
      $self->[0]->$method(@_);
  }
  
  sub can {                                  # override UNIVERSAL::can
      my $self = shift;
      $self->SUPER::can(@_) || (
        ref($self)
        ? $self->[0]->can(@_)
        : undef
      )
  }
  
  sub base {
      my $self = shift;
      my $base  = $self->[1];
  
      if (@_) { # set
  	my $new_base = shift;
  	# ensure absoluteness
  	$new_base = $new_base->abs if ref($new_base) && $new_base->isa(__PACKAGE__);
  	$self->[1] = $new_base;
      }
      return unless defined wantarray;
  
      # The base attribute supports 'lazy' conversion from URL strings
      # to URL objects. Strings may be stored but when a string is
      # fetched it will automatically be converted to a URL object.
      # The main benefit is to make it much cheaper to say:
      #   URI::WithBase->new($random_url_string, 'http:')
      if (defined($base) && !ref($base)) {
  	$base = ref($self)->new($base);
  	$self->[1] = $base unless @_;
      }
      $base;
  }
  
  sub clone
  {
      my $self = shift;
      my $base = $self->[1];
      $base = $base->clone if ref($base);
      bless [$self->[0]->clone, $base], ref($self);
  }
  
  sub abs
  {
      my $self = shift;
      my $base = shift || $self->base || return $self->clone;
      $base = $base->as_string if ref($base);
      bless [$self->[0]->abs($base, @_), $base], ref($self);
  }
  
  sub rel
  {
      my $self = shift;
      my $base = shift || $self->base || return $self->clone;
      $base = $base->as_string if ref($base);
      bless [$self->[0]->rel($base, @_), $base], ref($self);
  }
  
  1;
  
  __END__
  
  =head1 NAME
  
  URI::WithBase - URIs which remember their base
  
  =head1 SYNOPSIS
  
   $u1 = URI::WithBase->new($str, $base);
   $u2 = $u1->abs;
  
   $base = $u1->base;
   $u1->base( $new_base )
  
  =head1 DESCRIPTION
  
  This module provides the C<URI::WithBase> class.  Objects of this class
  are like C<URI> objects, but can keep their base too.  The base
  represents the context where this URI was found and can be used to
  absolutize or relativize the URI.  All the methods described in L<URI>
  are supported for C<URI::WithBase> objects.
  
  The methods provided in addition to or modified from those of C<URI> are:
  
  =over 4
  
  =item $uri = URI::WithBase->new($str, [$base])
  
  The constructor takes an optional base URI as the second argument.
  If provided, this argument initializes the base attribute.
  
  =item $uri->base( [$new_base] )
  
  Can be used to get or set the value of the base attribute.
  The return value, which is the old value, is a URI object or C<undef>.
  
  =item $uri->abs( [$base_uri] )
  
  The $base_uri argument is now made optional as the object carries its
  base with it.  A new object is returned even if $uri is already
  absolute (while plain URI objects simply return themselves in
  that case).
  
  =item $uri->rel( [$base_uri] )
  
  The $base_uri argument is now made optional as the object carries its
  base with it.  A new object is always returned.
  
  =back
  
  
  =head1 SEE ALSO
  
  L<URI>
  
  =head1 COPYRIGHT
  
  Copyright 1998-2002 Gisle Aas.
  
  =cut
URI_WITHBASE

$fatpacked{"URI/_foreign.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI__FOREIGN';
  package URI::_foreign;
  
  require URI::_generic;
  @ISA=qw(URI::_generic);
  
  1;
URI__FOREIGN

$fatpacked{"URI/_generic.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI__GENERIC';
  package URI::_generic;
  require URI;
  require URI::_query;
  @ISA=qw(URI URI::_query);
  
  use strict;
  use URI::Escape qw(uri_unescape);
  use Carp ();
  
  my $ACHAR = $URI::uric;  $ACHAR =~ s,\\[/?],,g;
  my $PCHAR = $URI::uric;  $PCHAR =~ s,\\[?],,g;
  
  sub _no_scheme_ok { 1 }
  
  sub authority
  {
      my $self = shift;
      $$self =~ m,^((?:$URI::scheme_re:)?)(?://([^/?\#]*))?(.*)$,os or die;
  
      if (@_) {
  	my $auth = shift;
  	$$self = $1;
  	my $rest = $3;
  	if (defined $auth) {
  	    $auth =~ s/([^$ACHAR])/ URI::Escape::escape_char($1)/ego;
  	    utf8::downgrade($auth);
  	    $$self .= "//$auth";
  	}
  	_check_path($rest, $$self);
  	$$self .= $rest;
      }
      $2;
  }
  
  sub path
  {
      my $self = shift;
      $$self =~ m,^((?:[^:/?\#]+:)?(?://[^/?\#]*)?)([^?\#]*)(.*)$,s or die;
  
      if (@_) {
  	$$self = $1;
  	my $rest = $3;
  	my $new_path = shift;
  	$new_path = "" unless defined $new_path;
  	$new_path =~ s/([^$PCHAR])/ URI::Escape::escape_char($1)/ego;
  	utf8::downgrade($new_path);
  	_check_path($new_path, $$self);
  	$$self .= $new_path . $rest;
      }
      $2;
  }
  
  sub path_query
  {
      my $self = shift;
      $$self =~ m,^((?:[^:/?\#]+:)?(?://[^/?\#]*)?)([^\#]*)(.*)$,s or die;
  
      if (@_) {
  	$$self = $1;
  	my $rest = $3;
  	my $new_path = shift;
  	$new_path = "" unless defined $new_path;
  	$new_path =~ s/([^$URI::uric])/ URI::Escape::escape_char($1)/ego;
  	utf8::downgrade($new_path);
  	_check_path($new_path, $$self);
  	$$self .= $new_path . $rest;
      }
      $2;
  }
  
  sub _check_path
  {
      my($path, $pre) = @_;
      my $prefix;
      if ($pre =~ m,/,) {  # authority present
  	$prefix = "/" if length($path) && $path !~ m,^[/?\#],;
      }
      else {
  	if ($path =~ m,^//,) {
  	    Carp::carp("Path starting with double slash is confusing")
  		if $^W;
  	}
  	elsif (!length($pre) && $path =~ m,^[^:/?\#]+:,) {
  	    Carp::carp("Path might look like scheme, './' prepended")
  		if $^W;
  	    $prefix = "./";
  	}
      }
      substr($_[0], 0, 0) = $prefix if defined $prefix;
  }
  
  sub path_segments
  {
      my $self = shift;
      my $path = $self->path;
      if (@_) {
  	my @arg = @_;  # make a copy
  	for (@arg) {
  	    if (ref($_)) {
  		my @seg = @$_;
  		$seg[0] =~ s/%/%25/g;
  		for (@seg) { s/;/%3B/g; }
  		$_ = join(";", @seg);
  	    }
  	    else {
  		 s/%/%25/g; s/;/%3B/g;
  	    }
  	    s,/,%2F,g;
  	}
  	$self->path(join("/", @arg));
      }
      return $path unless wantarray;
      map {/;/ ? $self->_split_segment($_)
               : uri_unescape($_) }
          split('/', $path, -1);
  }
  
  
  sub _split_segment
  {
      my $self = shift;
      require URI::_segment;
      URI::_segment->new(@_);
  }
  
  
  sub abs
  {
      my $self = shift;
      my $base = shift || Carp::croak("Missing base argument");
  
      if (my $scheme = $self->scheme) {
  	return $self unless $URI::ABS_ALLOW_RELATIVE_SCHEME;
  	$base = URI->new($base) unless ref $base;
  	return $self unless $scheme eq $base->scheme;
      }
  
      $base = URI->new($base) unless ref $base;
      my $abs = $self->clone;
      $abs->scheme($base->scheme);
      return $abs if $$self =~ m,^(?:$URI::scheme_re:)?//,o;
      $abs->authority($base->authority);
  
      my $path = $self->path;
      return $abs if $path =~ m,^/,;
  
      if (!length($path)) {
  	my $abs = $base->clone;
  	my $query = $self->query;
  	$abs->query($query) if defined $query;
  	$abs->fragment($self->fragment);
  	return $abs;
      }
  
      my $p = $base->path;
      $p =~ s,[^/]+$,,;
      $p .= $path;
      my @p = split('/', $p, -1);
      shift(@p) if @p && !length($p[0]);
      my $i = 1;
      while ($i < @p) {
  	#print "$i ", join("/", @p), " ($p[$i])\n";
  	if ($p[$i-1] eq ".") {
  	    splice(@p, $i-1, 1);
  	    $i-- if $i > 1;
  	}
  	elsif ($p[$i] eq ".." && $p[$i-1] ne "..") {
  	    splice(@p, $i-1, 2);
  	    if ($i > 1) {
  		$i--;
  		push(@p, "") if $i == @p;
  	    }
  	}
  	else {
  	    $i++;
  	}
      }
      $p[-1] = "" if @p && $p[-1] eq ".";  # trailing "/."
      if ($URI::ABS_REMOTE_LEADING_DOTS) {
          shift @p while @p && $p[0] =~ /^\.\.?$/;
      }
      $abs->path("/" . join("/", @p));
      $abs;
  }
  
  # The opposite of $url->abs.  Return a URI which is as relative as possible
  sub rel {
      my $self = shift;
      my $base = shift || Carp::croak("Missing base argument");
      my $rel = $self->clone;
      $base = URI->new($base) unless ref $base;
  
      #my($scheme, $auth, $path) = @{$rel}{qw(scheme authority path)};
      my $scheme = $rel->scheme;
      my $auth   = $rel->canonical->authority;
      my $path   = $rel->path;
  
      if (!defined($scheme) && !defined($auth)) {
  	# it is already relative
  	return $rel;
      }
  
      #my($bscheme, $bauth, $bpath) = @{$base}{qw(scheme authority path)};
      my $bscheme = $base->scheme;
      my $bauth   = $base->canonical->authority;
      my $bpath   = $base->path;
  
      for ($bscheme, $bauth, $auth) {
  	$_ = '' unless defined
      }
  
      unless ($scheme eq $bscheme && $auth eq $bauth) {
  	# different location, can't make it relative
  	return $rel;
      }
  
      for ($path, $bpath) {  $_ = "/$_" unless m,^/,; }
  
      # Make it relative by eliminating scheme and authority
      $rel->scheme(undef);
      $rel->authority(undef);
  
      # This loop is based on code from Nicolai Langfeldt <janl@ifi.uio.no>.
      # First we calculate common initial path components length ($li).
      my $li = 1;
      while (1) {
  	my $i = index($path, '/', $li);
  	last if $i < 0 ||
                  $i != index($bpath, '/', $li) ||
  	        substr($path,$li,$i-$li) ne substr($bpath,$li,$i-$li);
  	$li=$i+1;
      }
      # then we nuke it from both paths
      substr($path, 0,$li) = '';
      substr($bpath,0,$li) = '';
  
      if ($path eq $bpath &&
          defined($rel->fragment) &&
          !defined($rel->query)) {
          $rel->path("");
      }
      else {
          # Add one "../" for each path component left in the base path
          $path = ('../' x $bpath =~ tr|/|/|) . $path;
  	$path = "./" if $path eq "";
          $rel->path($path);
      }
  
      $rel;
  }
  
  1;
URI__GENERIC

$fatpacked{"URI/_idna.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI__IDNA';
  package URI::_idna;
  
  # This module implements the RFCs 3490 (IDNA) and 3491 (Nameprep)
  # based on Python-2.6.4/Lib/encodings/idna.py
  
  use strict;
  use URI::_punycode qw(encode_punycode decode_punycode);
  use Carp qw(croak);
  
  BEGIN {
    *URI::_idna::_ENV_::JOIN_LEAKS_UTF8_FLAGS = $] < 5.008_003
      ? sub () { 1 }
      : sub () { 0 }
    ;
  }
  
  my $ASCII = qr/^[\x00-\x7F]*\z/;
  
  sub encode {
      my $idomain = shift;
      my @labels = split(/\./, $idomain, -1);
      my @last_empty;
      push(@last_empty, pop @labels) if @labels > 1 && $labels[-1] eq "";
      for (@labels) {
  	$_ = ToASCII($_);
      }
  
      return eval 'join(".", @labels, @last_empty)' if URI::_idna::_ENV_::JOIN_LEAKS_UTF8_FLAGS;
      return join(".", @labels, @last_empty);
  }
  
  sub decode {
      my $domain = shift;
      return join(".", map ToUnicode($_), split(/\./, $domain, -1))
  }
  
  sub nameprep { # XXX real implementation missing
      my $label = shift;
      $label = lc($label);
      return $label;
  }
  
  sub check_size {
      my $label = shift;
      croak "Label empty" if $label eq "";
      croak "Label too long" if length($label) > 63;
      return $label;
  }
  
  sub ToASCII {
      my $label = shift;
      return check_size($label) if $label =~ $ASCII;
  
      # Step 2: nameprep
      $label = nameprep($label);
      # Step 3: UseSTD3ASCIIRules is false
      # Step 4: try ASCII again
      return check_size($label) if $label =~ $ASCII;
  
      # Step 5: Check ACE prefix
      if ($label =~ /^xn--/) {
          croak "Label starts with ACE prefix";
      }
  
      # Step 6: Encode with PUNYCODE
      $label = encode_punycode($label);
  
      # Step 7: Prepend ACE prefix
      $label = "xn--$label";
  
      # Step 8: Check size
      return check_size($label);
  }
  
  sub ToUnicode {
      my $label = shift;
      $label = nameprep($label) unless $label =~ $ASCII;
      return $label unless $label =~ /^xn--/;
      my $result = decode_punycode(substr($label, 4));
      my $label2 = ToASCII($result);
      if (lc($label) ne $label2) {
  	croak "IDNA does not round-trip: '\L$label\E' vs '$label2'";
      }
      return $result;
  }
  
  1;
URI__IDNA

$fatpacked{"URI/_ldap.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI__LDAP';
  # Copyright (c) 1998 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.
  
  package URI::_ldap;
  
  use strict;
  
  use vars qw($VERSION);
  $VERSION = "1.12";
  
  use URI::Escape qw(uri_unescape);
  
  sub _ldap_elem {
    my $self  = shift;
    my $elem  = shift;
    my $query = $self->query;
    my @bits  = (split(/\?/,defined($query) ? $query : ""),("")x4);
    my $old   = $bits[$elem];
  
    if (@_) {
      my $new = shift;
      $new =~ s/\?/%3F/g;
      $bits[$elem] = $new;
      $query = join("?",@bits);
      $query =~ s/\?+$//;
      $query = undef unless length($query);
      $self->query($query);
    }
  
    $old;
  }
  
  sub dn {
    my $old = shift->path(@_);
    $old =~ s:^/::;
    uri_unescape($old);
  }
  
  sub attributes {
    my $self = shift;
    my $old = _ldap_elem($self,0, @_ ? join(",", map { my $tmp = $_; $tmp =~ s/,/%2C/g; $tmp } @_) : ());
    return $old unless wantarray;
    map { uri_unescape($_) } split(/,/,$old);
  }
  
  sub _scope {
    my $self = shift;
    my $old = _ldap_elem($self,1, @_);
    return unless defined wantarray && defined $old;
    uri_unescape($old);
  }
  
  sub scope {
    my $old = &_scope;
    $old = "base" unless length $old;
    $old;
  }
  
  sub _filter {
    my $self = shift;
    my $old = _ldap_elem($self,2, @_);
    return unless defined wantarray && defined $old;
    uri_unescape($old); # || "(objectClass=*)";
  }
  
  sub filter {
    my $old = &_filter;
    $old = "(objectClass=*)" unless length $old;
    $old;
  }
  
  sub extensions {
    my $self = shift;
    my @ext;
    while (@_) {
      my $key = shift;
      my $value = shift;
      push(@ext, join("=", map { $_="" unless defined; s/,/%2C/g; $_ } $key, $value));
    }
    @ext = join(",", @ext) if @ext;
    my $old = _ldap_elem($self,3, @ext);
    return $old unless wantarray;
    map { uri_unescape($_) } map { /^([^=]+)=(.*)$/ } split(/,/,$old);
  }
  
  sub canonical
  {
      my $self = shift;
      my $other = $self->_nonldap_canonical;
  
      # The stuff below is not as efficient as one might hope...
  
      $other = $other->clone if $other == $self;
  
      $other->dn(_normalize_dn($other->dn));
  
      # Should really know about mixed case "postalAddress", etc...
      $other->attributes(map lc, $other->attributes);
  
      # Lowercase scope, remove default
      my $old_scope = $other->scope;
      my $new_scope = lc($old_scope);
      $new_scope = "" if $new_scope eq "base";
      $other->scope($new_scope) if $new_scope ne $old_scope;
  
      # Remove filter if default
      my $old_filter = $other->filter;
      $other->filter("") if lc($old_filter) eq "(objectclass=*)" ||
  	                  lc($old_filter) eq "objectclass=*";
  
      # Lowercase extensions types and deal with known extension values
      my @ext = $other->extensions;
      for (my $i = 0; $i < @ext; $i += 2) {
  	my $etype = $ext[$i] = lc($ext[$i]);
  	if ($etype =~ /^!?bindname$/) {
  	    $ext[$i+1] = _normalize_dn($ext[$i+1]);
  	}
      }
      $other->extensions(@ext) if @ext;
      
      $other;
  }
  
  sub _normalize_dn  # RFC 2253
  {
      my $dn = shift;
  
      return $dn;
      # The code below will fail if the "+" or "," is embedding in a quoted
      # string or simply escaped...
  
      my @dn = split(/([+,])/, $dn);
      for (@dn) {
  	s/^([a-zA-Z]+=)/lc($1)/e;
      }
      join("", @dn);
  }
  
  1;
URI__LDAP

$fatpacked{"URI/_login.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI__LOGIN';
  package URI::_login;
  
  require URI::_server;
  require URI::_userpass;
  @ISA = qw(URI::_server URI::_userpass);
  
  # Generic terminal logins.  This is used as a base class for 'telnet',
  # 'tn3270', and 'rlogin' URL schemes.
  
  1;
URI__LOGIN

$fatpacked{"URI/_punycode.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI__PUNYCODE';
  package URI::_punycode;
  
  use strict;
  our $VERSION = "0.04";
  
  require Exporter;
  our @ISA    = qw(Exporter);
  our @EXPORT = qw(encode_punycode decode_punycode);
  
  use integer;
  
  our $DEBUG = 0;
  
  use constant BASE => 36;
  use constant TMIN => 1;
  use constant TMAX => 26;
  use constant SKEW => 38;
  use constant DAMP => 700;
  use constant INITIAL_BIAS => 72;
  use constant INITIAL_N => 128;
  
  my $Delimiter = chr 0x2D;
  my $BasicRE   = qr/[\x00-\x7f]/;
  
  sub _croak { require Carp; Carp::croak(@_); }
  
  sub digit_value {
      my $code = shift;
      return ord($code) - ord("A") if $code =~ /[A-Z]/;
      return ord($code) - ord("a") if $code =~ /[a-z]/;
      return ord($code) - ord("0") + 26 if $code =~ /[0-9]/;
      return;
  }
  
  sub code_point {
      my $digit = shift;
      return $digit + ord('a') if 0 <= $digit && $digit <= 25;
      return $digit + ord('0') - 26 if 26 <= $digit && $digit <= 36;
      die 'NOT COME HERE';
  }
  
  sub adapt {
      my($delta, $numpoints, $firsttime) = @_;
      $delta = $firsttime ? $delta / DAMP : $delta / 2;
      $delta += $delta / $numpoints;
      my $k = 0;
      while ($delta > ((BASE - TMIN) * TMAX) / 2) {
  	$delta /= BASE - TMIN;
  	$k += BASE;
      }
      return $k + (((BASE - TMIN + 1) * $delta) / ($delta + SKEW));
  }
  
  sub decode_punycode {
      my $code = shift;
  
      my $n      = INITIAL_N;
      my $i      = 0;
      my $bias   = INITIAL_BIAS;
      my @output;
  
      if ($code =~ s/(.*)$Delimiter//o) {
  	push @output, map ord, split //, $1;
  	return _croak('non-basic code point') unless $1 =~ /^$BasicRE*$/o;
      }
  
      while ($code) {
  	my $oldi = $i;
  	my $w    = 1;
      LOOP:
  	for (my $k = BASE; 1; $k += BASE) {
  	    my $cp = substr($code, 0, 1, '');
  	    my $digit = digit_value($cp);
  	    defined $digit or return _croak("invalid punycode input");
  	    $i += $digit * $w;
  	    my $t = ($k <= $bias) ? TMIN
  		: ($k >= $bias + TMAX) ? TMAX : $k - $bias;
  	    last LOOP if $digit < $t;
  	    $w *= (BASE - $t);
  	}
  	$bias = adapt($i - $oldi, @output + 1, $oldi == 0);
  	warn "bias becomes $bias" if $DEBUG;
  	$n += $i / (@output + 1);
  	$i = $i % (@output + 1);
  	splice(@output, $i, 0, $n);
  	warn join " ", map sprintf('%04x', $_), @output if $DEBUG;
  	$i++;
      }
      return join '', map chr, @output;
  }
  
  sub encode_punycode {
      my $input = shift;
      my @input = split //, $input;
  
      my $n     = INITIAL_N;
      my $delta = 0;
      my $bias  = INITIAL_BIAS;
  
      my @output;
      my @basic = grep /$BasicRE/, @input;
      my $h = my $b = @basic;
      push @output, @basic;
      push @output, $Delimiter if $b && $h < @input;
      warn "basic codepoints: (@output)" if $DEBUG;
  
      while ($h < @input) {
  	my $m = min(grep { $_ >= $n } map ord, @input);
  	warn sprintf "next code point to insert is %04x", $m if $DEBUG;
  	$delta += ($m - $n) * ($h + 1);
  	$n = $m;
  	for my $i (@input) {
  	    my $c = ord($i);
  	    $delta++ if $c < $n;
  	    if ($c == $n) {
  		my $q = $delta;
  	    LOOP:
  		for (my $k = BASE; 1; $k += BASE) {
  		    my $t = ($k <= $bias) ? TMIN :
  			($k >= $bias + TMAX) ? TMAX : $k - $bias;
  		    last LOOP if $q < $t;
  		    my $cp = code_point($t + (($q - $t) % (BASE - $t)));
  		    push @output, chr($cp);
  		    $q = ($q - $t) / (BASE - $t);
  		}
  		push @output, chr(code_point($q));
  		$bias = adapt($delta, $h + 1, $h == $b);
  		warn "bias becomes $bias" if $DEBUG;
  		$delta = 0;
  		$h++;
  	    }
  	}
  	$delta++;
  	$n++;
      }
      return join '', @output;
  }
  
  sub min {
      my $min = shift;
      for (@_) { $min = $_ if $_ <= $min }
      return $min;
  }
  
  1;
  __END__
  
  =head1 NAME
  
  URI::_punycode - encodes Unicode string in Punycode
  
  =head1 SYNOPSIS
  
    use URI::_punycode;
    $punycode = encode_punycode($unicode);
    $unicode  = decode_punycode($punycode);
  
  =head1 DESCRIPTION
  
  URI::_punycode is a module to encode / decode Unicode strings into
  Punycode, an efficient encoding of Unicode for use with IDNA.
  
  This module requires Perl 5.6.0 or over to handle UTF8 flagged Unicode
  strings.
  
  =head1 FUNCTIONS
  
  This module exports following functions by default.
  
  =over 4
  
  =item encode_punycode
  
    $punycode = encode_punycode($unicode);
  
  takes Unicode string (UTF8-flagged variable) and returns Punycode
  encoding for it.
  
  =item decode_punycode
  
    $unicode = decode_punycode($punycode)
  
  takes Punycode encoding and returns original Unicode string.
  
  =back
  
  These functions throw exceptions on failure. You can catch 'em via
  C<eval>.
  
  =head1 AUTHOR
  
  Tatsuhiko Miyagawa E<lt>miyagawa@bulknews.netE<gt> is the author of
  IDNA::Punycode v0.02 which was the basis for this module.
  
  This library is free software; you can redistribute it and/or modify
  it under the same terms as Perl itself.
  
  =head1 SEE ALSO
  
  L<IDNA::Punycode>, RFC 3492
  
  =cut
URI__PUNYCODE

$fatpacked{"URI/_query.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI__QUERY';
  package URI::_query;
  
  use strict;
  use URI ();
  use URI::Escape qw(uri_unescape);
  
  sub query
  {
      my $self = shift;
      $$self =~ m,^([^?\#]*)(?:\?([^\#]*))?(.*)$,s or die;
  
      if (@_) {
  	my $q = shift;
  	$$self = $1;
  	if (defined $q) {
  	    $q =~ s/([^$URI::uric])/ URI::Escape::escape_char($1)/ego;
  	    utf8::downgrade($q);
  	    $$self .= "?$q";
  	}
  	$$self .= $3;
      }
      $2;
  }
  
  # Handle ...?foo=bar&bar=foo type of query
  sub query_form {
      my $self = shift;
      my $old = $self->query;
      if (@_) {
          # Try to set query string
          my $delim;
          my $r = $_[0];
          if (ref($r) eq "ARRAY") {
              $delim = $_[1];
              @_ = @$r;
          }
          elsif (ref($r) eq "HASH") {
              $delim = $_[1];
              @_ = %$r;
          }
          $delim = pop if @_ % 2;
  
          my @query;
          while (my($key,$vals) = splice(@_, 0, 2)) {
              $key = '' unless defined $key;
  	    $key =~ s/([;\/?:@&=+,\$\[\]%])/ URI::Escape::escape_char($1)/eg;
  	    $key =~ s/ /+/g;
  	    $vals = [ref($vals) eq "ARRAY" ? @$vals : $vals];
              for my $val (@$vals) {
                  $val = '' unless defined $val;
  		$val =~ s/([;\/?:@&=+,\$\[\]%])/ URI::Escape::escape_char($1)/eg;
                  $val =~ s/ /+/g;
                  push(@query, "$key=$val");
              }
          }
          if (@query) {
              unless ($delim) {
                  $delim = $1 if $old && $old =~ /([&;])/;
                  $delim ||= $URI::DEFAULT_QUERY_FORM_DELIMITER || "&";
              }
              $self->query(join($delim, @query));
          }
          else {
              $self->query(undef);
          }
      }
      return if !defined($old) || !length($old) || !defined(wantarray);
      return unless $old =~ /=/; # not a form
      map { s/\+/ /g; uri_unescape($_) }
           map { /=/ ? split(/=/, $_, 2) : ($_ => '')} split(/[&;]/, $old);
  }
  
  # Handle ...?dog+bones type of query
  sub query_keywords
  {
      my $self = shift;
      my $old = $self->query;
      if (@_) {
          # Try to set query string
  	my @copy = @_;
  	@copy = @{$copy[0]} if @copy == 1 && ref($copy[0]) eq "ARRAY";
  	for (@copy) { s/([;\/?:@&=+,\$\[\]%])/ URI::Escape::escape_char($1)/eg; }
  	$self->query(@copy ? join('+', @copy) : undef);
      }
      return if !defined($old) || !defined(wantarray);
      return if $old =~ /=/;  # not keywords, but a form
      map { uri_unescape($_) } split(/\+/, $old, -1);
  }
  
  # Some URI::URL compatibility stuff
  *equery = \&query;
  
  1;
URI__QUERY

$fatpacked{"URI/_segment.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI__SEGMENT';
  package URI::_segment;
  
  # Represents a generic path_segment so that it can be treated as
  # a string too.
  
  use strict;
  use URI::Escape qw(uri_unescape);
  
  use overload '""' => sub { $_[0]->[0] },
               fallback => 1;
  
  sub new
  {
      my $class = shift;
      my @segment = split(';', shift, -1);
      $segment[0] = uri_unescape($segment[0]);
      bless \@segment, $class;
  }
  
  1;
URI__SEGMENT

$fatpacked{"URI/_server.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI__SERVER';
  package URI::_server;
  require URI::_generic;
  @ISA=qw(URI::_generic);
  
  use strict;
  use URI::Escape qw(uri_unescape);
  
  sub _uric_escape {
      my($class, $str) = @_;
      if ($str =~ m,^((?:$URI::scheme_re:)?)//([^/?\#]*)(.*)$,os) {
  	my($scheme, $host, $rest) = ($1, $2, $3);
  	my $ui = $host =~ s/(.*@)// ? $1 : "";
  	my $port = $host =~ s/(:\d+)\z// ? $1 : "";
  	if (_host_escape($host)) {
  	    $str = "$scheme//$ui$host$port$rest";
  	}
      }
      return $class->SUPER::_uric_escape($str);
  }
  
  sub _host_escape {
      return unless $_[0] =~ /[^URI::uric]/;
      eval {
  	require URI::_idna;
  	$_[0] = URI::_idna::encode($_[0]);
      };
      return 0 if $@;
      return 1;
  }
  
  sub as_iri {
      my $self = shift;
      my $str = $self->SUPER::as_iri;
      if ($str =~ /\bxn--/) {
  	if ($str =~ m,^((?:$URI::scheme_re:)?)//([^/?\#]*)(.*)$,os) {
  	    my($scheme, $host, $rest) = ($1, $2, $3);
  	    my $ui = $host =~ s/(.*@)// ? $1 : "";
  	    my $port = $host =~ s/(:\d+)\z// ? $1 : "";
  	    require URI::_idna;
  	    $host = URI::_idna::decode($host);
  	    $str = "$scheme//$ui$host$port$rest";
  	}
      }
      return $str;
  }
  
  sub userinfo
  {
      my $self = shift;
      my $old = $self->authority;
  
      if (@_) {
  	my $new = $old;
  	$new = "" unless defined $new;
  	$new =~ s/.*@//;  # remove old stuff
  	my $ui = shift;
  	if (defined $ui) {
  	    $ui =~ s/@/%40/g;   # protect @
  	    $new = "$ui\@$new";
  	}
  	$self->authority($new);
      }
      return undef if !defined($old) || $old !~ /(.*)@/;
      return $1;
  }
  
  sub host
  {
      my $self = shift;
      my $old = $self->authority;
      if (@_) {
  	my $tmp = $old;
  	$tmp = "" unless defined $tmp;
  	my $ui = ($tmp =~ /(.*@)/) ? $1 : "";
  	my $port = ($tmp =~ /(:\d+)$/) ? $1 : "";
  	my $new = shift;
  	$new = "" unless defined $new;
  	if (length $new) {
  	    $new =~ s/[@]/%40/g;   # protect @
  	    if ($new =~ /^[^:]*:\d*\z/ || $new =~ /]:\d*\z/) {
  		$new =~ s/(:\d*)\z// || die "Assert";
  		$port = $1;
  	    }
  	    $new = "[$new]" if $new =~ /:/ && $new !~ /^\[/; # IPv6 address
  	    _host_escape($new);
  	}
  	$self->authority("$ui$new$port");
      }
      return undef unless defined $old;
      $old =~ s/.*@//;
      $old =~ s/:\d+$//;          # remove the port
      $old =~ s{^\[(.*)\]$}{$1};  # remove brackets around IPv6 (RFC 3986 3.2.2)
      return uri_unescape($old);
  }
  
  sub ihost
  {
      my $self = shift;
      my $old = $self->host(@_);
      if ($old =~ /(^|\.)xn--/) {
  	require URI::_idna;
  	$old = URI::_idna::decode($old);
      }
      return $old;
  }
  
  sub _port
  {
      my $self = shift;
      my $old = $self->authority;
      if (@_) {
  	my $new = $old;
  	$new =~ s/:\d*$//;
  	my $port = shift;
  	$new .= ":$port" if defined $port;
  	$self->authority($new);
      }
      return $1 if defined($old) && $old =~ /:(\d*)$/;
      return;
  }
  
  sub port
  {
      my $self = shift;
      my $port = $self->_port(@_);
      $port = $self->default_port if !defined($port) || $port eq "";
      $port;
  }
  
  sub host_port
  {
      my $self = shift;
      my $old = $self->authority;
      $self->host(shift) if @_;
      return undef unless defined $old;
      $old =~ s/.*@//;        # zap userinfo
      $old =~ s/:$//;         # empty port should be treated the same a no port
      $old .= ":" . $self->port unless $old =~ /:\d+$/;
      $old;
  }
  
  
  sub default_port { undef }
  
  sub canonical
  {
      my $self = shift;
      my $other = $self->SUPER::canonical;
      my $host = $other->host || "";
      my $port = $other->_port;
      my $uc_host = $host =~ /[A-Z]/;
      my $def_port = defined($port) && ($port eq "" ||
                                        $port == $self->default_port);
      if ($uc_host || $def_port) {
  	$other = $other->clone if $other == $self;
  	$other->host(lc $host) if $uc_host;
  	$other->port(undef)    if $def_port;
      }
      $other;
  }
  
  1;
URI__SERVER

$fatpacked{"URI/_userpass.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI__USERPASS';
  package URI::_userpass;
  
  use strict;
  use URI::Escape qw(uri_unescape);
  
  sub user
  {
      my $self = shift;
      my $info = $self->userinfo;
      if (@_) {
  	my $new = shift;
  	my $pass = defined($info) ? $info : "";
  	$pass =~ s/^[^:]*//;
  
  	if (!defined($new) && !length($pass)) {
  	    $self->userinfo(undef);
  	} else {
  	    $new = "" unless defined($new);
  	    $new =~ s/%/%25/g;
  	    $new =~ s/:/%3A/g;
  	    $self->userinfo("$new$pass");
  	}
      }
      return unless defined $info;
      $info =~ s/:.*//;
      uri_unescape($info);
  }
  
  sub password
  {
      my $self = shift;
      my $info = $self->userinfo;
      if (@_) {
  	my $new = shift;
  	my $user = defined($info) ? $info : "";
  	$user =~ s/:.*//;
  
  	if (!defined($new) && !length($user)) {
  	    $self->userinfo(undef);
  	} else {
  	    $new = "" unless defined($new);
  	    $new =~ s/%/%25/g;
  	    $self->userinfo("$user:$new");
  	}
      }
      return unless defined $info;
      return unless $info =~ s/^[^:]*://;
      uri_unescape($info);
  }
  
  1;
URI__USERPASS

$fatpacked{"URI/data.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI_DATA';
  package URI::data;  # RFC 2397
  
  require URI;
  @ISA=qw(URI);
  
  use strict;
  
  use MIME::Base64 qw(encode_base64 decode_base64);
  use URI::Escape  qw(uri_unescape);
  
  sub media_type
  {
      my $self = shift;
      my $opaque = $self->opaque;
      $opaque =~ /^([^,]*),?/ or die;
      my $old = $1;
      my $base64;
      $base64 = $1 if $old =~ s/(;base64)$//i;
      if (@_) {
  	my $new = shift;
  	$new = "" unless defined $new;
  	$new =~ s/%/%25/g;
  	$new =~ s/,/%2C/g;
  	$base64 = "" unless defined $base64;
  	$opaque =~ s/^[^,]*,?/$new$base64,/;
  	$self->opaque($opaque);
      }
      return uri_unescape($old) if $old;  # media_type can't really be "0"
      "text/plain;charset=US-ASCII";      # default type
  }
  
  sub data
  {
      my $self = shift;
      my($enc, $data) = split(",", $self->opaque, 2);
      unless (defined $data) {
  	$data = "";
  	$enc  = "" unless defined $enc;
      }
      my $base64 = ($enc =~ /;base64$/i);
      if (@_) {
  	$enc =~ s/;base64$//i if $base64;
  	my $new = shift;
  	$new = "" unless defined $new;
  	my $uric_count = _uric_count($new);
  	my $urienc_len = $uric_count + (length($new) - $uric_count) * 3;
  	my $base64_len = int((length($new)+2) / 3) * 4;
  	$base64_len += 7;  # because of ";base64" marker
  	if ($base64_len < $urienc_len || $_[0]) {
  	    $enc .= ";base64";
  	    $new = encode_base64($new, "");
  	} else {
  	    $new =~ s/%/%25/g;
  	}
  	$self->opaque("$enc,$new");
      }
      return unless defined wantarray;
      $data = uri_unescape($data);
      return $base64 ? decode_base64($data) : $data;
  }
  
  # I could not find a better way to interpolate the tr/// chars from
  # a variable.
  my $ENC = $URI::uric;
  $ENC =~ s/%//;
  
  eval <<EOT; die $@ if $@;
  sub _uric_count
  {
      \$_[0] =~ tr/$ENC//;
  }
  EOT
  
  1;
  
  __END__
  
  =head1 NAME
  
  URI::data - URI that contains immediate data
  
  =head1 SYNOPSIS
  
   use URI;
  
   $u = URI->new("data:");
   $u->media_type("image/gif");
   $u->data(scalar(`cat camel.gif`));
   print "$u\n";
   open(XV, "|xv -") and print XV $u->data;
  
  =head1 DESCRIPTION
  
  The C<URI::data> class supports C<URI> objects belonging to the I<data>
  URI scheme.  The I<data> URI scheme is specified in RFC 2397.  It
  allows inclusion of small data items as "immediate" data, as if it had
  been included externally.  Examples:
  
    data:,Perl%20is%20good
  
    data:image/gif;base64,R0lGODdhIAAgAIAAAAAAAPj8+CwAAAAAI
      AAgAAAClYyPqcu9AJyCjtIKc5w5xP14xgeO2tlY3nWcajmZZdeJcG
      Kxrmimms1KMTa1Wg8UROx4MNUq1HrycMjHT9b6xKxaFLM6VRKzI+p
      KS9XtXpcbdun6uWVxJXA8pNPkdkkxhxc21LZHFOgD2KMoQXa2KMWI
      JtnE2KizVUkYJVZZ1nczBxXlFopZBtoJ2diXGdNUymmJdFMAADs=
  
  
  
  C<URI> objects belonging to the data scheme support the common methods
  (described in L<URI>) and the following two scheme-specific methods:
  
  =over 4
  
  =item $uri->media_type( [$new_media_type] )
  
  Can be used to get or set the media type specified in the
  URI.  If no media type is specified, then the default
  C<"text/plain;charset=US-ASCII"> is returned.
  
  =item $uri->data( [$new_data] )
  
  Can be used to get or set the data contained in the URI.
  The data is passed unescaped (in binary form).  The decision about
  whether to base64 encode the data in the URI is taken automatically,
  based on the encoding that produces the shorter URI string.
  
  =back
  
  =head1 SEE ALSO
  
  L<URI>
  
  =head1 COPYRIGHT
  
  Copyright 1995-1998 Gisle Aas.
  
  This library is free software; you can redistribute it and/or
  modify it under the same terms as Perl itself.
  
  =cut
URI_DATA

$fatpacked{"URI/file.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI_FILE';
  package URI::file;
  
  use strict;
  use vars qw(@ISA $VERSION $DEFAULT_AUTHORITY %OS_CLASS);
  
  require URI::_generic;
  @ISA = qw(URI::_generic);
  $VERSION = "4.21";
  
  use URI::Escape qw(uri_unescape);
  
  $DEFAULT_AUTHORITY = "";
  
  # Map from $^O values to implementation classes.  The Unix
  # class is the default.
  %OS_CLASS = (
       os2     => "OS2",
       mac     => "Mac",
       MacOS   => "Mac",
       MSWin32 => "Win32",
       win32   => "Win32",
       msdos   => "FAT",
       dos     => "FAT",
       qnx     => "QNX",
  );
  
  sub os_class
  {
      my($OS) = shift || $^O;
  
      my $class = "URI::file::" . ($OS_CLASS{$OS} || "Unix");
      no strict 'refs';
      unless (%{"$class\::"}) {
  	eval "require $class";
  	die $@ if $@;
      }
      $class;
  }
  
  sub host { uri_unescape(shift->authority(@_)) }
  
  sub new
  {
      my($class, $path, $os) = @_;
      os_class($os)->new($path);
  }
  
  sub new_abs
  {
      my $class = shift;
      my $file = $class->new(@_);
      return $file->abs($class->cwd) unless $$file =~ /^file:/;
      $file;
  }
  
  sub cwd
  {
      my $class = shift;
      require Cwd;
      my $cwd = Cwd::cwd();
      $cwd = VMS::Filespec::unixpath($cwd) if $^O eq 'VMS';
      $cwd = $class->new($cwd);
      $cwd .= "/" unless substr($cwd, -1, 1) eq "/";
      $cwd;
  }
  
  sub canonical {
      my $self = shift;
      my $other = $self->SUPER::canonical;
  
      my $scheme = $other->scheme;
      my $auth = $other->authority;
      return $other if !defined($scheme) && !defined($auth);  # relative
  
      if (!defined($auth) ||
  	$auth eq "" ||
  	lc($auth) eq "localhost" ||
  	(defined($DEFAULT_AUTHORITY) && lc($auth) eq lc($DEFAULT_AUTHORITY))
         )
      {
  	# avoid cloning if $auth already match
  	if ((defined($auth) || defined($DEFAULT_AUTHORITY)) &&
  	    (!defined($auth) || !defined($DEFAULT_AUTHORITY) || $auth ne $DEFAULT_AUTHORITY)
  	   )
  	{
  	    $other = $other->clone if $self == $other;
  	    $other->authority($DEFAULT_AUTHORITY);
          }
      }
  
      $other;
  }
  
  sub file
  {
      my($self, $os) = @_;
      os_class($os)->file($self);
  }
  
  sub dir
  {
      my($self, $os) = @_;
      os_class($os)->dir($self);
  }
  
  1;
  
  __END__
  
  =head1 NAME
  
  URI::file - URI that maps to local file names
  
  =head1 SYNOPSIS
  
   use URI::file;
   
   $u1 = URI->new("file:/foo/bar");
   $u2 = URI->new("foo/bar", "file");
   
   $u3 = URI::file->new($path);
   $u4 = URI::file->new("c:\\windows\\", "win32");
   
   $u1->file;
   $u1->file("mac");
  
  =head1 DESCRIPTION
  
  The C<URI::file> class supports C<URI> objects belonging to the I<file>
  URI scheme.  This scheme allows us to map the conventional file names
  found on various computer systems to the URI name space.  An old
  specification of the I<file> URI scheme is found in RFC 1738.  Some
  older background information is also in RFC 1630. There are no newer
  specifications as far as I know.
  
  If you simply want to construct I<file> URI objects from URI strings,
  use the normal C<URI> constructor.  If you want to construct I<file>
  URI objects from the actual file names used by various systems, then
  use one of the following C<URI::file> constructors:
  
  =over 4
  
  =item $u = URI::file->new( $filename, [$os] )
  
  Maps a file name to the I<file:> URI name space, creates a URI object
  and returns it.  The $filename is interpreted as belonging to the
  indicated operating system ($os), which defaults to the value of the
  $^O variable.  The $filename can be either absolute or relative, and
  the corresponding type of URI object for $os is returned.
  
  =item $u = URI::file->new_abs( $filename, [$os] )
  
  Same as URI::file->new, but makes sure that the URI returned
  represents an absolute file name.  If the $filename argument is
  relative, then the name is resolved relative to the current directory,
  i.e. this constructor is really the same as:
  
    URI::file->new($filename)->abs(URI::file->cwd);
  
  =item $u = URI::file->cwd
  
  Returns a I<file> URI that represents the current working directory.
  See L<Cwd>.
  
  =back
  
  The following methods are supported for I<file> URI (in addition to
  the common and generic methods described in L<URI>):
  
  =over 4
  
  =item $u->file( [$os] )
  
  Returns a file name.  It maps from the URI name space
  to the file name space of the indicated operating system.
  
  It might return C<undef> if the name can not be represented in the
  indicated file system.
  
  =item $u->dir( [$os] )
  
  Some systems use a different form for names of directories than for plain
  files.  Use this method if you know you want to use the name for
  a directory.
  
  =back
  
  The C<URI::file> module can be used to map generic file names to names
  suitable for the current system.  As such, it can work as a nice
  replacement for the C<File::Spec> module.  For instance, the following
  code translates the UNIX-style file name F<Foo/Bar.pm> to a name
  suitable for the local system:
  
    $file = URI::file->new("Foo/Bar.pm", "unix")->file;
    die "Can't map filename Foo/Bar.pm for $^O" unless defined $file;
    open(FILE, $file) || die "Can't open '$file': $!";
    # do something with FILE
  
  =head1 MAPPING NOTES
  
  Most computer systems today have hierarchically organized file systems.
  Mapping the names used in these systems to the generic URI syntax
  allows us to work with relative file URIs that behave as they should
  when resolved using the generic algorithm for URIs (specified in RFC
  2396).  Mapping a file name to the generic URI syntax involves mapping
  the path separator character to "/" and encoding any reserved
  characters that appear in the path segments of the file name.  If
  path segments consisting of the strings "." or ".." have a
  different meaning than what is specified for generic URIs, then these
  must be encoded as well.
  
  If the file system has device, volume or drive specifications as
  the root of the name space, then it makes sense to map them to the
  authority field of the generic URI syntax.  This makes sure that
  relative URIs can not be resolved "above" them, i.e. generally how
  relative file names work in those systems.
  
  Another common use of the authority field is to encode the host on which
  this file name is valid.  The host name "localhost" is special and
  generally has the same meaning as a missing or empty authority
  field.  This use is in conflict with using it as a device
  specification, but can often be resolved for device specifications
  having characters not legal in plain host names.
  
  File name to URI mapping in normally not one-to-one.  There are
  usually many URIs that map to any given file name.  For instance, an
  authority of "localhost" maps the same as a URI with a missing or empty
  authority.
  
  Example 1: The Mac classic (Mac OS 9 and earlier) used ":" as path separator,
  but not in the same way as a generic URI. ":foo" was a relative name.  "foo:bar"
  was an absolute name.  Also, path segments could contain the "/" character as well
  as the literal "." or "..".  So the mapping looks like this:
  
    Mac classic           URI
    ----------            -------------------
    :foo:bar     <==>     foo/bar
    :            <==>     ./
    ::foo:bar    <==>     ../foo/bar
    :::          <==>     ../../
    foo:bar      <==>     file:/foo/bar
    foo:bar:     <==>     file:/foo/bar/
    ..           <==>     %2E%2E
    <undef>      <==      /
    foo/         <==      file:/foo%2F
    ./foo.txt    <==      file:/.%2Ffoo.txt
  
  Note that if you want a relative URL, you *must* begin the path with a :.  Any
  path that begins with [^:] is treated as absolute.
  
  Example 2: The UNIX file system is easy to map, as it uses the same path
  separator as URIs, has a single root, and segments of "." and ".."
  have the same meaning.  URIs that have the character "\0" or "/" as
  part of any path segment can not be turned into valid UNIX file names.
  
    UNIX                  URI
    ----------            ------------------
    foo/bar      <==>     foo/bar
    /foo/bar     <==>     file:/foo/bar
    /foo/bar     <==      file://localhost/foo/bar
    file:         ==>     ./file:
    <undef>      <==      file:/fo%00/bar
    /            <==>     file:/
  
  =cut
  
  
  RFC 1630
  
     [...]
  
     There is clearly a danger of confusion that a link made to a local
     file should be followed by someone on a different system, with
     unexpected and possibly harmful results.  Therefore, the convention
     is that even a "file" URL is provided with a host part.  This allows
     a client on another system to know that it cannot access the file
     system, or perhaps to use some other local mechanism to access the
     file.
  
     The special value "localhost" is used in the host field to indicate
     that the filename should really be used on whatever host one is.
     This for example allows links to be made to files which are
     distributed on many machines, or to "your unix local password file"
     subject of course to consistency across the users of the data.
  
     A void host field is equivalent to "localhost".
  
  =head1 CONFIGURATION VARIABLES
  
  The following configuration variables influence how the class and its
  methods behave:
  
  =over
  
  =item %URI::file::OS_CLASS
  
  This hash maps OS identifiers to implementation classes.  You might
  want to add or modify this if you want to plug in your own file
  handler class.  Normally the keys should match the $^O values in use.
  
  If there is no mapping then the "Unix" implementation is used.
  
  =item $URI::file::DEFAULT_AUTHORITY
  
  This determine what "authority" string to include in absolute file
  URIs.  It defaults to "".  If you prefer verbose URIs you might set it
  to be "localhost".
  
  Setting this value to C<undef> force behaviour compatible to URI v1.31
  and earlier.  In this mode host names in UNC paths and drive letters
  are mapped to the authority component on Windows, while we produce
  authority-less URIs on Unix.
  
  =back
  
  
  =head1 SEE ALSO
  
  L<URI>, L<File::Spec>, L<perlport>
  
  =head1 COPYRIGHT
  
  Copyright 1995-1998,2004 Gisle Aas.
  
  This library is free software; you can redistribute it and/or
  modify it under the same terms as Perl itself.
  
  =cut
URI_FILE

$fatpacked{"URI/file/Base.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI_FILE_BASE';
  package URI::file::Base;
  
  use strict;
  use URI::Escape qw();
  
  sub new
  {
      my $class = shift;
      my $path  = shift;
      $path = "" unless defined $path;
  
      my($auth, $escaped_auth, $escaped_path);
  
      ($auth, $escaped_auth) = $class->_file_extract_authority($path);
      ($path, $escaped_path) = $class->_file_extract_path($path);
  
      if (defined $auth) {
  	$auth =~ s,%,%25,g unless $escaped_auth;
  	$auth =~ s,([/?\#]), URI::Escape::escape_char($1),eg;
  	$auth = "//$auth";
  	if (defined $path) {
  	    $path = "/$path" unless substr($path, 0, 1) eq "/";
  	} else {
  	    $path = "";
  	}
      } else {
  	return undef unless defined $path;
  	$auth = "";
      }
  
      $path =~ s,([%;?]), URI::Escape::escape_char($1),eg unless $escaped_path;
      $path =~ s/\#/%23/g;
  
      my $uri = $auth . $path;
      $uri = "file:$uri" if substr($uri, 0, 1) eq "/";
  
      URI->new($uri, "file");
  }
  
  sub _file_extract_authority
  {
      my($class, $path) = @_;
      return undef unless $class->_file_is_absolute($path);
      return $URI::file::DEFAULT_AUTHORITY;
  }
  
  sub _file_extract_path
  {
      return undef;
  }
  
  sub _file_is_absolute
  {
      return 0;
  }
  
  sub _file_is_localhost
  {
      shift; # class
      my $host = lc(shift);
      return 1 if $host eq "localhost";
      eval {
  	require Net::Domain;
  	lc(Net::Domain::hostfqdn()) eq $host ||
  	lc(Net::Domain::hostname()) eq $host;
      };
  }
  
  sub file
  {
      undef;
  }
  
  sub dir
  {
      my $self = shift;
      $self->file(@_);
  }
  
  1;
URI_FILE_BASE

$fatpacked{"URI/file/FAT.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI_FILE_FAT';
  package URI::file::FAT;
  
  require URI::file::Win32;
  @ISA=qw(URI::file::Win32);
  
  sub fix_path
  {
      shift; # class
      for (@_) {
  	# turn it into 8.3 names
  	my @p = map uc, split(/\./, $_, -1);
  	return if @p > 2;     # more than 1 dot is not allowed
  	@p = ("") unless @p;  # split bug? (returns nothing when splitting "")
  	$_ = substr($p[0], 0, 8);
          if (@p > 1) {
  	    my $ext = substr($p[1], 0, 3);
  	    $_ .= ".$ext" if length $ext;
  	}
      }
      1;  # ok
  }
  
  1;
URI_FILE_FAT

$fatpacked{"URI/file/Mac.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI_FILE_MAC';
  package URI::file::Mac;
  
  require URI::file::Base;
  @ISA=qw(URI::file::Base);
  
  use strict;
  use URI::Escape qw(uri_unescape);
  
  
  
  sub _file_extract_path
  {
      my $class = shift;
      my $path = shift;
  
      my @pre;
      if ($path =~ s/^(:+)//) {
  	if (length($1) == 1) {
  	    @pre = (".") unless length($path);
  	} else {
  	    @pre = ("..") x (length($1) - 1);
  	}
      } else { #absolute
  	$pre[0] = "";
      }
  
      my $isdir = ($path =~ s/:$//);
      $path =~ s,([%/;]), URI::Escape::escape_char($1),eg;
  
      my @path = split(/:/, $path, -1);
      for (@path) {
  	if ($_ eq "." || $_ eq "..") {
  	    $_ = "%2E" x length($_);
  	}
  	$_ = ".." unless length($_);
      }
      push (@path,"") if $isdir;
      (join("/", @pre, @path), 1);
  }
  
  
  sub file
  {
      my $class = shift;
      my $uri = shift;
      my @path;
  
      my $auth = $uri->authority;
      if (defined $auth) {
  	if (lc($auth) ne "localhost" && $auth ne "") {
  	    my $u_auth = uri_unescape($auth);
  	    if (!$class->_file_is_localhost($u_auth)) {
  		# some other host (use it as volume name)
  		@path = ("", $auth);
  		# XXX or just return to make it illegal;
  	    }
  	}
      }
      my @ps = split("/", $uri->path, -1);
      shift @ps if @path;
      push(@path, @ps);
  
      my $pre = "";
      if (!@path) {
  	return;  # empty path; XXX return ":" instead?
      } elsif ($path[0] eq "") {
  	# absolute
  	shift(@path);
  	if (@path == 1) {
  	    return if $path[0] eq "";  # not root directory
  	    push(@path, "");           # volume only, effectively append ":"
  	}
  	@ps = @path;
  	@path = ();
          my $part;
  	for (@ps) {  #fix up "." and "..", including interior, in relatives
  	    next if $_ eq ".";
  	    $part = $_ eq ".." ? "" : $_;
  	    push(@path,$part);
  	}
  	if ($ps[-1] eq "..") {  #if this happens, we need another :
  	    push(@path,"");
  	}
  	
      } else {
  	$pre = ":";
  	@ps = @path;
  	@path = ();
          my $part;
  	for (@ps) {  #fix up "." and "..", including interior, in relatives
  	    next if $_ eq ".";
  	    $part = $_ eq ".." ? "" : $_;
  	    push(@path,$part);
  	}
  	if ($ps[-1] eq "..") {  #if this happens, we need another :
  	    push(@path,"");
  	}
  	
      }
      return unless $pre || @path;
      for (@path) {
  	s/;.*//;  # get rid of parameters
  	#return unless length; # XXX
  	$_ = uri_unescape($_);
  	return if /\0/;
  	return if /:/;  # Should we?
      }
      $pre . join(":", @path);
  }
  
  sub dir
  {
      my $class = shift;
      my $path = $class->file(@_);
      return unless defined $path;
      $path .= ":" unless $path =~ /:$/;
      $path;
  }
  
  1;
URI_FILE_MAC

$fatpacked{"URI/file/OS2.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI_FILE_OS2';
  package URI::file::OS2;
  
  require URI::file::Win32;
  @ISA=qw(URI::file::Win32);
  
  # The Win32 version translates k:/foo to file://k:/foo  (?!)
  # We add an empty host
  
  sub _file_extract_authority
  {
      my $class = shift;
      return $1 if $_[0] =~ s,^\\\\([^\\]+),,;  # UNC
      return $1 if $_[0] =~ s,^//([^/]+),,;     # UNC too?
  
      if ($_[0] =~ m#^[a-zA-Z]{1,2}:#) {	      # allow for ab: drives
  	return "";
      }
      return;
  }
  
  sub file {
    my $p = &URI::file::Win32::file;
    return unless defined $p;
    $p =~ s,\\,/,g;
    $p;
  }
  
  1;
URI_FILE_OS2

$fatpacked{"URI/file/QNX.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI_FILE_QNX';
  package URI::file::QNX;
  
  require URI::file::Unix;
  @ISA=qw(URI::file::Unix);
  
  use strict;
  
  sub _file_extract_path
  {
      my($class, $path) = @_;
      # tidy path
      $path =~ s,(.)//+,$1/,g; # ^// is correct
      $path =~ s,(/\.)+/,/,g;
      $path = "./$path" if $path =~ m,^[^:/]+:,,; # look like "scheme:"
      $path;
  }
  
  1;
URI_FILE_QNX

$fatpacked{"URI/file/Unix.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI_FILE_UNIX';
  package URI::file::Unix;
  
  require URI::file::Base;
  @ISA=qw(URI::file::Base);
  
  use strict;
  use URI::Escape qw(uri_unescape);
  
  sub _file_extract_path
  {
      my($class, $path) = @_;
  
      # tidy path
      $path =~ s,//+,/,g;
      $path =~ s,(/\.)+/,/,g;
      $path = "./$path" if $path =~ m,^[^:/]+:,,; # look like "scheme:"
  
      return $path;
  }
  
  sub _file_is_absolute {
      my($class, $path) = @_;
      return $path =~ m,^/,;
  }
  
  sub file
  {
      my $class = shift;
      my $uri = shift;
      my @path;
  
      my $auth = $uri->authority;
      if (defined($auth)) {
  	if (lc($auth) ne "localhost" && $auth ne "") {
  	    $auth = uri_unescape($auth);
  	    unless ($class->_file_is_localhost($auth)) {
  		push(@path, "", "", $auth);
  	    }
  	}
      }
  
      my @ps = $uri->path_segments;
      shift @ps if @path;
      push(@path, @ps);
  
      for (@path) {
  	# Unix file/directory names are not allowed to contain '\0' or '/'
  	return undef if /\0/;
  	return undef if /\//;  # should we really?
      }
  
      return join("/", @path);
  }
  
  1;
URI_FILE_UNIX

$fatpacked{"URI/file/Win32.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI_FILE_WIN32';
  package URI::file::Win32;
  
  require URI::file::Base;
  @ISA=qw(URI::file::Base);
  
  use strict;
  use URI::Escape qw(uri_unescape);
  
  sub _file_extract_authority
  {
      my $class = shift;
  
      return $class->SUPER::_file_extract_authority($_[0])
  	if defined $URI::file::DEFAULT_AUTHORITY;
  
      return $1 if $_[0] =~ s,^\\\\([^\\]+),,;  # UNC
      return $1 if $_[0] =~ s,^//([^/]+),,;     # UNC too?
  
      if ($_[0] =~ s,^([a-zA-Z]:),,) {
  	my $auth = $1;
  	$auth .= "relative" if $_[0] !~ m,^[\\/],;
  	return $auth;
      }
      return undef;
  }
  
  sub _file_extract_path
  {
      my($class, $path) = @_;
      $path =~ s,\\,/,g;
      #$path =~ s,//+,/,g;
      $path =~ s,(/\.)+/,/,g;
  
      if (defined $URI::file::DEFAULT_AUTHORITY) {
  	$path =~ s,^([a-zA-Z]:),/$1,;
      }
  
      return $path;
  }
  
  sub _file_is_absolute {
      my($class, $path) = @_;
      return $path =~ m,^[a-zA-Z]:, || $path =~ m,^[/\\],;
  }
  
  sub file
  {
      my $class = shift;
      my $uri = shift;
      my $auth = $uri->authority;
      my $rel; # is filename relative to drive specified in authority
      if (defined $auth) {
          $auth = uri_unescape($auth);
  	if ($auth =~ /^([a-zA-Z])[:|](relative)?/) {
  	    $auth = uc($1) . ":";
  	    $rel++ if $2;
  	} elsif (lc($auth) eq "localhost") {
  	    $auth = "";
  	} elsif (length $auth) {
  	    $auth = "\\\\" . $auth;  # UNC
  	}
      } else {
  	$auth = "";
      }
  
      my @path = $uri->path_segments;
      for (@path) {
  	return undef if /\0/;
  	return undef if /\//;
  	#return undef if /\\/;        # URLs with "\" is not uncommon
      }
      return undef unless $class->fix_path(@path);
  
      my $path = join("\\", @path);
      $path =~ s/^\\// if $rel;
      $path = $auth . $path;
      $path =~ s,^\\([a-zA-Z])[:|],\u$1:,;
  
      return $path;
  }
  
  sub fix_path { 1; }
  
  1;
URI_FILE_WIN32

$fatpacked{"URI/ftp.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI_FTP';
  package URI::ftp;
  
  require URI::_server;
  require URI::_userpass;
  @ISA=qw(URI::_server URI::_userpass);
  
  use strict;
  
  sub default_port { 21 }
  
  sub path { shift->path_query(@_) }  # XXX
  
  sub _user     { shift->SUPER::user(@_);     }
  sub _password { shift->SUPER::password(@_); }
  
  sub user
  {
      my $self = shift;
      my $user = $self->_user(@_);
      $user = "anonymous" unless defined $user;
      $user;
  }
  
  sub password
  {
      my $self = shift;
      my $pass = $self->_password(@_);
      unless (defined $pass) {
  	my $user = $self->user;
  	if ($user eq 'anonymous' || $user eq 'ftp') {
  	    # anonymous ftp login password
              # If there is no ftp anonymous password specified
              # then we'll just use 'anonymous@'
              # We don't try to send the read e-mail address because:
              # - We want to remain anonymous
              # - We want to stop SPAM
              # - We don't want to let ftp sites to discriminate by the user,
              #   host, country or ftp client being used.
  	    $pass = 'anonymous@';
  	}
      }
      $pass;
  }
  
  1;
URI_FTP

$fatpacked{"URI/gopher.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI_GOPHER';
  package URI::gopher;  # <draft-murali-url-gopher>, Dec 4, 1996
  
  require URI::_server;
  @ISA=qw(URI::_server);
  
  use strict;
  use URI::Escape qw(uri_unescape);
  
  #  A Gopher URL follows the common internet scheme syntax as defined in 
  #  section 4.3 of [RFC-URL-SYNTAX]:
  #
  #        gopher://<host>[:<port>]/<gopher-path>
  #
  #  where
  #
  #        <gopher-path> :=  <gopher-type><selector> | 
  #                          <gopher-type><selector>%09<search> |
  #                          <gopher-type><selector>%09<search>%09<gopher+_string>
  #
  #        <gopher-type> := '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7'
  #                         '8' | '9' | '+' | 'I' | 'g' | 'T'
  #
  #        <selector>    := *pchar     Refer to RFC 1808 [4]
  #        <search>      := *pchar
  #        <gopher+_string> := *uchar  Refer to RFC 1738 [3]
  #        
  #  If the optional port is omitted, the port defaults to 70. 
  
  sub default_port { 70 }
  
  sub _gopher_type
  {
      my $self = shift;
      my $path = $self->path_query;
      $path =~ s,^/,,;
      my $gtype = $1 if $path =~ s/^(.)//s;
      if (@_) {
  	my $new_type = shift;
  	if (defined($new_type)) {
  	    Carp::croak("Bad gopher type '$new_type'")
                 unless length($new_type) == 1;
  	    substr($path, 0, 0) = $new_type;
  	    $self->path_query($path);
  	} else {
  	    Carp::croak("Can't delete gopher type when selector is present")
  		if length($path);
  	    $self->path_query(undef);
  	}
      }
      return $gtype;
  }
  
  sub gopher_type
  {
      my $self = shift;
      my $gtype = $self->_gopher_type(@_);
      $gtype = "1" unless defined $gtype;
      $gtype;
  }
  
  *gtype = \&gopher_type;  # URI::URL compatibility
  
  sub selector { shift->_gfield(0, @_) }
  sub search   { shift->_gfield(1, @_) }
  sub string   { shift->_gfield(2, @_) }
  
  sub _gfield
  {
      my $self = shift;
      my $fno  = shift;
      my $path = $self->path_query;
  
      # not according to spec., but many popular browsers accept
      # gopher URLs with a '?' before the search string.
      $path =~ s/\?/\t/;
      $path = uri_unescape($path);
      $path =~ s,^/,,;
      my $gtype = $1 if $path =~ s,^(.),,s;
      my @path = split(/\t/, $path, 3);
      if (@_) {
  	# modify
  	my $new = shift;
  	$path[$fno] = $new;
  	pop(@path) while @path && !defined($path[-1]);
  	for (@path) { $_="" unless defined }
  	$path = $gtype;
  	$path = "1" unless defined $path;
  	$path .= join("\t", @path);
  	$self->path_query($path);
      }
      $path[$fno];
  }
  
  1;
URI_GOPHER

$fatpacked{"URI/http.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI_HTTP';
  package URI::http;
  
  require URI::_server;
  @ISA=qw(URI::_server);
  
  use strict;
  
  sub default_port { 80 }
  
  sub canonical
  {
      my $self = shift;
      my $other = $self->SUPER::canonical;
  
      my $slash_path = defined($other->authority) &&
          !length($other->path) && !defined($other->query);
  
      if ($slash_path) {
  	$other = $other->clone if $other == $self;
  	$other->path("/");
      }
      $other;
  }
  
  1;
URI_HTTP

$fatpacked{"URI/https.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI_HTTPS';
  package URI::https;
  require URI::http;
  @ISA=qw(URI::http);
  
  sub default_port { 443 }
  
  sub secure { 1 }
  
  1;
URI_HTTPS

$fatpacked{"URI/ldap.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI_LDAP';
  # Copyright (c) 1998 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.
  
  package URI::ldap;
  
  use strict;
  
  use vars qw(@ISA $VERSION);
  $VERSION = "1.12";
  
  require URI::_server;
  require URI::_ldap;
  @ISA=qw(URI::_ldap URI::_server);
  
  sub default_port { 389 }
  
  sub _nonldap_canonical {
      my $self = shift;
      $self->URI::_server::canonical(@_);
  }
  
  1;
  
  __END__
  
  =head1 NAME
  
  URI::ldap - LDAP Uniform Resource Locators
  
  =head1 SYNOPSIS
  
    use URI;
  
    $uri = URI->new("ldap:$uri_string");
    $dn     = $uri->dn;
    $filter = $uri->filter;
    @attr   = $uri->attributes;
    $scope  = $uri->scope;
    %extn   = $uri->extensions;
    
    $uri = URI->new("ldap:");  # start empty
    $uri->host("ldap.itd.umich.edu");
    $uri->dn("o=University of Michigan,c=US");
    $uri->attributes(qw(postalAddress));
    $uri->scope('sub');
    $uri->filter('(cn=Babs Jensen)');
    print $uri->as_string,"\n";
  
  =head1 DESCRIPTION
  
  C<URI::ldap> provides an interface to parse an LDAP URI into its
  constituent parts and also to build a URI as described in
  RFC 2255.
  
  =head1 METHODS
  
  C<URI::ldap> supports all the generic and server methods defined by
  L<URI>, plus the following.
  
  Each of the following methods can be used to set or get the value in
  the URI. The values are passed in unescaped form.  None of these
  return undefined values, but elements without a default can be empty.
  If arguments are given, then a new value is set for the given part
  of the URI.
  
  =over 4
  
  =item $uri->dn( [$new_dn] )
  
  Sets or gets the I<Distinguished Name> part of the URI.  The DN
  identifies the base object of the LDAP search.
  
  =item $uri->attributes( [@new_attrs] )
  
  Sets or gets the list of attribute names which are
  returned by the search.
  
  =item $uri->scope( [$new_scope] )
  
  Sets or gets the scope to be used by the search. The value can be one of
  C<"base">, C<"one"> or C<"sub">. If none is given in the URI then the
  return value defaults to C<"base">.
  
  =item $uri->_scope( [$new_scope] )
  
  Same as scope(), but does not default to anything.
  
  =item $uri->filter( [$new_filter] )
  
  Sets or gets the filter to be used by the search. If none is given in
  the URI then the return value defaults to C<"(objectClass=*)">.
  
  =item $uri->_filter( [$new_filter] )
  
  Same as filter(), but does not default to anything.
  
  =item $uri->extensions( [$etype => $evalue,...] )
  
  Sets or gets the extensions used for the search. The list passed should
  be in the form etype1 => evalue1, etype2 => evalue2,... This is also
  the form of list that is returned.
  
  =back
  
  =head1 SEE ALSO
  
  L<http://tools.ietf.org/html/rfc2255>
  
  =head1 AUTHOR
  
  Graham Barr E<lt>F<gbarr@pobox.com>E<gt>
  
  Slightly modified by Gisle Aas to fit into the URI distribution.
  
  =head1 COPYRIGHT
  
  Copyright (c) 1998 Graham Barr. All rights reserved. This program is
  free software; you can redistribute it and/or modify it under the same
  terms as Perl itself.
  
  =cut
URI_LDAP

$fatpacked{"URI/ldapi.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI_LDAPI';
  package URI::ldapi;
  
  use strict;
  
  use vars qw(@ISA);
  
  require URI::_generic;
  require URI::_ldap;
  @ISA=qw(URI::_ldap URI::_generic);
  
  require URI::Escape;
  
  sub un_path {
      my $self = shift;
      my $old = URI::Escape::uri_unescape($self->authority);
      if (@_) {
  	my $p = shift;
  	$p =~ s/:/%3A/g;
  	$p =~ s/\@/%40/g;
  	$self->authority($p);
      }
      return $old;
  }
  
  sub _nonldap_canonical {
      my $self = shift;
      $self->URI::_generic::canonical(@_);
  }
  
  1;
URI_LDAPI

$fatpacked{"URI/ldaps.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI_LDAPS';
  package URI::ldaps;
  require URI::ldap;
  @ISA=qw(URI::ldap);
  
  sub default_port { 636 }
  
  sub secure { 1 }
  
  1;
URI_LDAPS

$fatpacked{"URI/mailto.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI_MAILTO';
  package URI::mailto;  # RFC 2368
  
  require URI;
  require URI::_query;
  @ISA=qw(URI URI::_query);
  
  use strict;
  
  sub to
  {
      my $self = shift;
      my @old = $self->headers;
      if (@_) {
  	my @new = @old;
  	# get rid of any other to: fields
  	for (my $i = 0; $i < @new; $i += 2) {
  	    if (lc($new[$i] || '') eq "to") {
  		splice(@new, $i, 2);
  		redo;
  	    }
  	}
  
  	my $to = shift;
  	$to = "" unless defined $to;
  	unshift(@new, "to" => $to);
  	$self->headers(@new);
      }
      return unless defined wantarray;
  
      my @to;
      while (@old) {
  	my $h = shift @old;
  	my $v = shift @old;
  	push(@to, $v) if lc($h) eq "to";
      }
      join(",", @to);
  }
  
  
  sub headers
  {
      my $self = shift;
  
      # The trick is to just treat everything as the query string...
      my $opaque = "to=" . $self->opaque;
      $opaque =~ s/\?/&/;
  
      if (@_) {
  	my @new = @_;
  
  	# strip out any "to" fields
  	my @to;
  	for (my $i=0; $i < @new; $i += 2) {
  	    if (lc($new[$i] || '') eq "to") {
  		push(@to, (splice(@new, $i, 2))[1]);  # remove header
  		redo;
  	    }
  	}
  
  	my $new = join(",",@to);
  	$new =~ s/%/%25/g;
  	$new =~ s/\?/%3F/g;
  	$self->opaque($new);
  	$self->query_form(@new) if @new;
      }
      return unless defined wantarray;
  
      # I am lazy today...
      URI->new("mailto:?$opaque")->query_form;
  }
  
  1;
URI_MAILTO

$fatpacked{"URI/mms.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI_MMS';
  package URI::mms;
  
  require URI::http;
  @ISA=qw(URI::http);
  
  sub default_port { 1755 }
  
  1;
URI_MMS

$fatpacked{"URI/news.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI_NEWS';
  package URI::news;  # draft-gilman-news-url-01
  
  require URI::_server;
  @ISA=qw(URI::_server);
  
  use strict;
  use URI::Escape qw(uri_unescape);
  use Carp ();
  
  sub default_port { 119 }
  
  #   newsURL      =  scheme ":" [ news-server ] [ refbygroup | message ]
  #   scheme       =  "news" | "snews" | "nntp"
  #   news-server  =  "//" server "/"
  #   refbygroup   = group [ "/" messageno [ "-" messageno ] ]
  #   message      = local-part "@" domain
  
  sub _group
  {
      my $self = shift;
      my $old = $self->path;
      if (@_) {
  	my($group,$from,$to) = @_;
  	if ($group =~ /\@/) {
              $group =~ s/^<(.*)>$/$1/;  # "<" and ">" should not be part of it
  	}
  	$group =~ s,%,%25,g;
  	$group =~ s,/,%2F,g;
  	my $path = $group;
  	if (defined $from) {
  	    $path .= "/$from";
  	    $path .= "-$to" if defined $to;
  	}
  	$self->path($path);
      }
  
      $old =~ s,^/,,;
      if ($old !~ /\@/ && $old =~ s,/(.*),, && wantarray) {
  	my $extra = $1;
  	return (uri_unescape($old), split(/-/, $extra));
      }
      uri_unescape($old);
  }
  
  
  sub group
  {
      my $self = shift;
      if (@_) {
  	Carp::croak("Group name can't contain '\@'") if $_[0] =~ /\@/;
      }
      my @old = $self->_group(@_);
      return if $old[0] =~ /\@/;
      wantarray ? @old : $old[0];
  }
  
  sub message
  {
      my $self = shift;
      if (@_) {
  	Carp::croak("Message must contain '\@'") unless $_[0] =~ /\@/;
      }
      my $old = $self->_group(@_);
      return unless $old =~ /\@/;
      return $old;
  }
  
  1;
URI_NEWS

$fatpacked{"URI/nntp.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI_NNTP';
  package URI::nntp;  # draft-gilman-news-url-01
  
  require URI::news;
  @ISA=qw(URI::news);
  
  1;
URI_NNTP

$fatpacked{"URI/pop.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI_POP';
  package URI::pop;   # RFC 2384
  
  require URI::_server;
  @ISA=qw(URI::_server);
  
  use strict;
  use URI::Escape qw(uri_unescape);
  
  sub default_port { 110 }
  
  #pop://<user>;auth=<auth>@<host>:<port>
  
  sub user
  {
      my $self = shift;
      my $old = $self->userinfo;
  
      if (@_) {
  	my $new_info = $old;
  	$new_info = "" unless defined $new_info;
  	$new_info =~ s/^[^;]*//;
  
  	my $new = shift;
  	if (!defined($new) && !length($new_info)) {
  	    $self->userinfo(undef);
  	} else {
  	    $new = "" unless defined $new;
  	    $new =~ s/%/%25/g;
  	    $new =~ s/;/%3B/g;
  	    $self->userinfo("$new$new_info");
  	}
      }
  
      return unless defined $old;
      $old =~ s/;.*//;
      return uri_unescape($old);
  }
  
  sub auth
  {
      my $self = shift;
      my $old = $self->userinfo;
  
      if (@_) {
  	my $new = $old;
  	$new = "" unless defined $new;
  	$new =~ s/(^[^;]*)//;
  	my $user = $1;
  	$new =~ s/;auth=[^;]*//i;
  
  	
  	my $auth = shift;
  	if (defined $auth) {
  	    $auth =~ s/%/%25/g;
  	    $auth =~ s/;/%3B/g;
  	    $new = ";AUTH=$auth$new";
  	}
  	$self->userinfo("$user$new");
  	
      }
  
      return unless defined $old;
      $old =~ s/^[^;]*//;
      return uri_unescape($1) if $old =~ /;auth=(.*)/i;
      return;
  }
  
  1;
URI_POP

$fatpacked{"URI/rlogin.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI_RLOGIN';
  package URI::rlogin;
  require URI::_login;
  @ISA = qw(URI::_login);
  
  sub default_port { 513 }
  
  1;
URI_RLOGIN

$fatpacked{"URI/rsync.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI_RSYNC';
  package URI::rsync;  # http://rsync.samba.org/
  
  # rsync://[USER@]HOST[:PORT]/SRC
  
  require URI::_server;
  require URI::_userpass;
  
  @ISA=qw(URI::_server URI::_userpass);
  
  sub default_port { 873 }
  
  1;
URI_RSYNC

$fatpacked{"URI/rtsp.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI_RTSP';
  package URI::rtsp;
  
  require URI::http;
  @ISA=qw(URI::http);
  
  sub default_port { 554 }
  
  1;
URI_RTSP

$fatpacked{"URI/rtspu.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI_RTSPU';
  package URI::rtspu;
  
  require URI::rtsp;
  @ISA=qw(URI::rtsp);
  
  sub default_port { 554 }
  
  1;
URI_RTSPU

$fatpacked{"URI/sip.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI_SIP';
  #
  # Written by Ryan Kereliuk <ryker@ryker.org>.  This file may be
  # distributed under the same terms as Perl itself.
  #
  # The RFC 3261 sip URI is <scheme>:<authority>;<params>?<query>.
  #
  
  package URI::sip;
  
  require URI::_server;
  require URI::_userpass;
  @ISA=qw(URI::_server URI::_userpass);
  
  use strict;
  use vars qw(@ISA $VERSION);
  use URI::Escape qw(uri_unescape);
  
  $VERSION = "0.11";
  
  sub default_port { 5060 }
  
  sub authority
  {
      my $self = shift;
      $$self =~ m,^($URI::scheme_re:)?([^;?]*)(.*)$,os or die;
      my $old = $2;
  
      if (@_) {
          my $auth = shift;
          $$self = defined($1) ? $1 : "";
          my $rest = $3;
          if (defined $auth) {
              $auth =~ s/([^$URI::uric])/ URI::Escape::escape_char($1)/ego;
              $$self .= "$auth";
          }
          $$self .= $rest;
      }
      $old;
  }
  
  sub params_form
  {
      my $self = shift;
      $$self =~ m,^((?:$URI::scheme_re:)?)(?:([^;?]*))?(;[^?]*)?(.*)$,os or die;
      my $paramstr = $3;
  
      if (@_) {
      	my @args = @_; 
          $$self = $1 . $2;
          my $rest = $4;
  	my @new;
  	for (my $i=0; $i < @args; $i += 2) {
  	    push(@new, "$args[$i]=$args[$i+1]");
  	}
  	$paramstr = join(";", @new);
  	$$self .= ";" . $paramstr . $rest;
      }
      $paramstr =~ s/^;//o;
      return split(/[;=]/, $paramstr);
  }
  
  sub params
  {
      my $self = shift;
      $$self =~ m,^((?:$URI::scheme_re:)?)(?:([^;?]*))?(;[^?]*)?(.*)$,os or die;
      my $paramstr = $3;
  
      if (@_) {
      	my $new = shift; 
          $$self = $1 . $2;
          my $rest = $4;
  	$$self .= $paramstr . $rest;
      }
      $paramstr =~ s/^;//o;
      return $paramstr;
  }
  
  # Inherited methods that make no sense for a SIP URI.
  sub path {}
  sub path_query {}
  sub path_segments {}
  sub abs { shift }
  sub rel { shift }
  sub query_keywords {}
  
  1;
URI_SIP

$fatpacked{"URI/sips.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI_SIPS';
  package URI::sips;
  require URI::sip;
  @ISA=qw(URI::sip);
  
  sub default_port { 5061 }
  
  sub secure { 1 }
  
  1;
URI_SIPS

$fatpacked{"URI/snews.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI_SNEWS';
  package URI::snews;  # draft-gilman-news-url-01
  
  require URI::news;
  @ISA=qw(URI::news);
  
  sub default_port { 563 }
  
  sub secure { 1 }
  
  1;
URI_SNEWS

$fatpacked{"URI/ssh.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI_SSH';
  package URI::ssh;
  require URI::_login;
  @ISA=qw(URI::_login);
  
  # ssh://[USER@]HOST[:PORT]/SRC
  
  sub default_port { 22 }
  
  sub secure { 1 }
  
  1;
URI_SSH

$fatpacked{"URI/telnet.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI_TELNET';
  package URI::telnet;
  require URI::_login;
  @ISA = qw(URI::_login);
  
  sub default_port { 23 }
  
  1;
URI_TELNET

$fatpacked{"URI/tn3270.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI_TN3270';
  package URI::tn3270;
  require URI::_login;
  @ISA = qw(URI::_login);
  
  sub default_port { 23 }
  
  1;
URI_TN3270

$fatpacked{"URI/urn.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI_URN';
  package URI::urn;  # RFC 2141
  
  require URI;
  @ISA=qw(URI);
  
  use strict;
  use Carp qw(carp);
  
  use vars qw(%implementor);
  
  sub _init {
      my $class = shift;
      my $self = $class->SUPER::_init(@_);
      my $nid = $self->nid;
  
      my $impclass = $implementor{$nid};
      return $impclass->_urn_init($self, $nid) if $impclass;
  
      $impclass = "URI::urn";
      if ($nid =~ /^[A-Za-z\d][A-Za-z\d\-]*\z/) {
  	my $id = $nid;
  	# make it a legal perl identifier
  	$id =~ s/-/_/g;
  	$id = "_$id" if $id =~ /^\d/;
  
  	$impclass = "URI::urn::$id";
  	no strict 'refs';
  	unless (@{"${impclass}::ISA"}) {
  	    # Try to load it
  	    eval "require $impclass";
  	    die $@ if $@ && $@ !~ /Can\'t locate.*in \@INC/;
  	    $impclass = "URI::urn" unless @{"${impclass}::ISA"};
  	}
      }
      else {
  	carp("Illegal namespace identifier '$nid' for URN '$self'") if $^W;
      }
      $implementor{$nid} = $impclass;
  
      return $impclass->_urn_init($self, $nid);
  }
  
  sub _urn_init {
      my($class, $self, $nid) = @_;
      bless $self, $class;
  }
  
  sub _nid {
      my $self = shift;
      my $opaque = $self->opaque;
      if (@_) {
  	my $v = $opaque;
  	my $new = shift;
  	$v =~ s/[^:]*/$new/;
  	$self->opaque($v);
  	# XXX possible rebless
      }
      $opaque =~ s/:.*//s;
      return $opaque;
  }
  
  sub nid {  # namespace identifier
      my $self = shift;
      my $nid = $self->_nid(@_);
      $nid = lc($nid) if defined($nid);
      return $nid;
  }
  
  sub nss {  # namespace specific string
      my $self = shift;
      my $opaque = $self->opaque;
      if (@_) {
  	my $v = $opaque;
  	my $new = shift;
  	if (defined $new) {
  	    $v =~ s/(:|\z).*/:$new/;
  	}
  	else {
  	    $v =~ s/:.*//s;
  	}
  	$self->opaque($v);
      }
      return undef unless $opaque =~ s/^[^:]*://;
      return $opaque;
  }
  
  sub canonical {
      my $self = shift;
      my $nid = $self->_nid;
      my $new = $self->SUPER::canonical;
      return $new if $nid !~ /[A-Z]/ || $nid =~ /%/;
      $new = $new->clone if $new == $self;
      $new->nid(lc($nid));
      return $new;
  }
  
  1;
URI_URN

$fatpacked{"URI/urn/isbn.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI_URN_ISBN';
  package URI::urn::isbn;  # RFC 3187
  
  require URI::urn;
  @ISA=qw(URI::urn);
  
  use strict;
  use Carp qw(carp);
  
  BEGIN {
      require Business::ISBN;
      
      local $^W = 0; # don't warn about dev versions, perl5.004 style
      warn "Using Business::ISBN version " . Business::ISBN->VERSION . 
          " which is deprecated.\nUpgrade to Business::ISBN version 2\n"
          if Business::ISBN->VERSION < 2;
      }
      
  sub _isbn {
      my $nss = shift;
      $nss = $nss->nss if ref($nss);
      my $isbn = Business::ISBN->new($nss);
      $isbn = undef if $isbn && !$isbn->is_valid;
      return $isbn;
  }
  
  sub _nss_isbn {
      my $self = shift;
      my $nss = $self->nss(@_);
      my $isbn = _isbn($nss);
      $isbn = $isbn->as_string if $isbn;
      return($nss, $isbn);
  }
  
  sub isbn {
      my $self = shift;
      my $isbn;
      (undef, $isbn) = $self->_nss_isbn(@_);
      return $isbn;
  }
  
  sub isbn_publisher_code {
      my $isbn = shift->_isbn || return undef;
      return $isbn->publisher_code;
  }
  
  BEGIN {
  my $group_method = do {
      local $^W = 0; # don't warn about dev versions, perl5.004 style
      Business::ISBN->VERSION >= 2 ? 'group_code' : 'country_code';
      };
  
  sub isbn_group_code {
      my $isbn = shift->_isbn || return undef;
      return $isbn->$group_method;
  }
  }
  
  sub isbn_country_code {
      my $name = (caller(0))[3]; $name =~ s/.*:://;
      carp "$name is DEPRECATED. Use isbn_group_code instead";
      
      no strict 'refs';
      &isbn_group_code;
  }
  
  BEGIN {
  my $isbn13_method = do {
      local $^W = 0; # don't warn about dev versions, perl5.004 style
      Business::ISBN->VERSION >= 2 ? 'as_isbn13' : 'as_ean';
      };
  
  sub isbn13 {
      my $isbn = shift->_isbn || return undef;
      
      # Business::ISBN 1.x didn't put hyphens in the EAN, and it was just a string
      # Business::ISBN 2.0 doesn't do EAN, but it does ISBN-13 objects
      #   and it uses the hyphens, so call as_string with an empty anon array
      # or, adjust the test and features to say that it comes out with hyphens.
      my $thingy = $isbn->$isbn13_method;
      return eval { $thingy->can( 'as_string' ) } ? $thingy->as_string([]) : $thingy;
  }
  }
  
  sub isbn_as_ean {
      my $name = (caller(0))[3]; $name =~ s/.*:://;
      carp "$name is DEPRECATED. Use isbn13 instead";
  
      no strict 'refs';
      &isbn13;
  }
  
  sub canonical {
      my $self = shift;
      my($nss, $isbn) = $self->_nss_isbn;
      my $new = $self->SUPER::canonical;
      return $new unless $nss && $isbn && $nss ne $isbn;
      $new = $new->clone if $new == $self;
      $new->nss($isbn);
      return $new;
  }
  
  1;
URI_URN_ISBN

$fatpacked{"URI/urn/oid.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'URI_URN_OID';
  package URI::urn::oid;  # RFC 2061
  
  require URI::urn;
  @ISA=qw(URI::urn);
  
  use strict;
  
  sub oid {
      my $self = shift;
      my $old = $self->nss;
      if (@_) {
  	$self->nss(join(".", @_));
      }
      return split(/\./, $old) if wantarray;
      return $old;
  }
  
  1;
URI_URN_OID

$fatpacked{"WWW/Codeguard.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'WWW_CODEGUARD';
  package WWW::Codeguard;
  
  use strict;
  use warnings FATAL => 'all', NONFATAL => 'uninitialized';
  
  use Carp qw(croak);
  use English qw(-no_match_vars);
  use JSON;
  
  =head1 NAME
  
  WWW::Codeguard - Perl interface to interact with the Codeguard API
  
  =head1 VERSION
  
  Version 0.02
  
  =cut
  
  our $VERSION = '0.02';
  
  =head1 SYNOPSIS
  
  This module provides you with an perl interface to interact with the Codeguard API. This is really just the base class that returns the proper object to use.
  Depending on the params you pass, it will return either the 'Partner' object, or the 'User' object.
  
  	use WWW::Codeguard;
  
  	my $partner_api = WWW::Codeguard->new(
  		{
  			api_url => $api_url,
  			partner => {
  				partner_key => $partner_key,
  			},
  		}
  	);
  
  	my $user_api = WWW::Codeguard->new(
  		{
  			api_url => $api_url,
  			user => {
  				api_key       => $user_api_key,
  				api_secret    => $user_api_secret,
  				access_secret => $user_access_secret,
  				access_token  => $user_access_token,
  			},
  		}
  	);
  
  =cut
  
  =head1 Object Initialization
  
  B<Input> takes an hashref of params. The hashref should contain:
  
  	api_url
  	partner => $hashref_containing_the_partner_options
  	user => $hashref_containing_the_user_options
  
  If both 'partner' and 'user' options are specified, then you should use it an array context to get back both objects:
  
  	my ($partner_api, $user_api) = WWW::Codeguard->new(
  		{
  			api_url => $api_url,
  			partner => {
  				partner_key => $partner_key,
  			},
  			user => {
  				api_key       => $user_api_key,
  				api_secret    => $user_api_secret,
  				access_secret => $user_access_secret,
  				access_token  => $user_access_token,
  			},
  		}
  	);
  
  If array context is not specified, then it will only return the partner api object even if both objects were created.
  
  =cut
  
  sub new {
  
  	my ($class, $opts) = @_;
  	unless ( $opts and UNIVERSAL::isa($opts, 'HASH') and (exists $opts->{partner} or exists $opts->{user}) ) {
  		croak ('Object initialization failed. Invalid params passed to constructor.');
  	}
  
  	my ($partner_obj, $user_obj);
  	if ( exists $opts->{partner} and UNIVERSAL::isa($opts->{partner}, 'HASH') ) {
  		require WWW::Codeguard::Partner;
  		$partner_obj = WWW::Codeguard::Partner->new($opts->{api_url}, $opts->{partner});
  	}
  
  	if ( exists $opts->{user} and UNIVERSAL::isa($opts->{user}, 'HASH') ) {
  		require WWW::Codeguard::User;
  		$user_obj = WWW::Codeguard::User->new($opts->{api_url}, $opts->{user});
  	}
  
  	# If called in an array content, return both;
  	# if not just return which ever one is not undef.
  	return wantarray ? ($partner_obj, $user_obj) : $partner_obj || $user_obj;
  }
  
  =head1 METHODS
  
  Partner methods are documented in L<WWW::Codeguard::Partner>
  
  User methods are documented in L<WWW::Codeguard::User>
  
  =cut
  
  =head2 get_error
  
  Returns the current value in $self->{_error}.
  
  =cut
  
  sub get_error { shift->{_error}; }
  
  =head2 get_api_url
  
  Returns the current value in $self->{api_url}.
  
  =cut
  
  sub get_api_url { shift->{api_url}; }
  
  sub VERSION { return $WWW::Codeguard::VERSION; }
  
  # Internal Methods
  
  sub _do_method {
  
  	my ($self, $name, $params) = @_;
  	if (defined $params and not UNIVERSAL::isa($params, 'HASH')) {
  		$self->_error('$params passed has to be a HASHREF', 1);
  	}
  
  	$self->_sanitize_params($name, $params) or
  		$self->_error('Failed to sanitize params: "'.$self->get_error.'" - The parameters passed in were: '."\n".$self->_stringify_hash($params), 1);
  
  	return $self->_dispatch_request($name, $params);
  }
  
  sub _dispatch_request {
  
  	my ($self, $action, $params) = @_;
  	my $base_url = $self->get_api_url() or
  		return $self->_error('Failed to fetch api_url', 1);
  
  	my $request      = $self->_create_request($action, $params);
  	my $api_response = $self->{_ua}->request($request);
  	if (my $output = $api_response->decoded_content) {
  		my $json = eval { decode_json($output); }
  			or return $self->_error('Invalid API reponse received (unable to decode json): '.$api_response->status_line, 1);
  		return $json;
  	} else {
  		return $self->_error('Invalid API reponse received (no json received): '.$api_response->status_line, 1);
  	}
  	return;
  }
  
  sub _sanitize_params {
  
  	my ($self, $action, $params) = @_;
  	my $required_params = $self->_fetch_required_params($action, $params) or return $self->_error( 'Unknown action specified: ' . $action );
  	my $optional_params = $self->_fetch_optional_params($action);
  
  	if (my $check = _check_params($params, $required_params, $optional_params) ) {
  		my $error;
  		$error .= 'Missing required parameter(s): ' . join (', ', @{ $check->{'required_params'} } ).' ; '
  			if $check->{'required_params'};
  		$error .= 'Blank parameter(s): ' . join (', ', @{ $check->{'blank_params'} } ).' ; '
  			if $check->{'blank_params'};
  		$self->_error($error);
  		return;
  	}
  
  	return 1;
  }
  
  sub _set_content {
  
  	my ($self, $request, $params) = @_;
  	if ('GET' ne $request->method) {
  		my $json = eval {
  			encode_json( $params );
  		} or $self->_error('Failed to encode json payload for request', 1);
  		$request->content($json);
  	}
  	return;
  }
  
  =head2 _check_params
  
  B<Input>: Three hashrefs that contain the following in the specified order:
  
  	1) the hashref to the params that need to be checked.
  	2) the hashref to the 'required' set of params
  	3) the hashref to the 'optional' set of params
  
  B<Outupt>: Undef if everything is good. If errors are detected, it will return a hashref that has two arrays:
  
  	'required_params' - which will list the required params that are missing. And
  	'blank_params'    - which will list the params that have blank values specified for them.
  
  This also 'prunes' the first hashref of params that are not specified in either the required or the optional hashrefs.
  
  =cut
  
  sub _check_params {
  
  	my ($params_to_check, $required_params, $optional_params) = @_;
  	my $output;
  
  	foreach my $param ( keys %{ $params_to_check } ) {
  		if (not (exists $required_params->{$param} or exists $optional_params->{$param} ) ) {
  			delete $params_to_check->{$param};
  		} elsif (not length $params_to_check->{ $param } ) {
  			push @{ $output->{'blank_params'} }, $param;
  		}
  	}
  
  	foreach my $required_param ( keys %{ $required_params } ) {
  		if (not (exists $params_to_check->{ $required_param } and defined $params_to_check->{ $required_param } ) ) {
  			push @{ $output->{'required_params'} }, $required_param;
  		}
  	}
  
  	return $output;
  }
  
  sub _stringify_hash {
  
  	my $self    = shift;
  	my $hashref = shift;
  	my $string;
  	while (my ($key, $value) = each %{$hashref}) {
  		$string .= $key.'='.$value.', ';
  	}
  	$string =~ s/, $//;
  	return $string;
  }
  
  =head2 _error
  
  Internal method that is used to report and set $self->{_error}.
  
  Will croak if a true second argument is passed. Example:
  
  	$self->_error($msg, 1); 
  
  =cut
  
  sub _error {
  
  	my ($self, $msg, $croak) = @_;
  	$self->{_error} = $msg;
  	if ($croak) {
  		croak $msg;
  	}
  }
  
  =head1 AUTHOR
  
  Rishwanth Yeddula, C<< <ryeddula at cpan.org> >>
  
  =head1 BUGS
  
  Please report any bugs or feature requests to C<bug-www-codeguard at rt.cpan.org>, or through
  the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=WWW-Codeguard>.  I will be notified, and then you'll
  automatically be notified of progress on your bug as I make changes.
  
  =head1 SUPPORT
  
  You can find documentation for this module with the following perldoc commands.
  
      perldoc WWW::Codeguard
      perldoc WWW::Codeguard::Partner
      perldoc WWW::Codeguard::User
  
  
  You can also look for information at:
  
  =over 4
  
  =item * RT: CPAN's request tracker (report bugs here)
  
  L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=WWW-Codeguard>
  
  =item * AnnoCPAN: Annotated CPAN documentation
  
  L<http://annocpan.org/dist/WWW-Codeguard>
  
  =item * CPAN Ratings
  
  L<http://cpanratings.perl.org/d/WWW-Codeguard>
  
  =item * Search CPAN
  
  L<http://search.cpan.org/dist/WWW-Codeguard/>
  
  =back
  
  =head1 ACKNOWLEDGMENTS
  
  Thanks to L<Hostgator.com|http://hostgator.com/> for funding the development of this module and providing test resources.
  
  =head1 LICENSE AND COPYRIGHT
  
  Copyright 2014 Rishwanth Yeddula.
  
  This program is free software; you can redistribute it and/or modify it
  under the terms of the the Artistic License (2.0). You may obtain a
  copy of the full license at:
  
  L<http://www.perlfoundation.org/artistic_license_2_0>
  
  Any use, modification, and distribution of the Standard or Modified
  Versions is governed by this Artistic License. By using, modifying or
  distributing the Package, you accept this license. Do not use, modify,
  or distribute the Package, if you do not accept this license.
  
  If your Modified Version has been derived from a Modified Version made
  by someone other than you, you are nevertheless required to ensure that
  your Modified Version complies with the requirements of this license.
  
  This license does not grant you the right to use any trademark, service
  mark, tradename, or logo of the Copyright Holder.
  
  This license includes the non-exclusive, worldwide, free-of-charge
  patent license to make, have made, use, offer to sell, sell, import and
  otherwise transfer the Package with respect to any patent claims
  licensable by the Copyright Holder that are necessarily infringed by the
  Package. If you institute patent litigation (including a cross-claim or
  counterclaim) against any party alleging that the Package constitutes
  direct or contributory patent infringement, then this Artistic License
  to you shall terminate on the date that such litigation is filed.
  
  Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER
  AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES.
  THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
  PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY
  YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR
  CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR
  CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE,
  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  
  
  =cut
  
  1; # End of WWW::Codeguard
WWW_CODEGUARD

$fatpacked{"WWW/Codeguard/Partner.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'WWW_CODEGUARD_PARTNER';
  package WWW::Codeguard::Partner;
  
  use strict;
  use warnings FATAL => 'all', NONFATAL => 'uninitialized';
  
  use parent qw(WWW::Codeguard);
  
  use JSON;
  use LWP::UserAgent;
  use HTTP::Request;
  
  =head1 NAME
  
  WWW::Codeguard::Partner - Perl interface to interact with the Codeguard API as a 'partner'.
  
  =cut
  
  =head1 SYNOPSIS
  
  This module provides you with an perl interface to interact with the Codeguard API and perform the 'partner' level calls.
  
  	use WWW::Codeguard::Partner;
  
  	my $api = WWW::Codeguard::Partner->new(
  		$api_url,
  		{
  			partner_key => $partner_key,
  			verify_hostname => 1,
  		}
  	);
  
  	$api->create_user($params_for_create_user);
  	$api->list_user($params_for_list_user);
  	$api->delete_user($params_for_delete_user);
  
  =cut
  
  sub new {
  
  	my $class = shift;
  	my $self  = {};
  	bless $self, $class;
  	$self->_initialize(@_);
  	return $self;
  }
  
  sub _initialize {
  
  	my ($self, $api_url, $opts) = @_;
  
  	$self->{api_url}     = $api_url;
  	$self->{partner_key} = delete $opts->{partner_key} or $self->_error('partner_key is a required parameter', 1);
  
  	# initialize the UA
  	$self->{_ua} = LWP::UserAgent->new(
  		agent    => 'WWW-Codeguard-Partner '.$self->VERSION,
  		ssl_opts => {
  			verify_hostname => (exists $opts->{verify_hostname}? $opts->{verify_hostname} : 1),
  		},
  	);
  
  	return $self;
  }
  
  =head1 METHODS
  
  Each of these map to a call on Codeguard's Partner API.
   
  =cut
  
  =head2 create_user
  
  This allows you to create an account, on to which you can add website/database resources. Params should be a hashref that contains the following attributes:
  
  Required: The request will not succeed without these attributes.
  
  	name
  	email
  
  Optional Attributes:
  
  	password
  	time_zone
  	partner_data - This is a string that can be used to store user-specific information, that the partner may use to identify the user (such as package id, etc)
  	plan_id
  
  =cut
  
  sub create_user {
  
  	my ($self, $params) = @_;
  	return $self->_do_method('create_user', $params);
  }
  
  =head2 list_user
  
  This allows you to fetch information for a user. Params should be a hashref that contains the following attributes:
  
  Required:
  
  	user_id
  
  Optional:
  
  	None
  
  =cut
  
  sub list_user {
  
  	my ($self, $params) = @_;
  	return $self->_do_method('list_user', $params);
  }
  
  =head2 delete_user
  
  This method is used to delete existing users that were created using the specified partner_key. Parters can not delete users created by other partners.
  
  B<Note:> Deleting a user resource will also delete all associated Website and Database records.
  
  Params should be a hashref that contains the following attributes:
  
  Required:
  
  	user_id
  
  Optional Attributes:
  
  	None
  
  =cut
  
  sub delete_user {
  
  	my ($self, $params) = @_;
  	return $self->_do_method('delete_user', $params);
  }
  
  =head2 change_user_plan
  
  This method is used to change an existing user's plan. Params should be a hashref that contains the following attributes:
  
  Required:
  
  	user_id
  	plan_id
  
  Optional Attributes
  
  	None
  
  =cut
  
  sub change_user_plan {
  
  	my ($self, $params) = @_;
  	return $self->_do_method('change_user_plan', $params);
  }
  
  =head2 user_quota_report
  
  Required:
  
  	None
  
  Optional:
  
  	None
  
  Returns an array of Users who are using more than their allowed disk quota.
  
  B<Note>: Full User models are not included. Only the Attributes listed below are returned:
  
  =over 4
  
  =item * email         - User email address.
  
  =item * package       - CodeGuard plan ID associated with this user.
  
  =item * quota         - Allowed quota in bytes.
  
  =item * usage         - Disk usage in bytes.
  
  =item * percent_usage - Percent of quota used. This can be > 100%.
  
  =item * signup_date   - Date of User account creation.
  
  =item * overage_date  - Date the user was notified or 'Not yet notified' if a notification has not yet occurred.
  
  =back
  
  =cut
  
  sub user_quota_report {
  
  	my ($self, $params) = @_;
  	return $self->_do_method('user_quota_report', $params);
  }
  
  =head1 Accessors
  
  Basic accessor methods to retrieve the current settings
  
  =cut
  
  =head2 get_partner_key
  
  Returns the partner_key of the object instance.
  
  =cut
  
  sub get_partner_key { shift->{partner_key}; }
  
  # Internal Methods
  
  sub _create_request {
  
  	my ($self, $action, $params) = @_;
  	my $action_map = {
  		'change_user_plan'  => 'POST',
  		'create_user'       => 'POST',
  		'delete_user'       => 'DELETE',
  		'list_user'         => 'GET',
  		'user_quota_report' => 'GET',
  	};
  	my $request = HTTP::Request->new( $action_map->{$action} );
  	$request->header('Content-Type' => 'application/json' );
  	$self->_set_content($request, $params);
  	$self->_set_uri($action, $request, $params);
  	return $request;
  }
  
  sub _set_uri {
  
  	my ($self, $action, $request, $params) = @_;
  	my $base_url = $self->get_api_url();
  	my $uri_map = {
  		'change_user_plan'  => '/users/'.($params->{user_id} || '').'/plan',
  		'create_user'       => '/users',
  		'delete_user'       => '/users/'.($params->{user_id} || ''),
  		'list_user'         => '/users/'.($params->{user_id} || ''),
  		'user_quota_report' => '/partners/user_quota_report',
  	};
  	$request->uri($base_url.$uri_map->{$action}.'?api_key='.$self->get_partner_key);
  	return;
  }
  
  sub _fetch_required_params {
  
  	my ($self, $action, $params) = @_;
  	my $required_keys_map = {
  		'create_user'       => { map { ($_ => 1) } qw(name email) },
  		'list_user'         => { map { ($_ => 1) } qw(user_id) },
  		'change_user_plan'  => { map { ($_ => 1) } qw(user_id plan_id) },
  		'user_quota_report' => { },
  	};
  	$required_keys_map->{delete_user} = $required_keys_map->{list_user};
  	return $required_keys_map->{$action};
  }
  
  sub _fetch_optional_params {
  
  	my ($self, $action) = @_;
  	my $optional_keys_map = {
  		'create_user' => { map { ($_ => 1) } qw(password time_zone partner_data plan_id) },
  	};
  	return $optional_keys_map->{$action};
  }
  
  =head1 AUTHOR
  
  Rishwanth Yeddula, C<< <ryeddula at cpan.org> >>
  
  =head1 BUGS
  
  Please report any bugs or feature requests to C<bug-www-codeguard at rt.cpan.org>, or through
  the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=WWW-Codeguard>.  I will be notified, and then you'll
  automatically be notified of progress on your bug as I make changes.
  
  =head1 SUPPORT
  
  You can find documentation for this module with the following perldoc commands.
  
      perldoc WWW::Codeguard
      perldoc WWW::Codeguard::Partner
      perldoc WWW::Codeguard::User
  
  
  You can also look for information at:
  
  =over 4
  
  =item * RT: CPAN's request tracker (report bugs here)
  
  L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=WWW-Codeguard>
  
  =item * AnnoCPAN: Annotated CPAN documentation
  
  L<http://annocpan.org/dist/WWW-Codeguard>
  
  =item * CPAN Ratings
  
  L<http://cpanratings.perl.org/d/WWW-Codeguard>
  
  =item * Search CPAN
  
  L<http://search.cpan.org/dist/WWW-Codeguard/>
  
  =back
  
  =head1 ACKNOWLEDGMENTS
  
  Thanks to L<Hostgator.com|http://hostgator.com/> for funding the development of this module and providing test resources.
  
  =head1 LICENSE AND COPYRIGHT
  
  Copyright 2014 Rishwanth Yeddula.
  
  This program is free software; you can redistribute it and/or modify it
  under the terms of the the Artistic License (2.0). You may obtain a
  copy of the full license at:
  
  L<http://www.perlfoundation.org/artistic_license_2_0>
  
  Any use, modification, and distribution of the Standard or Modified
  Versions is governed by this Artistic License. By using, modifying or
  distributing the Package, you accept this license. Do not use, modify,
  or distribute the Package, if you do not accept this license.
  
  If your Modified Version has been derived from a Modified Version made
  by someone other than you, you are nevertheless required to ensure that
  your Modified Version complies with the requirements of this license.
  
  This license does not grant you the right to use any trademark, service
  mark, tradename, or logo of the Copyright Holder.
  
  This license includes the non-exclusive, worldwide, free-of-charge
  patent license to make, have made, use, offer to sell, sell, import and
  otherwise transfer the Package with respect to any patent claims
  licensable by the Copyright Holder that are necessarily infringed by the
  Package. If you institute patent litigation (including a cross-claim or
  counterclaim) against any party alleging that the Package constitutes
  direct or contributory patent infringement, then this Artistic License
  to you shall terminate on the date that such litigation is filed.
  
  Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER
  AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES.
  THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
  PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY
  YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR
  CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR
  CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE,
  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  
  =cut
  
  1;
WWW_CODEGUARD_PARTNER

$fatpacked{"WWW/Codeguard/User.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'WWW_CODEGUARD_USER';
  package WWW::Codeguard::User;
  
  use strict;
  use warnings FATAL => 'all', NONFATAL => 'uninitialized';
  
  use parent qw(WWW::Codeguard);
  
  use JSON qw();
  use Net::OAuth;
  use LWP::UserAgent;
  use HTTP::Request;
  
  =head1 NAME
  
  WWW::Codeguard::User - Perl interface to interact with the Codeguard API as a 'user'
  
  =cut
  
  =head1 SYNOPSIS
  
  This module provides you with an perl interface to interact with the Codeguard API and perform the 'user' level calls.
  
  	use WWW::Codeguard::User;
  
  	my $api = WWW::Codeguard::User->new(
  		$api_url,
  		{
  			api_secret      => $user_api_secret,
  			api_key         => $user_api_key,
  			access_secret   => $user_access_secret,
  			access_token    => $user_access_token,
  			verify_hostname => 1,
  		}
  	);
  
  =cut
  
  sub new {
  
  	my $class = shift;
  	my $self = {};
  	bless $self, $class;
  	$self->_initialize(@_);
  	return $self;
  }
  
  sub _initialize {
  
  	my ($self, $api_url, $opts) = @_;
  
  	$self->{api_url} = $api_url;
  	foreach my $key (qw(api_secret api_key access_secret access_token)) {
  		$self->{$key} = delete $opts->{$key} or $self->_error($key.' is a required parameter', 1);
  	}
  
  	# initialize the UA
  	$self->{_ua} = LWP::UserAgent->new(
  		agent    => 'WWW-Codeguard-User '.$self->VERSION(),
  		max_redirect => 0,
  		ssl_opts => {
  			verify_hostname => (exists $opts->{verify_hostname}? $opts->{verify_hostname} : 1),
  		},
  	);
  
  	return $self;
  }
  
  =head1 METHODS
  
  Each of these map to a call on Codeguard's User API.
  
  =cut
  
  =head2 create_website
  
  This allows you to create a website resource under your User account. Params should be a hashref that contains the following attributes:
  
  Required: The request will not succeed without these attributes.
  
  	url
  	hostname
  	account
  	password or key
  	provider
  
  Optional:
  
  	dir_path
  	port
  
  =cut
  
  sub create_website {
  
  	my ($self, $params) = @_;
  	return $self->_do_method('create_website', $params);
  }
  
  =head2 list_websites
  
  This allows you to list the website resources under your User account. Params should be a hashref that contains the following attributes:
  
  Required:
  
  	None
  
  Optional:
  
  	None
  
  =cut
  
  sub list_websites {
  
  	my ($self, $params) = @_;
  	return $self->_do_method('list_websites', $params);
  }
  
  =head2 list_website_rules
  
  This allows you to list the exclusion rules for a website resource under your User account. Params should be a hashref that contains the following attributes:
  
  Required:
  
  	website_id
  
  Optional:
  
  	None
  
  =cut
  
  sub list_website_rules {
  
  	my ($self, $params) = @_;
  	return $self->_do_method('list_website_rules', $params);
  }
  
  =head2 set_website_rules
  
  This allows you to set the exclusion rules for a website resource under your User account. Params should be a hashref that contains the following attributes:
  
  Required:
  
  	website_id
  	exclude_rules - must be an array ref with elements specifying what paths/files to ignore. Example:
  	[
  		'access-logs/*'
  		'*error_log*'
  		'*stats/*'
  		'/path/to/a/folder/*'
  		'/path/to/a/file.txt'
  	]
  
  Optional:
  
  	None
  
  =cut
  
  sub set_website_rules {
  
  	my ($self, $params) = @_;
  	return $self->_do_method('set_website_rules', $params);
  }
  
  =head2 edit_website
  
  This allows you to edit information for the specified website resource under your User account. Params should be a hashref that contains the following attributes:
  
  Required:
  
  	website_id
  
  Optional:
  
  	url
  	monitor_frequency
  	account
  	password or key
  	dir_path
  	hostname
  	disabled
  
  =cut
  
  sub edit_website {
  
  	my ($self, $params) = @_;
  	return $self->_do_method('edit_website', $params);
  }
  
  =head2 delete_website
  
  This allows you to delete the specified website resource under your User account. Params should be a hashref that contains the following attributes:
  
  Required:
  
  	website_id
  
  Optional:
  
  	None
  
  =cut
  
  sub delete_website {
  
  	my ($self, $params) = @_;
  	return $self->_do_method('delete_website', $params);
  }
  
  =head2 enable_website
  
  This allows you to enable a specified website resource under your User account. Params should be a hashref that contains the following attributes:
  
  Required:
  
  	website_id
  
  Optional:
  
  	None
  
  =cut
  
  sub enable_website {
  
  	my ($self, $params) = @_;
  	my $real_params = {
  		UNIVERSAL::isa($params, 'HASH') ? ( website_id => $params->{website_id} ) : (),
  	};
  
  	$real_params->{disabled} = JSON::false;
  	return $self->_do_method('edit_website', $real_params);
  }
  
  =head2 disable_website
  
  This allows you to disable a specified website resource under your User account. Params should be a hashref that contains the following attributes:
  
  Required:
  
  	website_id
  
  Optional:
  
  	None
  
  =cut
  
  sub disable_website {
  
  	my ($self, $params) = @_;
  	$self->_sanitize_params('edit_website', $params) or
  		$self->_error('Failed to sanitize params: "'.$self->get_error.'" - The parameters passed in were: '."\n".$self->_stringify_hash($params), 1);
  	$params->{disabled} = JSON::true;
  	return $self->_do_method('edit_website', $params);
  }
  
  =head2 create_database
  
  This allows you to create a database resource under your User account. Params should be a hashref that contains the following attributes:
  
  Required:
  
  	server_address - MySQL Database Hostname or IP address.
  	account        - MySQL username which has access to the database_name database.
  	password       - MySQL password associated with account.
  	                 Note: This parameter is only used during the create action. It is never returned by other API requests.
  	port           - MySQL server port number for use with the server_name.
  	database_name  - The name of the target database.
  
  Optional:
  
  	website_id          - Numeric ID of the parent Website record.
  	                      If no website_id is provided, the Database will not be associated with any website resource.
  
  B<Experimental features>: SSH functionality for DB backups is currently not fully functional on CodeGuard's side, and as such might not function as expected.
  
  	authentication_mode - This can be one of two values: 'direct' or 'ssh'.
  	                      The direct method will attempt to open a connection using a MySQL client on the specified server and port.
  	                      The ssh method will create an SSH tunnel through server_name using the server_account and
  	                      server_password credentials to connect to the database on server_name.
  
  	server_account      - SSH username on server_address. Note: This field is only valid if the authenticationmode is ssh.
  	                      Note: Required if authentication_mode is 'ssh'.
  
  	server_password     - SSH password associated with server_account.
  	                      Note: Required if authentication_mode is 'ssh'.
  
  =cut
  
  sub create_database {
  
  	my ($self, $params) = @_;
  	return $self->_do_method('create_database', $params);
  }
  
  =head2 list_databases
  
  This allows you to fetch all Database Records owned by the user.
  
  Required:
  
  	None
  
  Optional:
  
  	None
  
  =cut
  
  sub list_databases {
  
  	my ($self, $params) = @_;
  	return $self->_do_method('list_databases', $params);
  }
  
  =head2 show_database
  
  This allows you to fetch information for the specified database resource under your User account. Params should be a hashref that contains the following attributes:
  
  Required:
  
  	website_id
  	database_id
  
  Optional:
  
  	None
  
  =cut
  
  sub show_database {
  
  	my ($self, $params) = @_;
  	return $self->_do_method('show_database', $params);
  }
  
  =head2 edit_database
  
  This allows you to edit information for the specified database resource under your User account. Params should be a hashref that contains the following attributes:
  
  Required:
  
  	database_id
  
  Optional:
  
  	website_id
  	server_address
  	account
  	password
  	port
  	database_name
  	authentication_mode
  	server_account
  	server_password
  	disabled
  
  =cut
  
  sub edit_database {
  
  	my ($self, $params) = @_;
  	return $self->_do_method('edit_database', $params);
  }
  
  =head2 delete_database
  
  This allows you to delete the specified database resource under your User account. Params should be a hashref that contains the following attributes:
  
  Required:
  
  	database_id
  
  Optional:
  
  	None
  
  =cut
  
  sub delete_database {
  
  	my ($self, $params) = @_;
  	return $self->_do_method('delete_database', $params);
  }
  
  =head2 enable_database
  
  This allows you to enable a specified database resource under your User account. Params should be a hashref that contains the following attributes:
  
  Required:
  
  	database_id
  
  Optional:
  
  	None
  
  =cut
  
  sub enable_database {
  
  	my ($self, $params) = @_;
  	my $real_params = {
  		UNIVERSAL::isa($params, 'HASH') ? ( database_id => $params->{database_id} ) : (),
  	};
  
  	$real_params->{disabled} = JSON::false;
  	return $self->_do_method('edit_database', $real_params);
  }
  
  =head2 disable_database
  
  This allows you to disable a specified database resource under your User account. Params should be a hashref that contains the following attributes:
  
  Required:
  
  	database_id
  
  Optional:
  
  	None
  
  =cut
  
  sub disable_database {
  
  	my ($self, $params) = @_;
  	my $real_params = {
  		UNIVERSAL::isa($params, 'HASH') ? ( database_id => $params->{database_id} ) : (),
  	};
  
  	$real_params->{disabled} = JSON::true;
  	return $self->_do_method('edit_database', $real_params);
  }
  
  =head2 generate_login_link
  
  This creates a login URL that can be used to access the Codeguard Dashboard for your User account.
  
  Required:
  
  	None
  
  Optional:
  
  	None
  
  =cut
  
  sub generate_login_link {
  
  	my $self = shift;
  	return $self->_set_uri('list_websites');
  }
  
  =head1 Accessors
  
  Basic accessor methods to retrieve the current settings
  
  =cut
  
  =head2 get_api_secret
  
  Returns the current value in $self->{api_secret}.
  
  =cut
  
  sub get_api_secret { shift->{api_secret}; }
  
  =head2 get_api_key
  
  Returns the current value in $self->{api_key}.
  
  =cut
  
  sub get_api_key { shift->{api_key}; }
  
  =head2 get_access_secret
  
  Returns the current value in $self->{access_secret}.
  
  =cut
  
  sub get_access_secret { shift->{access_secret}; }
  
  =head2 get_access_token
  
  Returns the current value in $self->{access_token}.
  
  =cut
  
  sub get_access_token { shift->{access_token}; }
  
  # Internal Methods
  
  sub _create_request {
  
  	my ($self, $action, $params) = @_;
  	my $action_map = {
  		'create_website'     => 'POST',
  		'list_websites'      => 'GET',
  		'edit_website'       => 'PUT',
  		'delete_website'     => 'DELETE',
  		'list_website_rules' => 'GET',
  		'set_website_rules'  => 'POST',
  		'create_database'    => 'POST',
  		'list_databases'     => 'GET',
  		'show_database'      => 'GET',
  		'edit_database'      => 'PUT',
  		'delete_database'    => 'DELETE',
  	};
  	my $request = HTTP::Request->new( $action_map->{$action} );
  	$request->header('Content-Type' => 'application/json' );
  	$self->_set_uri($action, $request, $params);
  	$self->_set_content($request, $params);
  	return $request;
  }
  
  sub _set_uri {
  
  	my ($self, $action, $request, $params) = @_;
  	my $base_url = $self->get_api_url();
  	my $uri_map  = {
  		'create_website'     => '/websites',
  		'list_websites'      => '/websites',
  		'edit_website'       => '/websites/'.($params->{website_id} || ''),
  		'delete_website'     => '/websites/'.($params->{website_id} || ''),
  		'list_website_rules' => '/websites/'.($params->{website_id} || '').'/rules',
  		'set_website_rules'  => '/websites/'.($params->{website_id} || '').'/rules',
  		'create_database'    => '/database_backups',
  		'list_databases'     => '/database_backups',
  		'show_database'      => '/websites/'.($params->{website_id} || '').'/database_backups/'.($params->{database_id} || ''),
  		'edit_database'      => '/database_backups/'.($params->{database_id} || ''),
  		'delete_database'    => '/database_backups/'.($params->{database_id} || ''),
  	};
  
  	my $oauth_req = Net::OAuth->request('protected resource')->new(
  		'consumer_key'     => $self->{api_key},
  		'consumer_secret'  => $self->{api_secret},
  		'token'            => $self->{access_token},
  		'token_secret'     => $self->{access_secret},
  		'signature_method' => 'HMAC-SHA1',
  		'timestamp'        => time(),
  		'nonce'            => _oauth_nonce(),
  		'request_method'   => ($request) ? $request->method() : 'GET',
  		'request_url'      => $base_url.$uri_map->{$action},
  	);
  	$oauth_req->sign;
  	return ($request) ? $request->uri($oauth_req->to_url) : $oauth_req->to_url;
  }
  
  sub _fetch_required_params {
  
  	my ($self, $action, $params) = @_;
  	my $required_keys_map = {
  		create_website     => { map { ($_ => 1) } qw(url hostname account provider) },
  		list_websites      => { },
  		list_website_rules => { map { ($_ => 1) } qw(website_id) },
  		set_website_rules  => { map { ($_ => 1) } qw(website_id exclude_rules) },
  		create_database    => { map { ($_ => 1) } qw(server_address account password port database_name) },
  		list_databases     => { },
  		show_database      => { map { ($_ => 1) } qw(website_id database_id) },
  		edit_database      => { map { ($_ => 1) } qw(database_id) },
  	};
  
  	# The 'edit_website', and 'delete_website' calls have the same set of required params as the 'list_website_rules' call
  	$required_keys_map->{edit_website} = $required_keys_map->{delete_website} = $required_keys_map->{list_website_rules};
  
  	# The 'delete_database' call has the same set of required params as the 'edit_database' call
  	$required_keys_map->{delete_database} = $required_keys_map->{edit_database};
  
  	# if action is 'create_website',
  	# then we check the $params
  	# and mark either 'password' or 'key' as the required param.
  	if ($action eq 'create_website') {
  		if (exists $params->{key} and $params->{key}) {
  			$required_keys_map->{create_website}->{key} = 1;
  			delete $params->{password};
  		} elsif (exists $params->{password} and $params->{password}) {
  			$required_keys_map->{create_website}->{password} = 1;
  		} else {
  			# if neither key or password are present, then push a 'fake' value in, to indicate this.
  			$required_keys_map->{create_website}->{'Key or Password'} = 1;
  		}
  	} elsif ($action eq 'create_database' and (exists $params->{authentication_mode} and $params->{authentication_mode} eq 'ssh')) {
  		$required_keys_map->{create_database}->{server_account}  = 1;
  		$required_keys_map->{create_database}->{server_password} = 1;
  	}
  
  	return $required_keys_map->{$action};
  }
  
  sub _fetch_optional_params {
  
  	my ($self, $action) = @_;
  	my $optional_keys_map = {
  		create_website  => { map { ($_ => 1) } qw(port dir_path) },
  		create_database => { map { ($_ => 1) } qw(website_id authentication_mode) },
  		edit_website    => { map { ($_ => 1) } qw(url monitor_frequency account password key dir_path hostname disabled) },
  		edit_database   => { map { ($_ => 1) } qw(server_address account password port database_name authentication_mode server_account server_password website_id disabled) },
  	};
  	return $optional_keys_map->{$action};
  }
  
  sub _oauth_nonce {
  
  	my $nonce = '';
  	$nonce .= sprintf("%02x", int(rand(255))) for 1..16;
  	return $nonce;
  }
  
  =head1 AUTHOR
  
  Rishwanth Yeddula, C<< <ryeddula at cpan.org> >>
  
  =head1 BUGS
  
  Please report any bugs or feature requests to C<bug-www-codeguard at rt.cpan.org>, or through
  the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=WWW-Codeguard>.  I will be notified, and then you'll
  automatically be notified of progress on your bug as I make changes.
  
  =head1 SUPPORT
  
  You can find documentation for this module with the following perldoc commands.
  
      perldoc WWW::Codeguard
      perldoc WWW::Codeguard::Partner
      perldoc WWW::Codeguard::User
  
  
  You can also look for information at:
  
  =over 4
  
  =item * RT: CPAN's request tracker (report bugs here)
  
  L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=WWW-Codeguard>
  
  =item * AnnoCPAN: Annotated CPAN documentation
  
  L<http://annocpan.org/dist/WWW-Codeguard>
  
  =item * CPAN Ratings
  
  L<http://cpanratings.perl.org/d/WWW-Codeguard>
  
  =item * Search CPAN
  
  L<http://search.cpan.org/dist/WWW-Codeguard/>
  
  =back
  
  =head1 ACKNOWLEDGMENTS
  
  Thanks to L<Hostgator.com|http://hostgator.com/> for funding the development of this module and providing test resources.
  
  =head1 LICENSE AND COPYRIGHT
  
  Copyright 2014 Rishwanth Yeddula.
  
  This program is free software; you can redistribute it and/or modify it
  under the terms of the the Artistic License (2.0). You may obtain a
  copy of the full license at:
  
  L<http://www.perlfoundation.org/artistic_license_2_0>
  
  Any use, modification, and distribution of the Standard or Modified
  Versions is governed by this Artistic License. By using, modifying or
  distributing the Package, you accept this license. Do not use, modify,
  or distribute the Package, if you do not accept this license.
  
  If your Modified Version has been derived from a Modified Version made
  by someone other than you, you are nevertheless required to ensure that
  your Modified Version complies with the requirements of this license.
  
  This license does not grant you the right to use any trademark, service
  mark, tradename, or logo of the Copyright Holder.
  
  This license includes the non-exclusive, worldwide, free-of-charge
  patent license to make, have made, use, offer to sell, sell, import and
  otherwise transfer the Package with respect to any patent claims
  licensable by the Copyright Holder that are necessarily infringed by the
  Package. If you institute patent litigation (including a cross-claim or
  counterclaim) against any party alleging that the Package constitutes
  direct or contributory patent infringement, then this Artistic License
  to you shall terminate on the date that such litigation is filed.
  
  Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER
  AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES.
  THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
  PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY
  YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR
  CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR
  CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE,
  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  
  =cut
  
  1;
WWW_CODEGUARD_USER

$fatpacked{"YAML.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'YAML';
  use 5.008001;
  package YAML;
  use YAML::Mo;
  
  our $VERSION = '0.88';
  
  use Exporter;
  push @YAML::ISA, 'Exporter';
  our @EXPORT = qw{ Dump Load };
  our @EXPORT_OK = qw{ freeze thaw DumpFile LoadFile Bless Blessed };
  
  use YAML::Node; # XXX This is a temp fix for Module::Build
  
  # XXX This VALUE nonsense needs to go.
  use constant VALUE => "\x07YAML\x07VALUE\x07";
  
  # YAML Object Properties
  has dumper_class => default => sub {'YAML::Dumper'};
  has loader_class => default => sub {'YAML::Loader'};
  has dumper_object => default => sub {$_[0]->init_action_object("dumper")};
  has loader_object => default => sub {$_[0]->init_action_object("loader")};
  
  sub Dump {
      my $yaml = YAML->new;
      $yaml->dumper_class($YAML::DumperClass)
          if $YAML::DumperClass;
      return $yaml->dumper_object->dump(@_);
  }
  
  sub Load {
      my $yaml = YAML->new;
      $yaml->loader_class($YAML::LoaderClass)
          if $YAML::LoaderClass;
      return $yaml->loader_object->load(@_);
  }
  
  {
      no warnings 'once';
      # freeze/thaw is the API for Storable string serialization. Some
      # modules make use of serializing packages on if they use freeze/thaw.
      *freeze = \ &Dump;
      *thaw   = \ &Load;
  }
  
  sub DumpFile {
      my $OUT;
      my $filename = shift;
      if (ref $filename eq 'GLOB') {
          $OUT = $filename;
      }
      else {
          my $mode = '>';
          if ($filename =~ /^\s*(>{1,2})\s*(.*)$/) {
              ($mode, $filename) = ($1, $2);
          }
          open $OUT, $mode, $filename
            or YAML::Mo::Object->die('YAML_DUMP_ERR_FILE_OUTPUT', $filename, $!);
      }
      binmode $OUT, ':utf8';  # if $Config{useperlio} eq 'define';
      local $/ = "\n"; # reset special to "sane"
      print $OUT Dump(@_);
  }
  
  sub LoadFile {
      my $IN;
      my $filename = shift;
      if (ref $filename eq 'GLOB') {
          $IN = $filename;
      }
      else {
          open $IN, '<', $filename
            or YAML::Mo::Object->die('YAML_LOAD_ERR_FILE_INPUT', $filename, $!);
      }
      binmode $IN, ':utf8';  # if $Config{useperlio} eq 'define';
      return Load(do { local $/; <$IN> });
  }
  
  sub init_action_object {
      my $self = shift;
      my $object_class = (shift) . '_class';
      my $module_name = $self->$object_class;
      eval "require $module_name";
      $self->die("Error in require $module_name - $@")
          if $@ and "$@" !~ /Can't locate/;
      my $object = $self->$object_class->new;
      $object->set_global_options;
      return $object;
  }
  
  my $global = {};
  sub Bless {
      require YAML::Dumper::Base;
      YAML::Dumper::Base::bless($global, @_)
  }
  sub Blessed {
      require YAML::Dumper::Base;
      YAML::Dumper::Base::blessed($global, @_)
  }
  sub global_object { $global }
  
  1;
  
  __END__
  
  =encoding UTF-8
  
  =head1 NAME
  
  YAML - YAML Ain't Markup Language (tm)
  
  =head1 NOTE
  
  This module has been released to CPAN as YAML::Old, and soon YAML.pm
  will be changed to just be a frontend interface module for all the
  various Perl YAML implementation modules, including YAML::Old.
  
  If you want robust and fast YAML processing using the normal Dump/Load
  API, please consider switching to YAML::XS. It is by far the best Perl
  module for YAML at this time. It requires that you have a C compiler,
  since it is written in C.
  
  If you really need to use this version of YAML.pm it will always be
  available as YAML::Old.
  
  If you don't care which YAML module use, as long as it's the best one
  installed on your system, use YAML::Any.
  
  The rest of this documentation is left unchanged, until YAML.pm is
  switched over to the new UI-only version.
  
  =head1 SYNOPSIS
  
      use YAML;
  
      # Load a YAML stream of 3 YAML documents into Perl data structures.
      my ($hashref, $arrayref, $string) = Load(<<'...');
      ---
      name: ingy
      age: old
      weight: heavy
      # I should comment that I also like pink, but don't tell anybody.
      favorite colors:
          - red
          - green
          - blue
      ---
      - Clark Evans
      - Oren Ben-Kiki
      - Ingy döt Net
      --- >
      You probably think YAML stands for "Yet Another Markup Language". It
      ain't! YAML is really a data serialization language. But if you want
      to think of it as a markup, that's OK with me. A lot of people try
      to use XML as a serialization format.
  
      "YAML" is catchy and fun to say. Try it. "YAML, YAML, YAML!!!"
      ...
  
      # Dump the Perl data structures back into YAML.
      print Dump($string, $arrayref, $hashref);
  
      # YAML::Dump is used the same way you'd use Data::Dumper::Dumper
      use Data::Dumper;
      print Dumper($string, $arrayref, $hashref);
  
  =head1 DESCRIPTION
  
  The YAML.pm module implements a YAML Loader and Dumper based on the YAML
  1.0 specification. L<http://www.yaml.org/spec/>
  
  YAML is a generic data serialization language that is optimized for
  human readability. It can be used to express the data structures of most
  modern programming languages. (Including Perl!!!)
  
  For information on the YAML syntax, please refer to the YAML
  specification.
  
  =head1 WHY YAML IS COOL
  
  =over 4
  
  =item YAML is readable for people.
  
  It makes clear sense out of complex data structures. You should find
  that YAML is an exceptional data dumping tool. Structure is shown
  through indentation, YAML supports recursive data, and hash keys are
  sorted by default. In addition, YAML supports several styles of scalar
  formatting for different types of data.
  
  =item YAML is editable.
  
  YAML was designed from the ground up to be an excellent syntax for
  configuration files. Almost all programs need configuration files, so
  why invent a new syntax for each one? And why subject users to the
  complexities of XML or native Perl code?
  
  =item YAML is multilingual.
  
  Yes, YAML supports Unicode. But I'm actually referring to programming
  languages. YAML was designed to meet the serialization needs of Perl,
  Python, Ruby, Tcl, PHP, Javascript and Java. It was also designed to be
  interoperable between those languages. That means YAML serializations
  produced by Perl can be processed by Python.
  
  =item YAML is taint safe.
  
  Using modules like Data::Dumper for serialization is fine as long as you
  can be sure that nobody can tamper with your data files or
  transmissions. That's because you need to use Perl's C<eval()> built-in
  to deserialize the data. Somebody could add a snippet of Perl to erase
  your files.
  
  YAML's parser does not need to eval anything.
  
  =item YAML is full featured.
  
  YAML can accurately serialize all of the common Perl data structures and
  deserialize them again without losing data relationships. Although it is
  not 100% perfect (no serializer is or can be perfect), it fares as well
  as the popular current modules: Data::Dumper, Storable, XML::Dumper and
  Data::Denter.
  
  YAML.pm also has the ability to handle code (subroutine) references and
  typeglobs. (Still experimental) These features are not found in Perl's
  other serialization modules.
  
  =item YAML is extensible.
  
  The YAML language has been designed to be flexible enough to solve it's
  own problems. The markup itself has 3 basic construct which resemble
  Perl's hash, array and scalar. By default, these map to their Perl
  equivalents. But each YAML node also supports a tagging mechanism (type
  system) which can cause that node to be interpreted in a completely
  different manner. That's how YAML can support object serialization and
  oddball structures like Perl's typeglob.
  
  =back
  
  =head1 YAML IMPLEMENTATIONS IN PERL
  
  This module, YAML.pm, is really just the interface module for YAML
  modules written in Perl. The basic interface for YAML consists of two
  functions: C<Dump> and C<Load>. The real work is done by the modules
  YAML::Dumper and YAML::Loader.
  
  Different YAML module distributions can be created by subclassing
  YAML.pm and YAML::Loader and YAML::Dumper. For example, YAML-Simple
  consists of YAML::Simple YAML::Dumper::Simple and YAML::Loader::Simple.
  
  Why would there be more than one implementation of YAML? Well, despite
  YAML's offering of being a simple data format, YAML is actually very
  deep and complex. Implementing the entirety of the YAML specification is
  a daunting task.
  
  For this reason I am currently working on 3 different YAML implementations.
  
  =over
  
  =item YAML
  
  The main YAML distribution will keeping evolving to support the entire
  YAML specification in pure Perl. This may not be the fastest or most
  stable module though. Currently, YAML.pm has lots of known bugs. It is
  mostly a great tool for dumping Perl data structures to a readable form.
  
  =item YAML::Tiny
  
  The point of YAML::Tiny is to strip YAML down to the 90% that people
  use most and offer that in a small, fast, stable, pure Perl form.
  YAML::Tiny will simply die when it is asked to do something it can't.
  
  =item YAML::Syck
  
  C<libsyck> is the C based YAML processing library used by the Ruby
  programming language (and also Python, PHP and Pugs). YAML::Syck is the
  Perl binding to C<libsyck>. It should be very fast, but may have
  problems of its own. It will also require C compilation.
  
  NOTE: Audrey Tang has actually completed this module and it works great
        and is 10 times faster than YAML.pm.
  
  =back
  
  In the future, there will likely be even more YAML modules. Remember,
  people other than Ingy are allowed to write YAML modules!
  
  =head1 FUNCTIONAL USAGE
  
  YAML is completely OO under the hood. Still it exports a few useful top
  level functions so that it is dead simple to use. These functions just
  do the OO stuff for you. If you want direct access to the OO API see the
  documentation for YAML::Dumper and YAML::Loader.
  
  =head2 Exported Functions
  
  The following functions are exported by YAML.pm by default. The reason
  they are exported is so that YAML works much like Data::Dumper. If you
  don't want functions to be imported, just use YAML with an empty
  import list:
  
      use YAML ();
  
  =over 4
  
  =item Dump(list-of-Perl-data-structures)
  
  Turn Perl data into YAML. This function works very much like
  Data::Dumper::Dumper(). It takes a list of Perl data structures and
  dumps them into a serialized form. It returns a string containing the
  YAML stream. The structures can be references or plain scalars.
  
  =item Load(string-containing-a-YAML-stream)
  
  Turn YAML into Perl data. This is the opposite of Dump. Just like
  Storable's thaw() function or the eval() function in relation to
  Data::Dumper. It parses a string containing a valid YAML stream into a
  list of Perl data structures.
  
  =back
  
  =head2 Exportable Functions
  
  These functions are not exported by default but you can request them in
  an import list like this:
  
      use YAML qw'freeze thaw Bless';
  
  =over 4
  
  =item freeze() and thaw()
  
  Aliases to Dump() and Load() for Storable fans. This will also allow
  YAML.pm to be plugged directly into modules like POE.pm, that use the
  freeze/thaw API for internal serialization.
  
  =item DumpFile(filepath, list)
  
  Writes the YAML stream to a file instead of just returning a string.
  
  =item LoadFile(filepath)
  
  Reads the YAML stream from a file instead of a string.
  
  =item Bless(perl-node, [yaml-node | class-name])
  
  Associate a normal Perl node, with a yaml node. A yaml node is an object
  tied to the YAML::Node class. The second argument is either a yaml node
  that you've already created or a class (package) name that supports a
  yaml_dump() function. A yaml_dump() function should take a perl node and
  return a yaml node. If no second argument is provided, Bless will create
  a yaml node. This node is not returned, but can be retrieved with the
  Blessed() function.
  
  Here's an example of how to use Bless. Say you have a hash containing
  three keys, but you only want to dump two of them. Furthermore the keys
  must be dumped in a certain order. Here's how you do that:
  
      use YAML qw(Dump Bless);
      $hash = {apple => 'good', banana => 'bad', cauliflower => 'ugly'};
      print Dump $hash;
      Bless($hash)->keys(['banana', 'apple']);
      print Dump $hash;
  
  produces:
  
      ---
      apple: good
      banana: bad
      cauliflower: ugly
      ---
      banana: bad
      apple: good
  
  Bless returns the tied part of a yaml-node, so that you can call the
  YAML::Node methods. This is the same thing that YAML::Node::ynode()
  returns. So another way to do the above example is:
  
      use YAML qw(Dump Bless);
      use YAML::Node;
      $hash = {apple => 'good', banana => 'bad', cauliflower => 'ugly'};
      print Dump $hash;
      Bless($hash);
      $ynode = ynode(Blessed($hash));
      $ynode->keys(['banana', 'apple']);
      print Dump $hash;
  
  Note that Blessing a Perl data structure does not change it anyway. The
  extra information is stored separately and looked up by the Blessed
  node's memory address.
  
  =item Blessed(perl-node)
  
  Returns the yaml node that a particular perl node is associated with
  (see above). Returns undef if the node is not (YAML) Blessed.
  
  =back
  
  =head1 GLOBAL OPTIONS
  
  YAML options are set using a group of global variables in the YAML
  namespace. This is similar to how Data::Dumper works.
  
  For example, to change the indentation width, do something like:
  
      local $YAML::Indent = 3;
  
  The current options are:
  
  =over 4
  
  =item DumperClass
  
  You can override which module/class YAML uses for Dumping data.
  
  =item LoaderClass
  
  You can override which module/class YAML uses for Loading data.
  
  =item Indent
  
  This is the number of space characters to use for each indentation level
  when doing a Dump(). The default is 2.
  
  By the way, YAML can use any number of characters for indentation at any
  level. So if you are editing YAML by hand feel free to do it anyway that
  looks pleasing to you; just be consistent for a given level.
  
  =item SortKeys
  
  Default is 1. (true)
  
  Tells YAML.pm whether or not to sort hash keys when storing a document.
  
  YAML::Node objects can have their own sort order, which is usually what
  you want. To override the YAML::Node order and sort the keys anyway, set
  SortKeys to 2.
  
  =item Stringify
  
  Default is 0. (false)
  
  Objects with string overloading should honor the overloading and dump the
  stringification of themselves, rather than the actual object's guts.
  
  =item UseHeader
  
  Default is 1. (true)
  
  This tells YAML.pm whether to use a separator string for a Dump
  operation. This only applies to the first document in a stream.
  Subsequent documents must have a YAML header by definition.
  
  =item UseVersion
  
  Default is 0. (false)
  
  Tells YAML.pm whether to include the YAML version on the
  separator/header.
  
      --- %YAML:1.0
  
  =item AnchorPrefix
  
  Default is ''.
  
  Anchor names are normally numeric. YAML.pm simply starts with '1' and
  increases by one for each new anchor. This option allows you to specify a
  string to be prepended to each anchor number.
  
  =item UseCode
  
  Setting the UseCode option is a shortcut to set both the DumpCode and
  LoadCode options at once. Setting UseCode to '1' tells YAML.pm to dump
  Perl code references as Perl (using B::Deparse) and to load them back
  into memory using eval(). The reason this has to be an option is that
  using eval() to parse untrusted code is, well, untrustworthy.
  
  =item DumpCode
  
  Determines if and how YAML.pm should serialize Perl code references. By
  default YAML.pm will dump code references as dummy placeholders (much
  like Data::Dumper). If DumpCode is set to '1' or 'deparse', code
  references will be dumped as actual Perl code.
  
  DumpCode can also be set to a subroutine reference so that you can
  write your own serializing routine. YAML.pm passes you the code ref. You
  pass back the serialization (as a string) and a format indicator. The
  format indicator is a simple string like: 'deparse' or 'bytecode'.
  
  =item LoadCode
  
  LoadCode is the opposite of DumpCode. It tells YAML if and how to
  deserialize code references. When set to '1' or 'deparse' it will use
  C<eval()>. Since this is potentially risky, only use this option if you
  know where your YAML has been.
  
  LoadCode can also be set to a subroutine reference so that you can write
  your own deserializing routine. YAML.pm passes the serialization (as a
  string) and a format indicator. You pass back the code reference.
  
  =item UseBlock
  
  YAML.pm uses heuristics to guess which scalar style is best for a given
  node. Sometimes you'll want all multiline scalars to use the 'block'
  style. If so, set this option to 1.
  
  NOTE: YAML's block style is akin to Perl's here-document.
  
  =item UseFold
  
  If you want to force YAML to use the 'folded' style for all multiline
  scalars, then set $UseFold to 1.
  
  NOTE: YAML's folded style is akin to the way HTML folds text,
        except smarter.
  
  =item UseAliases
  
  YAML has an alias mechanism such that any given structure in memory gets
  serialized once. Any other references to that structure are serialized
  only as alias markers. This is how YAML can serialize duplicate and
  recursive structures.
  
  Sometimes, when you KNOW that your data is nonrecursive in nature, you
  may want to serialize such that every node is expressed in full. (ie as
  a copy of the original). Setting $YAML::UseAliases to 0 will allow you
  to do this. This also may result in faster processing because the lookup
  overhead is by bypassed.
  
  THIS OPTION CAN BE DANGEROUS. *If* your data is recursive, this option
  *will* cause Dump() to run in an endless loop, chewing up your computers
  memory. You have been warned.
  
  =item CompressSeries
  
  Default is 1.
  
  Compresses the formatting of arrays of hashes:
  
      -
        foo: bar
      -
        bar: foo
  
  becomes:
  
      - foo: bar
      - bar: foo
  
  Since this output is usually more desirable, this option is turned on by
  default.
  
  =back
  
  =head1 YAML TERMINOLOGY
  
  YAML is a full featured data serialization language, and thus has its
  own terminology.
  
  It is important to remember that although YAML is heavily influenced by
  Perl and Python, it is a language in its own right, not merely just a
  representation of Perl structures.
  
  YAML has three constructs that are conspicuously similar to Perl's hash,
  array, and scalar. They are called mapping, sequence, and string
  respectively. By default, they do what you would expect. But each
  instance may have an explicit or implicit tag (type) that makes it
  behave differently. In this manner, YAML can be extended to represent
  Perl's Glob or Python's tuple, or Ruby's Bigint.
  
  =over 4
  
  =item stream
  
  A YAML stream is the full sequence of Unicode characters that a YAML
  parser would read or a YAML emitter would write. A stream may contain
  one or more YAML documents separated by YAML headers.
  
      ---
      a: mapping
      foo: bar
      ---
      - a
      - sequence
  
  =item document
  
  A YAML document is an independent data structure representation within a
  stream. It is a top level node. Each document in a YAML stream must
  begin with a YAML header line. Actually the header is optional on the
  first document.
  
      ---
      This: top level mapping
      is:
          - a
          - YAML
          - document
  
  =item header
  
  A YAML header is a line that begins a YAML document. It consists of
  three dashes, possibly followed by more info. Another purpose of the
  header line is that it serves as a place to put top level tag and anchor
  information.
  
      --- !recursive-sequence &001
      - * 001
      - * 001
  
  =item node
  
  A YAML node is the representation of a particular data structure. Nodes
  may contain other nodes. (In Perl terms, nodes are like scalars.
  Strings, arrayrefs and hashrefs. But this refers to the serialized
  format, not the in-memory structure.)
  
  =item tag
  
  This is similar to a type. It indicates how a particular YAML node
  serialization should be transferred into or out of memory. For instance
  a Foo::Bar object would use the tag 'perl/Foo::Bar':
  
      - !perl/Foo::Bar
          foo: 42
          bar: stool
  
  =item collection
  
  A collection is the generic term for a YAML data grouping. YAML has two
  types of collections: mappings and sequences. (Similar to hashes and arrays)
  
  =item mapping
  
  A mapping is a YAML collection defined by unordered key/value pairs with
  unique keys. By default YAML mappings are loaded into Perl hashes.
  
      a mapping:
          foo: bar
          two: times two is 4
  
  =item sequence
  
  A sequence is a YAML collection defined by an ordered list of elements. By
  default YAML sequences are loaded into Perl arrays.
  
      a sequence:
          - one bourbon
          - one scotch
          - one beer
  
  =item scalar
  
  A scalar is a YAML node that is a single value. By default YAML scalars
  are loaded into Perl scalars.
  
      a scalar key: a scalar value
  
  YAML has many styles for representing scalars. This is important because
  varying data will have varying formatting requirements to retain the
  optimum human readability.
  
  =item plain scalar
  
  A plain scalar is unquoted. All plain scalars are automatic candidates
  for "implicit tagging". This means that their tag may be determined
  automatically by examination. The typical uses for this are plain alpha
  strings, integers, real numbers, dates, times and currency.
  
      - a plain string
      - -42
      - 3.1415
      - 12:34
      - 123 this is an error
  
  =item single quoted scalar
  
  This is similar to Perl's use of single quotes. It means no escaping
  except for single quotes which are escaped by using two adjacent
  single quotes.
  
      - 'When I say ''\n'' I mean "backslash en"'
  
  =item double quoted scalar
  
  This is similar to Perl's use of double quotes. Character escaping can
  be used.
  
      - "This scalar\nhas two lines, and a bell -->\a"
  
  =item folded scalar
  
  This is a multiline scalar which begins on the next line. It is
  indicated by a single right angle bracket. It is unescaped like the
  single quoted scalar. Line folding is also performed.
  
      - >
       This is a multiline scalar which begins on
       the next line. It is indicated by a single
       carat. It is unescaped like the single
       quoted scalar. Line folding is also
       performed.
  
  =item block scalar
  
  This final multiline form is akin to Perl's here-document except that
  (as in all YAML data) scope is indicated by indentation. Therefore, no
  ending marker is required. The data is verbatim. No line folding.
  
      - |
          QTY  DESC          PRICE  TOTAL
          ---  ----          -----  -----
            1  Foo Fighters  $19.95 $19.95
            2  Bar Belles    $29.95 $59.90
  
  =item parser
  
  A YAML processor has four stages: parse, load, dump, emit.
  
  A parser parses a YAML stream. YAML.pm's Load() function contains a
  parser.
  
  =item loader
  
  The other half of the Load() function is a loader. This takes the
  information from the parser and loads it into a Perl data structure.
  
  =item dumper
  
  The Dump() function consists of a dumper and an emitter. The dumper
  walks through each Perl data structure and gives info to the emitter.
  
  =item emitter
  
  The emitter takes info from the dumper and turns it into a YAML stream.
  
  NOTE:
  In YAML.pm the parser/loader and the dumper/emitter code are currently
  very closely tied together. In the future they may be broken into
  separate stages.
  
  =back
  
  For more information please refer to the immensely helpful YAML
  specification available at L<http://www.yaml.org/spec/>.
  
  =head1 ysh - The YAML Shell
  
  The YAML distribution ships with a script called 'ysh', the YAML shell.
  ysh provides a simple, interactive way to play with YAML. If you type in
  Perl code, it displays the result in YAML. If you type in YAML it turns
  it into Perl code.
  
  To run ysh, (assuming you installed it along with YAML.pm) simply type:
  
      ysh [options]
  
  Please read the C<ysh> documentation for the full details. There are
  lots of options.
  
  =head1 BUGS & DEFICIENCIES
  
  If you find a bug in YAML, please try to recreate it in the YAML Shell
  with logging turned on ('ysh -L'). When you have successfully reproduced
  the bug, please mail the LOG file to the author (ingy@cpan.org).
  
  WARNING: This is still *ALPHA* code. Well, most of this code has been
  around for years...
  
  BIGGER WARNING: YAML.pm has been slow in the making, but I am committed
  to having top notch YAML tools in the Perl world. The YAML team is close
  to finalizing the YAML 1.1 spec. This version of YAML.pm is based off of
  a very old pre 1.0 spec. In actuality there isn't a ton of difference,
  and this YAML.pm is still fairly useful. Things will get much better in
  the future.
  
  =head1 RESOURCES
  
  L<http://lists.sourceforge.net/lists/listinfo/yaml-core> is the mailing
  list. This is where the language is discussed and designed.
  
  L<http://www.yaml.org> is the official YAML website.
  
  L<http://www.yaml.org/spec/> is the YAML 1.0 specification.
  
  L<http://yaml.kwiki.org> is the official YAML wiki.
  
  =head1 SEE ALSO
  
  See YAML::XS. Fast!
  
  =head1 AUTHOR
  
  Ingy döt Net <ingy@cpan.org>
  
  is responsible for YAML.pm.
  
  The YAML serialization language is the result of years of collaboration
  between Oren Ben-Kiki, Clark Evans and Ingy döt Net. Several others
  have added help along the way.
  
  =head1 COPYRIGHT
  
  Copyright (c) 2005, 2006, 2008, 2011-2013. Ingy döt Net.
  
  Copyright (c) 2001, 2002, 2005. Brian Ingerson.
  
  Some parts copyright (c) 2009 - 2010 Adam Kennedy
  
  This program is free software; you can redistribute it and/or modify it
  under the same terms as Perl itself.
  
  See L<http://www.perl.com/perl/misc/Artistic.html>
  
  =cut
YAML

$fatpacked{"YAML/Any.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'YAML_ANY';
  package YAML::Any;
  
  our $VERSION = '0.88';
  
  use strict;
  use Exporter ();
  
  @YAML::Any::ISA       = 'Exporter';
  @YAML::Any::EXPORT    = qw(Dump Load);
  @YAML::Any::EXPORT_OK = qw(DumpFile LoadFile);
  
  my @dump_options = qw(
      UseCode
      DumpCode
      SpecVersion
      Indent
      UseHeader
      UseVersion
      SortKeys
      AnchorPrefix
      UseBlock
      UseFold
      CompressSeries
      InlineSeries
      UseAliases
      Purity
      Stringify
  );
  
  my @load_options = qw(
      UseCode
      LoadCode
  );
  
  my @implementations = qw(
      YAML::XS
      YAML::Syck
      YAML::Old
      YAML
      YAML::Tiny
  );
  
  sub import {
      __PACKAGE__->implementation;
      goto &Exporter::import;
  }
  
  sub Dump {
      no strict 'refs';
      my $implementation = __PACKAGE__->implementation;
      for my $option (@dump_options) {
          my $var = "$implementation\::$option";
          my $value = $$var;
          local $$var;
          $$var = defined $value ? $value : ${"YAML::$option"};
      }
      return &{"$implementation\::Dump"}(@_);
  }
  
  sub DumpFile {
      no strict 'refs';
      my $implementation = __PACKAGE__->implementation;
      for my $option (@dump_options) {
          my $var = "$implementation\::$option";
          my $value = $$var;
          local $$var;
          $$var = defined $value ? $value : ${"YAML::$option"};
      }
      return &{"$implementation\::DumpFile"}(@_);
  }
  
  sub Load {
      no strict 'refs';
      my $implementation = __PACKAGE__->implementation;
      for my $option (@load_options) {
          my $var = "$implementation\::$option";
          my $value = $$var;
          local $$var;
          $$var = defined $value ? $value : ${"YAML::$option"};
      }
      return &{"$implementation\::Load"}(@_);
  }
  
  sub LoadFile {
      no strict 'refs';
      my $implementation = __PACKAGE__->implementation;
      for my $option (@load_options) {
          my $var = "$implementation\::$option";
          my $value = $$var;
          local $$var;
          $$var = defined $value ? $value : ${"YAML::$option"};
      }
      return &{"$implementation\::LoadFile"}(@_);
  }
  
  sub order {
      return @YAML::Any::_TEST_ORDER
          if @YAML::Any::_TEST_ORDER;
      return @implementations;
  }
  
  sub implementation {
      my @order = __PACKAGE__->order;
      for my $module (@order) {
          my $path = $module;
          $path =~ s/::/\//g;
          $path .= '.pm';
          return $module if exists $INC{$path};
          eval "require $module; 1" and return $module;
      }
      croak("YAML::Any couldn't find any of these YAML implementations: @order");
  }
  
  sub croak {
      require Carp;
      Carp::Croak(@_);
  }
  
  1;
  
  __END__
  
  =encoding UTF-8
  
  =head1 NAME
  
  YAML::Any - Pick a YAML implementation and use it.
  
  =head1 SYNOPSIS
  
      use YAML::Any;
      $YAML::Indent = 3;
      my $yaml = Dump(@objects);
  
  =head1 DESCRIPTION
  
  There are several YAML implementations that support the Dump/Load API.
  This module selects the best one available and uses it.
  
  =head1 ORDER
  
  Currently, YAML::Any will choose the first one of these YAML
  implementations that is installed on your system:
  
      YAML::XS
      YAML::Syck
      YAML::Old
      YAML
      YAML::Tiny
  
  =head1 OPTIONS
  
  If you specify an option like:
  
      $YAML::Indent = 4;
  
  And YAML::Any is using YAML::XS, it will use the proper variable:
  $YAML::XS::Indent.
  
  =head1 SUBROUTINES
  
  Like all the YAML modules that YAML::Any uses, the following subroutines
  are exported by default:
  
      Dump
      Load
  
  and the following subroutines are exportable by request:
  
      DumpFile
      LoadFile
  
  =head1 METHODS
  
  YAML::Any provides the following class methods.
  
  =over
  
  =item YAML::Any->order;
  
  This method returns a list of the current possible implementations that
  YAML::Any will search for.
  
  =item YAML::Any->implementation;
  
  This method returns the implementation the YAML::Any will use. This
  result is obtained by finding the first member of YAML::Any->order that
  is either already loaded in C<%INC> or that can be loaded using
  C<require>. If no implementation is found, an error will be thrown.
  
  =back
  
  =head1 AUTHOR
  
  Ingy döt Net <ingy@cpan.org>
  
  =head1 COPYRIGHT
  
  Copyright (c) 2008. Ingy döt Net.
  
  This program is free software; you can redistribute it and/or modify it
  under the same terms as Perl itself.
  
  See L<http://www.perl.com/perl/misc/Artistic.html>
  
  =cut
YAML_ANY

$fatpacked{"YAML/Dumper.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'YAML_DUMPER';
  package YAML::Dumper;
  use YAML::Mo;
  extends 'YAML::Dumper::Base';
  
  our $VERSION = '0.88';
  
  use YAML::Dumper::Base;
  use YAML::Node;
  use YAML::Types;
  
  # Context constants
  use constant KEY       => 3;
  use constant BLESSED   => 4;
  use constant FROMARRAY => 5;
  use constant VALUE     => "\x07YAML\x07VALUE\x07";
  
  # Common YAML character sets
  my $ESCAPE_CHAR = '[\\x00-\\x08\\x0b-\\x0d\\x0e-\\x1f]';
  my $LIT_CHAR    = '|';
  
  #==============================================================================
  # OO version of Dump. YAML->new->dump($foo);
  sub dump {
      my $self = shift;
      $self->stream('');
      $self->document(0);
      for my $document (@_) {
          $self->{document}++;
          $self->transferred({});
          $self->id_refcnt({});
          $self->id_anchor({});
          $self->anchor(1);
          $self->level(0);
          $self->offset->[0] = 0 - $self->indent_width;
          $self->_prewalk($document);
          $self->_emit_header($document);
          $self->_emit_node($document);
      }
      return $self->stream;
  }
  
  # Every YAML document in the stream must begin with a YAML header, unless
  # there is only a single document and the user requests "no header".
  sub _emit_header {
      my $self = shift;
      my ($node) = @_;
      if (not $self->use_header and
          $self->document == 1
         ) {
          $self->die('YAML_DUMP_ERR_NO_HEADER')
            unless ref($node) =~ /^(HASH|ARRAY)$/;
          $self->die('YAML_DUMP_ERR_NO_HEADER')
            if ref($node) eq 'HASH' and keys(%$node) == 0;
          $self->die('YAML_DUMP_ERR_NO_HEADER')
            if ref($node) eq 'ARRAY' and @$node == 0;
          # XXX Also croak if aliased, blessed, or ynode
          $self->headless(1);
          return;
      }
      $self->{stream} .= '---';
  # XXX Consider switching to 1.1 style
      if ($self->use_version) {
  #         $self->{stream} .= " #YAML:1.0";
      }
  }
  
  # Walk the tree to be dumped and keep track of its reference counts.
  # This function is where the Dumper does all its work. All type
  # transfers happen here.
  sub _prewalk {
      my $self = shift;
      my $stringify = $self->stringify;
      my ($class, $type, $node_id) = $self->node_info(\$_[0], $stringify);
  
      # Handle typeglobs
      if ($type eq 'GLOB') {
          $self->transferred->{$node_id} =
            YAML::Type::glob->yaml_dump($_[0]);
          $self->_prewalk($self->transferred->{$node_id});
          return;
      }
  
      # Handle regexps
      if (ref($_[0]) eq 'Regexp') {
          return;
      }
  
      # Handle Purity for scalars.
      # XXX can't find a use case yet. Might be YAGNI.
      if (not ref $_[0]) {
          $self->{id_refcnt}{$node_id}++ if $self->purity;
          return;
      }
  
      # Make a copy of original
      my $value = $_[0];
      ($class, $type, $node_id) = $self->node_info($value, $stringify);
  
      # Must be a stringified object.
      return if (ref($value) and not $type);
  
      # Look for things already transferred.
      if ($self->transferred->{$node_id}) {
          (undef, undef, $node_id) = (ref $self->transferred->{$node_id})
            ? $self->node_info($self->transferred->{$node_id}, $stringify)
            : $self->node_info(\ $self->transferred->{$node_id}, $stringify);
          $self->{id_refcnt}{$node_id}++;
          return;
      }
  
      # Handle code refs
      if ($type eq 'CODE') {
          $self->transferred->{$node_id} = 'placeholder';
          YAML::Type::code->yaml_dump(
              $self->dump_code,
              $_[0],
              $self->transferred->{$node_id}
          );
          ($class, $type, $node_id) =
            $self->node_info(\ $self->transferred->{$node_id}, $stringify);
          $self->{id_refcnt}{$node_id}++;
          return;
      }
  
      # Handle blessed things
      if (defined $class) {
          if ($value->can('yaml_dump')) {
              $value = $value->yaml_dump;
          }
          elsif ($type eq 'SCALAR') {
              $self->transferred->{$node_id} = 'placeholder';
              YAML::Type::blessed->yaml_dump
                ($_[0], $self->transferred->{$node_id});
              ($class, $type, $node_id) =
                $self->node_info(\ $self->transferred->{$node_id}, $stringify);
              $self->{id_refcnt}{$node_id}++;
              return;
          }
          else {
              $value = YAML::Type::blessed->yaml_dump($value);
          }
          $self->transferred->{$node_id} = $value;
          (undef, $type, $node_id) = $self->node_info($value, $stringify);
      }
  
      # Handle YAML Blessed things
      require YAML;
      if (defined YAML->global_object()->{blessed_map}{$node_id}) {
          $value = YAML->global_object()->{blessed_map}{$node_id};
          $self->transferred->{$node_id} = $value;
          ($class, $type, $node_id) = $self->node_info($value, $stringify);
          $self->_prewalk($value);
          return;
      }
  
      # Handle hard refs
      if ($type eq 'REF' or $type eq 'SCALAR') {
          $value = YAML::Type::ref->yaml_dump($value);
          $self->transferred->{$node_id} = $value;
          (undef, $type, $node_id) = $self->node_info($value, $stringify);
      }
  
      # Handle ref-to-glob's
      elsif ($type eq 'GLOB') {
          my $ref_ynode = $self->transferred->{$node_id} =
            YAML::Type::ref->yaml_dump($value);
  
          my $glob_ynode = $ref_ynode->{&VALUE} =
            YAML::Type::glob->yaml_dump($$value);
  
          (undef, undef, $node_id) = $self->node_info($glob_ynode, $stringify);
          $self->transferred->{$node_id} = $glob_ynode;
          $self->_prewalk($glob_ynode);
          return;
      }
  
      # Increment ref count for node
      return if ++($self->{id_refcnt}{$node_id}) > 1;
  
      # Keep on walking
      if ($type eq 'HASH') {
          $self->_prewalk($value->{$_})
              for keys %{$value};
          return;
      }
      elsif ($type eq 'ARRAY') {
          $self->_prewalk($_)
              for @{$value};
          return;
      }
  
      # Unknown type. Need to know about it.
      $self->warn(<<"...");
  YAML::Dumper can't handle dumping this type of data.
  Please report this to the author.
  
  id:    $node_id
  type:  $type
  class: $class
  value: $value
  
  ...
  
      return;
  }
  
  # Every data element and sub data element is a node.
  # Everything emitted goes through this function.
  sub _emit_node {
      my $self = shift;
      my ($type, $node_id);
      my $ref = ref($_[0]);
      if ($ref) {
          if ($ref eq 'Regexp') {
              $self->_emit(' !!perl/regexp');
              $self->_emit_str("$_[0]");
              return;
          }
          (undef, $type, $node_id) = $self->node_info($_[0], $self->stringify);
      }
      else {
          $type = $ref || 'SCALAR';
          (undef, undef, $node_id) = $self->node_info(\$_[0], $self->stringify);
      }
  
      my ($ynode, $tag) = ('') x 2;
      my ($value, $context) = (@_, 0);
  
      if (defined $self->transferred->{$node_id}) {
          $value = $self->transferred->{$node_id};
          $ynode = ynode($value);
          if (ref $value) {
              $tag = defined $ynode ? $ynode->tag->short : '';
              (undef, $type, $node_id) =
                $self->node_info($value, $self->stringify);
          }
          else {
              $ynode = ynode($self->transferred->{$node_id});
              $tag = defined $ynode ? $ynode->tag->short : '';
              $type = 'SCALAR';
              (undef, undef, $node_id) =
                $self->node_info(
                    \ $self->transferred->{$node_id},
                    $self->stringify
                );
          }
      }
      elsif ($ynode = ynode($value)) {
          $tag = $ynode->tag->short;
      }
  
      if ($self->use_aliases) {
          $self->{id_refcnt}{$node_id} ||= 0;
          if ($self->{id_refcnt}{$node_id} > 1) {
              if (defined $self->{id_anchor}{$node_id}) {
                  $self->{stream} .= ' *' . $self->{id_anchor}{$node_id} . "\n";
                  return;
              }
              my $anchor = $self->anchor_prefix . $self->{anchor}++;
              $self->{stream} .= ' &' . $anchor;
              $self->{id_anchor}{$node_id} = $anchor;
          }
      }
  
      return $self->_emit_str("$value")   # Stringified object
        if ref($value) and not $type;
      return $self->_emit_scalar($value, $tag)
        if $type eq 'SCALAR' and $tag;
      return $self->_emit_str($value)
        if $type eq 'SCALAR';
      return $self->_emit_mapping($value, $tag, $node_id, $context)
        if $type eq 'HASH';
      return $self->_emit_sequence($value, $tag)
        if $type eq 'ARRAY';
      $self->warn('YAML_DUMP_WARN_BAD_NODE_TYPE', $type);
      return $self->_emit_str("$value");
  }
  
  # A YAML mapping is akin to a Perl hash.
  sub _emit_mapping {
      my $self = shift;
      my ($value, $tag, $node_id, $context) = @_;
      $self->{stream} .= " !$tag" if $tag;
  
      # Sometimes 'keys' fails. Like on a bad tie implementation.
      my $empty_hash = not(eval {keys %$value});
      $self->warn('YAML_EMIT_WARN_KEYS', $@) if $@;
      return ($self->{stream} .= " {}\n") if $empty_hash;
  
      # If CompressSeries is on (default) and legal is this context, then
      # use it and make the indent level be 2 for this node.
      if ($context == FROMARRAY and
          $self->compress_series and
          not (defined $self->{id_anchor}{$node_id} or $tag or $empty_hash)
         ) {
          $self->{stream} .= ' ';
          $self->offset->[$self->level+1] = $self->offset->[$self->level] + 2;
      }
      else {
          $context = 0;
          $self->{stream} .= "\n"
            unless $self->headless && not($self->headless(0));
          $self->offset->[$self->level+1] =
            $self->offset->[$self->level] + $self->indent_width;
      }
  
      $self->{level}++;
      my @keys;
      if ($self->sort_keys == 1) {
          if (ynode($value)) {
              @keys = keys %$value;
          }
          else {
              @keys = sort keys %$value;
          }
      }
      elsif ($self->sort_keys == 2) {
          @keys = sort keys %$value;
      }
      # XXX This is hackish but sometimes handy. Not sure whether to leave it in.
      elsif (ref($self->sort_keys) eq 'ARRAY') {
          my $i = 1;
          my %order = map { ($_, $i++) } @{$self->sort_keys};
          @keys = sort {
              (defined $order{$a} and defined $order{$b})
                ? ($order{$a} <=> $order{$b})
                : ($a cmp $b);
          } keys %$value;
      }
      else {
          @keys = keys %$value;
      }
      # Force the YAML::VALUE ('=') key to sort last.
      if (exists $value->{&VALUE}) {
          for (my $i = 0; $i < @keys; $i++) {
              if ($keys[$i] eq &VALUE) {
                  splice(@keys, $i, 1);
                  push @keys, &VALUE;
                  last;
              }
          }
      }
  
      for my $key (@keys) {
          $self->_emit_key($key, $context);
          $context = 0;
          $self->{stream} .= ':';
          $self->_emit_node($value->{$key});
      }
      $self->{level}--;
  }
  
  # A YAML series is akin to a Perl array.
  sub _emit_sequence {
      my $self = shift;
      my ($value, $tag) = @_;
      $self->{stream} .= " !$tag" if $tag;
  
      return ($self->{stream} .= " []\n") if @$value == 0;
  
      $self->{stream} .= "\n"
        unless $self->headless && not($self->headless(0));
  
      # XXX Really crufty feature. Better implemented by ynodes.
      if ($self->inline_series and
          @$value <= $self->inline_series and
          not (scalar grep {ref or /\n/} @$value)
         ) {
          $self->{stream} =~ s/\n\Z/ /;
          $self->{stream} .= '[';
          for (my $i = 0; $i < @$value; $i++) {
              $self->_emit_str($value->[$i], KEY);
              last if $i == $#{$value};
              $self->{stream} .= ', ';
          }
          $self->{stream} .= "]\n";
          return;
      }
  
      $self->offset->[$self->level + 1] =
        $self->offset->[$self->level] + $self->indent_width;
      $self->{level}++;
      for my $val (@$value) {
          $self->{stream} .= ' ' x $self->offset->[$self->level];
          $self->{stream} .= '-';
          $self->_emit_node($val, FROMARRAY);
      }
      $self->{level}--;
  }
  
  # Emit a mapping key
  sub _emit_key {
      my $self = shift;
      my ($value, $context) = @_;
      $self->{stream} .= ' ' x $self->offset->[$self->level]
        unless $context == FROMARRAY;
      $self->_emit_str($value, KEY);
  }
  
  # Emit a blessed SCALAR
  sub _emit_scalar {
      my $self = shift;
      my ($value, $tag) = @_;
      $self->{stream} .= " !$tag";
      $self->_emit_str($value, BLESSED);
  }
  
  sub _emit {
      my $self = shift;
      $self->{stream} .= join '', @_;
  }
  
  # Emit a string value. YAML has many scalar styles. This routine attempts to
  # guess the best style for the text.
  sub _emit_str {
      my $self = shift;
      my $type = $_[1] || 0;
  
      # Use heuristics to find the best scalar emission style.
      $self->offset->[$self->level + 1] =
        $self->offset->[$self->level] + $self->indent_width;
      $self->{level}++;
  
      my $sf = $type == KEY ? '' : ' ';
      my $sb = $type == KEY ? '? ' : ' ';
      my $ef = $type == KEY ? '' : "\n";
      my $eb = "\n";
  
      while (1) {
          $self->_emit($sf),
          $self->_emit_plain($_[0]),
          $self->_emit($ef), last
            if not defined $_[0];
          $self->_emit($sf, '=', $ef), last
            if $_[0] eq VALUE;
          $self->_emit($sf),
          $self->_emit_double($_[0]),
          $self->_emit($ef), last
            if $_[0] =~ /$ESCAPE_CHAR/;
          if ($_[0] =~ /\n/) {
              $self->_emit($sb),
              $self->_emit_block($LIT_CHAR, $_[0]),
              $self->_emit($eb), last
                if $self->use_block;
                Carp::cluck "[YAML] \$UseFold is no longer supported"
                if $self->use_fold;
              $self->_emit($sf),
              $self->_emit_double($_[0]),
              $self->_emit($ef), last
                if length $_[0] <= 30;
              $self->_emit($sf),
              $self->_emit_double($_[0]),
              $self->_emit($ef), last
                if $_[0] !~ /\n\s*\S/;
              $self->_emit($sb),
              $self->_emit_block($LIT_CHAR, $_[0]),
              $self->_emit($eb), last;
          }
          $self->_emit($sf),
          $self->_emit_plain($_[0]),
          $self->_emit($ef), last
            if $self->is_valid_plain($_[0]);
          $self->_emit($sf),
          $self->_emit_double($_[0]),
          $self->_emit($ef), last
            if $_[0] =~ /'/;
          $self->_emit($sf),
          $self->_emit_single($_[0]),
          $self->_emit($ef);
          last;
      }
  
      $self->{level}--;
  
      return;
  }
  
  # Check whether or not a scalar should be emitted as an plain scalar.
  sub is_valid_plain {
      my $self = shift;
      return 0 unless length $_[0];
      # refer to YAML::Loader::parse_inline_simple()
      return 0 if $_[0] =~ /^[\s\{\[\~\`\'\"\!\@\#\>\|\%\&\?\*\^]/;
      return 0 if $_[0] =~ /[\{\[\]\},]/;
      return 0 if $_[0] =~ /[:\-\?]\s/;
      return 0 if $_[0] =~ /\s#/;
      return 0 if $_[0] =~ /\:(\s|$)/;
      return 0 if $_[0] =~ /[\s\|\>]$/;
      return 1;
  }
  
  sub _emit_block {
      my $self = shift;
      my ($indicator, $value) = @_;
      $self->{stream} .= $indicator;
      $value =~ /(\n*)\Z/;
      my $chomp = length $1 ? (length $1 > 1) ? '+' : '' : '-';
      $value = '~' if not defined $value;
      $self->{stream} .= $chomp;
      $self->{stream} .= $self->indent_width if $value =~ /^\s/;
      $self->{stream} .= $self->indent($value);
  }
  
  # Plain means that the scalar is unquoted.
  sub _emit_plain {
      my $self = shift;
      $self->{stream} .= defined $_[0] ? $_[0] : '~';
  }
  
  # Double quoting is for single lined escaped strings.
  sub _emit_double {
      my $self = shift;
      (my $escaped = $self->escape($_[0])) =~ s/"/\\"/g;
      $self->{stream} .= qq{"$escaped"};
  }
  
  # Single quoting is for single lined unescaped strings.
  sub _emit_single {
      my $self = shift;
      my $item = shift;
      $item =~ s{'}{''}g;
      $self->{stream} .= "'$item'";
  }
  
  #==============================================================================
  # Utility subroutines.
  #==============================================================================
  
  # Indent a scalar to the current indentation level.
  sub indent {
      my $self = shift;
      my ($text) = @_;
      return $text unless length $text;
      $text =~ s/\n\Z//;
      my $indent = ' ' x $self->offset->[$self->level];
      $text =~ s/^/$indent/gm;
      $text = "\n$text";
      return $text;
  }
  
  # Escapes for unprintable characters
  my @escapes = qw(\0   \x01 \x02 \x03 \x04 \x05 \x06 \a
                   \x08 \t   \n   \v   \f   \r   \x0e \x0f
                   \x10 \x11 \x12 \x13 \x14 \x15 \x16 \x17
                   \x18 \x19 \x1a \e   \x1c \x1d \x1e \x1f
                  );
  
  # Escape the unprintable characters
  sub escape {
      my $self = shift;
      my ($text) = @_;
      $text =~ s/\\/\\\\/g;
      $text =~ s/([\x00-\x1f])/$escapes[ord($1)]/ge;
      return $text;
  }
  
  1;
  
  __END__
  
  =encoding UTF-8
  
  =head1 NAME
  
  YAML::Dumper - YAML class for dumping Perl objects to YAML
  
  =head1 SYNOPSIS
  
      use YAML::Dumper;
      my $dumper = YAML::Dumper->new;
      $dumper->indent_width(4);
      print $dumper->dump({foo => 'bar'});
  
  =head1 DESCRIPTION
  
  YAML::Dumper is the module that YAML.pm used to serialize Perl objects to
  YAML. It is fully object oriented and usable on its own.
  
  =head1 AUTHOR
  
  Ingy döt Net <ingy@cpan.org>
  
  =head1 COPYRIGHT
  
  Copyright (c) 2006, 2011-2013. Ingy döt Net. All rights reserved.
  
  This program is free software; you can redistribute it and/or modify it
  under the same terms as Perl itself.
  
  See L<http://www.perl.com/perl/misc/Artistic.html>
  
  =cut
YAML_DUMPER

$fatpacked{"YAML/Dumper/Base.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'YAML_DUMPER_BASE';
  package YAML::Dumper::Base;
  use YAML::Mo;
  
  our $VERSION = '0.88';
  
  use YAML::Node;
  
  # YAML Dumping options
  has spec_version    => default => sub {'1.0'};
  has indent_width    => default => sub {2};
  has use_header      => default => sub {1};
  has use_version     => default => sub {0};
  has sort_keys       => default => sub {1};
  has anchor_prefix   => default => sub {''};
  has dump_code       => default => sub {0};
  has use_block       => default => sub {0};
  has use_fold        => default => sub {0};
  has compress_series => default => sub {1};
  has inline_series   => default => sub {0};
  has use_aliases     => default => sub {1};
  has purity          => default => sub {0};
  has stringify       => default => sub {0};
  
  # Properties
  has stream      => default => sub {''};
  has document    => default => sub {0};
  has transferred => default => sub {{}};
  has id_refcnt   => default => sub {{}};
  has id_anchor   => default => sub {{}};
  has anchor      => default => sub {1};
  has level       => default => sub {0};
  has offset      => default => sub {[]};
  has headless    => default => sub {0};
  has blessed_map => default => sub {{}};
  
  # Global Options are an idea taken from Data::Dumper. Really they are just
  # sugar on top of real OO properties. They make the simple Dump/Load API
  # easy to configure.
  sub set_global_options {
      my $self = shift;
      $self->spec_version($YAML::SpecVersion)
        if defined $YAML::SpecVersion;
      $self->indent_width($YAML::Indent)
        if defined $YAML::Indent;
      $self->use_header($YAML::UseHeader)
        if defined $YAML::UseHeader;
      $self->use_version($YAML::UseVersion)
        if defined $YAML::UseVersion;
      $self->sort_keys($YAML::SortKeys)
        if defined $YAML::SortKeys;
      $self->anchor_prefix($YAML::AnchorPrefix)
        if defined $YAML::AnchorPrefix;
      $self->dump_code($YAML::DumpCode || $YAML::UseCode)
        if defined $YAML::DumpCode or defined $YAML::UseCode;
      $self->use_block($YAML::UseBlock)
        if defined $YAML::UseBlock;
      $self->use_fold($YAML::UseFold)
        if defined $YAML::UseFold;
      $self->compress_series($YAML::CompressSeries)
        if defined $YAML::CompressSeries;
      $self->inline_series($YAML::InlineSeries)
        if defined $YAML::InlineSeries;
      $self->use_aliases($YAML::UseAliases)
        if defined $YAML::UseAliases;
      $self->purity($YAML::Purity)
        if defined $YAML::Purity;
      $self->stringify($YAML::Stringify)
        if defined $YAML::Stringify;
  }
  
  sub dump {
      my $self = shift;
      $self->die('dump() not implemented in this class.');
  }
  
  sub blessed {
      my $self = shift;
      my ($ref) = @_;
      $ref = \$_[0] unless ref $ref;
      my (undef, undef, $node_id) = YAML::Mo::Object->node_info($ref);
      $self->{blessed_map}->{$node_id};
  }
  
  sub bless {
      my $self = shift;
      my ($ref, $blessing) = @_;
      my $ynode;
      $ref = \$_[0] unless ref $ref;
      my (undef, undef, $node_id) = YAML::Mo::Object->node_info($ref);
      if (not defined $blessing) {
          $ynode = YAML::Node->new($ref);
      }
      elsif (ref $blessing) {
          $self->die() unless ynode($blessing);
          $ynode = $blessing;
      }
      else {
          no strict 'refs';
          my $transfer = $blessing . "::yaml_dump";
          $self->die() unless defined &{$transfer};
          $ynode = &{$transfer}($ref);
          $self->die() unless ynode($ynode);
      }
      $self->{blessed_map}->{$node_id} = $ynode;
      my $object = ynode($ynode) or $self->die();
      return $object;
  }
  
  1;
  
  __END__
  
  =encoding UTF-8
  
  =head1 NAME
  
  YAML::Dumper::Base - Base class for YAML Dumper classes
  
  =head1 SYNOPSIS
  
      package YAML::Dumper::Something;
      use YAML::Dumper::Base -base;
  
  =head1 DESCRIPTION
  
  YAML::Dumper::Base is a base class for creating YAML dumper classes.
  
  =head1 AUTHOR
  
  Ingy döt Net <ingy@cpan.org>
  
  =head1 COPYRIGHT
  
  Copyright (c) 2006, 2011-2013. Ingy döt Net. All rights reserved.
  
  This program is free software; you can redistribute it and/or modify it
  under the same terms as Perl itself.
  
  See L<http://www.perl.com/perl/misc/Artistic.html>
  
  =cut
YAML_DUMPER_BASE

$fatpacked{"YAML/Error.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'YAML_ERROR';
  package YAML::Error;
  use YAML::Mo;
  
  our $VERSION = '0.88';
  
  has 'code';
  has 'type' => default => sub {'Error'};
  has 'line';
  has 'document';
  has 'arguments' => default => sub {[]};
  
  my ($error_messages, %line_adjust);
  
  sub format_message {
      my $self = shift;
      my $output = 'YAML ' . $self->type . ': ';
      my $code = $self->code;
      if ($error_messages->{$code}) {
          $code = sprintf($error_messages->{$code}, @{$self->arguments});
      }
      $output .= $code . "\n";
  
      $output .= '   Code: ' . $self->code . "\n"
          if defined $self->code;
      $output .= '   Line: ' . $self->line . "\n"
          if defined $self->line;
      $output .= '   Document: ' . $self->document . "\n"
          if defined $self->document;
      return $output;
  }
  
  sub error_messages {
      $error_messages;
  }
  
  %$error_messages = map {s/^\s+//;$_} split "\n", <<'...';
  YAML_PARSE_ERR_BAD_CHARS
    Invalid characters in stream. This parser only supports printable ASCII
  YAML_PARSE_ERR_NO_FINAL_NEWLINE
    Stream does not end with newline character
  YAML_PARSE_ERR_BAD_MAJOR_VERSION
    Can't parse a %s document with a 1.0 parser
  YAML_PARSE_WARN_BAD_MINOR_VERSION
    Parsing a %s document with a 1.0 parser
  YAML_PARSE_WARN_MULTIPLE_DIRECTIVES
    '%s directive used more than once'
  YAML_PARSE_ERR_TEXT_AFTER_INDICATOR
    No text allowed after indicator
  YAML_PARSE_ERR_NO_ANCHOR
    No anchor for alias '*%s'
  YAML_PARSE_ERR_NO_SEPARATOR
    Expected separator '---'
  YAML_PARSE_ERR_SINGLE_LINE
    Couldn't parse single line value
  YAML_PARSE_ERR_BAD_ANCHOR
    Invalid anchor
  YAML_DUMP_ERR_INVALID_INDENT
    Invalid Indent width specified: '%s'
  YAML_LOAD_USAGE
    usage: YAML::Load($yaml_stream_scalar)
  YAML_PARSE_ERR_BAD_NODE
    Can't parse node
  YAML_PARSE_ERR_BAD_EXPLICIT
    Unsupported explicit transfer: '%s'
  YAML_DUMP_USAGE_DUMPCODE
    Invalid value for DumpCode: '%s'
  YAML_LOAD_ERR_FILE_INPUT
    Couldn't open %s for input:\n%s
  YAML_DUMP_ERR_FILE_CONCATENATE
    Can't concatenate to YAML file %s
  YAML_DUMP_ERR_FILE_OUTPUT
    Couldn't open %s for output:\n%s
  YAML_DUMP_ERR_NO_HEADER
    With UseHeader=0, the node must be a plain hash or array
  YAML_DUMP_WARN_BAD_NODE_TYPE
    Can't perform serialization for node type: '%s'
  YAML_EMIT_WARN_KEYS
    Encountered a problem with 'keys':\n%s
  YAML_DUMP_WARN_DEPARSE_FAILED
    Deparse failed for CODE reference
  YAML_DUMP_WARN_CODE_DUMMY
    Emitting dummy subroutine for CODE reference
  YAML_PARSE_ERR_MANY_EXPLICIT
    More than one explicit transfer
  YAML_PARSE_ERR_MANY_IMPLICIT
    More than one implicit request
  YAML_PARSE_ERR_MANY_ANCHOR
    More than one anchor
  YAML_PARSE_ERR_ANCHOR_ALIAS
    Can't define both an anchor and an alias
  YAML_PARSE_ERR_BAD_ALIAS
    Invalid alias
  YAML_PARSE_ERR_MANY_ALIAS
    More than one alias
  YAML_LOAD_ERR_NO_CONVERT
    Can't convert implicit '%s' node to explicit '%s' node
  YAML_LOAD_ERR_NO_DEFAULT_VALUE
    No default value for '%s' explicit transfer
  YAML_LOAD_ERR_NON_EMPTY_STRING
    Only the empty string can be converted to a '%s'
  YAML_LOAD_ERR_BAD_MAP_TO_SEQ
    Can't transfer map as sequence. Non numeric key '%s' encountered.
  YAML_DUMP_ERR_BAD_GLOB
    '%s' is an invalid value for Perl glob
  YAML_DUMP_ERR_BAD_REGEXP
    '%s' is an invalid value for Perl Regexp
  YAML_LOAD_ERR_BAD_MAP_ELEMENT
    Invalid element in map
  YAML_LOAD_WARN_DUPLICATE_KEY
    Duplicate map key found. Ignoring.
  YAML_LOAD_ERR_BAD_SEQ_ELEMENT
    Invalid element in sequence
  YAML_PARSE_ERR_INLINE_MAP
    Can't parse inline map
  YAML_PARSE_ERR_INLINE_SEQUENCE
    Can't parse inline sequence
  YAML_PARSE_ERR_BAD_DOUBLE
    Can't parse double quoted string
  YAML_PARSE_ERR_BAD_SINGLE
    Can't parse single quoted string
  YAML_PARSE_ERR_BAD_INLINE_IMPLICIT
    Can't parse inline implicit value '%s'
  YAML_PARSE_ERR_BAD_IMPLICIT
    Unrecognized implicit value '%s'
  YAML_PARSE_ERR_INDENTATION
    Error. Invalid indentation level
  YAML_PARSE_ERR_INCONSISTENT_INDENTATION
    Inconsistent indentation level
  YAML_LOAD_WARN_UNRESOLVED_ALIAS
    Can't resolve alias *%s
  YAML_LOAD_WARN_NO_REGEXP_IN_REGEXP
    No 'REGEXP' element for Perl regexp
  YAML_LOAD_WARN_BAD_REGEXP_ELEM
    Unknown element '%s' in Perl regexp
  YAML_LOAD_WARN_GLOB_NAME
    No 'NAME' element for Perl glob
  YAML_LOAD_WARN_PARSE_CODE
    Couldn't parse Perl code scalar: %s
  YAML_LOAD_WARN_CODE_DEPARSE
    Won't parse Perl code unless $YAML::LoadCode is set
  YAML_EMIT_ERR_BAD_LEVEL
    Internal Error: Bad level detected
  YAML_PARSE_WARN_AMBIGUOUS_TAB
    Amibiguous tab converted to spaces
  YAML_LOAD_WARN_BAD_GLOB_ELEM
    Unknown element '%s' in Perl glob
  YAML_PARSE_ERR_ZERO_INDENT
    Can't use zero as an indentation width
  YAML_LOAD_WARN_GLOB_IO
    Can't load an IO filehandle. Yet!!!
  ...
  
  %line_adjust = map {($_, 1)}
    qw(YAML_PARSE_ERR_BAD_MAJOR_VERSION
       YAML_PARSE_WARN_BAD_MINOR_VERSION
       YAML_PARSE_ERR_TEXT_AFTER_INDICATOR
       YAML_PARSE_ERR_NO_ANCHOR
       YAML_PARSE_ERR_MANY_EXPLICIT
       YAML_PARSE_ERR_MANY_IMPLICIT
       YAML_PARSE_ERR_MANY_ANCHOR
       YAML_PARSE_ERR_ANCHOR_ALIAS
       YAML_PARSE_ERR_BAD_ALIAS
       YAML_PARSE_ERR_MANY_ALIAS
       YAML_LOAD_ERR_NO_CONVERT
       YAML_LOAD_ERR_NO_DEFAULT_VALUE
       YAML_LOAD_ERR_NON_EMPTY_STRING
       YAML_LOAD_ERR_BAD_MAP_TO_SEQ
       YAML_LOAD_ERR_BAD_STR_TO_INT
       YAML_LOAD_ERR_BAD_STR_TO_DATE
       YAML_LOAD_ERR_BAD_STR_TO_TIME
       YAML_LOAD_WARN_DUPLICATE_KEY
       YAML_PARSE_ERR_INLINE_MAP
       YAML_PARSE_ERR_INLINE_SEQUENCE
       YAML_PARSE_ERR_BAD_DOUBLE
       YAML_PARSE_ERR_BAD_SINGLE
       YAML_PARSE_ERR_BAD_INLINE_IMPLICIT
       YAML_PARSE_ERR_BAD_IMPLICIT
       YAML_LOAD_WARN_NO_REGEXP_IN_REGEXP
       YAML_LOAD_WARN_BAD_REGEXP_ELEM
       YAML_LOAD_WARN_REGEXP_CREATE
       YAML_LOAD_WARN_GLOB_NAME
       YAML_LOAD_WARN_PARSE_CODE
       YAML_LOAD_WARN_CODE_DEPARSE
       YAML_LOAD_WARN_BAD_GLOB_ELEM
       YAML_PARSE_ERR_ZERO_INDENT
      );
  
  package YAML::Warning;
  
  our @ISA = 'YAML::Error';
  
  1;
  
  __END__
  
  =encoding UTF-8
  
  =head1 NAME
  
  YAML::Error - Error formatting class for YAML modules
  
  =head1 SYNOPSIS
  
      $self->die('YAML_PARSE_ERR_NO_ANCHOR', $alias);
      $self->warn('YAML_LOAD_WARN_DUPLICATE_KEY');
  
  =head1 DESCRIPTION
  
  This module provides a C<die> and a C<warn> facility.
  
  =head1 AUTHOR
  
  Ingy döt Net <ingy@cpan.org>
  
  =head1 COPYRIGHT
  
  Copyright (c) 2006, 2011-2013. Ingy döt Net. All rights reserved.
  
  This program is free software; you can redistribute it and/or modify it
  under the same terms as Perl itself.
  
  See L<http://www.perl.com/perl/misc/Artistic.html>
  
  =cut
YAML_ERROR

$fatpacked{"YAML/Loader.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'YAML_LOADER';
  package YAML::Loader;
  use YAML::Mo;
  extends 'YAML::Loader::Base';
  
  our $VERSION = '0.88';
  
  use YAML::Loader::Base;
  use YAML::Types;
  
  # Context constants
  use constant LEAF       => 1;
  use constant COLLECTION => 2;
  use constant VALUE      => "\x07YAML\x07VALUE\x07";
  use constant COMMENT    => "\x07YAML\x07COMMENT\x07";
  
  # Common YAML character sets
  my $ESCAPE_CHAR = '[\\x00-\\x08\\x0b-\\x0d\\x0e-\\x1f]';
  my $FOLD_CHAR   = '>';
  my $LIT_CHAR    = '|';
  my $LIT_CHAR_RX = "\\$LIT_CHAR";
  
  sub load {
      my $self = shift;
      $self->stream($_[0] || '');
      return $self->_parse();
  }
  
  # Top level function for parsing. Parse each document in order and
  # handle processing for YAML headers.
  sub _parse {
      my $self = shift;
      my (%directives, $preface);
      $self->{stream} =~ s|\015\012|\012|g;
      $self->{stream} =~ s|\015|\012|g;
      $self->line(0);
      $self->die('YAML_PARSE_ERR_BAD_CHARS')
        if $self->stream =~ /$ESCAPE_CHAR/;
      $self->die('YAML_PARSE_ERR_NO_FINAL_NEWLINE')
        if length($self->stream) and
           $self->{stream} !~ s/(.)\n\Z/$1/s;
      $self->lines([split /\x0a/, $self->stream, -1]);
      $self->line(1);
      # Throw away any comments or blanks before the header (or start of
      # content for headerless streams)
      $self->_parse_throwaway_comments();
      $self->document(0);
      $self->documents([]);
      # Add an "assumed" header if there is no header and the stream is
      # not empty (after initial throwaways).
      if (not $self->eos) {
          if ($self->lines->[0] !~ /^---(\s|$)/) {
              unshift @{$self->lines}, '---';
              $self->{line}--;
          }
      }
  
      # Main Loop. Parse out all the top level nodes and return them.
      while (not $self->eos) {
          $self->anchor2node({});
          $self->{document}++;
          $self->done(0);
          $self->level(0);
          $self->offset->[0] = -1;
  
          if ($self->lines->[0] =~ /^---\s*(.*)$/) {
              my @words = split /\s+/, $1;
              %directives = ();
              while (@words && $words[0] =~ /^#(\w+):(\S.*)$/) {
                  my ($key, $value) = ($1, $2);
                  shift(@words);
                  if (defined $directives{$key}) {
                      $self->warn('YAML_PARSE_WARN_MULTIPLE_DIRECTIVES',
                        $key, $self->document);
                      next;
                  }
                  $directives{$key} = $value;
              }
              $self->preface(join ' ', @words);
          }
          else {
              $self->die('YAML_PARSE_ERR_NO_SEPARATOR');
          }
  
          if (not $self->done) {
              $self->_parse_next_line(COLLECTION);
          }
          if ($self->done) {
              $self->{indent} = -1;
              $self->content('');
          }
  
          $directives{YAML} ||= '1.0';
          $directives{TAB} ||= 'NONE';
          ($self->{major_version}, $self->{minor_version}) =
            split /\./, $directives{YAML}, 2;
          $self->die('YAML_PARSE_ERR_BAD_MAJOR_VERSION', $directives{YAML})
            if $self->major_version ne '1';
          $self->warn('YAML_PARSE_WARN_BAD_MINOR_VERSION', $directives{YAML})
            if $self->minor_version ne '0';
          $self->die('Unrecognized TAB policy')
            unless $directives{TAB} =~ /^(NONE|\d+)(:HARD)?$/;
  
          push @{$self->documents}, $self->_parse_node();
      }
      return wantarray ? @{$self->documents} : $self->documents->[-1];
  }
  
  # This function is the dispatcher for parsing each node. Every node
  # recurses back through here. (Inlines are an exception as they have
  # their own sub-parser.)
  sub _parse_node {
      my $self = shift;
      my $preface = $self->preface;
      $self->preface('');
      my ($node, $type, $indicator, $escape, $chomp) = ('') x 5;
      my ($anchor, $alias, $explicit, $implicit, $class) = ('') x 5;
      ($anchor, $alias, $explicit, $implicit, $preface) =
        $self->_parse_qualifiers($preface);
      if ($anchor) {
          $self->anchor2node->{$anchor} = CORE::bless [], 'YAML-anchor2node';
      }
      $self->inline('');
      while (length $preface) {
          my $line = $self->line - 1;
          if ($preface =~ s/^($FOLD_CHAR|$LIT_CHAR_RX)(-|\+)?\d*\s*//) {
              $indicator = $1;
              $chomp = $2 if defined($2);
          }
          else {
              $self->die('YAML_PARSE_ERR_TEXT_AFTER_INDICATOR') if $indicator;
              $self->inline($preface);
              $preface = '';
          }
      }
      if ($alias) {
          $self->die('YAML_PARSE_ERR_NO_ANCHOR', $alias)
            unless defined $self->anchor2node->{$alias};
          if (ref($self->anchor2node->{$alias}) ne 'YAML-anchor2node') {
              $node = $self->anchor2node->{$alias};
          }
          else {
              $node = do {my $sv = "*$alias"};
              push @{$self->anchor2node->{$alias}}, [\$node, $self->line];
          }
      }
      elsif (length $self->inline) {
          $node = $self->_parse_inline(1, $implicit, $explicit);
          if (length $self->inline) {
              $self->die('YAML_PARSE_ERR_SINGLE_LINE');
          }
      }
      elsif ($indicator eq $LIT_CHAR) {
          $self->{level}++;
          $node = $self->_parse_block($chomp);
          $node = $self->_parse_implicit($node) if $implicit;
          $self->{level}--;
      }
      elsif ($indicator eq $FOLD_CHAR) {
          $self->{level}++;
          $node = $self->_parse_unfold($chomp);
          $node = $self->_parse_implicit($node) if $implicit;
          $self->{level}--;
      }
      else {
          $self->{level}++;
          $self->offset->[$self->level] ||= 0;
          if ($self->indent == $self->offset->[$self->level]) {
              if ($self->content =~ /^-( |$)/) {
                  $node = $self->_parse_seq($anchor);
              }
              elsif ($self->content =~ /(^\?|\:( |$))/) {
                  $node = $self->_parse_mapping($anchor);
              }
              elsif ($preface =~ /^\s*$/) {
                  $node = $self->_parse_implicit('');
              }
              else {
                  $self->die('YAML_PARSE_ERR_BAD_NODE');
              }
          }
          else {
              $node = undef;
          }
          $self->{level}--;
      }
      $#{$self->offset} = $self->level;
  
      if ($explicit) {
          if ($class) {
              if (not ref $node) {
                  my $copy = $node;
                  undef $node;
                  $node = \$copy;
              }
              CORE::bless $node, $class;
          }
          else {
              $node = $self->_parse_explicit($node, $explicit);
          }
      }
      if ($anchor) {
          if (ref($self->anchor2node->{$anchor}) eq 'YAML-anchor2node') {
              # XXX Can't remember what this code actually does
              for my $ref (@{$self->anchor2node->{$anchor}}) {
                  ${$ref->[0]} = $node;
                  $self->warn('YAML_LOAD_WARN_UNRESOLVED_ALIAS',
                      $anchor, $ref->[1]);
              }
          }
          $self->anchor2node->{$anchor} = $node;
      }
      return $node;
  }
  
  # Preprocess the qualifiers that may be attached to any node.
  sub _parse_qualifiers {
      my $self = shift;
      my ($preface) = @_;
      my ($anchor, $alias, $explicit, $implicit, $token) = ('') x 5;
      $self->inline('');
      while ($preface =~ /^[&*!]/) {
          my $line = $self->line - 1;
          if ($preface =~ s/^\!(\S+)\s*//) {
              $self->die('YAML_PARSE_ERR_MANY_EXPLICIT') if $explicit;
              $explicit = $1;
          }
          elsif ($preface =~ s/^\!\s*//) {
              $self->die('YAML_PARSE_ERR_MANY_IMPLICIT') if $implicit;
              $implicit = 1;
          }
          elsif ($preface =~ s/^\&([^ ,:]+)\s*//) {
              $token = $1;
              $self->die('YAML_PARSE_ERR_BAD_ANCHOR')
                unless $token =~ /^[a-zA-Z0-9]+$/;
              $self->die('YAML_PARSE_ERR_MANY_ANCHOR') if $anchor;
              $self->die('YAML_PARSE_ERR_ANCHOR_ALIAS') if $alias;
              $anchor = $token;
          }
          elsif ($preface =~ s/^\*([^ ,:]+)\s*//) {
              $token = $1;
              $self->die('YAML_PARSE_ERR_BAD_ALIAS')
                unless $token =~ /^[a-zA-Z0-9]+$/;
              $self->die('YAML_PARSE_ERR_MANY_ALIAS') if $alias;
              $self->die('YAML_PARSE_ERR_ANCHOR_ALIAS') if $anchor;
              $alias = $token;
          }
      }
      return ($anchor, $alias, $explicit, $implicit, $preface);
  }
  
  # Morph a node to it's explicit type
  sub _parse_explicit {
      my $self = shift;
      my ($node, $explicit) = @_;
      my ($type, $class);
      if ($explicit =~ /^\!?perl\/(hash|array|ref|scalar)(?:\:(\w(\w|\:\:)*)?)?$/) {
          ($type, $class) = (($1 || ''), ($2 || ''));
  
          # FIXME # die unless uc($type) eq ref($node) ?
  
          if ( $type eq "ref" ) {
              $self->die('YAML_LOAD_ERR_NO_DEFAULT_VALUE', 'XXX', $explicit)
              unless exists $node->{VALUE()} and scalar(keys %$node) == 1;
  
              my $value = $node->{VALUE()};
              $node = \$value;
          }
  
          if ( $type eq "scalar" and length($class) and !ref($node) ) {
              my $value = $node;
              $node = \$value;
          }
  
          if ( length($class) ) {
              CORE::bless($node, $class);
          }
  
          return $node;
      }
      if ($explicit =~ m{^!?perl/(glob|regexp|code)(?:\:(\w(\w|\:\:)*)?)?$}) {
          ($type, $class) = (($1 || ''), ($2 || ''));
          my $type_class = "YAML::Type::$type";
          no strict 'refs';
          if ($type_class->can('yaml_load')) {
              return $type_class->yaml_load($node, $class, $self);
          }
          else {
              $self->die('YAML_LOAD_ERR_NO_CONVERT', 'XXX', $explicit);
          }
      }
      # This !perl/@Foo and !perl/$Foo are deprecated but still parsed
      elsif ($YAML::TagClass->{$explicit} ||
             $explicit =~ m{^perl/(\@|\$)?([a-zA-Z](\w|::)+)$}
            ) {
          $class = $YAML::TagClass->{$explicit} || $2;
          if ($class->can('yaml_load')) {
              require YAML::Node;
              return $class->yaml_load(YAML::Node->new($node, $explicit));
          }
          else {
              if (ref $node) {
                  return CORE::bless $node, $class;
              }
              else {
                  return CORE::bless \$node, $class;
              }
          }
      }
      elsif (ref $node) {
          require YAML::Node;
          return YAML::Node->new($node, $explicit);
      }
      else {
          # XXX This is likely wrong. Failing test:
          # --- !unknown 'scalar value'
          return $node;
      }
  }
  
  # Parse a YAML mapping into a Perl hash
  sub _parse_mapping {
      my $self = shift;
      my ($anchor) = @_;
      my $mapping = {};
      $self->anchor2node->{$anchor} = $mapping;
      my $key;
      while (not $self->done and $self->indent == $self->offset->[$self->level]) {
          # If structured key:
          if ($self->{content} =~ s/^\?\s*//) {
              $self->preface($self->content);
              $self->_parse_next_line(COLLECTION);
              $key = $self->_parse_node();
              $key = "$key";
          }
          # If "default" key (equals sign)
          elsif ($self->{content} =~ s/^\=\s*//) {
              $key = VALUE;
          }
          # If "comment" key (slash slash)
          elsif ($self->{content} =~ s/^\=\s*//) {
              $key = COMMENT;
          }
          # Regular scalar key:
          else {
              $self->inline($self->content);
              $key = $self->_parse_inline();
              $key = "$key";
              $self->content($self->inline);
              $self->inline('');
          }
  
          unless ($self->{content} =~ s/^:\s*//) {
              $self->die('YAML_LOAD_ERR_BAD_MAP_ELEMENT');
          }
          $self->preface($self->content);
          my $line = $self->line;
          $self->_parse_next_line(COLLECTION);
          my $value = $self->_parse_node();
          if (exists $mapping->{$key}) {
              $self->warn('YAML_LOAD_WARN_DUPLICATE_KEY');
          }
          else {
              $mapping->{$key} = $value;
          }
      }
      return $mapping;
  }
  
  # Parse a YAML sequence into a Perl array
  sub _parse_seq {
      my $self = shift;
      my ($anchor) = @_;
      my $seq = [];
      $self->anchor2node->{$anchor} = $seq;
      while (not $self->done and $self->indent == $self->offset->[$self->level]) {
          if ($self->content =~ /^-(?: (.*))?$/) {
              $self->preface(defined($1) ? $1 : '');
          }
          else {
              $self->die('YAML_LOAD_ERR_BAD_SEQ_ELEMENT');
          }
          if ($self->preface =~ /^(\s*)(\w.*\:(?: |$).*)$/) {
              $self->indent($self->offset->[$self->level] + 2 + length($1));
              $self->content($2);
              $self->level($self->level + 1);
              $self->offset->[$self->level] = $self->indent;
              $self->preface('');
              push @$seq, $self->_parse_mapping('');
              $self->{level}--;
              $#{$self->offset} = $self->level;
          }
          else {
              $self->_parse_next_line(COLLECTION);
              push @$seq, $self->_parse_node();
          }
      }
      return $seq;
  }
  
  # Parse an inline value. Since YAML supports inline collections, this is
  # the top level of a sub parsing.
  sub _parse_inline {
      my $self = shift;
      my ($top, $top_implicit, $top_explicit) = (@_, '', '', '');
      $self->{inline} =~ s/^\s*(.*)\s*$/$1/; # OUCH - mugwump
      my ($node, $anchor, $alias, $explicit, $implicit) = ('') x 5;
      ($anchor, $alias, $explicit, $implicit, $self->{inline}) =
        $self->_parse_qualifiers($self->inline);
      if ($anchor) {
          $self->anchor2node->{$anchor} = CORE::bless [], 'YAML-anchor2node';
      }
      $implicit ||= $top_implicit;
      $explicit ||= $top_explicit;
      ($top_implicit, $top_explicit) = ('', '');
      if ($alias) {
          $self->die('YAML_PARSE_ERR_NO_ANCHOR', $alias)
            unless defined $self->anchor2node->{$alias};
          if (ref($self->anchor2node->{$alias}) ne 'YAML-anchor2node') {
              $node = $self->anchor2node->{$alias};
          }
          else {
              $node = do {my $sv = "*$alias"};
              push @{$self->anchor2node->{$alias}}, [\$node, $self->line];
          }
      }
      elsif ($self->inline =~ /^\{/) {
          $node = $self->_parse_inline_mapping($anchor);
      }
      elsif ($self->inline =~ /^\[/) {
          $node = $self->_parse_inline_seq($anchor);
      }
      elsif ($self->inline =~ /^"/) {
          $node = $self->_parse_inline_double_quoted();
          $node = $self->_unescape($node);
          $node = $self->_parse_implicit($node) if $implicit;
      }
      elsif ($self->inline =~ /^'/) {
          $node = $self->_parse_inline_single_quoted();
          $node = $self->_parse_implicit($node) if $implicit;
      }
      else {
          if ($top) {
              $node = $self->inline;
              $self->inline('');
          }
          else {
              $node = $self->_parse_inline_simple();
          }
          $node = $self->_parse_implicit($node) unless $explicit;
      }
      if ($explicit) {
          $node = $self->_parse_explicit($node, $explicit);
      }
      if ($anchor) {
          if (ref($self->anchor2node->{$anchor}) eq 'YAML-anchor2node') {
              for my $ref (@{$self->anchor2node->{$anchor}}) {
                  ${$ref->[0]} = $node;
                  $self->warn('YAML_LOAD_WARN_UNRESOLVED_ALIAS',
                      $anchor, $ref->[1]);
              }
          }
          $self->anchor2node->{$anchor} = $node;
      }
      return $node;
  }
  
  # Parse the inline YAML mapping into a Perl hash
  sub _parse_inline_mapping {
      my $self = shift;
      my ($anchor) = @_;
      my $node = {};
      $self->anchor2node->{$anchor} = $node;
  
      $self->die('YAML_PARSE_ERR_INLINE_MAP')
        unless $self->{inline} =~ s/^\{\s*//;
      while (not $self->{inline} =~ s/^\s*\}//) {
          my $key = $self->_parse_inline();
          $self->die('YAML_PARSE_ERR_INLINE_MAP')
            unless $self->{inline} =~ s/^\: \s*//;
          my $value = $self->_parse_inline();
          if (exists $node->{$key}) {
              $self->warn('YAML_LOAD_WARN_DUPLICATE_KEY');
          }
          else {
              $node->{$key} = $value;
          }
          next if $self->inline =~ /^\s*\}/;
          $self->die('YAML_PARSE_ERR_INLINE_MAP')
            unless $self->{inline} =~ s/^\,\s*//;
      }
      return $node;
  }
  
  # Parse the inline YAML sequence into a Perl array
  sub _parse_inline_seq {
      my $self = shift;
      my ($anchor) = @_;
      my $node = [];
      $self->anchor2node->{$anchor} = $node;
  
      $self->die('YAML_PARSE_ERR_INLINE_SEQUENCE')
        unless $self->{inline} =~ s/^\[\s*//;
      while (not $self->{inline} =~ s/^\s*\]//) {
          my $value = $self->_parse_inline();
          push @$node, $value;
          next if $self->inline =~ /^\s*\]/;
          $self->die('YAML_PARSE_ERR_INLINE_SEQUENCE')
            unless $self->{inline} =~ s/^\,\s*//;
      }
      return $node;
  }
  
  # Parse the inline double quoted string.
  sub _parse_inline_double_quoted {
      my $self = shift;
      my $node;
      # https://rt.cpan.org/Public/Bug/Display.html?id=90593
      if ($self->inline =~ /^"((?>(?>(?:\\"|[^"]){0,32766}){0,32766}))"\s*(.*)$/) {
          $node = $1;
          $self->inline($2);
          $node =~ s/\\"/"/g;
      }
      else {
          $self->die('YAML_PARSE_ERR_BAD_DOUBLE');
      }
      return $node;
  }
  
  
  # Parse the inline single quoted string.
  sub _parse_inline_single_quoted {
      my $self = shift;
      my $node;
      if ($self->inline =~ /^'((?:''|[^'])*)'\s*(.*)$/) {
          $node = $1;
          $self->inline($2);
          $node =~ s/''/'/g;
      }
      else {
          $self->die('YAML_PARSE_ERR_BAD_SINGLE');
      }
      return $node;
  }
  
  # Parse the inline unquoted string and do implicit typing.
  sub _parse_inline_simple {
      my $self = shift;
      my $value;
      if ($self->inline =~ /^(|[^!@#%^&*].*?)(?=[\[\]\{\},]|, |: |- |:\s*$|$)/) {
          $value = $1;
          substr($self->{inline}, 0, length($1)) = '';
      }
      else {
          $self->die('YAML_PARSE_ERR_BAD_INLINE_IMPLICIT', $value);
      }
      return $value;
  }
  
  sub _parse_implicit {
      my $self = shift;
      my ($value) = @_;
      $value =~ s/\s*$//;
      return $value if $value eq '';
      return undef if $value =~ /^~$/;
      return $value
        unless $value =~ /^[\@\`\^]/ or
               $value =~ /^[\-\?]\s/;
      $self->die('YAML_PARSE_ERR_BAD_IMPLICIT', $value);
  }
  
  # Unfold a YAML multiline scalar into a single string.
  sub _parse_unfold {
      my $self = shift;
      my ($chomp) = @_;
      my $node = '';
      my $space = 0;
      while (not $self->done and $self->indent == $self->offset->[$self->level]) {
          $node .= $self->content. "\n";
          $self->_parse_next_line(LEAF);
      }
      $node =~ s/^(\S.*)\n(?=\S)/$1 /gm;
      $node =~ s/^(\S.*)\n(\n+\S)/$1$2/gm;
      $node =~ s/\n*\Z// unless $chomp eq '+';
      $node .= "\n" unless $chomp;
      return $node;
  }
  
  # Parse a YAML block style scalar. This is like a Perl here-document.
  sub _parse_block {
      my $self = shift;
      my ($chomp) = @_;
      my $node = '';
      while (not $self->done and $self->indent == $self->offset->[$self->level]) {
          $node .= $self->content . "\n";
          $self->_parse_next_line(LEAF);
      }
      return $node if '+' eq $chomp;
      $node =~ s/\n*\Z/\n/;
      $node =~ s/\n\Z// if $chomp eq '-';
      return $node;
  }
  
  # Handle Perl style '#' comments. Comments must be at the same indentation
  # level as the collection line following them.
  sub _parse_throwaway_comments {
      my $self = shift;
      while (@{$self->lines} and
             $self->lines->[0] =~ m{^\s*(\#|$)}
            ) {
          shift @{$self->lines};
          $self->{line}++;
      }
      $self->eos($self->{done} = not @{$self->lines});
  }
  
  # This is the routine that controls what line is being parsed. It gets called
  # once for each line in the YAML stream.
  #
  # This routine must:
  # 1) Skip past the current line
  # 2) Determine the indentation offset for a new level
  # 3) Find the next _content_ line
  #   A) Skip over any throwaways (Comments/blanks)
  #   B) Set $self->indent, $self->content, $self->line
  # 4) Expand tabs appropriately
  sub _parse_next_line {
      my $self = shift;
      my ($type) = @_;
      my $level = $self->level;
      my $offset = $self->offset->[$level];
      $self->die('YAML_EMIT_ERR_BAD_LEVEL') unless defined $offset;
      shift @{$self->lines};
      $self->eos($self->{done} = not @{$self->lines});
      return if $self->eos;
      $self->{line}++;
  
      # Determine the offset for a new leaf node
      if ($self->preface =~
          qr/(?:^|\s)(?:$FOLD_CHAR|$LIT_CHAR_RX)(?:-|\+)?(\d*)\s*$/
         ) {
          $self->die('YAML_PARSE_ERR_ZERO_INDENT')
            if length($1) and $1 == 0;
          $type = LEAF;
          if (length($1)) {
              $self->offset->[$level + 1] = $offset + $1;
          }
          else {
              # First get rid of any comments.
              while (@{$self->lines} && ($self->lines->[0] =~ /^\s*#/)) {
                  $self->lines->[0] =~ /^( *)/ or die;
                  last unless length($1) <= $offset;
                  shift @{$self->lines};
                  $self->{line}++;
              }
              $self->eos($self->{done} = not @{$self->lines});
              return if $self->eos;
              if ($self->lines->[0] =~ /^( *)\S/ and length($1) > $offset) {
                  $self->offset->[$level+1] = length($1);
              }
              else {
                  $self->offset->[$level+1] = $offset + 1;
              }
          }
          $offset = $self->offset->[++$level];
      }
      # Determine the offset for a new collection level
      elsif ($type == COLLECTION and
             $self->preface =~ /^(\s*(\!\S*|\&\S+))*\s*$/) {
          $self->_parse_throwaway_comments();
          if ($self->eos) {
              $self->offset->[$level+1] = $offset + 1;
              return;
          }
          else {
              $self->lines->[0] =~ /^( *)\S/ or die;
              if (length($1) > $offset) {
                  $self->offset->[$level+1] = length($1);
              }
              else {
                  $self->offset->[$level+1] = $offset + 1;
              }
          }
          $offset = $self->offset->[++$level];
      }
  
      if ($type == LEAF) {
          while (@{$self->lines} and
                 $self->lines->[0] =~ m{^( *)(\#)} and
                 length($1) < $offset
                ) {
              shift @{$self->lines};
              $self->{line}++;
          }
          $self->eos($self->{done} = not @{$self->lines});
      }
      else {
          $self->_parse_throwaway_comments();
      }
      return if $self->eos;
  
      if ($self->lines->[0] =~ /^---(\s|$)/) {
          $self->done(1);
          return;
      }
      if ($type == LEAF and
          $self->lines->[0] =~ /^ {$offset}(.*)$/
         ) {
          $self->indent($offset);
          $self->content($1);
      }
      elsif ($self->lines->[0] =~ /^\s*$/) {
          $self->indent($offset);
          $self->content('');
      }
      else {
          $self->lines->[0] =~ /^( *)(\S.*)$/;
          while ($self->offset->[$level] > length($1)) {
              $level--;
          }
          $self->die('YAML_PARSE_ERR_INCONSISTENT_INDENTATION')
            if $self->offset->[$level] != length($1);
          $self->indent(length($1));
          $self->content($2);
      }
      $self->die('YAML_PARSE_ERR_INDENTATION')
        if $self->indent - $offset > 1;
  }
  
  #==============================================================================
  # Utility subroutines.
  #==============================================================================
  
  # Printable characters for escapes
  my %unescapes = (
     0 => "\x00",
     a => "\x07",
     t => "\x09",
     n => "\x0a",
     'v' => "\x0b", # Potential v-string error on 5.6.2 if not quoted
     f => "\x0c",
     r => "\x0d",
     e => "\x1b",
     '\\' => '\\',
    );
  
  # Transform all the backslash style escape characters to their literal meaning
  sub _unescape {
      my $self = shift;
      my ($node) = @_;
      $node =~ s/\\([never\\fart0]|x([0-9a-fA-F]{2}))/
                (length($1)>1)?pack("H2",$2):$unescapes{$1}/gex;
      return $node;
  }
  
  1;
  
  __END__
  
  =encoding UTF-8
  
  =head1 NAME
  
  YAML::Loader - YAML class for loading Perl objects to YAML
  
  =head1 SYNOPSIS
  
      use YAML::Loader;
      my $loader = YAML::Loader->new;
      my $hash = $loader->load(<<'...');
      foo: bar
      ...
  
  =head1 DESCRIPTION
  
  YAML::Loader is the module that YAML.pm used to deserialize YAML to Perl
  objects. It is fully object oriented and usable on its own.
  
  =head1 AUTHOR
  
  Ingy döt Net <ingy@cpan.org>
  
  =head1 COPYRIGHT
  
  Copyright (c) 2006, 2011-2013. Ingy döt Net. All rights reserved.
  
  This program is free software; you can redistribute it and/or modify it
  under the same terms as Perl itself.
  
  See L<http://www.perl.com/perl/misc/Artistic.html>
  
  =cut
YAML_LOADER

$fatpacked{"YAML/Loader/Base.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'YAML_LOADER_BASE';
  package YAML::Loader::Base;
  use YAML::Mo;
  
  our $VERSION = '0.88';
  
  has load_code     => default => sub {0};
  has stream        => default => sub {''};
  has document      => default => sub {0};
  has line          => default => sub {0};
  has documents     => default => sub {[]};
  has lines         => default => sub {[]};
  has eos           => default => sub {0};
  has done          => default => sub {0};
  has anchor2node   => default => sub {{}};
  has level         => default => sub {0};
  has offset        => default => sub {[]};
  has preface       => default => sub {''};
  has content       => default => sub {''};
  has indent        => default => sub {0};
  has major_version => default => sub {0};
  has minor_version => default => sub {0};
  has inline        => default => sub {''};
  
  sub set_global_options {
      my $self = shift;
      $self->load_code($YAML::LoadCode || $YAML::UseCode)
        if defined $YAML::LoadCode or defined $YAML::UseCode;
  }
  
  sub load {
      die 'load() not implemented in this class.';
  }
  
  1;
  
  __END__
  
  =encoding UTF-8
  
  =head1 NAME
  
  YAML::Loader::Base - Base class for YAML Loader classes
  
  =head1 SYNOPSIS
  
      package YAML::Loader::Something;
      use YAML::Loader::Base -base;
  
  =head1 DESCRIPTION
  
  YAML::Loader::Base is a base class for creating YAML loader classes.
  
  =head1 AUTHOR
  
  Ingy döt Net <ingy@cpan.org>
  
  =head1 COPYRIGHT
  
  Copyright (c) 2006, 2011-2013. Ingy döt Net. All rights reserved.
  
  This program is free software; you can redistribute it and/or modify it
  under the same terms as Perl itself.
  
  See L<http://www.perl.com/perl/misc/Artistic.html>
  
  =cut
YAML_LOADER_BASE

$fatpacked{"YAML/Marshall.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'YAML_MARSHALL';
  use strict;
  use warnings;
  package YAML::Marshall;
  
  our $VERSION = '0.88';
  
  use YAML::Node ();
  
  sub import {
      my $class = shift;
      no strict 'refs';
      my $package = caller;
      unless (grep { $_ eq $class} @{$package . '::ISA'}) {
          push @{$package . '::ISA'}, $class;
      }
  
      my $tag = shift;
      if ( $tag ) {
          no warnings 'once';
          $YAML::TagClass->{$tag} = $package;
          ${$package . "::YamlTag"} = $tag;
      }
  }
  
  sub yaml_dump {
      my $self = shift;
      no strict 'refs';
      my $tag = ${ref($self) . "::YamlTag"} || 'perl/' . ref($self);
      $self->yaml_node($self, $tag);
  }
  
  sub yaml_load {
      my ($class, $node) = @_;
      if (my $ynode = $class->yaml_ynode($node)) {
          $node = $ynode->{NODE};
      }
      bless $node, $class;
  }
  
  sub yaml_node {
      shift;
      YAML::Node->new(@_);
  }
  
  sub yaml_ynode {
      shift;
      YAML::Node::ynode(@_);
  }
  
  1;
  
  __END__
  
  =encoding UTF-8
  
  =head1 NAME
  
  YAML::Marshall - YAML marshalling class you can mixin to your classes
  
  =head1 SYNOPSIS
  
      package Bar;
      use Foo -base;
      use YAML::Marshall -mixin;
  
  =head1 DESCRIPTION
  
  For classes that want to handle their own YAML serialization.
  
  =head1 AUTHOR
  
  Ingy döt Net <ingy@cpan.org>
  
  =head1 COPYRIGHT
  
  Copyright (c) 2006, 2011-2013. Ingy döt Net. All rights reserved.
  
  This program is free software; you can redistribute it and/or modify it
  under the same terms as Perl itself.
  
  See L<http://www.perl.com/perl/misc/Artistic.html>
  
  =cut
YAML_MARSHALL

$fatpacked{"YAML/Mo.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'YAML_MO';
  package YAML::Mo; $VERSION = '0.88';
  # use Mo qw[builder default import];
  #   The following line of code was produced from the previous line by
  #   Mo::Inline version 0.31
  no warnings;my$M=__PACKAGE__.'::';*{$M.Object::new}=sub{bless{@_[1..$#_]},$_[0]};*{$M.import}=sub{import warnings;$^H|=1538;my($P,%e,%o)=caller.'::';shift;eval"no Mo::$_",&{$M.$_.::e}($P,\%e,\%o,\@_)for@_;return if$e{M};%e=(extends,sub{eval"no $_[0]()";@{$P.ISA}=$_[0]},has,sub{my$n=shift;my$m=sub{$#_?$_[0]{$n}=$_[1]:$_[0]{$n}};$m=$o{$_}->($m,$n,@_)for sort keys%o;*{$P.$n}=$m},%e,);*{$P.$_}=$e{$_}for keys%e;@{$P.ISA}=$M.Object};*{$M.'builder::e'}=sub{my($P,$e,$o)=@_;$o->{builder}=sub{my($m,$n,%a)=@_;my$b=$a{builder}or return$m;sub{$#_?$m->(@_):!exists$_[0]{$n}?$_[0]{$n}=$_[0]->$b:$m->(@_)}}};*{$M.'default::e'}=sub{my($P,$e,$o)=@_;$o->{default}=sub{my($m,$n,%a)=@_;$a{default}or return$m;sub{$#_?$m->(@_):!exists$_[0]{$n}?$_[0]{$n}=$a{default}->(@_):$m->(@_)}}};my$i=\&import;*{$M.import}=sub{(@_==2 and not $_[1])?pop@_:@_==1?push@_,grep!/import/,@f:();goto&$i};@f=qw[builder default import];use strict;use warnings;
  
  our $DumperModule = 'Data::Dumper';
  
  my ($_new_error, $_info, $_scalar_info);
  
  no strict 'refs';
  *{$M.'Object::die'} = sub {
      my $self = shift;
      my $error = $self->$_new_error(@_);
      $error->type('Error');
      Carp::croak($error->format_message);
  };
  
  *{$M.'Object::warn'} = sub {
      my $self = shift;
      return unless $^W;
      my $error = $self->$_new_error(@_);
      $error->type('Warning');
      Carp::cluck($error->format_message);
  };
  
  # This code needs to be refactored to be simpler and more precise, and no,
  # Scalar::Util doesn't DWIM.
  #
  # Can't handle:
  # * blessed regexp
  *{$M.'Object::node_info'} = sub {
      my $self = shift;
      my $stringify = $_[1] || 0;
      my ($class, $type, $id) =
          ref($_[0])
          ? $stringify
            ? &$_info("$_[0]")
            : do {
                require overload;
                my @info = &$_info(overload::StrVal($_[0]));
                if (ref($_[0]) eq 'Regexp') {
                    @info[0, 1] = (undef, 'REGEXP');
                }
                @info;
            }
          : &$_scalar_info($_[0]);
      ($class, $type, $id) = &$_scalar_info("$_[0]")
          unless $id;
      return wantarray ? ($class, $type, $id) : $id;
  };
  
  #-------------------------------------------------------------------------------
  $_info = sub {
      return (($_[0]) =~ qr{^(?:(.*)\=)?([^=]*)\(([^\(]*)\)$}o);
  };
  
  $_scalar_info = sub {
      my $id = 'undef';
      if (defined $_[0]) {
          \$_[0] =~ /\((\w+)\)$/o or CORE::die();
          $id = "$1-S";
      }
      return (undef, undef, $id);
  };
  
  $_new_error = sub {
      require Carp;
      my $self = shift;
      require YAML::Error;
  
      my $code = shift || 'unknown error';
      my $error = YAML::Error->new(code => $code);
      $error->line($self->line) if $self->can('line');
      $error->document($self->document) if $self->can('document');
      $error->arguments([@_]);
      return $error;
  };
  
  1;
YAML_MO

$fatpacked{"YAML/Node.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'YAML_NODE';
  use strict;
  use warnings;
  package YAML::Node;
  
  our $VERSION = '0.88';
  
  use YAML::Tag;
  require YAML::Mo;
  
  use Exporter;
  our @ISA     = qw(Exporter YAML::Mo::Object);
  our @EXPORT  = qw(ynode);
  
  sub ynode {
      my $self;
      if (ref($_[0]) eq 'HASH') {
  	$self = tied(%{$_[0]});
      }
      elsif (ref($_[0]) eq 'ARRAY') {
  	$self = tied(@{$_[0]});
      }
      elsif (ref(\$_[0]) eq 'GLOB') {
  	$self = tied(*{$_[0]});
      }
      else {
  	$self = tied($_[0]);
      }
      return (ref($self) =~ /^yaml_/) ? $self : undef;
  }
  
  sub new {
      my ($class, $node, $tag) = @_;
      my $self;
      $self->{NODE} = $node;
      my (undef, $type) = YAML::Mo::Object->node_info($node);
      $self->{KIND} = (not defined $type) ? 'scalar' :
                      ($type eq 'ARRAY') ? 'sequence' :
  		    ($type eq 'HASH') ? 'mapping' :
  		    $class->die("Can't create YAML::Node from '$type'");
      tag($self, ($tag || ''));
      if ($self->{KIND} eq 'scalar') {
  	yaml_scalar->new($self, $_[1]);
  	return \ $_[1];
      }
      my $package = "yaml_" . $self->{KIND};
      $package->new($self)
  }
  
  sub node { $_->{NODE} }
  sub kind { $_->{KIND} }
  sub tag {
      my ($self, $value) = @_;
      if (defined $value) {
         	$self->{TAG} = YAML::Tag->new($value);
  	return $self;
      }
      else {
         return $self->{TAG};
      }
  }
  sub keys {
      my ($self, $value) = @_;
      if (defined $value) {
         	$self->{KEYS} = $value;
  	return $self;
      }
      else {
         return $self->{KEYS};
      }
  }
  
  #==============================================================================
  package yaml_scalar;
  
  @yaml_scalar::ISA = qw(YAML::Node);
  
  sub new {
      my ($class, $self) = @_;
      tie $_[2], $class, $self;
  }
  
  sub TIESCALAR {
      my ($class, $self) = @_;
      bless $self, $class;
      $self
  }
  
  sub FETCH {
      my ($self) = @_;
      $self->{NODE}
  }
  
  sub STORE {
      my ($self, $value) = @_;
      $self->{NODE} = $value
  }
  
  #==============================================================================
  package yaml_sequence;
  
  @yaml_sequence::ISA = qw(YAML::Node);
  
  sub new {
      my ($class, $self) = @_;
      my $new;
      tie @$new, $class, $self;
      $new
  }
  
  sub TIEARRAY {
      my ($class, $self) = @_;
      bless $self, $class
  }
  
  sub FETCHSIZE {
      my ($self) = @_;
      scalar @{$self->{NODE}};
  }
  
  sub FETCH {
      my ($self, $index) = @_;
      $self->{NODE}[$index]
  }
  
  sub STORE {
      my ($self, $index, $value) = @_;
      $self->{NODE}[$index] = $value
  }
  
  sub undone {
      die "Not implemented yet"; # XXX
  }
  
  *STORESIZE = *POP = *PUSH = *SHIFT = *UNSHIFT = *SPLICE = *DELETE = *EXISTS =
  *STORESIZE = *POP = *PUSH = *SHIFT = *UNSHIFT = *SPLICE = *DELETE = *EXISTS =
  *undone; # XXX Must implement before release
  
  #==============================================================================
  package yaml_mapping;
  
  @yaml_mapping::ISA = qw(YAML::Node);
  
  sub new {
      my ($class, $self) = @_;
      @{$self->{KEYS}} = sort keys %{$self->{NODE}};
      my $new;
      tie %$new, $class, $self;
      $new
  }
  
  sub TIEHASH {
      my ($class, $self) = @_;
      bless $self, $class
  }
  
  sub FETCH {
      my ($self, $key) = @_;
      if (exists $self->{NODE}{$key}) {
  	return (grep {$_ eq $key} @{$self->{KEYS}})
  	       ? $self->{NODE}{$key} : undef;
      }
      return $self->{HASH}{$key};
  }
  
  sub STORE {
      my ($self, $key, $value) = @_;
      if (exists $self->{NODE}{$key}) {
  	$self->{NODE}{$key} = $value;
      }
      elsif (exists $self->{HASH}{$key}) {
  	$self->{HASH}{$key} = $value;
      }
      else {
  	if (not grep {$_ eq $key} @{$self->{KEYS}}) {
  	    push(@{$self->{KEYS}}, $key);
  	}
  	$self->{HASH}{$key} = $value;
      }
      $value
  }
  
  sub DELETE {
      my ($self, $key) = @_;
      my $return;
      if (exists $self->{NODE}{$key}) {
  	$return = $self->{NODE}{$key};
      }
      elsif (exists $self->{HASH}{$key}) {
  	$return = delete $self->{NODE}{$key};
      }
      for (my $i = 0; $i < @{$self->{KEYS}}; $i++) {
  	if ($self->{KEYS}[$i] eq $key) {
  	    splice(@{$self->{KEYS}}, $i, 1);
  	}
      }
      return $return;
  }
  
  sub CLEAR {
      my ($self) = @_;
      @{$self->{KEYS}} = ();
      %{$self->{HASH}} = ();
  }
  
  sub FIRSTKEY {
      my ($self) = @_;
      $self->{ITER} = 0;
      $self->{KEYS}[0]
  }
  
  sub NEXTKEY {
      my ($self) = @_;
      $self->{KEYS}[++$self->{ITER}]
  }
  
  sub EXISTS {
      my ($self, $key) = @_;
      exists $self->{NODE}{$key}
  }
  
  1;
  
  __END__
  
  =encoding UTF-8
  
  =head1 NAME
  
  YAML::Node - A generic data node that encapsulates YAML information
  
  =head1 SYNOPSIS
  
      use YAML;
      use YAML::Node;
  
      my $ynode = YAML::Node->new({}, 'ingerson.com/fruit');
      %$ynode = qw(orange orange apple red grape green);
      print Dump $ynode;
  
  yields:
  
      --- !ingerson.com/fruit
      orange: orange
      apple: red
      grape: green
  
  =head1 DESCRIPTION
  
  A generic node in YAML is similar to a plain hash, array, or scalar node
  in Perl except that it must also keep track of its type. The type is a
  URI called the YAML type tag.
  
  YAML::Node is a class for generating and manipulating these containers.
  A YAML node (or ynode) is a tied hash, array or scalar. In most ways it
  behaves just like the plain thing. But you can assign and retrieve and
  YAML type tag URI to it. For the hash flavor, you can also assign the
  order that the keys will be retrieved in. By default a ynode will offer
  its keys in the same order that they were assigned.
  
  YAML::Node has a class method call new() that will return a ynode. You
  pass it a regular node and an optional type tag. After that you can
  use it like a normal Perl node, but when you YAML::Dump it, the magical
  properties will be honored.
  
  This is how you can control the sort order of hash keys during a YAML
  serialization. By default, YAML sorts keys alphabetically. But notice
  in the above example that the keys were Dumped in the same order they
  were assigned.
  
  YAML::Node exports a function called ynode(). This function returns the tied object so that you can call special methods on it like ->keys().
  
  keys() works like this:
  
      use YAML;
      use YAML::Node;
  
      %$node = qw(orange orange apple red grape green);
      $ynode = YAML::Node->new($node);
      ynode($ynode)->keys(['grape', 'apple']);
      print Dump $ynode;
  
  produces:
  
      ---
      grape: green
      apple: red
  
  It tells the ynode which keys and what order to use.
  
  ynodes will play a very important role in how programs use YAML. They
  are the foundation of how a Perl class can marshall the Loading and
  Dumping of its objects.
  
  The upcoming versions of YAML.pm will have much more information on this.
  
  =head1 AUTHOR
  
  Ingy döt Net <ingy@cpan.org>
  
  =head1 COPYRIGHT
  
  Copyright (c) 2006, 2011-2013. Ingy döt Net. All rights reserved.
  
  Copyright (c) 2002. Brian Ingerson. All rights reserved.
  
  This program is free software; you can redistribute it and/or modify it
  under the same terms as Perl itself.
  
  See L<http://www.perl.com/perl/misc/Artistic.html>
  
  =cut
YAML_NODE

$fatpacked{"YAML/Tag.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'YAML_TAG';
  use strict;
  use warnings;
  package YAML::Tag;
  
  our $VERSION = '0.88';
  
  use overload '""' => sub { ${$_[0]} };
  
  sub new {
      my ($class, $self) = @_;
      bless \$self, $class
  }
  
  sub short {
      ${$_[0]}
  }
  
  sub canonical {
      ${$_[0]}
  }
  
  1;
  
  __END__
  
  =encoding UTF-8
  
  =head1 NAME
  
  YAML::Tag - Tag URI object class for YAML
  
  =head1 SYNOPSIS
  
      use YAML::Tag;
  
  =head1 DESCRIPTION
  
  Used by YAML::Node.
  
  =head1 AUTHOR
  
  Ingy döt Net <ingy@cpan.org>
  
  =head1 COPYRIGHT
  
  Copyright (c) 2006, 2011-2013. Ingy döt Net. All rights reserved.
  
  This program is free software; you can redistribute it and/or modify it
  under the same terms as Perl itself.
  
  See L<http://www.perl.com/perl/misc/Artistic.html>
  
  =cut
YAML_TAG

$fatpacked{"YAML/Types.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'YAML_TYPES';
  package YAML::Types;
  use YAML::Mo;
  
  our $VERSION = '0.88';
  
  use YAML::Node;
  
  # XXX These classes and their APIs could still use some refactoring,
  # but at least they work for now.
  #-------------------------------------------------------------------------------
  package YAML::Type::blessed;
  use YAML::Mo; # XXX
  
  sub yaml_dump {
      my $self = shift;
      my ($value) = @_;
      my ($class, $type) = YAML::Mo::Object->node_info($value);
      no strict 'refs';
      my $kind = lc($type) . ':';
      my $tag = ${$class . '::ClassTag'} ||
                "!perl/$kind$class";
      if ($type eq 'REF') {
          YAML::Node->new(
              {(&YAML::VALUE, ${$_[0]})}, $tag
          );
      }
      elsif ($type eq 'SCALAR') {
          $_[1] = $$value;
          YAML::Node->new($_[1], $tag);
      } else {
          YAML::Node->new($value, $tag);
      }
  }
  
  #-------------------------------------------------------------------------------
  package YAML::Type::undef;
  
  sub yaml_dump {
      my $self = shift;
  }
  
  sub yaml_load {
      my $self = shift;
  }
  
  #-------------------------------------------------------------------------------
  package YAML::Type::glob;
  
  sub yaml_dump {
      my $self = shift;
      my $ynode = YAML::Node->new({}, '!perl/glob:');
      for my $type (qw(PACKAGE NAME SCALAR ARRAY HASH CODE IO)) {
          my $value = *{$_[0]}{$type};
          $value = $$value if $type eq 'SCALAR';
          if (defined $value) {
              if ($type eq 'IO') {
                  my @stats = qw(device inode mode links uid gid rdev size
                                 atime mtime ctime blksize blocks);
                  undef $value;
                  $value->{stat} = YAML::Node->new({});
                  if ($value->{fileno} = fileno(*{$_[0]})) {
                      local $^W;
                      map {$value->{stat}{shift @stats} = $_} stat(*{$_[0]});
                      $value->{tell} = tell(*{$_[0]});
                  }
              }
              $ynode->{$type} = $value;
          }
      }
      return $ynode;
  }
  
  sub yaml_load {
      my $self = shift;
      my ($node, $class, $loader) = @_;
      my ($name, $package);
      if (defined $node->{NAME}) {
          $name = $node->{NAME};
          delete $node->{NAME};
      }
      else {
          $loader->warn('YAML_LOAD_WARN_GLOB_NAME');
          return undef;
      }
      if (defined $node->{PACKAGE}) {
          $package = $node->{PACKAGE};
          delete $node->{PACKAGE};
      }
      else {
          $package = 'main';
      }
      no strict 'refs';
      if (exists $node->{SCALAR}) {
          *{"${package}::$name"} = \$node->{SCALAR};
          delete $node->{SCALAR};
      }
      for my $elem (qw(ARRAY HASH CODE IO)) {
          if (exists $node->{$elem}) {
              if ($elem eq 'IO') {
                  $loader->warn('YAML_LOAD_WARN_GLOB_IO');
                  delete $node->{IO};
                  next;
              }
              *{"${package}::$name"} = $node->{$elem};
              delete $node->{$elem};
          }
      }
      for my $elem (sort keys %$node) {
          $loader->warn('YAML_LOAD_WARN_BAD_GLOB_ELEM', $elem);
      }
      return *{"${package}::$name"};
  }
  
  #-------------------------------------------------------------------------------
  package YAML::Type::code;
  
  my $dummy_warned = 0;
  my $default = '{ "DUMMY" }';
  
  sub yaml_dump {
      my $self = shift;
      my $code;
      my ($dumpflag, $value) = @_;
      my ($class, $type) = YAML::Mo::Object->node_info($value);
      my $tag = "!perl/code";
      $tag .= ":$class" if defined $class;
      if (not $dumpflag) {
          $code = $default;
      }
      else {
          bless $value, "CODE" if $class;
          eval { use B::Deparse };
          return if $@;
          my $deparse = B::Deparse->new();
          eval {
              local $^W = 0;
              $code = $deparse->coderef2text($value);
          };
          if ($@) {
              warn YAML::YAML_DUMP_WARN_DEPARSE_FAILED() if $^W;
              $code = $default;
          }
          bless $value, $class if $class;
          chomp $code;
          $code .= "\n";
      }
      $_[2] = $code;
      YAML::Node->new($_[2], $tag);
  }
  
  sub yaml_load {
      my $self = shift;
      my ($node, $class, $loader) = @_;
      if ($loader->load_code) {
          my $code = eval "package main; sub $node";
          if ($@) {
              $loader->warn('YAML_LOAD_WARN_PARSE_CODE', $@);
              return sub {};
          }
          else {
              CORE::bless $code, $class if $class;
              return $code;
          }
      }
      else {
          return CORE::bless sub {}, $class if $class;
          return sub {};
      }
  }
  
  #-------------------------------------------------------------------------------
  package YAML::Type::ref;
  
  sub yaml_dump {
      my $self = shift;
      YAML::Node->new({(&YAML::VALUE, ${$_[0]})}, '!perl/ref')
  }
  
  sub yaml_load {
      my $self = shift;
      my ($node, $class, $loader) = @_;
      $loader->die('YAML_LOAD_ERR_NO_DEFAULT_VALUE', 'ptr')
        unless exists $node->{&YAML::VALUE};
      return \$node->{&YAML::VALUE};
  }
  
  #-------------------------------------------------------------------------------
  package YAML::Type::regexp;
  
  # XXX Be sure to handle blessed regexps (if possible)
  sub yaml_dump {
      die "YAML::Type::regexp::yaml_dump not currently implemented";
  }
  
  use constant _QR_TYPES => {
      '' => sub { qr{$_[0]} },
      x => sub { qr{$_[0]}x },
      i => sub { qr{$_[0]}i },
      s => sub { qr{$_[0]}s },
      m => sub { qr{$_[0]}m },
      ix => sub { qr{$_[0]}ix },
      sx => sub { qr{$_[0]}sx },
      mx => sub { qr{$_[0]}mx },
      si => sub { qr{$_[0]}si },
      mi => sub { qr{$_[0]}mi },
      ms => sub { qr{$_[0]}sm },
      six => sub { qr{$_[0]}six },
      mix => sub { qr{$_[0]}mix },
      msx => sub { qr{$_[0]}msx },
      msi => sub { qr{$_[0]}msi },
      msix => sub { qr{$_[0]}msix },
  };
  
  sub yaml_load {
      my $self = shift;
      my ($node, $class) = @_;
      return qr{$node} unless $node =~ /^\(\?([\^\-xism]*):(.*)\)\z/s;
      my ($flags, $re) = ($1, $2);
      $flags =~ s/-.*//;
      $flags =~ s/^\^//;
      my $sub = _QR_TYPES->{$flags} || sub { qr{$_[0]} };
      my $qr = &$sub($re);
      bless $qr, $class if length $class;
      return $qr;
  }
  
  1;
  
  __END__
  
  =encoding UTF-8
  
  =head1 NAME
  
  YAML::Types - Marshall Perl internal data types to/from YAML
  
  =head1 SYNOPSIS
  
      $::foo = 42;
      print YAML::Dump(*::foo);
  
      print YAML::Dump(qr{match me});
  
  =head1 DESCRIPTION
  
  This module has the helper classes for transferring objects,
  subroutines, references, globs, regexps and file handles to and
  from YAML.
  
  =head1 AUTHOR
  
  Ingy döt Net <ingy@cpan.org>
  
  =head1 COPYRIGHT
  
  Copyright (c) 2006, 2011-2013. Ingy döt Net. All rights reserved.
  
  This program is free software; you can redistribute it and/or modify it
  under the same terms as Perl itself.
  
  See L<http://www.perl.com/perl/misc/Artistic.html>
  
  =cut
YAML_TYPES

$fatpacked{"cPanel/PublicAPI.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'CPANEL_PUBLICAPI';
  package cPanel::PublicAPI;
  
  # Copyright (c) 2011, cPanel, Inc.
  # All rights reserved.
  # http://cpanel.net
  #
  # Redistribution and use in source and binary forms, with or without
  # modification, are permitted provided that the following conditions are met:
  #    * Redistributions of source code must retain the above copyright
  #       notice, this list of conditions and the following disclaimer.
  #     * Redistributions in binary form must reproduce the above copyright
  #       notice, this list of conditions and the following disclaimer in the
  #       documentation and/or other materials provided with the distribution.
  #     * Neither the name of cPanel, Inc. nor the
  #       names of its contributors may be used to endorse or promote products
  #       derived from this software without specific prior written permission.
  #
  # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  # DISCLAIMED. IN NO EVENT SHALL  BE LIABLE FOR ANY
  # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  
  our $VERSION = 1.002;
  
  use strict;
  use Socket           ();
  use Carp             ();
  use MIME::Base64     ();
  use IO::Socket::INET ();
  
  my ( $whm_sock, $whm_sock_host, $loaded_ssl );
  our %CFG;
  
  my %PORT_DB = (
      'whostmgr' => {
          'ssl'       => 2087,
          'plaintext' => 2086,
      },
      'cpanel' => {
          'ssl'       => 2083,
          'plaintext' => 2082,
      },
      'webmail' => {
          'ssl'       => 2096,
          'plaintext' => 2095,
      },
  );
  
  sub new {
      my ( $class, %OPTS ) = @_;
  
      my $self = {};
      bless( $self, $class );
  
      $self->{'debug'}   = $OPTS{'debug'}   || 0;
      $self->{'timeout'} = $OPTS{'timeout'} || 300;
  
      if ( exists $OPTS{'usessl'} ) {
          $self->{'usessl'} = $OPTS{'usessl'};
      }
      else {
          $self->{'usessl'} = 1;
      }
      if ( exists $OPTS{'keepalive'} ) {
          $self->{'keepalive'} = int $OPTS{'keepalive'};
      }
      else {
          $self->{'keepalive'} = 0;
      }
  
      if ( exists $OPTS{'ip'} ) {
          $self->{'ip'} = $OPTS{'ip'};
      }
      elsif ( exists $OPTS{'host'} ) {
          $self->{'host'} = $OPTS{'host'};
      }
      else {
          $self->{'ip'} = '127.0.0.1';
      }
  
      if ( exists $OPTS{'error_log'} && $OPTS{'error_log'} ne 'STDERR' ) {
          if ( !open( $self->{'error_fh'}, '>>', $OPTS{'error_log'} ) ) {
              print STDERR "Unable to open $OPTS{'error_log'} for writing, defaulting to STDERR for error logging: $@\n";
              $self->{'error_fh'} = \*STDERR;
          }
      }
      else {
          $self->{'error_fh'} = \*STDERR;
      }
  
      if ( $OPTS{'user'} ) {
          $self->{'user'} = $OPTS{'user'};
          $self->debug("Using user param from object creation") if $self->{'debug'};
      }
      else {
          $self->{'user'} = exists $INC{'cPanel/PwCache.pm'} ? ( cPanel::PwCache::getpwuid($>) )[0] : ( getpwuid($>) )[0];
          $self->debug("Setting user based on current uid ($>)") if $self->{'debug'};
      }
  
      if ( ( !exists( $OPTS{'pass'} ) || $OPTS{'pass'} eq '' ) && ( !exists $OPTS{'accesshash'} || $OPTS{'accesshash'} eq '' ) ) {
          my $homedir = exists $INC{'cPanel/PwCache.pm'} ? ( cPanel::PwCache::getpwuid($>) )[7] : ( getpwuid($>) )[7];
          $self->debug("Attempting to detect correct authentication credentials") if $self->{'debug'};
  
          if ( -e $homedir . '/.accesshash' ) {
              local $/;
              if ( open( my $hash_fh, '<', $homedir . '/.accesshash' ) ) {
                  $self->{'accesshash'} = readline($hash_fh);
                  $self->{'accesshash'} =~ s/[\r\n]+//g;
                  close($hash_fh);
                  $self->debug("Got access hash from $homedir/.accesshash") if $self->{'debug'};
              }
              else {
                  $self->debug("Failed to fetch access hash from $homedir/.accesshash") if $self->{'debug'};
              }
          }
          elsif ( exists $ENV{'REMOTE_PASSWORD'} && $ENV{'REMOTE_PASSWORD'} && $ENV{'REMOTE_PASSWORD'} ne '__HIDDEN__' && exists $ENV{'SERVER_SOFTWARE'} && $ENV{'SERVER_SOFTWARE'} =~ /^cpsrvd/ ) {
              $self->debug("Got user password from the REMOTE_PASSWORD environment variables.") if $self->{'debug'};
              $OPTS{'pass'} = $ENV{'REMOTE_PASSWORD'};
          }
  
          else {
              Carp::confess('pass or access hash is a required parameter');
          }
      }
      elsif ( $OPTS{'pass'} ) {
          $self->{'pass'} = $OPTS{'pass'};
          $self->debug("Using pass param from object creation") if $self->{'debug'};
      }
      else {
          $OPTS{'accesshash'} =~ s/[\r\n]//;
          $self->{'accesshash'} = $OPTS{'accesshash'};
          $self->debug("Using accesshash param from object creation") if $self->{'debug'};
      }
  
      return $self;
  }
  
  sub set_debug {
      my $self = shift;
      $self->{'debug'} = int shift;
  }
  
  sub user {
      my $self = shift;
      $self->{'user'} = shift;
  }
  
  sub pass {
      my $self = shift;
      $self->{'pass'} = shift;
      delete $self->{'accesshash'};
  }
  
  sub accesshash {
      my $self = shift;
      $self->{'accesshash'} = shift;
      delete $self->{'pass'};
  }
  
  sub whm_api {
      my ( $self, $call, $formdata, $format ) = @_;
      $self->_init_serializer() if !exists $cPanel::PublicAPI::CFG{'serializer'};
      if ( !defined $call || $call eq '' ) {
          $self->error("A call was not defined when called cPanel::PublicAPI::whm_api_request()");
      }
      if ( defined $format && $format ne 'xml' && $format ne 'json' && $format ne 'ref' ) {
          $self->error("cPanel::PublicAPI::whm_api_request() was called with an invalid data format, the only valid format are 'json', 'ref' or 'xml'");
      }
      my $query_format;
      if ( defined $format ) {
          $query_format = $format;
      }
      else {
          $query_format = $CFG{'serializer'};
      }
  
      my $uri = "/$query_format-api/$call";
  
      my ( $status, $statusmsg, $data ) = $self->api_request( 'whostmgr', $uri, 'POST', $formdata );
  
      if ( defined $format && ( $format eq 'json' || $format eq 'xml' ) ) {
          return $$data;
      }
      else {
          my $parsed_data;
          eval { $parsed_data = $CFG{'serializer_can_deref'} ? $CFG{'api_serializer_obj'}->($data) : $CFG{'api_serializer_obj'}->($$data); };
          if ( !ref $parsed_data ) {
              $self->error("There was an issue with parsing the following response from cPanel or WHM: [data=[$$data]]");
              die $self->{'error'};
          }
          if (
              ( exists $parsed_data->{'error'} && $parsed_data->{'error'} =~ /Unknown App Requested/ ) ||                              # xml-api v0 version
              ( exists $parsed_data->{'metadata'}->{'reason'} && $parsed_data->{'metadata'}->{'reason'} =~ /Unknown app requested/ )
            ) {                                                                                                                        # xml-api v1 version
              $self->error("cPanel::PublicAPI::whm_api was called with the invalid API call of: $call.");
              return;
          }
          return $parsed_data;
      }
  }
  
  sub api_request {
      my ( $self, $service, $uri, $method, $formdata, $headers ) = @_;
  
      $self->{'error'} = 0;
  
      $formdata ||= '';
      $method   ||= 'GET';
      $headers  ||= '';
  
      $self->debug("api_request: ( $self, $service, $uri, $method, $formdata, $headers )") if $self->{'debug'};
  
      $self->_init() if !exists $CFG{'init'};
  
      $self->{'error'} = undef;
      my $timeout = $self->{'timeout'} || 300;
  
      my $authstr;
      if ( exists $self->{'accesshash'} ) {
          $self->{'accesshash'} =~ s/[\r\n]//g;
          $authstr = 'WHM ' . $self->{'user'} . ':' . $self->{'accesshash'};
      }
      elsif ( exists $self->{'pass'} ) {
          $authstr = 'Basic ' . MIME::Base64::encode_base64( $self->{'user'} . ':' . $self->{'pass'} );
          $authstr =~ s/[\r\n]//g;
      }
      else {
          die 'No user name or password set, cannot execute query.';
      }
  
      my $orig_alarm = 0;
      my $page;
      my $port;
  
      if ( $self->{'usessl'} ) {
          if ( !$loaded_ssl ) {
              eval { require IO::Socket::SSL; };
              if ($@) {
                  die "Failed to load IO::Socket::SSL: $@.";
              }
              Net::SSLeay::load_error_strings();
              Net::SSLeay::OpenSSL_add_ssl_algorithms();
              Net::SSLeay::ERR_load_crypto_strings();
              Net::SSLeay::randomize();
              IO::Socket::SSL->import('inet4');    # see case 16674
              $loaded_ssl = 1;
          }
          $port = $service =~ /^\d+$/ ? $service : $PORT_DB{$service}{'ssl'};
      }
      else {
          $port = $service =~ /^\d+$/ ? $service : $PORT_DB{$service}{'plaintext'};
      }
  
      $self->debug("Found port for service $service to be $port (usessl=$self->{'usessl'})") if $self->{'debug'};
  
      eval {
          if ( !$self->{'user'} ) {
              $self->error("You must specify a user to login as.");
              die $self->{'error'};    #exit eval
          }
          my $remote_server = $self->{'ip'}   || $self->{'host'};
          my $server_name   = $self->{'host'} || $self->{'ip'};
          if ( !$remote_server ) {
              $self->error("You must set a host to connect to.");
              die $self->{'error'};    #exit eval
          }
          $server_name =~ s/\s*//g;
          my $keepalive         = $self->{'keepalive'} ? 1 : 0;
          my $connection_string = $remote_server . ':' . $port;
          my $attempts          = 0;
          my $hassigpipe;
          my $finished_request = 0;
  
          local $SIG{'ALRM'} = sub {
              $self->error('Connection Timed Out');
              die $self->{'error'};
          };
          local $SIG{'PIPE'} = sub { $hassigpipe = 1; };
          $orig_alarm = alarm($timeout);
          while ( ++$attempts < 3 ) {
              $hassigpipe = 0;
              if ( !ref $whm_sock || !$whm_sock_host || $whm_sock_host != $connection_string ) {
                  close($whm_sock) if ref $whm_sock;
                  $whm_sock =
                    $self->{'usessl'}
                    ? IO::Socket::SSL->new(PeerAddr => $connection_string, SSL_verify_mode => 0x00)
                    : IO::Socket::INET->new($connection_string);
                  if ( !$whm_sock ) {
                      undef $whm_sock;
                      $self->error("Could not connect to $connection_string: $!");
                      die $self->{'error'};    #exit eval
                  }
                  else {
                      $whm_sock_host = $connection_string;
                  }
              }
              my $connection_type = ( $keepalive ? 'Keep-Alive' : 'Close' );
  
              $headers = $self->format_http_headers($headers) if ref $headers;
              if ( $method eq 'POST' || $method eq 'PUT' ) {
                  $formdata = $self->format_http_query($formdata) if ref $formdata;
                  print {$whm_sock} "$method $uri HTTP/1.1\r\nHost: $server_name\r\nConnection: $connection_type\r\n" . 'Content-Length: ' . length($formdata) . "\r\n" . "User-Agent: " . 'cPanel::PublicAPI (perl) ' . $VERSION . "\r\n" . "Authorization: $authstr\r\n$headers\r\n" . $formdata;
                  $self->debug( ( "$method $uri HTTP/1.1\r\nHost: $server_name\r\nConnection: $connection_type\r\n" . 'Content-Length: ' . length($formdata) . "\r\n" . "User-Agent: " . 'cPanel::PublicAPI (perl) ' . $VERSION . "\r\n" . "Authorization: $authstr\r\n$headers\r\n" . $formdata ) ) if $self->{'debug'};
              }
              else {
                  print {$whm_sock} "$method "
                    . ( $uri . '?' . ( ref $formdata ? join( '&', map { $CFG{'uri_encoder_func'}->($_) . '=' . $CFG{'uri_encoder_func'}->( $formdata->{$_} ) } keys %{$formdata} ) : $formdata ) )
                    . " HTTP/1.1\r\nHost: $server_name\r\nConnection: $connection_type\r\n"
                    . "User-Agent: "
                    . 'cPanel::PublicAPI (perl) '
                    . $VERSION . "\r\n"
                    . "Authorization: $authstr\r\n$headers\r\n";
  
                  $self->debug( "$method " . ( $uri . '?' . ( ref $formdata ? join( '&', map { $CFG{'uri_encoder_func'}->($_) . '=' . $CFG{'uri_encoder_func'}->( $formdata->{$_} ) } keys %{$formdata} ) : $formdata ) ) . " HTTP/1.1\r\nHost: $server_name\r\nConnection: $connection_type\r\n" . "User-Agent: " . 'cPanel::PublicAPI (perl) ' . $VERSION . "\r\n" . "Authorization: $authstr\r\n$headers\r\n" )
                    if $self->{'debug'};
  
              }
  
              if ($hassigpipe) { undef $whm_sock_host; next; }    # http spec says to reconnect
  
              my $inheaders  = 1;
              my $httpheader = readline($whm_sock);
  
              $self->debug("HTTP LINE[$httpheader]") if $self->{'debug'};
  
              if ( $hassigpipe || !$httpheader ) { undef $whm_sock_host; next; }    # http spec says to reconnect
  
              my %HEADERS;
              {
                  local $/ = "\r\n\r\n";
                  %HEADERS = map { ( lc $_->[0], substr( $_->[1], 0, 8190 ) ) }     # lc the header and truncate the value to 8190 bytes
                    map { [ ( split( /:\s*/, $_, 2 ) )[ 0, 1 ] ] }                  # split header into name, value - and place into an arrayref for the next map to alter
                    split( /\r?\n/, readline($whm_sock) );                          # split each header
              }
              if ( $self->{'debug'} ) {
                  foreach my $header ( keys %HEADERS ) {
                      $self->debug("HEADER[$header]=[$HEADERS{$header}]");
                  }
              }
              {
                  if ( exists $HEADERS{'transfer-encoding'} && $HEADERS{'transfer-encoding'} =~ /chunked/i ) {
                      $self->debug("READ TYPE=chunked") if $self->{'debug'};
                      local $/ = "\r\n";
                      my ( $size_to_read, $read_size, $read_buffer, $bytes_read );
                    CHUNKED_READ:
                      while (1) {
                          chomp( $read_size = readline($whm_sock) );
                          $size_to_read = hex($read_size) + 2;
  
                          #if ( $self->{'debug'} ) {
                          #    $self->debug("CHUNKED read_size=$read_size")               ;
                          #    $self->debug("REQUESTING_READ size_to_read=$size_to_read") ;
                          #}
                          while ($size_to_read) {
                              if ( !defined($read_size) || !( $bytes_read = read( $whm_sock, $read_buffer, $size_to_read ) ) ) {
  
                                  #$self->debug("FINSIHED READING CHUNKED DATA [$bytes_read]") if $self->{'debug'};
                                  last CHUNKED_READ;
                              }
                              $size_to_read -= $bytes_read;
  
                              #$self->debug("BYTES READ = [$bytes_read] (remaining in chunk $size_to_read)") if $self->{'debug'};
                              $page .=
                                  $size_to_read == 0 ? substr( $read_buffer, 0, -2 )
                                : $size_to_read == 1 ? substr( $read_buffer, 0, -1 )
                                :                      $read_buffer;
                          }
                          last if hex($read_size) == 0;
                      }
                      $keepalive = 0 if exists $HEADERS{'connection'} && $HEADERS{'connection'} =~ /close/i;
                  }
                  elsif ( defined $HEADERS{'content-length'} ) {
                      $self->debug("READ TYPE=content-length") if $self->{'debug'};
                      my $bytes_to_read = int $HEADERS{'content-length'};
                      my $bytes_read = read( $whm_sock, $page, $bytes_to_read ) if $bytes_to_read;
                      if ( $bytes_to_read && $bytes_read < $bytes_to_read ) {
                          $bytes_to_read -= $bytes_read;
                          my $page_buffer;
                          while ( $bytes_read = read( $whm_sock, $page_buffer, $bytes_to_read ) ) {
                              $bytes_to_read -= $bytes_read;
                              $page .= $page_buffer;
                              last if !$bytes_to_read;
                          }
                      }
                      $keepalive = 0 if exists $HEADERS{'connection'} && $HEADERS{'connection'} =~ /close/i;
                  }
                  else {
                      $self->debug("READ TYPE=close") if $self->{'debug'};
                      $keepalive = 0;
                      local $/;
                      $page = readline($whm_sock);    # read until we close ths socket
                  }
              }
  
              if ( $httpheader !~ m/^\S+\s+2/ ) {
                  $keepalive = 0;
                  $self->error("Server Error from $remote_server: ${httpheader}");
              }
  
              if ( !$keepalive ) {
                  close($whm_sock);
                  undef $whm_sock_host;
              }
  
              $finished_request = 1;
              last;
          }
  
          if ( !$finished_request && !$self->{'error'} ) {
              $self->error("The request could not be completed after the maximum attempts");
          }
  
      };
      if ( $self->{'debug'} && $@ ) {
          warn $@;
      }
  
      alarm($orig_alarm);    # Reset with parent's alarm value
  
      return ( $self->{'error'} ? 0 : 1, $self->{'error'}, \$page );
  }
  
  sub cpanel_api1_request {
      my ( $self, $service, $cfg, $formdata, $format ) = @_;
  
      my $query_format;
      if ( defined $format ) {
          $query_format = $format;
      }
      else {
          $query_format = $CFG{'serializer'};
      }
  
      $self->_init_serializer() if !exists $cPanel::PublicAPI::CFG{'serializer'};
      my $count = 0;
      if ( ref $formdata eq 'ARRAY' ) {
          $formdata = { map { ( 'arg-' . $count++ ) => $_ } @{$formdata} };
      }
      foreach my $cfg_item ( keys %{$cfg} ) {
          $formdata->{ 'cpanel_' . $query_format . 'api_' . $cfg_item } = $cfg->{$cfg_item};
      }
      $formdata->{ 'cpanel_' . $query_format . 'api_apiversion' } = 1;
  
      my ( $status, $statusmsg, $data ) = $self->api_request( $service, '/' . $query_format . '-api/cpanel', ( ( scalar keys %$formdata < 10 && _total_form_length( $formdata, 1024 ) < 1024 ) ? 'GET' : 'POST' ), $formdata );
      if ( defined $format && ( $format eq 'json' || $format eq 'xml' ) ) {
          return $$data;
      }
      else {
          my $parsed_data;
          eval { $parsed_data = $CFG{'serializer_can_deref'} ? $CFG{'api_serializer_obj'}->($data) : $CFG{'api_serializer_obj'}->($$data); };
          if ( !ref $parsed_data ) {
              $self->error("There was an issue with parsing the following response from cPanel or WHM:\n$$data");
              die $self->{'error'};
          }
          if ( exists $parsed_data->{'event'}->{'reason'} && $parsed_data->{'event'}->{'reason'} =~ /failed: Undefined subroutine/ ) {
              $self->error( "cPanel::PublicAPI::cpanel_api1_request was called with the invalid API1 call of: " . $parsed_data->{'module'} . '::' . $parsed_data->{'func'} );
              return;
          }
          return $parsed_data;
      }
  }
  
  sub cpanel_api2_request {
      my ( $self, $service, $cfg, $formdata, $format ) = @_;
      $self->_init_serializer() if !exists $cPanel::PublicAPI::CFG{'serializer'};
  
      my $query_format;
      if ( defined $format ) {
          $query_format = $format;
      }
      else {
          $query_format = $CFG{'serializer'};
      }
  
      foreach my $cfg_item ( keys %{$cfg} ) {
          $formdata->{ 'cpanel_' . $query_format . 'api_' . $cfg_item } = $cfg->{$cfg_item};
      }
      $formdata->{ 'cpanel_' . $query_format . 'api_apiversion' } = 2;
      my ( $status, $statusmsg, $data ) = $self->api_request( $service, '/' . $query_format . '-api/cpanel', ( ( scalar keys %$formdata < 10 && _total_form_length( $formdata, 1024 ) < 1024 ) ? 'GET' : 'POST' ), $formdata );
  
      if ( defined $format && ( $format eq 'json' || $format eq 'xml' ) ) {
          return $$data;
      }
      else {
          my $parsed_data;
          eval { $parsed_data = $CFG{'serializer_can_deref'} ? $CFG{'api_serializer_obj'}->($data) : $CFG{'api_serializer_obj'}->($$data); };
          if ( !ref $parsed_data ) {
              $self->error("There was an issue with parsing the following response from cPanel or WHM:\n$$data");
              die $self->{'error'};
          }
          if ( exists $parsed_data->{'cpanelresult'}->{'error'} && $parsed_data->{'cpanelresult'}->{'error'} =~ /Could not find function/ ) {    # xml-api v1 version
              $self->error( "cPanel::PublicAPI::cpanel_api2_request was called with the invalid API2 call of: " . $parsed_data->{'cpanelresult'}->{'module'} . '::' . $parsed_data->{'cpanelresult'}->{'func'} );
              return;
          }
          return $parsed_data;
      }
  }
  
  sub _total_form_length {
      my $data = shift;
      my $max  = shift;
      my $size = 0;
      foreach my $key ( keys %{$data} ) {
          return 1024 if ( ( $size += ( length($key) + 2 + length( $data->{$key} ) ) ) >= 1024 );
      }
      return $size;
  }
  
  sub _init_serializer {
      return if exists $CFG{'serializer'};
      my $self = shift;    #not required
      foreach my $serializer (
  
          #module, key (cpanel api uri), deserializer function, deserializer understands references
          [ 'JSON::Syck', 'json', \&JSON::Syck::Load,      0 ],
          [ 'JSON',       'json', \&JSON::decode_json,     0 ],
          [ 'JSON::XS',   'json', \&JSON::XS::decode_json, 0 ],
          [ 'JSON::PP',   'json', \&JSON::PP::decode_json, 0 ],
        ) {
          my $serializer_module = $serializer->[0];
          my $serializer_key    = $serializer->[1];
          $CFG{'api_serializer_obj'}   = $serializer->[2];
          $CFG{'serializer_can_deref'} = $serializer->[3];
          eval " require $serializer_module; ";
          if ( !$@ ) {
              $self->debug("loaded serializer: $serializer_module") if $self && ref $self && $self->{'debug'};
              $CFG{'serializer'}        = $CFG{'parser_key'}    = $serializer_key;
              $CFG{'serializer_module'} = $CFG{'parser_module'} = $serializer_module;
              last;
          }
          else {
              $self->debug("Failed to load serializer: $serializer_module: @_") if $self && ref $self && $self->{'debug'};
          }
      }
      if ($@) {
          Carp::confess("Unable to find a module capable of deserializing the api response.");
      }
  }
  
  sub _init {
      return if exists $CFG{'init'};
      my $self = shift;    #not required
      $CFG{'init'} = 1;
  
      # moved this over to a pattern to allow easy change of deps
      foreach my $encoder (
          [ 'cPanel/CPAN/URI/Escape.pm', \&cPanel::CPAN::URI::Escape::uri_escape ],
          [ 'URI/Escape.pm',             \&URI::Escape::uri_escape ],
        ) {
          my $module   = $encoder->[0];
          my $function = $encoder->[1];
          eval { require $module; };
  
          if ( !$@ ) {
              $self->debug("loaded encoder: $module") if $self && ref $self && $self->{'debug'};
              $CFG{'uri_encoder_func'} = $function;
              last;
          }
          else {
              $self->debug("failed to load encoder: $module") if $self && ref $self && $self->{'debug'};
          }
      }
      if ($@) {
          Carp::confess("Unable to find a module capable of encoding api requests.");
      }
  }
  
  sub error {
      my ( $self, $msg ) = @_;
      print { $self->{'error_fh'} } $msg . "\n";
      $self->{'error'} = $msg;
  }
  
  sub debug {
      my ( $self, $msg ) = @_;
      print { $self->{'error_fh'} } "debug: " . $msg . "\n";
  }
  
  sub format_http_headers {
      my ( $self, $headers ) = @_;
      if ( ref $headers ) {
          return '' if !scalar keys %{$headers};
          return join( "\r\n", map { $_ ? ( $_ . ': ' . $headers->{$_} ) : () } keys %{$headers} ) . "\r\n";
      }
      return $headers;
  }
  
  sub format_http_query {
      my ( $self, $formdata ) = @_;
      if ( ref $formdata ) {
          return join( '&', map { $CFG{'uri_encoder_func'}->($_) . '=' . $CFG{'uri_encoder_func'}->( $formdata->{$_} ) } keys %{$formdata} );
      }
      return $formdata;
  }
CPANEL_PUBLICAPI

$fatpacked{"cPanel/PublicAPI/Utils.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'CPANEL_PUBLICAPI_UTILS';
  package cPanel::PublicAPI::Utils;
  
  # Copyright (c) 2011, cPanel, Inc.
  # All rights reserved.
  # http://cpanel.net
  #
  # Redistribution and use in source and binary forms, with or without
  # modification, are permitted provided that the following conditions are met:
  #    * Redistributions of source code must retain the above copyright
  #       notice, this list of conditions and the following disclaimer.
  #     * Redistributions in binary form must reproduce the above copyright
  #       notice, this list of conditions and the following disclaimer in the
  #       documentation and/or other materials provided with the distribution.
  #     * Neither the name of cPanel, Inc. nor the
  #       names of its contributors may be used to endorse or promote products
  #       derived from this software without specific prior written permission.
  #
  # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  # DISCLAIMED. IN NO EVENT SHALL  BE LIABLE FOR ANY
  # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  
  sub remove_trailing_newline {
      my $string = shift;
      $string =~ s/\r?\n$//g;
      return $string;
  }
  
  sub get_string_with_collapsed_trailing_eols {
      my @copy = @_;    # this addresses 'Modification of a read-only value attempted at cPanel/Accounting.pm ...' from $line =~ below
      my $txt;
      foreach my $line (@copy) {
          if ( ref $line eq 'ARRAY' ) {
              foreach my $subline ( @{$line} ) {
                  $subline =~ s/[\r\n]+$//g;
                  $txt .= $subline . "\n";
              }
          }
          else {
              $line =~ s/[\r\n]+$//g;
              $txt .= $line . "\n";
          }
      }
      return $txt;
  }
  
  1;
CPANEL_PUBLICAPI_UTILS

$fatpacked{"cPanel/PublicAPI/WHM.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'CPANEL_PUBLICAPI_WHM';
  package cPanel::PublicAPI::WHM;
  
  # Copyright (c) 2011, cPanel, Inc.
  # All rights reserved.
  # http://cpanel.net
  #
  # Redistribution and use in source and binary forms, with or without
  # modification, are permitted provided that the following conditions are met:
  #    * Redistributions of source code must retain the above copyright
  #       notice, this list of conditions and the following disclaimer.
  #     * Redistributions in binary form must reproduce the above copyright
  #       notice, this list of conditions and the following disclaimer in the
  #       documentation and/or other materials provided with the distribution.
  #     * Neither the name of cPanel, Inc. nor the
  #       names of its contributors may be used to endorse or promote products
  #       derived from this software without specific prior written permission.
  #
  # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  # DISCLAIMED. IN NO EVENT SHALL  BE LIABLE FOR ANY
  # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  
  use cPanel::PublicAPI ();
  
  our $VERSION = 1.0;
  
  package cPanel::PublicAPI;
  
  sub simple_get_whmreq {
      my ( $self, $uri, $argref, $argnameref, $opts ) = @_;
  
      $self->_init() if !exists $cPanel::PublicAPI::CFG{'init'};
  
      $self->debug("simple_get_whmreq: ( $self, $uri, $argref, $argnameref, $opts )\n") if $self->{'debug'};
  
      my $count = 0;
      if ( !$opts || !ref $opts ) { $opts = []; }
      if ( ref $argnameref ) {
          foreach my $arg ( @{$argnameref} ) {
              push @{$opts}, $cPanel::PublicAPI::CFG{'uri_encoder_func'}->($arg) . '=' . $cPanel::PublicAPI::CFG{'uri_encoder_func'}->( $argref->[$count] );
              $count++;
          }
      }
      my $page_ref = $self->whmreq( $uri . '?' . join( '&', @{$opts} ) );
      if ( $self->{'error'} ) { return ''; }
      return $page_ref;
  }
  
  sub simple_post_whmreq {
      my ( $self, $uri, $argref, $argnameref, $opts ) = @_;
  
      $self->_init() if !exists $cPanel::PublicAPI::CFG{'init'};
  
      $self->debug("simple_post_whmreq: ( $self, $uri, $argref, $argnameref, $opts )") if $self->{'debug'};
  
      my $count = 0;
      if ( !$opts || !ref $opts ) { $opts = []; }
      if ( ref $argnameref ) {
          foreach my $arg ( @{$argnameref} ) {
              push @{$opts}, $cPanel::PublicAPI::CFG{'uri_encoder_func'}->($arg) . '=' . $cPanel::PublicAPI::CFG{'uri_encoder_func'}->( $argref->[$count] );
              $count++;
          }
      }
      my $page_ref = $self->whmreq( $uri, 'POST', join( '&', @{$opts} ) );
      if ( $self->{'error'} ) { return ''; }
      return $page_ref;
  }
  
  sub whmreq {
      my $self     = shift;
      my $uri      = shift;
      my $method   = shift || 'GET';
      my $formdata = shift;
      if ( $method eq 'GET' && $uri =~ /\?/ ) {
          ( $uri, $formdata ) = split( /\?/, $uri );
      }
  
      $self->debug("whmreq: ( $self, $uri, $method, $formdata )\n") if $self->{'debug'};
  
      my ( $status, $statusmsg, $data ) = $self->api_request( 'whostmgr', $uri, $method, $formdata );
      return wantarray ? split( /\r?\n/, $$data ) : $$data;
  }
  
  sub api1 {    #cPanel::Accounting compat
      my $self   = shift;
      my $user   = shift;
      my $module = shift;
      my $func   = shift;
      return $self->cpanel_api1_request( 'whostmgr', { 'user' => $user, 'module' => $module, 'func' => $func }, \@_, 'xml' );
  }
  
  sub api2 {    #cPanel::Accounting compat
      my $self   = shift;
      my $user   = shift;
      my $module = shift;
      my $func   = shift;
      return $self->cpanel_api2_request( 'whostmgr', { 'user' => $user, 'module' => $module, 'func' => $func }, {@_}, 'xml' );
  }
  
  1;
CPANEL_PUBLICAPI_WHM

$fatpacked{"cPanel/PublicAPI/WHM/API.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'CPANEL_PUBLICAPI_WHM_API';
  package cPanel::PublicAPI::API;
  
  # Copyright (c) 2011, cPanel, Inc.
  # All rights reserved.
  # http://cpanel.net
  #
  # Redistribution and use in source and binary forms, with or without
  # modification, are permitted provided that the following conditions are met:
  #    * Redistributions of source code must retain the above copyright
  #       notice, this list of conditions and the following disclaimer.
  #     * Redistributions in binary form must reproduce the above copyright
  #       notice, this list of conditions and the following disclaimer in the
  #       documentation and/or other materials provided with the distribution.
  #     * Neither the name of cPanel, Inc. nor the
  #       names of its contributors may be used to endorse or promote products
  #       derived from this software without specific prior written permission.
  #
  # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  # DISCLAIMED. IN NO EVENT SHALL  BE LIABLE FOR ANY
  # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  
  use cPanel::PublicAPI ();
  our $VERSION = 1.0;
  
  package cPanel::PublicAPI;
  
  use cPanel::PublicAPI::WHM ();
  
  cPanel::PublicAPI::_init_serializer() if !exists $cPanel::PublicAPI::CFG{'serializer'};
  
  sub api_listaccts {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/listaccts', \@_, [ 'search', 'searchtype' ] ) );
  }
  
  sub api_createacct {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/createacct', \@_, [ 'username', 'domain', 'password', 'plan' ] ) );
  }
  
  sub api_removeacct {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/removeacct', \@_, ['user'] ) );
  }
  
  sub api_showversion {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/version', \@_ ) );
  }
  
  sub api_version {
      goto &xmlapi_showversion;
  }
  
  sub api_applist {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/applist', \@_ ) );
  }
  
  sub api_generatessl {
      my $self = shift;
      return $self->serialize( $self->simple_post_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/generatessl', \@_, [ 'host', 'pass', 'country', 'state', 'city', 'co', 'cod', 'email', 'xemail' ] ) );
  }
  
  sub api_generatessl_noemail {
      my $self = shift;
      return $self->serialize( $self->simple_post_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/generatessl', \@_, [ 'host', 'pass', 'country', 'state', 'city', 'co', 'cod', 'email' ], ['noemail=1'] ) );
  }
  
  sub api_listcrts {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/listcrts', \@_ ) );
  }
  
  # Variable arguments
  sub api_setresellerlimits {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/setresellerlimits', \@_ ) );
  }
  
  sub api_setresellerpackagelimit {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/setresellerpackagelimit', \@_, [ 'user', 'package', 'allowerd', 'number', 'no_limit' ] ) );
  }
  
  sub api_setresellermainip {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/setresellermainip', \@_, [ 'user', 'ip' ] ) );
  }
  
  sub api_setresellerips {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/setresellerips', \@_, [ 'user', 'delegate', 'ips' ] ) );
  }
  
  sub api_setresellernameservers {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/setresellernameservers', \@_, [ 'user', 'nameservers' ] ) );
  }
  
  sub api_suspendreseller {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/suspendreseller', \@_, [ 'user', 'reason', 'disallow' ] ) );
  }
  
  sub api_unsuspendreseller {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/unsuspendreseller', \@_, ['user'] ) );
  }
  
  # Variable arguments
  sub api_addzonerecord {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/addzonerecord', \@_ ) );
  }
  
  # Variable arguments
  sub api_editzonerecord {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/editzonerecord', \@_ ) );
  }
  
  sub api_removezonerecord {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/removezonerecord', \@_, [ 'domain', 'Line' ] ) );
  }
  
  sub api_getzonerecord {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/getzonerecord', \@_, [ 'domain', 'Line' ] ) );
  }
  
  sub api_servicestatus {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/servicestatus', \@_, ['service'] ) );
  }
  
  sub api_configureservice {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/configureservice', \@_, [ 'service', 'enabled', 'monitored' ] ) );
  }
  
  sub api_acctcounts {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/acctcounts', \@_, ['user'] ) );
  }
  
  sub api_domainuserdata {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/domainuserdata', \@_, ['domain'] ) );
  }
  
  sub api_editquota {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/editquota', \@_, [ 'user', 'quota' ] ) );
  }
  
  sub api_nvget {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/nvget', \@_, ['key'] ) );
  }
  
  # The underlying XMLAPI call allows setting multiple nvvars at once by appending
  # labels to the end of the variable names... i.e. key1, value1
  sub api_nvset {
      my $self = shift;
      return $self->serialize( $self->simple_post_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/nvset', \@_, [ 'key', 'value' ] ) );
  }
  
  sub api_myprivs {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/myprivs', \@_ ) );
  }
  
  sub api_listzones {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/listzones', \@_ ) );
  }
  
  sub api_sethostname {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/sethostname', \@_, ['hostname'] ) );
  }
  
  sub api_setresolvers {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/setresolvers', \@_, [ 'nameserver1', 'nameserver2', 'nameserver3' ] ) );
  }
  
  sub api_addip {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/addip', \@_, [ 'ip', 'netmask' ] ) );
  }
  
  sub api_delip {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/delip', \@_, [ 'ip', 'ethernetdev', 'skipifshutdown' ] ) );
  }
  
  sub api_listips {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/listips', \@_ ) );
  }
  
  sub api_dumpzone {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/dumpzone', \@_, ['domain'] ) );
  }
  
  sub api_listpkgs {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/listpkgs', \@_ ) );
  }
  
  sub api_limitbw {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/limitbw', \@_, [ 'user', 'bwlimit' ] ) );
  }
  
  sub api_showbw {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/showbw', \@_, [ 'month', 'year', 'showres', 'search', 'searchtype' ] ) );
  }
  
  sub api_killdns {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/killdns', \@_, ['domain'] ) );
  }
  
  sub api_adddns {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/adddns', \@_, [ 'domain', 'ip', 'trueowner' ] ) );
  }
  
  sub api_changepackage {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/changepackage', \@_, [ 'user', 'pkg' ] ) );
  }
  
  sub api_modifyacct {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/modifyacct', \@_, [ 'user', 'domain', 'HASCGI', 'CPTHEME', 'LANG', 'MAXPOP', 'MAXFTP', 'MAXLST', 'MAXSUB', 'MAXPARK', 'MAXADDON', 'MAXSQL', 'shell' ] ) );
  }
  
  sub api_suspendacct {
      my $self = shift;
      return $self->serialize( $self->simple_post_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/suspendacct', \@_, [ 'user', 'reason' ] ) );
  }
  
  sub api_unsuspendacct {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/unsuspendacct', \@_, ['user'] ) );
  }
  
  sub api_listsuspended {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/listsuspended', \@_ ) );
  }
  
  sub api_addpkg {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/addpkg', \@_, [ 'pkgname', 'quota', 'ip', 'cgi', 'frontpage', 'cpmod', 'maxftp', 'maxsql', 'maxpop', 'maxlst', 'maxsub', 'maxpark', 'maxaddon', 'featurelist', 'hasshell', 'bwlimit' ] ) );
  }
  
  sub api_killpkg {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/killpkg', \@_, ['pkg'] ) );
  }
  
  sub api_editpkg {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/editpkg', \@_, [ 'pkgname', 'quota', 'ip', 'cgi', 'frontpage', 'cpmod', 'maxftp', 'maxsql', 'maxpop', 'maxlst', 'maxsub', 'maxpark', 'maxaddon', 'featurelist', 'hasshell', 'bwlimit' ] ) );
  }
  
  sub api_setacls {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/setacls', \@_, [ 'reseller', 'acllist' ] ) );
  }
  
  sub api_terminatereseller {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/terminatereseller', \@_, [ 'reseller', 'verify' ] ) );
  }
  
  sub api_resellerstats {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/resellerstats', \@_, ['reseller'] ) );
  }
  
  sub api_setupreseller {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/setupreseller', \@_, [ 'user', 'makeowner' ] ) );
  }
  
  sub api_lookupnsip {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/lookupnsip', \@_, ['nameserver'] ) );
  }
  
  sub api_listresellers {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/listresellers', \@_ ) );
  }
  
  sub api_listacls {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/listacls', \@_ ) );
  }
  
  sub api_saveacllist {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/saveacllist', \@_, ['acllist'] ) );
  }
  
  sub api_unsetupreseller {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/unsetupreseller', \@_, ['user'] ) );
  }
  
  sub api_gethostname {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/gethostname', \@_ ) );
  }
  
  sub api_fetchsslinfo {
      my $self = shift;
      return $self->serialize( $self->simple_post_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/fetchsslinfo', \@_, [ 'domain', 'crtdata' ] ) );
  }
  
  sub api_installssl {
      my $self = shift;
      return $self->serialize( $self->simple_post_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/installssl', \@_, [ 'domain', 'user', 'cert', 'key', 'cab', 'ip' ] ) );
  }
  
  sub api_passwd {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/passwd', \@_, [ 'user', 'pass' ] ) );
  }
  
  sub api_getlanglist {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/getlanglist', \@_ ) );
  }
  
  sub api_reboot {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/reboot', \@_, ['force'] ) );
  }
  
  sub api_accountsummary_user {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/accountsummary', \@_, ['user'] ) );
  }
  
  sub api_accountsummary_domain {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/accountsummary', \@_, ['domain'] ) );
  }
  
  sub api_loadavg {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/loadavg', \@_ ) );
  }
  
  sub api_restartservice {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/restartservice', \@_, ['service'] ) );
  }
  
  sub api_setsiteip_user {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/setsiteip', \@_, [ 'user', 'ip' ] ) );
  }
  
  sub api_setsiteip_domain {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/setsiteip', \@_, [ 'domain', 'ip' ] ) );
  }
  
  sub api_initializemsgcenter {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/initializemsgcenter', \@_, [ 'title', 'id' ] ) );
  }
  
  sub api_createmsg {
      my $self = shift;
  
      # Need to perform magic to deal with the optional parameters.
      my @parm_names = ( 'title', 'updated', 'published', 'content', 'author.name', 'author.email', 'author.uri', 'contributor.name', 'contributor.email', 'contributor.uri', 'summary' );
  
      my $extra_count = scalar(@_) - scalar(@parm_names);
      my $cat_count = int( $extra_count / 3 + ( ( $extra_count % 3 ) && 1 ) );
      foreach my $i ( 1 .. $cat_count ) {
          push @parm_names, "category.$i.term", "category.$i.label", "category.$i.scheme";
      }
  
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/createmsg', \@_, \@parm_names ) );
  }
  
  sub api_deletemsg {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/deletemsg', \@_, ['atom_id'] ) );
  }
  
  sub api_getmsgfeed {
      my $self = shift;
      return $self->serialize( $self->simple_get_whmreq( '/' . $cPanel::PublicAPI::CFG{'serializer'} . '-api/getmsgfeed', \@_, ['which'] ) );
  }
  
  sub serialize {
      my $self = shift;
      return $cPanel::PublicAPI::CFG{'api_serializer_obj'}->(@_);
  }
  
  1;
CPANEL_PUBLICAPI_WHM_API

$fatpacked{"cPanel/PublicAPI/WHM/CachedVersion.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'CPANEL_PUBLICAPI_WHM_CACHEDVERSION';
  package cPanel::PublicAPI::WHM::CachedVersion;
  
  # Copyright (c) 2011, cPanel, Inc.
  # All rights reserved.
  # http://cpanel.net
  #
  # Redistribution and use in source and binary forms, with or without
  # modification, are permitted provided that the following conditions are met:
  #    * Redistributions of source code must retain the above copyright
  #       notice, this list of conditions and the following disclaimer.
  #     * Redistributions in binary form must reproduce the above copyright
  #       notice, this list of conditions and the following disclaimer in the
  #       documentation and/or other materials provided with the distribution.
  #     * Neither the name of cPanel, Inc. nor the
  #       names of its contributors may be used to endorse or promote products
  #       derived from this software without specific prior written permission.
  #
  # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  # DISCLAIMED. IN NO EVENT SHALL  BE LIABLE FOR ANY
  # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  
  use cPanel::PublicAPI ();
  
  our $VERSION = 1.0;
  
  package cPanel::PublicAPI;
  
  use cPanel::PublicAPI::WHM::Legacy ();
  
  our $basedir  = '/var/cpanel/accounting';
  our $cachedir = '/var/cpanel/accounting/cache';
  our $cachettl = 3600;                             #one hour
  
  sub check_dirs {
      foreach my $dir ( $basedir, $cachedir ) {
          if ( !-e $dir ) {
              mkdir( $dir, 0700 );
          }
      }
  }
  
  sub cached_version {
      my $self = shift;
      my $ttl = shift || $cachettl;
      my $version;
  
      $self->check_dirs();
  
      my $file = ( $self->{'ip'} || $self->{'host'} );
  
      if ( !$file ) {
          return;
      }
  
      $file =~ s/\///g;
      my $fullfile = $cachedir . '/' . $file;
      my $now      = time();
      my $mtime    = ( stat($fullfile) )[9];
  
      if ( $mtime && ( $mtime + $ttl ) > $now && $mtime < $now ) {
          if ( open( my $cache_fh, '<', $fullfile ) ) {
              my $fileversion = readline($cache_fh);
              if ( $fileversion =~ /^(\d+\.\d+\.\d+)/ ) {
                  $version = $1;
              }
              close($cache_fh);
          }
      }
  
      if ($version) { return $version; }
  
      $version = $self->version();
  
      if ($version) {
          if ( open( my $cache_fh, '>', $fullfile ) ) {
              print {$cache_fh} $version;
              close($cache_fh);
          }
      }
  
      return $version;
  }
  
  1;
CPANEL_PUBLICAPI_WHM_CACHEDVERSION

$fatpacked{"cPanel/PublicAPI/WHM/DNS.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'CPANEL_PUBLICAPI_WHM_DNS';
  package cPanel::PublicAPI::DNS;
  
  # Copyright (c) 2011, cPanel, Inc.
  # All rights reserved.
  # http://cpanel.net
  #
  # Redistribution and use in source and binary forms, with or without
  # modification, are permitted provided that the following conditions are met:
  #    * Redistributions of source code must retain the above copyright
  #       notice, this list of conditions and the following disclaimer.
  #     * Redistributions in binary form must reproduce the above copyright
  #       notice, this list of conditions and the following disclaimer in the
  #       documentation and/or other materials provided with the distribution.
  #     * Neither the name of cPanel, Inc. nor the
  #       names of its contributors may be used to endorse or promote products
  #       derived from this software without specific prior written permission.
  #
  # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  # DISCLAIMED. IN NO EVENT SHALL  BE LIABLE FOR ANY
  # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  
  use cPanel::PublicAPI ();
  
  our $VERSION = 1.0;
  
  package cPanel::PublicAPI;
  
  use cPanel::PublicAPI::WHM   ();
  use cPanel::PublicAPI::Utils ();
  
  sub addtocluster {
      my $self = shift;
      my $page = $self->simple_post_whmreq( '/cgi/trustclustermaster.cgi', \@_, [ 'user', 'clustermaster', 'pass', 'version' ], ['recurse=0'] );
      if ( $page =~ /has been established/i ) {
          return 1;
      }
      return;
  }
  
  sub getzone_local {
      my $self = shift;
      return $self->simple_post_whmreq( '/scripts2/getzone_local', \@_, [ 'zone', 'dnsuniqid' ] );
  }
  
  sub getzones_local {
      my $self = shift;
      return $self->simple_post_whmreq( '/scripts2/getzones_local', \@_, [ 'zones', 'dnsuniqid' ] );
  }
  
  sub getallzones_local {
      my $self = shift;
      return $self->simple_post_whmreq( '/scripts2/getallzones_local', \@_, ['dnsuniqid'] );
  }
  
  sub cleandns_local {
      my $self = shift;
      return $self->simple_get_whmreq( '/scripts2/cleandns_local', \@_, ['dnsuniqid'] );
  }
  
  sub getips_local {
      my $self = shift;
      return cPanel::PublicAPI::Utils::get_string_with_collapsed_trailing_eols( split( /\n/, ( $self->simple_get_whmreq( '/scripts2/getips_local', \@_, ['dnsuniqid'] ) ) ) );
  }
  
  sub getpath_local {
      my $self = shift;
      return cPanel::PublicAPI::Utils::get_string_with_collapsed_trailing_eols( split( /\n/, ( $self->simple_get_whmreq( '/scripts2/getpath_local', \@_, ['dnsuniqid'] ) ) ) );
  }
  
  sub removezone_local {
      my $self = shift;
      return $self->simple_post_whmreq( '/scripts2/removezone_local', \@_, [ 'zone', 'dnsuniqid' ] );
  }
  
  sub removezones_local {
      my $self = shift;
      return $self->simple_post_whmreq( '/scripts2/removezones_local', \@_, [ 'zones', 'dnsuniqid' ] );
  }
  
  sub reloadzones_local {
      my $self = shift;
      return $self->simple_post_whmreq( '/scripts2/reloadzones_local', \@_, [ 'dnsuniqid', 'zone' ] );    # backcompat
  }
  
  sub reloadbind_local {
      my $self = shift;
      return $self->simple_post_whmreq( '/scripts2/reloadbind_local', \@_, [ 'dnsuniqid', 'zone' ] );     # backcompat
  }
  
  sub reconfigbind_local {
      my $self = shift;
      return $self->simple_post_whmreq( '/scripts2/reconfigbind_local', \@_, [ 'dnsuniqid', 'zone' ] );    # backcompat
  }
  
  sub quickzoneadd_local {
      my $self = shift;
      return $self->simple_post_whmreq( '/scripts2/quickzoneadd_local', \@_, [ 'zone', 'zonedata', 'dnsuniqid' ] );
  }
  
  sub savezone_local {
      my $self = shift;
      return $self->simple_post_whmreq( '/scripts2/savezone_local', \@_, [ 'zone', 'zonedata', 'dnsuniqid' ] );
  }
  
  sub synczones_local {
      my ( $self, $formdata, $dnsuniqid ) = @_;
      cPanel::PublicAPI::_init() if !exists $cPanel::PublicAPI::CFG{'init'};
      $formdata =~ s/\&$//g;    # formdata must come pre encoded.
      $formdata .= '&dnsuniqid=' . $cPanel::PublicAPI::CFG{'uri_encoder_func'}->($dnsuniqid);
      my $page = join( "\n", $self->whmreq( '/scripts2/synczones_local', 'POST', $formdata ) );
      return if $self->{'error'};
      return $page;
  }
  
  sub addzoneconf_local {
      my $self = shift;
      return $self->simple_get_whmreq( '/scripts2/addzoneconf_local', \@_, [ 'zone', 'dnsuniqid' ] );
  }
  
  sub getzonelist_local {
      my $self = shift;
      return split( /\n/, $self->simple_get_whmreq( '/scripts2/getzonelist_local', \@_, ['dnsuniqid'] ) );
  }
  
  sub zoneexists_local {
      my $self = shift;
      my $exists = cPanel::PublicAPI::Utils::remove_trailing_newline( $self->simple_post_whmreq( '/scripts2/zoneexists_local', \@_, [ 'zone', 'dnsuniqid' ] ) );
      $exists =~ s/[\r\n]//g;
      if ( $exists eq '1' ) {
          return 1;
      }
      return 0;
  }
  
CPANEL_PUBLICAPI_WHM_DNS

$fatpacked{"cPanel/PublicAPI/WHM/JSONAPI.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'CPANEL_PUBLICAPI_WHM_JSONAPI';
  package cPanel::PublicAPI::JSONAPI;
  
  # Copyright (c) 2011, cPanel, Inc.
  # All rights reserved.
  # http://cpanel.net
  #
  # Redistribution and use in source and binary forms, with or without
  # modification, are permitted provided that the following conditions are met:
  #    * Redistributions of source code must retain the above copyright
  #       notice, this list of conditions and the following disclaimer.
  #     * Redistributions in binary form must reproduce the above copyright
  #       notice, this list of conditions and the following disclaimer in the
  #       documentation and/or other materials provided with the distribution.
  #     * Neither the name of cPanel, Inc. nor the
  #       names of its contributors may be used to endorse or promote products
  #       derived from this software without specific prior written permission.
  #
  # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  # DISCLAIMED. IN NO EVENT SHALL  BE LIABLE FOR ANY
  # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  
  use cPanel::PublicAPI ();
  
  our $VERSION = 1.0;
  
  package cPanel::PublicAPI;
  
  use cPanel::PublicAPI::WHM::API ();
  
  foreach my $sub ( grep ( /^api_/, keys %cPanel::PublicAPI:: ) ) {
      *{"json$sub"} = *$sub;
  }
  
  1;
  
CPANEL_PUBLICAPI_WHM_JSONAPI

$fatpacked{"cPanel/PublicAPI/WHM/Legacy.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'CPANEL_PUBLICAPI_WHM_LEGACY';
  package cPanel::PublicAPI::Legacy;
  
  # Copyright (c) 2011, cPanel, Inc.
  # All rights reserved.
  # http://cpanel.net
  #
  # Redistribution and use in source and binary forms, with or without
  # modification, are permitted provided that the following conditions are met:
  #    * Redistributions of source code must retain the above copyright
  #       notice, this list of conditions and the following disclaimer.
  #     * Redistributions in binary form must reproduce the above copyright
  #       notice, this list of conditions and the following disclaimer in the
  #       documentation and/or other materials provided with the distribution.
  #     * Neither the name of cPanel, Inc. nor the
  #       names of its contributors may be used to endorse or promote products
  #       derived from this software without specific prior written permission.
  #
  # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  # DISCLAIMED. IN NO EVENT SHALL  BE LIABLE FOR ANY
  # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  
  use cPanel::PublicAPI ();
  
  our $VERSION = 1.0;
  
  package cPanel::PublicAPI;
  
  use cPanel::PublicAPI::WHM ();
  
  sub _modpkg {
      my $self  = shift;
      my $op    = shift;
      my $count = 0;
      my @OPTS  = ('nohtml=1');
      if ( $op eq 'edit' ) { push @OPTS, 'edit=yes'; }
      return $self->simple_get_whmreq( '/scripts/addpkg', \@_, [ 'name', 'hasshell', 'bwlimit', 'quota', 'ip', 'cgi', 'frontpage', 'cpmod', 'maxftp', 'maxsql', 'maxpop', 'maxlst', 'maxsub', 'maxpark', 'maxaddon', 'featurelist', 'language' ], \@OPTS );
  }
  
  sub addpkg {
      my $self = shift;
      return $self->_modpkg( 'add', @_ );
  }
  
  sub editpkg {
      my $self = shift;
      return $self->_modpkg( 'edit', @_ );
  }
  
  sub killpkg {
      my $self = shift;
      return $self->simple_get_whmreq( '/scripts/killpkg', \@_, ['pkg'], ['nohtml=1'] );
  }
  
  sub suspend {
      my $self = shift;
      return $self->simple_get_whmreq( '/scripts/remote_suspend', \@_, ['user'] );
  }
  
  sub unsuspend {
      my $self = shift;
      return $self->simple_get_whmreq( '/scripts/remote_unsuspend', \@_, ['user'] );
  }
  
  sub killacct {
      my $self = shift;
      return $self->simple_get_whmreq( '/scripts/killacct', \@_, ['user'], ['nohtml=1'] );
  }
  
  sub showversion {
      my $self = shift;
      return $self->simple_get_whmreq( '/scripts2/showversion', \@_ );
  }
  
  sub version {
      my $self = shift;
      return $self->simple_get_whmreq( '/scripts2/showversion', \@_ );
  }
  
  sub showhostname {
      my $self = shift;
      return $self->simple_get_whmreq( '/scripts2/gethostname', \@_ );
  }
  
  sub createacct {
      my $self = shift;
      return $self->simple_get_whmreq( '/scripts/wwwacct', \@_, [ 'domain', 'username', 'password', 'plan', 'language' ], ['nohtml=1'] );
  }
  
  sub listpkgs {
      my $self = shift;
      my $req = $self->simple_get_whmreq( '/scripts/remote_listpkg', \@_ );
      my %PKGS;
      foreach ( split( /\n/, $req ) ) {
          my ( $pkg, $contents ) = split( /=/, $_ );
          my @CONTENTS = split( /\,/, $contents );
          $PKGS{$pkg} = \@CONTENTS;
      }
      return wantarray ? %PKGS : \%PKGS;
  }
  
  sub listaccts {
      my $self = shift;
      my $req = $self->simple_get_whmreq( '/scripts2/listaccts', \@_, [], ['nohtml=1&viewall=1'] );
      my %ACCTS;
      foreach ( split( /\n/, $req ) ) {
          my ( $acct, $contents ) = split( /=/, $_ );
          my @CONTENTS = split( /\,/, $contents );
          $ACCTS{$acct} = \@CONTENTS;
      }
      return wantarray ? %ACCTS : \%ACCTS;
  }
  1;
CPANEL_PUBLICAPI_WHM_LEGACY

$fatpacked{"cPanel/PublicAPI/WHM/XMLAPI.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'CPANEL_PUBLICAPI_WHM_XMLAPI';
  package cPanel::PublicAPI::XMLAPI;
  
  # Copyright (c) 2011, cPanel, Inc.
  # All rights reserved.
  # http://cpanel.net
  #
  # Redistribution and use in source and binary forms, with or without
  # modification, are permitted provided that the following conditions are met:
  #    * Redistributions of source code must retain the above copyright
  #       notice, this list of conditions and the following disclaimer.
  #     * Redistributions in binary form must reproduce the above copyright
  #       notice, this list of conditions and the following disclaimer in the
  #       documentation and/or other materials provided with the distribution.
  #     * Neither the name of cPanel, Inc. nor the
  #       names of its contributors may be used to endorse or promote products
  #       derived from this software without specific prior written permission.
  #
  # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  # DISCLAIMED. IN NO EVENT SHALL  BE LIABLE FOR ANY
  # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  
  use cPanel::PublicAPI ();
  
  our $VERSION = 1.0;
  
  package cPanel::PublicAPI;
  
  use cPanel::PublicAPI::WHM::API ();
  
  foreach my $sub ( grep ( /^api_/, keys %cPanel::PublicAPI:: ) ) {
      *{"xml$sub"} = *$sub;
  }
  
  1;
  
CPANEL_PUBLICAPI_WHM_XMLAPI

$fatpacked{"constant.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'CONSTANT';
  package constant;
  use 5.008;
  use strict;
  use warnings::register;
  
  use vars qw($VERSION %declared);
  $VERSION = '1.27';
  
  #=======================================================================
  
  # Some names are evil choices.
  my %keywords = map +($_, 1), qw{ BEGIN INIT CHECK END DESTROY AUTOLOAD };
  $keywords{UNITCHECK}++ if $] > 5.009;
  
  my %forced_into_main = map +($_, 1),
      qw{ STDIN STDOUT STDERR ARGV ARGVOUT ENV INC SIG };
  
  my %forbidden = (%keywords, %forced_into_main);
  
  my $normal_constant_name = qr/^_?[^\W_0-9]\w*\z/;
  my $tolerable = qr/^[A-Za-z_]\w*\z/;
  my $boolean = qr/^[01]?\z/;
  
  BEGIN {
      # We'd like to do use constant _CAN_PCS => $] > 5.009002
      # but that's a bit tricky before we load the constant module :-)
      # By doing this, we save 1 run time check for *every* call to import.
      no strict 'refs';
      my $const = $] > 5.009002;
      *_CAN_PCS = sub () {$const};
  
      my $downgrade = $] < 5.015004; # && $] >= 5.008
      *_DOWNGRADE = sub () { $downgrade };
  }
  
  #=======================================================================
  # import() - import symbols into user's namespace
  #
  # What we actually do is define a function in the caller's namespace
  # which returns the value. The function we create will normally
  # be inlined as a constant, thereby avoiding further sub calling 
  # overhead.
  #=======================================================================
  sub import {
      my $class = shift;
      return unless @_;			# Ignore 'use constant;'
      my $constants;
      my $multiple  = ref $_[0];
      my $pkg = caller;
      my $flush_mro;
      my $symtab;
  
      if (_CAN_PCS) {
  	no strict 'refs';
  	$symtab = \%{$pkg . '::'};
      };
  
      if ( $multiple ) {
  	if (ref $_[0] ne 'HASH') {
  	    require Carp;
  	    Carp::croak("Invalid reference type '".ref(shift)."' not 'HASH'");
  	}
  	$constants = shift;
      } else {
  	unless (defined $_[0]) {
  	    require Carp;
  	    Carp::croak("Can't use undef as constant name");
  	}
  	$constants->{+shift} = undef;
      }
  
      foreach my $name ( keys %$constants ) {
  	# Normal constant name
  	if ($name =~ $normal_constant_name and !$forbidden{$name}) {
  	    # Everything is okay
  
  	# Name forced into main, but we're not in main. Fatal.
  	} elsif ($forced_into_main{$name} and $pkg ne 'main') {
  	    require Carp;
  	    Carp::croak("Constant name '$name' is forced into main::");
  
  	# Starts with double underscore. Fatal.
  	} elsif ($name =~ /^__/) {
  	    require Carp;
  	    Carp::croak("Constant name '$name' begins with '__'");
  
  	# Maybe the name is tolerable
  	} elsif ($name =~ $tolerable) {
  	    # Then we'll warn only if you've asked for warnings
  	    if (warnings::enabled()) {
  		if ($keywords{$name}) {
  		    warnings::warn("Constant name '$name' is a Perl keyword");
  		} elsif ($forced_into_main{$name}) {
  		    warnings::warn("Constant name '$name' is " .
  			"forced into package main::");
  		}
  	    }
  
  	# Looks like a boolean
  	# use constant FRED == fred;
  	} elsif ($name =~ $boolean) {
              require Carp;
  	    if (@_) {
  		Carp::croak("Constant name '$name' is invalid");
  	    } else {
  		Carp::croak("Constant name looks like boolean value");
  	    }
  
  	} else {
  	   # Must have bad characters
              require Carp;
  	    Carp::croak("Constant name '$name' has invalid characters");
  	}
  
  	{
  	    no strict 'refs';
  	    my $full_name = "${pkg}::$name";
  	    $declared{$full_name}++;
  	    if ($multiple || @_ == 1) {
  		my $scalar = $multiple ? $constants->{$name} : $_[0];
  
  		if (_DOWNGRADE) { # for 5.8 to 5.14
  		    # Work around perl bug #31991: Sub names (actually glob
  		    # names in general) ignore the UTF8 flag. So we have to
  		    # turn it off to get the "right" symbol table entry.
  		    utf8::is_utf8 $name and utf8::encode $name;
  		}
  
  		# The constant serves to optimise this entire block out on
  		# 5.8 and earlier.
  		if (_CAN_PCS && $symtab && !exists $symtab->{$name}) {
  		    # No typeglob yet, so we can use a reference as space-
  		    # efficient proxy for a constant subroutine
  		    # The check in Perl_ck_rvconst knows that inlinable
  		    # constants from cv_const_sv are read only. So we have to:
  		    Internals::SvREADONLY($scalar, 1);
  		    $symtab->{$name} = \$scalar;
  		    ++$flush_mro;
  		} else {
  		    *$full_name = sub () { $scalar };
  		}
  	    } elsif (@_) {
  		my @list = @_;
  		*$full_name = sub () { @list };
  	    } else {
  		*$full_name = sub () { };
  	    }
  	}
      }
      # Flush the cache exactly once if we make any direct symbol table changes.
      mro::method_changed_in($pkg) if _CAN_PCS && $flush_mro;
  }
  
  1;
  
  __END__
  
  =head1 NAME
  
  constant - Perl pragma to declare constants
  
  =head1 SYNOPSIS
  
      use constant PI    => 4 * atan2(1, 1);
      use constant DEBUG => 0;
  
      print "Pi equals ", PI, "...\n" if DEBUG;
  
      use constant {
          SEC   => 0,
          MIN   => 1,
          HOUR  => 2,
          MDAY  => 3,
          MON   => 4,
          YEAR  => 5,
          WDAY  => 6,
          YDAY  => 7,
          ISDST => 8,
      };
  
      use constant WEEKDAYS => qw(
          Sunday Monday Tuesday Wednesday Thursday Friday Saturday
      );
  
      print "Today is ", (WEEKDAYS)[ (localtime)[WDAY] ], ".\n";
  
  =head1 DESCRIPTION
  
  This pragma allows you to declare constants at compile-time.
  
  When you declare a constant such as C<PI> using the method shown
  above, each machine your script runs upon can have as many digits
  of accuracy as it can use. Also, your program will be easier to
  read, more likely to be maintained (and maintained correctly), and
  far less likely to send a space probe to the wrong planet because
  nobody noticed the one equation in which you wrote C<3.14195>.
  
  When a constant is used in an expression, Perl replaces it with its
  value at compile time, and may then optimize the expression further.
  In particular, any code in an C<if (CONSTANT)> block will be optimized
  away if the constant is false.
  
  =head1 NOTES
  
  As with all C<use> directives, defining a constant happens at
  compile time. Thus, it's probably not correct to put a constant
  declaration inside of a conditional statement (like C<if ($foo)
  { use constant ... }>).
  
  Constants defined using this module cannot be interpolated into
  strings like variables.  However, concatenation works just fine:
  
      print "Pi equals PI...\n";        # WRONG: does not expand "PI"
      print "Pi equals ".PI."...\n";    # right
  
  Even though a reference may be declared as a constant, the reference may
  point to data which may be changed, as this code shows.
  
      use constant ARRAY => [ 1,2,3,4 ];
      print ARRAY->[1];
      ARRAY->[1] = " be changed";
      print ARRAY->[1];
  
  Dereferencing constant references incorrectly (such as using an array
  subscript on a constant hash reference, or vice versa) will be trapped at
  compile time.
  
  Constants belong to the package they are defined in.  To refer to a
  constant defined in another package, specify the full package name, as
  in C<Some::Package::CONSTANT>.  Constants may be exported by modules,
  and may also be called as either class or instance methods, that is,
  as C<< Some::Package->CONSTANT >> or as C<< $obj->CONSTANT >> where
  C<$obj> is an instance of C<Some::Package>.  Subclasses may define
  their own constants to override those in their base class.
  
  The use of all caps for constant names is merely a convention,
  although it is recommended in order to make constants stand out
  and to help avoid collisions with other barewords, keywords, and
  subroutine names. Constant names must begin with a letter or
  underscore. Names beginning with a double underscore are reserved. Some
  poor choices for names will generate warnings, if warnings are enabled at
  compile time.
  
  =head2 List constants
  
  Constants may be lists of more (or less) than one value.  A constant
  with no values evaluates to C<undef> in scalar context.  Note that
  constants with more than one value do I<not> return their last value in
  scalar context as one might expect.  They currently return the number
  of values, but B<this may change in the future>.  Do not use constants
  with multiple values in scalar context.
  
  B<NOTE:> This implies that the expression defining the value of a
  constant is evaluated in list context.  This may produce surprises:
  
      use constant TIMESTAMP => localtime;                # WRONG!
      use constant TIMESTAMP => scalar localtime;         # right
  
  The first line above defines C<TIMESTAMP> as a 9-element list, as
  returned by C<localtime()> in list context.  To set it to the string
  returned by C<localtime()> in scalar context, an explicit C<scalar>
  keyword is required.
  
  List constants are lists, not arrays.  To index or slice them, they
  must be placed in parentheses.
  
      my @workdays = WEEKDAYS[1 .. 5];            # WRONG!
      my @workdays = (WEEKDAYS)[1 .. 5];          # right
  
  =head2 Defining multiple constants at once
  
  Instead of writing multiple C<use constant> statements, you may define
  multiple constants in a single statement by giving, instead of the
  constant name, a reference to a hash where the keys are the names of
  the constants to be defined.  Obviously, all constants defined using
  this method must have a single value.
  
      use constant {
          FOO => "A single value",
          BAR => "This", "won't", "work!",        # Error!
      };
  
  This is a fundamental limitation of the way hashes are constructed in
  Perl.  The error messages produced when this happens will often be
  quite cryptic -- in the worst case there may be none at all, and
  you'll only later find that something is broken.
  
  When defining multiple constants, you cannot use the values of other
  constants defined in the same declaration.  This is because the
  calling package doesn't know about any constant within that group
  until I<after> the C<use> statement is finished.
  
      use constant {
          BITMASK => 0xAFBAEBA8,
          NEGMASK => ~BITMASK,                    # Error!
      };
  
  =head2 Magic constants
  
  Magical values and references can be made into constants at compile
  time, allowing for way cool stuff like this.  (These error numbers
  aren't totally portable, alas.)
  
      use constant E2BIG => ($! = 7);
      print   E2BIG, "\n";        # something like "Arg list too long"
      print 0+E2BIG, "\n";        # "7"
  
  You can't produce a tied constant by giving a tied scalar as the
  value.  References to tied variables, however, can be used as
  constants without any problems.
  
  =head1 TECHNICAL NOTES
  
  In the current implementation, scalar constants are actually
  inlinable subroutines. As of version 5.004 of Perl, the appropriate
  scalar constant is inserted directly in place of some subroutine
  calls, thereby saving the overhead of a subroutine call. See
  L<perlsub/"Constant Functions"> for details about how and when this
  happens.
  
  In the rare case in which you need to discover at run time whether a
  particular constant has been declared via this module, you may use
  this function to examine the hash C<%constant::declared>. If the given
  constant name does not include a package name, the current package is
  used.
  
      sub declared ($) {
          use constant 1.01;              # don't omit this!
          my $name = shift;
          $name =~ s/^::/main::/;
          my $pkg = caller;
          my $full_name = $name =~ /::/ ? $name : "${pkg}::$name";
          $constant::declared{$full_name};
      }
  
  =head1 CAVEATS
  
  In the current version of Perl, list constants are not inlined
  and some symbols may be redefined without generating a warning.
  
  It is not possible to have a subroutine or a keyword with the same
  name as a constant in the same package. This is probably a Good Thing.
  
  A constant with a name in the list C<STDIN STDOUT STDERR ARGV ARGVOUT
  ENV INC SIG> is not allowed anywhere but in package C<main::>, for
  technical reasons. 
  
  Unlike constants in some languages, these cannot be overridden
  on the command line or via environment variables.
  
  You can get into trouble if you use constants in a context which
  automatically quotes barewords (as is true for any subroutine call).
  For example, you can't say C<$hash{CONSTANT}> because C<CONSTANT> will
  be interpreted as a string.  Use C<$hash{CONSTANT()}> or
  C<$hash{+CONSTANT}> to prevent the bareword quoting mechanism from
  kicking in.  Similarly, since the C<< => >> operator quotes a bareword
  immediately to its left, you have to say C<< CONSTANT() => 'value' >>
  (or simply use a comma in place of the big arrow) instead of
  C<< CONSTANT => 'value' >>.
  
  =head1 SEE ALSO
  
  L<Readonly> - Facility for creating read-only scalars, arrays, hashes.
  
  L<Attribute::Constant> - Make read-only variables via attribute
  
  L<Scalar::Readonly> - Perl extension to the C<SvREADONLY> scalar flag
  
  L<Hash::Util> - A selection of general-utility hash subroutines (mostly
  to lock/unlock keys and values)
  
  =head1 BUGS
  
  Please report any bugs or feature requests via the perlbug(1) utility.
  
  =head1 AUTHORS
  
  Tom Phoenix, E<lt>F<rootbeer@redcat.com>E<gt>, with help from
  many other folks.
  
  Multiple constant declarations at once added by Casey West,
  E<lt>F<casey@geeknest.com>E<gt>.
  
  Documentation mostly rewritten by Ilmari Karonen,
  E<lt>F<perl@itz.pp.sci.fi>E<gt>.
  
  This program is maintained by the Perl 5 Porters. 
  The CPAN distribution is maintained by SE<eacute>bastien Aperghis-Tramoni
  E<lt>F<sebastien@aperghis.net>E<gt>.
  
  =head1 COPYRIGHT & LICENSE
  
  Copyright (C) 1997, 1999 Tom Phoenix
  
  This module is free software; you can redistribute it or modify it
  under the same terms as Perl itself.
  
  =cut
CONSTANT

$fatpacked{"parent.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'PARENT';
  package parent;
  use strict;
  use vars qw($VERSION);
  $VERSION = '0.228';
  
  sub import {
      my $class = shift;
  
      my $inheritor = caller(0);
  
      if ( @_ and $_[0] eq '-norequire' ) {
          shift @_;
      } else {
          for ( my @filename = @_ ) {
              if ( $_ eq $inheritor ) {
                  warn "Class '$inheritor' tried to inherit from itself\n";
              };
  
              s{::|'}{/}g;
              require "$_.pm"; # dies if the file is not found
          }
      }
  
      {
          no strict 'refs';
          push @{"$inheritor\::ISA"}, @_;
      };
  };
  
  "All your base are belong to us"
  
  __END__
  
  =encoding utf8
  
  =head1 NAME
  
  parent - Establish an ISA relationship with base classes at compile time
  
  =head1 SYNOPSIS
  
      package Baz;
      use parent qw(Foo Bar);
  
  =head1 DESCRIPTION
  
  Allows you to both load one or more modules, while setting up inheritance from
  those modules at the same time.  Mostly similar in effect to
  
      package Baz;
      BEGIN {
          require Foo;
          require Bar;
          push @ISA, qw(Foo Bar);
      }
  
  By default, every base class needs to live in a file of its own.
  If you want to have a subclass and its parent class in the same file, you
  can tell C<parent> not to load any modules by using the C<-norequire> switch:
  
    package Foo;
    sub exclaim { "I CAN HAS PERL" }
  
    package DoesNotLoadFooBar;
    use parent -norequire, 'Foo', 'Bar';
    # will not go looking for Foo.pm or Bar.pm
  
  This is equivalent to the following code:
  
    package Foo;
    sub exclaim { "I CAN HAS PERL" }
  
    package DoesNotLoadFooBar;
    push @DoesNotLoadFooBar::ISA, 'Foo', 'Bar';
  
  This is also helpful for the case where a package lives within
  a differently named file:
  
    package MyHash;
    use Tie::Hash;
    use parent -norequire, 'Tie::StdHash';
  
  This is equivalent to the following code:
  
    package MyHash;
    require Tie::Hash;
    push @ISA, 'Tie::StdHash';
  
  If you want to load a subclass from a file that C<require> would
  not consider an eligible filename (that is, it does not end in
  either C<.pm> or C<.pmc>), use the following code:
  
    package MySecondPlugin;
    require './plugins/custom.plugin'; # contains Plugin::Custom
    use parent -norequire, 'Plugin::Custom';
  
  =head1 DIAGNOSTICS
  
  =over 4
  
  =item Class 'Foo' tried to inherit from itself
  
  Attempting to inherit from yourself generates a warning.
  
      package Foo;
      use parent 'Foo';
  
  =back
  
  =head1 HISTORY
  
  This module was forked from L<base> to remove the cruft
  that had accumulated in it.
  
  =head1 CAVEATS
  
  =head1 SEE ALSO
  
  L<base>
  
  =head1 AUTHORS AND CONTRIBUTORS
  
  Rafaël Garcia-Suarez, Bart Lateur, Max Maischein, Anno Siegel, Michael Schwern
  
  =head1 MAINTAINER
  
  Max Maischein C< corion@cpan.org >
  
  Copyright (c) 2007-10 Max Maischein C<< <corion@cpan.org> >>
  Based on the idea of C<base.pm>, which was introduced with Perl 5.004_04.
  
  =head1 LICENSE
  
  This module is released under the same terms as Perl itself.
  
  =cut
PARENT

$fatpacked{"x86_64-linux/Data/Dumper.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'X86_64-LINUX_DATA_DUMPER';
  #
  # Data/Dumper.pm
  #
  # convert perl data structures into perl syntax suitable for both printing
  # and eval
  #
  # Documentation at the __END__
  #
  
  package Data::Dumper;
  
  BEGIN {
      $VERSION = '2.145'; # Don't forget to set version and release
  }               # date in POD below!
  
  #$| = 1;
  
  use 5.006_001;
  require Exporter;
  require overload;
  
  use Carp;
  
  BEGIN {
      @ISA = qw(Exporter);
      @EXPORT = qw(Dumper);
      @EXPORT_OK = qw(DumperX);
  
      # if run under miniperl, or otherwise lacking dynamic loading,
      # XSLoader should be attempted to load, or the pure perl flag
      # toggled on load failure.
      eval {
          require XSLoader;
          XSLoader::load( 'Data::Dumper' );
          1
      }
      or $Useperl = 1;
  }
  
  # module vars and their defaults
  $Indent     = 2         unless defined $Indent;
  $Purity     = 0         unless defined $Purity;
  $Pad        = ""        unless defined $Pad;
  $Varname    = "VAR"     unless defined $Varname;
  $Useqq      = 0         unless defined $Useqq;
  $Terse      = 0         unless defined $Terse;
  $Freezer    = ""        unless defined $Freezer;
  $Toaster    = ""        unless defined $Toaster;
  $Deepcopy   = 0         unless defined $Deepcopy;
  $Quotekeys  = 1         unless defined $Quotekeys;
  $Bless      = "bless"   unless defined $Bless;
  #$Expdepth   = 0         unless defined $Expdepth;
  $Maxdepth   = 0         unless defined $Maxdepth;
  $Pair       = ' => '    unless defined $Pair;
  $Useperl    = 0         unless defined $Useperl;
  $Sortkeys   = 0         unless defined $Sortkeys;
  $Deparse    = 0         unless defined $Deparse;
  $Sparseseen = 0         unless defined $Sparseseen;
  
  #
  # expects an arrayref of values to be dumped.
  # can optionally pass an arrayref of names for the values.
  # names must have leading $ sign stripped. begin the name with *
  # to cause output of arrays and hashes rather than refs.
  #
  sub new {
    my($c, $v, $n) = @_;
  
    croak "Usage:  PACKAGE->new(ARRAYREF, [ARRAYREF])"
      unless (defined($v) && (ref($v) eq 'ARRAY'));
    $n = [] unless (defined($n) && (ref($n) eq 'ARRAY'));
  
    my($s) = {
          level      => 0,           # current recursive depth
          indent     => $Indent,     # various styles of indenting
          pad        => $Pad,        # all lines prefixed by this string
          xpad       => "",          # padding-per-level
          apad       => "",          # added padding for hash keys n such
          sep        => "",          # list separator
          pair       => $Pair,    # hash key/value separator: defaults to ' => '
          seen       => {},          # local (nested) refs (id => [name, val])
          todump     => $v,          # values to dump []
          names      => $n,          # optional names for values []
          varname    => $Varname,    # prefix to use for tagging nameless ones
          purity     => $Purity,     # degree to which output is evalable
          useqq      => $Useqq,      # use "" for strings (backslashitis ensues)
          terse      => $Terse,      # avoid name output (where feasible)
          freezer    => $Freezer,    # name of Freezer method for objects
          toaster    => $Toaster,    # name of method to revive objects
          deepcopy   => $Deepcopy,   # dont cross-ref, except to stop recursion
          quotekeys  => $Quotekeys,  # quote hash keys
          'bless'    => $Bless,    # keyword to use for "bless"
  #        expdepth   => $Expdepth,   # cutoff depth for explicit dumping
          maxdepth   => $Maxdepth,   # depth beyond which we give up
          useperl    => $Useperl,    # use the pure Perl implementation
          sortkeys   => $Sortkeys,   # flag or filter for sorting hash keys
          deparse    => $Deparse,    # use B::Deparse for coderefs
          noseen     => $Sparseseen, # do not populate the seen hash unless necessary
         };
  
    if ($Indent > 0) {
      $s->{xpad} = "  ";
      $s->{sep} = "\n";
    }
    return bless($s, $c);
  }
  
  # Packed numeric addresses take less memory. Plus pack is faster than sprintf
  
  # Most users of current versions of Data::Dumper will be 5.008 or later.
  # Anyone on 5.6.1 and 5.6.2 upgrading will be rare (particularly judging by
  # the bug reports from users on those platforms), so for the common case avoid
  # complexity, and avoid even compiling the unneeded code.
  
  sub init_refaddr_format {
  }
  
  sub format_refaddr {
      require Scalar::Util;
      pack "J", Scalar::Util::refaddr(shift);
  };
  
  if ($] < 5.008) {
      eval <<'EOC' or die;
      no warnings 'redefine';
      my $refaddr_format;
      sub init_refaddr_format {
          require Config;
          my $f = $Config::Config{uvxformat};
          $f =~ tr/"//d;
          $refaddr_format = "0x%" . $f;
      }
  
      sub format_refaddr {
          require Scalar::Util;
          sprintf $refaddr_format, Scalar::Util::refaddr(shift);
      }
  
      1
  EOC
  }
  
  #
  # add-to or query the table of already seen references
  #
  sub Seen {
    my($s, $g) = @_;
    if (defined($g) && (ref($g) eq 'HASH'))  {
      init_refaddr_format();
      my($k, $v, $id);
      while (($k, $v) = each %$g) {
        if (defined $v) {
          if (ref $v) {
            $id = format_refaddr($v);
            if ($k =~ /^[*](.*)$/) {
              $k = (ref $v eq 'ARRAY') ? ( "\\\@" . $1 ) :
                   (ref $v eq 'HASH')  ? ( "\\\%" . $1 ) :
                   (ref $v eq 'CODE')  ? ( "\\\&" . $1 ) :
                   (   "\$" . $1 ) ;
            }
            elsif ($k !~ /^\$/) {
              $k = "\$" . $k;
            }
            $s->{seen}{$id} = [$k, $v];
          }
          else {
            carp "Only refs supported, ignoring non-ref item \$$k";
          }
        }
        else {
          carp "Value of ref must be defined; ignoring undefined item \$$k";
        }
      }
      return $s;
    }
    else {
      return map { @$_ } values %{$s->{seen}};
    }
  }
  
  #
  # set or query the values to be dumped
  #
  sub Values {
    my($s, $v) = @_;
    if (defined($v)) {
      if (ref($v) eq 'ARRAY')  {
        $s->{todump} = [@$v];        # make a copy
        return $s;
      }
      else {
        croak "Argument to Values, if provided, must be array ref";
      }
    }
    else {
      return @{$s->{todump}};
    }
  }
  
  #
  # set or query the names of the values to be dumped
  #
  sub Names {
    my($s, $n) = @_;
    if (defined($n)) {
      if (ref($n) eq 'ARRAY') {
        $s->{names} = [@$n];         # make a copy
        return $s;
      }
      else {
        croak "Argument to Names, if provided, must be array ref";
      }
    }
    else {
      return @{$s->{names}};
    }
  }
  
  sub DESTROY {}
  
  sub Dump {
      return &Dumpxs
      unless $Data::Dumper::Useperl || (ref($_[0]) && $_[0]->{useperl}) ||
             $Data::Dumper::Useqq   || (ref($_[0]) && $_[0]->{useqq}) ||
             $Data::Dumper::Deparse || (ref($_[0]) && $_[0]->{deparse});
      return &Dumpperl;
  }
  
  #
  # dump the refs in the current dumper object.
  # expects same args as new() if called via package name.
  #
  sub Dumpperl {
    my($s) = shift;
    my(@out, $val, $name);
    my($i) = 0;
    local(@post);
    init_refaddr_format();
  
    $s = $s->new(@_) unless ref $s;
  
    for $val (@{$s->{todump}}) {
      @post = ();
      $name = $s->{names}[$i++];
      $name = $s->_refine_name($name, $val, $i);
  
      my $valstr;
      {
        local($s->{apad}) = $s->{apad};
        $s->{apad} .= ' ' x (length($name) + 3) if $s->{indent} >= 2 and !$s->{terse};
        $valstr = $s->_dump($val, $name);
      }
  
      $valstr = "$name = " . $valstr . ';' if @post or !$s->{terse};
      my $out = $s->_compose_out($valstr, \@post);
  
      push @out, $out;
    }
    return wantarray ? @out : join('', @out);
  }
  
  # wrap string in single quotes (escaping if needed)
  sub _quote {
      my $val = shift;
      $val =~ s/([\\\'])/\\$1/g;
      return  "'" . $val .  "'";
  }
  
  # Old Perls (5.14-) have trouble resetting vstring magic when it is no
  # longer valid.
  use constant _bad_vsmg => defined &_vstring && (_vstring(~v0)||'') eq "v0";
  
  #
  # twist, toil and turn;
  # and recurse, of course.
  # sometimes sordidly;
  # and curse if no recourse.
  #
  sub _dump {
    my($s, $val, $name) = @_;
    my($out, $type, $id, $sname);
  
    $type = ref $val;
    $out = "";
  
    if ($type) {
  
      # Call the freezer method if it's specified and the object has the
      # method.  Trap errors and warn() instead of die()ing, like the XS
      # implementation.
      my $freezer = $s->{freezer};
      if ($freezer and UNIVERSAL::can($val, $freezer)) {
        eval { $val->$freezer() };
        warn "WARNING(Freezer method call failed): $@" if $@;
      }
  
      require Scalar::Util;
      my $realpack = Scalar::Util::blessed($val);
      my $realtype = $realpack ? Scalar::Util::reftype($val) : ref $val;
      $id = format_refaddr($val);
  
      # Note: By this point $name is always defined and of non-zero length.
      # Keep a tab on it so that we dont fall into recursive pit.
      if (exists $s->{seen}{$id}) {
        if ($s->{purity} and $s->{level} > 0) {
          $out = ($realtype eq 'HASH')  ? '{}' :
                 ($realtype eq 'ARRAY') ? '[]' :
                 'do{my $o}' ;
          push @post, $name . " = " . $s->{seen}{$id}[0];
        }
        else {
          $out = $s->{seen}{$id}[0];
          if ($name =~ /^([\@\%])/) {
            my $start = $1;
            if ($out =~ /^\\$start/) {
              $out = substr($out, 1);
            }
            else {
              $out = $start . '{' . $out . '}';
            }
          }
        }
        return $out;
      }
      else {
        # store our name
        $s->{seen}{$id} = [ (
            ($name =~ /^[@%]/)
              ? ('\\' . $name )
              : ($realtype eq 'CODE' and $name =~ /^[*](.*)$/)
                ? ('\\&' . $1 )
                : $name
          ), $val ];
      }
      my $no_bless = 0;
      my $is_regex = 0;
      if ( $realpack and ($] >= 5.009005 ? re::is_regexp($val) : $realpack eq 'Regexp') ) {
          $is_regex = 1;
          $no_bless = $realpack eq 'Regexp';
      }
  
      # If purity is not set and maxdepth is set, then check depth:
      # if we have reached maximum depth, return the string
      # representation of the thing we are currently examining
      # at this depth (i.e., 'Foo=ARRAY(0xdeadbeef)').
      if (!$s->{purity}
        and defined($s->{maxdepth})
        and $s->{maxdepth} > 0
        and $s->{level} >= $s->{maxdepth})
      {
        return qq['$val'];
      }
  
      # we have a blessed ref
      my ($blesspad);
      if ($realpack and !$no_bless) {
        $out = $s->{'bless'} . '( ';
        $blesspad = $s->{apad};
        $s->{apad} .= '       ' if ($s->{indent} >= 2);
      }
  
      $s->{level}++;
      my $ipad = $s->{xpad} x $s->{level};
  
      if ($is_regex) {
          my $pat;
          # This really sucks, re:regexp_pattern is in ext/re/re.xs and not in
          # universal.c, and even worse we cant just require that re to be loaded
          # we *have* to use() it.
          # We should probably move it to universal.c for 5.10.1 and fix this.
          # Currently we only use re::regexp_pattern when the re is blessed into another
          # package. This has the disadvantage of meaning that a DD dump won't round trip
          # as the pattern will be repeatedly wrapped with the same modifiers.
          # This is an aesthetic issue so we will leave it for now, but we could use
          # regexp_pattern() in list context to get the modifiers separately.
          # But since this means loading the full debugging engine in process we wont
          # bother unless its necessary for accuracy.
          if (($realpack ne 'Regexp') && defined(*re::regexp_pattern{CODE})) {
            $pat = re::regexp_pattern($val);
          }
          else {
            $pat = "$val";
          }
          $pat =~ s <(\\.)|/> { $1 || '\\/' }ge;
          $out .= "qr/$pat/";
      }
      elsif ($realtype eq 'SCALAR' || $realtype eq 'REF'
      || $realtype eq 'VSTRING') {
        if ($realpack) {
          $out .= 'do{\\(my $o = ' . $s->_dump($$val, "\${$name}") . ')}';
        }
        else {
          $out .= '\\' . $s->_dump($$val, "\${$name}");
        }
      }
      elsif ($realtype eq 'GLOB') {
        $out .= '\\' . $s->_dump($$val, "*{$name}");
      }
      elsif ($realtype eq 'ARRAY') {
        my($pad, $mname);
        my($i) = 0;
        $out .= ($name =~ /^\@/) ? '(' : '[';
        $pad = $s->{sep} . $s->{pad} . $s->{apad};
        ($name =~ /^\@(.*)$/) ? ($mname = "\$" . $1) :
      # omit -> if $foo->[0]->{bar}, but not ${$foo->[0]}->{bar}
          ($name =~ /^\\?[\%\@\*\$][^{].*[]}]$/) ? ($mname = $name) :
          ($mname = $name . '->');
        $mname .= '->' if $mname =~ /^\*.+\{[A-Z]+\}$/;
        for my $v (@$val) {
          $sname = $mname . '[' . $i . ']';
          $out .= $pad . $ipad . '#' . $i
            if $s->{indent} >= 3;
          $out .= $pad . $ipad . $s->_dump($v, $sname);
          $out .= "," if $i++ < $#$val;
        }
        $out .= $pad . ($s->{xpad} x ($s->{level} - 1)) if $i;
        $out .= ($name =~ /^\@/) ? ')' : ']';
      }
      elsif ($realtype eq 'HASH') {
        my ($k, $v, $pad, $lpad, $mname, $pair);
        $out .= ($name =~ /^\%/) ? '(' : '{';
        $pad = $s->{sep} . $s->{pad} . $s->{apad};
        $lpad = $s->{apad};
        $pair = $s->{pair};
        ($name =~ /^\%(.*)$/) ? ($mname = "\$" . $1) :
      # omit -> if $foo->[0]->{bar}, but not ${$foo->[0]}->{bar}
          ($name =~ /^\\?[\%\@\*\$][^{].*[]}]$/) ? ($mname = $name) :
          ($mname = $name . '->');
        $mname .= '->' if $mname =~ /^\*.+\{[A-Z]+\}$/;
        my $sortkeys = defined($s->{sortkeys}) ? $s->{sortkeys} : '';
        my $keys = [];
        if ($sortkeys) {
          if (ref($s->{sortkeys}) eq 'CODE') {
            $keys = $s->{sortkeys}($val);
            unless (ref($keys) eq 'ARRAY') {
              carp "Sortkeys subroutine did not return ARRAYREF";
              $keys = [];
            }
          }
          else {
            $keys = [ sort keys %$val ];
          }
        }
  
        # Ensure hash iterator is reset
        keys(%$val);
  
        my $key;
        while (($k, $v) = ! $sortkeys ? (each %$val) :
           @$keys ? ($key = shift(@$keys), $val->{$key}) :
           () )
        {
          my $nk = $s->_dump($k, "");
          $nk = $1
            if !$s->{quotekeys} and $nk =~ /^[\"\']([A-Za-z_]\w*)[\"\']$/;
          $sname = $mname . '{' . $nk . '}';
          $out .= $pad . $ipad . $nk . $pair;
  
          # temporarily alter apad
          $s->{apad} .= (" " x (length($nk) + 4))
            if $s->{indent} >= 2;
          $out .= $s->_dump($val->{$k}, $sname) . ",";
          $s->{apad} = $lpad
            if $s->{indent} >= 2;
        }
        if (substr($out, -1) eq ',') {
          chop $out;
          $out .= $pad . ($s->{xpad} x ($s->{level} - 1));
        }
        $out .= ($name =~ /^\%/) ? ')' : '}';
      }
      elsif ($realtype eq 'CODE') {
        if ($s->{deparse}) {
          require B::Deparse;
          my $sub =  'sub ' . (B::Deparse->new)->coderef2text($val);
          $pad    =  $s->{sep} . $s->{pad} . $s->{apad} . $s->{xpad} x ($s->{level} - 1);
          $sub    =~ s/\n/$pad/gse;
          $out   .=  $sub;
        }
        else {
          $out .= 'sub { "DUMMY" }';
          carp "Encountered CODE ref, using dummy placeholder" if $s->{purity};
        }
      }
      else {
        croak "Can't handle '$realtype' type";
      }
  
      if ($realpack and !$no_bless) { # we have a blessed ref
        $out .= ', ' . _quote($realpack) . ' )';
        $out .= '->' . $s->{toaster} . '()'
          if $s->{toaster} ne '';
        $s->{apad} = $blesspad;
      }
      $s->{level}--;
    }
    else {                                 # simple scalar
  
      my $ref = \$_[1];
      my $v;
      # first, catalog the scalar
      if ($name ne '') {
        $id = format_refaddr($ref);
        if (exists $s->{seen}{$id}) {
          if ($s->{seen}{$id}[2]) {
            $out = $s->{seen}{$id}[0];
            #warn "[<$out]\n";
            return "\${$out}";
          }
        }
        else {
          #warn "[>\\$name]\n";
          $s->{seen}{$id} = ["\\$name", $ref];
        }
      }
      $ref = \$val;
      if (ref($ref) eq 'GLOB') {  # glob
        my $name = substr($val, 1);
        if ($name =~ /^[A-Za-z_][\w:]*$/ && $name ne 'main::') {
          $name =~ s/^main::/::/;
          $sname = $name;
        }
        else {
          $sname = $s->_dump(
            $name eq 'main::' || $] < 5.007 && $name eq "main::\0"
              ? ''
              : $name,
            "",
          );
          $sname = '{' . $sname . '}';
        }
        if ($s->{purity}) {
          my $k;
          local ($s->{level}) = 0;
          for $k (qw(SCALAR ARRAY HASH)) {
            my $gval = *$val{$k};
            next unless defined $gval;
            next if $k eq "SCALAR" && ! defined $$gval;  # always there
  
            # _dump can push into @post, so we hold our place using $postlen
            my $postlen = scalar @post;
            $post[$postlen] = "\*$sname = ";
            local ($s->{apad}) = " " x length($post[$postlen]) if $s->{indent} >= 2;
            $post[$postlen] .= $s->_dump($gval, "\*$sname\{$k\}");
          }
        }
        $out .= '*' . $sname;
      }
      elsif (!defined($val)) {
        $out .= "undef";
      }
      elsif (defined &_vstring and $v = _vstring($val)
        and !_bad_vsmg || eval $v eq $val) {
        $out .= $v;
      }
      elsif (!defined &_vstring
         and ref $ref eq 'VSTRING' || eval{Scalar::Util::isvstring($val)}) {
        $out .= sprintf "%vd", $val;
      }
      elsif ($val =~ /^(?:0|-?[1-9]\d{0,8})\z/) { # safe decimal number
        $out .= $val;
      }
      else {                 # string
        if ($s->{useqq} or $val =~ tr/\0-\377//c) {
          # Fall back to qq if there's Unicode
          $out .= qquote($val, $s->{useqq});
        }
        else {
          $out .= _quote($val);
        }
      }
    }
    if ($id) {
      # if we made it this far, $id was added to seen list at current
      # level, so remove it to get deep copies
      if ($s->{deepcopy}) {
        delete($s->{seen}{$id});
      }
      elsif ($name) {
        $s->{seen}{$id}[2] = 1;
      }
    }
    return $out;
  }
  
  #
  # non-OO style of earlier version
  #
  sub Dumper {
    return Data::Dumper->Dump([@_]);
  }
  
  # compat stub
  sub DumperX {
    return Data::Dumper->Dumpxs([@_], []);
  }
  
  #
  # reset the "seen" cache
  #
  sub Reset {
    my($s) = shift;
    $s->{seen} = {};
    return $s;
  }
  
  sub Indent {
    my($s, $v) = @_;
    if (defined($v)) {
      if ($v == 0) {
        $s->{xpad} = "";
        $s->{sep} = "";
      }
      else {
        $s->{xpad} = "  ";
        $s->{sep} = "\n";
      }
      $s->{indent} = $v;
      return $s;
    }
    else {
      return $s->{indent};
    }
  }
  
  sub Pair {
      my($s, $v) = @_;
      defined($v) ? (($s->{pair} = $v), return $s) : $s->{pair};
  }
  
  sub Pad {
    my($s, $v) = @_;
    defined($v) ? (($s->{pad} = $v), return $s) : $s->{pad};
  }
  
  sub Varname {
    my($s, $v) = @_;
    defined($v) ? (($s->{varname} = $v), return $s) : $s->{varname};
  }
  
  sub Purity {
    my($s, $v) = @_;
    defined($v) ? (($s->{purity} = $v), return $s) : $s->{purity};
  }
  
  sub Useqq {
    my($s, $v) = @_;
    defined($v) ? (($s->{useqq} = $v), return $s) : $s->{useqq};
  }
  
  sub Terse {
    my($s, $v) = @_;
    defined($v) ? (($s->{terse} = $v), return $s) : $s->{terse};
  }
  
  sub Freezer {
    my($s, $v) = @_;
    defined($v) ? (($s->{freezer} = $v), return $s) : $s->{freezer};
  }
  
  sub Toaster {
    my($s, $v) = @_;
    defined($v) ? (($s->{toaster} = $v), return $s) : $s->{toaster};
  }
  
  sub Deepcopy {
    my($s, $v) = @_;
    defined($v) ? (($s->{deepcopy} = $v), return $s) : $s->{deepcopy};
  }
  
  sub Quotekeys {
    my($s, $v) = @_;
    defined($v) ? (($s->{quotekeys} = $v), return $s) : $s->{quotekeys};
  }
  
  sub Bless {
    my($s, $v) = @_;
    defined($v) ? (($s->{'bless'} = $v), return $s) : $s->{'bless'};
  }
  
  sub Maxdepth {
    my($s, $v) = @_;
    defined($v) ? (($s->{'maxdepth'} = $v), return $s) : $s->{'maxdepth'};
  }
  
  sub Useperl {
    my($s, $v) = @_;
    defined($v) ? (($s->{'useperl'} = $v), return $s) : $s->{'useperl'};
  }
  
  sub Sortkeys {
    my($s, $v) = @_;
    defined($v) ? (($s->{'sortkeys'} = $v), return $s) : $s->{'sortkeys'};
  }
  
  sub Deparse {
    my($s, $v) = @_;
    defined($v) ? (($s->{'deparse'} = $v), return $s) : $s->{'deparse'};
  }
  
  sub Sparseseen {
    my($s, $v) = @_;
    defined($v) ? (($s->{'noseen'} = $v), return $s) : $s->{'noseen'};
  }
  
  # used by qquote below
  my %esc = (
      "\a" => "\\a",
      "\b" => "\\b",
      "\t" => "\\t",
      "\n" => "\\n",
      "\f" => "\\f",
      "\r" => "\\r",
      "\e" => "\\e",
  );
  
  # put a string value in double quotes
  sub qquote {
    local($_) = shift;
    s/([\\\"\@\$])/\\$1/g;
    my $bytes; { use bytes; $bytes = length }
    s/([^\x00-\x7f])/'\x{'.sprintf("%x",ord($1)).'}'/ge if $bytes > length;
    return qq("$_") unless
      /[^ !"\#\$%&'()*+,\-.\/0-9:;<=>?\@A-Z[\\\]^_`a-z{|}~]/;  # fast exit
  
    my $high = shift || "";
    s/([\a\b\t\n\f\r\e])/$esc{$1}/g;
  
    if (ord('^')==94)  { # ascii
      # no need for 3 digits in escape for these
      s/([\0-\037])(?!\d)/'\\'.sprintf('%o',ord($1))/eg;
      s/([\0-\037\177])/'\\'.sprintf('%03o',ord($1))/eg;
      # all but last branch below not supported --BEHAVIOR SUBJECT TO CHANGE--
      if ($high eq "iso8859") {
        s/([\200-\240])/'\\'.sprintf('%o',ord($1))/eg;
      } elsif ($high eq "utf8") {
  #     use utf8;
  #     $str =~ s/([^\040-\176])/sprintf "\\x{%04x}", ord($1)/ge;
      } elsif ($high eq "8bit") {
          # leave it as it is
      } else {
        s/([\200-\377])/'\\'.sprintf('%03o',ord($1))/eg;
        s/([^\040-\176])/sprintf "\\x{%04x}", ord($1)/ge;
      }
    }
    else { # ebcdic
        s{([^ !"\#\$%&'()*+,\-.\/0-9:;<=>?\@A-Z[\\\]^_`a-z{|}~])(?!\d)}
         {my $v = ord($1); '\\'.sprintf(($v <= 037 ? '%o' : '%03o'), $v)}eg;
        s{([^ !"\#\$%&'()*+,\-.\/0-9:;<=>?\@A-Z[\\\]^_`a-z{|}~])}
         {'\\'.sprintf('%03o',ord($1))}eg;
    }
  
    return qq("$_");
  }
  
  # helper sub to sort hash keys in Perl < 5.8.0 where we don't have
  # access to sortsv() from XS
  sub _sortkeys { [ sort keys %{$_[0]} ] }
  
  sub _refine_name {
      my $s = shift;
      my ($name, $val, $i) = @_;
      if (defined $name) {
        if ($name =~ /^[*](.*)$/) {
          if (defined $val) {
              $name = (ref $val eq 'ARRAY') ? ( "\@" . $1 ) :
                (ref $val eq 'HASH')  ? ( "\%" . $1 ) :
                (ref $val eq 'CODE')  ? ( "\*" . $1 ) :
                ( "\$" . $1 ) ;
          }
          else {
            $name = "\$" . $1;
          }
        }
        elsif ($name !~ /^\$/) {
          $name = "\$" . $name;
        }
      }
      else { # no names provided
        $name = "\$" . $s->{varname} . $i;
      }
      return $name;
  }
  
  sub _compose_out {
      my $s = shift;
      my ($valstr, $postref) = @_;
      my $out = "";
      $out .= $s->{pad} . $valstr . $s->{sep};
      if (@{$postref}) {
          $out .= $s->{pad} .
              join(';' . $s->{sep} . $s->{pad}, @{$postref}) .
              ';' .
              $s->{sep};
      }
      return $out;
  }
  
  1;
  __END__
  
  =head1 NAME
  
  Data::Dumper - stringified perl data structures, suitable for both printing and C<eval>
  
  =head1 SYNOPSIS
  
      use Data::Dumper;
  
      # simple procedural interface
      print Dumper($foo, $bar);
  
      # extended usage with names
      print Data::Dumper->Dump([$foo, $bar], [qw(foo *ary)]);
  
      # configuration variables
      {
        local $Data::Dumper::Purity = 1;
        eval Data::Dumper->Dump([$foo, $bar], [qw(foo *ary)]);
      }
  
      # OO usage
      $d = Data::Dumper->new([$foo, $bar], [qw(foo *ary)]);
         ...
      print $d->Dump;
         ...
      $d->Purity(1)->Terse(1)->Deepcopy(1);
      eval $d->Dump;
  
  
  =head1 DESCRIPTION
  
  Given a list of scalars or reference variables, writes out their contents in
  perl syntax. The references can also be objects.  The content of each
  variable is output in a single Perl statement.  Handles self-referential
  structures correctly.
  
  The return value can be C<eval>ed to get back an identical copy of the
  original reference structure.  (Please do consider the security implications
  of eval'ing code from untrusted sources!)
  
  Any references that are the same as one of those passed in will be named
  C<$VAR>I<n> (where I<n> is a numeric suffix), and other duplicate references
  to substructures within C<$VAR>I<n> will be appropriately labeled using arrow
  notation.  You can specify names for individual values to be dumped if you
  use the C<Dump()> method, or you can change the default C<$VAR> prefix to
  something else.  See C<$Data::Dumper::Varname> and C<$Data::Dumper::Terse>
  below.
  
  The default output of self-referential structures can be C<eval>ed, but the
  nested references to C<$VAR>I<n> will be undefined, since a recursive
  structure cannot be constructed using one Perl statement.  You should set the
  C<Purity> flag to 1 to get additional statements that will correctly fill in
  these references.  Moreover, if C<eval>ed when strictures are in effect,
  you need to ensure that any variables it accesses are previously declared.
  
  In the extended usage form, the references to be dumped can be given
  user-specified names.  If a name begins with a C<*>, the output will
  describe the dereferenced type of the supplied reference for hashes and
  arrays, and coderefs.  Output of names will be avoided where possible if
  the C<Terse> flag is set.
  
  In many cases, methods that are used to set the internal state of the
  object will return the object itself, so method calls can be conveniently
  chained together.
  
  Several styles of output are possible, all controlled by setting
  the C<Indent> flag.  See L<Configuration Variables or Methods> below
  for details.
  
  
  =head2 Methods
  
  =over 4
  
  =item I<PACKAGE>->new(I<ARRAYREF [>, I<ARRAYREF]>)
  
  Returns a newly created C<Data::Dumper> object.  The first argument is an
  anonymous array of values to be dumped.  The optional second argument is an
  anonymous array of names for the values.  The names need not have a leading
  C<$> sign, and must be comprised of alphanumeric characters.  You can begin
  a name with a C<*> to specify that the dereferenced type must be dumped
  instead of the reference itself, for ARRAY and HASH references.
  
  The prefix specified by C<$Data::Dumper::Varname> will be used with a
  numeric suffix if the name for a value is undefined.
  
  Data::Dumper will catalog all references encountered while dumping the
  values. Cross-references (in the form of names of substructures in perl
  syntax) will be inserted at all possible points, preserving any structural
  interdependencies in the original set of values.  Structure traversal is
  depth-first,  and proceeds in order from the first supplied value to
  the last.
  
  =item I<$OBJ>->Dump  I<or>  I<PACKAGE>->Dump(I<ARRAYREF [>, I<ARRAYREF]>)
  
  Returns the stringified form of the values stored in the object (preserving
  the order in which they were supplied to C<new>), subject to the
  configuration options below.  In a list context, it returns a list
  of strings corresponding to the supplied values.
  
  The second form, for convenience, simply calls the C<new> method on its
  arguments before dumping the object immediately.
  
  =item I<$OBJ>->Seen(I<[HASHREF]>)
  
  Queries or adds to the internal table of already encountered references.
  You must use C<Reset> to explicitly clear the table if needed.  Such
  references are not dumped; instead, their names are inserted wherever they
  are encountered subsequently.  This is useful especially for properly
  dumping subroutine references.
  
  Expects an anonymous hash of name => value pairs.  Same rules apply for names
  as in C<new>.  If no argument is supplied, will return the "seen" list of
  name => value pairs, in a list context.  Otherwise, returns the object
  itself.
  
  =item I<$OBJ>->Values(I<[ARRAYREF]>)
  
  Queries or replaces the internal array of values that will be dumped.  When
  called without arguments, returns the values as a list.  When called with a
  reference to an array of replacement values, returns the object itself.  When
  called with any other type of argument, dies.
  
  =item I<$OBJ>->Names(I<[ARRAYREF]>)
  
  Queries or replaces the internal array of user supplied names for the values
  that will be dumped.  When called without arguments, returns the names.  When
  called with an array of replacement names, returns the object itself.  If the
  number of replacment names exceeds the number of values to be named, the
  excess names will not be used.  If the number of replacement names falls short
  of the number of values to be named, the list of replacment names will be
  exhausted and remaining values will not be renamed.  When
  called with any other type of argument, dies.
  
  =item I<$OBJ>->Reset
  
  Clears the internal table of "seen" references and returns the object
  itself.
  
  =back
  
  =head2 Functions
  
  =over 4
  
  =item Dumper(I<LIST>)
  
  Returns the stringified form of the values in the list, subject to the
  configuration options below.  The values will be named C<$VAR>I<n> in the
  output, where I<n> is a numeric suffix.  Will return a list of strings
  in a list context.
  
  =back
  
  =head2 Configuration Variables or Methods
  
  Several configuration variables can be used to control the kind of output
  generated when using the procedural interface.  These variables are usually
  C<local>ized in a block so that other parts of the code are not affected by
  the change.
  
  These variables determine the default state of the object created by calling
  the C<new> method, but cannot be used to alter the state of the object
  thereafter.  The equivalent method names should be used instead to query
  or set the internal state of the object.
  
  The method forms return the object itself when called with arguments,
  so that they can be chained together nicely.
  
  =over 4
  
  =item *
  
  $Data::Dumper::Indent  I<or>  I<$OBJ>->Indent(I<[NEWVAL]>)
  
  Controls the style of indentation.  It can be set to 0, 1, 2 or 3.  Style 0
  spews output without any newlines, indentation, or spaces between list
  items.  It is the most compact format possible that can still be called
  valid perl.  Style 1 outputs a readable form with newlines but no fancy
  indentation (each level in the structure is simply indented by a fixed
  amount of whitespace).  Style 2 (the default) outputs a very readable form
  which takes into account the length of hash keys (so the hash value lines
  up).  Style 3 is like style 2, but also annotates the elements of arrays
  with their index (but the comment is on its own line, so array output
  consumes twice the number of lines).  Style 2 is the default.
  
  =item *
  
  $Data::Dumper::Purity  I<or>  I<$OBJ>->Purity(I<[NEWVAL]>)
  
  Controls the degree to which the output can be C<eval>ed to recreate the
  supplied reference structures.  Setting it to 1 will output additional perl
  statements that will correctly recreate nested references.  The default is
  0.
  
  =item *
  
  $Data::Dumper::Pad  I<or>  I<$OBJ>->Pad(I<[NEWVAL]>)
  
  Specifies the string that will be prefixed to every line of the output.
  Empty string by default.
  
  =item *
  
  $Data::Dumper::Varname  I<or>  I<$OBJ>->Varname(I<[NEWVAL]>)
  
  Contains the prefix to use for tagging variable names in the output. The
  default is "VAR".
  
  =item *
  
  $Data::Dumper::Useqq  I<or>  I<$OBJ>->Useqq(I<[NEWVAL]>)
  
  When set, enables the use of double quotes for representing string values.
  Whitespace other than space will be represented as C<[\n\t\r]>, "unsafe"
  characters will be backslashed, and unprintable characters will be output as
  quoted octal integers.  Since setting this variable imposes a performance
  penalty, the default is 0.  C<Dump()> will run slower if this flag is set,
  since the fast XSUB implementation doesn't support it yet.
  
  =item *
  
  $Data::Dumper::Terse  I<or>  I<$OBJ>->Terse(I<[NEWVAL]>)
  
  When set, Data::Dumper will emit single, non-self-referential values as
  atoms/terms rather than statements.  This means that the C<$VAR>I<n> names
  will be avoided where possible, but be advised that such output may not
  always be parseable by C<eval>.
  
  =item *
  
  $Data::Dumper::Freezer  I<or>  $I<OBJ>->Freezer(I<[NEWVAL]>)
  
  Can be set to a method name, or to an empty string to disable the feature.
  Data::Dumper will invoke that method via the object before attempting to
  stringify it.  This method can alter the contents of the object (if, for
  instance, it contains data allocated from C), and even rebless it in a
  different package.  The client is responsible for making sure the specified
  method can be called via the object, and that the object ends up containing
  only perl data types after the method has been called.  Defaults to an empty
  string.
  
  If an object does not support the method specified (determined using
  UNIVERSAL::can()) then the call will be skipped.  If the method dies a
  warning will be generated.
  
  =item *
  
  $Data::Dumper::Toaster  I<or>  $I<OBJ>->Toaster(I<[NEWVAL]>)
  
  Can be set to a method name, or to an empty string to disable the feature.
  Data::Dumper will emit a method call for any objects that are to be dumped
  using the syntax C<bless(DATA, CLASS)-E<gt>METHOD()>.  Note that this means that
  the method specified will have to perform any modifications required on the
  object (like creating new state within it, and/or reblessing it in a
  different package) and then return it.  The client is responsible for making
  sure the method can be called via the object, and that it returns a valid
  object.  Defaults to an empty string.
  
  =item *
  
  $Data::Dumper::Deepcopy  I<or>  $I<OBJ>->Deepcopy(I<[NEWVAL]>)
  
  Can be set to a boolean value to enable deep copies of structures.
  Cross-referencing will then only be done when absolutely essential
  (i.e., to break reference cycles).  Default is 0.
  
  =item *
  
  $Data::Dumper::Quotekeys  I<or>  $I<OBJ>->Quotekeys(I<[NEWVAL]>)
  
  Can be set to a boolean value to control whether hash keys are quoted.
  A defined false value will avoid quoting hash keys when it looks like a simple
  string.  Default is 1, which will always enclose hash keys in quotes.
  
  =item *
  
  $Data::Dumper::Bless  I<or>  $I<OBJ>->Bless(I<[NEWVAL]>)
  
  Can be set to a string that specifies an alternative to the C<bless>
  builtin operator used to create objects.  A function with the specified
  name should exist, and should accept the same arguments as the builtin.
  Default is C<bless>.
  
  =item *
  
  $Data::Dumper::Pair  I<or>  $I<OBJ>->Pair(I<[NEWVAL]>)
  
  Can be set to a string that specifies the separator between hash keys
  and values. To dump nested hash, array and scalar values to JavaScript,
  use: C<$Data::Dumper::Pair = ' : ';>. Implementing C<bless> in JavaScript
  is left as an exercise for the reader.
  A function with the specified name exists, and accepts the same arguments
  as the builtin.
  
  Default is: C< =E<gt> >.
  
  =item *
  
  $Data::Dumper::Maxdepth  I<or>  $I<OBJ>->Maxdepth(I<[NEWVAL]>)
  
  Can be set to a positive integer that specifies the depth beyond which
  we don't venture into a structure.  Has no effect when
  C<Data::Dumper::Purity> is set.  (Useful in debugger when we often don't
  want to see more than enough).  Default is 0, which means there is
  no maximum depth.
  
  =item *
  
  $Data::Dumper::Useperl  I<or>  $I<OBJ>->Useperl(I<[NEWVAL]>)
  
  Can be set to a boolean value which controls whether the pure Perl
  implementation of C<Data::Dumper> is used. The C<Data::Dumper> module is
  a dual implementation, with almost all functionality written in both
  pure Perl and also in XS ('C'). Since the XS version is much faster, it
  will always be used if possible. This option lets you override the
  default behavior, usually for testing purposes only. Default is 0, which
  means the XS implementation will be used if possible.
  
  =item *
  
  $Data::Dumper::Sortkeys  I<or>  $I<OBJ>->Sortkeys(I<[NEWVAL]>)
  
  Can be set to a boolean value to control whether hash keys are dumped in
  sorted order. A true value will cause the keys of all hashes to be
  dumped in Perl's default sort order. Can also be set to a subroutine
  reference which will be called for each hash that is dumped. In this
  case C<Data::Dumper> will call the subroutine once for each hash,
  passing it the reference of the hash. The purpose of the subroutine is
  to return a reference to an array of the keys that will be dumped, in
  the order that they should be dumped. Using this feature, you can
  control both the order of the keys, and which keys are actually used. In
  other words, this subroutine acts as a filter by which you can exclude
  certain keys from being dumped. Default is 0, which means that hash keys
  are not sorted.
  
  =item *
  
  $Data::Dumper::Deparse  I<or>  $I<OBJ>->Deparse(I<[NEWVAL]>)
  
  Can be set to a boolean value to control whether code references are
  turned into perl source code. If set to a true value, C<B::Deparse>
  will be used to get the source of the code reference. Using this option
  will force using the Perl implementation of the dumper, since the fast
  XSUB implementation doesn't support it.
  
  Caution : use this option only if you know that your coderefs will be
  properly reconstructed by C<B::Deparse>.
  
  =item *
  
  $Data::Dumper::Sparseseen I<or>  $I<OBJ>->Sparseseen(I<[NEWVAL]>)
  
  By default, Data::Dumper builds up the "seen" hash of scalars that
  it has encountered during serialization. This is very expensive.
  This seen hash is necessary to support and even just detect circular
  references. It is exposed to the user via the C<Seen()> call both
  for writing and reading.
  
  If you, as a user, do not need explicit access to the "seen" hash,
  then you can set the C<Sparseseen> option to allow Data::Dumper
  to eschew building the "seen" hash for scalars that are known not
  to possess more than one reference. This speeds up serialization
  considerably if you use the XS implementation.
  
  Note: If you turn on C<Sparseseen>, then you must not rely on the
  content of the seen hash since its contents will be an
  implementation detail!
  
  =back
  
  =head2 Exports
  
  =over 4
  
  =item Dumper
  
  =back
  
  =head1 EXAMPLES
  
  Run these code snippets to get a quick feel for the behavior of this
  module.  When you are through with these examples, you may want to
  add or change the various configuration variables described above,
  to see their behavior.  (See the testsuite in the Data::Dumper
  distribution for more examples.)
  
  
      use Data::Dumper;
  
      package Foo;
      sub new {bless {'a' => 1, 'b' => sub { return "foo" }}, $_[0]};
  
      package Fuz;                       # a weird REF-REF-SCALAR object
      sub new {bless \($_ = \ 'fu\'z'), $_[0]};
  
      package main;
      $foo = Foo->new;
      $fuz = Fuz->new;
      $boo = [ 1, [], "abcd", \*foo,
               {1 => 'a', 023 => 'b', 0x45 => 'c'},
               \\"p\q\'r", $foo, $fuz];
  
      ########
      # simple usage
      ########
  
      $bar = eval(Dumper($boo));
      print($@) if $@;
      print Dumper($boo), Dumper($bar);  # pretty print (no array indices)
  
      $Data::Dumper::Terse = 1;        # don't output names where feasible
      $Data::Dumper::Indent = 0;       # turn off all pretty print
      print Dumper($boo), "\n";
  
      $Data::Dumper::Indent = 1;       # mild pretty print
      print Dumper($boo);
  
      $Data::Dumper::Indent = 3;       # pretty print with array indices
      print Dumper($boo);
  
      $Data::Dumper::Useqq = 1;        # print strings in double quotes
      print Dumper($boo);
  
      $Data::Dumper::Pair = " : ";     # specify hash key/value separator
      print Dumper($boo);
  
  
      ########
      # recursive structures
      ########
  
      @c = ('c');
      $c = \@c;
      $b = {};
      $a = [1, $b, $c];
      $b->{a} = $a;
      $b->{b} = $a->[1];
      $b->{c} = $a->[2];
      print Data::Dumper->Dump([$a,$b,$c], [qw(a b c)]);
  
  
      $Data::Dumper::Purity = 1;         # fill in the holes for eval
      print Data::Dumper->Dump([$a, $b], [qw(*a b)]); # print as @a
      print Data::Dumper->Dump([$b, $a], [qw(*b a)]); # print as %b
  
  
      $Data::Dumper::Deepcopy = 1;       # avoid cross-refs
      print Data::Dumper->Dump([$b, $a], [qw(*b a)]);
  
  
      $Data::Dumper::Purity = 0;         # avoid cross-refs
      print Data::Dumper->Dump([$b, $a], [qw(*b a)]);
  
      ########
      # deep structures
      ########
  
      $a = "pearl";
      $b = [ $a ];
      $c = { 'b' => $b };
      $d = [ $c ];
      $e = { 'd' => $d };
      $f = { 'e' => $e };
      print Data::Dumper->Dump([$f], [qw(f)]);
  
      $Data::Dumper::Maxdepth = 3;       # no deeper than 3 refs down
      print Data::Dumper->Dump([$f], [qw(f)]);
  
  
      ########
      # object-oriented usage
      ########
  
      $d = Data::Dumper->new([$a,$b], [qw(a b)]);
      $d->Seen({'*c' => $c});            # stash a ref without printing it
      $d->Indent(3);
      print $d->Dump;
      $d->Reset->Purity(0);              # empty the seen cache
      print join "----\n", $d->Dump;
  
  
      ########
      # persistence
      ########
  
      package Foo;
      sub new { bless { state => 'awake' }, shift }
      sub Freeze {
          my $s = shift;
          print STDERR "preparing to sleep\n";
          $s->{state} = 'asleep';
          return bless $s, 'Foo::ZZZ';
      }
  
      package Foo::ZZZ;
      sub Thaw {
          my $s = shift;
          print STDERR "waking up\n";
          $s->{state} = 'awake';
          return bless $s, 'Foo';
      }
  
      package main;
      use Data::Dumper;
      $a = Foo->new;
      $b = Data::Dumper->new([$a], ['c']);
      $b->Freezer('Freeze');
      $b->Toaster('Thaw');
      $c = $b->Dump;
      print $c;
      $d = eval $c;
      print Data::Dumper->Dump([$d], ['d']);
  
  
      ########
      # symbol substitution (useful for recreating CODE refs)
      ########
  
      sub foo { print "foo speaking\n" }
      *other = \&foo;
      $bar = [ \&other ];
      $d = Data::Dumper->new([\&other,$bar],['*other','bar']);
      $d->Seen({ '*foo' => \&foo });
      print $d->Dump;
  
  
      ########
      # sorting and filtering hash keys
      ########
  
      $Data::Dumper::Sortkeys = \&my_filter;
      my $foo = { map { (ord, "$_$_$_") } 'I'..'Q' };
      my $bar = { %$foo };
      my $baz = { reverse %$foo };
      print Dumper [ $foo, $bar, $baz ];
  
      sub my_filter {
          my ($hash) = @_;
          # return an array ref containing the hash keys to dump
          # in the order that you want them to be dumped
          return [
            # Sort the keys of %$foo in reverse numeric order
              $hash eq $foo ? (sort {$b <=> $a} keys %$hash) :
            # Only dump the odd number keys of %$bar
              $hash eq $bar ? (grep {$_ % 2} keys %$hash) :
            # Sort keys in default order for all other hashes
              (sort keys %$hash)
          ];
      }
  
  =head1 BUGS
  
  Due to limitations of Perl subroutine call semantics, you cannot pass an
  array or hash.  Prepend it with a C<\> to pass its reference instead.  This
  will be remedied in time, now that Perl has subroutine prototypes.
  For now, you need to use the extended usage form, and prepend the
  name with a C<*> to output it as a hash or array.
  
  C<Data::Dumper> cheats with CODE references.  If a code reference is
  encountered in the structure being processed (and if you haven't set
  the C<Deparse> flag), an anonymous subroutine that
  contains the string '"DUMMY"' will be inserted in its place, and a warning
  will be printed if C<Purity> is set.  You can C<eval> the result, but bear
  in mind that the anonymous sub that gets created is just a placeholder.
  Someday, perl will have a switch to cache-on-demand the string
  representation of a compiled piece of code, I hope.  If you have prior
  knowledge of all the code refs that your data structures are likely
  to have, you can use the C<Seen> method to pre-seed the internal reference
  table and make the dumped output point to them, instead.  See L</EXAMPLES>
  above.
  
  The C<Useqq> and C<Deparse> flags makes Dump() run slower, since the
  XSUB implementation does not support them.
  
  SCALAR objects have the weirdest looking C<bless> workaround.
  
  Pure Perl version of C<Data::Dumper> escapes UTF-8 strings correctly
  only in Perl 5.8.0 and later.
  
  =head2 NOTE
  
  Starting from Perl 5.8.1 different runs of Perl will have different
  ordering of hash keys.  The change was done for greater security,
  see L<perlsec/"Algorithmic Complexity Attacks">.  This means that
  different runs of Perl will have different Data::Dumper outputs if
  the data contains hashes.  If you need to have identical Data::Dumper
  outputs from different runs of Perl, use the environment variable
  PERL_HASH_SEED, see L<perlrun/PERL_HASH_SEED>.  Using this restores
  the old (platform-specific) ordering: an even prettier solution might
  be to use the C<Sortkeys> filter of Data::Dumper.
  
  =head1 AUTHOR
  
  Gurusamy Sarathy        gsar@activestate.com
  
  Copyright (c) 1996-98 Gurusamy Sarathy. All rights reserved.
  This program is free software; you can redistribute it and/or
  modify it under the same terms as Perl itself.
  
  =head1 VERSION
  
  Version 2.145  (March 15 2013))
  
  =head1 SEE ALSO
  
  perl(1)
  
  =cut
X86_64-LINUX_DATA_DUMPER

$fatpacked{"x86_64-linux/JSON/XS.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'X86_64-LINUX_JSON_XS';
  =head1 NAME
  
  JSON::XS - JSON serialising/deserialising, done correctly and fast
  
  =encoding utf-8
  
  JSON::XS - 正しくて高速な JSON シリアライザ/デシリアライザ
             (http://fleur.hio.jp/perldoc/mix/lib/JSON/XS.html)
  
  =head1 SYNOPSIS
  
   use JSON::XS;
  
   # exported functions, they croak on error
   # and expect/generate UTF-8
  
   $utf8_encoded_json_text = encode_json $perl_hash_or_arrayref;
   $perl_hash_or_arrayref  = decode_json $utf8_encoded_json_text;
  
   # OO-interface
  
   $coder = JSON::XS->new->ascii->pretty->allow_nonref;
   $pretty_printed_unencoded = $coder->encode ($perl_scalar);
   $perl_scalar = $coder->decode ($unicode_json_text);
  
   # Note that JSON version 2.0 and above will automatically use JSON::XS
   # if available, at virtually no speed overhead either, so you should
   # be able to just:
   
   use JSON;
  
   # and do the same things, except that you have a pure-perl fallback now.
  
  =head1 DESCRIPTION
  
  This module converts Perl data structures to JSON and vice versa. Its
  primary goal is to be I<correct> and its secondary goal is to be
  I<fast>. To reach the latter goal it was written in C.
  
  Beginning with version 2.0 of the JSON module, when both JSON and
  JSON::XS are installed, then JSON will fall back on JSON::XS (this can be
  overridden) with no overhead due to emulation (by inheriting constructor
  and methods). If JSON::XS is not available, it will fall back to the
  compatible JSON::PP module as backend, so using JSON instead of JSON::XS
  gives you a portable JSON API that can be fast when you need and doesn't
  require a C compiler when that is a problem.
  
  As this is the n-th-something JSON module on CPAN, what was the reason
  to write yet another JSON module? While it seems there are many JSON
  modules, none of them correctly handle all corner cases, and in most cases
  their maintainers are unresponsive, gone missing, or not listening to bug
  reports for other reasons.
  
  See MAPPING, below, on how JSON::XS maps perl values to JSON values and
  vice versa.
  
  =head2 FEATURES
  
  =over 4
  
  =item * correct Unicode handling
  
  This module knows how to handle Unicode, documents how and when it does
  so, and even documents what "correct" means.
  
  =item * round-trip integrity
  
  When you serialise a perl data structure using only data types supported
  by JSON and Perl, the deserialised data structure is identical on the Perl
  level. (e.g. the string "2.0" doesn't suddenly become "2" just because
  it looks like a number). There I<are> minor exceptions to this, read the
  MAPPING section below to learn about those.
  
  =item * strict checking of JSON correctness
  
  There is no guessing, no generating of illegal JSON texts by default,
  and only JSON is accepted as input by default (the latter is a security
  feature).
  
  =item * fast
  
  Compared to other JSON modules and other serialisers such as Storable,
  this module usually compares favourably in terms of speed, too.
  
  =item * simple to use
  
  This module has both a simple functional interface as well as an object
  oriented interface.
  
  =item * reasonably versatile output formats
  
  You can choose between the most compact guaranteed-single-line format
  possible (nice for simple line-based protocols), a pure-ASCII format
  (for when your transport is not 8-bit clean, still supports the whole
  Unicode range), or a pretty-printed format (for when you want to read that
  stuff). Or you can combine those features in whatever way you like.
  
  =back
  
  =cut
  
  package JSON::XS;
  
  use common::sense;
  
  our $VERSION = 3.01;
  our @ISA = qw(Exporter);
  
  our @EXPORT = qw(encode_json decode_json);
  
  use Exporter;
  use XSLoader;
  
  use Types::Serialiser ();
  
  =head1 FUNCTIONAL INTERFACE
  
  The following convenience methods are provided by this module. They are
  exported by default:
  
  =over 4
  
  =item $json_text = encode_json $perl_scalar
  
  Converts the given Perl data structure to a UTF-8 encoded, binary string
  (that is, the string contains octets only). Croaks on error.
  
  This function call is functionally identical to:
  
     $json_text = JSON::XS->new->utf8->encode ($perl_scalar)
  
  Except being faster.
  
  =item $perl_scalar = decode_json $json_text
  
  The opposite of C<encode_json>: expects an UTF-8 (binary) string and tries
  to parse that as an UTF-8 encoded JSON text, returning the resulting
  reference. Croaks on error.
  
  This function call is functionally identical to:
  
     $perl_scalar = JSON::XS->new->utf8->decode ($json_text)
  
  Except being faster.
  
  =back
  
  
  =head1 A FEW NOTES ON UNICODE AND PERL
  
  Since this often leads to confusion, here are a few very clear words on
  how Unicode works in Perl, modulo bugs.
  
  =over 4
  
  =item 1. Perl strings can store characters with ordinal values > 255.
  
  This enables you to store Unicode characters as single characters in a
  Perl string - very natural.
  
  =item 2. Perl does I<not> associate an encoding with your strings.
  
  ... until you force it to, e.g. when matching it against a regex, or
  printing the scalar to a file, in which case Perl either interprets your
  string as locale-encoded text, octets/binary, or as Unicode, depending
  on various settings. In no case is an encoding stored together with your
  data, it is I<use> that decides encoding, not any magical meta data.
  
  =item 3. The internal utf-8 flag has no meaning with regards to the
  encoding of your string.
  
  Just ignore that flag unless you debug a Perl bug, a module written in
  XS or want to dive into the internals of perl. Otherwise it will only
  confuse you, as, despite the name, it says nothing about how your string
  is encoded. You can have Unicode strings with that flag set, with that
  flag clear, and you can have binary data with that flag set and that flag
  clear. Other possibilities exist, too.
  
  If you didn't know about that flag, just the better, pretend it doesn't
  exist.
  
  =item 4. A "Unicode String" is simply a string where each character can be
  validly interpreted as a Unicode code point.
  
  If you have UTF-8 encoded data, it is no longer a Unicode string, but a
  Unicode string encoded in UTF-8, giving you a binary string.
  
  =item 5. A string containing "high" (> 255) character values is I<not> a UTF-8 string.
  
  It's a fact. Learn to live with it.
  
  =back
  
  I hope this helps :)
  
  
  =head1 OBJECT-ORIENTED INTERFACE
  
  The object oriented interface lets you configure your own encoding or
  decoding style, within the limits of supported formats.
  
  =over 4
  
  =item $json = new JSON::XS
  
  Creates a new JSON::XS object that can be used to de/encode JSON
  strings. All boolean flags described below are by default I<disabled>.
  
  The mutators for flags all return the JSON object again and thus calls can
  be chained:
  
     my $json = JSON::XS->new->utf8->space_after->encode ({a => [1,2]})
     => {"a": [1, 2]}
  
  =item $json = $json->ascii ([$enable])
  
  =item $enabled = $json->get_ascii
  
  If C<$enable> is true (or missing), then the C<encode> method will not
  generate characters outside the code range C<0..127> (which is ASCII). Any
  Unicode characters outside that range will be escaped using either a
  single \uXXXX (BMP characters) or a double \uHHHH\uLLLLL escape sequence,
  as per RFC4627. The resulting encoded JSON text can be treated as a native
  Unicode string, an ascii-encoded, latin1-encoded or UTF-8 encoded string,
  or any other superset of ASCII.
  
  If C<$enable> is false, then the C<encode> method will not escape Unicode
  characters unless required by the JSON syntax or other flags. This results
  in a faster and more compact format.
  
  See also the section I<ENCODING/CODESET FLAG NOTES> later in this
  document.
  
  The main use for this flag is to produce JSON texts that can be
  transmitted over a 7-bit channel, as the encoded JSON texts will not
  contain any 8 bit characters.
  
    JSON::XS->new->ascii (1)->encode ([chr 0x10401])
    => ["\ud801\udc01"]
  
  =item $json = $json->latin1 ([$enable])
  
  =item $enabled = $json->get_latin1
  
  If C<$enable> is true (or missing), then the C<encode> method will encode
  the resulting JSON text as latin1 (or iso-8859-1), escaping any characters
  outside the code range C<0..255>. The resulting string can be treated as a
  latin1-encoded JSON text or a native Unicode string. The C<decode> method
  will not be affected in any way by this flag, as C<decode> by default
  expects Unicode, which is a strict superset of latin1.
  
  If C<$enable> is false, then the C<encode> method will not escape Unicode
  characters unless required by the JSON syntax or other flags.
  
  See also the section I<ENCODING/CODESET FLAG NOTES> later in this
  document.
  
  The main use for this flag is efficiently encoding binary data as JSON
  text, as most octets will not be escaped, resulting in a smaller encoded
  size. The disadvantage is that the resulting JSON text is encoded
  in latin1 (and must correctly be treated as such when storing and
  transferring), a rare encoding for JSON. It is therefore most useful when
  you want to store data structures known to contain binary data efficiently
  in files or databases, not when talking to other JSON encoders/decoders.
  
    JSON::XS->new->latin1->encode (["\x{89}\x{abc}"]
    => ["\x{89}\\u0abc"]    # (perl syntax, U+abc escaped, U+89 not)
  
  =item $json = $json->utf8 ([$enable])
  
  =item $enabled = $json->get_utf8
  
  If C<$enable> is true (or missing), then the C<encode> method will encode
  the JSON result into UTF-8, as required by many protocols, while the
  C<decode> method expects to be handled an UTF-8-encoded string.  Please
  note that UTF-8-encoded strings do not contain any characters outside the
  range C<0..255>, they are thus useful for bytewise/binary I/O. In future
  versions, enabling this option might enable autodetection of the UTF-16
  and UTF-32 encoding families, as described in RFC4627.
  
  If C<$enable> is false, then the C<encode> method will return the JSON
  string as a (non-encoded) Unicode string, while C<decode> expects thus a
  Unicode string.  Any decoding or encoding (e.g. to UTF-8 or UTF-16) needs
  to be done yourself, e.g. using the Encode module.
  
  See also the section I<ENCODING/CODESET FLAG NOTES> later in this
  document.
  
  Example, output UTF-16BE-encoded JSON:
  
    use Encode;
    $jsontext = encode "UTF-16BE", JSON::XS->new->encode ($object);
  
  Example, decode UTF-32LE-encoded JSON:
  
    use Encode;
    $object = JSON::XS->new->decode (decode "UTF-32LE", $jsontext);
  
  =item $json = $json->pretty ([$enable])
  
  This enables (or disables) all of the C<indent>, C<space_before> and
  C<space_after> (and in the future possibly more) flags in one call to
  generate the most readable (or most compact) form possible.
  
  Example, pretty-print some simple structure:
  
     my $json = JSON::XS->new->pretty(1)->encode ({a => [1,2]})
     =>
     {
        "a" : [
           1,
           2
        ]
     }
  
  =item $json = $json->indent ([$enable])
  
  =item $enabled = $json->get_indent
  
  If C<$enable> is true (or missing), then the C<encode> method will use a multiline
  format as output, putting every array member or object/hash key-value pair
  into its own line, indenting them properly.
  
  If C<$enable> is false, no newlines or indenting will be produced, and the
  resulting JSON text is guaranteed not to contain any C<newlines>.
  
  This setting has no effect when decoding JSON texts.
  
  =item $json = $json->space_before ([$enable])
  
  =item $enabled = $json->get_space_before
  
  If C<$enable> is true (or missing), then the C<encode> method will add an extra
  optional space before the C<:> separating keys from values in JSON objects.
  
  If C<$enable> is false, then the C<encode> method will not add any extra
  space at those places.
  
  This setting has no effect when decoding JSON texts. You will also
  most likely combine this setting with C<space_after>.
  
  Example, space_before enabled, space_after and indent disabled:
  
     {"key" :"value"}
  
  =item $json = $json->space_after ([$enable])
  
  =item $enabled = $json->get_space_after
  
  If C<$enable> is true (or missing), then the C<encode> method will add an extra
  optional space after the C<:> separating keys from values in JSON objects
  and extra whitespace after the C<,> separating key-value pairs and array
  members.
  
  If C<$enable> is false, then the C<encode> method will not add any extra
  space at those places.
  
  This setting has no effect when decoding JSON texts.
  
  Example, space_before and indent disabled, space_after enabled:
  
     {"key": "value"}
  
  =item $json = $json->relaxed ([$enable])
  
  =item $enabled = $json->get_relaxed
  
  If C<$enable> is true (or missing), then C<decode> will accept some
  extensions to normal JSON syntax (see below). C<encode> will not be
  affected in anyway. I<Be aware that this option makes you accept invalid
  JSON texts as if they were valid!>. I suggest only to use this option to
  parse application-specific files written by humans (configuration files,
  resource files etc.)
  
  If C<$enable> is false (the default), then C<decode> will only accept
  valid JSON texts.
  
  Currently accepted extensions are:
  
  =over 4
  
  =item * list items can have an end-comma
  
  JSON I<separates> array elements and key-value pairs with commas. This
  can be annoying if you write JSON texts manually and want to be able to
  quickly append elements, so this extension accepts comma at the end of
  such items not just between them:
  
     [
        1,
        2, <- this comma not normally allowed
     ]
     {
        "k1": "v1",
        "k2": "v2", <- this comma not normally allowed
     }
  
  =item * shell-style '#'-comments
  
  Whenever JSON allows whitespace, shell-style comments are additionally
  allowed. They are terminated by the first carriage-return or line-feed
  character, after which more white-space and comments are allowed.
  
    [
       1, # this comment not allowed in JSON
          # neither this one...
    ]
  
  =back
  
  =item $json = $json->canonical ([$enable])
  
  =item $enabled = $json->get_canonical
  
  If C<$enable> is true (or missing), then the C<encode> method will output JSON objects
  by sorting their keys. This is adding a comparatively high overhead.
  
  If C<$enable> is false, then the C<encode> method will output key-value
  pairs in the order Perl stores them (which will likely change between runs
  of the same script, and can change even within the same run from 5.18
  onwards).
  
  This option is useful if you want the same data structure to be encoded as
  the same JSON text (given the same overall settings). If it is disabled,
  the same hash might be encoded differently even if contains the same data,
  as key-value pairs have no inherent ordering in Perl.
  
  This setting has no effect when decoding JSON texts.
  
  This setting has currently no effect on tied hashes.
  
  =item $json = $json->allow_nonref ([$enable])
  
  =item $enabled = $json->get_allow_nonref
  
  If C<$enable> is true (or missing), then the C<encode> method can convert a
  non-reference into its corresponding string, number or null JSON value,
  which is an extension to RFC4627. Likewise, C<decode> will accept those JSON
  values instead of croaking.
  
  If C<$enable> is false, then the C<encode> method will croak if it isn't
  passed an arrayref or hashref, as JSON texts must either be an object
  or array. Likewise, C<decode> will croak if given something that is not a
  JSON object or array.
  
  Example, encode a Perl scalar as JSON value with enabled C<allow_nonref>,
  resulting in an invalid JSON text:
  
     JSON::XS->new->allow_nonref->encode ("Hello, World!")
     => "Hello, World!"
  
  =item $json = $json->allow_unknown ([$enable])
  
  =item $enabled = $json->get_allow_unknown
  
  If C<$enable> is true (or missing), then C<encode> will I<not> throw an
  exception when it encounters values it cannot represent in JSON (for
  example, filehandles) but instead will encode a JSON C<null> value. Note
  that blessed objects are not included here and are handled separately by
  c<allow_nonref>.
  
  If C<$enable> is false (the default), then C<encode> will throw an
  exception when it encounters anything it cannot encode as JSON.
  
  This option does not affect C<decode> in any way, and it is recommended to
  leave it off unless you know your communications partner.
  
  =item $json = $json->allow_blessed ([$enable])
  
  =item $enabled = $json->get_allow_blessed
  
  See L<OBJECT SERIALISATION> for details.
  
  If C<$enable> is true (or missing), then the C<encode> method will not
  barf when it encounters a blessed reference that it cannot convert
  otherwise. Instead, a JSON C<null> value is encoded instead of the object.
  
  If C<$enable> is false (the default), then C<encode> will throw an
  exception when it encounters a blessed object that it cannot convert
  otherwise.
  
  This setting has no effect on C<decode>.
  
  =item $json = $json->convert_blessed ([$enable])
  
  =item $enabled = $json->get_convert_blessed
  
  See L<OBJECT SERIALISATION> for details.
  
  If C<$enable> is true (or missing), then C<encode>, upon encountering a
  blessed object, will check for the availability of the C<TO_JSON> method
  on the object's class. If found, it will be called in scalar context and
  the resulting scalar will be encoded instead of the object.
  
  The C<TO_JSON> method may safely call die if it wants. If C<TO_JSON>
  returns other blessed objects, those will be handled in the same
  way. C<TO_JSON> must take care of not causing an endless recursion cycle
  (== crash) in this case. The name of C<TO_JSON> was chosen because other
  methods called by the Perl core (== not by the user of the object) are
  usually in upper case letters and to avoid collisions with any C<to_json>
  function or method.
  
  If C<$enable> is false (the default), then C<encode> will not consider
  this type of conversion.
  
  This setting has no effect on C<decode>.
  
  =item $json = $json->allow_tags ([$enable])
  
  =item $enabled = $json->allow_tags
  
  See L<OBJECT SERIALISATION> for details.
  
  If C<$enable> is true (or missing), then C<encode>, upon encountering a
  blessed object, will check for the availability of the C<FREEZE> method on
  the object's class. If found, it will be used to serialise the object into
  a nonstandard tagged JSON value (that JSON decoders cannot decode).
  
  It also causes C<decode> to parse such tagged JSON values and deserialise
  them via a call to the C<THAW> method.
  
  If C<$enable> is false (the default), then C<encode> will not consider
  this type of conversion, and tagged JSON values will cause a parse error
  in C<decode>, as if tags were not part of the grammar.
  
  =item $json = $json->filter_json_object ([$coderef->($hashref)])
  
  When C<$coderef> is specified, it will be called from C<decode> each
  time it decodes a JSON object. The only argument is a reference to the
  newly-created hash. If the code references returns a single scalar (which
  need not be a reference), this value (i.e. a copy of that scalar to avoid
  aliasing) is inserted into the deserialised data structure. If it returns
  an empty list (NOTE: I<not> C<undef>, which is a valid scalar), the
  original deserialised hash will be inserted. This setting can slow down
  decoding considerably.
  
  When C<$coderef> is omitted or undefined, any existing callback will
  be removed and C<decode> will not change the deserialised hash in any
  way.
  
  Example, convert all JSON objects into the integer 5:
  
     my $js = JSON::XS->new->filter_json_object (sub { 5 });
     # returns [5]
     $js->decode ('[{}]')
     # throw an exception because allow_nonref is not enabled
     # so a lone 5 is not allowed.
     $js->decode ('{"a":1, "b":2}');
  
  =item $json = $json->filter_json_single_key_object ($key [=> $coderef->($value)])
  
  Works remotely similar to C<filter_json_object>, but is only called for
  JSON objects having a single key named C<$key>.
  
  This C<$coderef> is called before the one specified via
  C<filter_json_object>, if any. It gets passed the single value in the JSON
  object. If it returns a single value, it will be inserted into the data
  structure. If it returns nothing (not even C<undef> but the empty list),
  the callback from C<filter_json_object> will be called next, as if no
  single-key callback were specified.
  
  If C<$coderef> is omitted or undefined, the corresponding callback will be
  disabled. There can only ever be one callback for a given key.
  
  As this callback gets called less often then the C<filter_json_object>
  one, decoding speed will not usually suffer as much. Therefore, single-key
  objects make excellent targets to serialise Perl objects into, especially
  as single-key JSON objects are as close to the type-tagged value concept
  as JSON gets (it's basically an ID/VALUE tuple). Of course, JSON does not
  support this in any way, so you need to make sure your data never looks
  like a serialised Perl hash.
  
  Typical names for the single object key are C<__class_whatever__>, or
  C<$__dollars_are_rarely_used__$> or C<}ugly_brace_placement>, or even
  things like C<__class_md5sum(classname)__>, to reduce the risk of clashing
  with real hashes.
  
  Example, decode JSON objects of the form C<< { "__widget__" => <id> } >>
  into the corresponding C<< $WIDGET{<id>} >> object:
  
     # return whatever is in $WIDGET{5}:
     JSON::XS
        ->new
        ->filter_json_single_key_object (__widget__ => sub {
              $WIDGET{ $_[0] }
           })
        ->decode ('{"__widget__": 5')
  
     # this can be used with a TO_JSON method in some "widget" class
     # for serialisation to json:
     sub WidgetBase::TO_JSON {
        my ($self) = @_;
  
        unless ($self->{id}) {
           $self->{id} = ..get..some..id..;
           $WIDGET{$self->{id}} = $self;
        }
  
        { __widget__ => $self->{id} }
     }
  
  =item $json = $json->shrink ([$enable])
  
  =item $enabled = $json->get_shrink
  
  Perl usually over-allocates memory a bit when allocating space for
  strings. This flag optionally resizes strings generated by either
  C<encode> or C<decode> to their minimum size possible. This can save
  memory when your JSON texts are either very very long or you have many
  short strings. It will also try to downgrade any strings to octet-form
  if possible: perl stores strings internally either in an encoding called
  UTF-X or in octet-form. The latter cannot store everything but uses less
  space in general (and some buggy Perl or C code might even rely on that
  internal representation being used).
  
  The actual definition of what shrink does might change in future versions,
  but it will always try to save space at the expense of time.
  
  If C<$enable> is true (or missing), the string returned by C<encode> will
  be shrunk-to-fit, while all strings generated by C<decode> will also be
  shrunk-to-fit.
  
  If C<$enable> is false, then the normal perl allocation algorithms are used.
  If you work with your data, then this is likely to be faster.
  
  In the future, this setting might control other things, such as converting
  strings that look like integers or floats into integers or floats
  internally (there is no difference on the Perl level), saving space.
  
  =item $json = $json->max_depth ([$maximum_nesting_depth])
  
  =item $max_depth = $json->get_max_depth
  
  Sets the maximum nesting level (default C<512>) accepted while encoding
  or decoding. If a higher nesting level is detected in JSON text or a Perl
  data structure, then the encoder and decoder will stop and croak at that
  point.
  
  Nesting level is defined by number of hash- or arrayrefs that the encoder
  needs to traverse to reach a given point or the number of C<{> or C<[>
  characters without their matching closing parenthesis crossed to reach a
  given character in a string.
  
  Setting the maximum depth to one disallows any nesting, so that ensures
  that the object is only a single hash/object or array.
  
  If no argument is given, the highest possible setting will be used, which
  is rarely useful.
  
  Note that nesting is implemented by recursion in C. The default value has
  been chosen to be as large as typical operating systems allow without
  crashing.
  
  See SECURITY CONSIDERATIONS, below, for more info on why this is useful.
  
  =item $json = $json->max_size ([$maximum_string_size])
  
  =item $max_size = $json->get_max_size
  
  Set the maximum length a JSON text may have (in bytes) where decoding is
  being attempted. The default is C<0>, meaning no limit. When C<decode>
  is called on a string that is longer then this many bytes, it will not
  attempt to decode the string but throw an exception. This setting has no
  effect on C<encode> (yet).
  
  If no argument is given, the limit check will be deactivated (same as when
  C<0> is specified).
  
  See SECURITY CONSIDERATIONS, below, for more info on why this is useful.
  
  =item $json_text = $json->encode ($perl_scalar)
  
  Converts the given Perl value or data structure to its JSON
  representation. Croaks on error.
  
  =item $perl_scalar = $json->decode ($json_text)
  
  The opposite of C<encode>: expects a JSON text and tries to parse it,
  returning the resulting simple scalar or reference. Croaks on error.
  
  =item ($perl_scalar, $characters) = $json->decode_prefix ($json_text)
  
  This works like the C<decode> method, but instead of raising an exception
  when there is trailing garbage after the first JSON object, it will
  silently stop parsing there and return the number of characters consumed
  so far.
  
  This is useful if your JSON texts are not delimited by an outer protocol
  and you need to know where the JSON text ends.
  
     JSON::XS->new->decode_prefix ("[1] the tail")
     => ([], 3)
  
  =back
  
  
  =head1 INCREMENTAL PARSING
  
  In some cases, there is the need for incremental parsing of JSON
  texts. While this module always has to keep both JSON text and resulting
  Perl data structure in memory at one time, it does allow you to parse a
  JSON stream incrementally. It does so by accumulating text until it has
  a full JSON object, which it then can decode. This process is similar to
  using C<decode_prefix> to see if a full JSON object is available, but
  is much more efficient (and can be implemented with a minimum of method
  calls).
  
  JSON::XS will only attempt to parse the JSON text once it is sure it
  has enough text to get a decisive result, using a very simple but
  truly incremental parser. This means that it sometimes won't stop as
  early as the full parser, for example, it doesn't detect mismatched
  parentheses. The only thing it guarantees is that it starts decoding as
  soon as a syntactically valid JSON text has been seen. This means you need
  to set resource limits (e.g. C<max_size>) to ensure the parser will stop
  parsing in the presence if syntax errors.
  
  The following methods implement this incremental parser.
  
  =over 4
  
  =item [void, scalar or list context] = $json->incr_parse ([$string])
  
  This is the central parsing function. It can both append new text and
  extract objects from the stream accumulated so far (both of these
  functions are optional).
  
  If C<$string> is given, then this string is appended to the already
  existing JSON fragment stored in the C<$json> object.
  
  After that, if the function is called in void context, it will simply
  return without doing anything further. This can be used to add more text
  in as many chunks as you want.
  
  If the method is called in scalar context, then it will try to extract
  exactly I<one> JSON object. If that is successful, it will return this
  object, otherwise it will return C<undef>. If there is a parse error,
  this method will croak just as C<decode> would do (one can then use
  C<incr_skip> to skip the erroneous part). This is the most common way of
  using the method.
  
  And finally, in list context, it will try to extract as many objects
  from the stream as it can find and return them, or the empty list
  otherwise. For this to work, there must be no separators between the JSON
  objects or arrays, instead they must be concatenated back-to-back. If
  an error occurs, an exception will be raised as in the scalar context
  case. Note that in this case, any previously-parsed JSON texts will be
  lost.
  
  Example: Parse some JSON arrays/objects in a given string and return
  them.
  
     my @objs = JSON::XS->new->incr_parse ("[5][7][1,2]");
  
  =item $lvalue_string = $json->incr_text
  
  This method returns the currently stored JSON fragment as an lvalue, that
  is, you can manipulate it. This I<only> works when a preceding call to
  C<incr_parse> in I<scalar context> successfully returned an object. Under
  all other circumstances you must not call this function (I mean it.
  although in simple tests it might actually work, it I<will> fail under
  real world conditions). As a special exception, you can also call this
  method before having parsed anything.
  
  This function is useful in two cases: a) finding the trailing text after a
  JSON object or b) parsing multiple JSON objects separated by non-JSON text
  (such as commas).
  
  =item $json->incr_skip
  
  This will reset the state of the incremental parser and will remove
  the parsed text from the input buffer so far. This is useful after
  C<incr_parse> died, in which case the input buffer and incremental parser
  state is left unchanged, to skip the text parsed so far and to reset the
  parse state.
  
  The difference to C<incr_reset> is that only text until the parse error
  occurred is removed.
  
  =item $json->incr_reset
  
  This completely resets the incremental parser, that is, after this call,
  it will be as if the parser had never parsed anything.
  
  This is useful if you want to repeatedly parse JSON objects and want to
  ignore any trailing data, which means you have to reset the parser after
  each successful decode.
  
  =back
  
  =head2 LIMITATIONS
  
  All options that affect decoding are supported, except
  C<allow_nonref>. The reason for this is that it cannot be made to work
  sensibly: JSON objects and arrays are self-delimited, i.e. you can
  concatenate them back to back and still decode them perfectly. This does
  not hold true for JSON numbers, however.
  
  For example, is the string C<1> a single JSON number, or is it simply the
  start of C<12>? Or is C<12> a single JSON number, or the concatenation
  of C<1> and C<2>? In neither case you can tell, and this is why JSON::XS
  takes the conservative route and disallows this case.
  
  =head2 EXAMPLES
  
  Some examples will make all this clearer. First, a simple example that
  works similarly to C<decode_prefix>: We want to decode the JSON object at
  the start of a string and identify the portion after the JSON object:
  
     my $text = "[1,2,3] hello";
  
     my $json = new JSON::XS;
  
     my $obj = $json->incr_parse ($text)
        or die "expected JSON object or array at beginning of string";
  
     my $tail = $json->incr_text;
     # $tail now contains " hello"
  
  Easy, isn't it?
  
  Now for a more complicated example: Imagine a hypothetical protocol where
  you read some requests from a TCP stream, and each request is a JSON
  array, without any separation between them (in fact, it is often useful to
  use newlines as "separators", as these get interpreted as whitespace at
  the start of the JSON text, which makes it possible to test said protocol
  with C<telnet>...).
  
  Here is how you'd do it (it is trivial to write this in an event-based
  manner):
  
     my $json = new JSON::XS;
  
     # read some data from the socket
     while (sysread $socket, my $buf, 4096) {
  
        # split and decode as many requests as possible
        for my $request ($json->incr_parse ($buf)) {
           # act on the $request
        }
     }
  
  Another complicated example: Assume you have a string with JSON objects
  or arrays, all separated by (optional) comma characters (e.g. C<[1],[2],
  [3]>). To parse them, we have to skip the commas between the JSON texts,
  and here is where the lvalue-ness of C<incr_text> comes in useful:
  
     my $text = "[1],[2], [3]";
     my $json = new JSON::XS;
  
     # void context, so no parsing done
     $json->incr_parse ($text);
  
     # now extract as many objects as possible. note the
     # use of scalar context so incr_text can be called.
     while (my $obj = $json->incr_parse) {
        # do something with $obj
  
        # now skip the optional comma
        $json->incr_text =~ s/^ \s* , //x;
     }
  
  Now lets go for a very complex example: Assume that you have a gigantic
  JSON array-of-objects, many gigabytes in size, and you want to parse it,
  but you cannot load it into memory fully (this has actually happened in
  the real world :).
  
  Well, you lost, you have to implement your own JSON parser. But JSON::XS
  can still help you: You implement a (very simple) array parser and let
  JSON decode the array elements, which are all full JSON objects on their
  own (this wouldn't work if the array elements could be JSON numbers, for
  example):
  
     my $json = new JSON::XS;
  
     # open the monster
     open my $fh, "<bigfile.json"
        or die "bigfile: $!";
  
     # first parse the initial "["
     for (;;) {
        sysread $fh, my $buf, 65536
           or die "read error: $!";
        $json->incr_parse ($buf); # void context, so no parsing
  
        # Exit the loop once we found and removed(!) the initial "[".
        # In essence, we are (ab-)using the $json object as a simple scalar
        # we append data to.
        last if $json->incr_text =~ s/^ \s* \[ //x;
     }
  
     # now we have the skipped the initial "[", so continue
     # parsing all the elements.
     for (;;) {
        # in this loop we read data until we got a single JSON object
        for (;;) {
           if (my $obj = $json->incr_parse) {
              # do something with $obj
              last;
           }
  
           # add more data
           sysread $fh, my $buf, 65536
              or die "read error: $!";
           $json->incr_parse ($buf); # void context, so no parsing
        }
  
        # in this loop we read data until we either found and parsed the
        # separating "," between elements, or the final "]"
        for (;;) {
           # first skip whitespace
           $json->incr_text =~ s/^\s*//;
  
           # if we find "]", we are done
           if ($json->incr_text =~ s/^\]//) {
              print "finished.\n";
              exit;
           }
  
           # if we find ",", we can continue with the next element
           if ($json->incr_text =~ s/^,//) {
              last;
           }
  
           # if we find anything else, we have a parse error!
           if (length $json->incr_text) {
              die "parse error near ", $json->incr_text;
           }
  
           # else add more data
           sysread $fh, my $buf, 65536
              or die "read error: $!";
           $json->incr_parse ($buf); # void context, so no parsing
        }
  
  This is a complex example, but most of the complexity comes from the fact
  that we are trying to be correct (bear with me if I am wrong, I never ran
  the above example :).
  
  
  
  =head1 MAPPING
  
  This section describes how JSON::XS maps Perl values to JSON values and
  vice versa. These mappings are designed to "do the right thing" in most
  circumstances automatically, preserving round-tripping characteristics
  (what you put in comes out as something equivalent).
  
  For the more enlightened: note that in the following descriptions,
  lowercase I<perl> refers to the Perl interpreter, while uppercase I<Perl>
  refers to the abstract Perl language itself.
  
  
  =head2 JSON -> PERL
  
  =over 4
  
  =item object
  
  A JSON object becomes a reference to a hash in Perl. No ordering of object
  keys is preserved (JSON does not preserve object key ordering itself).
  
  =item array
  
  A JSON array becomes a reference to an array in Perl.
  
  =item string
  
  A JSON string becomes a string scalar in Perl - Unicode codepoints in JSON
  are represented by the same codepoints in the Perl string, so no manual
  decoding is necessary.
  
  =item number
  
  A JSON number becomes either an integer, numeric (floating point) or
  string scalar in perl, depending on its range and any fractional parts. On
  the Perl level, there is no difference between those as Perl handles all
  the conversion details, but an integer may take slightly less memory and
  might represent more values exactly than floating point numbers.
  
  If the number consists of digits only, JSON::XS will try to represent
  it as an integer value. If that fails, it will try to represent it as
  a numeric (floating point) value if that is possible without loss of
  precision. Otherwise it will preserve the number as a string value (in
  which case you lose roundtripping ability, as the JSON number will be
  re-encoded to a JSON string).
  
  Numbers containing a fractional or exponential part will always be
  represented as numeric (floating point) values, possibly at a loss of
  precision (in which case you might lose perfect roundtripping ability, but
  the JSON number will still be re-encoded as a JSON number).
  
  Note that precision is not accuracy - binary floating point values cannot
  represent most decimal fractions exactly, and when converting from and to
  floating point, JSON::XS only guarantees precision up to but not including
  the least significant bit.
  
  =item true, false
  
  These JSON atoms become C<Types::Serialiser::true> and
  C<Types::Serialiser::false>, respectively. They are overloaded to act
  almost exactly like the numbers C<1> and C<0>. You can check whether
  a scalar is a JSON boolean by using the C<Types::Serialiser::is_bool>
  function (after C<use Types::Serialier>, of course).
  
  =item null
  
  A JSON null atom becomes C<undef> in Perl.
  
  =item shell-style comments (C<< # I<text> >>)
  
  As a nonstandard extension to the JSON syntax that is enabled by the
  C<relaxed> setting, shell-style comments are allowed. They can start
  anywhere outside strings and go till the end of the line.
  
  =item tagged values (C<< (I<tag>)I<value> >>).
  
  Another nonstandard extension to the JSON syntax, enabled with the
  C<allow_tags> setting, are tagged values. In this implementation, the
  I<tag> must be a perl package/class name encoded as a JSON string, and the
  I<value> must be a JSON array encoding optional constructor arguments.
  
  See L<OBJECT SERIALISATION>, below, for details.
  
  =back
  
  
  =head2 PERL -> JSON
  
  The mapping from Perl to JSON is slightly more difficult, as Perl is a
  truly typeless language, so we can only guess which JSON type is meant by
  a Perl value.
  
  =over 4
  
  =item hash references
  
  Perl hash references become JSON objects. As there is no inherent
  ordering in hash keys (or JSON objects), they will usually be encoded
  in a pseudo-random order. JSON::XS can optionally sort the hash keys
  (determined by the I<canonical> flag), so the same datastructure will
  serialise to the same JSON text (given same settings and version of
  JSON::XS), but this incurs a runtime overhead and is only rarely useful,
  e.g. when you want to compare some JSON text against another for equality.
  
  =item array references
  
  Perl array references become JSON arrays.
  
  =item other references
  
  Other unblessed references are generally not allowed and will cause an
  exception to be thrown, except for references to the integers C<0> and
  C<1>, which get turned into C<false> and C<true> atoms in JSON.
  
  Since C<JSON::XS> uses the boolean model from L<Types::Serialiser>, you
  can also C<use Types::Serialiser> and then use C<Types::Serialiser::false>
  and C<Types::Serialiser::true> to improve readability.
  
     use Types::Serialiser;
     encode_json [\0, Types::Serialiser::true]      # yields [false,true]
  
  =item Types::Serialiser::true, Types::Serialiser::false
  
  These special values from the L<Types::Serialiser> module become JSON true
  and JSON false values, respectively. You can also use C<\1> and C<\0>
  directly if you want.
  
  =item blessed objects
  
  Blessed objects are not directly representable in JSON, but C<JSON::XS>
  allows various ways of handling objects. See L<OBJECT SERIALISATION>,
  below, for details.
  
  =item simple scalars
  
  Simple Perl scalars (any scalar that is not a reference) are the most
  difficult objects to encode: JSON::XS will encode undefined scalars as
  JSON C<null> values, scalars that have last been used in a string context
  before encoding as JSON strings, and anything else as number value:
  
     # dump as number
     encode_json [2]                      # yields [2]
     encode_json [-3.0e17]                # yields [-3e+17]
     my $value = 5; encode_json [$value]  # yields [5]
  
     # used as string, so dump as string
     print $value;
     encode_json [$value]                 # yields ["5"]
  
     # undef becomes null
     encode_json [undef]                  # yields [null]
  
  You can force the type to be a JSON string by stringifying it:
  
     my $x = 3.1; # some variable containing a number
     "$x";        # stringified
     $x .= "";    # another, more awkward way to stringify
     print $x;    # perl does it for you, too, quite often
  
  You can force the type to be a JSON number by numifying it:
  
     my $x = "3"; # some variable containing a string
     $x += 0;     # numify it, ensuring it will be dumped as a number
     $x *= 1;     # same thing, the choice is yours.
  
  You can not currently force the type in other, less obscure, ways. Tell me
  if you need this capability (but don't forget to explain why it's needed
  :).
  
  Note that numerical precision has the same meaning as under Perl (so
  binary to decimal conversion follows the same rules as in Perl, which
  can differ to other languages). Also, your perl interpreter might expose
  extensions to the floating point numbers of your platform, such as
  infinities or NaN's - these cannot be represented in JSON, and it is an
  error to pass those in.
  
  =back
  
  =head2 OBJECT SERIALISATION
  
  As JSON cannot directly represent Perl objects, you have to choose between
  a pure JSON representation (without the ability to deserialise the object
  automatically again), and a nonstandard extension to the JSON syntax,
  tagged values.
  
  =head3 SERIALISATION
  
  What happens when C<JSON::XS> encounters a Perl object depends on the
  C<allow_blessed>, C<convert_blessed> and C<allow_tags> settings, which are
  used in this order:
  
  =over 4
  
  =item 1. C<allow_tags> is enabled and the object has a C<FREEZE> method.
  
  In this case, C<JSON::XS> uses the L<Types::Serialiser> object
  serialisation protocol to create a tagged JSON value, using a nonstandard
  extension to the JSON syntax.
  
  This works by invoking the C<FREEZE> method on the object, with the first
  argument being the object to serialise, and the second argument being the
  constant string C<JSON> to distinguish it from other serialisers.
  
  The C<FREEZE> method can return any number of values (i.e. zero or
  more). These values and the paclkage/classname of the object will then be
  encoded as a tagged JSON value in the following format:
  
     ("classname")[FREEZE return values...]
  
  e.g.:
  
     ("URI")["http://www.google.com/"]
     ("MyDate")[2013,10,29]
     ("ImageData::JPEG")["Z3...VlCg=="]
  
  For example, the hypothetical C<My::Object> C<FREEZE> method might use the
  objects C<type> and C<id> members to encode the object:
  
     sub My::Object::FREEZE {
        my ($self, $serialiser) = @_;
  
        ($self->{type}, $self->{id})
     }
  
  =item 2. C<convert_blessed> is enabled and the object has a C<TO_JSON> method.
  
  In this case, the C<TO_JSON> method of the object is invoked in scalar
  context. It must return a single scalar that can be directly encoded into
  JSON. This scalar replaces the object in the JSON text.
  
  For example, the following C<TO_JSON> method will convert all L<URI>
  objects to JSON strings when serialised. The fatc that these values
  originally were L<URI> objects is lost.
  
     sub URI::TO_JSON {
        my ($uri) = @_;
        $uri->as_string
     }
  
  =item 3. C<allow_blessed> is enabled.
  
  The object will be serialised as a JSON null value.
  
  =item 4. none of the above
  
  If none of the settings are enabled or the respective methods are missing,
  C<JSON::XS> throws an exception.
  
  =back
  
  =head3 DESERIALISATION
  
  For deserialisation there are only two cases to consider: either
  nonstandard tagging was used, in which case C<allow_tags> decides,
  or objects cannot be automatically be deserialised, in which
  case you can use postprocessing or the C<filter_json_object> or
  C<filter_json_single_key_object> callbacks to get some real objects our of
  your JSON.
  
  This section only considers the tagged value case: I a tagged JSON object
  is encountered during decoding and C<allow_tags> is disabled, a parse
  error will result (as if tagged values were not part of the grammar).
  
  If C<allow_tags> is enabled, C<JSON::XS> will look up the C<THAW> method
  of the package/classname used during serialisation (it will not attempt
  to load the package as a Perl module). If there is no such method, the
  decoding will fail with an error.
  
  Otherwise, the C<THAW> method is invoked with the classname as first
  argument, the constant string C<JSON> as second argument, and all the
  values from the JSON array (the values originally returned by the
  C<FREEZE> method) as remaining arguments.
  
  The method must then return the object. While technically you can return
  any Perl scalar, you might have to enable the C<enable_nonref> setting to
  make that work in all cases, so better return an actual blessed reference.
  
  As an example, let's implement a C<THAW> function that regenerates the
  C<My::Object> from the C<FREEZE> example earlier:
  
     sub My::Object::THAW {
        my ($class, $serialiser, $type, $id) = @_;
  
        $class->new (type => $type, id => $id)
     }
  
  
  =head1 ENCODING/CODESET FLAG NOTES
  
  The interested reader might have seen a number of flags that signify
  encodings or codesets - C<utf8>, C<latin1> and C<ascii>. There seems to be
  some confusion on what these do, so here is a short comparison:
  
  C<utf8> controls whether the JSON text created by C<encode> (and expected
  by C<decode>) is UTF-8 encoded or not, while C<latin1> and C<ascii> only
  control whether C<encode> escapes character values outside their respective
  codeset range. Neither of these flags conflict with each other, although
  some combinations make less sense than others.
  
  Care has been taken to make all flags symmetrical with respect to
  C<encode> and C<decode>, that is, texts encoded with any combination of
  these flag values will be correctly decoded when the same flags are used
  - in general, if you use different flag settings while encoding vs. when
  decoding you likely have a bug somewhere.
  
  Below comes a verbose discussion of these flags. Note that a "codeset" is
  simply an abstract set of character-codepoint pairs, while an encoding
  takes those codepoint numbers and I<encodes> them, in our case into
  octets. Unicode is (among other things) a codeset, UTF-8 is an encoding,
  and ISO-8859-1 (= latin 1) and ASCII are both codesets I<and> encodings at
  the same time, which can be confusing.
  
  =over 4
  
  =item C<utf8> flag disabled
  
  When C<utf8> is disabled (the default), then C<encode>/C<decode> generate
  and expect Unicode strings, that is, characters with high ordinal Unicode
  values (> 255) will be encoded as such characters, and likewise such
  characters are decoded as-is, no changes to them will be done, except
  "(re-)interpreting" them as Unicode codepoints or Unicode characters,
  respectively (to Perl, these are the same thing in strings unless you do
  funny/weird/dumb stuff).
  
  This is useful when you want to do the encoding yourself (e.g. when you
  want to have UTF-16 encoded JSON texts) or when some other layer does
  the encoding for you (for example, when printing to a terminal using a
  filehandle that transparently encodes to UTF-8 you certainly do NOT want
  to UTF-8 encode your data first and have Perl encode it another time).
  
  =item C<utf8> flag enabled
  
  If the C<utf8>-flag is enabled, C<encode>/C<decode> will encode all
  characters using the corresponding UTF-8 multi-byte sequence, and will
  expect your input strings to be encoded as UTF-8, that is, no "character"
  of the input string must have any value > 255, as UTF-8 does not allow
  that.
  
  The C<utf8> flag therefore switches between two modes: disabled means you
  will get a Unicode string in Perl, enabled means you get an UTF-8 encoded
  octet/binary string in Perl.
  
  =item C<latin1> or C<ascii> flags enabled
  
  With C<latin1> (or C<ascii>) enabled, C<encode> will escape characters
  with ordinal values > 255 (> 127 with C<ascii>) and encode the remaining
  characters as specified by the C<utf8> flag.
  
  If C<utf8> is disabled, then the result is also correctly encoded in those
  character sets (as both are proper subsets of Unicode, meaning that a
  Unicode string with all character values < 256 is the same thing as a
  ISO-8859-1 string, and a Unicode string with all character values < 128 is
  the same thing as an ASCII string in Perl).
  
  If C<utf8> is enabled, you still get a correct UTF-8-encoded string,
  regardless of these flags, just some more characters will be escaped using
  C<\uXXXX> then before.
  
  Note that ISO-8859-1-I<encoded> strings are not compatible with UTF-8
  encoding, while ASCII-encoded strings are. That is because the ISO-8859-1
  encoding is NOT a subset of UTF-8 (despite the ISO-8859-1 I<codeset> being
  a subset of Unicode), while ASCII is.
  
  Surprisingly, C<decode> will ignore these flags and so treat all input
  values as governed by the C<utf8> flag. If it is disabled, this allows you
  to decode ISO-8859-1- and ASCII-encoded strings, as both strict subsets of
  Unicode. If it is enabled, you can correctly decode UTF-8 encoded strings.
  
  So neither C<latin1> nor C<ascii> are incompatible with the C<utf8> flag -
  they only govern when the JSON output engine escapes a character or not.
  
  The main use for C<latin1> is to relatively efficiently store binary data
  as JSON, at the expense of breaking compatibility with most JSON decoders.
  
  The main use for C<ascii> is to force the output to not contain characters
  with values > 127, which means you can interpret the resulting string
  as UTF-8, ISO-8859-1, ASCII, KOI8-R or most about any character set and
  8-bit-encoding, and still get the same data structure back. This is useful
  when your channel for JSON transfer is not 8-bit clean or the encoding
  might be mangled in between (e.g. in mail), and works because ASCII is a
  proper subset of most 8-bit and multibyte encodings in use in the world.
  
  =back
  
  
  =head2 JSON and ECMAscript
  
  JSON syntax is based on how literals are represented in javascript (the
  not-standardised predecessor of ECMAscript) which is presumably why it is
  called "JavaScript Object Notation".
  
  However, JSON is not a subset (and also not a superset of course) of
  ECMAscript (the standard) or javascript (whatever browsers actually
  implement).
  
  If you want to use javascript's C<eval> function to "parse" JSON, you
  might run into parse errors for valid JSON texts, or the resulting data
  structure might not be queryable:
  
  One of the problems is that U+2028 and U+2029 are valid characters inside
  JSON strings, but are not allowed in ECMAscript string literals, so the
  following Perl fragment will not output something that can be guaranteed
  to be parsable by javascript's C<eval>:
  
     use JSON::XS;
  
     print encode_json [chr 0x2028];
  
  The right fix for this is to use a proper JSON parser in your javascript
  programs, and not rely on C<eval> (see for example Douglas Crockford's
  F<json2.js> parser).
  
  If this is not an option, you can, as a stop-gap measure, simply encode to
  ASCII-only JSON:
  
     use JSON::XS;
  
     print JSON::XS->new->ascii->encode ([chr 0x2028]);
  
  Note that this will enlarge the resulting JSON text quite a bit if you
  have many non-ASCII characters. You might be tempted to run some regexes
  to only escape U+2028 and U+2029, e.g.:
  
     # DO NOT USE THIS!
     my $json = JSON::XS->new->utf8->encode ([chr 0x2028]);
     $json =~ s/\xe2\x80\xa8/\\u2028/g; # escape U+2028
     $json =~ s/\xe2\x80\xa9/\\u2029/g; # escape U+2029
     print $json;
  
  Note that I<this is a bad idea>: the above only works for U+2028 and
  U+2029 and thus only for fully ECMAscript-compliant parsers. Many existing
  javascript implementations, however, have issues with other characters as
  well - using C<eval> naively simply I<will> cause problems.
  
  Another problem is that some javascript implementations reserve
  some property names for their own purposes (which probably makes
  them non-ECMAscript-compliant). For example, Iceweasel reserves the
  C<__proto__> property name for its own purposes.
  
  If that is a problem, you could parse try to filter the resulting JSON
  output for these property strings, e.g.:
  
     $json =~ s/"__proto__"\s*:/"__proto__renamed":/g;
  
  This works because C<__proto__> is not valid outside of strings, so every
  occurrence of C<"__proto__"\s*:> must be a string used as property name.
  
  If you know of other incompatibilities, please let me know.
  
  
  =head2 JSON and YAML
  
  You often hear that JSON is a subset of YAML. This is, however, a mass
  hysteria(*) and very far from the truth (as of the time of this writing),
  so let me state it clearly: I<in general, there is no way to configure
  JSON::XS to output a data structure as valid YAML> that works in all
  cases.
  
  If you really must use JSON::XS to generate YAML, you should use this
  algorithm (subject to change in future versions):
  
     my $to_yaml = JSON::XS->new->utf8->space_after (1);
     my $yaml = $to_yaml->encode ($ref) . "\n";
  
  This will I<usually> generate JSON texts that also parse as valid
  YAML. Please note that YAML has hardcoded limits on (simple) object key
  lengths that JSON doesn't have and also has different and incompatible
  unicode character escape syntax, so you should make sure that your hash
  keys are noticeably shorter than the 1024 "stream characters" YAML allows
  and that you do not have characters with codepoint values outside the
  Unicode BMP (basic multilingual page). YAML also does not allow C<\/>
  sequences in strings (which JSON::XS does not I<currently> generate, but
  other JSON generators might).
  
  There might be other incompatibilities that I am not aware of (or the YAML
  specification has been changed yet again - it does so quite often). In
  general you should not try to generate YAML with a JSON generator or vice
  versa, or try to parse JSON with a YAML parser or vice versa: chances are
  high that you will run into severe interoperability problems when you
  least expect it.
  
  =over 4
  
  =item (*)
  
  I have been pressured multiple times by Brian Ingerson (one of the
  authors of the YAML specification) to remove this paragraph, despite him
  acknowledging that the actual incompatibilities exist. As I was personally
  bitten by this "JSON is YAML" lie, I refused and said I will continue to
  educate people about these issues, so others do not run into the same
  problem again and again. After this, Brian called me a (quote)I<complete
  and worthless idiot>(unquote).
  
  In my opinion, instead of pressuring and insulting people who actually
  clarify issues with YAML and the wrong statements of some of its
  proponents, I would kindly suggest reading the JSON spec (which is not
  that difficult or long) and finally make YAML compatible to it, and
  educating users about the changes, instead of spreading lies about the
  real compatibility for many I<years> and trying to silence people who
  point out that it isn't true.
  
  Addendum/2009: the YAML 1.2 spec is still incompatible with JSON, even
  though the incompatibilities have been documented (and are known to Brian)
  for many years and the spec makes explicit claims that YAML is a superset
  of JSON. It would be so easy to fix, but apparently, bullying people and
  corrupting userdata is so much easier.
  
  =back
  
  
  =head2 SPEED
  
  It seems that JSON::XS is surprisingly fast, as shown in the following
  tables. They have been generated with the help of the C<eg/bench> program
  in the JSON::XS distribution, to make it easy to compare on your own
  system.
  
  First comes a comparison between various modules using
  a very short single-line JSON string (also available at
  L<http://dist.schmorp.de/misc/json/short.json>).
  
     {"method": "handleMessage", "params": ["user1",
     "we were just talking"], "id": null, "array":[1,11,234,-5,1e5,1e7,
     1,  0]}
  
  It shows the number of encodes/decodes per second (JSON::XS uses
  the functional interface, while JSON::XS/2 uses the OO interface
  with pretty-printing and hashkey sorting enabled, JSON::XS/3 enables
  shrink. JSON::DWIW/DS uses the deserialise function, while JSON::DWIW::FJ
  uses the from_json method). Higher is better:
  
     module        |     encode |     decode |
     --------------|------------|------------|
     JSON::DWIW/DS |  86302.551 | 102300.098 |
     JSON::DWIW/FJ |  86302.551 |  75983.768 |
     JSON::PP      |  15827.562 |   6638.658 |
     JSON::Syck    |  63358.066 |  47662.545 |
     JSON::XS      | 511500.488 | 511500.488 |
     JSON::XS/2    | 291271.111 | 388361.481 |
     JSON::XS/3    | 361577.931 | 361577.931 |
     Storable      |  66788.280 | 265462.278 |
     --------------+------------+------------+
  
  That is, JSON::XS is almost six times faster than JSON::DWIW on encoding,
  about five times faster on decoding, and over thirty to seventy times
  faster than JSON's pure perl implementation. It also compares favourably
  to Storable for small amounts of data.
  
  Using a longer test string (roughly 18KB, generated from Yahoo! Locals
  search API (L<http://dist.schmorp.de/misc/json/long.json>).
  
     module        |     encode |     decode |
     --------------|------------|------------|
     JSON::DWIW/DS |   1647.927 |   2673.916 |
     JSON::DWIW/FJ |   1630.249 |   2596.128 |
     JSON::PP      |    400.640 |     62.311 |
     JSON::Syck    |   1481.040 |   1524.869 |
     JSON::XS      |  20661.596 |   9541.183 |
     JSON::XS/2    |  10683.403 |   9416.938 |
     JSON::XS/3    |  20661.596 |   9400.054 |
     Storable      |  19765.806 |  10000.725 |
     --------------+------------+------------+
  
  Again, JSON::XS leads by far (except for Storable which non-surprisingly
  decodes a bit faster).
  
  On large strings containing lots of high Unicode characters, some modules
  (such as JSON::PC) seem to decode faster than JSON::XS, but the result
  will be broken due to missing (or wrong) Unicode handling. Others refuse
  to decode or encode properly, so it was impossible to prepare a fair
  comparison table for that case.
  
  
  =head1 SECURITY CONSIDERATIONS
  
  When you are using JSON in a protocol, talking to untrusted potentially
  hostile creatures requires relatively few measures.
  
  First of all, your JSON decoder should be secure, that is, should not have
  any buffer overflows. Obviously, this module should ensure that and I am
  trying hard on making that true, but you never know.
  
  Second, you need to avoid resource-starving attacks. That means you should
  limit the size of JSON texts you accept, or make sure then when your
  resources run out, that's just fine (e.g. by using a separate process that
  can crash safely). The size of a JSON text in octets or characters is
  usually a good indication of the size of the resources required to decode
  it into a Perl structure. While JSON::XS can check the size of the JSON
  text, it might be too late when you already have it in memory, so you
  might want to check the size before you accept the string.
  
  Third, JSON::XS recurses using the C stack when decoding objects and
  arrays. The C stack is a limited resource: for instance, on my amd64
  machine with 8MB of stack size I can decode around 180k nested arrays but
  only 14k nested JSON objects (due to perl itself recursing deeply on croak
  to free the temporary). If that is exceeded, the program crashes. To be
  conservative, the default nesting limit is set to 512. If your process
  has a smaller stack, you should adjust this setting accordingly with the
  C<max_depth> method.
  
  Something else could bomb you, too, that I forgot to think of. In that
  case, you get to keep the pieces. I am always open for hints, though...
  
  Also keep in mind that JSON::XS might leak contents of your Perl data
  structures in its error messages, so when you serialise sensitive
  information you might want to make sure that exceptions thrown by JSON::XS
  will not end up in front of untrusted eyes.
  
  If you are using JSON::XS to return packets to consumption
  by JavaScript scripts in a browser you should have a look at
  L<http://blog.archive.jpsykes.com/47/practical-csrf-and-json-security/> to
  see whether you are vulnerable to some common attack vectors (which really
  are browser design bugs, but it is still you who will have to deal with
  it, as major browser developers care only for features, not about getting
  security right).
  
  
  =head1 INTEROPERABILITY WITH OTHER MODULES
  
  C<JSON::XS> uses the L<Types::Serialiser> module to provide boolean
  constants. That means that the JSON true and false values will be
  comaptible to true and false values of iother modules that do the same,
  such as L<JSON::PP> and L<CBOR::XS>.
  
  
  =head1 THREADS
  
  This module is I<not> guaranteed to be thread safe and there are no
  plans to change this until Perl gets thread support (as opposed to the
  horribly slow so-called "threads" which are simply slow and bloated
  process simulations - use fork, it's I<much> faster, cheaper, better).
  
  (It might actually work, but you have been warned).
  
  
  =head1 THE PERILS OF SETLOCALE
  
  Sometimes people avoid the Perl locale support and directly call the
  system's setlocale function with C<LC_ALL>.
  
  This breaks both perl and modules such as JSON::XS, as stringification of
  numbers no longer works correctly (e.g. C<$x = 0.1; print "$x"+1> might
  print C<1>, and JSON::XS might output illegal JSON as JSON::XS relies on
  perl to stringify numbers).
  
  The solution is simple: don't call C<setlocale>, or use it for only those
  categories you need, such as C<LC_MESSAGES> or C<LC_CTYPE>.
  
  If you need C<LC_NUMERIC>, you should enable it only around the code that
  actually needs it (avoiding stringification of numbers), and restore it
  afterwards.
  
  
  =head1 BUGS
  
  While the goal of this module is to be correct, that unfortunately does
  not mean it's bug-free, only that I think its design is bug-free. If you
  keep reporting bugs they will be fixed swiftly, though.
  
  Please refrain from using rt.cpan.org or any other bug reporting
  service. I put the contact address into my modules for a reason.
  
  =cut
  
  BEGIN {
     *true    = \$Types::Serialiser::true;
     *true    = \&Types::Serialiser::true;
     *false   = \$Types::Serialiser::false;
     *false   = \&Types::Serialiser::false;
     *is_bool = \&Types::Serialiser::is_bool;
  
     *JSON::XS::Boolean:: = *Types::Serialiser::Boolean::;
  }
  
  XSLoader::load "JSON::XS", $VERSION;
  
  =head1 SEE ALSO
  
  The F<json_xs> command line utility for quick experiments.
  
  =head1 AUTHOR
  
   Marc Lehmann <schmorp@schmorp.de>
   http://home.schmorp.de/
  
  =cut
  
  1
  
X86_64-LINUX_JSON_XS

$fatpacked{"x86_64-linux/JSON/XS/Boolean.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'X86_64-LINUX_JSON_XS_BOOLEAN';
  =head1 NAME
  
  JSON::XS::Boolean - dummy module providing JSON::XS::Boolean
  
  =head1 SYNOPSIS
  
   # do not "use" yourself
  
  =head1 DESCRIPTION
  
  This module exists only to provide overload resolution for Storable and
  similar modules. It's only needed for compatibility with data serialised
  (by other modules such as Storable) that was decoded by JSON::XS versions
  before 3.0.
  
  Since 3.0, JSON::PP::Boolean has replaced it. Support for
  JSON::XS::Boolean will be removed in a future release.
  
  =cut
  
  use JSON::XS ();
  
  1;
  
  =head1 AUTHOR
  
   Marc Lehmann <schmorp@schmorp.de>
   http://home.schmorp.de/
  
  =cut
  
X86_64-LINUX_JSON_XS_BOOLEAN

$fatpacked{"x86_64-linux/List/Util.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'X86_64-LINUX_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
X86_64-LINUX_LIST_UTIL

$fatpacked{"x86_64-linux/List/Util/XS.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'X86_64-LINUX_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
X86_64-LINUX_LIST_UTIL_XS

$fatpacked{"x86_64-linux/MIME/Base64.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'X86_64-LINUX_MIME_BASE64';
  package MIME::Base64;
  
  use strict;
  use vars qw(@ISA @EXPORT @EXPORT_OK $VERSION);
  
  require Exporter;
  @ISA = qw(Exporter);
  @EXPORT = qw(encode_base64 decode_base64);
  @EXPORT_OK = qw(encode_base64url decode_base64url encoded_base64_length decoded_base64_length);
  
  $VERSION = '3.14';
  
  require XSLoader;
  XSLoader::load('MIME::Base64', $VERSION);
  
  *encode = \&encode_base64;
  *decode = \&decode_base64;
  
  sub encode_base64url {
      my $e = encode_base64(shift, "");
      $e =~ s/=+\z//;
      $e =~ tr[+/][-_];
      return $e;
  }
  
  sub decode_base64url {
      my $s = shift;
      $s =~ tr[-_][+/];
      $s .= '=' while length($s) % 4;
      return decode_base64($s);
  }
  
  1;
  
  __END__
  
  =head1 NAME
  
  MIME::Base64 - Encoding and decoding of base64 strings
  
  =head1 SYNOPSIS
  
   use MIME::Base64;
  
   $encoded = encode_base64('Aladdin:open sesame');
   $decoded = decode_base64($encoded);
  
  =head1 DESCRIPTION
  
  This module provides functions to encode and decode strings into and from the
  base64 encoding specified in RFC 2045 - I<MIME (Multipurpose Internet
  Mail Extensions)>. The base64 encoding is designed to represent
  arbitrary sequences of octets in a form that need not be humanly
  readable. A 65-character subset ([A-Za-z0-9+/=]) of US-ASCII is used,
  enabling 6 bits to be represented per printable character.
  
  The following primary functions are provided:
  
  =over 4
  
  =item encode_base64( $bytes )
  
  =item encode_base64( $bytes, $eol );
  
  Encode data by calling the encode_base64() function.  The first
  argument is the byte string to encode.  The second argument is the
  line-ending sequence to use.  It is optional and defaults to "\n".  The
  returned encoded string is broken into lines of no more than 76
  characters each and it will end with $eol unless it is empty.  Pass an
  empty string as second argument if you do not want the encoded string
  to be broken into lines.
  
  The function will croak with "Wide character in subroutine entry" if $bytes
  contains characters with code above 255.  The base64 encoding is only defined
  for single-byte characters.  Use the Encode module to select the byte encoding
  you want.
  
  =item decode_base64( $str )
  
  Decode a base64 string by calling the decode_base64() function.  This
  function takes a single argument which is the string to decode and
  returns the decoded data.
  
  Any character not part of the 65-character base64 subset is
  silently ignored.  Characters occurring after a '=' padding character
  are never decoded.
  
  =back
  
  If you prefer not to import these routines into your namespace, you can
  call them as:
  
      use MIME::Base64 ();
      $encoded = MIME::Base64::encode($decoded);
      $decoded = MIME::Base64::decode($encoded);
  
  Additional functions not exported by default:
  
  =over 4
  
  =item encode_base64url( $bytes )
  
  =item decode_base64url( $str )
  
  Encode and decode according to the base64 scheme for "URL applications" [1].
  This is a variant of the base64 encoding which does not use padding, does not
  break the string into multiple lines and use the characters "-" and "_" instead
  of "+" and "/" to avoid using reserved URL characters.
  
  =item encoded_base64_length( $bytes )
  
  =item encoded_base64_length( $bytes, $eol )
  
  Returns the length that the encoded string would have without actually
  encoding it.  This will return the same value as C<< length(encode_base64($bytes)) >>,
  but should be more efficient.
  
  =item decoded_base64_length( $str )
  
  Returns the length that the decoded string would have without actually
  decoding it.  This will return the same value as C<< length(decode_base64($str)) >>,
  but should be more efficient.
  
  =back
  
  =head1 EXAMPLES
  
  If you want to encode a large file, you should encode it in chunks
  that are a multiple of 57 bytes.  This ensures that the base64 lines
  line up and that you do not end up with padding in the middle. 57
  bytes of data fills one complete base64 line (76 == 57*4/3):
  
     use MIME::Base64 qw(encode_base64);
  
     open(FILE, "/var/log/wtmp") or die "$!";
     while (read(FILE, $buf, 60*57)) {
         print encode_base64($buf);
     }
  
  or if you know you have enough memory
  
     use MIME::Base64 qw(encode_base64);
     local($/) = undef;  # slurp
     print encode_base64(<STDIN>);
  
  The same approach as a command line:
  
     perl -MMIME::Base64 -0777 -ne 'print encode_base64($_)' <file
  
  Decoding does not need slurp mode if every line contains a multiple
  of four base64 chars:
  
     perl -MMIME::Base64 -ne 'print decode_base64($_)' <file
  
  Perl v5.8 and better allow extended Unicode characters in strings.
  Such strings cannot be encoded directly, as the base64
  encoding is only defined for single-byte characters.  The solution is
  to use the Encode module to select the byte encoding you want.  For
  example:
  
      use MIME::Base64 qw(encode_base64);
      use Encode qw(encode);
  
      $encoded = encode_base64(encode("UTF-8", "\x{FFFF}\n"));
      print $encoded;
  
  =head1 COPYRIGHT
  
  Copyright 1995-1999, 2001-2004, 2010 Gisle Aas.
  
  This library is free software; you can redistribute it and/or
  modify it under the same terms as Perl itself.
  
  Distantly based on LWP::Base64 written by Martijn Koster
  <m.koster@nexor.co.uk> and Joerg Reichelt <j.reichelt@nexor.co.uk> and
  code posted to comp.lang.perl <3pd2lp$6gf@wsinti07.win.tue.nl> by Hans
  Mulder <hansm@wsinti07.win.tue.nl>
  
  The XS implementation uses code from metamail.  Copyright 1991 Bell
  Communications Research, Inc. (Bellcore)
  
  =head1 SEE ALSO
  
  L<MIME::QuotedPrint>
  
  [1] L<http://en.wikipedia.org/wiki/Base64#URL_applications>
  
  =cut
X86_64-LINUX_MIME_BASE64

$fatpacked{"x86_64-linux/MIME/QuotedPrint.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'X86_64-LINUX_MIME_QUOTEDPRINT';
  package MIME::QuotedPrint;
  
  use strict;
  use vars qw(@ISA @EXPORT $VERSION);
  
  require Exporter;
  @ISA = qw(Exporter);
  @EXPORT = qw(encode_qp decode_qp);
  
  $VERSION = "3.13";
  
  use MIME::Base64;  # will load XS version of {en,de}code_qp()
  
  *encode = \&encode_qp;
  *decode = \&decode_qp;
  
  1;
  
  __END__
  
  =head1 NAME
  
  MIME::QuotedPrint - Encoding and decoding of quoted-printable strings
  
  =head1 SYNOPSIS
  
   use MIME::QuotedPrint;
  
   $encoded = encode_qp($decoded);
   $decoded = decode_qp($encoded);
  
  =head1 DESCRIPTION
  
  This module provides functions to encode and decode strings into and from the
  quoted-printable encoding specified in RFC 2045 - I<MIME (Multipurpose
  Internet Mail Extensions)>.  The quoted-printable encoding is intended
  to represent data that largely consists of bytes that correspond to
  printable characters in the ASCII character set.  Each non-printable
  character (as defined by English Americans) is represented by a
  triplet consisting of the character "=" followed by two hexadecimal
  digits.
  
  The following functions are provided:
  
  =over 4
  
  =item encode_qp( $str)
  
  =item encode_qp( $str, $eol)
  
  =item encode_qp( $str, $eol, $binmode )
  
  This function returns an encoded version of the string ($str) given as
  argument.
  
  The second argument ($eol) is the line-ending sequence to use.  It is
  optional and defaults to "\n".  Every occurrence of "\n" is replaced
  with this string, and it is also used for additional "soft line
  breaks" to ensure that no line end up longer than 76 characters.  Pass
  it as "\015\012" to produce data suitable for external consumption.
  The string "\r\n" produces the same result on many platforms, but not
  all.
  
  The third argument ($binmode) will select binary mode if passed as a
  TRUE value.  In binary mode "\n" will be encoded in the same way as
  any other non-printable character.  This ensures that a decoder will
  end up with exactly the same string whatever line ending sequence it
  uses.  In general it is preferable to use the base64 encoding for
  binary data; see L<MIME::Base64>.
  
  An $eol of "" (the empty string) is special.  In this case, no "soft
  line breaks" are introduced and binary mode is effectively enabled so
  that any "\n" in the original data is encoded as well.
  
  =item decode_qp( $str )
  
  This function returns the plain text version of the string given
  as argument.  The lines of the result are "\n" terminated, even if
  the $str argument contains "\r\n" terminated lines.
  
  =back
  
  
  If you prefer not to import these routines into your namespace, you can
  call them as:
  
    use MIME::QuotedPrint ();
    $encoded = MIME::QuotedPrint::encode($decoded);
    $decoded = MIME::QuotedPrint::decode($encoded);
  
  Perl v5.8 and better allow extended Unicode characters in strings.
  Such strings cannot be encoded directly, as the quoted-printable
  encoding is only defined for single-byte characters.  The solution is
  to use the Encode module to select the byte encoding you want.  For
  example:
  
      use MIME::QuotedPrint qw(encode_qp);
      use Encode qw(encode);
  
      $encoded = encode_qp(encode("UTF-8", "\x{FFFF}\n"));
      print $encoded;
  
  =head1 COPYRIGHT
  
  Copyright 1995-1997,2002-2004 Gisle Aas.
  
  This library is free software; you can redistribute it and/or
  modify it under the same terms as Perl itself.
  
  =head1 SEE ALSO
  
  L<MIME::Base64>
  
  =cut
X86_64-LINUX_MIME_QUOTEDPRINT

$fatpacked{"x86_64-linux/Scalar/Util.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'X86_64-LINUX_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
X86_64-LINUX_SCALAR_UTIL

$fatpacked{"x86_64-linux/Socket.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'X86_64-LINUX_SOCKET';
  package Socket;
  
  use strict;
  { use 5.006001; }
  
  our $VERSION = '2.013';
  
  =head1 NAME
  
  C<Socket> - networking constants and support functions
  
  =head1 SYNOPSIS
  
  C<Socket> a low-level module used by, among other things, the L<IO::Socket>
  family of modules. The following examples demonstrate some low-level uses but
  a practical program would likely use the higher-level API provided by
  C<IO::Socket> or similar instead.
  
   use Socket qw(PF_INET SOCK_STREAM pack_sockaddr_in inet_aton);
  
   socket(my $socket, PF_INET, SOCK_STREAM, 0)
       or die "socket: $!";
  
   my $port = getservbyname "echo", "tcp";
   connect($socket, pack_sockaddr_in($port, inet_aton("localhost")))
       or die "connect: $!";
  
   print $socket "Hello, world!\n";
   print <$socket>;
  
  See also the L</EXAMPLES> section.
  
  =head1 DESCRIPTION
  
  This module provides a variety of constants, structure manipulators and other
  functions related to socket-based networking. The values and functions
  provided are useful when used in conjunction with Perl core functions such as
  socket(), setsockopt() and bind(). It also provides several other support
  functions, mostly for dealing with conversions of network addresses between
  human-readable and native binary forms, and for hostname resolver operations.
  
  Some constants and functions are exported by default by this module; but for
  backward-compatibility any recently-added symbols are not exported by default
  and must be requested explicitly. When an import list is provided to the
  C<use Socket> line, the default exports are not automatically imported. It is
  therefore best practice to always to explicitly list all the symbols required.
  
  Also, some common socket "newline" constants are provided: the constants
  C<CR>, C<LF>, and C<CRLF>, as well as C<$CR>, C<$LF>, and C<$CRLF>, which map
  to C<\015>, C<\012>, and C<\015\012>. If you do not want to use the literal
  characters in your programs, then use the constants provided here. They are
  not exported by default, but can be imported individually, and with the
  C<:crlf> export tag:
  
   use Socket qw(:DEFAULT :crlf);
  
   $sock->print("GET / HTTP/1.0$CRLF");
  
  The entire getaddrinfo() subsystem can be exported using the tag C<:addrinfo>;
  this exports the getaddrinfo() and getnameinfo() functions, and all the
  C<AI_*>, C<NI_*>, C<NIx_*> and C<EAI_*> constants.
  
  =cut
  
  =head1 CONSTANTS
  
  In each of the following groups, there may be many more constants provided
  than just the ones given as examples in the section heading. If the heading
  ends C<...> then this means there are likely more; the exact constants
  provided will depend on the OS and headers found at compile-time.
  
  =cut
  
  =head2 PF_INET, PF_INET6, PF_UNIX, ...
  
  Protocol family constants to use as the first argument to socket() or the
  value of the C<SO_DOMAIN> or C<SO_FAMILY> socket option.
  
  =head2 AF_INET, AF_INET6, AF_UNIX, ...
  
  Address family constants used by the socket address structures, to pass to
  such functions as inet_pton() or getaddrinfo(), or are returned by such
  functions as sockaddr_family().
  
  =head2 SOCK_STREAM, SOCK_DGRAM, SOCK_RAW, ...
  
  Socket type constants to use as the second argument to socket(), or the value
  of the C<SO_TYPE> socket option.
  
  =head2 SOCK_NONBLOCK. SOCK_CLOEXEC
  
  Linux-specific shortcuts to specify the C<O_NONBLOCK> and C<FD_CLOEXEC> flags
  during a C<socket(2)> call.
  
   socket( my $sockh, PF_INET, SOCK_DGRAM|SOCK_NONBLOCK, 0 )
  
  =head2 SOL_SOCKET
  
  Socket option level constant for setsockopt() and getsockopt().
  
  =head2 SO_ACCEPTCONN, SO_BROADCAST, SO_ERROR, ...
  
  Socket option name constants for setsockopt() and getsockopt() at the
  C<SOL_SOCKET> level.
  
  =head2 IP_OPTIONS, IP_TOS, IP_TTL, ...
  
  Socket option name constants for IPv4 socket options at the C<IPPROTO_IP>
  level.
  
  =head2 IPTOS_LOWDELAY, IPTOS_THROUGHPUT, IPTOS_RELIABILITY, ...
  
  Socket option value constants for C<IP_TOS> socket option.
  
  =head2 MSG_BCAST, MSG_OOB, MSG_TRUNC, ...
  
  Message flag constants for send() and recv().
  
  =head2 SHUT_RD, SHUT_RDWR, SHUT_WR
  
  Direction constants for shutdown().
  
  =head2 INADDR_ANY, INADDR_BROADCAST, INADDR_LOOPBACK, INADDR_NONE
  
  Constants giving the special C<AF_INET> addresses for wildcard, broadcast,
  local loopback, and invalid addresses.
  
  Normally equivalent to inet_aton('0.0.0.0'), inet_aton('255.255.255.255'),
  inet_aton('localhost') and inet_aton('255.255.255.255') respectively.
  
  =head2 IPPROTO_IP, IPPROTO_IPV6, IPPROTO_TCP, ...
  
  IP protocol constants to use as the third argument to socket(), the level
  argument to getsockopt() or setsockopt(), or the value of the C<SO_PROTOCOL>
  socket option.
  
  =head2 TCP_CORK, TCP_KEEPALIVE, TCP_NODELAY, ...
  
  Socket option name constants for TCP socket options at the C<IPPROTO_TCP>
  level.
  
  =head2 IN6ADDR_ANY, IN6ADDR_LOOPBACK
  
  Constants giving the special C<AF_INET6> addresses for wildcard and local
  loopback.
  
  Normally equivalent to inet_pton(AF_INET6, "::") and
  inet_pton(AF_INET6, "::1") respectively.
  
  =head2 IPV6_ADD_MEMBERSHIP, IPV6_MTU, IPV6_V6ONLY, ...
  
  Socket option name constants for IPv6 socket options at the C<IPPROTO_IPV6>
  level.
  
  =cut
  
  # Still undocumented: SCM_*, SOMAXCONN, IOV_MAX, UIO_MAXIOV
  
  =head1 STRUCTURE MANIPULATORS
  
  The following functions convert between lists of Perl values and packed binary
  strings representing structures.
  
  =cut
  
  =head2 $family = sockaddr_family $sockaddr
  
  Takes a packed socket address (as returned by pack_sockaddr_in(),
  pack_sockaddr_un() or the perl builtin functions getsockname() and
  getpeername()). Returns the address family tag. This will be one of the
  C<AF_*> constants, such as C<AF_INET> for a C<sockaddr_in> addresses or
  C<AF_UNIX> for a C<sockaddr_un>. It can be used to figure out what unpack to
  use for a sockaddr of unknown type.
  
  =head2 $sockaddr = pack_sockaddr_in $port, $ip_address
  
  Takes two arguments, a port number and an opaque string (as returned by
  inet_aton(), or a v-string). Returns the C<sockaddr_in> structure with those
  arguments packed in and C<AF_INET> filled in. For Internet domain sockets,
  this structure is normally what you need for the arguments in bind(),
  connect(), and send().
  
  =head2 ($port, $ip_address) = unpack_sockaddr_in $sockaddr
  
  Takes a C<sockaddr_in> structure (as returned by pack_sockaddr_in(),
  getpeername() or recv()). Returns a list of two elements: the port and an
  opaque string representing the IP address (you can use inet_ntoa() to convert
  the address to the four-dotted numeric format). Will croak if the structure
  does not represent an C<AF_INET> address.
  
  In scalar context will return just the IP address.
  
  =head2 $sockaddr = sockaddr_in $port, $ip_address
  
  =head2 ($port, $ip_address) = sockaddr_in $sockaddr
  
  A wrapper of pack_sockaddr_in() or unpack_sockaddr_in(). In list context,
  unpacks its argument and returns a list consisting of the port and IP address.
  In scalar context, packs its port and IP address arguments as a C<sockaddr_in>
  and returns it.
  
  Provided largely for legacy compatibility; it is better to use
  pack_sockaddr_in() or unpack_sockaddr_in() explicitly.
  
  =head2 $sockaddr = pack_sockaddr_in6 $port, $ip6_address, [$scope_id, [$flowinfo]]
  
  Takes two to four arguments, a port number, an opaque string (as returned by
  inet_pton()), optionally a scope ID number, and optionally a flow label
  number. Returns the C<sockaddr_in6> structure with those arguments packed in
  and C<AF_INET6> filled in. IPv6 equivalent of pack_sockaddr_in().
  
  =head2 ($port, $ip6_address, $scope_id, $flowinfo) = unpack_sockaddr_in6 $sockaddr
  
  Takes a C<sockaddr_in6> structure. Returns a list of four elements: the port
  number, an opaque string representing the IPv6 address, the scope ID, and the
  flow label. (You can use inet_ntop() to convert the address to the usual
  string format). Will croak if the structure does not represent an C<AF_INET6>
  address.
  
  In scalar context will return just the IP address.
  
  =head2 $sockaddr = sockaddr_in6 $port, $ip6_address, [$scope_id, [$flowinfo]]
  
  =head2 ($port, $ip6_address, $scope_id, $flowinfo) = sockaddr_in6 $sockaddr
  
  A wrapper of pack_sockaddr_in6() or unpack_sockaddr_in6(). In list context,
  unpacks its argument according to unpack_sockaddr_in6(). In scalar context,
  packs its arguments according to pack_sockaddr_in6().
  
  Provided largely for legacy compatibility; it is better to use
  pack_sockaddr_in6() or unpack_sockaddr_in6() explicitly.
  
  =head2 $sockaddr = pack_sockaddr_un $path
  
  Takes one argument, a pathname. Returns the C<sockaddr_un> structure with that
  path packed in with C<AF_UNIX> filled in. For C<PF_UNIX> sockets, this
  structure is normally what you need for the arguments in bind(), connect(),
  and send().
  
  =head2 ($path) = unpack_sockaddr_un $sockaddr
  
  Takes a C<sockaddr_un> structure (as returned by pack_sockaddr_un(),
  getpeername() or recv()). Returns a list of one element: the pathname. Will
  croak if the structure does not represent an C<AF_UNIX> address.
  
  =head2 $sockaddr = sockaddr_un $path
  
  =head2 ($path) = sockaddr_un $sockaddr
  
  A wrapper of pack_sockaddr_un() or unpack_sockaddr_un(). In a list context,
  unpacks its argument and returns a list consisting of the pathname. In a
  scalar context, packs its pathname as a C<sockaddr_un> and returns it.
  
  Provided largely for legacy compatibility; it is better to use
  pack_sockaddr_un() or unpack_sockaddr_un() explicitly.
  
  These are only supported if your system has E<lt>F<sys/un.h>E<gt>.
  
  =head2 $ip_mreq = pack_ip_mreq $multiaddr, $interface
  
  Takes an IPv4 multicast address and optionally an interface address (or
  C<INADDR_ANY>). Returns the C<ip_mreq> structure with those arguments packed
  in. Suitable for use with the C<IP_ADD_MEMBERSHIP> and C<IP_DROP_MEMBERSHIP>
  sockopts.
  
  =head2 ($multiaddr, $interface) = unpack_ip_mreq $ip_mreq
  
  Takes an C<ip_mreq> structure. Returns a list of two elements; the IPv4
  multicast address and interface address.
  
  =head2 $ip_mreq_source = pack_ip_mreq_source $multiaddr, $source, $interface
  
  Takes an IPv4 multicast address, source address, and optionally an interface
  address (or C<INADDR_ANY>). Returns the C<ip_mreq_source> structure with those
  arguments packed in. Suitable for use with the C<IP_ADD_SOURCE_MEMBERSHIP>
  and C<IP_DROP_SOURCE_MEMBERSHIP> sockopts.
  
  =head2 ($multiaddr, $source, $interface) = unpack_ip_mreq_source $ip_mreq
  
  Takes an C<ip_mreq_source> structure. Returns a list of three elements; the
  IPv4 multicast address, source address and interface address.
  
  =head2 $ipv6_mreq = pack_ipv6_mreq $multiaddr6, $ifindex
  
  Takes an IPv6 multicast address and an interface number. Returns the
  C<ipv6_mreq> structure with those arguments packed in. Suitable for use with
  the C<IPV6_ADD_MEMBERSHIP> and C<IPV6_DROP_MEMBERSHIP> sockopts.
  
  =head2 ($multiaddr6, $ifindex) = unpack_ipv6_mreq $ipv6_mreq
  
  Takes an C<ipv6_mreq> structure. Returns a list of two elements; the IPv6
  address and an interface number.
  
  =cut
  
  =head1 FUNCTIONS
  
  =cut
  
  =head2 $ip_address = inet_aton $string
  
  Takes a string giving the name of a host, or a textual representation of an IP
  address and translates that to an packed binary address structure suitable to
  pass to pack_sockaddr_in(). If passed a hostname that cannot be resolved,
  returns C<undef>. For multi-homed hosts (hosts with more than one address),
  the first address found is returned.
  
  For portability do not assume that the result of inet_aton() is 32 bits wide,
  in other words, that it would contain only the IPv4 address in network order.
  
  This IPv4-only function is provided largely for legacy reasons. Newly-written
  code should use getaddrinfo() or inet_pton() instead for IPv6 support.
  
  =head2 $string = inet_ntoa $ip_address
  
  Takes a packed binary address structure such as returned by
  unpack_sockaddr_in() (or a v-string representing the four octets of the IPv4
  address in network order) and translates it into a string of the form
  C<d.d.d.d> where the C<d>s are numbers less than 256 (the normal
  human-readable four dotted number notation for Internet addresses).
  
  This IPv4-only function is provided largely for legacy reasons. Newly-written
  code should use getnameinfo() or inet_ntop() instead for IPv6 support.
  
  =head2 $address = inet_pton $family, $string
  
  Takes an address family (such as C<AF_INET> or C<AF_INET6>) and a string
  containing a textual representation of an address in that family and
  translates that to an packed binary address structure.
  
  See also getaddrinfo() for a more powerful and flexible function to look up
  socket addresses given hostnames or textual addresses.
  
  =head2 $string = inet_ntop $family, $address
  
  Takes an address family and a packed binary address structure and translates
  it into a human-readable textual representation of the address; typically in
  C<d.d.d.d> form for C<AF_INET> or C<hhhh:hhhh::hhhh> form for C<AF_INET6>.
  
  See also getnameinfo() for a more powerful and flexible function to turn
  socket addresses into human-readable textual representations.
  
  =head2 ($err, @result) = getaddrinfo $host, $service, [$hints]
  
  Given both a hostname and service name, this function attempts to resolve the
  host name into a list of network addresses, and the service name into a
  protocol and port number, and then returns a list of address structures
  suitable to connect() to it.
  
  Given just a host name, this function attempts to resolve it to a list of
  network addresses, and then returns a list of address structures giving these
  addresses.
  
  Given just a service name, this function attempts to resolve it to a protocol
  and port number, and then returns a list of address structures that represent
  it suitable to bind() to. This use should be combined with the C<AI_PASSIVE>
  flag; see below.
  
  Given neither name, it generates an error.
  
  If present, $hints should be a reference to a hash, where the following keys
  are recognised:
  
  =over 4
  
  =item flags => INT
  
  A bitfield containing C<AI_*> constants; see below.
  
  =item family => INT
  
  Restrict to only generating addresses in this address family
  
  =item socktype => INT
  
  Restrict to only generating addresses of this socket type
  
  =item protocol => INT
  
  Restrict to only generating addresses for this protocol
  
  =back
  
  The return value will be a list; the first value being an error indication,
  followed by a list of address structures (if no error occurred).
  
  The error value will be a dualvar; comparable to the C<EI_*> error constants,
  or printable as a human-readable error message string. If no error occurred it
  will be zero numerically and an empty string.
  
  Each value in the results list will be a hash reference containing the following
  fields:
  
  =over 4
  
  =item family => INT
  
  The address family (e.g. C<AF_INET>)
  
  =item socktype => INT
  
  The socket type (e.g. C<SOCK_STREAM>)
  
  =item protocol => INT
  
  The protocol (e.g. C<IPPROTO_TCP>)
  
  =item addr => STRING
  
  The address in a packed string (such as would be returned by
  pack_sockaddr_in())
  
  =item canonname => STRING
  
  The canonical name for the host if the C<AI_CANONNAME> flag was provided, or
  C<undef> otherwise. This field will only be present on the first returned
  address.
  
  =back
  
  The following flag constants are recognised in the $hints hash. Other flag
  constants may exist as provided by the OS.
  
  =over 4
  
  =item AI_PASSIVE
  
  Indicates that this resolution is for a local bind() for a passive (i.e.
  listening) socket, rather than an active (i.e. connecting) socket.
  
  =item AI_CANONNAME
  
  Indicates that the caller wishes the canonical hostname (C<canonname>) field
  of the result to be filled in.
  
  =item AI_NUMERICHOST
  
  Indicates that the caller will pass a numeric address, rather than a hostname,
  and that getaddrinfo() must not perform a resolve operation on this name. This
  flag will prevent a possibly-slow network lookup operation, and instead return
  an error if a hostname is passed.
  
  =back
  
  =head2 ($err, $hostname, $servicename) = getnameinfo $sockaddr, [$flags, [$xflags]]
  
  Given a packed socket address (such as from getsockname(), getpeername(), or
  returned by getaddrinfo() in a C<addr> field), returns the hostname and
  symbolic service name it represents. $flags may be a bitmask of C<NI_*>
  constants, or defaults to 0 if unspecified.
  
  The return value will be a list; the first value being an error condition,
  followed by the hostname and service name.
  
  The error value will be a dualvar; comparable to the C<EI_*> error constants,
  or printable as a human-readable error message string. The host and service
  names will be plain strings.
  
  The following flag constants are recognised as $flags. Other flag constants may
  exist as provided by the OS.
  
  =over 4
  
  =item NI_NUMERICHOST
  
  Requests that a human-readable string representation of the numeric address be
  returned directly, rather than performing a name resolve operation that may
  convert it into a hostname. This will also avoid potentially-blocking network
  IO.
  
  =item NI_NUMERICSERV
  
  Requests that the port number be returned directly as a number representation
  rather than performing a name resolve operation that may convert it into a
  service name.
  
  =item NI_NAMEREQD
  
  If a name resolve operation fails to provide a name, then this flag will cause
  getnameinfo() to indicate an error, rather than returning the numeric
  representation as a human-readable string.
  
  =item NI_DGRAM
  
  Indicates that the socket address relates to a C<SOCK_DGRAM> socket, for the
  services whose name differs between TCP and UDP protocols.
  
  =back
  
  The following constants may be supplied as $xflags.
  
  =over 4
  
  =item NIx_NOHOST
  
  Indicates that the caller is not interested in the hostname of the result, so
  it does not have to be converted. C<undef> will be returned as the hostname.
  
  =item NIx_NOSERV
  
  Indicates that the caller is not interested in the service name of the result,
  so it does not have to be converted. C<undef> will be returned as the service
  name.
  
  =back
  
  =head1 getaddrinfo() / getnameinfo() ERROR CONSTANTS
  
  The following constants may be returned by getaddrinfo() or getnameinfo().
  Others may be provided by the OS.
  
  =over 4
  
  =item EAI_AGAIN
  
  A temporary failure occurred during name resolution. The operation may be
  successful if it is retried later.
  
  =item EAI_BADFLAGS
  
  The value of the C<flags> hint to getaddrinfo(), or the $flags parameter to
  getnameinfo() contains unrecognised flags.
  
  =item EAI_FAMILY
  
  The C<family> hint to getaddrinfo(), or the family of the socket address
  passed to getnameinfo() is not supported.
  
  =item EAI_NODATA
  
  The host name supplied to getaddrinfo() did not provide any usable address
  data.
  
  =item EAI_NONAME
  
  The host name supplied to getaddrinfo() does not exist, or the address
  supplied to getnameinfo() is not associated with a host name and the
  C<NI_NAMEREQD> flag was supplied.
  
  =item EAI_SERVICE
  
  The service name supplied to getaddrinfo() is not available for the socket
  type given in the $hints.
  
  =back
  
  =cut
  
  =head1 EXAMPLES
  
  =head2 Lookup for connect()
  
  The getaddrinfo() function converts a hostname and a service name into a list
  of structures, each containing a potential way to connect() to the named
  service on the named host.
  
   use IO::Socket;
   use Socket qw(SOCK_STREAM getaddrinfo);
  
   my %hints = (socktype => SOCK_STREAM);
   my ($err, @res) = getaddrinfo("localhost", "echo", \%hints);
   die "Cannot getaddrinfo - $err" if $err;
  
   my $sock;
  
   foreach my $ai (@res) {
       my $candidate = IO::Socket->new();
  
       $candidate->socket($ai->{family}, $ai->{socktype}, $ai->{protocol})
           or next;
  
       $candidate->connect($ai->{addr})
           or next;
  
       $sock = $candidate;
       last;
   }
  
   die "Cannot connect to localhost:echo" unless $sock;
  
   $sock->print("Hello, world!\n");
   print <$sock>;
  
  Because a list of potential candidates is returned, the C<while> loop tries
  each in turn until it finds one that succeeds both the socket() and connect()
  calls.
  
  This function performs the work of the legacy functions gethostbyname(),
  getservbyname(), inet_aton() and pack_sockaddr_in().
  
  In practice this logic is better performed by L<IO::Socket::IP>.
  
  =head2 Making a human-readable string out of an address
  
  The getnameinfo() function converts a socket address, such as returned by
  getsockname() or getpeername(), into a pair of human-readable strings
  representing the address and service name.
  
   use IO::Socket::IP;
   use Socket qw(getnameinfo);
  
   my $server = IO::Socket::IP->new(LocalPort => 12345, Listen => 1) or
       die "Cannot listen - $@";
  
   my $socket = $server->accept or die "accept: $!";
  
   my ($err, $hostname, $servicename) = getnameinfo($socket->peername);
   die "Cannot getnameinfo - $err" if $err;
  
   print "The peer is connected from $hostname\n";
  
  Since in this example only the hostname was used, the redundant conversion of
  the port number into a service name may be omitted by passing the
  C<NIx_NOSERV> flag.
  
   use Socket qw(getnameinfo NIx_NOSERV);
  
   my ($err, $hostname) = getnameinfo($socket->peername, 0, NIx_NOSERV);
  
  This function performs the work of the legacy functions unpack_sockaddr_in(),
  inet_ntoa(), gethostbyaddr() and getservbyport().
  
  In practice this logic is better performed by L<IO::Socket::IP>.
  
  =head2 Resolving hostnames into IP addresses
  
  To turn a hostname into a human-readable plain IP address use getaddrinfo()
  to turn the hostname into a list of socket structures, then getnameinfo() on
  each one to make it a readable IP address again.
  
   use Socket qw(:addrinfo SOCK_RAW);
  
   my ($err, @res) = getaddrinfo($hostname, "", {socktype => SOCK_RAW});
   die "Cannot getaddrinfo - $err" if $err;
  
   while( my $ai = shift @res ) {
       my ($err, $ipaddr) = getnameinfo($ai->{addr}, NI_NUMERICHOST, NIx_NOSERV);
       die "Cannot getnameinfo - $err" if $err;
  
       print "$ipaddr\n";
   }
  
  The C<socktype> hint to getaddrinfo() filters the results to only include one
  socket type and protocol. Without this most OSes return three combinations,
  for C<SOCK_STREAM>, C<SOCK_DGRAM> and C<SOCK_RAW>, resulting in triplicate
  output of addresses. The C<NI_NUMERICHOST> flag to getnameinfo() causes it to
  return a string-formatted plain IP address, rather than reverse resolving it
  back into a hostname.
  
  This combination performs the work of the legacy functions gethostbyname()
  and inet_ntoa().
  
  =head2 Accessing socket options
  
  The many C<SO_*> and other constants provide the socket option names for
  getsockopt() and setsockopt().
  
   use IO::Socket::INET;
   use Socket qw(SOL_SOCKET SO_RCVBUF IPPROTO_IP IP_TTL);
  
   my $socket = IO::Socket::INET->new(LocalPort => 0, Proto => 'udp')
       or die "Cannot create socket: $@";
  
   $socket->setsockopt(SOL_SOCKET, SO_RCVBUF, 64*1024) or
       die "setsockopt: $!";
  
   print "Receive buffer is ", $socket->getsockopt(SOL_SOCKET, SO_RCVBUF),
       " bytes\n";
  
   print "IP TTL is ", $socket->getsockopt(IPPROTO_IP, IP_TTL), "\n";
  
  As a convenience, L<IO::Socket>'s setsockopt() method will convert a number
  into a packed byte buffer, and getsockopt() will unpack a byte buffer of the
  correct size back into a number.
  
  =cut
  
  =head1 AUTHOR
  
  This module was originally maintained in Perl core by the Perl 5 Porters.
  
  It was extracted to dual-life on CPAN at version 1.95 by
  Paul Evans <leonerd@leonerd.org.uk>
  
  =cut
  
  use Carp;
  use warnings::register;
  
  require Exporter;
  require XSLoader;
  our @ISA = qw(Exporter);
  
  # <@Nicholas> you can't change @EXPORT without breaking the implicit API
  # Please put any new constants in @EXPORT_OK!
  
  # List re-ordered to match documentation above. Try to keep the ordering
  # consistent so it's easier to see which ones are or aren't documented.
  our @EXPORT = qw(
  	PF_802 PF_AAL PF_APPLETALK PF_CCITT PF_CHAOS PF_CTF PF_DATAKIT
  	PF_DECnet PF_DLI PF_ECMA PF_GOSIP PF_HYLINK PF_IMPLINK PF_INET PF_INET6
  	PF_ISO PF_KEY PF_LAST PF_LAT PF_LINK PF_MAX PF_NBS PF_NIT PF_NS PF_OSI
  	PF_OSINET PF_PUP PF_ROUTE PF_SNA PF_UNIX PF_UNSPEC PF_USER PF_WAN
  	PF_X25
  
  	AF_802 AF_AAL AF_APPLETALK AF_CCITT AF_CHAOS AF_CTF AF_DATAKIT
  	AF_DECnet AF_DLI AF_ECMA AF_GOSIP AF_HYLINK AF_IMPLINK AF_INET AF_INET6
  	AF_ISO AF_KEY AF_LAST AF_LAT AF_LINK AF_MAX AF_NBS AF_NIT AF_NS AF_OSI
  	AF_OSINET AF_PUP AF_ROUTE AF_SNA AF_UNIX AF_UNSPEC AF_USER AF_WAN
  	AF_X25
  
  	SOCK_DGRAM SOCK_RAW SOCK_RDM SOCK_SEQPACKET SOCK_STREAM
  
  	SOL_SOCKET
  
  	SO_ACCEPTCONN SO_ATTACH_FILTER SO_BACKLOG SO_BROADCAST SO_CHAMELEON
  	SO_DEBUG SO_DETACH_FILTER SO_DGRAM_ERRIND SO_DOMAIN SO_DONTLINGER
  	SO_DONTROUTE SO_ERROR SO_FAMILY SO_KEEPALIVE SO_LINGER SO_OOBINLINE
  	SO_PASSCRED SO_PASSIFNAME SO_PEERCRED SO_PROTOCOL SO_PROTOTYPE
  	SO_RCVBUF SO_RCVLOWAT SO_RCVTIMEO SO_REUSEADDR SO_REUSEPORT
  	SO_SECURITY_AUTHENTICATION SO_SECURITY_ENCRYPTION_NETWORK
  	SO_SECURITY_ENCRYPTION_TRANSPORT SO_SNDBUF SO_SNDLOWAT SO_SNDTIMEO
  	SO_STATE SO_TYPE SO_USELOOPBACK SO_XOPEN SO_XSE
  
  	IP_OPTIONS IP_HDRINCL IP_TOS IP_TTL IP_RECVOPTS IP_RECVRETOPTS
  	IP_RETOPTS
  
  	MSG_BCAST MSG_BTAG MSG_CTLFLAGS MSG_CTLIGNORE MSG_CTRUNC MSG_DONTROUTE
  	MSG_DONTWAIT MSG_EOF MSG_EOR MSG_ERRQUEUE MSG_ETAG MSG_FIN
  	MSG_MAXIOVLEN MSG_MCAST MSG_NOSIGNAL MSG_OOB MSG_PEEK MSG_PROXY MSG_RST
  	MSG_SYN MSG_TRUNC MSG_URG MSG_WAITALL MSG_WIRE
  
  	SHUT_RD SHUT_RDWR SHUT_WR
  
  	INADDR_ANY INADDR_BROADCAST INADDR_LOOPBACK INADDR_NONE
  
  	SCM_CONNECT SCM_CREDENTIALS SCM_CREDS SCM_RIGHTS SCM_TIMESTAMP
  
  	SOMAXCONN
  
  	IOV_MAX
  	UIO_MAXIOV
  
  	sockaddr_family
  	pack_sockaddr_in  unpack_sockaddr_in  sockaddr_in
  	pack_sockaddr_in6 unpack_sockaddr_in6 sockaddr_in6
  	pack_sockaddr_un  unpack_sockaddr_un  sockaddr_un 
  
  	inet_aton inet_ntoa
  );
  
  # List re-ordered to match documentation above. Try to keep the ordering
  # consistent so it's easier to see which ones are or aren't documented.
  our @EXPORT_OK = qw(
  	CR LF CRLF $CR $LF $CRLF
  
  	SOCK_NONBLOCK SOCK_CLOEXEC
  
  	IP_ADD_MEMBERSHIP IP_ADD_SOURCE_MEMBERSHIP IP_DROP_MEMBERSHIP
  	IP_DROP_SOURCE_MEMBERSHIP IP_MULTICAST_IF IP_MULTICAST_LOOP
  	IP_MULTICAST_TTL
  
  	IPPROTO_IP IPPROTO_IPV6 IPPROTO_RAW IPPROTO_ICMP IPPROTO_TCP
  	IPPROTO_UDP
  
  	IPTOS_LOWDELAY IPTOS_THROUGHPUT IPTOS_RELIABILITY IPTOS_MINCOST
  
  	TCP_CONGESTION TCP_CONNECTIONTIMEOUT TCP_CORK TCP_DEFER_ACCEPT TCP_INFO
  	TCP_INIT_CWND TCP_KEEPALIVE TCP_KEEPCNT TCP_KEEPIDLE TCP_KEEPINTVL
  	TCP_LINGER2 TCP_MAXRT TCP_MAXSEG TCP_MD5SIG TCP_NODELAY TCP_NOOPT
  	TCP_NOPUSH TCP_QUICKACK TCP_SACK_ENABLE TCP_STDURG TCP_SYNCNT
  	TCP_WINDOW_CLAMP
  
  	IN6ADDR_ANY IN6ADDR_LOOPBACK
  
  	IPV6_ADD_MEMBERSHIP IPV6_DROP_MEMBERSHIP IPV6_JOIN_GROUP
  	IPV6_LEAVE_GROUP IPV6_MTU IPV6_MTU_DISCOVER IPV6_MULTICAST_HOPS
  	IPV6_MULTICAST_IF IPV6_MULTICAST_LOOP IPV6_UNICAST_HOPS IPV6_V6ONLY
  
  	pack_ip_mreq unpack_ip_mreq pack_ip_mreq_source unpack_ip_mreq_source
  
  	pack_ipv6_mreq unpack_ipv6_mreq
  
  	inet_pton inet_ntop
  
  	getaddrinfo getnameinfo
  
  	AI_ADDRCONFIG AI_ALL AI_CANONIDN AI_CANONNAME AI_IDN
  	AI_IDN_ALLOW_UNASSIGNED AI_IDN_USE_STD3_ASCII_RULES AI_NUMERICHOST
  	AI_NUMERICSERV AI_PASSIVE AI_V4MAPPED
  
  	NI_DGRAM NI_IDN NI_IDN_ALLOW_UNASSIGNED NI_IDN_USE_STD3_ASCII_RULES
  	NI_NAMEREQD NI_NOFQDN NI_NUMERICHOST NI_NUMERICSERV
  
  	NIx_NOHOST NIx_NOSERV
  
  	EAI_ADDRFAMILY EAI_AGAIN EAI_BADFLAGS EAI_BADHINTS EAI_FAIL EAI_FAMILY
  	EAI_NODATA EAI_NONAME EAI_PROTOCOL EAI_SERVICE EAI_SOCKTYPE EAI_SYSTEM
  );
  
  our %EXPORT_TAGS = (
      crlf     => [qw(CR LF CRLF $CR $LF $CRLF)],
      addrinfo => [qw(getaddrinfo getnameinfo), grep m/^(?:AI|NI|NIx|EAI)_/, @EXPORT_OK],
      all      => [@EXPORT, @EXPORT_OK],
  );
  
  BEGIN {
      sub CR   () {"\015"}
      sub LF   () {"\012"}
      sub CRLF () {"\015\012"}
  
      # These are not gni() constants; they're extensions for the perl API
      # The definitions in Socket.pm and Socket.xs must match
      sub NIx_NOHOST() {1 << 0}
      sub NIx_NOSERV() {1 << 1}
  }
  
  *CR   = \CR();
  *LF   = \LF();
  *CRLF = \CRLF();
  
  sub sockaddr_in {
      if (@_ == 6 && !wantarray) { # perl5.001m compat; use this && die
  	my($af, $port, @quad) = @_;
  	warnings::warn "6-ARG sockaddr_in call is deprecated" 
  	    if warnings::enabled();
  	pack_sockaddr_in($port, inet_aton(join('.', @quad)));
      } elsif (wantarray) {
  	croak "usage:   (port,iaddr) = sockaddr_in(sin_sv)" unless @_ == 1;
          unpack_sockaddr_in(@_);
      } else {
  	croak "usage:   sin_sv = sockaddr_in(port,iaddr))" unless @_ == 2;
          pack_sockaddr_in(@_);
      }
  }
  
  sub sockaddr_in6 {
      if (wantarray) {
  	croak "usage:   (port,in6addr,scope_id,flowinfo) = sockaddr_in6(sin6_sv)" unless @_ == 1;
  	unpack_sockaddr_in6(@_);
      }
      else {
  	croak "usage:   sin6_sv = sockaddr_in6(port,in6addr,[scope_id,[flowinfo]])" unless @_ >= 2 and @_ <= 4;
  	pack_sockaddr_in6(@_);
      }
  }
  
  sub sockaddr_un {
      if (wantarray) {
  	croak "usage:   (filename) = sockaddr_un(sun_sv)" unless @_ == 1;
          unpack_sockaddr_un(@_);
      } else {
  	croak "usage:   sun_sv = sockaddr_un(filename)" unless @_ == 1;
          pack_sockaddr_un(@_);
      }
  }
  
  XSLoader::load(__PACKAGE__, $VERSION);
  
  my %errstr;
  
  if( defined &getaddrinfo ) {
      # These are not part of the API, nothing uses them, and deleting them
      # reduces the size of %Socket:: by about 12K
      delete $Socket::{fake_getaddrinfo};
      delete $Socket::{fake_getnameinfo};
  } else {
      require Scalar::Util;
  
      *getaddrinfo = \&fake_getaddrinfo;
      *getnameinfo = \&fake_getnameinfo;
  
      # These numbers borrowed from GNU libc's implementation, but since
      # they're only used by our emulation, it doesn't matter if the real
      # platform's values differ
      my %constants = (
  	AI_PASSIVE     => 1,
  	AI_CANONNAME   => 2,
  	AI_NUMERICHOST => 4,
  	AI_V4MAPPED    => 8,
  	AI_ALL         => 16,
  	AI_ADDRCONFIG  => 32,
  	# RFC 2553 doesn't define this but Linux does - lets be nice and
  	# provide it since we can
  	AI_NUMERICSERV => 1024,
  
  	EAI_BADFLAGS   => -1,
  	EAI_NONAME     => -2,
  	EAI_NODATA     => -5,
  	EAI_FAMILY     => -6,
  	EAI_SERVICE    => -8,
  
  	NI_NUMERICHOST => 1,
  	NI_NUMERICSERV => 2,
  	NI_NOFQDN      => 4,
  	NI_NAMEREQD    => 8,
  	NI_DGRAM       => 16,
  
  	# Constants we don't support. Export them, but croak if anyone tries to
  	# use them
  	AI_IDN                      => 64,
  	AI_CANONIDN                 => 128,
  	AI_IDN_ALLOW_UNASSIGNED     => 256,
  	AI_IDN_USE_STD3_ASCII_RULES => 512,
  	NI_IDN                      => 32,
  	NI_IDN_ALLOW_UNASSIGNED     => 64,
  	NI_IDN_USE_STD3_ASCII_RULES => 128,
  
  	# Error constants we'll never return, so it doesn't matter what value
  	# these have, nor that we don't provide strings for them
  	EAI_SYSTEM   => -11,
  	EAI_BADHINTS => -1000,
  	EAI_PROTOCOL => -1001
      );
  
      foreach my $name ( keys %constants ) {
  	my $value = $constants{$name};
  
  	no strict 'refs';
  	defined &$name or *$name = sub () { $value };
      }
  
      %errstr = (
  	# These strings from RFC 2553
  	EAI_BADFLAGS()   => "invalid value for ai_flags",
  	EAI_NONAME()     => "nodename nor servname provided, or not known",
  	EAI_NODATA()     => "no address associated with nodename",
  	EAI_FAMILY()     => "ai_family not supported",
  	EAI_SERVICE()    => "servname not supported for ai_socktype",
      );
  }
  
  # The following functions are used if the system does not have a
  # getaddrinfo(3) function in libc; and are used to emulate it for the AF_INET
  # family
  
  # Borrowed from Regexp::Common::net
  my $REGEXP_IPv4_DECIMAL = qr/25[0-5]|2[0-4][0-9]|1?[0-9][0-9]{1,2}/;
  my $REGEXP_IPv4_DOTTEDQUAD = qr/$REGEXP_IPv4_DECIMAL\.$REGEXP_IPv4_DECIMAL\.$REGEXP_IPv4_DECIMAL\.$REGEXP_IPv4_DECIMAL/;
  
  sub fake_makeerr
  {
      my ( $errno ) = @_;
      my $errstr = $errno == 0 ? "" : ( $errstr{$errno} || $errno );
      return Scalar::Util::dualvar( $errno, $errstr );
  }
  
  sub fake_getaddrinfo
  {
      my ( $node, $service, $hints ) = @_;
  
      $node = "" unless defined $node;
  
      $service = "" unless defined $service;
  
      my ( $family, $socktype, $protocol, $flags ) = @$hints{qw( family socktype protocol flags )};
  
      $family ||= Socket::AF_INET(); # 0 == AF_UNSPEC, which we want too
      $family == Socket::AF_INET() or return fake_makeerr( EAI_FAMILY() );
  
      $socktype ||= 0;
  
      $protocol ||= 0;
  
      $flags ||= 0;
  
      my $flag_passive     = $flags & AI_PASSIVE();     $flags &= ~AI_PASSIVE();
      my $flag_canonname   = $flags & AI_CANONNAME();   $flags &= ~AI_CANONNAME();
      my $flag_numerichost = $flags & AI_NUMERICHOST(); $flags &= ~AI_NUMERICHOST();
      my $flag_numericserv = $flags & AI_NUMERICSERV(); $flags &= ~AI_NUMERICSERV();
  
      # These constants don't apply to AF_INET-only lookups, so we might as well
      # just ignore them. For AI_ADDRCONFIG we just presume the host has ability
      # to talk AF_INET. If not we'd have to return no addresses at all. :)
      $flags &= ~(AI_V4MAPPED()|AI_ALL()|AI_ADDRCONFIG());
  
      $flags & (AI_IDN()|AI_CANONIDN()|AI_IDN_ALLOW_UNASSIGNED()|AI_IDN_USE_STD3_ASCII_RULES()) and
  	croak "Socket::getaddrinfo() does not support IDN";
  
      $flags == 0 or return fake_makeerr( EAI_BADFLAGS() );
  
      $node eq "" and $service eq "" and return fake_makeerr( EAI_NONAME() );
  
      my $canonname;
      my @addrs;
      if( $node ne "" ) {
  	return fake_makeerr( EAI_NONAME() ) if( $flag_numerichost and $node !~ m/^$REGEXP_IPv4_DOTTEDQUAD$/ );
  	( $canonname, undef, undef, undef, @addrs ) = gethostbyname( $node );
  	defined $canonname or return fake_makeerr( EAI_NONAME() );
  
  	undef $canonname unless $flag_canonname;
      }
      else {
  	$addrs[0] = $flag_passive ? Socket::inet_aton( "0.0.0.0" )
  				  : Socket::inet_aton( "127.0.0.1" );
      }
  
      my @ports; # Actually ARRAYrefs of [ socktype, protocol, port ]
      my $protname = "";
      if( $protocol ) {
  	$protname = getprotobynumber( $protocol );
      }
  
      if( $service ne "" and $service !~ m/^\d+$/ ) {
  	return fake_makeerr( EAI_NONAME() ) if( $flag_numericserv );
  	getservbyname( $service, $protname ) or return fake_makeerr( EAI_SERVICE() );
      }
  
      foreach my $this_socktype ( Socket::SOCK_STREAM(), Socket::SOCK_DGRAM(), Socket::SOCK_RAW() ) {
  	next if $socktype and $this_socktype != $socktype;
  
  	my $this_protname = "raw";
  	$this_socktype == Socket::SOCK_STREAM() and $this_protname = "tcp";
  	$this_socktype == Socket::SOCK_DGRAM()  and $this_protname = "udp";
  
  	next if $protname and $this_protname ne $protname;
  
  	my $port;
  	if( $service ne "" ) {
  	    if( $service =~ m/^\d+$/ ) {
  		$port = "$service";
  	    }
  	    else {
  		( undef, undef, $port, $this_protname ) = getservbyname( $service, $this_protname );
  		next unless defined $port;
  	    }
  	}
  	else {
  	    $port = 0;
  	}
  
  	push @ports, [ $this_socktype, scalar getprotobyname( $this_protname ) || 0, $port ];
      }
  
      my @ret;
      foreach my $addr ( @addrs ) {
  	foreach my $portspec ( @ports ) {
  	    my ( $socktype, $protocol, $port ) = @$portspec;
  	    push @ret, {
  		family    => $family,
  		socktype  => $socktype,
  		protocol  => $protocol,
  		addr      => Socket::pack_sockaddr_in( $port, $addr ),
  		canonname => undef,
  	    };
  	}
      }
  
      # Only supply canonname for the first result
      if( defined $canonname ) {
  	$ret[0]->{canonname} = $canonname;
      }
  
      return ( fake_makeerr( 0 ), @ret );
  }
  
  sub fake_getnameinfo
  {
      my ( $addr, $flags, $xflags ) = @_;
  
      my ( $port, $inetaddr );
      eval { ( $port, $inetaddr ) = Socket::unpack_sockaddr_in( $addr ) }
  	or return fake_makeerr( EAI_FAMILY() );
  
      my $family = Socket::AF_INET();
  
      $flags ||= 0;
  
      my $flag_numerichost = $flags & NI_NUMERICHOST(); $flags &= ~NI_NUMERICHOST();
      my $flag_numericserv = $flags & NI_NUMERICSERV(); $flags &= ~NI_NUMERICSERV();
      my $flag_nofqdn      = $flags & NI_NOFQDN();      $flags &= ~NI_NOFQDN();
      my $flag_namereqd    = $flags & NI_NAMEREQD();    $flags &= ~NI_NAMEREQD();
      my $flag_dgram       = $flags & NI_DGRAM()   ;    $flags &= ~NI_DGRAM();
  
      $flags & (NI_IDN()|NI_IDN_ALLOW_UNASSIGNED()|NI_IDN_USE_STD3_ASCII_RULES()) and
  	croak "Socket::getnameinfo() does not support IDN";
  
      $flags == 0 or return fake_makeerr( EAI_BADFLAGS() );
  
      $xflags ||= 0;
  
      my $node;
      if( $xflags & NIx_NOHOST ) {
  	$node = undef;
      }
      elsif( $flag_numerichost ) {
  	$node = Socket::inet_ntoa( $inetaddr );
      }
      else {
  	$node = gethostbyaddr( $inetaddr, $family );
  	if( !defined $node ) {
  	    return fake_makeerr( EAI_NONAME() ) if $flag_namereqd;
  	    $node = Socket::inet_ntoa( $inetaddr );
  	}
  	elsif( $flag_nofqdn ) {
  	    my ( $shortname ) = split m/\./, $node;
  	    my ( $fqdn ) = gethostbyname $shortname;
  	    $node = $shortname if defined $fqdn and $fqdn eq $node;
  	}
      }
  
      my $service;
      if( $xflags & NIx_NOSERV ) {
  	$service = undef;
      }
      elsif( $flag_numericserv ) {
  	$service = "$port";
      }
      else {
  	my $protname = $flag_dgram ? "udp" : "";
  	$service = getservbyport( $port, $protname );
  	if( !defined $service ) {
  	    $service = "$port";
  	}
      }
  
      return ( fake_makeerr( 0 ), $node, $service );
  }
  
  1;
X86_64-LINUX_SOCKET

$fatpacked{"x86_64-linux/Storable.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'X86_64-LINUX_STORABLE';
  #
  #  Copyright (c) 1995-2001, Raphael Manfredi
  #  Copyright (c) 2002-2013 by the Perl 5 Porters
  #  
  #  You may redistribute only under the same terms as Perl 5, as specified
  #  in the README file that comes with the distribution.
  #
  
  require XSLoader;
  require Exporter;
  package Storable; @ISA = qw(Exporter);
  
  @EXPORT = qw(store retrieve);
  @EXPORT_OK = qw(
  	nstore store_fd nstore_fd fd_retrieve
  	freeze nfreeze thaw
  	dclone
  	retrieve_fd
  	lock_store lock_nstore lock_retrieve
          file_magic read_magic
  );
  
  use vars qw($canonical $forgive_me $VERSION);
  
  $VERSION = '2.45';
  
  BEGIN {
      if (eval { local $SIG{__DIE__}; require Log::Agent; 1 }) {
          Log::Agent->import;
      }
      #
      # Use of Log::Agent is optional. If it hasn't imported these subs then
      # provide a fallback implementation.
      #
      unless ($Storable::{logcroak} && *{$Storable::{logcroak}}{CODE}) {
          require Carp;
          *logcroak = sub {
              Carp::croak(@_);
          };
      }
      unless ($Storable::{logcarp} && *{$Storable::{logcarp}}{CODE}) {
  	require Carp;
          *logcarp = sub {
            Carp::carp(@_);
          };
      }
  }
  
  #
  # They might miss :flock in Fcntl
  #
  
  BEGIN {
  	if (eval { require Fcntl; 1 } && exists $Fcntl::EXPORT_TAGS{'flock'}) {
  		Fcntl->import(':flock');
  	} else {
  		eval q{
  			sub LOCK_SH ()	{1}
  			sub LOCK_EX ()	{2}
  		};
  	}
  }
  
  sub CLONE {
      # clone context under threads
      Storable::init_perinterp();
  }
  
  # By default restricted hashes are downgraded on earlier perls.
  
  $Storable::downgrade_restricted = 1;
  $Storable::accept_future_minor = 1;
  
  XSLoader::load('Storable', $Storable::VERSION);
  
  #
  # Determine whether locking is possible, but only when needed.
  #
  
  sub CAN_FLOCK; my $CAN_FLOCK; sub CAN_FLOCK {
  	return $CAN_FLOCK if defined $CAN_FLOCK;
  	require Config; import Config;
  	return $CAN_FLOCK =
  		$Config{'d_flock'} ||
  		$Config{'d_fcntl_can_lock'} ||
  		$Config{'d_lockf'};
  }
  
  sub show_file_magic {
      print <<EOM;
  #
  # To recognize the data files of the Perl module Storable,
  # the following lines need to be added to the local magic(5) file,
  # usually either /usr/share/misc/magic or /etc/magic.
  #
  0	string	perl-store	perl Storable(v0.6) data
  >4	byte	>0	(net-order %d)
  >>4	byte	&01	(network-ordered)
  >>4	byte	=3	(major 1)
  >>4	byte	=2	(major 1)
  
  0	string	pst0	perl Storable(v0.7) data
  >4	byte	>0
  >>4	byte	&01	(network-ordered)
  >>4	byte	=5	(major 2)
  >>4	byte	=4	(major 2)
  >>5	byte	>0	(minor %d)
  EOM
  }
  
  sub file_magic {
      require IO::File;
  
      my $file = shift;
      my $fh = IO::File->new;
      open($fh, "<". $file) || die "Can't open '$file': $!";
      binmode($fh);
      defined(sysread($fh, my $buf, 32)) || die "Can't read from '$file': $!";
      close($fh);
  
      $file = "./$file" unless $file;  # ensure TRUE value
  
      return read_magic($buf, $file);
  }
  
  sub read_magic {
      my($buf, $file) = @_;
      my %info;
  
      my $buflen = length($buf);
      my $magic;
      if ($buf =~ s/^(pst0|perl-store)//) {
  	$magic = $1;
  	$info{file} = $file || 1;
      }
      else {
  	return undef if $file;
  	$magic = "";
      }
  
      return undef unless length($buf);
  
      my $net_order;
      if ($magic eq "perl-store" && ord(substr($buf, 0, 1)) > 1) {
  	$info{version} = -1;
  	$net_order = 0;
      }
      else {
  	$buf =~ s/(.)//s;
  	my $major = (ord $1) >> 1;
  	return undef if $major > 4; # sanity (assuming we never go that high)
  	$info{major} = $major;
  	$net_order = (ord $1) & 0x01;
  	if ($major > 1) {
  	    return undef unless $buf =~ s/(.)//s;
  	    my $minor = ord $1;
  	    $info{minor} = $minor;
  	    $info{version} = "$major.$minor";
  	    $info{version_nv} = sprintf "%d.%03d", $major, $minor;
  	}
  	else {
  	    $info{version} = $major;
  	}
      }
      $info{version_nv} ||= $info{version};
      $info{netorder} = $net_order;
  
      unless ($net_order) {
  	return undef unless $buf =~ s/(.)//s;
  	my $len = ord $1;
  	return undef unless length($buf) >= $len;
  	return undef unless $len == 4 || $len == 8;  # sanity
  	@info{qw(byteorder intsize longsize ptrsize)}
  	    = unpack "a${len}CCC", $buf;
  	(substr $buf, 0, $len + 3) = '';
  	if ($info{version_nv} >= 2.002) {
  	    return undef unless $buf =~ s/(.)//s;
  	    $info{nvsize} = ord $1;
  	}
      }
      $info{hdrsize} = $buflen - length($buf);
  
      return \%info;
  }
  
  sub BIN_VERSION_NV {
      sprintf "%d.%03d", BIN_MAJOR(), BIN_MINOR();
  }
  
  sub BIN_WRITE_VERSION_NV {
      sprintf "%d.%03d", BIN_MAJOR(), BIN_WRITE_MINOR();
  }
  
  #
  # store
  #
  # Store target object hierarchy, identified by a reference to its root.
  # The stored object tree may later be retrieved to memory via retrieve.
  # Returns undef if an I/O error occurred, in which case the file is
  # removed.
  #
  sub store {
  	return _store(\&pstore, @_, 0);
  }
  
  #
  # nstore
  #
  # Same as store, but in network order.
  #
  sub nstore {
  	return _store(\&net_pstore, @_, 0);
  }
  
  #
  # lock_store
  #
  # Same as store, but flock the file first (advisory locking).
  #
  sub lock_store {
  	return _store(\&pstore, @_, 1);
  }
  
  #
  # lock_nstore
  #
  # Same as nstore, but flock the file first (advisory locking).
  #
  sub lock_nstore {
  	return _store(\&net_pstore, @_, 1);
  }
  
  # Internal store to file routine
  sub _store {
  	my $xsptr = shift;
  	my $self = shift;
  	my ($file, $use_locking) = @_;
  	logcroak "not a reference" unless ref($self);
  	logcroak "wrong argument number" unless @_ == 2;	# No @foo in arglist
  	local *FILE;
  	if ($use_locking) {
  		open(FILE, ">>$file") || logcroak "can't write into $file: $!";
  		unless (&CAN_FLOCK) {
  			logcarp "Storable::lock_store: fcntl/flock emulation broken on $^O";
  			return undef;
  		}
  		flock(FILE, LOCK_EX) ||
  			logcroak "can't get exclusive lock on $file: $!";
  		truncate FILE, 0;
  		# Unlocking will happen when FILE is closed
  	} else {
  		open(FILE, ">$file") || logcroak "can't create $file: $!";
  	}
  	binmode FILE;				# Archaic systems...
  	my $da = $@;				# Don't mess if called from exception handler
  	my $ret;
  	# Call C routine nstore or pstore, depending on network order
  	eval { $ret = &$xsptr(*FILE, $self) };
  	# close will return true on success, so the or short-circuits, the ()
  	# expression is true, and for that case the block will only be entered
  	# if $@ is true (ie eval failed)
  	# if close fails, it returns false, $ret is altered, *that* is (also)
  	# false, so the () expression is false, !() is true, and the block is
  	# entered.
  	if (!(close(FILE) or undef $ret) || $@) {
  		unlink($file) or warn "Can't unlink $file: $!\n";
  	}
  	logcroak $@ if $@ =~ s/\.?\n$/,/;
  	$@ = $da;
  	return $ret;
  }
  
  #
  # store_fd
  #
  # Same as store, but perform on an already opened file descriptor instead.
  # Returns undef if an I/O error occurred.
  #
  sub store_fd {
  	return _store_fd(\&pstore, @_);
  }
  
  #
  # nstore_fd
  #
  # Same as store_fd, but in network order.
  #
  sub nstore_fd {
  	my ($self, $file) = @_;
  	return _store_fd(\&net_pstore, @_);
  }
  
  # Internal store routine on opened file descriptor
  sub _store_fd {
  	my $xsptr = shift;
  	my $self = shift;
  	my ($file) = @_;
  	logcroak "not a reference" unless ref($self);
  	logcroak "too many arguments" unless @_ == 1;	# No @foo in arglist
  	my $fd = fileno($file);
  	logcroak "not a valid file descriptor" unless defined $fd;
  	my $da = $@;				# Don't mess if called from exception handler
  	my $ret;
  	# Call C routine nstore or pstore, depending on network order
  	eval { $ret = &$xsptr($file, $self) };
  	logcroak $@ if $@ =~ s/\.?\n$/,/;
  	local $\; print $file '';	# Autoflush the file if wanted
  	$@ = $da;
  	return $ret;
  }
  
  #
  # freeze
  #
  # Store object and its hierarchy in memory and return a scalar
  # containing the result.
  #
  sub freeze {
  	_freeze(\&mstore, @_);
  }
  
  #
  # nfreeze
  #
  # Same as freeze but in network order.
  #
  sub nfreeze {
  	_freeze(\&net_mstore, @_);
  }
  
  # Internal freeze routine
  sub _freeze {
  	my $xsptr = shift;
  	my $self = shift;
  	logcroak "not a reference" unless ref($self);
  	logcroak "too many arguments" unless @_ == 0;	# No @foo in arglist
  	my $da = $@;				# Don't mess if called from exception handler
  	my $ret;
  	# Call C routine mstore or net_mstore, depending on network order
  	eval { $ret = &$xsptr($self) };
  	logcroak $@ if $@ =~ s/\.?\n$/,/;
  	$@ = $da;
  	return $ret ? $ret : undef;
  }
  
  #
  # retrieve
  #
  # Retrieve object hierarchy from disk, returning a reference to the root
  # object of that tree.
  #
  sub retrieve {
  	_retrieve($_[0], 0);
  }
  
  #
  # lock_retrieve
  #
  # Same as retrieve, but with advisory locking.
  #
  sub lock_retrieve {
  	_retrieve($_[0], 1);
  }
  
  # Internal retrieve routine
  sub _retrieve {
  	my ($file, $use_locking) = @_;
  	local *FILE;
  	open(FILE, $file) || logcroak "can't open $file: $!";
  	binmode FILE;							# Archaic systems...
  	my $self;
  	my $da = $@;							# Could be from exception handler
  	if ($use_locking) {
  		unless (&CAN_FLOCK) {
  			logcarp "Storable::lock_store: fcntl/flock emulation broken on $^O";
  			return undef;
  		}
  		flock(FILE, LOCK_SH) || logcroak "can't get shared lock on $file: $!";
  		# Unlocking will happen when FILE is closed
  	}
  	eval { $self = pretrieve(*FILE) };		# Call C routine
  	close(FILE);
  	logcroak $@ if $@ =~ s/\.?\n$/,/;
  	$@ = $da;
  	return $self;
  }
  
  #
  # fd_retrieve
  #
  # Same as retrieve, but perform from an already opened file descriptor instead.
  #
  sub fd_retrieve {
  	my ($file) = @_;
  	my $fd = fileno($file);
  	logcroak "not a valid file descriptor" unless defined $fd;
  	my $self;
  	my $da = $@;							# Could be from exception handler
  	eval { $self = pretrieve($file) };		# Call C routine
  	logcroak $@ if $@ =~ s/\.?\n$/,/;
  	$@ = $da;
  	return $self;
  }
  
  sub retrieve_fd { &fd_retrieve }		# Backward compatibility
  
  #
  # thaw
  #
  # Recreate objects in memory from an existing frozen image created
  # by freeze.  If the frozen image passed is undef, return undef.
  #
  sub thaw {
  	my ($frozen) = @_;
  	return undef unless defined $frozen;
  	my $self;
  	my $da = $@;							# Could be from exception handler
  	eval { $self = mretrieve($frozen) };	# Call C routine
  	logcroak $@ if $@ =~ s/\.?\n$/,/;
  	$@ = $da;
  	return $self;
  }
  
  1;
  __END__
  
  =head1 NAME
  
  Storable - persistence for Perl data structures
  
  =head1 SYNOPSIS
  
   use Storable;
   store \%table, 'file';
   $hashref = retrieve('file');
  
   use Storable qw(nstore store_fd nstore_fd freeze thaw dclone);
  
   # Network order
   nstore \%table, 'file';
   $hashref = retrieve('file');	# There is NO nretrieve()
  
   # Storing to and retrieving from an already opened file
   store_fd \@array, \*STDOUT;
   nstore_fd \%table, \*STDOUT;
   $aryref = fd_retrieve(\*SOCKET);
   $hashref = fd_retrieve(\*SOCKET);
  
   # Serializing to memory
   $serialized = freeze \%table;
   %table_clone = %{ thaw($serialized) };
  
   # Deep (recursive) cloning
   $cloneref = dclone($ref);
  
   # Advisory locking
   use Storable qw(lock_store lock_nstore lock_retrieve)
   lock_store \%table, 'file';
   lock_nstore \%table, 'file';
   $hashref = lock_retrieve('file');
  
  =head1 DESCRIPTION
  
  The Storable package brings persistence to your Perl data structures
  containing SCALAR, ARRAY, HASH or REF objects, i.e. anything that can be
  conveniently stored to disk and retrieved at a later time.
  
  It can be used in the regular procedural way by calling C<store> with
  a reference to the object to be stored, along with the file name where
  the image should be written.
  
  The routine returns C<undef> for I/O problems or other internal error,
  a true value otherwise. Serious errors are propagated as a C<die> exception.
  
  To retrieve data stored to disk, use C<retrieve> with a file name.
  The objects stored into that file are recreated into memory for you,
  and a I<reference> to the root object is returned. In case an I/O error
  occurs while reading, C<undef> is returned instead. Other serious
  errors are propagated via C<die>.
  
  Since storage is performed recursively, you might want to stuff references
  to objects that share a lot of common data into a single array or hash
  table, and then store that object. That way, when you retrieve back the
  whole thing, the objects will continue to share what they originally shared.
  
  At the cost of a slight header overhead, you may store to an already
  opened file descriptor using the C<store_fd> routine, and retrieve
  from a file via C<fd_retrieve>. Those names aren't imported by default,
  so you will have to do that explicitly if you need those routines.
  The file descriptor you supply must be already opened, for read
  if you're going to retrieve and for write if you wish to store.
  
  	store_fd(\%table, *STDOUT) || die "can't store to stdout\n";
  	$hashref = fd_retrieve(*STDIN);
  
  You can also store data in network order to allow easy sharing across
  multiple platforms, or when storing on a socket known to be remotely
  connected. The routines to call have an initial C<n> prefix for I<network>,
  as in C<nstore> and C<nstore_fd>. At retrieval time, your data will be
  correctly restored so you don't have to know whether you're restoring
  from native or network ordered data.  Double values are stored stringified
  to ensure portability as well, at the slight risk of loosing some precision
  in the last decimals.
  
  When using C<fd_retrieve>, objects are retrieved in sequence, one
  object (i.e. one recursive tree) per associated C<store_fd>.
  
  If you're more from the object-oriented camp, you can inherit from
  Storable and directly store your objects by invoking C<store> as
  a method. The fact that the root of the to-be-stored tree is a
  blessed reference (i.e. an object) is special-cased so that the
  retrieve does not provide a reference to that object but rather the
  blessed object reference itself. (Otherwise, you'd get a reference
  to that blessed object).
  
  =head1 MEMORY STORE
  
  The Storable engine can also store data into a Perl scalar instead, to
  later retrieve them. This is mainly used to freeze a complex structure in
  some safe compact memory place (where it can possibly be sent to another
  process via some IPC, since freezing the structure also serializes it in
  effect). Later on, and maybe somewhere else, you can thaw the Perl scalar
  out and recreate the original complex structure in memory.
  
  Surprisingly, the routines to be called are named C<freeze> and C<thaw>.
  If you wish to send out the frozen scalar to another machine, use
  C<nfreeze> instead to get a portable image.
  
  Note that freezing an object structure and immediately thawing it
  actually achieves a deep cloning of that structure:
  
      dclone(.) = thaw(freeze(.))
  
  Storable provides you with a C<dclone> interface which does not create
  that intermediary scalar but instead freezes the structure in some
  internal memory space and then immediately thaws it out.
  
  =head1 ADVISORY LOCKING
  
  The C<lock_store> and C<lock_nstore> routine are equivalent to
  C<store> and C<nstore>, except that they get an exclusive lock on
  the file before writing.  Likewise, C<lock_retrieve> does the same
  as C<retrieve>, but also gets a shared lock on the file before reading.
  
  As with any advisory locking scheme, the protection only works if you
  systematically use C<lock_store> and C<lock_retrieve>.  If one side of
  your application uses C<store> whilst the other uses C<lock_retrieve>,
  you will get no protection at all.
  
  The internal advisory locking is implemented using Perl's flock()
  routine.  If your system does not support any form of flock(), or if
  you share your files across NFS, you might wish to use other forms
  of locking by using modules such as LockFile::Simple which lock a
  file using a filesystem entry, instead of locking the file descriptor.
  
  =head1 SPEED
  
  The heart of Storable is written in C for decent speed. Extra low-level
  optimizations have been made when manipulating perl internals, to
  sacrifice encapsulation for the benefit of greater speed.
  
  =head1 CANONICAL REPRESENTATION
  
  Normally, Storable stores elements of hashes in the order they are
  stored internally by Perl, i.e. pseudo-randomly.  If you set
  C<$Storable::canonical> to some C<TRUE> value, Storable will store
  hashes with the elements sorted by their key.  This allows you to
  compare data structures by comparing their frozen representations (or
  even the compressed frozen representations), which can be useful for
  creating lookup tables for complicated queries.
  
  Canonical order does not imply network order; those are two orthogonal
  settings.
  
  =head1 CODE REFERENCES
  
  Since Storable version 2.05, CODE references may be serialized with
  the help of L<B::Deparse>. To enable this feature, set
  C<$Storable::Deparse> to a true value. To enable deserialization,
  C<$Storable::Eval> should be set to a true value. Be aware that
  deserialization is done through C<eval>, which is dangerous if the
  Storable file contains malicious data. You can set C<$Storable::Eval>
  to a subroutine reference which would be used instead of C<eval>. See
  below for an example using a L<Safe> compartment for deserialization
  of CODE references.
  
  If C<$Storable::Deparse> and/or C<$Storable::Eval> are set to false
  values, then the value of C<$Storable::forgive_me> (see below) is
  respected while serializing and deserializing.
  
  =head1 FORWARD COMPATIBILITY
  
  This release of Storable can be used on a newer version of Perl to
  serialize data which is not supported by earlier Perls.  By default,
  Storable will attempt to do the right thing, by C<croak()>ing if it
  encounters data that it cannot deserialize.  However, the defaults
  can be changed as follows:
  
  =over 4
  
  =item utf8 data
  
  Perl 5.6 added support for Unicode characters with code points > 255,
  and Perl 5.8 has full support for Unicode characters in hash keys.
  Perl internally encodes strings with these characters using utf8, and
  Storable serializes them as utf8.  By default, if an older version of
  Perl encounters a utf8 value it cannot represent, it will C<croak()>.
  To change this behaviour so that Storable deserializes utf8 encoded
  values as the string of bytes (effectively dropping the I<is_utf8> flag)
  set C<$Storable::drop_utf8> to some C<TRUE> value.  This is a form of
  data loss, because with C<$drop_utf8> true, it becomes impossible to tell
  whether the original data was the Unicode string, or a series of bytes
  that happen to be valid utf8.
  
  =item restricted hashes
  
  Perl 5.8 adds support for restricted hashes, which have keys
  restricted to a given set, and can have values locked to be read only.
  By default, when Storable encounters a restricted hash on a perl
  that doesn't support them, it will deserialize it as a normal hash,
  silently discarding any placeholder keys and leaving the keys and
  all values unlocked.  To make Storable C<croak()> instead, set
  C<$Storable::downgrade_restricted> to a C<FALSE> value.  To restore
  the default set it back to some C<TRUE> value.
  
  =item files from future versions of Storable
  
  Earlier versions of Storable would immediately croak if they encountered
  a file with a higher internal version number than the reading Storable
  knew about.  Internal version numbers are increased each time new data
  types (such as restricted hashes) are added to the vocabulary of the file
  format.  This meant that a newer Storable module had no way of writing a
  file readable by an older Storable, even if the writer didn't store newer
  data types.
  
  This version of Storable will defer croaking until it encounters a data
  type in the file that it does not recognize.  This means that it will
  continue to read files generated by newer Storable modules which are careful
  in what they write out, making it easier to upgrade Storable modules in a
  mixed environment.
  
  The old behaviour of immediate croaking can be re-instated by setting
  C<$Storable::accept_future_minor> to some C<FALSE> value.
  
  =back
  
  All these variables have no effect on a newer Perl which supports the
  relevant feature.
  
  =head1 ERROR REPORTING
  
  Storable uses the "exception" paradigm, in that it does not try to workaround
  failures: if something bad happens, an exception is generated from the
  caller's perspective (see L<Carp> and C<croak()>).  Use eval {} to trap
  those exceptions.
  
  When Storable croaks, it tries to report the error via the C<logcroak()>
  routine from the C<Log::Agent> package, if it is available.
  
  Normal errors are reported by having store() or retrieve() return C<undef>.
  Such errors are usually I/O errors (or truncated stream errors at retrieval).
  
  =head1 WIZARDS ONLY
  
  =head2 Hooks
  
  Any class may define hooks that will be called during the serialization
  and deserialization process on objects that are instances of that class.
  Those hooks can redefine the way serialization is performed (and therefore,
  how the symmetrical deserialization should be conducted).
  
  Since we said earlier:
  
      dclone(.) = thaw(freeze(.))
  
  everything we say about hooks should also hold for deep cloning. However,
  hooks get to know whether the operation is a mere serialization, or a cloning.
  
  Therefore, when serializing hooks are involved,
  
      dclone(.) <> thaw(freeze(.))
  
  Well, you could keep them in sync, but there's no guarantee it will always
  hold on classes somebody else wrote.  Besides, there is little to gain in
  doing so: a serializing hook could keep only one attribute of an object,
  which is probably not what should happen during a deep cloning of that
  same object.
  
  Here is the hooking interface:
  
  =over 4
  
  =item C<STORABLE_freeze> I<obj>, I<cloning>
  
  The serializing hook, called on the object during serialization.  It can be
  inherited, or defined in the class itself, like any other method.
  
  Arguments: I<obj> is the object to serialize, I<cloning> is a flag indicating
  whether we're in a dclone() or a regular serialization via store() or freeze().
  
  Returned value: A LIST C<($serialized, $ref1, $ref2, ...)> where $serialized
  is the serialized form to be used, and the optional $ref1, $ref2, etc... are
  extra references that you wish to let the Storable engine serialize.
  
  At deserialization time, you will be given back the same LIST, but all the
  extra references will be pointing into the deserialized structure.
  
  The B<first time> the hook is hit in a serialization flow, you may have it
  return an empty list.  That will signal the Storable engine to further
  discard that hook for this class and to therefore revert to the default
  serialization of the underlying Perl data.  The hook will again be normally
  processed in the next serialization.
  
  Unless you know better, serializing hook should always say:
  
      sub STORABLE_freeze {
          my ($self, $cloning) = @_;
          return if $cloning;         # Regular default serialization
          ....
      }
  
  in order to keep reasonable dclone() semantics.
  
  =item C<STORABLE_thaw> I<obj>, I<cloning>, I<serialized>, ...
  
  The deserializing hook called on the object during deserialization.
  But wait: if we're deserializing, there's no object yet... right?
  
  Wrong: the Storable engine creates an empty one for you.  If you know Eiffel,
  you can view C<STORABLE_thaw> as an alternate creation routine.
  
  This means the hook can be inherited like any other method, and that
  I<obj> is your blessed reference for this particular instance.
  
  The other arguments should look familiar if you know C<STORABLE_freeze>:
  I<cloning> is true when we're part of a deep clone operation, I<serialized>
  is the serialized string you returned to the engine in C<STORABLE_freeze>,
  and there may be an optional list of references, in the same order you gave
  them at serialization time, pointing to the deserialized objects (which
  have been processed courtesy of the Storable engine).
  
  When the Storable engine does not find any C<STORABLE_thaw> hook routine,
  it tries to load the class by requiring the package dynamically (using
  the blessed package name), and then re-attempts the lookup.  If at that
  time the hook cannot be located, the engine croaks.  Note that this mechanism
  will fail if you define several classes in the same file, but L<perlmod>
  warned you.
  
  It is up to you to use this information to populate I<obj> the way you want.
  
  Returned value: none.
  
  =item C<STORABLE_attach> I<class>, I<cloning>, I<serialized>
  
  While C<STORABLE_freeze> and C<STORABLE_thaw> are useful for classes where
  each instance is independent, this mechanism has difficulty (or is
  incompatible) with objects that exist as common process-level or
  system-level resources, such as singleton objects, database pools, caches
  or memoized objects.
  
  The alternative C<STORABLE_attach> method provides a solution for these
  shared objects. Instead of C<STORABLE_freeze> --E<gt> C<STORABLE_thaw>,
  you implement C<STORABLE_freeze> --E<gt> C<STORABLE_attach> instead.
  
  Arguments: I<class> is the class we are attaching to, I<cloning> is a flag
  indicating whether we're in a dclone() or a regular de-serialization via
  thaw(), and I<serialized> is the stored string for the resource object.
  
  Because these resource objects are considered to be owned by the entire
  process/system, and not the "property" of whatever is being serialized,
  no references underneath the object should be included in the serialized
  string. Thus, in any class that implements C<STORABLE_attach>, the
  C<STORABLE_freeze> method cannot return any references, and C<Storable>
  will throw an error if C<STORABLE_freeze> tries to return references.
  
  All information required to "attach" back to the shared resource object
  B<must> be contained B<only> in the C<STORABLE_freeze> return string.
  Otherwise, C<STORABLE_freeze> behaves as normal for C<STORABLE_attach>
  classes.
  
  Because C<STORABLE_attach> is passed the class (rather than an object),
  it also returns the object directly, rather than modifying the passed
  object.
  
  Returned value: object of type C<class>
  
  =back
  
  =head2 Predicates
  
  Predicates are not exportable.  They must be called by explicitly prefixing
  them with the Storable package name.
  
  =over 4
  
  =item C<Storable::last_op_in_netorder>
  
  The C<Storable::last_op_in_netorder()> predicate will tell you whether
  network order was used in the last store or retrieve operation.  If you
  don't know how to use this, just forget about it.
  
  =item C<Storable::is_storing>
  
  Returns true if within a store operation (via STORABLE_freeze hook).
  
  =item C<Storable::is_retrieving>
  
  Returns true if within a retrieve operation (via STORABLE_thaw hook).
  
  =back
  
  =head2 Recursion
  
  With hooks comes the ability to recurse back to the Storable engine.
  Indeed, hooks are regular Perl code, and Storable is convenient when
  it comes to serializing and deserializing things, so why not use it
  to handle the serialization string?
  
  There are a few things you need to know, however:
  
  =over 4
  
  =item *
  
  You can create endless loops if the things you serialize via freeze()
  (for instance) point back to the object we're trying to serialize in
  the hook.
  
  =item *
  
  Shared references among objects will not stay shared: if we're serializing
  the list of object [A, C] where both object A and C refer to the SAME object
  B, and if there is a serializing hook in A that says freeze(B), then when
  deserializing, we'll get [A', C'] where A' refers to B', but C' refers to D,
  a deep clone of B'.  The topology was not preserved.
  
  =back
  
  That's why C<STORABLE_freeze> lets you provide a list of references
  to serialize.  The engine guarantees that those will be serialized in the
  same context as the other objects, and therefore that shared objects will
  stay shared.
  
  In the above [A, C] example, the C<STORABLE_freeze> hook could return:
  
  	("something", $self->{B})
  
  and the B part would be serialized by the engine.  In C<STORABLE_thaw>, you
  would get back the reference to the B' object, deserialized for you.
  
  Therefore, recursion should normally be avoided, but is nonetheless supported.
  
  =head2 Deep Cloning
  
  There is a Clone module available on CPAN which implements deep cloning
  natively, i.e. without freezing to memory and thawing the result.  It is
  aimed to replace Storable's dclone() some day.  However, it does not currently
  support Storable hooks to redefine the way deep cloning is performed.
  
  =head1 Storable magic
  
  Yes, there's a lot of that :-) But more precisely, in UNIX systems
  there's a utility called C<file>, which recognizes data files based on
  their contents (usually their first few bytes).  For this to work,
  a certain file called F<magic> needs to taught about the I<signature>
  of the data.  Where that configuration file lives depends on the UNIX
  flavour; often it's something like F</usr/share/misc/magic> or
  F</etc/magic>.  Your system administrator needs to do the updating of
  the F<magic> file.  The necessary signature information is output to
  STDOUT by invoking Storable::show_file_magic().  Note that the GNU
  implementation of the C<file> utility, version 3.38 or later,
  is expected to contain support for recognising Storable files
  out-of-the-box, in addition to other kinds of Perl files.
  
  You can also use the following functions to extract the file header
  information from Storable images:
  
  =over
  
  =item $info = Storable::file_magic( $filename )
  
  If the given file is a Storable image return a hash describing it.  If
  the file is readable, but not a Storable image return C<undef>.  If
  the file does not exist or is unreadable then croak.
  
  The hash returned has the following elements:
  
  =over
  
  =item C<version>
  
  This returns the file format version.  It is a string like "2.7".
  
  Note that this version number is not the same as the version number of
  the Storable module itself.  For instance Storable v0.7 create files
  in format v2.0 and Storable v2.15 create files in format v2.7.  The
  file format version number only increment when additional features
  that would confuse older versions of the module are added.
  
  Files older than v2.0 will have the one of the version numbers "-1",
  "0" or "1".  No minor number was used at that time.
  
  =item C<version_nv>
  
  This returns the file format version as number.  It is a string like
  "2.007".  This value is suitable for numeric comparisons.
  
  The constant function C<Storable::BIN_VERSION_NV> returns a comparable
  number that represents the highest file version number that this
  version of Storable fully supports (but see discussion of
  C<$Storable::accept_future_minor> above).  The constant
  C<Storable::BIN_WRITE_VERSION_NV> function returns what file version
  is written and might be less than C<Storable::BIN_VERSION_NV> in some
  configurations.
  
  =item C<major>, C<minor>
  
  This also returns the file format version.  If the version is "2.7"
  then major would be 2 and minor would be 7.  The minor element is
  missing for when major is less than 2.
  
  =item C<hdrsize>
  
  The is the number of bytes that the Storable header occupies.
  
  =item C<netorder>
  
  This is TRUE if the image store data in network order.  This means
  that it was created with nstore() or similar.
  
  =item C<byteorder>
  
  This is only present when C<netorder> is FALSE.  It is the
  $Config{byteorder} string of the perl that created this image.  It is
  a string like "1234" (32 bit little endian) or "87654321" (64 bit big
  endian).  This must match the current perl for the image to be
  readable by Storable.
  
  =item C<intsize>, C<longsize>, C<ptrsize>, C<nvsize>
  
  These are only present when C<netorder> is FALSE. These are the sizes of
  various C datatypes of the perl that created this image.  These must
  match the current perl for the image to be readable by Storable.
  
  The C<nvsize> element is only present for file format v2.2 and
  higher.
  
  =item C<file>
  
  The name of the file.
  
  =back
  
  =item $info = Storable::read_magic( $buffer )
  
  =item $info = Storable::read_magic( $buffer, $must_be_file )
  
  The $buffer should be a Storable image or the first few bytes of it.
  If $buffer starts with a Storable header, then a hash describing the
  image is returned, otherwise C<undef> is returned.
  
  The hash has the same structure as the one returned by
  Storable::file_magic().  The C<file> element is true if the image is a
  file image.
  
  If the $must_be_file argument is provided and is TRUE, then return
  C<undef> unless the image looks like it belongs to a file dump.
  
  The maximum size of a Storable header is currently 21 bytes.  If the
  provided $buffer is only the first part of a Storable image it should
  at least be this long to ensure that read_magic() will recognize it as
  such.
  
  =back
  
  =head1 EXAMPLES
  
  Here are some code samples showing a possible usage of Storable:
  
  	use Storable qw(store retrieve freeze thaw dclone);
  
  	%color = ('Blue' => 0.1, 'Red' => 0.8, 'Black' => 0, 'White' => 1);
  
  	store(\%color, 'mycolors') or die "Can't store %a in mycolors!\n";
  
  	$colref = retrieve('mycolors');
  	die "Unable to retrieve from mycolors!\n" unless defined $colref;
  	printf "Blue is still %lf\n", $colref->{'Blue'};
  
  	$colref2 = dclone(\%color);
  
  	$str = freeze(\%color);
  	printf "Serialization of %%color is %d bytes long.\n", length($str);
  	$colref3 = thaw($str);
  
  which prints (on my machine):
  
  	Blue is still 0.100000
  	Serialization of %color is 102 bytes long.
  
  Serialization of CODE references and deserialization in a safe
  compartment:
  
  =for example begin
  
  	use Storable qw(freeze thaw);
  	use Safe;
  	use strict;
  	my $safe = new Safe;
          # because of opcodes used in "use strict":
  	$safe->permit(qw(:default require));
  	local $Storable::Deparse = 1;
  	local $Storable::Eval = sub { $safe->reval($_[0]) };
  	my $serialized = freeze(sub { 42 });
  	my $code = thaw($serialized);
  	$code->() == 42;
  
  =for example end
  
  =for example_testing
          is( $code->(), 42 );
  
  =head1 SECURITY WARNING
  
  B<Do not accept Storable documents from untrusted sources!>
  
  Some features of Storable can lead to security vulnerabilities if you
  accept Storable documents from untrusted sources. Most obviously, the
  optional (off by default) CODE reference serialization feature allows
  transfer of code to the deserializing process. Furthermore, any
  serialized object will cause Storable to helpfully load the module
  corresponding to the class of the object in the deserializing module.
  For manipulated module names, this can load almost arbitrary code.
  Finally, the deserialized object's destructors will be invoked when
  the objects get destroyed in the deserializing process. Maliciously
  crafted Storable documents may put such objects in the value of
  a hash key that is overridden by another key/value pair in the
  same hash, thus causing immediate destructor execution.
  
  In a future version of Storable, we intend to provide options to disable
  loading modules for classes and to disable deserializing objects
  altogether. I<Nonetheless, Storable deserializing documents from
  untrusted sources is expected to have other, yet undiscovered,
  security concerns such as allowing an attacker to cause the deserializer
  to crash hard.>
  
  B<Therefore, let me repeat: Do not accept Storable documents from
  untrusted sources!>
  
  If your application requires accepting data from untrusted sources, you
  are best off with a less powerful and more-likely safe serialization format
  and implementation. If your data is sufficiently simple, JSON is a good
  choice and offers maximum interoperability.
  
  =head1 WARNING
  
  If you're using references as keys within your hash tables, you're bound
  to be disappointed when retrieving your data. Indeed, Perl stringifies
  references used as hash table keys. If you later wish to access the
  items via another reference stringification (i.e. using the same
  reference that was used for the key originally to record the value into
  the hash table), it will work because both references stringify to the
  same string.
  
  It won't work across a sequence of C<store> and C<retrieve> operations,
  however, because the addresses in the retrieved objects, which are
  part of the stringified references, will probably differ from the
  original addresses. The topology of your structure is preserved,
  but not hidden semantics like those.
  
  On platforms where it matters, be sure to call C<binmode()> on the
  descriptors that you pass to Storable functions.
  
  Storing data canonically that contains large hashes can be
  significantly slower than storing the same data normally, as
  temporary arrays to hold the keys for each hash have to be allocated,
  populated, sorted and freed.  Some tests have shown a halving of the
  speed of storing -- the exact penalty will depend on the complexity of
  your data.  There is no slowdown on retrieval.
  
  =head1 BUGS
  
  You can't store GLOB, FORMLINE, REGEXP, etc.... If you can define semantics
  for those operations, feel free to enhance Storable so that it can
  deal with them.
  
  The store functions will C<croak> if they run into such references
  unless you set C<$Storable::forgive_me> to some C<TRUE> value. In that
  case, the fatal message is turned in a warning and some
  meaningless string is stored instead.
  
  Setting C<$Storable::canonical> may not yield frozen strings that
  compare equal due to possible stringification of numbers. When the
  string version of a scalar exists, it is the form stored; therefore,
  if you happen to use your numbers as strings between two freezing
  operations on the same data structures, you will get different
  results.
  
  When storing doubles in network order, their value is stored as text.
  However, you should also not expect non-numeric floating-point values
  such as infinity and "not a number" to pass successfully through a
  nstore()/retrieve() pair.
  
  As Storable neither knows nor cares about character sets (although it
  does know that characters may be more than eight bits wide), any difference
  in the interpretation of character codes between a host and a target
  system is your problem.  In particular, if host and target use different
  code points to represent the characters used in the text representation
  of floating-point numbers, you will not be able be able to exchange
  floating-point data, even with nstore().
  
  C<Storable::drop_utf8> is a blunt tool.  There is no facility either to
  return B<all> strings as utf8 sequences, or to attempt to convert utf8
  data back to 8 bit and C<croak()> if the conversion fails.
  
  Prior to Storable 2.01, no distinction was made between signed and
  unsigned integers on storing.  By default Storable prefers to store a
  scalars string representation (if it has one) so this would only cause
  problems when storing large unsigned integers that had never been converted
  to string or floating point.  In other words values that had been generated
  by integer operations such as logic ops and then not used in any string or
  arithmetic context before storing.
  
  =head2 64 bit data in perl 5.6.0 and 5.6.1
  
  This section only applies to you if you have existing data written out
  by Storable 2.02 or earlier on perl 5.6.0 or 5.6.1 on Unix or Linux which
  has been configured with 64 bit integer support (not the default)
  If you got a precompiled perl, rather than running Configure to build
  your own perl from source, then it almost certainly does not affect you,
  and you can stop reading now (unless you're curious). If you're using perl
  on Windows it does not affect you.
  
  Storable writes a file header which contains the sizes of various C
  language types for the C compiler that built Storable (when not writing in
  network order), and will refuse to load files written by a Storable not
  on the same (or compatible) architecture.  This check and a check on
  machine byteorder is needed because the size of various fields in the file
  are given by the sizes of the C language types, and so files written on
  different architectures are incompatible.  This is done for increased speed.
  (When writing in network order, all fields are written out as standard
  lengths, which allows full interworking, but takes longer to read and write)
  
  Perl 5.6.x introduced the ability to optional configure the perl interpreter
  to use C's C<long long> type to allow scalars to store 64 bit integers on 32
  bit systems.  However, due to the way the Perl configuration system
  generated the C configuration files on non-Windows platforms, and the way
  Storable generates its header, nothing in the Storable file header reflected
  whether the perl writing was using 32 or 64 bit integers, despite the fact
  that Storable was storing some data differently in the file.  Hence Storable
  running on perl with 64 bit integers will read the header from a file
  written by a 32 bit perl, not realise that the data is actually in a subtly
  incompatible format, and then go horribly wrong (possibly crashing) if it
  encountered a stored integer.  This is a design failure.
  
  Storable has now been changed to write out and read in a file header with
  information about the size of integers.  It's impossible to detect whether
  an old file being read in was written with 32 or 64 bit integers (they have
  the same header) so it's impossible to automatically switch to a correct
  backwards compatibility mode.  Hence this Storable defaults to the new,
  correct behaviour.
  
  What this means is that if you have data written by Storable 1.x running
  on perl 5.6.0 or 5.6.1 configured with 64 bit integers on Unix or Linux
  then by default this Storable will refuse to read it, giving the error
  I<Byte order is not compatible>.  If you have such data then you
  should set C<$Storable::interwork_56_64bit> to a true value to make this
  Storable read and write files with the old header.  You should also
  migrate your data, or any older perl you are communicating with, to this
  current version of Storable.
  
  If you don't have data written with specific configuration of perl described
  above, then you do not and should not do anything.  Don't set the flag -
  not only will Storable on an identically configured perl refuse to load them,
  but Storable a differently configured perl will load them believing them
  to be correct for it, and then may well fail or crash part way through
  reading them.
  
  =head1 CREDITS
  
  Thank you to (in chronological order):
  
  	Jarkko Hietaniemi <jhi@iki.fi>
  	Ulrich Pfeifer <pfeifer@charly.informatik.uni-dortmund.de>
  	Benjamin A. Holzman <bholzman@earthlink.net>
  	Andrew Ford <A.Ford@ford-mason.co.uk>
  	Gisle Aas <gisle@aas.no>
  	Jeff Gresham <gresham_jeffrey@jpmorgan.com>
  	Murray Nesbitt <murray@activestate.com>
  	Marc Lehmann <pcg@opengroup.org>
  	Justin Banks <justinb@wamnet.com>
  	Jarkko Hietaniemi <jhi@iki.fi> (AGAIN, as perl 5.7.0 Pumpkin!)
  	Salvador Ortiz Garcia <sog@msg.com.mx>
  	Dominic Dunlop <domo@computer.org>
  	Erik Haugan <erik@solbors.no>
  	Benjamin A. Holzman <ben.holzman@grantstreet.com>
  	Reini Urban <rurban@cpanel.net>
  
  for their bug reports, suggestions and contributions.
  
  Benjamin Holzman contributed the tied variable support, Andrew Ford
  contributed the canonical order for hashes, and Gisle Aas fixed
  a few misunderstandings of mine regarding the perl internals,
  and optimized the emission of "tags" in the output streams by
  simply counting the objects instead of tagging them (leading to
  a binary incompatibility for the Storable image starting at version
  0.6--older images are, of course, still properly understood).
  Murray Nesbitt made Storable thread-safe.  Marc Lehmann added overloading
  and references to tied items support.  Benjamin Holzman added a performance
  improvement for overloaded classes; thanks to Grant Street Group for footing
  the bill.
  
  =head1 AUTHOR
  
  Storable was written by Raphael Manfredi F<E<lt>Raphael_Manfredi@pobox.comE<gt>>
  Maintenance is now done by the perl5-porters F<E<lt>perl5-porters@perl.orgE<gt>>
  
  Please e-mail us with problems, bug fixes, comments and complaints,
  although if you have compliments you should send them to Raphael.
  Please don't e-mail Raphael with problems, as he no longer works on
  Storable, and your message will be delayed while he forwards it to us.
  
  =head1 SEE ALSO
  
  L<Clone>.
  
  =cut
X86_64-LINUX_STORABLE

$fatpacked{"x86_64-linux/common/sense.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'X86_64-LINUX_COMMON_SENSE';
  package common::sense;
  
  our $VERSION = 3.72;
  
  # overload should be included
  
  sub import {
     local $^W; # work around perl 5.16 spewing out warnings for next statement
     # use warnings
     ${^WARNING_BITS} ^= ${^WARNING_BITS} ^ "\x3c\x3f\x33\x00\x0f\xf0\x0f\xc0\xf0\xfc\x33\x00\x00";
     # use strict, use utf8; use feature;
     $^H |= 0x1c820fc0;
     @^H{qw(feature_fc feature___SUB__ feature_unicode feature_evalbytes feature_say feature_state feature_switch)} = (1) x 7;
  }
  
  1
X86_64-LINUX_COMMON_SENSE

s/^  //mg for values %fatpacked;

my $class = 'FatPacked::'.(0+\%fatpacked);
no strict 'refs';
*{"${class}::files"} = sub { keys %{$_[0]} };

if ($] < 5.008) {
  *{"${class}::INC"} = sub {
     if (my $fat = $_[0]{$_[1]}) {
       return sub {
         return 0 unless length $fat;
         $fat =~ s/^([^\n]*\n?)//;
         $_ = $1;
         return 1;
       };
     }
     return;
  };
}

else {
  *{"${class}::INC"} = sub {
    if (my $fat = $_[0]{$_[1]}) {
      open my $fh, '<', \$fat
        or die "FatPacker error loading $_[1] (could be a perl installation issue?)";
      return $fh;
    }
    return;
  };
}

unshift @INC, bless \%fatpacked, $class;
  } # END OF FATPACK CODE

#===============================================================================
#         FILE:  codeguard_fixer.pl
#         WIKI:  https://gatorwiki.hostgator.com/Admin/Codeguard
#       AUTHOR:  Rishwanth Yeddula (Rish), ryeddula@hostgator.com
#      COMPANY:  Hostgator.com LLC
#      CREATED:  02/05/2014 01:39:56 PM
#===============================================================================

use strict;
use warnings;

use Data::Dumper;
use Fcntl qw (:flock);
use Getopt::Long qw (:config pass_through);
use POSIX qw (strftime);

use Codeguard::Fixer::User;

my $opts;
GetOptions (
	'correct_dbs'       => \$opts->{correct_dbs},
	'correct_sites'     => \$opts->{correct_sites},
	'delete_db=s'       => \$opts->{delete_db},
	'delete_site=s'     => \$opts->{delete_site},
	'delete_blacklist'  => \$opts->{delete_blacklist},
	'blacklist_db=s'    => \$opts->{blacklist_db},
	'blacklist_site=s'  => \$opts->{blacklist_site},
	'clean_dbusers'     => \$opts->{clean_dbusers},
	'list_sites'        => \$opts->{list_sites},
	'list_dbs'          => \$opts->{list_dbs},
	'db_sleep=i'        => \$opts->{db_sleep},
	'help'              => \$opts->{help},
	'sync_missing_dbs'  => \$opts->{sync_missing_dbs},
	'fix_exclude_rules' => \$opts->{fix_exclude_rules},
);

display_header();
if ($opts->{help}) {
	display_help();
	exit 1;
}

my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
my $logfile = 'codeguard_fixer-'.sprintf("%4d%02d%02d",$year+1900,$mon+1,$mday).'.log';
eval {
	if (not -d '/var/log/hgtransfer') {
		mkdir '/var/log/hgtransfer';
	}
	1;
} or do {
	print "Error creating log directory: /var/log/hgtransfer/\n";
	exit 1;
};

main($opts, @ARGV);
sub main {

	my ($opts, $cpanel_username) = @_;
	if (not ($cpanel_username and _check_opts($opts) ) ) {
		print "[!] You must specify a cPanel username, and at least one valid option. Please see '--help' for guidance.\n";
		exit 1;
	}

	if ( not _check_username($cpanel_username) ) {
		print "[!] '$cpanel_username' is not a valid username - account does not exist, or is misconfigured.\n";
		exit 1;
	}

	my $fixer = Codeguard::Fixer::User->new(
		{
			user_name   => $cpanel_username,
		}
	);

	if (not $fixer) {
		print "[!] Failed to initiate Codeguard Fixer object. Error: ".$Codeguard::Fixer::ERROR."\n";
		exit 1;
	}

	if ( $fixer->initialize( \&printer ) ) {
		my $errors = _check_account($fixer);
		if ( not scalar @{$errors} ) {
			if ( $opts->{blacklist_site} ) {
				$fixer->blacklist_site( $opts->{blacklist_site}, \&printer ) and
					$opts->{correct_sites} = 1;
			}
			if ( $opts->{blacklist_db} ) {
				$fixer->blacklist_db( $opts->{blacklist_db}, \&printer ) and
					$opts->{correct_dbs} = 1;
			}
			if ( $opts->{delete_site} ) {
				$fixer->delete_site( $opts->{delete_site}, \&printer );
			}
			if ( $opts->{delete_db} ) {
				$fixer->delete_db( $opts->{delete_db}, \&printer ) and
					$opts->{clean_dbusers} = 1;
			}
			if ( $opts->{delete_blacklist} ) {
				$fixer->remove_blacklisted_resources( \&printer );
			}
			if ( $opts->{correct_sites} ) {
				$fixer->correct_sites( \&printer ) and
					$opts->{fix_exclude_rules} = 1;
			}
			if ( $opts->{correct_dbs} ) {
				$fixer->correct_dbs( \&printer );
			}
			if ( $opts->{sync_missing_dbs} ) {
				$fixer->sync_missing_dbs( \&printer ) and
					$opts->{clean_dbusers} = 1;
			}
			if ( $opts->{list_sites} ) {
				$fixer->list_cg_sites( \&printer );
			}
			if ( $opts->{list_dbs} ) {
				$fixer->list_cg_dbs( \&printer );
			}
			if ( $opts->{clean_dbusers} ) {
				$fixer->clean_dbusers( \&printer );
			}
			if ( $opts->{fix_exclude_rules} ) {
				$fixer->update_exclude_rules( \&printer );
			}
			print "\n";
			exit;
		} else {
			printer("\n[!] Codeguard Checks Failed: \n");
			foreach my $error ( @{ $errors } ) {
				$error =~ s/at\s\/.*$//;
				printer("\t$error\n");
			}
			exit 1;
		}
	}

	print "\n[!] Failed to initialize Codeguard Fixer. Error: ".$fixer->get_errstr()."\n";
	exit 1;
}

sub printer {

	my $message = shift;
	print $message;

	open my $logfile_fh, '>>', "/var/log/hgtransfer/$logfile" or return;
	flock $logfile_fh, LOCK_EX or return; #Exclusive Lock
	my $timestamp = strftime("%m/%d/%Y %H:%M:%S", localtime);
	$message =~ s/[\n]+$//g;
	print $logfile_fh "[$timestamp] [Pid: $$] [Admin: ".($ENV{RUSER}? $ENV{RUSER} : 'unknown')."] Content:\n$message\n#####\n";
	close $logfile_fh;
	return;
}

sub _check_account {

	my $fixer = shift;

	my @errors;
	if ( -d _user_homedir($fixer->get_cpanel_username).'/.ssh' ) {
		my $owner = getpwuid( (stat _user_homedir($fixer->get_cpanel_username).'/.ssh')[4] );
		if ($owner ne $fixer->get_cpanel_username) {
			push @errors, "'.ssh' directory is not owned by the user! Current owner is '$owner'!";
		}
	}
	if (not $fixer->fetch_blacklist_on_cpanel) {
		push @errors, 'Failed to parse blacklist properly. Error: '.$fixer->get_errstr;
	}
	return \@errors;
}

sub _user_homedir{

	my $user = shift;
	my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwnam $user;

	if ($dir and -d $dir) {
		return $dir;
	}

	return;
}

sub _check_username {

	my $user = shift;
	my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwnam $user;

	if (($name) and (($dir) and (-d $dir)) and (-s "/var/cpanel/users/$user")) {
		return 1;
	}

	return;
}

sub _check_opts {

	my $opts = shift;
	if ( grep { defined $opts->{$_} } (keys %{ $opts} ) ) {
		return 1;
	}
	return;
}

sub display_header {
	print "\n[*] Codeguard Resource Correction Tool\n";
	print "[*] Please report bugs at: https://projects.hostgator.com/projects/codeguard-rootbin-tool\n\n";
}

sub display_help {
	print "Usage: codeguard_fixer <valid_options> <cpanel_username>\n\n";
	print "Valid options to use:\n\n";
	print join "\n", map { "\t--$_" } (sort keys %{ $opts });
	print "\n\nSee wiki for more details: https://gatorwiki.hostgator.com/Admin/Codeguard\n";
}
