# -*- coding: utf-8-unix -*-

package Math::BigInt;

#
# "Mike had an infinite amount to do and a negative amount of time in which
# to do it." - Before and After
#

# The following hash values are used:
#   value: unsigned int with actual value (as a Math::BigInt::Calc or similar)
#   sign : +, -, NaN, +inf, -inf
#   _a   : accuracy
#   _p   : precision

# Remember not to take shortcuts ala $xs = $x->{value}; $LIB->foo($xs); since
# underlying lib might change the reference!

use 5.006001;
use strict;
use warnings;

use Carp          qw< carp croak >;
use Scalar::Util  qw< blessed >;

our $VERSION = '1.999830';
$VERSION =~ tr/_//d;

require Exporter;
our @ISA = qw(Exporter);
our @EXPORT_OK = qw(objectify bgcd blcm);

# Inside overload, the first arg is always an object. If the original code had
# it reversed (like $x = 2 * $y), then the third parameter is true.
# In some cases (like add, $x = $x + 2 is the same as $x = 2 + $x) this makes
# no difference, but in some cases it does.

# For overloaded ops with only one argument we simple use $_[0]->copy() to
# preserve the argument.

# Thus inheritance of overload operators becomes possible and transparent for
# our subclasses without the need to repeat the entire overload section there.

use overload

  # overload key: with_assign

  '+'     =>      sub { $_[0] -> copy() -> badd($_[1]); },

  '-'     =>      sub { my $c = $_[0] -> copy();
                        $_[2] ? $c -> bneg() -> badd($_[1])
                              : $c -> bsub($_[1]); },

  '*'     =>      sub { $_[0] -> copy() -> bmul($_[1]); },

  '/'     =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bdiv($_[0])
                              : $_[0] -> copy() -> bdiv($_[1]); },

  '%'     =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bmod($_[0])
                              : $_[0] -> copy() -> bmod($_[1]); },

  '**'    =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bpow($_[0])
                              : $_[0] -> copy() -> bpow($_[1]); },

  '<<'    =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> blsft($_[0])
                              : $_[0] -> copy() -> blsft($_[1]); },

  '>>'    =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> brsft($_[0])
                              : $_[0] -> copy() -> brsft($_[1]); },

  # overload key: assign

  '+='    =>      sub { $_[0] -> badd($_[1]); },

  '-='    =>      sub { $_[0] -> bsub($_[1]); },

  '*='    =>      sub { $_[0] -> bmul($_[1]); },

  '/='    =>      sub { scalar $_[0] -> bdiv($_[1]); },

  '%='    =>      sub { $_[0] -> bmod($_[1]); },

  '**='   =>      sub { $_[0] -> bpow($_[1]); },

  '<<='   =>      sub { $_[0] -> blsft($_[1]); },

  '>>='   =>      sub { $_[0] -> brsft($_[1]); },

#  'x='    =>      sub { },

#  '.='    =>      sub { },

  # overload key: num_comparison

  '<'     =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> blt($_[0])
                              : $_[0] -> blt($_[1]); },

  '<='    =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> ble($_[0])
                              : $_[0] -> ble($_[1]); },

  '>'     =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bgt($_[0])
                              : $_[0] -> bgt($_[1]); },

  '>='    =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bge($_[0])
                              : $_[0] -> bge($_[1]); },

  '=='    =>      sub { $_[0] -> beq($_[1]); },

  '!='    =>      sub { $_[0] -> bne($_[1]); },

  # overload key: 3way_comparison

  '<=>'   =>      sub { my $cmp = $_[0] -> bcmp($_[1]);
                        defined($cmp) && $_[2] ? -$cmp : $cmp; },

  'cmp'   =>      sub { $_[2] ? "$_[1]" cmp $_[0] -> bstr()
                              : $_[0] -> bstr() cmp "$_[1]"; },

  # overload key: str_comparison

#  'lt'    =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bstrlt($_[0])
#                              : $_[0] -> bstrlt($_[1]); },
#
#  'le'    =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bstrle($_[0])
#                              : $_[0] -> bstrle($_[1]); },
#
#  'gt'    =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bstrgt($_[0])
#                              : $_[0] -> bstrgt($_[1]); },
#
#  'ge'    =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bstrge($_[0])
#                              : $_[0] -> bstrge($_[1]); },
#
#  'eq'    =>      sub { $_[0] -> bstreq($_[1]); },
#
#  'ne'    =>      sub { $_[0] -> bstrne($_[1]); },

  # overload key: binary

  '&'     =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> band($_[0])
                              : $_[0] -> copy() -> band($_[1]); },

  '&='    =>      sub { $_[0] -> band($_[1]); },

  '|'     =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bior($_[0])
                              : $_[0] -> copy() -> bior($_[1]); },

  '|='    =>      sub { $_[0] -> bior($_[1]); },

  '^'     =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bxor($_[0])
                              : $_[0] -> copy() -> bxor($_[1]); },

  '^='    =>      sub { $_[0] -> bxor($_[1]); },

#  '&.'    =>      sub { },

#  '&.='   =>      sub { },

#  '|.'    =>      sub { },

#  '|.='   =>      sub { },

#  '^.'    =>      sub { },

#  '^.='   =>      sub { },

  # overload key: unary

  'neg'   =>      sub { $_[0] -> copy() -> bneg(); },

#  '!'     =>      sub { },

  '~'     =>      sub { $_[0] -> copy() -> bnot(); },

#  '~.'    =>      sub { },

  # overload key: mutators

  '++'    =>      sub { $_[0] -> binc() },

  '--'    =>      sub { $_[0] -> bdec() },

  # overload key: func

  'atan2' =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> batan2($_[0])
                              : $_[0] -> copy() -> batan2($_[1]); },

  'cos'   =>      sub { $_[0] -> copy() -> bcos(); },

  'sin'   =>      sub { $_[0] -> copy() -> bsin(); },

  'exp'   =>      sub { $_[0] -> copy() -> bexp($_[1]); },

  'abs'   =>      sub { $_[0] -> copy() -> babs(); },

  'log'   =>      sub { $_[0] -> copy() -> blog(); },

  'sqrt'  =>      sub { $_[0] -> copy() -> bsqrt(); },

  'int'   =>      sub { $_[0] -> copy() -> bint(); },

  # overload key: conversion

  'bool'  =>      sub { $_[0] -> is_zero() ? '' : 1; },

  '""'    =>      sub { $_[0] -> bstr(); },

  '0+'    =>      sub { $_[0] -> numify(); },

  '='     =>      sub { $_[0] -> copy(); },

  ;

##############################################################################
# global constants, flags and accessory

# These vars are public, but their direct usage is not recommended, use the
# accessor methods instead

our $round_mode = 'even'; # one of 'even', 'odd', '+inf', '-inf', 'zero', 'trunc' or 'common'
our $accuracy   = undef;
our $precision  = undef;
our $div_scale  = 40;
our $upgrade    = undef;                    # default is no upgrade
our $downgrade  = undef;                    # default is no downgrade

# These are internally, and not to be used from the outside at all

our $_trap_nan = 0;                         # are NaNs ok? set w/ config()
our $_trap_inf = 0;                         # are infs ok? set w/ config()

my $nan = 'NaN';                        # constants for easier life

# Module to do the low level math.

my $DEFAULT_LIB = 'Math::BigInt::Calc';
my $LIB;

# Has import() been called yet? Needed to make "require" work.

my $IMPORT = 0;

##############################################################################
# the old code had $rnd_mode, so we need to support it, too

our $rnd_mode   = 'even';

sub TIESCALAR {
    my ($class) = @_;
    bless \$round_mode, $class;
}

sub FETCH {
    return $round_mode;
}

sub STORE {
    $rnd_mode = $_[0]->round_mode($_[1]);
}

BEGIN {
    # tie to enable $rnd_mode to work transparently
    tie $rnd_mode, 'Math::BigInt';

    # set up some handy alias names
    *as_int = \&as_number;
    *is_pos = \&is_positive;
    *is_neg = \&is_negative;
}

###############################################################################
# Configuration methods
###############################################################################

sub round_mode {
    my $self = shift;
    my $class = ref($self) || $self || __PACKAGE__;

    if (@_) {                           # setter
        my $m = shift;
        croak("The value for 'round_mode' must be defined")
          unless defined $m;
        croak("Unknown round mode '$m'")
          unless $m =~ /^(even|odd|\+inf|\-inf|zero|trunc|common)$/;
        no strict 'refs';
        ${"${class}::round_mode"} = $m;
    }

    else {                              # getter
        no strict 'refs';
        my $m = ${"${class}::round_mode"};
        defined($m) ? $m : $round_mode;
    }
}

sub upgrade {
    no strict 'refs';
    # make Class->upgrade() work
    my $self = shift;
    my $class = ref($self) || $self || __PACKAGE__;
    # need to set new value?
    if (@_ > 0) {
        return ${"${class}::upgrade"} = $_[0];
    }
    ${"${class}::upgrade"};
}

sub downgrade {
    no strict 'refs';
    # make Class->downgrade() work
    my $self = shift;
    my $class = ref($self) || $self || __PACKAGE__;
    # need to set new value?
    if (@_ > 0) {
        return ${"${class}::downgrade"} = $_[0];
    }
    ${"${class}::downgrade"};
}

sub div_scale {
    my $self = shift;
    my $class = ref($self) || $self || __PACKAGE__;

    if (@_) {                           # setter
        my $ds = shift;
        croak("The value for 'div_scale' must be defined") unless defined $ds;
        croak("The value for 'div_scale' must be positive") unless $ds > 0;
        $ds = $ds -> numify() if defined(blessed($ds));
        no strict 'refs';
        ${"${class}::div_scale"} = $ds;
    }

    else {                              # getter
        no strict 'refs';
        my $ds = ${"${class}::div_scale"};
        defined($ds) ? $ds : $div_scale;
    }
}

sub accuracy {
    # $x->accuracy($a);           ref($x) $a
    # $x->accuracy();             ref($x)
    # Class->accuracy();          class
    # Class->accuracy($a);        class $a

    my $x = shift;
    my $class = ref($x) || $x || __PACKAGE__;

    no strict 'refs';
    if (@_ > 0) {
        my $a = shift;
        if (defined $a) {
            $a = $a->numify() if ref($a) && $a->can('numify');
            # also croak on non-numerical
            if (!$a || $a <= 0) {
                croak('Argument to accuracy must be greater than zero');
            }
            if (int($a) != $a) {
                croak('Argument to accuracy must be an integer');
            }
        }

        if (ref($x)) {
            # Set instance variable.
            $x->bround($a) if $a; # not for undef, 0
            $x->{_a} = $a;        # set/overwrite, even if not rounded
            delete $x->{_p};      # clear P
            # Why return class variable here? Fixme!
            $a = ${"${class}::accuracy"} unless defined $a; # proper return value
        } else {
            # Set class variable.
            ${"${class}::accuracy"} = $a; # set global A
            ${"${class}::precision"} = undef; # clear global P
        }

        return $a;              # shortcut
    }

    # Return instance variable.
    return $x->{_a} if ref($x) && (defined $x->{_a} || defined $x->{_p});

    # Return class variable.
    return ${"${class}::accuracy"};
}

sub precision {
    # $x->precision($p);          ref($x) $p
    # $x->precision();            ref($x)
    # Class->precision();         class
    # Class->precision($p);       class $p

    my $x = shift;
    my $class = ref($x) || $x || __PACKAGE__;

    no strict 'refs';
    if (@_ > 0) {
        my $p = shift;
        if (defined $p) {
            $p = $p->numify() if ref($p) && $p->can('numify');
            if ($p != int $p) {
                croak('Argument to precision must be an integer');
            }
        }

        if (ref($x)) {
            # Set instance variable.
            $x->bfround($p) if $p; # not for undef, 0
            $x->{_p} = $p;         # set/overwrite, even if not rounded
            delete $x->{_a};       # clear A
            # Why return class variable here? Fixme!
            $p = ${"${class}::precision"} unless defined $p; # proper return value
        } else {
            # Set class variable.
            ${"${class}::precision"} = $p; # set global P
            ${"${class}::accuracy"} = undef; # clear global A
        }

        return $p;              # shortcut
    }

    # Return instance variable.
    return $x->{_p} if ref($x) && (defined $x->{_a} || defined $x->{_p});

    # Return class variable.
    return ${"${class}::precision"};
}

sub config {
    # return (or set) configuration data.
    my $class = shift || __PACKAGE__;

    no strict 'refs';
    if (@_ > 1 || (@_ == 1 && (ref($_[0]) eq 'HASH'))) {
        # try to set given options as arguments from hash

        my $args = $_[0];
        if (ref($args) ne 'HASH') {
            $args = { @_ };
        }
        # these values can be "set"
        my $set_args = {};
        foreach my $key (qw/
                               accuracy precision
                               round_mode div_scale
                               upgrade downgrade
                               trap_inf trap_nan
                           /)
        {
            $set_args->{$key} = $args->{$key} if exists $args->{$key};
            delete $args->{$key};
        }
        if (keys %$args > 0) {
            croak("Illegal key(s) '", join("', '", keys %$args),
                        "' passed to $class\->config()");
        }
        foreach my $key (keys %$set_args) {
            if ($key =~ /^trap_(inf|nan)\z/) {
                ${"${class}::_trap_$1"} = ($set_args->{"trap_$1"} ? 1 : 0);
                next;
            }
            # use a call instead of just setting the $variable to check argument
            $class->$key($set_args->{$key});
        }
    }

    # now return actual configuration

    my $cfg = {
               lib         => $LIB,
               lib_version => ${"${LIB}::VERSION"},
               class       => $class,
               trap_nan    => ${"${class}::_trap_nan"},
               trap_inf    => ${"${class}::_trap_inf"},
               version     => ${"${class}::VERSION"},
              };
    foreach my $key (qw/
                           accuracy precision
                           round_mode div_scale
                           upgrade downgrade
                       /)
    {
        $cfg->{$key} = ${"${class}::$key"};
    }
    if (@_ == 1 && (ref($_[0]) ne 'HASH')) {
        # calls of the style config('lib') return just this value
        return $cfg->{$_[0]};
    }
    $cfg;
}

sub _scale_a {
    # select accuracy parameter based on precedence,
    # used by bround() and bfround(), may return undef for scale (means no op)
    my ($x, $scale, $mode) = @_;

    $scale = $x->{_a} unless defined $scale;

    no strict 'refs';
    my $class = ref($x);

    $scale = ${ $class . '::accuracy' } unless defined $scale;
    $mode = ${ $class . '::round_mode' } unless defined $mode;

    if (defined $scale) {
        $scale = $scale->can('numify') ? $scale->numify()
                                       : "$scale" if ref($scale);
        $scale = int($scale);
    }

    ($scale, $mode);
}

sub _scale_p {
    # select precision parameter based on precedence,
    # used by bround() and bfround(), may return undef for scale (means no op)
    my ($x, $scale, $mode) = @_;

    $scale = $x->{_p} unless defined $scale;

    no strict 'refs';
    my $class = ref($x);

    $scale = ${ $class . '::precision' } unless defined $scale;
    $mode = ${ $class . '::round_mode' } unless defined $mode;

    if (defined $scale) {
        $scale = $scale->can('numify') ? $scale->numify()
                                       : "$scale" if ref($scale);
        $scale = int($scale);
    }

    ($scale, $mode);
}

###############################################################################
# Constructor methods
###############################################################################

sub new {
    # Create a new Math::BigInt object from a string or another Math::BigInt
    # object. See hash keys documented at top.

    # The argument could be an object, so avoid ||, && etc. on it. This would
    # cause costly overloaded code to be called. The only allowed ops are ref()
    # and defined.

    my $self    = shift;
    my $selfref = ref $self;
    my $class   = $selfref || $self;

    # Make "require" work.

    $class -> import() if $IMPORT == 0;

    # Although this use has been discouraged for more than 10 years, people
    # apparently still use it, so we still support it.

    return $class -> bzero() unless @_;

    my ($wanted, @r) = @_;

    if (!defined($wanted)) {
        #if (warnings::enabled("uninitialized")) {
        #    warnings::warn("uninitialized",
        #                   "Use of uninitialized value in new()");
        #}
        return $class -> bzero(@r);
    }

    if (!ref($wanted) && $wanted eq "") {
        #if (warnings::enabled("numeric")) {
        #    warnings::warn("numeric",
        #                   q|Argument "" isn't numeric in new()|);
        #}
        #return $class -> bzero(@r);
        return $class -> bnan(@r);
    }

    # Initialize a new object.

    $self = bless {}, $class;

    # Math::BigInt or subclass

    if (defined(blessed($wanted)) && $wanted -> isa($class)) {

        # We don't copy the accuracy and precision, because a new object should
        # get them from the global configuration.

        $self -> {sign}  = $wanted -> {sign};
        $self -> {value} = $LIB -> _copy($wanted -> {value});
        $self->round(@r) unless @r >= 2 && !defined($r[0]) && !defined($r[1]);
        return $self;
    }

    # Shortcut for non-zero scalar integers with no non-zero exponent.

    if ($wanted =~ / ^
                     ([+-]?)            # optional sign
                     ([1-9][0-9]*)      # non-zero significand
                     (\.0*)?            # ... with optional zero fraction
                     ([Ee][+-]?0+)?     # optional zero exponent
                     \z
                   /x)
    {
        my $sgn = $1;
        my $abs = $2;
        $self->{sign} = $sgn || '+';
        $self->{value} = $LIB->_new($abs);
        $self->round(@r) unless @r >= 2 && !defined($r[0]) && !defined($r[1]);
        return $self;
    }

    # Handle Infs.

    if ($wanted =~ /^\s*([+-]?)inf(inity)?\s*\z/i) {
        my $sgn = $1 || '+';
        $self = $class -> binf($sgn);
        $self->round(@r) unless @r >= 2 && !defined($r[0]) && !defined($r[1]);
        return $self;
    }

    # Handle explicit NaNs (not the ones returned due to invalid input).

    if ($wanted =~ /^\s*([+-]?)nan\s*\z/i) {
        $self = $class -> bnan();
        $self->round(@r) unless @r >= 2 && !defined($r[0]) && !defined($r[1]);
        return $self;
    }

    my @parts;

    if (
        # Handle hexadecimal numbers. We auto-detect hexadecimal numbers if they
        # have a "0x", "0X", "x", or "X" prefix, cf. CORE::oct().

        $wanted =~ /^\s*[+-]?0?[Xx]/ and
        @parts = $class -> _hex_str_to_lib_parts($wanted)

          or

        # Handle octal numbers. We auto-detect octal numbers if they have a
        # "0o", "0O", "o", "O" prefix, cf. CORE::oct().

        $wanted =~ /^\s*[+-]?0?[Oo]/ and
        @parts = $class -> _oct_str_to_lib_parts($wanted)

          or

        # Handle binary numbers. We auto-detect binary numbers if they have a
        # "0b", "0B", "b", or "B" prefix, cf. CORE::oct().

        $wanted =~ /^\s*[+-]?0?[Bb]/ and
        @parts = $class -> _bin_str_to_lib_parts($wanted)

          or

        # At this point, what is left are decimal numbers that aren't handled
        # above and octal floating point numbers that don't have any of the
        # "0o", "0O", "o", or "O" prefixes. First see if it is a decimal number.

        @parts = $class -> _dec_str_to_lib_parts($wanted)
          or

        # See if it is an octal floating point number. The extra check is
        # included because _oct_str_to_lib_parts() accepts octal numbers that
        # don't have a prefix (this is needed to make it work with, e.g.,
        # from_oct() that don't require a prefix). However, Perl requires a
        # prefix for octal floating point literals. For example, "1p+0" is not
        # valid, but "01p+0" and "0__1p+0" are.

        $wanted =~ /^\s*[+-]?0_*\d/ and
        @parts = $class -> _oct_str_to_lib_parts($wanted))
    {
        # The value is an integer iff the exponent is non-negative.

        if ($parts[2] eq '+') {
            $self -> {sign}  = $parts[0];
            $self -> {value} = $LIB -> _lsft($parts[1], $parts[3], 10);
            $self->round(@r) unless @r >= 2 && !defined($r[0]) && !defined($r[1]);
            return $self;
        }

        # If we get here, the value is a valid number, but it is not an integer.

        return $upgrade -> new($wanted, @r) if defined $upgrade;
        return $class -> bnan();
    }

    # If we get here, the value is neither a valid decimal, binary, octal, or
    # hexadecimal number. It is not explicit an Inf or a NaN either.

    return $class -> bnan();
}

# Create a Math::BigInt from a decimal string. This is an equivalent to
# from_hex(), from_oct(), and from_bin(). It is like new() except that it does
# not accept anything but a string representing a finite decimal number.

sub from_dec {
    my $self    = shift;
    my $selfref = ref $self;
    my $class   = $selfref || $self;

    # Don't modify constant (read-only) objects.

    return if $selfref && $self->modify('from_dec');

    my $str = shift;
    my @r   = @_;

    # If called as a class method, initialize a new object.

    $self = $class -> bzero() unless $selfref;

    if (my @parts = $class -> _dec_str_to_lib_parts($str)) {

        # The value is an integer iff the exponent is non-negative.

        if ($parts[2] eq '+') {
            $self -> {sign}  = $parts[0];
            $self -> {value} = $LIB -> _lsft($parts[1], $parts[3], 10);
            return $self -> round(@r);
        }

        return $upgrade -> new($str, @r) if defined $upgrade;
    }

    return $self -> bnan(@r);
}

# Create a Math::BigInt from a hexadecimal string.

sub from_hex {
    my $self    = shift;
    my $selfref = ref $self;
    my $class   = $selfref || $self;

    # Don't modify constant (read-only) objects.

    return if $selfref && $self->modify('from_hex');

    my $str = shift;
    my @r   = @_;

    # If called as a class method, initialize a new object.

    $self = $class -> bzero() unless $selfref;

    if (my @parts = $class -> _hex_str_to_lib_parts($str)) {

        # The value is an integer iff the exponent is non-negative.

        if ($parts[2] eq '+') {
            $self -> {sign}  = $parts[0];
            $self -> {value} = $LIB -> _lsft($parts[1], $parts[3], 10);
            return $self -> round(@r);
        }

        return $upgrade -> new($str, @r) if defined $upgrade;
    }

    return $self -> bnan(@r);
}

# Create a Math::BigInt from an octal string.

sub from_oct {
    my $self    = shift;
    my $selfref = ref $self;
    my $class   = $selfref || $self;

    # Don't modify constant (read-only) objects.

    return if $selfref && $self->modify('from_oct');

    my $str = shift;
    my @r   = @_;

    # If called as a class method, initialize a new object.

    $self = $class -> bzero() unless $selfref;

    if (my @parts = $class -> _oct_str_to_lib_parts($str)) {

        # The value is an integer iff the exponent is non-negative.

        if ($parts[2] eq '+') {
            $self -> {sign}  = $parts[0];
            $self -> {value} = $LIB -> _lsft($parts[1], $parts[3], 10);
            return $self -> round(@r);
        }

        return $upgrade -> new($str, @r) if defined $upgrade;
    }

    return $self -> bnan(@r);
}

# Create a Math::BigInt from a binary string.

sub from_bin {
    my $self    = shift;
    my $selfref = ref $self;
    my $class   = $selfref || $self;

    # Don't modify constant (read-only) objects.

    return if $selfref && $self->modify('from_bin');

    my $str = shift;
    my @r   = @_;

    # If called as a class method, initialize a new object.

    $self = $class -> bzero() unless $selfref;

    if (my @parts = $class -> _bin_str_to_lib_parts($str)) {

        # The value is an integer iff the exponent is non-negative.

        if ($parts[2] eq '+') {
            $self -> {sign}  = $parts[0];
            $self -> {value} = $LIB -> _lsft($parts[1], $parts[3], 10);
            return $self -> round(@r);
        }

        return $upgrade -> new($str, @r) if defined $upgrade;
    }

    return $self -> bnan(@r);
}

# Create a Math::BigInt from a byte string.

sub from_bytes {
    my $self    = shift;
    my $selfref = ref $self;
    my $class   = $selfref || $self;

    # Don't modify constant (read-only) objects.

    return if $selfref && $self->modify('from_bytes');

    croak("from_bytes() requires a newer version of the $LIB library.")
        unless $LIB->can('_from_bytes');

    my $str = shift;
    my @r = @_;

    # If called as a class method, initialize a new object.

    $self = $class -> bzero() unless $selfref;
    $self -> {sign}  = '+';
    $self -> {value} = $LIB -> _from_bytes($str);
    return $self -> round(@r);
}

sub from_base {
    my $self    = shift;
    my $selfref = ref $self;
    my $class   = $selfref || $self;

    # Don't modify constant (read-only) objects.

    return if $selfref && $self->modify('from_base');

    my $str = shift;

    my $base = shift;
    $base = $class->new($base) unless ref($base);

    croak("the base must be a finite integer >= 2")
      if $base < 2 || ! $base -> is_int();

    # If called as a class method, initialize a new object.

    $self = $class -> bzero() unless $selfref;

    # If no collating sequence is given, pass some of the conversions to
    # methods optimized for those cases.

    if (! @_) {
        return $self -> from_bin($str) if $base == 2;
        return $self -> from_oct($str) if $base == 8;
        return $self -> from_hex($str) if $base == 16;
        if ($base == 10) {
            my $tmp = $class -> new($str);
            $self -> {value} = $tmp -> {value};
            $self -> {sign}  = '+';
        }
    }

    croak("from_base() requires a newer version of the $LIB library.")
      unless $LIB->can('_from_base');

    $self -> {sign}  = '+';
    $self -> {value}
      = $LIB->_from_base($str, $base -> {value}, @_ ? shift() : ());
    return $self;
}

sub from_base_num {
    my $self    = shift;
    my $selfref = ref $self;
    my $class   = $selfref || $self;

    # Don't modify constant (read-only) objects.

    return if $selfref && $self->modify('from_base_num');

    # Make sure we have an array of non-negative, finite, numerical objects.

    my $nums = shift;
    $nums = [ @$nums ];         # create new reference

    for my $i (0 .. $#$nums) {
        # Make sure we have an object.
        $nums -> [$i] = $class -> new($nums -> [$i])
          unless ref($nums -> [$i]) && $nums -> [$i] -> isa($class);
        # Make sure we have a finite, non-negative integer.
        croak "the elements must be finite non-negative integers"
          if $nums -> [$i] -> is_neg() || ! $nums -> [$i] -> is_int();
    }

    my $base = shift;
    $base = $class -> new($base) unless ref($base) && $base -> isa($class);

    my @r = @_;

    # If called as a class method, initialize a new object.

    $self = $class -> bzero() unless $selfref;

    croak("from_base_num() requires a newer version of the $LIB library.")
      unless $LIB->can('_from_base_num');

    $self -> {sign}  = '+';
    $self -> {value} = $LIB -> _from_base_num([ map { $_ -> {value} } @$nums ],
                                           $base -> {value});

    return $self -> round(@r);
}

sub bzero {
    # create/assign '+0'

    if (@_ == 0) {
        #carp("Using bzero() as a function is deprecated;",
        #           " use bzero() as a method instead");
        unshift @_, __PACKAGE__;
    }

    my $self    = shift;
    my $selfref = ref $self;
    my $class   = $selfref || $self;

    $self->import() if $IMPORT == 0;            # make require work

    # Don't modify constant (read-only) objects.

    return if $selfref && $self->modify('bzero');

    $self = bless {}, $class unless $selfref;

    $self->{sign} = '+';
    $self->{value} = $LIB->_zero();

    # If rounding parameters are given as arguments, use them. If no rounding
    # parameters are given, and if called as a class method initialize the new
    # instance with the class variables.

    if (@_) {
        croak "can't specify both accuracy and precision"
          if @_ >= 2 && defined $_[0] && defined $_[1];
        $self->{_a} = $_[0];
        $self->{_p} = $_[1];
    } else {
        unless($selfref) {
            $self->{_a} = $class -> accuracy();
            $self->{_p} = $class -> precision();
        }
    }

    return $self;
}

sub bone {
    # Create or assign '+1' (or -1 if given sign '-').

    if (@_ == 0 || (defined($_[0]) && ($_[0] eq '+' || $_[0] eq '-'))) {
        #carp("Using bone() as a function is deprecated;",
        #           " use bone() as a method instead");
        unshift @_, __PACKAGE__;
    }

    my $self    = shift;
    my $selfref = ref $self;
    my $class   = $selfref || $self;

    $self->import() if $IMPORT == 0;            # make require work

    # Don't modify constant (read-only) objects.

    return if $selfref && $self->modify('bone');

    my $sign = '+';             # default
    if (@_) {
        $sign = shift;
        $sign = $sign =~ /^\s*-/ ? "-" : "+";
    }

    $self = bless {}, $class unless $selfref;

    $self->{sign}  = $sign;
    $self->{value} = $LIB->_one();

    # If rounding parameters are given as arguments, use them. If no rounding
    # parameters are given, and if called as a class method initialize the new
    # instance with the class variables.

    if (@_) {
        croak "can't specify both accuracy and precision"
          if @_ >= 2 && defined $_[0] && defined $_[1];
        $self->{_a} = $_[0];
        $self->{_p} = $_[1];
    } else {
        unless($selfref) {
            $self->{_a} = $class -> accuracy();
            $self->{_p} = $class -> precision();
        }
    }

    return $self;
}

sub binf {
    # create/assign a '+inf' or '-inf'

    if (@_ == 0 || (defined($_[0]) && !ref($_[0]) &&
                    $_[0] =~ /^\s*[+-](inf(inity)?)?\s*$/))
    {
        #carp("Using binf() as a function is deprecated;",
        #           " use binf() as a method instead");
        unshift @_, __PACKAGE__;
    }

    my $self    = shift;
    my $selfref = ref $self;
    my $class   = $selfref || $self;

    {
        no strict 'refs';
        if (${"${class}::_trap_inf"}) {
            croak("Tried to create +-inf in $class->binf()");
        }
    }

    $self->import() if $IMPORT == 0;            # make require work

    # Don't modify constant (read-only) objects.

    return if $selfref && $self->modify('binf');

    my $sign = shift;
    $sign = defined $sign && $sign =~ /^\s*-/ ? "-" : "+";

    $self = bless {}, $class unless $selfref;

    $self -> {sign}  = $sign . 'inf';
    $self -> {value} = $LIB -> _zero();

    # If rounding parameters are given as arguments, use them. If no rounding
    # parameters are given, and if called as a class method initialize the new
    # instance with the class variables.

    if (@_) {
        croak "can't specify both accuracy and precision"
          if @_ >= 2 && defined $_[0] && defined $_[1];
        $self->{_a} = $_[0];
        $self->{_p} = $_[1];
    } else {
        unless($selfref) {
            $self->{_a} = $class -> accuracy();
            $self->{_p} = $class -> precision();
        }
    }

    return $self;
}

sub bnan {
    # create/assign a 'NaN'

    if (@_ == 0) {
        #carp("Using bnan() as a function is deprecated;",
        #           " use bnan() as a method instead");
        unshift @_, __PACKAGE__;
    }

    my $self    = shift;
    my $selfref = ref($self);
    my $class   = $selfref || $self;

    {
        no strict 'refs';
        if (${"${class}::_trap_nan"}) {
            croak("Tried to create NaN in $class->bnan()");
        }
    }

    $self->import() if $IMPORT == 0;            # make require work

    # Don't modify constant (read-only) objects.

    return if $selfref && $self->modify('bnan');

    $self = bless {}, $class unless $selfref;

    $self -> {sign}  = $nan;
    $self -> {value} = $LIB -> _zero();

    # If rounding parameters are given as arguments, use them. If no rounding
    # parameters are given, and if called as a class method initialize the new
    # instance with the class variables.

    if (@_) {
        croak "can't specify both accuracy and precision"
          if @_ >= 2 && defined $_[0] && defined $_[1];
        $self->{_a} = $_[0];
        $self->{_p} = $_[1];
    } else {
        unless($selfref) {
            $self->{_a} = $class -> accuracy();
            $self->{_p} = $class -> precision();
        }
    }

    return $self;
}

sub bpi {

    # Called as               Argument list
    # ---------               -------------
    # Math::BigInt->bpi()     ("Math::BigInt")
    # Math::BigInt->bpi(10)   ("Math::BigInt", 10)
    # $x->bpi()               ($x)
    # $x->bpi(10)             ($x, 10)
    # Math::BigInt::bpi()     ()
    # Math::BigInt::bpi(10)   (10)
    #
    # In ambiguous cases, we favour the OO-style, so the following case
    #
    #   $n = Math::BigInt->new("10");
    #   $x = Math::BigInt->bpi($n);
    #
    # which gives an argument list with the single element $n, is resolved as
    #
    #   $n->bpi();

    my $self    = shift;
    my $selfref = ref $self;
    my $class   = $selfref || $self;

    my @r;                      # rounding paramters

    # If bpi() is called as a function ...
    #
    # This cludge is necessary because we still support bpi() as a function. If
    # bpi() is called with either no argument or one argument, and that one
    # argument is either undefined or a scalar that looks like a number, then
    # we assume bpi() is called as a function.

    if (@_ == 0 &&
        (defined($self) && !ref($self) && $self =~ /^\s*[+-]?\d/)
          ||
        !defined($self))
    {
        $r[0]  = $self;
        $class = __PACKAGE__;
        $self  = bless {}, $class;
    }

    # ... or if bpi() is called as a method ...

    else {
        @r = @_;
        if ($selfref) {                     # bpi() called as instance method
            return $self if $self -> modify('bpi');
        } else {                            # bpi() called as class method
            $self  = bless {}, $class;
        }
    }

    return $upgrade -> bpi(@r) if defined $upgrade;

    # hard-wired to "3"
    $self -> {sign}  = '+';
    $self -> {value} = $LIB -> _new("3");
    $self -> round(@r) unless @r >= 2 && !defined($r[0]) && !defined($r[1]);
    return $self;
}

sub copy {
    my $self    = shift;
    my $selfref = ref $self;
    my $class   = $selfref || $self;

    # If called as a class method, the object to copy is the next argument.

    $self = shift() unless $selfref;

    my $copy = bless {}, $class;

    $copy->{sign}  = $self->{sign};
    $copy->{value} = $LIB->_copy($self->{value});
    $copy->{_a}    = $self->{_a} if exists $self->{_a};
    $copy->{_p}    = $self->{_p} if exists $self->{_p};

    return $copy;
}

sub as_number {
    # An object might be asked to return itself as bigint on certain overloaded
    # operations. This does exactly this, so that sub classes can simple inherit
    # it or override with their own integer conversion routine.
    $_[0]->copy();
}

###############################################################################
# Boolean methods
###############################################################################

sub is_zero {
    # return true if arg (BINT or num_str) is zero (array '+', '0')
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    return 0 if $x->{sign} !~ /^\+$/; # -, NaN & +-inf aren't
    $LIB->_is_zero($x->{value});
}

sub is_one {
    # return true if arg (BINT or num_str) is +1, or -1 if sign is given
    my ($class, $x, $sign) = ref($_[0]) ? (undef, @_) : objectify(1, @_);

    $sign = '+' if !defined $sign || $sign ne '-';

    return 0 if $x->{sign} ne $sign; # -1 != +1, NaN, +-inf aren't either
    $LIB->_is_one($x->{value});
}

sub is_finite {
    my $x = shift;
    return $x->{sign} eq '+' || $x->{sign} eq '-';
}

sub is_inf {
    # return true if arg (BINT or num_str) is +-inf
    my ($class, $x, $sign) = ref($_[0]) ? (undef, @_) : objectify(1, @_);

    if (defined $sign) {
        $sign = '[+-]inf' if $sign eq ''; # +- doesn't matter, only that's inf
        $sign = "[$1]inf" if $sign =~ /^([+-])(inf)?$/; # extract '+' or '-'
        return $x->{sign} =~ /^$sign$/ ? 1 : 0;
    }
    $x->{sign} =~ /^[+-]inf$/ ? 1 : 0; # only +-inf is infinity
}

sub is_nan {
    # return true if arg (BINT or num_str) is NaN
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    $x->{sign} eq $nan ? 1 : 0;
}

sub is_positive {
    # return true when arg (BINT or num_str) is positive (> 0)
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    return 1 if $x->{sign} eq '+inf'; # +inf is positive

    # 0+ is neither positive nor negative
    ($x->{sign} eq '+' && !$x->is_zero()) ? 1 : 0;
}

sub is_negative {
    # return true when arg (BINT or num_str) is negative (< 0)
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    $x->{sign} =~ /^-/ ? 1 : 0; # -inf is negative, but NaN is not
}

sub is_non_negative {
    # Return true if argument is non-negative (>= 0).
    my ($class, $x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);

    return 1 if $x->{sign} =~ /^\+/;
    return 1 if $x -> is_zero();
    return 0;
}

sub is_non_positive {
    # Return true if argument is non-positive (<= 0).
    my ($class, $x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);

    return 1 if $x->{sign} =~ /^\-/;
    return 1 if $x -> is_zero();
    return 0;
}

sub is_odd {
    # return true when arg (BINT or num_str) is odd, false for even
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    return 0 if $x->{sign} !~ /^[+-]$/; # NaN & +-inf aren't
    $LIB->_is_odd($x->{value});
}

sub is_even {
    # return true when arg (BINT or num_str) is even, false for odd
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    return 0 if $x->{sign} !~ /^[+-]$/; # NaN & +-inf aren't
    $LIB->_is_even($x->{value});
}

sub is_int {
    # return true when arg (BINT or num_str) is an integer
    # always true for Math::BigInt, but different for Math::BigFloat objects
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    $x->{sign} =~ /^[+-]$/ ? 1 : 0; # inf/-inf/NaN aren't
}

###############################################################################
# Comparison methods
###############################################################################

sub bcmp {
    # Compares 2 values.  Returns one of undef, <0, =0, >0. (suitable for sort)
    # (BINT or num_str, BINT or num_str) return cond_code

    # set up parameters
    my ($class, $x, $y) = ref($_[0]) && ref($_[0]) eq ref($_[1])
                        ? (ref($_[0]), @_)
                        : objectify(2, @_);

    return $upgrade->bcmp($x, $y) if defined $upgrade &&
      ((!$x->isa($class)) || (!$y->isa($class)));

    if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/)) {
        # handle +-inf and NaN
        return    if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
        return  0 if $x->{sign} eq $y->{sign} && $x->{sign} =~ /^[+-]inf$/;
        return +1 if $x->{sign} eq '+inf';
        return -1 if $x->{sign} eq '-inf';
        return -1 if $y->{sign} eq '+inf';
        return +1;
    }
    # check sign for speed first
    return 1 if $x->{sign} eq '+' && $y->{sign} eq '-'; # does also 0 <=> -y
    return -1 if $x->{sign} eq '-' && $y->{sign} eq '+'; # does also -x <=> 0

    # have same sign, so compare absolute values.  Don't make tests for zero
    # here because it's actually slower than testing in Calc (especially w/ Pari
    # et al)

    # post-normalized compare for internal use (honors signs)
    if ($x->{sign} eq '+') {
        # $x and $y both > 0
        return $LIB->_acmp($x->{value}, $y->{value});
    }

    # $x && $y both < 0
    $LIB->_acmp($y->{value}, $x->{value}); # swapped acmp (lib returns 0, 1, -1)
}

sub bacmp {
    # Compares 2 values, ignoring their signs.
    # Returns one of undef, <0, =0, >0. (suitable for sort)
    # (BINT, BINT) return cond_code

    # set up parameters
    my ($class, $x, $y) = ref($_[0]) && ref($_[0]) eq ref($_[1])
                        ? (ref($_[0]), @_)
                        : objectify(2, @_);

    return $upgrade->bacmp($x, $y) if defined $upgrade &&
      ((!$x->isa($class)) || (!$y->isa($class)));

    if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/)) {
        # handle +-inf and NaN
        return   if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
        return 0 if $x->{sign} =~ /^[+-]inf$/ && $y->{sign} =~ /^[+-]inf$/;
        return 1 if $x->{sign} =~ /^[+-]inf$/ && $y->{sign} !~ /^[+-]inf$/;
        return -1;
    }
    $LIB->_acmp($x->{value}, $y->{value}); # lib does only 0, 1, -1
}

sub beq {
    my $self    = shift;
    my $selfref = ref $self;

    croak 'beq() is an instance method, not a class method' unless $selfref;
    croak 'Wrong number of arguments for beq()' unless @_ == 1;

    my $cmp = $self -> bcmp(shift);
    return defined($cmp) && ! $cmp;
}

sub bne {
    my $self    = shift;
    my $selfref = ref $self;

    croak 'bne() is an instance method, not a class method' unless $selfref;
    croak 'Wrong number of arguments for bne()' unless @_ == 1;

    my $cmp = $self -> bcmp(shift);
    return defined($cmp) && ! $cmp ? '' : 1;
}

sub blt {
    my $self    = shift;
    my $selfref = ref $self;

    croak 'blt() is an instance method, not a class method' unless $selfref;
    croak 'Wrong number of arguments for blt()' unless @_ == 1;

    my $cmp = $self -> bcmp(shift);
    return defined($cmp) && $cmp < 0;
}

sub ble {
    my $self    = shift;
    my $selfref = ref $self;

    croak 'ble() is an instance method, not a class method' unless $selfref;
    croak 'Wrong number of arguments for ble()' unless @_ == 1;

    my $cmp = $self -> bcmp(shift);
    return defined($cmp) && $cmp <= 0;
}

sub bgt {
    my $self    = shift;
    my $selfref = ref $self;

    croak 'bgt() is an instance method, not a class method' unless $selfref;
    croak 'Wrong number of arguments for bgt()' unless @_ == 1;

    my $cmp = $self -> bcmp(shift);
    return defined($cmp) && $cmp > 0;
}

sub bge {
    my $self    = shift;
    my $selfref = ref $self;

    croak 'bge() is an instance method, not a class method'
        unless $selfref;
    croak 'Wrong number of arguments for bge()' unless @_ == 1;

    my $cmp = $self -> bcmp(shift);
    return defined($cmp) && $cmp >= 0;
}

###############################################################################
# Arithmetic methods
###############################################################################

sub bneg {
    # (BINT or num_str) return BINT
    # negate number or make a negated number from string
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    return $x if $x->modify('bneg');

    # for +0 do not negate (to have always normalized +0). Does nothing for 'NaN'
    $x->{sign} =~ tr/+-/-+/ unless ($x->{sign} eq '+' && $LIB->_is_zero($x->{value}));
    $x;
}

sub babs {
    # (BINT or num_str) return BINT
    # make number absolute, or return absolute BINT from string
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    return $x if $x->modify('babs');
    # post-normalized abs for internal use (does nothing for NaN)
    $x->{sign} =~ s/^-/+/;
    $x;
}

sub bsgn {
    # Signum function.

    my $self = shift;

    return $self if $self->modify('bsgn');

    return $self -> bone("+") if $self -> is_pos();
    return $self -> bone("-") if $self -> is_neg();
    return $self;               # zero or NaN
}

sub bnorm {
    # (numstr or BINT) return BINT
    # Normalize number -- no-op here
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);
    $x;
}

sub binc {
    # increment arg by one
    my ($class, $x, $a, $p, $r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
    return $x if $x->modify('binc');

    if ($x->{sign} eq '+') {
        $x->{value} = $LIB->_inc($x->{value});
        return $x->round($a, $p, $r);
    } elsif ($x->{sign} eq '-') {
        $x->{value} = $LIB->_dec($x->{value});
        $x->{sign} = '+' if $LIB->_is_zero($x->{value}); # -1 +1 => -0 => +0
        return $x->round($a, $p, $r);
    }
    # inf, nan handling etc
    $x->badd($class->bone(), $a, $p, $r); # badd does round
}

sub bdec {
    # decrement arg by one
    my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
    return $x if $x->modify('bdec');

    if ($x->{sign} eq '-') {
        # x already < 0
        $x->{value} = $LIB->_inc($x->{value});
    } else {
        return $x->badd($class->bone('-'), @r)
          unless $x->{sign} eq '+'; # inf or NaN
        # >= 0
        if ($LIB->_is_zero($x->{value})) {
            # == 0
            $x->{value} = $LIB->_one();
            $x->{sign} = '-'; # 0 => -1
        } else {
            # > 0
            $x->{value} = $LIB->_dec($x->{value});
        }
    }
    $x->round(@r);
}

#sub bstrcmp {
#    my $self    = shift;
#    my $selfref = ref $self;
#    my $class   = $selfref || $self;
#
#    croak 'bstrcmp() is an instance method, not a class method'
#        unless $selfref;
#    croak 'Wrong number of arguments for bstrcmp()' unless @_ == 1;
#
#    return $self -> bstr() CORE::cmp shift;
#}
#
#sub bstreq {
#    my $self    = shift;
#    my $selfref = ref $self;
#    my $class   = $selfref || $self;
#
#    croak 'bstreq() is an instance method, not a class method'
#        unless $selfref;
#    croak 'Wrong number of arguments for bstreq()' unless @_ == 1;
#
#    my $cmp = $self -> bstrcmp(shift);
#    return defined($cmp) && ! $cmp;
#}
#
#sub bstrne {
#    my $self    = shift;
#    my $selfref = ref $self;
#    my $class   = $selfref || $self;
#
#    croak 'bstrne() is an instance method, not a class method'
#        unless $selfref;
#    croak 'Wrong number of arguments for bstrne()' unless @_ == 1;
#
#    my $cmp = $self -> bstrcmp(shift);
#    return defined($cmp) && ! $cmp ? '' : 1;
#}
#
#sub bstrlt {
#    my $self    = shift;
#    my $selfref = ref $self;
#    my $class   = $selfref || $self;
#
#    croak 'bstrlt() is an instance method, not a class method'
#        unless $selfref;
#    croak 'Wrong number of arguments for bstrlt()' unless @_ == 1;
#
#    my $cmp = $self -> bstrcmp(shift);
#    return defined($cmp) && $cmp < 0;
#}
#
#sub bstrle {
#    my $self    = shift;
#    my $selfref = ref $self;
#    my $class   = $selfref || $self;
#
#    croak 'bstrle() is an instance method, not a class method'
#        unless $selfref;
#    croak 'Wrong number of arguments for bstrle()' unless @_ == 1;
#
#    my $cmp = $self -> bstrcmp(shift);
#    return defined($cmp) && $cmp <= 0;
#}
#
#sub bstrgt {
#    my $self    = shift;
#    my $selfref = ref $self;
#    my $class   = $selfref || $self;
#
#    croak 'bstrgt() is an instance method, not a class method'
#        unless $selfref;
#    croak 'Wrong number of arguments for bstrgt()' unless @_ == 1;
#
#    my $cmp = $self -> bstrcmp(shift);
#    return defined($cmp) && $cmp > 0;
#}
#
#sub bstrge {
#    my $self    = shift;
#    my $selfref = ref $self;
#    my $class   = $selfref || $self;
#
#    croak 'bstrge() is an instance method, not a class method'
#        unless $selfref;
#    croak 'Wrong number of arguments for bstrge()' unless @_ == 1;
#
#    my $cmp = $self -> bstrcmp(shift);
#    return defined($cmp) && $cmp >= 0;
#}

sub badd {

    # add second arg (BINT or string) to first (BINT) (modifies first)
    # return result as BINT

    # set up parameters
    my ($class, $x, $y, @r) = (ref($_[0]), @_);
    # objectify is costly, so avoid it
    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
        ($class, $x, $y, @r) = objectify(2, @_);
    }

    return $x if $x->modify('badd');
    return $upgrade->badd($upgrade->new($x), $upgrade->new($y), @r) if defined $upgrade &&
      ((!$x->isa($class)) || (!$y->isa($class)));

    $r[3] = $y;                 # no push!
    # inf and NaN handling
    if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/) {
        # NaN first
        return $x->bnan() if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
        # inf handling
        if (($x->{sign} =~ /^[+-]inf$/) && ($y->{sign} =~ /^[+-]inf$/)) {
            # +inf++inf or -inf+-inf => same, rest is NaN
            return $x if $x->{sign} eq $y->{sign};
            return $x->bnan();
        }
        # +-inf + something => +inf
        # something +-inf => +-inf
        $x->{sign} = $y->{sign}, return $x if $y->{sign} =~ /^[+-]inf$/;
        return $x;
    }

    my ($sx, $sy) = ($x->{sign}, $y->{sign});  # get signs

    if ($sx eq $sy) {
        $x->{value} = $LIB->_add($x->{value}, $y->{value}); # same sign, abs add
    } else {
        my $a = $LIB->_acmp ($y->{value}, $x->{value}); # absolute compare
        if ($a > 0) {
            $x->{value} = $LIB->_sub($y->{value}, $x->{value}, 1); # abs sub w/ swap
            $x->{sign} = $sy;
        } elsif ($a == 0) {
            # speedup, if equal, set result to 0
            $x->{value} = $LIB->_zero();
            $x->{sign} = '+';
        } else                  # a < 0
        {
            $x->{value} = $LIB->_sub($x->{value}, $y->{value}); # abs sub
        }
    }
    $x->round(@r);
}

sub bsub {
    # (BINT or num_str, BINT or num_str) return BINT
    # subtract second arg from first, modify first

    # set up parameters
    my ($class, $x, $y, @r) = (ref($_[0]), @_);

    # objectify is costly, so avoid it
    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
        ($class, $x, $y, @r) = objectify(2, @_);
    }

    return $x if $x -> modify('bsub');

    return $upgrade -> bsub($upgrade -> new($x), $upgrade -> new($y), @r)
      if defined $upgrade && (!$x -> isa($class) || !$y -> isa($class));

    return $x -> round(@r) if $y -> is_zero();

    # To correctly handle the lone special case $x -> bsub($x), we note the
    # sign of $x, then flip the sign from $y, and if the sign of $x did change,
    # too, then we caught the special case:

    my $xsign = $x -> {sign};
    $y -> {sign} =~ tr/+-/-+/;  # does nothing for NaN
    if ($xsign ne $x -> {sign}) {
        # special case of $x -> bsub($x) results in 0
        return $x -> bzero(@r) if $xsign =~ /^[+-]$/;
        return $x -> bnan();    # NaN, -inf, +inf
    }
    $x -> badd($y, @r);         # badd does not leave internal zeros
    $y -> {sign} =~ tr/+-/-+/;  # refix $y (does nothing for NaN)
    $x;                         # already rounded by badd() or no rounding
}

sub bmul {
    # multiply the first number by the second number
    # (BINT or num_str, BINT or num_str) return BINT

    # set up parameters
    my ($class, $x, $y, @r) = (ref($_[0]), @_);
    # objectify is costly, so avoid it
    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
        ($class, $x, $y, @r) = objectify(2, @_);
    }

    return $x if $x->modify('bmul');

    return $x->bnan() if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));

    # inf handling
    if (($x->{sign} =~ /^[+-]inf$/) || ($y->{sign} =~ /^[+-]inf$/)) {
        return $x->bnan() if $x->is_zero() || $y->is_zero();
        # result will always be +-inf:
        # +inf * +/+inf => +inf, -inf * -/-inf => +inf
        # +inf * -/-inf => -inf, -inf * +/+inf => -inf
        return $x->binf() if ($x->{sign} =~ /^\+/ && $y->{sign} =~ /^\+/);
        return $x->binf() if ($x->{sign} =~ /^-/ && $y->{sign} =~ /^-/);
        return $x->binf('-');
    }

    return $upgrade->bmul($x, $upgrade->new($y), @r)
      if defined $upgrade && !$y->isa($class);

    $r[3] = $y;                 # no push here

    $x->{sign} = $x->{sign} eq $y->{sign} ? '+' : '-'; # +1 * +1 or -1 * -1 => +

    $x->{value} = $LIB->_mul($x->{value}, $y->{value}); # do actual math
    $x->{sign} = '+' if $LIB->_is_zero($x->{value});   # no -0

    $x->round(@r);
}

sub bmuladd {
    # multiply two numbers and then add the third to the result
    # (BINT or num_str, BINT or num_str, BINT or num_str) return BINT

    # set up parameters
    my ($class, $x, $y, $z, @r) = objectify(3, @_);

    return $x if $x->modify('bmuladd');

    return $x->bnan() if (($x->{sign} eq $nan) ||
                          ($y->{sign} eq $nan) ||
                          ($z->{sign} eq $nan));

    # inf handling of x and y
    if (($x->{sign} =~ /^[+-]inf$/) || ($y->{sign} =~ /^[+-]inf$/)) {
        return $x->bnan() if $x->is_zero() || $y->is_zero();
        # result will always be +-inf:
        # +inf * +/+inf => +inf, -inf * -/-inf => +inf
        # +inf * -/-inf => -inf, -inf * +/+inf => -inf
        return $x->binf() if ($x->{sign} =~ /^\+/ && $y->{sign} =~ /^\+/);
        return $x->binf() if ($x->{sign} =~ /^-/ && $y->{sign} =~ /^-/);
        return $x->binf('-');
    }
    # inf handling x*y and z
    if (($z->{sign} =~ /^[+-]inf$/)) {
        # something +-inf => +-inf
        $x->{sign} = $z->{sign}, return $x if $z->{sign} =~ /^[+-]inf$/;
    }

    return $upgrade->bmuladd($x, $upgrade->new($y), $upgrade->new($z), @r)
      if defined $upgrade && (!$y->isa($class) || !$z->isa($class) || !$x->isa($class));

    # TODO: what if $y and $z have A or P set?
    $r[3] = $z;                 # no push here

    $x->{sign} = $x->{sign} eq $y->{sign} ? '+' : '-'; # +1 * +1 or -1 * -1 => +

    $x->{value} = $LIB->_mul($x->{value}, $y->{value}); # do actual math
    $x->{sign} = '+' if $LIB->_is_zero($x->{value});   # no -0

    my ($sx, $sz) = ( $x->{sign}, $z->{sign} ); # get signs

    if ($sx eq $sz) {
        $x->{value} = $LIB->_add($x->{value}, $z->{value}); # same sign, abs add
    } else {
        my $a = $LIB->_acmp ($z->{value}, $x->{value}); # absolute compare
        if ($a > 0) {
            $x->{value} = $LIB->_sub($z->{value}, $x->{value}, 1); # abs sub w/ swap
            $x->{sign} = $sz;
        } elsif ($a == 0) {
            # speedup, if equal, set result to 0
            $x->{value} = $LIB->_zero();
            $x->{sign} = '+';
        } else                  # a < 0
        {
            $x->{value} = $LIB->_sub($x->{value}, $z->{value}); # abs sub
        }
    }
    $x->round(@r);
}

sub bdiv {
    # This does floored division, where the quotient is floored, i.e., rounded
    # towards negative infinity. As a consequence, the remainder has the same
    # sign as the divisor.

    # Set up parameters.
    my ($class, $x, $y, @r) = (ref($_[0]), @_);

    # objectify() is costly, so avoid it if we can.
    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
        ($class, $x, $y, @r) = objectify(2, @_);
    }

    return $x if $x -> modify('bdiv');

    my $wantarray = wantarray;          # call only once

    # At least one argument is NaN. Return NaN for both quotient and the
    # modulo/remainder.

    if ($x -> is_nan() || $y -> is_nan()) {
        return $wantarray ? ($x -> bnan(), $class -> bnan()) : $x -> bnan();
    }

    # Divide by zero and modulo zero.
    #
    # Division: Use the common convention that x / 0 is inf with the same sign
    # as x, except when x = 0, where we return NaN. This is also what earlier
    # versions did.
    #
    # Modulo: In modular arithmetic, the congruence relation z = x (mod y)
    # means that there is some integer k such that z - x = k y. If y = 0, we
    # get z - x = 0 or z = x. This is also what earlier versions did, except
    # that 0 % 0 returned NaN.
    #
    #     inf /    0 =  inf                  inf %    0 =  inf
    #       5 /    0 =  inf                    5 %    0 =    5
    #       0 /    0 =  NaN                    0 %    0 =    0
    #      -5 /    0 = -inf                   -5 %    0 =   -5
    #    -inf /    0 = -inf                 -inf %    0 = -inf

    if ($y -> is_zero()) {
        my $rem;
        if ($wantarray) {
            $rem = $x -> copy();
        }
        if ($x -> is_zero()) {
            $x -> bnan();
        } else {
            $x -> binf($x -> {sign});
        }
        return $wantarray ? ($x, $rem) : $x;
    }

    # Numerator (dividend) is +/-inf, and denominator is finite and non-zero.
    # The divide by zero cases are covered above. In all of the cases listed
    # below we return the same as core Perl.
    #
    #     inf / -inf =  NaN                  inf % -inf =  NaN
    #     inf /   -5 = -inf                  inf %   -5 =  NaN
    #     inf /    5 =  inf                  inf %    5 =  NaN
    #     inf /  inf =  NaN                  inf %  inf =  NaN
    #
    #    -inf / -inf =  NaN                 -inf % -inf =  NaN
    #    -inf /   -5 =  inf                 -inf %   -5 =  NaN
    #    -inf /    5 = -inf                 -inf %    5 =  NaN
    #    -inf /  inf =  NaN                 -inf %  inf =  NaN

    if ($x -> is_inf()) {
        my $rem;
        $rem = $class -> bnan() if $wantarray;
        if ($y -> is_inf()) {
            $x -> bnan();
        } else {
            my $sign = $x -> bcmp(0) == $y -> bcmp(0) ? '+' : '-';
            $x -> binf($sign);
        }
        return $wantarray ? ($x, $rem) : $x;
    }

    # Denominator (divisor) is +/-inf. The cases when the numerator is +/-inf
    # are covered above. In the modulo cases (in the right column) we return
    # the same as core Perl, which does floored division, so for consistency we
    # also do floored division in the division cases (in the left column).
    #
    #      -5 /  inf =   -1                   -5 %  inf =  inf
    #       0 /  inf =    0                    0 %  inf =    0
    #       5 /  inf =    0                    5 %  inf =    5
    #
    #      -5 / -inf =    0                   -5 % -inf =   -5
    #       0 / -inf =    0                    0 % -inf =    0
    #       5 / -inf =   -1                    5 % -inf = -inf

    if ($y -> is_inf()) {
        my $rem;
        if ($x -> is_zero() || $x -> bcmp(0) == $y -> bcmp(0)) {
            $rem = $x -> copy() if $wantarray;
            $x -> bzero();
        } else {
            $rem = $class -> binf($y -> {sign}) if $wantarray;
            $x -> bone('-');
        }
        return $wantarray ? ($x, $rem) : $x;
    }

    # At this point, both the numerator and denominator are finite numbers, and
    # the denominator (divisor) is non-zero.

    return $upgrade -> bdiv($upgrade -> new($x), $upgrade -> new($y), @r)
      if defined $upgrade;

    $r[3] = $y;                                   # no push!

    # Inialize remainder.

    my $rem = $class -> bzero();

    # Are both operands the same object, i.e., like $x -> bdiv($x)? If so,
    # flipping the sign of $y also flips the sign of $x.

    my $xsign = $x -> {sign};
    my $ysign = $y -> {sign};

    $y -> {sign} =~ tr/+-/-+/;            # Flip the sign of $y, and see ...
    my $same = $xsign ne $x -> {sign};    # ... if that changed the sign of $x.
    $y -> {sign} = $ysign;                # Re-insert the original sign.

    if ($same) {
        $x -> bone();
    } else {
        ($x -> {value}, $rem -> {value}) =
          $LIB -> _div($x -> {value}, $y -> {value});

        if ($LIB -> _is_zero($rem -> {value})) {
            if ($xsign eq $ysign || $LIB -> _is_zero($x -> {value})) {
                $x -> {sign} = '+';
            } else {
                $x -> {sign} = '-';
            }
        } else {
            if ($xsign eq $ysign) {
                $x -> {sign} = '+';
            } else {
                if ($xsign eq '+') {
                    $x -> badd(1);
                } else {
                    $x -> bsub(1);
                }
                $x -> {sign} = '-';
            }
        }
    }

    $x -> round(@r);

    if ($wantarray) {
        unless ($LIB -> _is_zero($rem -> {value})) {
            if ($xsign ne $ysign) {
                $rem = $y -> copy() -> babs() -> bsub($rem);
            }
            $rem -> {sign} = $ysign;
        }
        $rem -> {_a} = $x -> {_a};
        $rem -> {_p} = $x -> {_p};
        $rem -> round(@r);
        return ($x, $rem);
    }

    return $x;
}

sub btdiv {
    # This does truncated division, where the quotient is truncted, i.e.,
    # rounded towards zero.
    #
    # ($q, $r) = $x -> btdiv($y) returns $q and $r so that $q is int($x / $y)
    # and $q * $y + $r = $x.

    # Set up parameters
    my ($class, $x, $y, @r) = (ref($_[0]), @_);

    # objectify is costly, so avoid it if we can.
    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
        ($class, $x, $y, @r) = objectify(2, @_);
    }

    return $x if $x -> modify('btdiv');

    my $wantarray = wantarray;          # call only once

    # At least one argument is NaN. Return NaN for both quotient and the
    # modulo/remainder.

    if ($x -> is_nan() || $y -> is_nan()) {
        return $wantarray ? ($x -> bnan(), $class -> bnan()) : $x -> bnan();
    }

    # Divide by zero and modulo zero.
    #
    # Division: Use the common convention that x / 0 is inf with the same sign
    # as x, except when x = 0, where we return NaN. This is also what earlier
    # versions did.
    #
    # Modulo: In modular arithmetic, the congruence relation z = x (mod y)
    # means that there is some integer k such that z - x = k y. If y = 0, we
    # get z - x = 0 or z = x. This is also what earlier versions did, except
    # that 0 % 0 returned NaN.
    #
    #     inf / 0 =  inf                     inf % 0 =  inf
    #       5 / 0 =  inf                       5 % 0 =    5
    #       0 / 0 =  NaN                       0 % 0 =    0
    #      -5 / 0 = -inf                      -5 % 0 =   -5
    #    -inf / 0 = -inf                    -inf % 0 = -inf

    if ($y -> is_zero()) {
        my $rem;
        if ($wantarray) {
            $rem = $x -> copy();
        }
        if ($x -> is_zero()) {
            $x -> bnan();
        } else {
            $x -> binf($x -> {sign});
        }
        return $wantarray ? ($x, $rem) : $x;
    }

    # Numerator (dividend) is +/-inf, and denominator is finite and non-zero.
    # The divide by zero cases are covered above. In all of the cases listed
    # below we return the same as core Perl.
    #
    #     inf / -inf =  NaN                  inf % -inf =  NaN
    #     inf /   -5 = -inf                  inf %   -5 =  NaN
    #     inf /    5 =  inf                  inf %    5 =  NaN
    #     inf /  inf =  NaN                  inf %  inf =  NaN
    #
    #    -inf / -inf =  NaN                 -inf % -inf =  NaN
    #    -inf /   -5 =  inf                 -inf %   -5 =  NaN
    #    -inf /    5 = -inf                 -inf %    5 =  NaN
    #    -inf /  inf =  NaN                 -inf %  inf =  NaN

    if ($x -> is_inf()) {
        my $rem;
        $rem = $class -> bnan() if $wantarray;
        if ($y -> is_inf()) {
            $x -> bnan();
        } else {
            my $sign = $x -> bcmp(0) == $y -> bcmp(0) ? '+' : '-';
            $x -> binf($sign);
        }
        return $wantarray ? ($x, $rem) : $x;
    }

    # Denominator (divisor) is +/-inf. The cases when the numerator is +/-inf
    # are covered above. In the modulo cases (in the right column) we return
    # the same as core Perl, which does floored division, so for consistency we
    # also do floored division in the division cases (in the left column).
    #
    #      -5 /  inf =    0                   -5 %  inf =  -5
    #       0 /  inf =    0                    0 %  inf =   0
    #       5 /  inf =    0                    5 %  inf =   5
    #
    #      -5 / -inf =    0                   -5 % -inf =  -5
    #       0 / -inf =    0                    0 % -inf =   0
    #       5 / -inf =    0                    5 % -inf =   5

    if ($y -> is_inf()) {
        my $rem;
        $rem = $x -> copy() if $wantarray;
        $x -> bzero();
        return $wantarray ? ($x, $rem) : $x;
    }

    return $upgrade -> btdiv($upgrade -> new($x), $upgrade -> new($y), @r)
      if defined $upgrade;

    $r[3] = $y;                 # no push!

    # Inialize remainder.

    my $rem = $class -> bzero();

    # Are both operands the same object, i.e., like $x -> bdiv($x)? If so,
    # flipping the sign of $y also flips the sign of $x.

    my $xsign = $x -> {sign};
    my $ysign = $y -> {sign};

    $y -> {sign} =~ tr/+-/-+/;            # Flip the sign of $y, and see ...
    my $same = $xsign ne $x -> {sign};    # ... if that changed the sign of $x.
    $y -> {sign} = $ysign;                # Re-insert the original sign.

    if ($same) {
        $x -> bone();
    } else {
        ($x -> {value}, $rem -> {value}) =
          $LIB -> _div($x -> {value}, $y -> {value});

        $x -> {sign} = $xsign eq $ysign ? '+' : '-';
        $x -> {sign} = '+' if $LIB -> _is_zero($x -> {value});
        $x -> round(@r);
    }

    if (wantarray) {
        $rem -> {sign} = $xsign;
        $rem -> {sign} = '+' if $LIB -> _is_zero($rem -> {value});
        $rem -> {_a} = $x -> {_a};
        $rem -> {_p} = $x -> {_p};
        $rem -> round(@r);
        return ($x, $rem);
    }

    return $x;
}

sub bmod {
    # This is the remainder after floored division.

    # Set up parameters.
    my ($class, $x, $y, @r) = (ref($_[0]), @_);

    # objectify is costly, so avoid it
    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
        ($class, $x, $y, @r) = objectify(2, @_);
    }

    return $x if $x -> modify('bmod');
    $r[3] = $y;                 # no push!

    # At least one argument is NaN.

    if ($x -> is_nan() || $y -> is_nan()) {
        return $x -> bnan();
    }

    # Modulo zero. See documentation for bdiv().

    if ($y -> is_zero()) {
        return $x;
    }

    # Numerator (dividend) is +/-inf.

    if ($x -> is_inf()) {
        return $x -> bnan();
    }

    # Denominator (divisor) is +/-inf.

    if ($y -> is_inf()) {
        if ($x -> is_zero() || $x -> bcmp(0) == $y -> bcmp(0)) {
            return $x;
        } else {
            return $x -> binf($y -> sign());
        }
    }

    # Calc new sign and in case $y == +/- 1, return $x.

    $x -> {value} = $LIB -> _mod($x -> {value}, $y -> {value});
    if ($LIB -> _is_zero($x -> {value})) {
        $x -> {sign} = '+';     # do not leave -0
    } else {
        $x -> {value} = $LIB -> _sub($y -> {value}, $x -> {value}, 1) # $y-$x
          if ($x -> {sign} ne $y -> {sign});
        $x -> {sign} = $y -> {sign};
    }

    $x -> round(@r);
}

sub btmod {
    # Remainder after truncated division.

    # set up parameters
    my ($class, $x, $y, @r) = (ref($_[0]), @_);

    # objectify is costly, so avoid it
    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
        ($class, $x, $y, @r) = objectify(2, @_);
    }

    return $x if $x -> modify('btmod');

    # At least one argument is NaN.

    if ($x -> is_nan() || $y -> is_nan()) {
        return $x -> bnan();
    }

    # Modulo zero. See documentation for btdiv().

    if ($y -> is_zero()) {
        return $x;
    }

    # Numerator (dividend) is +/-inf.

    if ($x -> is_inf()) {
        return $x -> bnan();
    }

    # Denominator (divisor) is +/-inf.

    if ($y -> is_inf()) {
        return $x;
    }

    return $upgrade -> btmod($upgrade -> new($x), $upgrade -> new($y), @r)
      if defined $upgrade;

    $r[3] = $y;                 # no push!

    my $xsign = $x -> {sign};

    $x -> {value} = $LIB -> _mod($x -> {value}, $y -> {value});

    $x -> {sign} = $xsign;
    $x -> {sign} = '+' if $LIB -> _is_zero($x -> {value});
    $x -> round(@r);
    return $x;
}

sub bmodinv {
    # Return modular multiplicative inverse:
    #
    #   z is the modular inverse of x (mod y) if and only if
    #
    #       x*z ≡ 1  (mod y)
    #
    # If the modulus y is larger than one, x and z are relative primes (i.e.,
    # their greatest common divisor is one).
    #
    # If no modular multiplicative inverse exists, NaN is returned.

    # set up parameters
    my ($class, $x, $y, @r) = (undef, @_);
    # objectify is costly, so avoid it
    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
        ($class, $x, $y, @r) = objectify(2, @_);
    }

    return $x if $x->modify('bmodinv');

    # Return NaN if one or both arguments is +inf, -inf, or nan.

    return $x->bnan() if ($y->{sign} !~ /^[+-]$/ ||
                          $x->{sign} !~ /^[+-]$/);

    # Return NaN if $y is zero; 1 % 0 makes no sense.

    return $x->bnan() if $y->is_zero();

    # Return 0 in the trivial case. $x % 1 or $x % -1 is zero for all finite
    # integers $x.

    return $x->bzero() if ($y->is_one() ||
                           $y->is_one('-'));

    # Return NaN if $x = 0, or $x modulo $y is zero. The only valid case when
    # $x = 0 is when $y = 1 or $y = -1, but that was covered above.
    #
    # Note that computing $x modulo $y here affects the value we'll feed to
    # $LIB->_modinv() below when $x and $y have opposite signs. E.g., if $x =
    # 5 and $y = 7, those two values are fed to _modinv(), but if $x = -5 and
    # $y = 7, the values fed to _modinv() are $x = 2 (= -5 % 7) and $y = 7.
    # The value if $x is affected only when $x and $y have opposite signs.

    $x->bmod($y);
    return $x->bnan() if $x->is_zero();

    # Compute the modular multiplicative inverse of the absolute values. We'll
    # correct for the signs of $x and $y later. Return NaN if no GCD is found.

    ($x->{value}, $x->{sign}) = $LIB->_modinv($x->{value}, $y->{value});
    return $x->bnan() if !defined $x->{value};

    # Library inconsistency workaround: _modinv() in Math::BigInt::GMP versions
    # <= 1.32 return undef rather than a "+" for the sign.

    $x->{sign} = '+' unless defined $x->{sign};

    # When one or both arguments are negative, we have the following
    # relations.  If x and y are positive:
    #
    #   modinv(-x, -y) = -modinv(x, y)
    #   modinv(-x, y) = y - modinv(x, y)  = -modinv(x, y) (mod y)
    #   modinv( x, -y) = modinv(x, y) - y  =  modinv(x, y) (mod -y)

    # We must swap the sign of the result if the original $x is negative.
    # However, we must compensate for ignoring the signs when computing the
    # inverse modulo. The net effect is that we must swap the sign of the
    # result if $y is negative.

    $x -> bneg() if $y->{sign} eq '-';

    # Compute $x modulo $y again after correcting the sign.

    $x -> bmod($y) if $x->{sign} ne $y->{sign};

    return $x;
}

sub bmodpow {
    # Modular exponentiation. Raises a very large number to a very large exponent
    # in a given very large modulus quickly, thanks to binary exponentiation.
    # Supports negative exponents.
    my ($class, $num, $exp, $mod, @r) = objectify(3, @_);

    return $num if $num->modify('bmodpow');

    # When the exponent 'e' is negative, use the following relation, which is
    # based on finding the multiplicative inverse 'd' of 'b' modulo 'm':
    #
    #    b^(-e) (mod m) = d^e (mod m) where b*d = 1 (mod m)

    $num->bmodinv($mod) if ($exp->{sign} eq '-');

    # Check for valid input. All operands must be finite, and the modulus must be
    # non-zero.

    return $num->bnan() if ($num->{sign} =~ /NaN|inf/ || # NaN, -inf, +inf
                            $exp->{sign} =~ /NaN|inf/ || # NaN, -inf, +inf
                            $mod->{sign} =~ /NaN|inf/);  # NaN, -inf, +inf

    # Modulo zero. See documentation for Math::BigInt's bmod() method.

    if ($mod -> is_zero()) {
        if ($num -> is_zero()) {
            return $class -> bnan();
        } else {
            return $num -> copy();
        }
    }

    # Compute 'a (mod m)', ignoring the signs on 'a' and 'm'. If the resulting
    # value is zero, the output is also zero, regardless of the signs on 'a' and
    # 'm'.

    my $value = $LIB->_modpow($num->{value}, $exp->{value}, $mod->{value});
    my $sign  = '+';

    # If the resulting value is non-zero, we have four special cases, depending
    # on the signs on 'a' and 'm'.

    unless ($LIB->_is_zero($value)) {

        # There is a negative sign on 'a' (= $num**$exp) only if the number we
        # are exponentiating ($num) is negative and the exponent ($exp) is odd.

        if ($num->{sign} eq '-' && $exp->is_odd()) {

            # When both the number 'a' and the modulus 'm' have a negative sign,
            # use this relation:
            #
            #    -a (mod -m) = -(a (mod m))

            if ($mod->{sign} eq '-') {
                $sign = '-';
            }

            # When only the number 'a' has a negative sign, use this relation:
            #
            #    -a (mod m) = m - (a (mod m))

            else {
                # Use copy of $mod since _sub() modifies the first argument.
                my $mod = $LIB->_copy($mod->{value});
                $value = $LIB->_sub($mod, $value);
                $sign  = '+';
            }

        } else {

            # When only the modulus 'm' has a negative sign, use this relation:
            #
            #    a (mod -m) = (a (mod m)) - m
            #               = -(m - (a (mod m)))

            if ($mod->{sign} eq '-') {
                # Use copy of $mod since _sub() modifies the first argument.
                my $mod = $LIB->_copy($mod->{value});
                $value = $LIB->_sub($mod, $value);
                $sign  = '-';
            }

            # When neither the number 'a' nor the modulus 'm' have a negative
            # sign, directly return the already computed value.
            #
            #    (a (mod m))

        }

    }

    $num->{value} = $value;
    $num->{sign}  = $sign;

    return $num -> round(@r);
}

sub bpow {
    # (BINT or num_str, BINT or num_str) return BINT
    # compute power of two numbers -- stolen from Knuth Vol 2 pg 233
    # modifies first argument

    # set up parameters
    my ($class, $x, $y, @r) = (ref($_[0]), @_);
    # objectify is costly, so avoid it
    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
        ($class, $x, $y, @r) = objectify(2, @_);
    }

    return $x if $x -> modify('bpow');

    # $x and/or $y is a NaN
    return $x -> bnan() if $x -> is_nan() || $y -> is_nan();

    # $x and/or $y is a +/-Inf
    if ($x -> is_inf("-")) {
        return $x -> bzero()   if $y -> is_negative();
        return $x -> bnan()    if $y -> is_zero();
        return $x            if $y -> is_odd();
        return $x -> bneg();
    } elsif ($x -> is_inf("+")) {
        return $x -> bzero()   if $y -> is_negative();
        return $x -> bnan()    if $y -> is_zero();
        return $x;
    } elsif ($y -> is_inf("-")) {
        return $x -> bnan()    if $x -> is_one("-");
        return $x -> binf("+") if $x -> is_zero();
        return $x -> bone()    if $x -> is_one("+");
        return $x -> bzero();
    } elsif ($y -> is_inf("+")) {
        return $x -> bnan()    if $x -> is_one("-");
        return $x -> bzero()   if $x -> is_zero();
        return $x -> bone()    if $x -> is_one("+");
        return $x -> binf("+");
    }

    if ($x -> is_zero()) {
        return $x -> bone() if $y -> is_zero();
        return $x -> binf() if $y -> is_negative();
        return $x;
    }

    if ($x -> is_one("+")) {
        return $x;
    }

    if ($x -> is_one("-")) {
        return $x if $y -> is_odd();
        return $x -> bneg();
    }

    # We don't support finite non-integers, so upgrade or return zero. The
    # reason for returning zero, not NaN, is that all output is in the open
    # interval (0,1), and truncating that to integer gives zero.

    if ($y->{sign} eq '-' || !$y -> isa($class)) {
        return $upgrade -> bpow($upgrade -> new($x), $y, @r)
          if defined $upgrade;
        return $x -> bzero();
    }

    $r[3] = $y;                 # no push!

    $x->{value} = $LIB -> _pow($x->{value}, $y->{value});
    $x->{sign}  = $x -> is_negative() && $y -> is_odd() ? '-' : '+';
    $x -> round(@r);
}

sub blog {
    # Return the logarithm of the operand. If a second operand is defined, that
    # value is used as the base, otherwise the base is assumed to be Euler's
    # constant.

    my ($class, $x, $base, @r);

    # Don't objectify the base, since an undefined base, as in $x->blog() or
    # $x->blog(undef) signals that the base is Euler's number.

    if (!ref($_[0]) && $_[0] =~ /^[A-Za-z]|::/) {
        # E.g., Math::BigInt->blog(256, 2)
        ($class, $x, $base, @r) =
          defined $_[2] ? objectify(2, @_) : objectify(1, @_);
    } else {
        # E.g., Math::BigInt::blog(256, 2) or $x->blog(2)
        ($class, $x, $base, @r) =
          defined $_[1] ? objectify(2, @_) : objectify(1, @_);
    }

    return $x if $x->modify('blog');

    # Handle all exception cases and all trivial cases. I have used Wolfram
    # Alpha (http://www.wolframalpha.com) as the reference for these cases.

    return $x -> bnan() if $x -> is_nan();

    if (defined $base) {
        $base = $class -> new($base) unless ref $base;
        if ($base -> is_nan() || $base -> is_one()) {
            return $x -> bnan();
        } elsif ($base -> is_inf() || $base -> is_zero()) {
            return $x -> bnan() if $x -> is_inf() || $x -> is_zero();
            return $x -> bzero();
        } elsif ($base -> is_negative()) {        # -inf < base < 0
            return $x -> bzero() if $x -> is_one(); #     x = 1
            return $x -> bone()  if $x == $base;    #     x = base
            return $x -> bnan();                    #     otherwise
        }
        return $x -> bone() if $x == $base; # 0 < base && 0 < x < inf
    }

    # We now know that the base is either undefined or >= 2 and finite.

    return $x -> binf('+') if $x -> is_inf(); #   x = +/-inf
    return $x -> bnan()    if $x -> is_neg(); #   -inf < x < 0
    return $x -> bzero()   if $x -> is_one(); #   x = 1
    return $x -> binf('-') if $x -> is_zero(); #   x = 0

    # At this point we are done handling all exception cases and trivial cases.

    return $upgrade -> blog($upgrade -> new($x), $base, @r) if defined $upgrade;

    # fix for bug #24969:
    # the default base is e (Euler's number) which is not an integer
    if (!defined $base) {
        require Math::BigFloat;
        my $u = Math::BigFloat->blog(Math::BigFloat->new($x))->as_int();
        # modify $x in place
        $x->{value} = $u->{value};
        $x->{sign} = $u->{sign};
        return $x;
    }

    my ($rc) = $LIB->_log_int($x->{value}, $base->{value});
    return $x->bnan() unless defined $rc; # not possible to take log?
    $x->{value} = $rc;
    $x->round(@r);
}

sub bexp {
    # Calculate e ** $x (Euler's number to the power of X), truncated to
    # an integer value.
    my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
    return $x if $x->modify('bexp');

    # inf, -inf, NaN, <0 => NaN
    return $x->bnan() if $x->{sign} eq 'NaN';
    return $x->bone() if $x->is_zero();
    return $x if $x->{sign} eq '+inf';
    return $x->bzero() if $x->{sign} eq '-inf';

    my $u;
    {
        # run through Math::BigFloat unless told otherwise
        require Math::BigFloat unless defined $upgrade;
        local $upgrade = 'Math::BigFloat' unless defined $upgrade;
        # calculate result, truncate it to integer
        $u = $upgrade->bexp($upgrade->new($x), @r);
    }

    if (defined $upgrade) {
        $x = $u;
    } else {
        $u = $u->as_int();
        # modify $x in place
        $x->{value} = $u->{value};
        $x->round(@r);
    }
}

sub bnok {
    # Calculate n over k (binomial coefficient or "choose" function) as
    # integer.

    # Set up parameters.
    my ($self, $n, $k, @r) = (ref($_[0]), @_);

    # Objectify is costly, so avoid it.
    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
        ($self, $n, $k, @r) = objectify(2, @_);
    }

    return $n if $n->modify('bnok');

    # All cases where at least one argument is NaN.

    return $n->bnan() if $n->{sign} eq 'NaN' || $k->{sign} eq 'NaN';

    # All cases where at least one argument is +/-inf.

    if ($n -> is_inf()) {
        if ($k -> is_inf()) {                   # bnok(+/-inf,+/-inf)
            return $n -> bnan();
        } elsif ($k -> is_neg()) {              # bnok(+/-inf,k), k < 0
            return $n -> bzero();
        } elsif ($k -> is_zero()) {             # bnok(+/-inf,k), k = 0
            return $n -> bone();
        } else {
            if ($n -> is_inf("+")) {            # bnok(+inf,k), 0 < k < +inf
                return $n -> binf("+");
            } else {                            # bnok(-inf,k), k > 0
                my $sign = $k -> is_even() ? "+" : "-";
                return $n -> binf($sign);
            }
        }
    }

    elsif ($k -> is_inf()) {            # bnok(n,+/-inf), -inf <= n <= inf
        return $n -> bnan();
    }

    # At this point, both n and k are real numbers.

    my $sign = 1;

    if ($n >= 0) {
        if ($k < 0 || $k > $n) {
            return $n -> bzero();
        }
    } else {

        if ($k >= 0) {

            # n < 0 and k >= 0: bnok(n,k) = (-1)^k * bnok(-n+k-1,k)

            $sign = (-1) ** $k;
            $n -> bneg() -> badd($k) -> bdec();

        } elsif ($k <= $n) {

            # n < 0 and k <= n: bnok(n,k) = (-1)^(n-k) * bnok(-k-1,n-k)

            $sign = (-1) ** ($n - $k);
            my $x0 = $n -> copy();
            $n -> bone() -> badd($k) -> bneg();
            $k = $k -> copy();
            $k -> bneg() -> badd($x0);

        } else {

            # n < 0 and n < k < 0:

            return $n -> bzero();
        }
    }

    $n->{value} = $LIB->_nok($n->{value}, $k->{value});
    $n -> bneg() if $sign == -1;

    $n->round(@r);
}

sub buparrow {
    my $a = shift;
    my $y = $a -> uparrow(@_);
    $a -> {value} = $y -> {value};
    return $a;
}

sub uparrow {
    # Knuth's up-arrow notation buparrow(a, n, b)
    #
    # The following is a simple, recursive implementation of the up-arrow
    # notation, just to show the idea. Such implementations cause "Deep
    # recursion on subroutine ..." warnings, so we use a faster, non-recursive
    # algorithm below with @_ as a stack.
    #
    #   sub buparrow {
    #       my ($a, $n, $b) = @_;
    #       return $a ** $b if $n == 1;
    #       return $a * $b  if $n == 0;
    #       return 1        if $b == 0;
    #       return buparrow($a, $n - 1, buparrow($a, $n, $b - 1));
    #   }

    my ($a, $b, $n) = @_;
    my $class = ref $a;
    croak("a must be non-negative") if $a < 0;
    croak("n must be non-negative") if $n < 0;
    croak("b must be non-negative") if $b < 0;

    while (@_ >= 3) {

        # return $a ** $b if $n == 1;

        if ($_[-2] == 1) {
            my ($a, $n, $b) = splice @_, -3;
            push @_, $a ** $b;
            next;
        }

        # return $a * $b if $n == 0;

        if ($_[-2] == 0) {
            my ($a, $n, $b) = splice @_, -3;
            push @_, $a * $b;
            next;
        }

        # return 1 if $b == 0;

        if ($_[-1] == 0) {
            splice @_, -3;
            push @_, $class -> bone();
            next;
        }

        # return buparrow($a, $n - 1, buparrow($a, $n, $b - 1));

        my ($a, $n, $b) = splice @_, -3;
        push @_, ($a, $n - 1,
                      $a, $n, $b - 1);

    }

    pop @_;
}

sub backermann {
    my $m = shift;
    my $y = $m -> ackermann(@_);
    $m -> {value} = $y -> {value};
    return $m;
}

sub ackermann {
    # Ackermann's function ackermann(m, n)
    #
    # The following is a simple, recursive implementation of the ackermann
    # function, just to show the idea. Such implementations cause "Deep
    # recursion on subroutine ..." warnings, so we use a faster, non-recursive
    # algorithm below with @_ as a stack.
    #
    # sub ackermann {
    #     my ($m, $n) = @_;
    #     return $n + 1                                  if $m == 0;
    #     return ackermann($m - 1, 1)                    if $m > 0 && $n == 0;
    #     return ackermann($m - 1, ackermann($m, $n - 1) if $m > 0 && $n > 0;
    # }

    my ($m, $n) = @_;
    my $class = ref $m;
    croak("m must be non-negative") if $m < 0;
    croak("n must be non-negative") if $n < 0;

    my $two      = $class -> new("2");
    my $three    = $class -> new("3");
    my $thirteen = $class -> new("13");

    $n = pop;
    $n = $class -> new($n) unless ref($n);
    while (@_) {
        my $m = pop;
        if ($m > $three) {
            push @_, (--$m) x $n;
            while (--$m >= $three) {
                push @_, $m;
            }
            $n = $thirteen;
        } elsif ($m == $three) {
            $n = $class -> bone() -> blsft($n + $three) -> bsub($three);
        } elsif ($m == $two) {
            $n -> bmul($two) -> badd($three);
        } elsif ($m >= 0) {
            $n -> badd($m) -> binc();
        } else {
            die "negative m!";
        }
    }
    $n;
}

sub bsin {
    # Calculate sinus(x) to N digits. Unless upgrading is in effect, returns the
    # result truncated to an integer.
    my ($class, $x, @r) = ref($_[0]) ? (undef, @_) : objectify(1, @_);

    return $x if $x->modify('bsin');

    return $x->bnan() if $x->{sign} !~ /^[+-]\z/; # -inf +inf or NaN => NaN

    return $upgrade -> bsin($upgrade -> new($x, @r)) if defined $upgrade;

    require Math::BigFloat;
    # calculate the result and truncate it to integer
    my $t = Math::BigFloat->new($x)->bsin(@r)->as_int();

    $x->bone() if $t->is_one();
    $x->bzero() if $t->is_zero();
    $x->round(@r);
}

sub bcos {
    # Calculate cosinus(x) to N digits. Unless upgrading is in effect, returns the
    # result truncated to an integer.
    my ($class, $x, @r) = ref($_[0]) ? (undef, @_) : objectify(1, @_);

    return $x if $x->modify('bcos');

    return $x->bnan() if $x->{sign} !~ /^[+-]\z/; # -inf +inf or NaN => NaN

    return $upgrade -> bcos($upgrade -> new($x), @r) if defined $upgrade;

    require Math::BigFloat;
    # calculate the result and truncate it to integer
    my $t = Math::BigFloat -> bcos(Math::BigFloat -> new($x), @r) -> as_int();

    $x->bone() if $t->is_one();
    $x->bzero() if $t->is_zero();
    $x->round(@r);
}

sub batan {
    # Calculate arcus tangens of x to N digits. Unless upgrading is in effect, returns the
    # result truncated to an integer.
    my ($class, $x, @r) = ref($_[0]) ? (undef, @_) : objectify(1, @_);

    return $x if $x->modify('batan');

    return $x->bnan() if $x->{sign} !~ /^[+-]\z/; # -inf +inf or NaN => NaN

    return $upgrade->new($x)->batan(@r) if defined $upgrade;

    # calculate the result and truncate it to integer
    my $tmp = Math::BigFloat->new($x)->batan(@r);

    $x->{value} = $LIB->_new($tmp->as_int()->bstr());
    $x->round(@r);
}

sub batan2 {
    # calculate arcus tangens of ($y/$x)

    # set up parameters
    my ($class, $y, $x, @r) = (ref($_[0]), @_);
    # objectify is costly, so avoid it
    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
        ($class, $y, $x, @r) = objectify(2, @_);
    }

    return $y if $y->modify('batan2');

    return $y->bnan() if ($y->{sign} eq $nan) || ($x->{sign} eq $nan);

    # Y    X
    # != 0 -inf result is +- pi
    if ($x->is_inf() || $y->is_inf()) {
        # upgrade to Math::BigFloat etc.
        return $upgrade->new($y)->batan2($upgrade->new($x), @r) if defined $upgrade;
        if ($y->is_inf()) {
            if ($x->{sign} eq '-inf') {
                # calculate 3 pi/4 => 2.3.. => 2
                $y->bone(substr($y->{sign}, 0, 1));
                $y->bmul($class->new(2));
            } elsif ($x->{sign} eq '+inf') {
                # calculate pi/4 => 0.7 => 0
                $y->bzero();
            } else {
                # calculate pi/2 => 1.5 => 1
                $y->bone(substr($y->{sign}, 0, 1));
            }
        } else {
            if ($x->{sign} eq '+inf') {
                # calculate pi/4 => 0.7 => 0
                $y->bzero();
            } else {
                # PI => 3.1415.. => 3
                $y->bone(substr($y->{sign}, 0, 1));
                $y->bmul($class->new(3));
            }
        }
        return $y;
    }

    return $upgrade->new($y)->batan2($upgrade->new($x), @r) if defined $upgrade;

    require Math::BigFloat;
    my $r = Math::BigFloat->new($y)
      ->batan2(Math::BigFloat->new($x), @r)
        ->as_int();

    $x->{value} = $r->{value};
    $x->{sign} = $r->{sign};

    $x;
}

sub bsqrt {
    # calculate square root of $x
    my ($class, $x, @r) = ref($_[0]) ? (undef, @_) : objectify(1, @_);

    return $x if $x->modify('bsqrt');

    return $x->bnan() if $x->{sign} !~ /^\+/; # -x or -inf or NaN => NaN
    return $x if $x->{sign} eq '+inf';        # sqrt(+inf) == inf

    return $upgrade->bsqrt($x, @r) if defined $upgrade;

    $x->{value} = $LIB->_sqrt($x->{value});
    $x->round(@r);
}

sub broot {
    # calculate $y'th root of $x

    # set up parameters
    my ($class, $x, $y, @r) = (ref($_[0]), @_);

    $y = $class->new(2) unless defined $y;

    # objectify is costly, so avoid it
    if ((!ref($x)) || (ref($x) ne ref($y))) {
        ($class, $x, $y, @r) = objectify(2, $class || $class, @_);
    }

    return $x if $x->modify('broot');

    # NaN handling: $x ** 1/0, x or y NaN, or y inf/-inf or y == 0
    return $x->bnan() if $x->{sign} !~ /^\+/ || $y->is_zero() ||
      $y->{sign} !~ /^\+$/;

    return $x->round(@r)
      if $x->is_zero() || $x->is_one() || $x->is_inf() || $y->is_one();

    return $upgrade->new($x)->broot($upgrade->new($y), @r) if defined $upgrade;

    $x->{value} = $LIB->_root($x->{value}, $y->{value});
    $x->round(@r);
}

sub bfac {
    # (BINT or num_str, BINT or num_str) return BINT
    # compute factorial number from $x, modify $x in place
    my ($class, $x, @r) = ref($_[0]) ? (undef, @_) : objectify(1, @_);

    return $x if $x->modify('bfac') || $x->{sign} eq '+inf'; # inf => inf
    return $x->bnan() if $x->{sign} ne '+'; # NaN, <0 => NaN

    $x->{value} = $LIB->_fac($x->{value});
    $x->round(@r);
}

sub bdfac {
    # compute double factorial, modify $x in place
    my ($class, $x, @r) = ref($_[0]) ? (undef, @_) : objectify(1, @_);

    return $x if $x->modify('bdfac') || $x->{sign} eq '+inf'; # inf => inf
    return $x->bnan() if $x->is_nan() || $x <= -2;
    return $x->bone() if $x <= 1;

    croak("bdfac() requires a newer version of the $LIB library.")
        unless $LIB->can('_dfac');

    $x->{value} = $LIB->_dfac($x->{value});
    $x->round(@r);
}

sub btfac {
    # compute triple factorial, modify $x in place
    my ($class, $x, @r) = objectify(1, @_);

    return $x if $x->modify('btfac') || $x->{sign} eq '+inf'; # inf => inf

    return $x->bnan() if $x->is_nan();

    my $k = $class -> new("3");
    return $x->bnan() if $x <= -$k;

    my $one = $class -> bone();
    return $x->bone() if $x <= $one;

    my $f = $x -> copy();
    while ($f -> bsub($k) > $one) {
        $x -> bmul($f);
    }
    $x->round(@r);
}

sub bmfac {
    # compute multi-factorial
    my ($class, $x, $k, @r) = objectify(2, @_);

    return $x if $x->modify('bmfac') || $x->{sign} eq '+inf';
    return $x->bnan() if $x->is_nan() || $k->is_nan() || $k < 1 || $x <= -$k;

    my $one = $class -> bone();
    return $x->bone() if $x <= $one;

    my $f = $x -> copy();
    while ($f -> bsub($k) > $one) {
        $x -> bmul($f);
    }
    $x->round(@r);
}

sub bfib {
    # compute Fibonacci number(s)
    my ($class, $x, @r) = objectify(1, @_);

    croak("bfib() requires a newer version of the $LIB library.")
        unless $LIB->can('_fib');

    return $x if $x->modify('bfib');

    # List context.

    if (wantarray) {
        return () if $x ->  is_nan();
        croak("bfib() can't return an infinitely long list of numbers")
            if $x -> is_inf();

        # Use the backend library to compute the first $x Fibonacci numbers.

        my @values = $LIB->_fib($x->{value});

        # Make objects out of them. The last element in the array is the
        # invocand.

        for (my $i = 0 ; $i < $#values ; ++ $i) {
            my $fib =  $class -> bzero();
            $fib -> {value} = $values[$i];
            $values[$i] = $fib;
        }

        $x -> {value} = $values[-1];
        $values[-1] = $x;

        # If negative, insert sign as appropriate.

        if ($x -> is_neg()) {
            for (my $i = 2 ; $i <= $#values ; $i += 2) {
                $values[$i]{sign} = '-';
            }
        }

        @values = map { $_ -> round(@r) } @values;
        return @values;
    }

    # Scalar context.

    else {
        return $x if $x->modify('bdfac') || $x ->  is_inf('+');
        return $x->bnan() if $x -> is_nan() || $x -> is_inf('-');

        $x->{sign}  = $x -> is_neg() && $x -> is_even() ? '-' : '+';
        $x->{value} = $LIB->_fib($x->{value});
        return $x->round(@r);
    }
}

sub blucas {
    # compute Lucas number(s)
    my ($class, $x, @r) = objectify(1, @_);

    croak("blucas() requires a newer version of the $LIB library.")
        unless $LIB->can('_lucas');

    return $x if $x->modify('blucas');

    # List context.

    if (wantarray) {
        return () if $x -> is_nan();
        croak("blucas() can't return an infinitely long list of numbers")
            if $x -> is_inf();

        # Use the backend library to compute the first $x Lucas numbers.

        my @values = $LIB->_lucas($x->{value});

        # Make objects out of them. The last element in the array is the
        # invocand.

        for (my $i = 0 ; $i < $#values ; ++ $i) {
            my $lucas =  $class -> bzero();
            $lucas -> {value} = $values[$i];
            $values[$i] = $lucas;
        }

        $x -> {value} = $values[-1];
        $values[-1] = $x;

        # If negative, insert sign as appropriate.

        if ($x -> is_neg()) {
            for (my $i = 2 ; $i <= $#values ; $i += 2) {
                $values[$i]{sign} = '-';
            }
        }

        @values = map { $_ -> round(@r) } @values;
        return @values;
    }

    # Scalar context.

    else {
        return $x if $x ->  is_inf('+');
        return $x->bnan() if $x -> is_nan() || $x -> is_inf('-');

        $x->{sign}  = $x -> is_neg() && $x -> is_even() ? '-' : '+';
        $x->{value} = $LIB->_lucas($x->{value});
        return $x->round(@r);
    }
}

sub blsft {
    # (BINT or num_str, BINT or num_str) return BINT
    # compute x << y, base n, y >= 0

    my ($class, $x, $y, $b, @r);

    # Objectify the base only when it is defined, since an undefined base, as
    # in $x->blsft(3) or $x->blog(3, undef) means use the default base 2.

    if (!ref($_[0]) && $_[0] =~ /^[A-Za-z]|::/) {
        # E.g., Math::BigInt->blog(256, 5, 2)
        ($class, $x, $y, $b, @r) =
          defined $_[3] ? objectify(3, @_) : objectify(2, @_);
    } else {
        # E.g., Math::BigInt::blog(256, 5, 2) or $x->blog(5, 2)
        ($class, $x, $y, $b, @r) =
          defined $_[2] ? objectify(3, @_) : objectify(2, @_);
    }

    return $x if $x -> modify('blsft');
    return $x -> bnan() if ($x -> {sign} !~ /^[+-]$/ ||
                            $y -> {sign} !~ /^[+-]$/);
    return $x -> round(@r) if $y -> is_zero();

    $b = defined($b) ? $b -> numify() : 2;

    # While some of the libraries support an arbitrarily large base, not all of
    # them do, so rather than returning an incorrect result in those cases,
    # disallow bases that don't work with all libraries.

    my $uintmax = ~0;
    croak("Base is too large.") if $b > $uintmax;

    return $x -> bnan() if $b <= 0 || $y -> {sign} eq '-';

    $x -> {value} = $LIB -> _lsft($x -> {value}, $y -> {value}, $b);
    $x -> round(@r);
}

sub brsft {
    # (BINT or num_str, BINT or num_str) return BINT
    # compute x >> y, base n, y >= 0

    # set up parameters
    my ($class, $x, $y, $b, @r) = (ref($_[0]), @_);

    # objectify is costly, so avoid it
    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
        ($class, $x, $y, $b, @r) = objectify(2, @_);
    }

    return $x if $x -> modify('brsft');
    return $x -> bnan() if ($x -> {sign} !~ /^[+-]$/ || $y -> {sign} !~ /^[+-]$/);
    return $x -> round(@r) if $y -> is_zero();
    return $x -> bzero(@r) if $x -> is_zero(); # 0 => 0

    $b = 2 if !defined $b;
    return $x -> bnan() if $b <= 0 || $y -> {sign} eq '-';

    # this only works for negative numbers when shifting in base 2
    if (($x -> {sign} eq '-') && ($b == 2)) {
        return $x -> round(@r) if $x -> is_one('-'); # -1 => -1
        if (!$y -> is_one()) {
            # although this is O(N*N) in calc (as_bin!) it is O(N) in Pari et
            # al but perhaps there is a better emulation for two's complement
            # shift...
            # if $y != 1, we must simulate it by doing:
            # convert to bin, flip all bits, shift, and be done
            $x -> binc();           # -3 => -2
            my $bin = $x -> as_bin();
            $bin =~ s/^-0b//;       # strip '-0b' prefix
            $bin =~ tr/10/01/;      # flip bits
            # now shift
            if ($y >= CORE::length($bin)) {
                $bin = '0';         # shifting to far right creates -1
                                    # 0, because later increment makes
                                    # that 1, attached '-' makes it '-1'
                                    # because -1 >> x == -1 !
            } else {
                $bin =~ s/.{$y}$//; # cut off at the right side
                $bin = '1' . $bin;  # extend left side by one dummy '1'
                $bin =~ tr/10/01/;  # flip bits back
            }
            my $res = $class -> new('0b' . $bin); # add prefix and convert back
            $res -> binc();                       # remember to increment
            $x -> {value} = $res -> {value};      # take over value
            return $x -> round(@r); # we are done now, magic, isn't?
        }

        # x < 0, n == 2, y == 1
        $x -> bdec();           # n == 2, but $y == 1: this fixes it
    }

    $x -> {value} = $LIB -> _rsft($x -> {value}, $y -> {value}, $b);
    $x -> round(@r);
}

###############################################################################
# Bitwise methods
###############################################################################

sub band {
    #(BINT or num_str, BINT or num_str) return BINT
    # compute x & y

    # set up parameters
    my ($class, $x, $y, @r) = (ref($_[0]), @_);
    # objectify is costly, so avoid it
    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
        ($class, $x, $y, @r) = objectify(2, @_);
    }

    return $x if $x->modify('band');

    $r[3] = $y;                 # no push!

    return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);

    if ($x->{sign} eq '+' && $y->{sign} eq '+') {
        $x->{value} = $LIB->_and($x->{value}, $y->{value});
    } else {
        ($x->{value}, $x->{sign}) = $LIB->_sand($x->{value}, $x->{sign},
                                                $y->{value}, $y->{sign});
    }
    return $x->round(@r);
}

sub bior {
    #(BINT or num_str, BINT or num_str) return BINT
    # compute x | y

    # set up parameters
    my ($class, $x, $y, @r) = (ref($_[0]), @_);
    # objectify is costly, so avoid it
    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
        ($class, $x, $y, @r) = objectify(2, @_);
    }

    return $x if $x->modify('bior');

    $r[3] = $y;                 # no push!

    return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);

    if ($x->{sign} eq '+' && $y->{sign} eq '+') {
        $x->{value} = $LIB->_or($x->{value}, $y->{value});
    } else {
        ($x->{value}, $x->{sign}) = $LIB->_sor($x->{value}, $x->{sign},
                                               $y->{value}, $y->{sign});
    }
    return $x->round(@r);
}

sub bxor {
    #(BINT or num_str, BINT or num_str) return BINT
    # compute x ^ y

    # set up parameters
    my ($class, $x, $y, @r) = (ref($_[0]), @_);
    # objectify is costly, so avoid it
    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
        ($class, $x, $y, @r) = objectify(2, @_);
    }

    return $x if $x->modify('bxor');

    $r[3] = $y;                 # no push!

    return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);

    if ($x->{sign} eq '+' && $y->{sign} eq '+') {
        $x->{value} = $LIB->_xor($x->{value}, $y->{value});
    } else {
        ($x->{value}, $x->{sign}) = $LIB->_sxor($x->{value}, $x->{sign},
                                               $y->{value}, $y->{sign});
    }
    return $x->round(@r);
}

sub bnot {
    # (num_str or BINT) return BINT
    # represent ~x as twos-complement number
    # we don't need $class, so undef instead of ref($_[0]) make it slightly faster
    my ($class, $x) = ref($_[0]) ? (undef, @_) : objectify(1, @_);

    return $x if $x->modify('bnot');
    $x->binc()->bneg();         # binc already does round
}

###############################################################################
# Rounding methods
###############################################################################

sub round {
    # Round $self according to given parameters, or given second argument's
    # parameters or global defaults

    # for speed reasons, _find_round_parameters is embedded here:

    my ($self, $a, $p, $r, @args) = @_;
    # $a accuracy, if given by caller
    # $p precision, if given by caller
    # $r round_mode, if given by caller
    # @args all 'other' arguments (0 for unary, 1 for binary ops)

    my $class = ref($self);       # find out class of argument(s)
    no strict 'refs';

    # now pick $a or $p, but only if we have got "arguments"
    if (!defined $a) {
        foreach ($self, @args) {
            # take the defined one, or if both defined, the one that is smaller
            $a = $_->{_a} if (defined $_->{_a}) && (!defined $a || $_->{_a} < $a);
        }
    }
    if (!defined $p) {
        # even if $a is defined, take $p, to signal error for both defined
        foreach ($self, @args) {
            # take the defined one, or if both defined, the one that is bigger
            # -2 > -3, and 3 > 2
            $p = $_->{_p} if (defined $_->{_p}) && (!defined $p || $_->{_p} > $p);
        }
    }

    # if still none defined, use globals
    unless (defined $a || defined $p) {
        $a = ${"$class\::accuracy"};
        $p = ${"$class\::precision"};
    }

    # A == 0 is useless, so undef it to signal no rounding
    $a = undef if defined $a && $a == 0;

    # no rounding today?
    return $self unless defined $a || defined $p; # early out

    # set A and set P is an fatal error
    return $self->bnan() if defined $a && defined $p;

    $r = ${"$class\::round_mode"} unless defined $r;
    if ($r !~ /^(even|odd|[+-]inf|zero|trunc|common)$/) {
        croak("Unknown round mode '$r'");
    }

    # now round, by calling either bround or bfround:
    if (defined $a) {
        $self->bround(int($a), $r) if !defined $self->{_a} || $self->{_a} >= $a;
    } else {                  # both can't be undefined due to early out
        $self->bfround(int($p), $r) if !defined $self->{_p} || $self->{_p} <= $p;
    }

    # bround() or bfround() already called bnorm() if nec.
    $self;
}

sub bround {
    # accuracy: +$n preserve $n digits from left,
    #           -$n preserve $n digits from right (f.i. for 0.1234 style in MBF)
    # no-op for $n == 0
    # and overwrite the rest with 0's, return normalized number
    # do not return $x->bnorm(), but $x

    my $x = shift;
    $x = __PACKAGE__->new($x) unless ref $x;
    my ($scale, $mode) = $x->_scale_a(@_);
    return $x if !defined $scale || $x->modify('bround'); # no-op

    if ($x->is_zero() || $scale == 0) {
        $x->{_a} = $scale if !defined $x->{_a} || $x->{_a} > $scale; # 3 > 2
        return $x;
    }
    return $x if $x->{sign} !~ /^[+-]$/; # inf, NaN

    # we have fewer digits than we want to scale to
    my $len = $x->length();
    # convert $scale to a scalar in case it is an object (put's a limit on the
    # number length, but this would already limited by memory constraints), makes
    # it faster
    $scale = $scale->numify() if ref ($scale);

    # scale < 0, but > -len (not >=!)
    if (($scale < 0 && $scale < -$len-1) || ($scale >= $len)) {
        $x->{_a} = $scale if !defined $x->{_a} || $x->{_a} > $scale; # 3 > 2
        return $x;
    }

    # count of 0's to pad, from left (+) or right (-): 9 - +6 => 3, or |-6| => 6
    my ($pad, $digit_round, $digit_after);
    $pad = $len - $scale;
    $pad = abs($scale-1) if $scale < 0;

    # do not use digit(), it is very costly for binary => decimal
    # getting the entire string is also costly, but we need to do it only once
    my $xs = $LIB->_str($x->{value});
    my $pl = -$pad-1;

    # pad:   123: 0 => -1, at 1 => -2, at 2 => -3, at 3 => -4
    # pad+1: 123: 0 => 0, at 1 => -1, at 2 => -2, at 3 => -3
    $digit_round = '0';
    $digit_round = substr($xs, $pl, 1) if $pad <= $len;
    $pl++;
    $pl ++ if $pad >= $len;
    $digit_after = '0';
    $digit_after = substr($xs, $pl, 1) if $pad > 0;

    # in case of 01234 we round down, for 6789 up, and only in case 5 we look
    # closer at the remaining digits of the original $x, remember decision
    my $round_up = 1;           # default round up
    $round_up -- if
      ($mode eq 'trunc')                      ||   # trunc by round down
        ($digit_after =~ /[01234]/)           ||   # round down anyway,
          # 6789 => round up
          ($digit_after eq '5')               &&   # not 5000...0000
            ($x->_scan_for_nonzero($pad, $xs, $len) == 0)   &&
              (
               ($mode eq 'even') && ($digit_round =~ /[24680]/) ||
               ($mode eq 'odd')  && ($digit_round =~ /[13579]/) ||
               ($mode eq '+inf') && ($x->{sign} eq '-')         ||
               ($mode eq '-inf') && ($x->{sign} eq '+')         ||
               ($mode eq 'zero') # round down if zero, sign adjusted below
              );
    my $put_back = 0;           # not yet modified

    if (($pad > 0) && ($pad <= $len)) {
        substr($xs, -$pad, $pad) = '0' x $pad; # replace with '00...'
        $xs =~ s/^0+(\d)/$1/;                  # "00000" -> "0"
        $put_back = 1;                         # need to put back
    } elsif ($pad > $len) {
        $x->bzero();            # round to '0'
    }

    if ($round_up) {            # what gave test above?
        $put_back = 1;                               # need to put back
        $pad = $len, $xs = '0' x $pad if $scale < 0; # tlr: whack 0.51=>1.0

        # we modify directly the string variant instead of creating a number and
        # adding it, since that is faster (we already have the string)
        my $c = 0;
        $pad ++;                # for $pad == $len case
        while ($pad <= $len) {
            $c = substr($xs, -$pad, 1) + 1;
            $c = '0' if $c eq '10';
            substr($xs, -$pad, 1) = $c;
            $pad++;
            last if $c != 0;    # no overflow => early out
        }
        $xs = '1'.$xs if $c == 0;
    }
    $x->{value} = $LIB->_new($xs) if $put_back == 1; # put back, if needed

    $x->{_a} = $scale if $scale >= 0;
    if ($scale < 0) {
        $x->{_a} = $len+$scale;
        $x->{_a} = 0 if $scale < -$len;
    }
    $x;
}

sub bfround {
    # precision: round to the $Nth digit left (+$n) or right (-$n) from the '.'
    # $n == 0 || $n == 1 => round to integer
    my $x = shift;
    my $class = ref($x) || $x;
    $x = $class->new($x) unless ref $x;

    my ($scale, $mode) = $x->_scale_p(@_);

    return $x if !defined $scale || $x->modify('bfround'); # no-op

    # no-op for Math::BigInt objects if $n <= 0
    $x->bround($x->length()-$scale, $mode) if $scale > 0;

    delete $x->{_a};            # delete to save memory
    $x->{_p} = $scale;          # store new _p
    $x;
}

sub fround {
    # Exists to make life easier for switch between MBF and MBI (should we
    # autoload fxxx() like MBF does for bxxx()?)
    my $x = shift;
    $x = __PACKAGE__->new($x) unless ref $x;
    $x->bround(@_);
}

sub bfloor {
    # round towards minus infinity; no-op since it's already integer
    my ($class, $x, @r) = ref($_[0]) ? (undef, @_) : objectify(1, @_);

    $x->round(@r);
}

sub bceil {
    # round towards plus infinity; no-op since it's already int
    my ($class, $x, @r) = ref($_[0]) ? (undef, @_) : objectify(1, @_);

    $x->round(@r);
}

sub bint {
    # round towards zero; no-op since it's already integer
    my ($class, $x, @r) = ref($_[0]) ? (undef, @_) : objectify(1, @_);

    $x->round(@r);
}

###############################################################################
# Other mathematical methods
###############################################################################

sub bgcd {
    # (BINT or num_str, BINT or num_str) return BINT
    # does not modify arguments, but returns new object
    # GCD -- Euclid's algorithm, variant C (Knuth Vol 3, pg 341 ff)

    my ($class, @args) = objectify(0, @_);

    my $x = shift @args;
    $x = ref($x) && $x -> isa($class) ? $x -> copy() : $class -> new($x);

    return $class->bnan() if $x->{sign} !~ /^[+-]$/;    # x NaN?

    while (@args) {
        my $y = shift @args;
        $y = $class->new($y) unless ref($y) && $y -> isa($class);
        return $class->bnan() if $y->{sign} !~ /^[+-]$/;    # y NaN?
        $x->{value} = $LIB->_gcd($x->{value}, $y->{value});
        last if $LIB->_is_one($x->{value});
    }

    return $x -> babs();
}

sub blcm {
    # (BINT or num_str, BINT or num_str) return BINT
    # does not modify arguments, but returns new object
    # Least Common Multiple

    my ($class, @args) = objectify(0, @_);

    my $x = shift @args;
    $x = ref($x) && $x -> isa($class) ? $x -> copy() : $class -> new($x);
    return $class->bnan() if $x->{sign} !~ /^[+-]$/;    # x NaN?

    while (@args) {
        my $y = shift @args;
        $y = $class -> new($y) unless ref($y) && $y -> isa($class);
        return $x->bnan() if $y->{sign} !~ /^[+-]$/;     # y not integer
        $x -> {value} = $LIB->_lcm($x -> {value}, $y -> {value});
    }

    return $x -> babs();
}

###############################################################################
# Object property methods
###############################################################################

sub sign {
    # return the sign of the number: +/-/-inf/+inf/NaN
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    $x->{sign};
}

sub digit {
    # return the nth decimal digit, negative values count backward, 0 is right
    my ($class, $x, $n) = ref($_[0]) ? (undef, @_) : objectify(1, @_);

    $n = $n->numify() if ref($n);
    $LIB->_digit($x->{value}, $n || 0);
}

sub bdigitsum {
    # like digitsum(), but assigns the result to the invocand
    my $x = shift;

    return $x           if $x -> is_nan();
    return $x -> bnan() if $x -> is_inf();

    $x -> {value} = $LIB -> _digitsum($x -> {value});
    $x -> {sign}  = '+';
    return $x;
}

sub digitsum {
    # compute sum of decimal digits and return it
    my $x = shift;
    my $class = ref $x;

    return $class -> bnan() if $x -> is_nan();
    return $class -> bnan() if $x -> is_inf();

    my $y = $class -> bzero();
    $y -> {value} = $LIB -> _digitsum($x -> {value});
    return $y;
}

sub length {
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    my $e = $LIB->_len($x->{value});
    wantarray ? ($e, 0) : $e;
}

sub exponent {
    # return a copy of the exponent (here always 0, NaN or 1 for $m == 0)
    my ($class, $x) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_);

    if ($x->{sign} !~ /^[+-]$/) {
        my $s = $x->{sign};
        $s =~ s/^[+-]//; # NaN, -inf, +inf => NaN or inf
        return $class->new($s);
    }
    return $class->bzero() if $x->is_zero();

    # 12300 => 2 trailing zeros => exponent is 2
    $class->new($LIB->_zeros($x->{value}));
}

sub mantissa {
    # return the mantissa (compatible to Math::BigFloat, e.g. reduced)
    my ($class, $x) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_);

    if ($x->{sign} !~ /^[+-]$/) {
        # for NaN, +inf, -inf: keep the sign
        return $class->new($x->{sign});
    }
    my $m = $x->copy();
    delete $m->{_p};
    delete $m->{_a};

    # that's a bit inefficient:
    my $zeros = $LIB->_zeros($m->{value});
    $m->brsft($zeros, 10) if $zeros != 0;
    $m;
}

sub parts {
    # return a copy of both the exponent and the mantissa
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    ($x->mantissa(), $x->exponent());
}

sub sparts {
    my $self  = shift;
    my $class = ref $self;

    croak("sparts() is an instance method, not a class method")
        unless $class;

    # Not-a-number.

    if ($self -> is_nan()) {
        my $mant = $self -> copy();             # mantissa
        return $mant unless wantarray;          # scalar context
        my $expo = $class -> bnan();            # exponent
        return ($mant, $expo);                  # list context
    }

    # Infinity.

    if ($self -> is_inf()) {
        my $mant = $self -> copy();             # mantissa
        return $mant unless wantarray;          # scalar context
        my $expo = $class -> binf('+');         # exponent
        return ($mant, $expo);                  # list context
    }

    # Finite number.

    my $mant   = $self -> copy();
    my $nzeros = $LIB -> _zeros($mant -> {value});

    $mant -> brsft($nzeros, 10) if $nzeros != 0;
    return $mant unless wantarray;

    my $expo = $class -> new($nzeros);
    return ($mant, $expo);
}

sub nparts {
    my $self  = shift;
    my $class = ref $self;

    croak("nparts() is an instance method, not a class method")
        unless $class;

    # Not-a-number.

    if ($self -> is_nan()) {
        my $mant = $self -> copy();             # mantissa
        return $mant unless wantarray;          # scalar context
        my $expo = $class -> bnan();            # exponent
        return ($mant, $expo);                  # list context
    }

    # Infinity.

    if ($self -> is_inf()) {
        my $mant = $self -> copy();             # mantissa
        return $mant unless wantarray;          # scalar context
        my $expo = $class -> binf('+');         # exponent
        return ($mant, $expo);                  # list context
    }

    # Finite number.

    my ($mant, $expo) = $self -> sparts();

    if ($mant -> bcmp(0)) {
        my ($ndigtot, $ndigfrac) = $mant -> length();
        my $expo10adj = $ndigtot - $ndigfrac - 1;

        if ($expo10adj != 0) {
            return $upgrade -> new($self) -> nparts() if $upgrade;
            $mant -> bnan();
            return $mant unless wantarray;
            $expo -> badd($expo10adj);
            return ($mant, $expo);
        }
    }

    return $mant unless wantarray;
    return ($mant, $expo);
}

sub eparts {
    my $self  = shift;
    my $class = ref $self;

    croak("eparts() is an instance method, not a class method")
        unless $class;

    # Not-a-number and Infinity.

    return $self -> sparts() if $self -> is_nan() || $self -> is_inf();

    # Finite number.

    my ($mant, $expo) = $self -> sparts();

    if ($mant -> bcmp(0)) {
        my $ndigmant  = $mant -> length();
        $expo -> badd($ndigmant);

        # $c is the number of digits that will be in the integer part of the
        # final mantissa.

        my $c = $expo -> copy() -> bdec() -> bmod(3) -> binc();
        $expo -> bsub($c);

        if ($ndigmant > $c) {
            return $upgrade -> new($self) -> eparts() if $upgrade;
            $mant -> bnan();
            return $mant unless wantarray;
            return ($mant, $expo);
        }

        $mant -> blsft($c - $ndigmant, 10);
    }

    return $mant unless wantarray;
    return ($mant, $expo);
}

sub dparts {
    my $self  = shift;
    my $class = ref $self;

    croak("dparts() is an instance method, not a class method")
        unless $class;

    my $int = $self -> copy();
    return $int unless wantarray;

    my $frc = $class -> bzero();
    return ($int, $frc);
}

sub fparts {
    my $x = shift;
    my $class = ref $x;

    croak("fparts() is an instance method") unless $class;

    return ($x -> copy(),
            $x -> is_nan() ? $class -> bnan() : $class -> bone());
}

sub numerator {
    my $x = shift;
    my $class = ref $x;

    croak("numerator() is an instance method") unless $class;

    return $x -> copy();
}

sub denominator {
    my $x = shift;
    my $class = ref $x;

    croak("denominator() is an instance method") unless $class;

    return $x -> is_nan() ? $class -> bnan() : $class -> bone();
}

###############################################################################
# String conversion methods
###############################################################################

sub bstr {
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    if ($x->{sign} ne '+' && $x->{sign} ne '-') {
        return $x->{sign} unless $x->{sign} eq '+inf'; # -inf, NaN
        return 'inf';                                  # +inf
    }
    my $str = $LIB->_str($x->{value});
    return $x->{sign} eq '-' ? "-$str" : $str;
}

# Scientific notation with significand/mantissa as an integer, e.g., "12345" is
# written as "1.2345e+4".

sub bsstr {
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    if ($x->{sign} ne '+' && $x->{sign} ne '-') {
        return $x->{sign} unless $x->{sign} eq '+inf';  # -inf, NaN
        return 'inf';                                   # +inf
    }
    my ($m, $e) = $x -> parts();
    my $str = $LIB->_str($m->{value}) . 'e+' . $LIB->_str($e->{value});
    return $x->{sign} eq '-' ? "-$str" : $str;
}

# Normalized notation, e.g., "12345" is written as "12345e+0".

sub bnstr {
    my $x = shift;

    if ($x->{sign} ne '+' && $x->{sign} ne '-') {
        return $x->{sign} unless $x->{sign} eq '+inf';  # -inf, NaN
        return 'inf';                                   # +inf
    }

    return $x -> bstr() if $x -> is_nan() || $x -> is_inf();

    my ($mant, $expo) = $x -> parts();

    # The "fraction posision" is the position (offset) for the decimal point
    # relative to the end of the digit string.

    my $fracpos = $mant -> length() - 1;
    if ($fracpos == 0) {
        my $str = $LIB->_str($mant->{value}) . "e+" . $LIB->_str($expo->{value});
        return $x->{sign} eq '-' ? "-$str" : $str;
    }

    $expo += $fracpos;
    my $mantstr = $LIB->_str($mant -> {value});
    substr($mantstr, -$fracpos, 0) = '.';

    my $str = $mantstr . 'e+' . $LIB->_str($expo -> {value});
    return $x->{sign} eq '-' ? "-$str" : $str;
}

# Engineering notation, e.g., "12345" is written as "12.345e+3".

sub bestr {
    my $x = shift;

    if ($x->{sign} ne '+' && $x->{sign} ne '-') {
        return $x->{sign} unless $x->{sign} eq '+inf';  # -inf, NaN
        return 'inf';                                   # +inf
    }

    my ($mant, $expo) = $x -> parts();

    my $sign = $mant -> sign();
    $mant -> babs();

    my $mantstr = $LIB->_str($mant -> {value});
    my $mantlen = CORE::length($mantstr);

    my $dotidx = 1;
    $expo += $mantlen - 1;

    my $c = $expo -> copy() -> bmod(3);
    $expo   -= $c;
    $dotidx += $c;

    if ($mantlen < $dotidx) {
        $mantstr .= "0" x ($dotidx - $mantlen);
    } elsif ($mantlen > $dotidx) {
        substr($mantstr, $dotidx, 0) = ".";
    }

    my $str = $mantstr . 'e+' . $LIB->_str($expo -> {value});
    return $sign eq "-" ? "-$str" : $str;
}

# Decimal notation, e.g., "12345".

sub bdstr {
    my $x = shift;

    if ($x->{sign} ne '+' && $x->{sign} ne '-') {
        return $x->{sign} unless $x->{sign} eq '+inf'; # -inf, NaN
        return 'inf';                                  # +inf
    }

    my $str = $LIB->_str($x->{value});
    return $x->{sign} eq '-' ? "-$str" : $str;
}

sub to_hex {
    # return as hex string, with prefixed 0x
    my $x = shift;
    $x = __PACKAGE__->new($x) if !ref($x);

    return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc

    my $hex = $LIB->_to_hex($x->{value});
    return $x->{sign} eq '-' ? "-$hex" : $hex;
}

sub to_oct {
    # return as octal string, with prefixed 0
    my $x = shift;
    $x = __PACKAGE__->new($x) if !ref($x);

    return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc

    my $oct = $LIB->_to_oct($x->{value});
    return $x->{sign} eq '-' ? "-$oct" : $oct;
}

sub to_bin {
    # return as binary string, with prefixed 0b
    my $x = shift;
    $x = __PACKAGE__->new($x) if !ref($x);

    return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc

    my $bin = $LIB->_to_bin($x->{value});
    return $x->{sign} eq '-' ? "-$bin" : $bin;
}

sub to_bytes {
    # return a byte string
    my $x = shift;
    $x = __PACKAGE__->new($x) if !ref($x);

    croak("to_bytes() requires a finite, non-negative integer")
        if $x -> is_neg() || ! $x -> is_int();

    croak("to_bytes() requires a newer version of the $LIB library.")
        unless $LIB->can('_to_bytes');

    return $LIB->_to_bytes($x->{value});
}

sub to_base {
    # return a base anything string
    my $x = shift;
    $x = __PACKAGE__->new($x) if !ref($x);

    croak("the value to convert must be a finite, non-negative integer")
      if $x -> is_neg() || !$x -> is_int();

    my $base = shift;
    $base = __PACKAGE__->new($base) unless ref($base);

    croak("the base must be a finite integer >= 2")
      if $base < 2 || ! $base -> is_int();

    # If no collating sequence is given, pass some of the conversions to
    # methods optimized for those cases.

    if (! @_) {
        return    $x -> to_bin() if $base == 2;
        return    $x -> to_oct() if $base == 8;
        return uc $x -> to_hex() if $base == 16;
        return    $x -> bstr()   if $base == 10;
    }

    croak("to_base() requires a newer version of the $LIB library.")
      unless $LIB->can('_to_base');

    return $LIB->_to_base($x->{value}, $base -> {value}, @_ ? shift() : ());
}

sub to_base_num {
    my $x = shift;
    my $class = ref $x;

    # return a base anything string
    croak("the value to convert must be a finite non-negative integer")
      if $x -> is_neg() || !$x -> is_int();

    my $base = shift;
    $base = $class -> new($base) unless ref $base;

    croak("the base must be a finite integer >= 2")
      if $base < 2 || ! $base -> is_int();

    croak("to_base() requires a newer version of the $LIB library.")
      unless $LIB->can('_to_base');

    # Get a reference to an array of library thingies, and replace each element
    # with a Math::BigInt object using that thingy.

    my $vals = $LIB -> _to_base_num($x->{value}, $base -> {value});

    for my $i (0 .. $#$vals) {
        my $x = $class -> bzero();
        $x -> {value} = $vals -> [$i];
        $vals -> [$i] = $x;
    }

    return $vals;
}

sub as_hex {
    # return as hex string, with prefixed 0x
    my $x = shift;
    $x = __PACKAGE__->new($x) if !ref($x);

    return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc

    my $hex = $LIB->_as_hex($x->{value});
    return $x->{sign} eq '-' ? "-$hex" : $hex;
}

sub as_oct {
    # return as octal string, with prefixed 0
    my $x = shift;
    $x = __PACKAGE__->new($x) if !ref($x);

    return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc

    my $oct = $LIB->_as_oct($x->{value});
    return $x->{sign} eq '-' ? "-$oct" : $oct;
}

sub as_bin {
    # return as binary string, with prefixed 0b
    my $x = shift;
    $x = __PACKAGE__->new($x) if !ref($x);

    return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc

    my $bin = $LIB->_as_bin($x->{value});
    return $x->{sign} eq '-' ? "-$bin" : $bin;
}

*as_bytes = \&to_bytes;

###############################################################################
# Other conversion methods
###############################################################################

sub numify {
    # Make a Perl scalar number from a Math::BigInt object.
    my $x = shift;
    $x = __PACKAGE__->new($x) unless ref $x;

    if ($x -> is_nan()) {
        require Math::Complex;
        my $inf = $Math::Complex::Inf;
        return $inf - $inf;
    }

    if ($x -> is_inf()) {
        require Math::Complex;
        my $inf = $Math::Complex::Inf;
        return $x -> is_negative() ? -$inf : $inf;
    }

    my $num = 0 + $LIB->_num($x->{value});
    return $x->{sign} eq '-' ? -$num : $num;
}

###############################################################################
# Private methods and functions.
###############################################################################

sub objectify {
    # Convert strings and "foreign objects" to the objects we want.

    # The first argument, $count, is the number of following arguments that
    # objectify() looks at and converts to objects. The first is a classname.
    # If the given count is 0, all arguments will be used.

    # After the count is read, objectify obtains the name of the class to which
    # the following arguments are converted. If the second argument is a
    # reference, use the reference type as the class name. Otherwise, if it is
    # a string that looks like a class name, use that. Otherwise, use $class.

    # Caller:                        Gives us:
    #
    # $x->badd(1);                => ref x, scalar y
    # Class->badd(1, 2);           => classname x (scalar), scalar x, scalar y
    # Class->badd(Class->(1), 2);  => classname x (scalar), ref x, scalar y
    # Math::BigInt::badd(1, 2);    => scalar x, scalar y

    # A shortcut for the common case $x->unary_op(), in which case the argument
    # list is (0, $x) or (1, $x).

    return (ref($_[1]), $_[1]) if @_ == 2 && ($_[0] || 0) == 1 && ref($_[1]);

    # Check the context.

    unless (wantarray) {
        croak(__PACKAGE__ . "::objectify() needs list context");
    }

    # Get the number of arguments to objectify.

    my $count = shift;

    # Initialize the output array.

    my @a = @_;

    # If the first argument is a reference, use that reference type as our
    # class name. Otherwise, if the first argument looks like a class name,
    # then use that as our class name. Otherwise, use the default class name.

    my $class;
    if (ref($a[0])) {                   # reference?
        $class = ref($a[0]);
    } elsif ($a[0] =~ /^[A-Z].*::/) {   # string with class name?
        $class = shift @a;
    } else {
        $class = __PACKAGE__;           # default class name
    }

    $count ||= @a;
    unshift @a, $class;

    no strict 'refs';

    # What we upgrade to, if anything. Note that we need the whole upgrade
    # chain, since there might be multiple levels of upgrading. E.g., class A
    # upgrades to class B, which upgrades to class C. Delay getting the chain
    # until we actually need it.

    my @upg = ();
    my $have_upgrade_chain = 0;

    # Disable downgrading, because Math::BigFloat -> foo('1.0', '2.0') needs
    # floats.

    my $down;
    if (defined ${"$a[0]::downgrade"}) {
        $down = ${"$a[0]::downgrade"};
        ${"$a[0]::downgrade"} = undef;
    }

  ARG: for my $i (1 .. $count) {

        my $ref = ref $a[$i];

        # Perl scalars are fed to the appropriate constructor.

        unless ($ref) {
            $a[$i] = $a[0] -> new($a[$i]);
            next;
        }

        # If it is an object of the right class, all is fine.

        next if $ref -> isa($a[0]);

        # Upgrading is OK, so skip further tests if the argument is upgraded,
        # but first get the whole upgrade chain if we haven't got it yet.

        unless ($have_upgrade_chain) {
            my $cls = $class;
            my $upg = $cls -> upgrade();
            while (defined $upg) {
                last if $upg eq $cls;
                push @upg, $upg;
                $cls = $upg;
                $upg = $cls -> upgrade();
            }
            $have_upgrade_chain = 1;
        }

        for my $upg (@upg) {
            next ARG if $ref -> isa($upg);
        }

        # See if we can call one of the as_xxx() methods. We don't know whether
        # the as_xxx() method returns an object or a scalar, so re-check
        # afterwards.

        my $recheck = 0;

        if ($a[0] -> isa('Math::BigInt')) {
            if ($a[$i] -> can('as_int')) {
                $a[$i] = $a[$i] -> as_int();
                $recheck = 1;
            } elsif ($a[$i] -> can('as_number')) {
                $a[$i] = $a[$i] -> as_number();
                $recheck = 1;
            }
        }

        elsif ($a[0] -> isa('Math::BigFloat')) {
            if ($a[$i] -> can('as_float')) {
                $a[$i] = $a[$i] -> as_float();
                $recheck = $1;
            }
        }

        # If we called one of the as_xxx() methods, recheck.

        if ($recheck) {
            $ref = ref($a[$i]);

            # Perl scalars are fed to the appropriate constructor.

            unless ($ref) {
                $a[$i] = $a[0] -> new($a[$i]);
                next;
            }

            # If it is an object of the right class, all is fine.

            next if $ref -> isa($a[0]);
        }

        # Last resort.

        $a[$i] = $a[0] -> new($a[$i]);
    }

    # Reset the downgrading.

    ${"$a[0]::downgrade"} = $down;

    return @a;
}

sub import {
    my $class = shift;
    $IMPORT++;                  # remember we did import()
    my @a;                      # unrecognized arguments

    while (@_) {
        my $param = shift;

        # Enable overloading of constants.

        if ($param eq ':constant') {
            overload::constant

                integer => sub {
                    $class -> new(shift);
                },

                float   => sub {
                    $class -> new(shift);
                },

                binary  => sub {
                    # E.g., a literal 0377 shall result in an object whose value
                    # is decimal 255, but new("0377") returns decimal 377.
                    return $class -> from_oct($_[0]) if $_[0] =~ /^0_*[0-7]/;
                    $class -> new(shift);
                };
            next;
        }

        # Upgrading.

        if ($param eq 'upgrade') {
            $class -> upgrade(shift);
            next;
        }

        # Downgrading.

        if ($param eq 'downgrade') {
            $class -> downgrade(shift);
            next;
        }

        # Accuracy.

        if ($param eq 'accuracy') {
            $class -> accuracy(shift);
            next;
        }

        # Precision.

        if ($param eq 'precision') {
            $class -> precision(shift);
            next;
        }

        # Rounding mode.

        if ($param eq 'round_mode') {
            $class -> round_mode(shift);
            next;
        }

        # Backend library.

        if ($param =~ /^(lib|try|only)\z/) {
            # try  => 0 (no warn if unavailable module)
            # lib  => 1 (warn on fallback)
            # only => 2 (die on fallback)

            # Get the list of user-specified libraries.

            croak "Library argument for import parameter '$param' is missing"
              unless @_;
            my $libs = shift;
            croak "Library argument for import parameter '$param' is undefined"
              unless defined($libs);

            # Check and clean up the list of user-specified libraries.

            my @libs;
            for my $lib (split /,/, $libs) {
                $lib =~ s/^\s+//;
                $lib =~ s/\s+$//;

                if ($lib =~ /[^a-zA-Z0-9_:]/) {
                    carp "Library name '$lib' contains invalid characters";
                    next;
                }

                if (! CORE::length $lib) {
                    carp "Library name is empty";
                    next;
                }

                $lib = "Math::BigInt::$lib" if $lib !~ /^Math::BigInt::/i;

                # If a library has already been loaded, that is OK only if the
                # requested library is identical to the loaded one.

                if (defined($LIB)) {
                    if ($lib ne $LIB) {
                        #carp "Library '$LIB' has already been loaded, so",
                        #  " ignoring requested library '$lib'";
                    }
                    next;
                }

                push @libs, $lib;
            }

            next if defined $LIB;

            croak "Library list contains no valid libraries" unless @libs;

            # Try to load the specified libraries, if any.

            for (my $i = 0 ; $i <= $#libs ; $i++) {
                my $lib = $libs[$i];
                eval "require $lib";
                unless ($@) {
                    $LIB = $lib;
                    last;
                }
            }

            next if defined $LIB;

            # No library has been loaded, and none of the requested libraries
            # could be loaded, and fallback and the user doesn't allow fallback.

            if ($param eq 'only') {
                croak "Couldn't load the specified math lib(s) ",
                  join(", ", map "'$_'", @libs),
                  ", and fallback to '$DEFAULT_LIB' is not allowed";
            }

            # No library has been loaded, and none of the requested libraries
            # could be loaded, but the user accepts the use of a fallback
            # library, so try to load it.

            eval "require $DEFAULT_LIB";
            if ($@) {
                croak "Couldn't load the specified math lib(s) ",
                  join(", ", map "'$_'", @libs),
                  ", not even the fallback lib '$DEFAULT_LIB'";
            }

            # The fallback library was successfully loaded, but the user
            # might want to know that we are using the fallback.

            if ($param eq 'lib') {
                carp "Couldn't load the specified math lib(s) ",
                  join(", ", map "'$_'", @libs),
                  ", so using fallback lib '$DEFAULT_LIB'";
            }

            next;
        }

        # Unrecognized parameter.

        push @a, $param;
    }

    # Any non-':constant' stuff is handled by our parent, Exporter

    if (@a) {
        $class->SUPER::import(@a);              # need it for subclasses
        $class->export_to_level(1, $class, @a); # need it for Math::BigFloat
    }

    # We might not have loaded any backend library yet, either because the user
    # didn't specify any, or because the specified libraries failed to load and
    # the user allows the use of a fallback library.

    unless (defined $LIB) {
        eval "require $DEFAULT_LIB";
        if ($@) {
            croak "No lib specified, and couldn't load the default",
              " lib '$DEFAULT_LIB'";
        }
        $LIB = $DEFAULT_LIB;
    }

    # import done
}

sub _split {
    # input: num_str; output: undef for invalid or
    # (\$mantissa_sign, \$mantissa_value, \$mantissa_fraction,
    # \$exp_sign, \$exp_value)
    # Internal, take apart a string and return the pieces.
    # Strip leading/trailing whitespace, leading zeros, underscore and reject
    # invalid input.
    my $x = shift;

    # strip white space at front, also extraneous leading zeros
    $x =~ s/^\s*([-]?)0*([0-9])/$1$2/g; # will not strip '  .2'
    $x =~ s/^\s+//;                     # but this will
    $x =~ s/\s+$//g;                    # strip white space at end

    # shortcut, if nothing to split, return early
    if ($x =~ /^[+-]?[0-9]+\z/) {
        $x =~ s/^([+-])0*([0-9])/$2/;
        my $sign = $1 || '+';
        return (\$sign, \$x, \'', \'', \0);
    }

    # invalid starting char?
    return if $x !~ /^[+-]?(\.?[0-9]|0b[0-1]|0x[0-9a-fA-F])/;

    return Math::BigInt->from_hex($x) if $x =~ /^[+-]?0x/; # hex string
    return Math::BigInt->from_bin($x) if $x =~ /^[+-]?0b/; # binary string

    # strip underscores between digits
    $x =~ s/([0-9])_([0-9])/$1$2/g;
    $x =~ s/([0-9])_([0-9])/$1$2/g; # do twice for 1_2_3

    # some possible inputs:
    # 2.1234 # 0.12        # 1          # 1E1 # 2.134E1 # 434E-10 # 1.02009E-2
    # .2     # 1_2_3.4_5_6 # 1.4E1_2_3  # 1e3 # +.2     # 0e999

    my ($m, $e, $last) = split /[Ee]/, $x;
    return if defined $last;    # last defined => 1e2E3 or others
    $e = '0' if !defined $e || $e eq "";

    # sign, value for exponent, mantint, mantfrac
    my ($es, $ev, $mis, $miv, $mfv);
    # valid exponent?
    if ($e =~ /^([+-]?)0*([0-9]+)$/) # strip leading zeros
    {
        $es = $1;
        $ev = $2;
        # valid mantissa?
        return if $m eq '.' || $m eq '';
        my ($mi, $mf, $lastf) = split /\./, $m;
        return if defined $lastf; # lastf defined => 1.2.3 or others
        $mi = '0' if !defined $mi;
        $mi .= '0' if $mi =~ /^[\-\+]?$/;
        $mf = '0' if !defined $mf || $mf eq '';
        if ($mi =~ /^([+-]?)0*([0-9]+)$/) # strip leading zeros
        {
            $mis = $1 || '+';
            $miv = $2;
            return unless ($mf =~ /^([0-9]*?)0*$/); # strip trailing zeros
            $mfv = $1;
            # handle the 0e999 case here
            $ev = 0 if $miv eq '0' && $mfv eq '';
            return (\$mis, \$miv, \$mfv, \$es, \$ev);
        }
    }
    return;                     # NaN, not a number
}

sub _e_add {
    # Internal helper sub to take two positive integers and their signs and
    # then add them. Input ($LIB, $LIB, ('+'|'-'), ('+'|'-')), output
    # ($LIB, ('+'|'-')).

    my ($x, $y, $xs, $ys) = @_;

    # if the signs are equal we can add them (-5 + -3 => -(5 + 3) => -8)
    if ($xs eq $ys) {
        $x = $LIB->_add($x, $y); # +a + +b or -a + -b
    } else {
        my $a = $LIB->_acmp($x, $y);
        if ($a == 0) {
            # This does NOT modify $x in-place. TODO: Fix this?
            $x = $LIB->_zero(); # result is 0
            $xs = '+';
            return ($x, $xs);
        }
        if ($a > 0) {
            $x = $LIB->_sub($x, $y);     # abs sub
        } else {                         # a < 0
            $x = $LIB->_sub ($y, $x, 1); # abs sub
            $xs = $ys;
        }
    }

    $xs = '+' if $xs eq '-' && $LIB->_is_zero($x); # no "-0"

    return ($x, $xs);
}

sub _e_sub {
    # Internal helper sub to take two positive integers and their signs and
    # then subtract them. Input ($LIB, $LIB, ('+'|'-'), ('+'|'-')),
    # output ($LIB, ('+'|'-'))
    my ($x, $y, $xs, $ys) = @_;

    # flip sign
    $ys = $ys eq '+' ? '-' : '+'; # swap sign of second operand ...
    _e_add($x, $y, $xs, $ys);     # ... and let _e_add() do the job
    #$LIB -> _sadd($x, $xs, $y, $ys);     # ... and let $LIB -> _sadd() do the job
}

sub _trailing_zeros {
    # return the amount of trailing zeros in $x (as scalar)
    my $x = shift;
    $x = __PACKAGE__->new($x) unless ref $x;

    return 0 if $x->{sign} !~ /^[+-]$/; # NaN, inf, -inf etc

    $LIB->_zeros($x->{value}); # must handle odd values, 0 etc
}

sub _scan_for_nonzero {
    # internal, used by bround() to scan for non-zeros after a '5'
    my ($x, $pad, $xs, $len) = @_;

    return 0 if $len == 1;      # "5" is trailed by invisible zeros
    my $follow = $pad - 1;
    return 0 if $follow > $len || $follow < 1;

    # use the string form to check whether only '0's follow or not
    substr ($xs, -$follow) =~ /[^0]/ ? 1 : 0;
}

sub _find_round_parameters {
    # After any operation or when calling round(), the result is rounded by
    # regarding the A & P from arguments, local parameters, or globals.

    # !!!!!!! If you change this, remember to change round(), too! !!!!!!!!!!

    # This procedure finds the round parameters, but it is for speed reasons
    # duplicated in round. Otherwise, it is tested by the testsuite and used
    # by bdiv().

    # returns ($self) or ($self, $a, $p, $r) - sets $self to NaN of both A and P
    # were requested/defined (locally or globally or both)

    my ($self, $a, $p, $r, @args) = @_;
    # $a accuracy, if given by caller
    # $p precision, if given by caller
    # $r round_mode, if given by caller
    # @args all 'other' arguments (0 for unary, 1 for binary ops)

    my $class = ref($self);       # find out class of argument(s)
    no strict 'refs';

    # convert to normal scalar for speed and correctness in inner parts
    $a = $a->can('numify') ? $a->numify() : "$a" if defined $a && ref($a);
    $p = $p->can('numify') ? $p->numify() : "$p" if defined $p && ref($p);

    # now pick $a or $p, but only if we have got "arguments"
    if (!defined $a) {
        foreach ($self, @args) {
            # take the defined one, or if both defined, the one that is smaller
            $a = $_->{_a} if (defined $_->{_a}) && (!defined $a || $_->{_a} < $a);
        }
    }
    if (!defined $p) {
        # even if $a is defined, take $p, to signal error for both defined
        foreach ($self, @args) {
            # take the defined one, or if both defined, the one that is bigger
            # -2 > -3, and 3 > 2
            $p = $_->{_p} if (defined $_->{_p}) && (!defined $p || $_->{_p} > $p);
        }
    }

    # if still none defined, use globals (#2)
    $a = ${"$class\::accuracy"}  unless defined $a;
    $p = ${"$class\::precision"} unless defined $p;

    # A == 0 is useless, so undef it to signal no rounding
    $a = undef if defined $a && $a == 0;

    # no rounding today?
    return ($self) unless defined $a || defined $p; # early out

    # set A and set P is an fatal error
    return ($self->bnan()) if defined $a && defined $p; # error

    $r = ${"$class\::round_mode"} unless defined $r;
    if ($r !~ /^(even|odd|[+-]inf|zero|trunc|common)$/) {
        croak("Unknown round mode '$r'");
    }

    $a = int($a) if defined $a;
    $p = int($p) if defined $p;

    ($self, $a, $p, $r);
}

# Trims the sign of the significand, the (absolute value of the) significand,
# the sign of the exponent, and the (absolute value of the) exponent. The
# returned values have no underscores ("_") or unnecessary leading or trailing
# zeros.

sub _trim_split_parts {
    shift;

    my $sig_sgn = shift() || '+';
    my $sig_str = shift() || '0';
    my $exp_sgn = shift() || '+';
    my $exp_str = shift() || '0';

    $sig_str =~ tr/_//d;                        # "1.0_0_0" -> "1.000"
    $sig_str =~ s/^0+//;                        # "01.000" -> "1.000"
    $sig_str =~ s/\.0*$//                       # "1.000" -> "1"
      || $sig_str =~ s/(\..*[^0])0+$/$1/;       # "1.010" -> "1.01"
    $sig_str = '0' unless CORE::length($sig_str);

    return '+', '0', '+', '0' if $sig_str eq '0';

    $exp_str =~ tr/_//d;                        # "01_234" -> "01234"
    $exp_str =~ s/^0+//;                        # "01234" -> "1234"
    $exp_str = '0' unless CORE::length($exp_str);

    return $sig_sgn, $sig_str, $exp_sgn, $exp_str;
}

# Takes any string representing a valid decimal number and splits it into four
# strings: the sign of the significand, the absolute value of the significand,
# the sign of the exponent, and the absolute value of the exponent. Both the
# significand and the exponent are in base 10.
#
# Perl accepts literals like the following. The value is 100.1.
#
#   1__0__.__0__1__e+0__1__     (prints "Misplaced _ in number")
#   1_0.0_1e+0_1
#
# Strings representing decimal numbers do not allow underscores, so only the
# following is valid
#
#   "10.01e+01"

sub _dec_str_to_str_parts {
    my $class = shift;
    my $str   = shift;

    if ($str =~ /
                    ^

                    # optional leading whitespace
                    \s*

                    # optional sign
                    ( [+-]? )

                    # significand
                    (
                        # integer part and optional fraction part ...
                        \d+ (?: _+ \d+ )* _*
                        (?:
                            \.
                            (?: _* \d+ (?: _+ \d+ )* _* )?
                        )?
                    |
                        # ... or mandatory fraction part
                        \.
                        \d+ (?: _+ \d+ )* _*
                    )

                    # optional exponent
                    (?:
                        [Ee]
                        ( [+-]? )
                        ( \d+ (?: _+ \d+ )* _* )
                    )?

                    # optional trailing whitespace
                    \s*

                    $
                /x)
    {
        return $class -> _trim_split_parts($1, $2, $3, $4);
    }

    return;
}

# Takes any string representing a valid hexadecimal number and splits it into
# four strings: the sign of the significand, the absolute value of the
# significand, the sign of the exponent, and the absolute value of the exponent.
# The significand is in base 16, and the exponent is in base 2.
#
# Perl accepts literals like the following. The "x" might be a capital "X". The
# value is 32.0078125.
#
#   0x__1__0__.0__1__p+0__1__   (prints "Misplaced _ in number")
#   0x1_0.0_1p+0_1
#
# The CORE::hex() function does not accept floating point accepts
#
#   "0x_1_0"
#   "x_1_0"
#   "_1_0"

sub _hex_str_to_str_parts {
    my $class = shift;
    my $str   = shift;

    if ($str =~ /
                    ^

                    # optional leading whitespace
                    \s*

                    # optional sign
                    ( [+-]? )

                    # optional hex prefix
                    (?: 0? [Xx] _* )?

                    # significand using the hex digits 0..9 and a..f
                    (
                        # integer part and optional fraction part ...
                        [0-9a-fA-F]+ (?: _+ [0-9a-fA-F]+ )* _*
                        (?:
                            \.
                            (?: _* [0-9a-fA-F]+ (?: _+ [0-9a-fA-F]+ )* _* )?
                        )?
                    |
                        # ... or mandatory fraction part
                        \.
                        [0-9a-fA-F]+ (?: _+ [0-9a-fA-F]+ )* _*
                    )

                    # optional exponent (power of 2) using decimal digits
                    (?:
                        [Pp]
                        ( [+-]? )
                        ( \d+ (?: _+ \d+ )* _* )
                    )?

                    # optional trailing whitespace
                    \s*

                    $
                /x)
    {
        return $class -> _trim_split_parts($1, $2, $3, $4);
    }

    return;
}

# Takes any string representing a valid octal number and splits it into four
# strings: the sign of the significand, the absolute value of the significand,
# the sign of the exponent, and the absolute value of the exponent. The
# significand is in base 8, and the exponent is in base 2.

sub _oct_str_to_str_parts {
    my $class = shift;
    my $str   = shift;

    if ($str =~ /
                    ^

                    # optional leading whitespace
                    \s*

                    # optional sign
                    ( [+-]? )

                    # optional octal prefix
                    (?: 0? [Oo] _* )?

                    # significand using the octal digits 0..7
                    (
                        # integer part and optional fraction part ...
                        [0-7]+ (?: _+ [0-7]+ )* _*
                        (?:
                            \.
                            (?: _* [0-7]+ (?: _+ [0-7]+ )* _* )?
                        )?
                    |
                        # ... or mandatory fraction part
                        \.
                        [0-7]+ (?: _+ [0-7]+ )* _*
                    )

                    # optional exponent (power of 2) using decimal digits
                    (?:
                        [Pp]
                        ( [+-]? )
                        ( \d+ (?: _+ \d+ )* _* )
                    )?

                    # optional trailing whitespace
                    \s*

                    $
                /x)
    {
        return $class -> _trim_split_parts($1, $2, $3, $4);
    }

    return;
}

# Takes any string representing a valid binary number and splits it into four
# strings: the sign of the significand, the absolute value of the significand,
# the sign of the exponent, and the absolute value of the exponent. The
# significand is in base 2, and the exponent is in base 2.

sub _bin_str_to_str_parts {
    my $class = shift;
    my $str   = shift;

    if ($str =~ /
                    ^

                    # optional leading whitespace
                    \s*

                    # optional sign
                    ( [+-]? )

                    # optional binary prefix
                    (?: 0? [Bb] _* )?

                    # significand using the binary digits 0 and 1
                    (
                        # integer part and optional fraction part ...
                        [01]+ (?: _+ [01]+ )* _*
                        (?:
                            \.
                            (?: _* [01]+ (?: _+ [01]+ )* _* )?
                        )?
                    |
                        # ... or mandatory fraction part
                        \.
                        [01]+ (?: _+ [01]+ )* _*
                    )

                    # optional exponent (power of 2) using decimal digits
                    (?:
                        [Pp]
                        ( [+-]? )
                        ( \d+ (?: _+ \d+ )* _* )
                    )?

                    # optional trailing whitespace
                    \s*

                    $
                /x)
    {
        return $class -> _trim_split_parts($1, $2, $3, $4);
    }

    return;
}

# Takes any string representing a valid decimal number and splits it into four
# parts: the sign of the significand, the absolute value of the significand as a
# libray thingy, the sign of the exponent, and the absolute value of the
# exponent as a library thingy.

sub _dec_parts_to_lib_parts {
    shift;

    my ($sig_sgn, $sig_str, $exp_sgn, $exp_str) = @_;

    # Handle zero.

    if ($sig_str eq '0') {
        return '+', $LIB -> _zero(), '+', $LIB -> _zero();
    }

    # Absolute value of exponent as library "object".

    my $exp_lib = $LIB -> _new($exp_str);

    # If there is a dot in the significand, remove it so the significand
    # becomes an integer and adjust the exponent accordingly. Also remove
    # leading zeros which might now appear in the significand. E.g.,
    #
    #     12.345e-2  ->  12345e-5
    #     12.345e+2  ->  12345e-1
    #     0.0123e+5  ->  00123e+1  ->  123e+1

    my $idx = index $sig_str, '.';
    if ($idx >= 0) {
        substr($sig_str, $idx, 1) = '';

        # delta = length - index
        my $delta = $LIB -> _new(CORE::length($sig_str));
        $delta = $LIB -> _sub($delta, $LIB -> _new($idx));

        # exponent - delta
        ($exp_lib, $exp_sgn) = _e_sub($exp_lib, $delta, $exp_sgn, '+');
        #($exp_lib, $exp_sgn) = $LIB -> _ssub($exp_lib, $exp_sgn, $delta, '+');

        $sig_str =~ s/^0+//;
    }

    # If there are trailing zeros in the significand, remove them and
    # adjust the exponent. E.g.,
    #
    #     12340e-5  ->  1234e-4
    #     12340e-1  ->  1234e0
    #     12340e+3  ->  1234e4

    if ($sig_str =~ s/(0+)\z//) {
        my $len = CORE::length($1);
        ($exp_lib, $exp_sgn) =
          $LIB -> _sadd($exp_lib, $exp_sgn, $LIB -> _new($len), '+');
    }

    # At this point, the significand is empty or an integer with no trailing
    # zeros. The exponent is in base 10.

    unless (CORE::length $sig_str) {
        return '+', $LIB -> _zero(), '+', $LIB -> _zero();
    }

    # Absolute value of significand as library "object".

    my $sig_lib = $LIB -> _new($sig_str);

    return $sig_sgn, $sig_lib, $exp_sgn, $exp_lib;
}

# Takes any string representing a valid binary number and splits it into four
# parts: the sign of the significand, the absolute value of the significand as a
# libray thingy, the sign of the exponent, and the absolute value of the
# exponent as a library thingy.

sub _bin_parts_to_lib_parts {
    shift;

    my ($sig_sgn, $sig_str, $exp_sgn, $exp_str, $bpc) = @_;
    my $bpc_lib = $LIB -> _new($bpc);

    # Handle zero.

    if ($sig_str eq '0') {
        return '+', $LIB -> _zero(), '+', $LIB -> _zero();
    }

    # Absolute value of exponent as library "object".

    my $exp_lib = $LIB -> _new($exp_str);

    # If there is a dot in the significand, remove it so the significand
    # becomes an integer and adjust the exponent accordingly. Also remove
    # leading zeros which might now appear in the significand. E.g., with
    # hexadecimal numbers
    #
    #     12.345p-2  ->  12345p-14
    #     12.345p+2  ->  12345p-10
    #     0.0123p+5  ->  00123p-11  ->  123p-11

    my $idx = index $sig_str, '.';
    if ($idx >= 0) {
        substr($sig_str, $idx, 1) = '';

        # delta = (length - index) * bpc
        my $delta = $LIB -> _new(CORE::length($sig_str));
        $delta = $LIB -> _sub($delta, $LIB -> _new($idx));
        $delta = $LIB -> _mul($delta, $bpc_lib) if $bpc != 1;

        # exponent - delta
        ($exp_lib, $exp_sgn) = _e_sub($exp_lib, $delta, $exp_sgn, '+');
        #($exp_lib, $exp_sgn) = $LIB -> _ssub($exp_lib, $exp_sgn, $delta, '+');

        $sig_str =~ s/^0+//;
    }

    # If there are trailing zeros in the significand, remove them and
    # adjust the exponent accordingly. E.g., with hexadecimal numbers
    #
    #     12340p-5  ->  1234p-1
    #     12340p-1  ->  1234p+3
    #     12340p+3  ->  1234p+7

    if ($sig_str =~ s/(0+)\z//) {

        # delta = length * bpc
        my $delta = $LIB -> _new(CORE::length($1));
        $delta = $LIB -> _mul($delta, $bpc_lib) if $bpc != 1;

        # exponent + delta
        ($exp_lib, $exp_sgn) = $LIB -> _sadd($exp_lib, $exp_sgn, $delta, '+');
    }

    # At this point, the significand is empty or an integer with no leading
    # or trailing zeros. The exponent is in base 2.

    unless (CORE::length $sig_str) {
        return '+', $LIB -> _zero(), '+', $LIB -> _zero();
    }

    # Absolute value of significand as library "object".

    my $sig_lib = $bpc == 1 ? $LIB -> _from_bin('0b' . $sig_str)
                : $bpc == 3 ? $LIB -> _from_oct('0'  . $sig_str)
                : $bpc == 4 ? $LIB -> _from_hex('0x' . $sig_str)
                : die "internal error: invalid exponent multiplier";

    # If the exponent (in base 2) is positive or zero ...

    if ($exp_sgn eq '+') {

        if (!$LIB -> _is_zero($exp_lib)) {

            # Multiply significand by 2 raised to the exponent.

            my $p = $LIB -> _pow($LIB -> _two(), $exp_lib);
            $sig_lib = $LIB -> _mul($sig_lib, $p);
            $exp_lib = $LIB -> _zero();
        }
    }

    # ... else if the exponent is negative ...

    else {

        # Rather than dividing the significand by 2 raised to the absolute
        # value of the exponent, multiply the significand by 5 raised to the
        # absolute value of the exponent and let the exponent be in base 10:
        #
        # a * 2^(-b) = a * 5^b * 10^(-b) = c * 10^(-b), where c = a * 5^b

        my $p = $LIB -> _pow($LIB -> _new("5"), $exp_lib);
        $sig_lib = $LIB -> _mul($sig_lib, $p);
    }

    # Adjust for the case when the conversion to decimal introduced trailing
    # zeros in the significand.

    my $n = $LIB -> _zeros($sig_lib);
    if ($n) {
        $n = $LIB -> _new($n);
        $sig_lib = $LIB -> _rsft($sig_lib, $n, 10);
        ($exp_lib, $exp_sgn) = $LIB -> _sadd($exp_lib, $exp_sgn, $n, '+');
    }

    return $sig_sgn, $sig_lib, $exp_sgn, $exp_lib;
}

# Takes any string representing a valid hexadecimal number and splits it into
# four parts: the sign of the significand, the absolute value of the significand
# as a libray thingy, the sign of the exponent, and the absolute value of the
# exponent as a library thingy.

sub _hex_str_to_lib_parts {
    my $class = shift;
    my $str   = shift;
    if (my @parts = $class -> _hex_str_to_str_parts($str)) {
        return $class -> _bin_parts_to_lib_parts(@parts, 4);  # 4 bits pr. chr
    }
    return;
}

# Takes any string representing a valid octal number and splits it into four
# parts: the sign of the significand, the absolute value of the significand as a
# libray thingy, the sign of the exponent, and the absolute value of the
# exponent as a library thingy.

sub _oct_str_to_lib_parts {
    my $class = shift;
    my $str   = shift;
    if (my @parts = $class -> _oct_str_to_str_parts($str)) {
        return $class -> _bin_parts_to_lib_parts(@parts, 3);  # 3 bits pr. chr
    }
    return;
}

# Takes any string representing a valid binary number and splits it into four
# parts: the sign of the significand, the absolute value of the significand as a
# libray thingy, the sign of the exponent, and the absolute value of the
# exponent as a library thingy.

sub _bin_str_to_lib_parts {
    my $class = shift;
    my $str   = shift;
    if (my @parts = $class -> _bin_str_to_str_parts($str)) {
        return $class -> _bin_parts_to_lib_parts(@parts, 1);  # 1 bit pr. chr
    }
    return;
}

# Decimal string is split into the sign of the signficant, the absolute value of
# the significand as library thingy, the sign of the exponent, and the absolute
# value of the exponent as a a library thingy.

sub _dec_str_to_lib_parts {
    my $class = shift;
    my $str   = shift;
    if (my @parts = $class -> _dec_str_to_str_parts($str)) {
        return $class -> _dec_parts_to_lib_parts(@parts);
    }
    return;
}

# Hexdecimal string to a string using decimal floating point notation.

sub hex_str_to_dec_flt_str {
    my $class = shift;
    my $str   = shift;
    if (my @parts = $class -> _hex_str_to_lib_parts($str)) {
        return $class -> _lib_parts_to_flt_str(@parts);
    }
    return;
}

# Octal string to a string using decimal floating point notation.

sub oct_str_to_dec_flt_str {
    my $class = shift;
    my $str   = shift;
    if (my @parts = $class -> _oct_str_to_lib_parts($str)) {
        return $class -> _lib_parts_to_flt_str(@parts);
    }
    return;
}

# Binary string to a string decimal floating point notation.

sub bin_str_to_dec_flt_str {
    my $class = shift;
    my $str   = shift;
    if (my @parts = $class -> _bin_str_to_lib_parts($str)) {
        return $class -> _lib_parts_to_flt_str(@parts);
    }
    return;
}

# Decimal string to a string using decimal floating point notation.

sub dec_str_to_dec_flt_str {
    my $class = shift;
    my $str   = shift;
    if (my @parts = $class -> _dec_str_to_lib_parts($str)) {
        return $class -> _lib_parts_to_flt_str(@parts);
    }
    return;
}

# Hexdecimal string to decimal notation (no exponent).

sub hex_str_to_dec_str {
    my $class = shift;
    my $str   = shift;
    if (my @parts = $class -> _dec_str_to_lib_parts($str)) {
        return $class -> _lib_parts_to_dec_str(@parts);
    }
    return;
}

# Octal string to decimal notation (no exponent).

sub oct_str_to_dec_str {
    my $class = shift;
    my $str   = shift;
    if (my @parts = $class -> _oct_str_to_lib_parts($str)) {
        return $class -> _lib_parts_to_dec_str(@parts);
    }
    return;
}

# Binary string to decimal notation (no exponent).

sub bin_str_to_dec_str {
    my $class = shift;
    my $str   = shift;
    if (my @parts = $class -> _bin_str_to_lib_parts($str)) {
        return $class -> _lib_parts_to_dec_str(@parts);
    }
    return;
}

# Decimal string to decimal notation (no exponent).

sub dec_str_to_dec_str {
    my $class = shift;
    my $str   = shift;
    if (my @parts = $class -> _dec_str_to_lib_parts($str)) {
        return $class -> _lib_parts_to_dec_str(@parts);
    }
    return;
}

sub _lib_parts_to_flt_str {
    my $class = shift;
    my @parts = @_;
    return $parts[0] . $LIB -> _str($parts[1])
      . 'e' . $parts[2] . $LIB -> _str($parts[3]);
}

sub _lib_parts_to_dec_str {
    my $class = shift;
    my @parts = @_;

    # The number is an integer iff the exponent is non-negative.

    if ($parts[2] eq '+') {
        my $str = $parts[0]
          . $LIB -> _str($LIB -> _lsft($parts[1], $parts[3], 10));
        return $str;
    }

    # If it is not an integer, add a decimal point.

    else {
        my $mant     = $LIB -> _str($parts[1]);
        my $mant_len = CORE::length($mant);
        my $expo     = $LIB -> _num($parts[3]);
        my $len_cmp = $mant_len <=> $expo;
        if ($len_cmp <= 0) {
            return $parts[0] . '0.' . '0' x ($expo - $mant_len) . $mant;
        } else {
            substr $mant, $mant_len - $expo, 0, '.';
            return $parts[0] . $mant;
        }
    }
}

###############################################################################
# this method returns 0 if the object can be modified, or 1 if not.
# We use a fast constant sub() here, to avoid costly calls. Subclasses
# may override it with special code (f.i. Math::BigInt::Constant does so)

sub modify () { 0; }

1;

__END__

=pod

=head1 NAME

Math::BigInt - arbitrary size integer math package

=head1 SYNOPSIS

  use Math::BigInt;

  # or make it faster with huge numbers: install (optional)
  # Math::BigInt::GMP and always use (it falls back to
  # pure Perl if the GMP library is not installed):
  # (See also the L<MATH LIBRARY> section!)

  # to warn if Math::BigInt::GMP cannot be found, use
  use Math::BigInt lib => 'GMP';

  # to suppress the warning if Math::BigInt::GMP cannot be found, use
  # use Math::BigInt try => 'GMP';

  # to die if Math::BigInt::GMP cannot be found, use
  # use Math::BigInt only => 'GMP';

  my $str = '1234567890';
  my @values = (64, 74, 18);
  my $n = 1; my $sign = '-';

  # Configuration methods (may be used as class methods and instance methods)

  Math::BigInt->accuracy();     # get class accuracy
  Math::BigInt->accuracy($n);   # set class accuracy
  Math::BigInt->precision();    # get class precision
  Math::BigInt->precision($n);  # set class precision
  Math::BigInt->round_mode();   # get class rounding mode
  Math::BigInt->round_mode($m); # set global round mode, must be one of
                                # 'even', 'odd', '+inf', '-inf', 'zero',
                                # 'trunc', or 'common'
  Math::BigInt->config();       # return hash with configuration

  # Constructor methods (when the class methods below are used as instance
  # methods, the value is assigned the invocand)

  $x = Math::BigInt->new($str);             # defaults to 0
  $x = Math::BigInt->new('0x123');          # from hexadecimal
  $x = Math::BigInt->new('0b101');          # from binary
  $x = Math::BigInt->from_hex('cafe');      # from hexadecimal
  $x = Math::BigInt->from_oct('377');       # from octal
  $x = Math::BigInt->from_bin('1101');      # from binary
  $x = Math::BigInt->from_base('why', 36);  # from any base
  $x = Math::BigInt->from_base_num([1, 0], 2);  # from any base
  $x = Math::BigInt->bzero();               # create a +0
  $x = Math::BigInt->bone();                # create a +1
  $x = Math::BigInt->bone('-');             # create a -1
  $x = Math::BigInt->binf();                # create a +inf
  $x = Math::BigInt->binf('-');             # create a -inf
  $x = Math::BigInt->bnan();                # create a Not-A-Number
  $x = Math::BigInt->bpi();                 # returns pi

  $y = $x->copy();         # make a copy (unlike $y = $x)
  $y = $x->as_int();       # return as a Math::BigInt

  # Boolean methods (these don't modify the invocand)

  $x->is_zero();          # if $x is 0
  $x->is_one();           # if $x is +1
  $x->is_one("+");        # ditto
  $x->is_one("-");        # if $x is -1
  $x->is_inf();           # if $x is +inf or -inf
  $x->is_inf("+");        # if $x is +inf
  $x->is_inf("-");        # if $x is -inf
  $x->is_nan();           # if $x is NaN

  $x->is_positive();      # if $x > 0
  $x->is_pos();           # ditto
  $x->is_negative();      # if $x < 0
  $x->is_neg();           # ditto

  $x->is_odd();           # if $x is odd
  $x->is_even();          # if $x is even
  $x->is_int();           # if $x is an integer

  # Comparison methods

  $x->bcmp($y);           # compare numbers (undef, < 0, == 0, > 0)
  $x->bacmp($y);          # compare absolutely (undef, < 0, == 0, > 0)
  $x->beq($y);            # true if and only if $x == $y
  $x->bne($y);            # true if and only if $x != $y
  $x->blt($y);            # true if and only if $x < $y
  $x->ble($y);            # true if and only if $x <= $y
  $x->bgt($y);            # true if and only if $x > $y
  $x->bge($y);            # true if and only if $x >= $y

  # Arithmetic methods

  $x->bneg();             # negation
  $x->babs();             # absolute value
  $x->bsgn();             # sign function (-1, 0, 1, or NaN)
  $x->bnorm();            # normalize (no-op)
  $x->binc();             # increment $x by 1
  $x->bdec();             # decrement $x by 1
  $x->badd($y);           # addition (add $y to $x)
  $x->bsub($y);           # subtraction (subtract $y from $x)
  $x->bmul($y);           # multiplication (multiply $x by $y)
  $x->bmuladd($y,$z);     # $x = $x * $y + $z
  $x->bdiv($y);           # division (floored), set $x to quotient
                          # return (quo,rem) or quo if scalar
  $x->btdiv($y);          # division (truncated), set $x to quotient
                          # return (quo,rem) or quo if scalar
  $x->bmod($y);           # modulus (x % y)
  $x->btmod($y);          # modulus (truncated)
  $x->bmodinv($mod);      # modular multiplicative inverse
  $x->bmodpow($y,$mod);   # modular exponentiation (($x ** $y) % $mod)
  $x->bpow($y);           # power of arguments (x ** y)
  $x->blog();             # logarithm of $x to base e (Euler's number)
  $x->blog($base);        # logarithm of $x to base $base (e.g., base 2)
  $x->bexp();             # calculate e ** $x where e is Euler's number
  $x->bnok($y);           # x over y (binomial coefficient n over k)
  $x->buparrow($n, $y);   # Knuth's up-arrow notation
  $x->backermann($y);     # the Ackermann function
  $x->bsin();             # sine
  $x->bcos();             # cosine
  $x->batan();            # inverse tangent
  $x->batan2($y);         # two-argument inverse tangent
  $x->bsqrt();            # calculate square root
  $x->broot($y);          # $y'th root of $x (e.g. $y == 3 => cubic root)
  $x->bfac();             # factorial of $x (1*2*3*4*..$x)
  $x->bdfac();            # double factorial of $x ($x*($x-2)*($x-4)*...)
  $x->btfac();            # triple factorial of $x ($x*($x-3)*($x-6)*...)
  $x->bmfac($k);          # $k'th multi-factorial of $x ($x*($x-$k)*...)

  $x->blsft($n);          # left shift $n places in base 2
  $x->blsft($n,$b);       # left shift $n places in base $b
                          # returns (quo,rem) or quo (scalar context)
  $x->brsft($n);          # right shift $n places in base 2
  $x->brsft($n,$b);       # right shift $n places in base $b
                          # returns (quo,rem) or quo (scalar context)

  # Bitwise methods

  $x->band($y);           # bitwise and
  $x->bior($y);           # bitwise inclusive or
  $x->bxor($y);           # bitwise exclusive or
  $x->bnot();             # bitwise not (two's complement)

  # Rounding methods
  $x->round($A,$P,$mode); # round to accuracy or precision using
                          # rounding mode $mode
  $x->bround($n);         # accuracy: preserve $n digits
  $x->bfround($n);        # $n > 0: round to $nth digit left of dec. point
                          # $n < 0: round to $nth digit right of dec. point
  $x->bfloor();           # round towards minus infinity
  $x->bceil();            # round towards plus infinity
  $x->bint();             # round towards zero

  # Other mathematical methods

  $x->bgcd($y);            # greatest common divisor
  $x->blcm($y);            # least common multiple

  # Object property methods (do not modify the invocand)

  $x->sign();              # the sign, either +, - or NaN
  $x->digit($n);           # the nth digit, counting from the right
  $x->digit(-$n);          # the nth digit, counting from the left
  $x->length();            # return number of digits in number
  ($xl,$f) = $x->length(); # length of number and length of fraction
                           # part, latter is always 0 digits long
                           # for Math::BigInt objects
  $x->mantissa();          # return (signed) mantissa as a Math::BigInt
  $x->exponent();          # return exponent as a Math::BigInt
  $x->parts();             # return (mantissa,exponent) as a Math::BigInt
  $x->sparts();            # mantissa and exponent (as integers)
  $x->nparts();            # mantissa and exponent (normalised)
  $x->eparts();            # mantissa and exponent (engineering notation)
  $x->dparts();            # integer and fraction part
  $x->fparts();            # numerator and denominator
  $x->numerator();         # numerator
  $x->denominator();       # denominator

  # Conversion methods (do not modify the invocand)

  $x->bstr();         # decimal notation, possibly zero padded
  $x->bsstr();        # string in scientific notation with integers
  $x->bnstr();        # string in normalized notation
  $x->bestr();        # string in engineering notation
  $x->bdstr();        # string in decimal notation

  $x->to_hex();       # as signed hexadecimal string
  $x->to_bin();       # as signed binary string
  $x->to_oct();       # as signed octal string
  $x->to_bytes();     # as byte string
  $x->to_base($b);    # as string in any base
  $x->to_base_num($b);   # as array of integers in any base

  $x->as_hex();       # as signed hexadecimal string with prefixed 0x
  $x->as_bin();       # as signed binary string with prefixed 0b
  $x->as_oct();       # as signed octal string with prefixed 0

  # Other conversion methods

  $x->numify();           # return as scalar (might overflow or underflow)

=head1 DESCRIPTION

Math::BigInt provides support for arbitrary precision integers. Overloading is
also provided for Perl operators.

=head2 Input

Input values to these routines may be any scalar number or string that looks
like a number and represents an integer. Anything that is accepted by Perl as a
literal numeric constant should be accepted by this module, except that finite
non-integers return NaN.

=over

=item *

Leading and trailing whitespace is ignored.

=item *

Leading zeros are ignored, except for floating point numbers with a binary
exponent, in which case the number is interpreted as an octal floating point
number. For example, "01.4p+0" gives 1.5, "00.4p+0" gives 0.5, but "0.4p+0"
gives a NaN. And while "0377" gives 255, "0377p0" gives 255.

=item *

If the string has a "0x" or "0X" prefix, it is interpreted as a hexadecimal
number.

=item *

If the string has a "0o" or "0O" prefix, it is interpreted as an octal number. A
floating point literal with a "0" prefix is also interpreted as an octal number.

=item *

If the string has a "0b" or "0B" prefix, it is interpreted as a binary number.

=item *

Underline characters are allowed in the same way as they are allowed in literal
numerical constants.

=item *

If the string can not be interpreted, or does not represent a finite integer,
NaN is returned.

=item *

For hexadecimal, octal, and binary floating point numbers, the exponent must be
separated from the significand (mantissa) by the letter "p" or "P", not "e" or
"E" as with decimal numbers.

=back

Some examples of valid string input

    Input string                Resulting value

    123                         123
    1.23e2                      123
    12300e-2                    123

    67_538_754                  67538754
    -4_5_6.7_8_9e+0_1_0         -4567890000000

    0x13a                       314
    0x13ap0                     314
    0x1.3ap+8                   314
    0x0.00013ap+24              314
    0x13a000p-12                314

    0o472                       314
    0o1.164p+8                  314
    0o0.0001164p+20             314
    0o1164000p-10               314

    0472                        472     Note!
    01.164p+8                   314
    00.0001164p+20              314
    01164000p-10                314

    0b100111010                 314
    0b1.0011101p+8              314
    0b0.00010011101p+12         314
    0b100111010000p-3           314

Input given as scalar numbers might lose precision. Quote your input to ensure
that no digits are lost:

    $x = Math::BigInt->new( 56789012345678901234 );   # bad
    $x = Math::BigInt->new('56789012345678901234');   # good

Currently, C<Math::BigInt->new()> (no input argument) and
C<Math::BigInt->new("")> return 0. This might change in the future, so always
use the following explicit forms to get a zero:

    $zero = Math::BigInt->bzero();

=head2 Output

Output values are usually Math::BigInt objects.

Boolean operators C<is_zero()>, C<is_one()>, C<is_inf()>, etc. return true or
false.

Comparison operators C<bcmp()> and C<bacmp()>) return -1, 0, 1, or
undef.

=head1 METHODS

=head2 Configuration methods

Each of the methods below (except config(), accuracy() and precision()) accepts
three additional parameters. These arguments C<$A>, C<$P> and C<$R> are
C<accuracy>, C<precision> and C<round_mode>. Please see the section about
L</ACCURACY and PRECISION> for more information.

Setting a class variable effects all object instance that are created
afterwards.

=over

=item accuracy()

    Math::BigInt->accuracy(5);      # set class accuracy
    $x->accuracy(5);                # set instance accuracy

    $A = Math::BigInt->accuracy();  # get class accuracy
    $A = $x->accuracy();            # get instance accuracy

Set or get the accuracy, i.e., the number of significant digits. The accuracy
must be an integer. If the accuracy is set to C<undef>, no rounding is done.

Alternatively, one can round the results explicitly using one of L</round()>,
L</bround()> or L</bfround()> or by passing the desired accuracy to the method
as an additional parameter:

    my $x = Math::BigInt->new(30000);
    my $y = Math::BigInt->new(7);
    print scalar $x->copy()->bdiv($y, 2);               # prints 4300
    print scalar $x->copy()->bdiv($y)->bround(2);       # prints 4300

Please see the section about L</ACCURACY and PRECISION> for further details.

    $y = Math::BigInt->new(1234567);    # $y is not rounded
    Math::BigInt->accuracy(4);          # set class accuracy to 4
    $x = Math::BigInt->new(1234567);    # $x is rounded automatically
    print "$x $y";                      # prints "1235000 1234567"

    print $x->accuracy();       # prints "4"
    print $y->accuracy();       # also prints "4", since
                                #   class accuracy is 4

    Math::BigInt->accuracy(5);  # set class accuracy to 5
    print $x->accuracy();       # prints "4", since instance
                                #   accuracy is 4
    print $y->accuracy();       # prints "5", since no instance
                                #   accuracy, and class accuracy is 5

Note: Each class has it's own globals separated from Math::BigInt, but it is
possible to subclass Math::BigInt and make the globals of the subclass aliases
to the ones from Math::BigInt.

=item precision()

    Math::BigInt->precision(-2);     # set class precision
    $x->precision(-2);               # set instance precision

    $P = Math::BigInt->precision();  # get class precision
    $P = $x->precision();            # get instance precision

Set or get the precision, i.e., the place to round relative to the decimal
point. The precision must be a integer. Setting the precision to $P means that
each number is rounded up or down, depending on the rounding mode, to the
nearest multiple of 10**$P. If the precision is set to C<undef>, no rounding is
done.

You might want to use L</accuracy()> instead. With L</accuracy()> you set the
number of digits each result should have, with L</precision()> you set the
place where to round.

Please see the section about L</ACCURACY and PRECISION> for further details.

    $y = Math::BigInt->new(1234567);    # $y is not rounded
    Math::BigInt->precision(4);         # set class precision to 4
    $x = Math::BigInt->new(1234567);    # $x is rounded automatically
    print $x;                           # prints "1230000"

Note: Each class has its own globals separated from Math::BigInt, but it is
possible to subclass Math::BigInt and make the globals of the subclass aliases
to the ones from Math::BigInt.

=item div_scale()

Set/get the fallback accuracy. This is the accuracy used when neither accuracy
nor precision is set explicitly. It is used when a computation might otherwise
attempt to return an infinite number of digits.

=item round_mode()

Set/get the rounding mode.

=item upgrade()

Set/get the class for upgrading. When a computation might result in a
non-integer, the operands are upgraded to this class. This is used for instance
by L<bignum>. The default is C<undef>, i.e., no upgrading.

    # with no upgrading
    $x = Math::BigInt->new(12);
    $y = Math::BigInt->new(5);
    print $x / $y, "\n";                # 2 as a Math::BigInt

    # with upgrading to Math::BigFloat
    Math::BigInt -> upgrade("Math::BigFloat");
    print $x / $y, "\n";                # 2.4 as a Math::BigFloat

    # with upgrading to Math::BigRat (after loading Math::BigRat)
    Math::BigInt -> upgrade("Math::BigRat");
    print $x / $y, "\n";                # 12/5 as a Math::BigRat

=item downgrade()

Set/get the class for downgrading. The default is C<undef>, i.e., no
downgrading. Downgrading is not done by Math::BigInt.

=item modify()

    $x->modify('bpowd');

This method returns 0 if the object can be modified with the given operation,
or 1 if not.

This is used for instance by L<Math::BigInt::Constant>.

=item config()

    Math::BigInt->config("trap_nan" => 1);      # set
    $accu = Math::BigInt->config("accuracy");   # get

Set or get class variables. Read-only parameters are marked as RO. Read-write
parameters are marked as RW. The following parameters are supported.

    Parameter       RO/RW   Description
                            Example
    ============================================================
    lib             RO      Name of the math backend library
                            Math::BigInt::Calc
    lib_version     RO      Version of the math backend library
                            0.30
    class           RO      The class of config you just called
                            Math::BigRat
    version         RO      version number of the class you used
                            0.10
    upgrade         RW      To which class numbers are upgraded
                            undef
    downgrade       RW      To which class numbers are downgraded
                            undef
    precision       RW      Global precision
                            undef
    accuracy        RW      Global accuracy
                            undef
    round_mode      RW      Global round mode
                            even
    div_scale       RW      Fallback accuracy for division etc.
                            40
    trap_nan        RW      Trap NaNs
                            undef
    trap_inf        RW      Trap +inf/-inf
                            undef

=back

=head2 Constructor methods

=over

=item new()

    $x = Math::BigInt->new($str,$A,$P,$R);

Creates a new Math::BigInt object from a scalar or another Math::BigInt object.
The input is accepted as decimal, hexadecimal (with leading '0x'), octal (with
leading ('0o') or binary (with leading '0b').

See L</Input> for more info on accepted input formats.

=item from_dec()

    $x = Math::BigInt->from_dec("314159");    # input is decimal

Interpret input as a decimal. It is equivalent to new(), but does not accept
anything but strings representing finite, decimal numbers.

=item from_hex()

    $x = Math::BigInt->from_hex("0xcafe");    # input is hexadecimal

Interpret input as a hexadecimal string. A "0x" or "x" prefix is optional. A
single underscore character may be placed right after the prefix, if present,
or between any two digits. If the input is invalid, a NaN is returned.

=item from_oct()

    $x = Math::BigInt->from_oct("0775");      # input is octal

Interpret the input as an octal string and return the corresponding value. A
"0" (zero) prefix is optional. A single underscore character may be placed
right after the prefix, if present, or between any two digits. If the input is
invalid, a NaN is returned.

=item from_bin()

    $x = Math::BigInt->from_bin("0b10011");   # input is binary

Interpret the input as a binary string. A "0b" or "b" prefix is optional. A
single underscore character may be placed right after the prefix, if present,
or between any two digits. If the input is invalid, a NaN is returned.

=item from_bytes()

    $x = Math::BigInt->from_bytes("\xf3\x6b");  # $x = 62315

Interpret the input as a byte string, assuming big endian byte order. The
output is always a non-negative, finite integer.

In some special cases, from_bytes() matches the conversion done by unpack():

    $b = "\x4e";                             # one char byte string
    $x = Math::BigInt->from_bytes($b);       # = 78
    $y = unpack "C", $b;                     # ditto, but scalar

    $b = "\xf3\x6b";                         # two char byte string
    $x = Math::BigInt->from_bytes($b);       # = 62315
    $y = unpack "S>", $b;                    # ditto, but scalar

    $b = "\x2d\xe0\x49\xad";                 # four char byte string
    $x = Math::BigInt->from_bytes($b);       # = 769673645
    $y = unpack "L>", $b;                    # ditto, but scalar

    $b = "\x2d\xe0\x49\xad\x2d\xe0\x49\xad"; # eight char byte string
    $x = Math::BigInt->from_bytes($b);       # = 3305723134637787565
    $y = unpack "Q>", $b;                    # ditto, but scalar

=item from_base()

Given a string, a base, and an optional collation sequence, interpret the
string as a number in the given base. The collation sequence describes the
value of each character in the string.

If a collation sequence is not given, a default collation sequence is used. If
the base is less than or equal to 36, the collation sequence is the string
consisting of the 36 characters "0" to "9" and "A" to "Z". In this case, the
letter case in the input is ignored. If the base is greater than 36, and
smaller than or equal to 62, the collation sequence is the string consisting of
the 62 characters "0" to "9", "A" to "Z", and "a" to "z". A base larger than 62
requires the collation sequence to be specified explicitly.

These examples show standard binary, octal, and hexadecimal conversion. All
cases return 250.

    $x = Math::BigInt->from_base("11111010", 2);
    $x = Math::BigInt->from_base("372", 8);
    $x = Math::BigInt->from_base("fa", 16);

When the base is less than or equal to 36, and no collation sequence is given,
the letter case is ignored, so both of these also return 250:

    $x = Math::BigInt->from_base("6Y", 16);
    $x = Math::BigInt->from_base("6y", 16);

When the base greater than 36, and no collation sequence is given, the default
collation sequence contains both uppercase and lowercase letters, so
the letter case in the input is not ignored:

    $x = Math::BigInt->from_base("6S", 37);         # $x is 250
    $x = Math::BigInt->from_base("6s", 37);         # $x is 276
    $x = Math::BigInt->from_base("121", 3);         # $x is 16
    $x = Math::BigInt->from_base("XYZ", 36);        # $x is 44027
    $x = Math::BigInt->from_base("Why", 42);        # $x is 58314

The collation sequence can be any set of unique characters. These two cases
are equivalent

    $x = Math::BigInt->from_base("100", 2, "01");   # $x is 4
    $x = Math::BigInt->from_base("|--", 2, "-|");   # $x is 4

=item from_base_num()

Returns a new Math::BigInt object given an array of values and a base. This
method is equivalent to C<from_base()>, but works on numbers in an array rather
than characters in a string. Unlike C<from_base()>, all input values may be
arbitrarily large.

    $x = Math::BigInt->from_base_num([1, 1, 0, 1], 2)     # $x is 13
    $x = Math::BigInt->from_base_num([3, 125, 39], 128)   # $x is 65191

=item bzero()

    $x = Math::BigInt->bzero();
    $x->bzero();

Returns a new Math::BigInt object representing zero. If used as an instance
method, assigns the value to the invocand.

=item bone()

    $x = Math::BigInt->bone();          # +1
    $x = Math::BigInt->bone("+");       # +1
    $x = Math::BigInt->bone("-");       # -1
    $x->bone();                         # +1
    $x->bone("+");                      # +1
    $x->bone('-');                      # -1

Creates a new Math::BigInt object representing one. The optional argument is
either '-' or '+', indicating whether you want plus one or minus one. If used
as an instance method, assigns the value to the invocand.

=item binf()

    $x = Math::BigInt->binf($sign);

Creates a new Math::BigInt object representing infinity. The optional argument
is either '-' or '+', indicating whether you want infinity or minus infinity.
If used as an instance method, assigns the value to the invocand.

    $x->binf();
    $x->binf('-');

=item bnan()

    $x = Math::BigInt->bnan();

Creates a new Math::BigInt object representing NaN (Not A Number). If used as
an instance method, assigns the value to the invocand.

    $x->bnan();

=item bpi()

    $x = Math::BigInt->bpi(100);        # 3
    $x->bpi(100);                       # 3

Creates a new Math::BigInt object representing PI. If used as an instance
method, assigns the value to the invocand. With Math::BigInt this always
returns 3.

If upgrading is in effect, returns PI, rounded to N digits with the current
rounding mode:

    use Math::BigFloat;
    use Math::BigInt upgrade => "Math::BigFloat";
    print Math::BigInt->bpi(3), "\n";           # 3.14
    print Math::BigInt->bpi(100), "\n";         # 3.1415....

=item copy()

    $x->copy();         # make a true copy of $x (unlike $y = $x)

=item as_int()

=item as_number()

These methods are called when Math::BigInt encounters an object it doesn't know
how to handle. For instance, assume $x is a Math::BigInt, or subclass thereof,
and $y is defined, but not a Math::BigInt, or subclass thereof. If you do

    $x -> badd($y);

$y needs to be converted into an object that $x can deal with. This is done by
first checking if $y is something that $x might be upgraded to. If that is the
case, no further attempts are made. The next is to see if $y supports the
method C<as_int()>. If it does, C<as_int()> is called, but if it doesn't, the
next thing is to see if $y supports the method C<as_number()>. If it does,
C<as_number()> is called. The method C<as_int()> (and C<as_number()>) is
expected to return either an object that has the same class as $x, a subclass
thereof, or a string that C<ref($x)-E<gt>new()> can parse to create an object.

C<as_number()> is an alias to C<as_int()>. C<as_number> was introduced in
v1.22, while C<as_int()> was introduced in v1.68.

In Math::BigInt, C<as_int()> has the same effect as C<copy()>.

=back

=head2 Boolean methods

None of these methods modify the invocand object.

=over

=item is_zero()

    $x->is_zero();              # true if $x is 0

Returns true if the invocand is zero and false otherwise.

=item is_one( [ SIGN ])

    $x->is_one();               # true if $x is +1
    $x->is_one("+");            # ditto
    $x->is_one("-");            # true if $x is -1

Returns true if the invocand is one and false otherwise.

=item is_finite()

    $x->is_finite();    # true if $x is not +inf, -inf or NaN

Returns true if the invocand is a finite number, i.e., it is neither +inf,
-inf, nor NaN.

=item is_inf( [ SIGN ] )

    $x->is_inf();               # true if $x is +inf
    $x->is_inf("+");            # ditto
    $x->is_inf("-");            # true if $x is -inf

Returns true if the invocand is infinite and false otherwise.

=item is_nan()

    $x->is_nan();               # true if $x is NaN

=item is_positive()

=item is_pos()

    $x->is_positive();          # true if > 0
    $x->is_pos();               # ditto

Returns true if the invocand is positive and false otherwise. A C<NaN> is
neither positive nor negative.

=item is_negative()

=item is_neg()

    $x->is_negative();          # true if < 0
    $x->is_neg();               # ditto

Returns true if the invocand is negative and false otherwise. A C<NaN> is
neither positive nor negative.

=item is_non_positive()

    $x->is_non_positive();      # true if <= 0

Returns true if the invocand is negative or zero.

=item is_non_negative()

    $x->is_non_negative();      # true if >= 0

Returns true if the invocand is positive or zero.

=item is_odd()

    $x->is_odd();               # true if odd, false for even

Returns true if the invocand is odd and false otherwise. C<NaN>, C<+inf>, and
C<-inf> are neither odd nor even.

=item is_even()

    $x->is_even();              # true if $x is even

Returns true if the invocand is even and false otherwise. C<NaN>, C<+inf>,
C<-inf> are not integers and are neither odd nor even.

=item is_int()

    $x->is_int();               # true if $x is an integer

Returns true if the invocand is an integer and false otherwise. C<NaN>,
C<+inf>, C<-inf> are not integers.

=back

=head2 Comparison methods

None of these methods modify the invocand object. Note that a C<NaN> is neither
less than, greater than, or equal to anything else, even a C<NaN>.

=over

=item bcmp()

    $x->bcmp($y);

Returns -1, 0, 1 depending on whether $x is less than, equal to, or grater than
$y. Returns undef if any operand is a NaN.

=item bacmp()

    $x->bacmp($y);

Returns -1, 0, 1 depending on whether the absolute value of $x is less than,
equal to, or grater than the absolute value of $y. Returns undef if any operand
is a NaN.

=item beq()

    $x -> beq($y);

Returns true if and only if $x is equal to $y, and false otherwise.

=item bne()

    $x -> bne($y);

Returns true if and only if $x is not equal to $y, and false otherwise.

=item blt()

    $x -> blt($y);

Returns true if and only if $x is equal to $y, and false otherwise.

=item ble()

    $x -> ble($y);

Returns true if and only if $x is less than or equal to $y, and false
otherwise.

=item bgt()

    $x -> bgt($y);

Returns true if and only if $x is greater than $y, and false otherwise.

=item bge()

    $x -> bge($y);

Returns true if and only if $x is greater than or equal to $y, and false
otherwise.

=back

=head2 Arithmetic methods

These methods modify the invocand object and returns it.

=over

=item bneg()

    $x->bneg();

Negate the number, e.g. change the sign between '+' and '-', or between '+inf'
and '-inf', respectively. Does nothing for NaN or zero.

=item babs()

    $x->babs();

Set the number to its absolute value, e.g. change the sign from '-' to '+'
and from '-inf' to '+inf', respectively. Does nothing for NaN or positive
numbers.

=item bsgn()

    $x->bsgn();

Signum function. Set the number to -1, 0, or 1, depending on whether the
number is negative, zero, or positive, respectively. Does not modify NaNs.

=item bnorm()

    $x->bnorm();                        # normalize (no-op)

Normalize the number. This is a no-op and is provided only for backwards
compatibility.

=item binc()

    $x->binc();                 # increment x by 1

=item bdec()

    $x->bdec();                 # decrement x by 1

=item badd()

    $x->badd($y);               # addition (add $y to $x)

=item bsub()

    $x->bsub($y);               # subtraction (subtract $y from $x)

=item bmul()

    $x->bmul($y);               # multiplication (multiply $x by $y)

=item bmuladd()

    $x->bmuladd($y,$z);

Multiply $x by $y, and then add $z to the result,

This method was added in v1.87 of Math::BigInt (June 2007).

=item bdiv()

    $x->bdiv($y);               # divide, set $x to quotient

Divides $x by $y by doing floored division (F-division), where the quotient is
the floored (rounded towards negative infinity) quotient of the two operands.
In list context, returns the quotient and the remainder. The remainder is
either zero or has the same sign as the second operand. In scalar context, only
the quotient is returned.

The quotient is always the greatest integer less than or equal to the
real-valued quotient of the two operands, and the remainder (when it is
non-zero) always has the same sign as the second operand; so, for example,

      1 /  4  => ( 0,  1)
      1 / -4  => (-1, -3)
     -3 /  4  => (-1,  1)
     -3 / -4  => ( 0, -3)
    -11 /  2  => (-5,  1)
     11 / -2  => (-5, -1)

The behavior of the overloaded operator % agrees with the behavior of Perl's
built-in % operator (as documented in the perlop manpage), and the equation

    $x == ($x / $y) * $y + ($x % $y)

holds true for any finite $x and finite, non-zero $y.

Perl's "use integer" might change the behaviour of % and / for scalars. This is
because under 'use integer' Perl does what the underlying C library thinks is
right, and this varies. However, "use integer" does not change the way things
are done with Math::BigInt objects.

=item btdiv()

    $x->btdiv($y);              # divide, set $x to quotient

Divides $x by $y by doing truncated division (T-division), where quotient is
the truncated (rouneded towards zero) quotient of the two operands. In list
context, returns the quotient and the remainder. The remainder is either zero
or has the same sign as the first operand. In scalar context, only the quotient
is returned.

=item bmod()

    $x->bmod($y);               # modulus (x % y)

Returns $x modulo $y, i.e., the remainder after floored division (F-division).
This method is like Perl's % operator. See L</bdiv()>.

=item btmod()

    $x->btmod($y);              # modulus

Returns the remainer after truncated division (T-division). See L</btdiv()>.

=item bmodinv()

    $x->bmodinv($mod);          # modular multiplicative inverse

Returns the multiplicative inverse of C<$x> modulo C<$mod>. If

    $y = $x -> copy() -> bmodinv($mod)

then C<$y> is the number closest to zero, and with the same sign as C<$mod>,
satisfying

    ($x * $y) % $mod = 1 % $mod

If C<$x> and C<$y> are non-zero, they must be relative primes, i.e.,
C<bgcd($y, $mod)==1>. 'C<NaN>' is returned when no modular multiplicative
inverse exists.

=item bmodpow()

    $num->bmodpow($exp,$mod);           # modular exponentiation
                                        # ($num**$exp % $mod)

Returns the value of C<$num> taken to the power C<$exp> in the modulus
C<$mod> using binary exponentiation.  C<bmodpow> is far superior to
writing

    $num ** $exp % $mod

because it is much faster - it reduces internal variables into
the modulus whenever possible, so it operates on smaller numbers.

C<bmodpow> also supports negative exponents.

    bmodpow($num, -1, $mod)

is exactly equivalent to

    bmodinv($num, $mod)

=item bpow()

    $x->bpow($y);               # power of arguments (x ** y)

C<bpow()> (and the rounding functions) now modifies the first argument and
returns it, unlike the old code which left it alone and only returned the
result. This is to be consistent with C<badd()> etc. The first three modifies
$x, the last one won't:

    print bpow($x,$i),"\n";         # modify $x
    print $x->bpow($i),"\n";        # ditto
    print $x **= $i,"\n";           # the same
    print $x ** $i,"\n";            # leave $x alone

The form C<$x **= $y> is faster than C<$x = $x ** $y;>, though.

=item blog()

    $x->blog($base, $accuracy);         # logarithm of x to the base $base

If C<$base> is not defined, Euler's number (e) is used:

    print $x->blog(undef, 100);         # log(x) to 100 digits

=item bexp()

    $x->bexp($accuracy);                # calculate e ** X

Calculates the expression C<e ** $x> where C<e> is Euler's number.

This method was added in v1.82 of Math::BigInt (April 2007).

See also L</blog()>.

=item bnok()

    $x->bnok($y);               # x over y (binomial coefficient n over k)

Calculates the binomial coefficient n over k, also called the "choose"
function, which is

    ( n )       n!
    |   |  = --------
    ( k )    k!(n-k)!

when n and k are non-negative. This method implements the full Kronenburg
extension (Kronenburg, M.J. "The Binomial Coefficient for Negative Arguments."
18 May 2011. http://arxiv.org/abs/1105.3689/) illustrated by the following
pseudo-code:

    if n >= 0 and k >= 0:
        return binomial(n, k)
    if k >= 0:
        return (-1)^k*binomial(-n+k-1, k)
    if k <= n:
        return (-1)^(n-k)*binomial(-k-1, n-k)
    else
        return 0

The behaviour is identical to the behaviour of the Maple and Mathematica
function for negative integers n, k.

=item buparrow()

=item uparrow()

    $a -> buparrow($n, $b);         # modifies $a
    $x = $a -> uparrow($n, $b);     # does not modify $a

This method implements Knuth's up-arrow notation, where $n is a non-negative
integer representing the number of up-arrows. $n = 0 gives multiplication, $n =
1 gives exponentiation, $n = 2 gives tetration, $n = 3 gives hexation etc. The
following illustrates the relation between the first values of $n.

See L<https://en.wikipedia.org/wiki/Knuth%27s_up-arrow_notation>.

=item backermann()

=item ackermann()

    $m -> backermann($n);           # modifies $a
    $x = $m -> ackermann($n);       # does not modify $a

This method implements the Ackermann function:

             / n + 1              if m = 0
   A(m, n) = | A(m-1, 1)          if m > 0 and n = 0
             \ A(m-1, A(m, n-1))  if m > 0 and n > 0

Its value grows rapidly, even for small inputs. For example, A(4, 2) is an
integer of 19729 decimal digits.

See https://en.wikipedia.org/wiki/Ackermann_function

=item bsin()

    my $x = Math::BigInt->new(1);
    print $x->bsin(100), "\n";

Calculate the sine of $x, modifying $x in place.

In Math::BigInt, unless upgrading is in effect, the result is truncated to an
integer.

This method was added in v1.87 of Math::BigInt (June 2007).

=item bcos()

    my $x = Math::BigInt->new(1);
    print $x->bcos(100), "\n";

Calculate the cosine of $x, modifying $x in place.

In Math::BigInt, unless upgrading is in effect, the result is truncated to an
integer.

This method was added in v1.87 of Math::BigInt (June 2007).

=item batan()

    my $x = Math::BigFloat->new(0.5);
    print $x->batan(100), "\n";

Calculate the arcus tangens of $x, modifying $x in place.

In Math::BigInt, unless upgrading is in effect, the result is truncated to an
integer.

This method was added in v1.87 of Math::BigInt (June 2007).

=item batan2()

    my $x = Math::BigInt->new(1);
    my $y = Math::BigInt->new(1);
    print $y->batan2($x), "\n";

Calculate the arcus tangens of C<$y> divided by C<$x>, modifying $y in place.

In Math::BigInt, unless upgrading is in effect, the result is truncated to an
integer.

This method was added in v1.87 of Math::BigInt (June 2007).

=item bsqrt()

    $x->bsqrt();                # calculate square root

C<bsqrt()> returns the square root truncated to an integer.

If you want a better approximation of the square root, then use:

    $x = Math::BigFloat->new(12);
    Math::BigFloat->precision(0);
    Math::BigFloat->round_mode('even');
    print $x->copy->bsqrt(),"\n";           # 4

    Math::BigFloat->precision(2);
    print $x->bsqrt(),"\n";                 # 3.46
    print $x->bsqrt(3),"\n";                # 3.464

=item broot()

    $x->broot($N);

Calculates the N'th root of C<$x>.

=item bfac()

    $x->bfac();             # factorial of $x

Returns the factorial of C<$x>, i.e., $x*($x-1)*($x-2)*...*2*1, the product of
all positive integers up to and including C<$x>. C<$x> must be > -1. The
factorial of N is commonly written as N!, or N!1, when using the multifactorial
notation.

=item bdfac()

    $x->bdfac();                # double factorial of $x

Returns the double factorial of C<$x>, i.e., $x*($x-2)*($x-4)*... C<$x> must be
> -2. The double factorial of N is commonly written as N!!, or N!2, when using
the multifactorial notation.

=item btfac()

    $x->btfac();            # triple factorial of $x

Returns the triple factorial of C<$x>, i.e., $x*($x-3)*($x-6)*... C<$x> must be
> -3. The triple factorial of N is commonly written as N!!!, or N!3, when using
the multifactorial notation.

=item bmfac()

    $x->bmfac($k);          # $k'th multifactorial of $x

Returns the multi-factorial of C<$x>, i.e., $x*($x-$k)*($x-2*$k)*... C<$x> must
be > -$k. The multi-factorial of N is commonly written as N!K.

=item bfib()

    $F = $n->bfib();            # a single Fibonacci number
    @F = $n->bfib();            # a list of Fibonacci numbers

In scalar context, returns a single Fibonacci number. In list context, returns
a list of Fibonacci numbers. The invocand is the last element in the output.

The Fibonacci sequence is defined by

    F(0) = 0
    F(1) = 1
    F(n) = F(n-1) + F(n-2)

In list context, F(0) and F(n) is the first and last number in the output,
respectively. For example, if $n is 12, then C<< @F = $n->bfib() >> returns the
following values, F(0) to F(12):

    0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144

The sequence can also be extended to negative index n using the re-arranged
recurrence relation

    F(n-2) = F(n) - F(n-1)

giving the bidirectional sequence

       n  -7  -6  -5  -4  -3  -2  -1   0   1   2   3   4   5   6   7
    F(n)  13  -8   5  -3   2  -1   1   0   1   1   2   3   5   8  13

If $n is -12, the following values, F(0) to F(12), are returned:

    0, 1, -1, 2, -3, 5, -8, 13, -21, 34, -55, 89, -144

=item blucas()

    $F = $n->blucas();          # a single Lucas number
    @F = $n->blucas();          # a list of Lucas numbers

In scalar context, returns a single Lucas number. In list context, returns a
list of Lucas numbers. The invocand is the last element in the output.

The Lucas sequence is defined by

    L(0) = 2
    L(1) = 1
    L(n) = L(n-1) + L(n-2)

In list context, L(0) and L(n) is the first and last number in the output,
respectively. For example, if $n is 12, then C<< @L = $n->blucas() >> returns
the following values, L(0) to L(12):

    2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, 199, 322

The sequence can also be extended to negative index n using the re-arranged
recurrence relation

    L(n-2) = L(n) - L(n-1)

giving the bidirectional sequence

       n  -7  -6  -5  -4  -3  -2  -1   0   1   2   3   4   5   6   7
    L(n)  29 -18  11  -7   4  -3   1   2   1   3   4   7  11  18  29

If $n is -12, the following values, L(0) to L(-12), are returned:

    2, 1, -3, 4, -7, 11, -18, 29, -47, 76, -123, 199, -322

=item brsft()

    $x->brsft($n);              # right shift $n places in base 2
    $x->brsft($n, $b);          # right shift $n places in base $b

The latter is equivalent to

    $x -> bdiv($b -> copy() -> bpow($n))

=item blsft()

    $x->blsft($n);              # left shift $n places in base 2
    $x->blsft($n, $b);          # left shift $n places in base $b

The latter is equivalent to

    $x -> bmul($b -> copy() -> bpow($n))

=back

=head2 Bitwise methods

=over

=item band()

    $x->band($y);               # bitwise and

=item bior()

    $x->bior($y);               # bitwise inclusive or

=item bxor()

    $x->bxor($y);               # bitwise exclusive or

=item bnot()

    $x->bnot();                 # bitwise not (two's complement)

Two's complement (bitwise not). This is equivalent to, but faster than,

    $x->binc()->bneg();

=back

=head2 Rounding methods

=over

=item round()

    $x->round($A,$P,$round_mode);

Round $x to accuracy C<$A> or precision C<$P> using the round mode
C<$round_mode>.

=item bround()

    $x->bround($N);               # accuracy: preserve $N digits

Rounds $x to an accuracy of $N digits.

=item bfround()

    $x->bfround($N);

Rounds to a multiple of 10**$N. Examples:

    Input            N          Result

    123456.123456    3          123500
    123456.123456    2          123450
    123456.123456   -2          123456.12
    123456.123456   -3          123456.123

=item bfloor()

    $x->bfloor();

Round $x towards minus infinity, i.e., set $x to the largest integer less than
or equal to $x.

=item bceil()

    $x->bceil();

Round $x towards plus infinity, i.e., set $x to the smallest integer greater
than or equal to $x).

=item bint()

    $x->bint();

Round $x towards zero.

=back

=head2 Other mathematical methods

=over

=item bgcd()

    $x -> bgcd($y);             # GCD of $x and $y
    $x -> bgcd($y, $z, ...);    # GCD of $x, $y, $z, ...

Returns the greatest common divisor (GCD).

=item blcm()

    $x -> blcm($y);             # LCM of $x and $y
    $x -> blcm($y, $z, ...);    # LCM of $x, $y, $z, ...

Returns the least common multiple (LCM).

=back

=head2 Object property methods

=over

=item sign()

    $x->sign();

Return the sign, of $x, meaning either C<+>, C<->, C<-inf>, C<+inf> or NaN.

If you want $x to have a certain sign, use one of the following methods:

    $x->babs();                 # '+'
    $x->babs()->bneg();         # '-'
    $x->bnan();                 # 'NaN'
    $x->binf();                 # '+inf'
    $x->binf('-');              # '-inf'

=item digit()

    $x->digit($n);       # return the nth digit, counting from right

If C<$n> is negative, returns the digit counting from left.

=item digitsum()

    $x->digitsum();

Computes the sum of the base 10 digits and returns it.

=item bdigitsum()

    $x->bdigitsum();

Computes the sum of the base 10 digits and assigns the result to the invocand.

=item length()

    $x->length();
    ($xl, $fl) = $x->length();

Returns the number of digits in the decimal representation of the number. In
list context, returns the length of the integer and fraction part. For
Math::BigInt objects, the length of the fraction part is always 0.

The following probably doesn't do what you expect:

    $c = Math::BigInt->new(123);
    print $c->length(),"\n";                # prints 30

It prints both the number of digits in the number and in the fraction part
since print calls C<length()> in list context. Use something like:

    print scalar $c->length(),"\n";         # prints 3

=item mantissa()

    $x->mantissa();

Return the signed mantissa of $x as a Math::BigInt.

=item exponent()

    $x->exponent();

Return the exponent of $x as a Math::BigInt.

=item parts()

    $x->parts();

Returns the significand (mantissa) and the exponent as integers. In
Math::BigFloat, both are returned as Math::BigInt objects.

=item sparts()

Returns the significand (mantissa) and the exponent as integers. In scalar
context, only the significand is returned. The significand is the integer with
the smallest absolute value. The output of C<sparts()> corresponds to the
output from C<bsstr()>.

In Math::BigInt, this method is identical to C<parts()>.

=item nparts()

Returns the significand (mantissa) and exponent corresponding to normalized
notation. In scalar context, only the significand is returned. For finite
non-zero numbers, the significand's absolute value is greater than or equal to
1 and less than 10. The output of C<nparts()> corresponds to the output from
C<bnstr()>. In Math::BigInt, if the significand can not be represented as an
integer, upgrading is performed or NaN is returned.

=item eparts()

Returns the significand (mantissa) and exponent corresponding to engineering
notation. In scalar context, only the significand is returned. For finite
non-zero numbers, the significand's absolute value is greater than or equal to
1 and less than 1000, and the exponent is a multiple of 3. The output of
C<eparts()> corresponds to the output from C<bestr()>. In Math::BigInt, if the
significand can not be represented as an integer, upgrading is performed or NaN
is returned.

=item dparts()

Returns the integer part and the fraction part. If the fraction part can not be
represented as an integer, upgrading is performed or NaN is returned. The
output of C<dparts()> corresponds to the output from C<bdstr()>.

=item fparts()

Returns the smallest possible numerator and denominator so that the numerator
divided by the denominator gives back the original value. For finite numbers,
both values are integers. Mnemonic: fraction.

=item numerator()

Together with L</denominator()>, returns the smallest integers so that the
numerator divided by the denominator reproduces the original value. With
Math::BigInt, numerator() simply returns a copy of the invocand.

=item denominator()

Together with L</numerator()>, returns the smallest integers so that the
numerator divided by the denominator reproduces the original value. With
Math::BigInt, denominator() always returns either a 1 or a NaN.

=back

=head2 String conversion methods

=over

=item bstr()

Returns a string representing the number using decimal notation. In
Math::BigFloat, the output is zero padded according to the current accuracy or
precision, if any of those are defined.

=item bsstr()

Returns a string representing the number using scientific notation where both
the significand (mantissa) and the exponent are integers. The output
corresponds to the output from C<sparts()>.

      123 is returned as "123e+0"
     1230 is returned as "123e+1"
    12300 is returned as "123e+2"
    12000 is returned as "12e+3"
    10000 is returned as "1e+4"

=item bnstr()

Returns a string representing the number using normalized notation, the most
common variant of scientific notation. For finite non-zero numbers, the
absolute value of the significand is greater than or equal to 1 and less than
10. The output corresponds to the output from C<nparts()>.

      123 is returned as "1.23e+2"
     1230 is returned as "1.23e+3"
    12300 is returned as "1.23e+4"
    12000 is returned as "1.2e+4"
    10000 is returned as "1e+4"

=item bestr()

Returns a string representing the number using engineering notation. For finite
non-zero numbers, the absolute value of the significand is greater than or
equal to 1 and less than 1000, and the exponent is a multiple of 3. The output
corresponds to the output from C<eparts()>.

      123 is returned as "123e+0"
     1230 is returned as "1.23e+3"
    12300 is returned as "12.3e+3"
    12000 is returned as "12e+3"
    10000 is returned as "10e+3"

=item bdstr()

Returns a string representing the number using decimal notation. The output
corresponds to the output from C<dparts()>.

      123 is returned as "123"
     1230 is returned as "1230"
    12300 is returned as "12300"
    12000 is returned as "12000"
    10000 is returned as "10000"

=item to_hex()

    $x->to_hex();

Returns a hexadecimal string representation of the number. See also from_hex().

=item to_bin()

    $x->to_bin();

Returns a binary string representation of the number. See also from_bin().

=item to_oct()

    $x->to_oct();

Returns an octal string representation of the number. See also from_oct().

=item to_bytes()

    $x = Math::BigInt->new("1667327589");
    $s = $x->to_bytes();                    # $s = "cafe"

Returns a byte string representation of the number using big endian byte
order. The invocand must be a non-negative, finite integer. See also from_bytes().

=item to_base()

    $x = Math::BigInt->new("250");
    $x->to_base(2);     # returns "11111010"
    $x->to_base(8);     # returns "372"
    $x->to_base(16);    # returns "fa"

Returns a string representation of the number in the given base. If a collation
sequence is given, the collation sequence determines which characters are used
in the output.

Here are some more examples

    $x = Math::BigInt->new("16")->to_base(3);       # returns "121"
    $x = Math::BigInt->new("44027")->to_base(36);   # returns "XYZ"
    $x = Math::BigInt->new("58314")->to_base(42);   # returns "Why"
    $x = Math::BigInt->new("4")->to_base(2, "-|");  # returns "|--"

See from_base() for information and examples.

=item to_base_num()

Converts the given number to the given base. This method is equivalent to
C<_to_base()>, but returns numbers in an array rather than characters in a
string. In the output, the first element is the most significant. Unlike
C<_to_base()>, all input values may be arbitrarily large.

    $x = Math::BigInt->new(13);
    $x->to_base_num(2);                         # returns [1, 1, 0, 1]

    $x = Math::BigInt->new(65191);
    $x->to_base_num(128);                       # returns [3, 125, 39]

=item as_hex()

    $x->as_hex();

As, C<to_hex()>, but with a "0x" prefix.

=item as_bin()

    $x->as_bin();

As, C<to_bin()>, but with a "0b" prefix.

=item as_oct()

    $x->as_oct();

As, C<to_oct()>, but with a "0" prefix.

=item as_bytes()

This is just an alias for C<to_bytes()>.

=back

=head2 Other conversion methods

=over

=item numify()

    print $x->numify();

Returns a Perl scalar from $x. It is used automatically whenever a scalar is
needed, for instance in array index operations.

=back

=head2 Utility methods

These utility methods are made public

=over

=item dec_str_to_dec_flt_str()

Takes a string representing any valid number using decimal notation and converts
it to a string representing the same number using decimal floating point
notation. The output consists of five parts joined together: the sign of the
significand, the absolute value of the significand as the smallest possible
integer, the letter "e", the sign of the exponent, and the absolute value of the
exponent. If the input is invalid, nothing is returned.

    $str2 = $class -> dec_str_to_dec_flt_str($str1);

Some examples

    Input           Output
    31400.00e-4     +314e-2
    -0.00012300e8   -123e+2
    0               +0e+0

=item hex_str_to_dec_flt_str()

Takes a string representing any valid number using hexadecimal notation and
converts it to a string representing the same number using decimal floating
point notation. The output has the same format as that of
L</dec_str_to_dec_flt_str()>.

    $str2 = $class -> hex_str_to_dec_flt_str($str1);

Some examples

    Input           Output
    0xff            +255e+0

Some examples

=item oct_str_to_dec_flt_str()

Takes a string representing any valid number using octal notation and converts
it to a string representing the same number using decimal floating point
notation. The output has the same format as that of
L</dec_str_to_dec_flt_str()>.

    $str2 = $class -> oct_str_to_dec_flt_str($str1);

=item bin_str_to_dec_flt_str()

Takes a string representing any valid number using binary notation and converts
it to a string representing the same number using decimal floating point
notation. The output has the same format as that of
L</dec_str_to_dec_flt_str()>.

    $str2 = $class -> bin_str_to_dec_flt_str($str1);

=item dec_str_to_dec_str()

Takes a string representing any valid number using decimal notation and converts
it to a string representing the same number using decimal notation. If the
number represents an integer, the output consists of a sign and the absolute
value. If the number represents a non-integer, the output consists of a sign,
the integer part of the number, the decimal point ".", and the fraction part of
the number without any trailing zeros. If the input is invalid, nothing is
returned.

=item hex_str_to_dec_str()

Takes a string representing any valid number using hexadecimal notation and
converts it to a string representing the same number using decimal notation. The
output has the same format as that of L</dec_str_to_dec_str()>.

=item oct_str_to_dec_str()

Takes a string representing any valid number using octal notation and converts
it to a string representing the same number using decimal notation. The
output has the same format as that of L</dec_str_to_dec_str()>.

=item bin_str_to_dec_str()

Takes a string representing any valid number using binary notation and converts
it to a string representing the same number using decimal notation. The output
has the same format as that of L</dec_str_to_dec_str()>.

=back

=head1 ACCURACY and PRECISION

Math::BigInt and Math::BigFloat have full support for accuracy and precision
based rounding, both automatically after every operation, as well as manually.

This section describes the accuracy/precision handling in Math::BigInt and
Math::BigFloat as it used to be and as it is now, complete with an explanation
of all terms and abbreviations.

Not yet implemented things (but with correct description) are marked with '!',
things that need to be answered are marked with '?'.

In the next paragraph follows a short description of terms used here (because
these may differ from terms used by others people or documentation).

During the rest of this document, the shortcuts A (for accuracy), P (for
precision), F (fallback) and R (rounding mode) are be used.

=head2 Precision P

Precision is a fixed number of digits before (positive) or after (negative) the
decimal point. For example, 123.45 has a precision of -2. 0 means an integer
like 123 (or 120). A precision of 2 means at least two digits to the left of
the decimal point are zero, so 123 with P = 1 becomes 120. Note that numbers
with zeros before the decimal point may have different precisions, because 1200
can have P = 0, 1 or 2 (depending on what the initial value was). It could also
have p < 0, when the digits after the decimal point are zero.

The string output (of floating point numbers) is padded with zeros:

    Initial value    P      A       Result          String
    ------------------------------------------------------------
    1234.01         -3              1000            1000
    1234            -2              1200            1200
    1234.5          -1              1230            1230
    1234.001         1              1234            1234.0
    1234.01          0              1234            1234
    1234.01          2              1234.01         1234.01
    1234.01          5              1234.01         1234.01000

For Math::BigInt objects, no padding occurs.

=head2 Accuracy A

Number of significant digits. Leading zeros are not counted. A number may have
an accuracy greater than the non-zero digits when there are zeros in it or
trailing zeros. For example, 123.456 has A of 6, 10203 has 5, 123.0506 has 7,
123.45000 has 8 and 0.000123 has 3.

The string output (of floating point numbers) is padded with zeros:

    Initial value    P      A       Result          String
    ------------------------------------------------------------
    1234.01                 3       1230            1230
    1234.01                 6       1234.01         1234.01
    1234.1                  8       1234.1          1234.1000

For Math::BigInt objects, no padding occurs.

=head2 Fallback F

When both A and P are undefined, this is used as a fallback accuracy when
dividing numbers.

=head2 Rounding mode R

When rounding a number, different 'styles' or 'kinds' of rounding are possible.
(Note that random rounding, as in Math::Round, is not implemented.)

=head3 Directed rounding

These round modes always round in the same direction.

=over

=item 'trunc'

Round towards zero. Remove all digits following the rounding place, i.e.,
replace them with zeros. Thus, 987.65 rounded to tens (P=1) becomes 980, and
rounded to the fourth significant digit becomes 987.6 (A=4). 123.456 rounded to
the second place after the decimal point (P=-2) becomes 123.46. This
corresponds to the IEEE 754 rounding mode 'roundTowardZero'.

=back

=head3 Rounding to nearest

These rounding modes round to the nearest digit. They differ in how they
determine which way to round in the ambiguous case when there is a tie.

=over

=item 'even'

Round towards the nearest even digit, e.g., when rounding to nearest integer,
-5.5 becomes -6, 4.5 becomes 4, but 4.501 becomes 5. This corresponds to the
IEEE 754 rounding mode 'roundTiesToEven'.

=item 'odd'

Round towards the nearest odd digit, e.g., when rounding to nearest integer,
4.5 becomes 5, -5.5 becomes -5, but 5.501 becomes 6. This corresponds to the
IEEE 754 rounding mode 'roundTiesToOdd'.

=item '+inf'

Round towards plus infinity, i.e., always round up. E.g., when rounding to the
nearest integer, 4.5 becomes 5, -5.5 becomes -5, and 4.501 also becomes 5. This
corresponds to the IEEE 754 rounding mode 'roundTiesToPositive'.

=item '-inf'

Round towards minus infinity, i.e., always round down. E.g., when rounding to
the nearest integer, 4.5 becomes 4, -5.5 becomes -6, but 4.501 becomes 5. This
corresponds to the IEEE 754 rounding mode 'roundTiesToNegative'.

=item 'zero'

Round towards zero, i.e., round positive numbers down and negative numbers up.
E.g., when rounding to the nearest integer, 4.5 becomes 4, -5.5 becomes -5, but
4.501 becomes 5. This corresponds to the IEEE 754 rounding mode
'roundTiesToZero'.

=item 'common'

Round away from zero, i.e., round to the number with the largest absolute
value. E.g., when rounding to the nearest integer, -1.5 becomes -2, 1.5 becomes
2 and 1.49 becomes 1. This corresponds to the IEEE 754 rounding mode
'roundTiesToAway'.

=back

The handling of A & P in MBI/MBF (the old core code shipped with Perl versions
<= 5.7.2) is like this:

=over

=item Precision

  * bfround($p) is able to round to $p number of digits after the decimal
    point
  * otherwise P is unused

=item Accuracy (significant digits)

  * bround($a) rounds to $a significant digits
  * only bdiv() and bsqrt() take A as (optional) parameter
    + other operations simply create the same number (bneg etc), or
      more (bmul) of digits
    + rounding/truncating is only done when explicitly calling one
      of bround or bfround, and never for Math::BigInt (not implemented)
  * bsqrt() simply hands its accuracy argument over to bdiv.
  * the documentation and the comment in the code indicate two
    different ways on how bdiv() determines the maximum number
    of digits it should calculate, and the actual code does yet
    another thing
    POD:
      max($Math::BigFloat::div_scale,length(dividend)+length(divisor))
    Comment:
      result has at most max(scale, length(dividend), length(divisor)) digits
    Actual code:
      scale = max(scale, length(dividend)-1,length(divisor)-1);
      scale += length(divisor) - length(dividend);
    So for lx = 3, ly = 9, scale = 10, scale will actually be 16 (10
    So for lx = 3, ly = 9, scale = 10, scale will actually be 16
    (10+9-3). Actually, the 'difference' added to the scale is cal-
    culated from the number of "significant digits" in dividend and
    divisor, which is derived by looking at the length of the man-
    tissa. Which is wrong, since it includes the + sign (oops) and
    actually gets 2 for '+100' and 4 for '+101'. Oops again. Thus
    124/3 with div_scale=1 will get you '41.3' based on the strange
    assumption that 124 has 3 significant digits, while 120/7 will
    get you '17', not '17.1' since 120 is thought to have 2 signif-
    icant digits. The rounding after the division then uses the
    remainder and $y to determine whether it must round up or down.
 ?  I have no idea which is the right way. That's why I used a slightly more
 ?  simple scheme and tweaked the few failing testcases to match it.

=back

This is how it works now:

=over

=item Setting/Accessing

  * You can set the A global via Math::BigInt->accuracy() or
    Math::BigFloat->accuracy() or whatever class you are using.
  * You can also set P globally by using Math::SomeClass->precision()
    likewise.
  * Globals are classwide, and not inherited by subclasses.
  * to undefine A, use Math::SomeClass->accuracy(undef);
  * to undefine P, use Math::SomeClass->precision(undef);
  * Setting Math::SomeClass->accuracy() clears automatically
    Math::SomeClass->precision(), and vice versa.
  * To be valid, A must be > 0, P can have any value.
  * If P is negative, this means round to the P'th place to the right of the
    decimal point; positive values mean to the left of the decimal point.
    P of 0 means round to integer.
  * to find out the current global A, use Math::SomeClass->accuracy()
  * to find out the current global P, use Math::SomeClass->precision()
  * use $x->accuracy() respective $x->precision() for the local
    setting of $x.
  * Please note that $x->accuracy() respective $x->precision()
    return eventually defined global A or P, when $x's A or P is not
    set.

=item Creating numbers

  * When you create a number, you can give the desired A or P via:
    $x = Math::BigInt->new($number,$A,$P);
  * Only one of A or P can be defined, otherwise the result is NaN
  * If no A or P is give ($x = Math::BigInt->new($number) form), then the
    globals (if set) will be used. Thus changing the global defaults later on
    will not change the A or P of previously created numbers (i.e., A and P of
    $x will be what was in effect when $x was created)
  * If given undef for A and P, NO rounding will occur, and the globals will
    NOT be used. This is used by subclasses to create numbers without
    suffering rounding in the parent. Thus a subclass is able to have its own
    globals enforced upon creation of a number by using
    $x = Math::BigInt->new($number,undef,undef):

        use Math::BigInt::SomeSubclass;
        use Math::BigInt;

        Math::BigInt->accuracy(2);
        Math::BigInt::SomeSubclass->accuracy(3);
        $x = Math::BigInt::SomeSubclass->new(1234);

    $x is now 1230, and not 1200. A subclass might choose to implement
    this otherwise, e.g. falling back to the parent's A and P.

=item Usage

  * If A or P are enabled/defined, they are used to round the result of each
    operation according to the rules below
  * Negative P is ignored in Math::BigInt, since Math::BigInt objects never
    have digits after the decimal point
  * Math::BigFloat uses Math::BigInt internally, but setting A or P inside
    Math::BigInt as globals does not tamper with the parts of a Math::BigFloat.
    A flag is used to mark all Math::BigFloat numbers as 'never round'.

=item Precedence

  * It only makes sense that a number has only one of A or P at a time.
    If you set either A or P on one object, or globally, the other one will
    be automatically cleared.
  * If two objects are involved in an operation, and one of them has A in
    effect, and the other P, this results in an error (NaN).
  * A takes precedence over P (Hint: A comes before P).
    If neither of them is defined, nothing is used, i.e. the result will have
    as many digits as it can (with an exception for bdiv/bsqrt) and will not
    be rounded.
  * There is another setting for bdiv() (and thus for bsqrt()). If neither of
    A or P is defined, bdiv() will use a fallback (F) of $div_scale digits.
    If either the dividend's or the divisor's mantissa has more digits than
    the value of F, the higher value will be used instead of F.
    This is to limit the digits (A) of the result (just consider what would
    happen with unlimited A and P in the case of 1/3 :-)
  * bdiv will calculate (at least) 4 more digits than required (determined by
    A, P or F), and, if F is not used, round the result
    (this will still fail in the case of a result like 0.12345000000001 with A
    or P of 5, but this can not be helped - or can it?)
  * Thus you can have the math done by on Math::Big* class in two modi:
    + never round (this is the default):
      This is done by setting A and P to undef. No math operation
      will round the result, with bdiv() and bsqrt() as exceptions to guard
      against overflows. You must explicitly call bround(), bfround() or
      round() (the latter with parameters).
      Note: Once you have rounded a number, the settings will 'stick' on it
      and 'infect' all other numbers engaged in math operations with it, since
      local settings have the highest precedence. So, to get SaferRound[tm],
      use a copy() before rounding like this:

        $x = Math::BigFloat->new(12.34);
        $y = Math::BigFloat->new(98.76);
        $z = $x * $y;                           # 1218.6984
        print $x->copy()->bround(3);            # 12.3 (but A is now 3!)
        $z = $x * $y;                           # still 1218.6984, without
                                                # copy would have been 1210!

    + round after each op:
      After each single operation (except for testing like is_zero()), the
      method round() is called and the result is rounded appropriately. By
      setting proper values for A and P, you can have all-the-same-A or
      all-the-same-P modes. For example, Math::Currency might set A to undef,
      and P to -2, globally.

 ?Maybe an extra option that forbids local A & P settings would be in order,
 ?so that intermediate rounding does not 'poison' further math?

=item Overriding globals

  * you will be able to give A, P and R as an argument to all the calculation
    routines; the second parameter is A, the third one is P, and the fourth is
    R (shift right by one for binary operations like badd). P is used only if
    the first parameter (A) is undefined. These three parameters override the
    globals in the order detailed as follows, i.e. the first defined value
    wins:
    (local: per object, global: global default, parameter: argument to sub)
      + parameter A
      + parameter P
      + local A (if defined on both of the operands: smaller one is taken)
      + local P (if defined on both of the operands: bigger one is taken)
      + global A
      + global P
      + global F
  * bsqrt() will hand its arguments to bdiv(), as it used to, only now for two
    arguments (A and P) instead of one

=item Local settings

  * You can set A or P locally by using $x->accuracy() or
    $x->precision()
    and thus force different A and P for different objects/numbers.
  * Setting A or P this way immediately rounds $x to the new value.
  * $x->accuracy() clears $x->precision(), and vice versa.

=item Rounding

  * the rounding routines will use the respective global or local settings.
    bround() is for accuracy rounding, while bfround() is for precision
  * the two rounding functions take as the second parameter one of the
    following rounding modes (R):
    'even', 'odd', '+inf', '-inf', 'zero', 'trunc', 'common'
  * you can set/get the global R by using Math::SomeClass->round_mode()
    or by setting $Math::SomeClass::round_mode
  * after each operation, $result->round() is called, and the result may
    eventually be rounded (that is, if A or P were set either locally,
    globally or as parameter to the operation)
  * to manually round a number, call $x->round($A,$P,$round_mode);
    this will round the number by using the appropriate rounding function
    and then normalize it.
  * rounding modifies the local settings of the number:

        $x = Math::BigFloat->new(123.456);
        $x->accuracy(5);
        $x->bround(4);

    Here 4 takes precedence over 5, so 123.5 is the result and $x->accuracy()
    will be 4 from now on.

=item Default values

  * R: 'even'
  * F: 40
  * A: undef
  * P: undef

=item Remarks

  * The defaults are set up so that the new code gives the same results as
    the old code (except in a few cases on bdiv):
    + Both A and P are undefined and thus will not be used for rounding
      after each operation.
    + round() is thus a no-op, unless given extra parameters A and P

=back

=head1 Infinity and Not a Number

While Math::BigInt has extensive handling of inf and NaN, certain quirks
remain.

=over

=item oct()/hex()

These perl routines currently (as of Perl v.5.8.6) cannot handle passed inf.

    te@linux:~> perl -wle 'print 2 ** 3333'
    Inf
    te@linux:~> perl -wle 'print 2 ** 3333 == 2 ** 3333'
    1
    te@linux:~> perl -wle 'print oct(2 ** 3333)'
    0
    te@linux:~> perl -wle 'print hex(2 ** 3333)'
    Illegal hexadecimal digit 'I' ignored at -e line 1.
    0

The same problems occur if you pass them Math::BigInt->binf() objects. Since
overloading these routines is not possible, this cannot be fixed from
Math::BigInt.

=back

=head1 INTERNALS

You should neither care about nor depend on the internal representation; it
might change without notice. Use B<ONLY> method calls like C<< $x->sign(); >>
instead relying on the internal representation.

=head2 MATH LIBRARY

The mathematical computations are performed by a backend library. It is not
required to specify which backend library to use, but some backend libraries
are much faster than the default library.

=head3 The default library

The default library is L<Math::BigInt::Calc>, which is implemented in pure Perl
and hence does not require a compiler.

=head3 Specifying a library

The simple case

    use Math::BigInt;

is equivalent to saying

    use Math::BigInt try => 'Calc';

You can use a different backend library with, e.g.,

    use Math::BigInt try => 'GMP';

which attempts to load the L<Math::BigInt::GMP> library, and falls back to the
default library if the specified library can't be loaded.

Multiple libraries can be specified by separating them by a comma, e.g.,

    use Math::BigInt try => 'GMP,Pari';

If you request a specific set of libraries and do not allow fallback to the
default library, specify them using "only",

    use Math::BigInt only => 'GMP,Pari';

If you prefer a specific set of libraries, but want to see a warning if the
fallback library is used, specify them using "lib",

    use Math::BigInt lib => 'GMP,Pari';

The following first tries to find Math::BigInt::Foo, then Math::BigInt::Bar, and
if this also fails, reverts to Math::BigInt::Calc:

    use Math::BigInt try => 'Foo,Math::BigInt::Bar';

=head3 Which library to use?

B<Note>: General purpose packages should not be explicit about the library to
use; let the script author decide which is best.

L<Math::BigInt::GMP>, L<Math::BigInt::Pari>, and L<Math::BigInt::GMPz> are in
cases involving big numbers much faster than L<Math::BigInt::Calc>. However
these libraries are slower when dealing with very small numbers (less than about
20 digits) and when converting very large numbers to decimal (for instance for
printing, rounding, calculating their length in decimal etc.).

So please select carefully what library you want to use.

Different low-level libraries use different formats to store the numbers, so
mixing them won't work. You should not depend on the number having a specific
internal format.

See the respective math library module documentation for further details.

=head3 Loading multiple libraries

The first library that is successfully loaded is the one that will be used. Any
further attempts at loading a different module will be ignored. This is to avoid
the situation where module A requires math library X, and module B requires math
library Y, causing modules A and B to be incompatible. For example,

    use Math::BigInt;                   # loads default "Calc"
    use Math::BigFloat only => "GMP";   # ignores "GMP"

=head2 SIGN

The sign is either '+', '-', 'NaN', '+inf' or '-inf'.

A sign of 'NaN' is used to represent the result when input arguments are not
numbers or as a result of 0/0. '+inf' and '-inf' represent plus respectively
minus infinity. You get '+inf' when dividing a positive number by 0, and '-inf'
when dividing any negative number by 0.

=head1 EXAMPLES

  use Math::BigInt;

  sub bigint { Math::BigInt->new(shift); }

  $x = Math::BigInt->bstr("1234")       # string "1234"
  $x = "$x";                            # same as bstr()
  $x = Math::BigInt->bneg("1234");      # Math::BigInt "-1234"
  $x = Math::BigInt->babs("-12345");    # Math::BigInt "12345"
  $x = Math::BigInt->bnorm("-0.00");    # Math::BigInt "0"
  $x = bigint(1) + bigint(2);           # Math::BigInt "3"
  $x = bigint(1) + "2";                 # ditto ("2" becomes a Math::BigInt)
  $x = bigint(1);                       # Math::BigInt "1"
  $x = $x + 5 / 2;                      # Math::BigInt "3"
  $x = $x ** 3;                         # Math::BigInt "27"
  $x *= 2;                              # Math::BigInt "54"
  $x = Math::BigInt->new(0);            # Math::BigInt "0"
  $x--;                                 # Math::BigInt "-1"
  $x = Math::BigInt->badd(4,5)          # Math::BigInt "9"
  print $x->bsstr();                    # 9e+0

Examples for rounding:

  use Math::BigFloat;
  use Test::More;

  $x = Math::BigFloat->new(123.4567);
  $y = Math::BigFloat->new(123.456789);
  Math::BigFloat->accuracy(4);          # no more A than 4

  is ($x->copy()->bround(),123.4);      # even rounding
  print $x->copy()->bround(),"\n";      # 123.4
  Math::BigFloat->round_mode('odd');    # round to odd
  print $x->copy()->bround(),"\n";      # 123.5
  Math::BigFloat->accuracy(5);          # no more A than 5
  Math::BigFloat->round_mode('odd');    # round to odd
  print $x->copy()->bround(),"\n";      # 123.46
  $y = $x->copy()->bround(4),"\n";      # A = 4: 123.4
  print "$y, ",$y->accuracy(),"\n";     # 123.4, 4

  Math::BigFloat->accuracy(undef);      # A not important now
  Math::BigFloat->precision(2);         # P important
  print $x->copy()->bnorm(),"\n";       # 123.46
  print $x->copy()->bround(),"\n";      # 123.46

Examples for converting:

  my $x = Math::BigInt->new('0b1'.'01' x 123);
  print "bin: ",$x->as_bin()," hex:",$x->as_hex()," dec: ",$x,"\n";

=head1 NUMERIC LITERALS

After C<use Math::BigInt ':constant'> all numeric literals in the given scope
are converted to C<Math::BigInt> objects. This conversion happens at compile
time. Every non-integer is convert to a NaN.

For example,

    perl -MMath::BigInt=:constant -le 'print 2**150'

prints the exact value of C<2**150>. Note that without conversion of constants
to objects the expression C<2**150> is calculated using Perl scalars, which
leads to an inaccurate result.

Please note that strings are not affected, so that

    use Math::BigInt qw/:constant/;

    $x = "1234567890123456789012345678901234567890"
            + "123456789123456789";

does give you what you expect. You need an explicit Math::BigInt->new() around
at least one of the operands. You should also quote large constants to prevent
loss of precision:

    use Math::BigInt;

    $x = Math::BigInt->new("1234567889123456789123456789123456789");

Without the quotes Perl first converts the large number to a floating point
constant at compile time, and then converts the result to a Math::BigInt object
at run time, which results in an inaccurate result.

=head2 Hexadecimal, octal, and binary floating point literals

Perl (and this module) accepts hexadecimal, octal, and binary floating point
literals, but use them with care with Perl versions before v5.32.0, because some
versions of Perl silently give the wrong result. Below are some examples of
different ways to write the number decimal 314.

Hexadecimal floating point literals:

    0x1.3ap+8         0X1.3AP+8
    0x1.3ap8          0X1.3AP8
    0x13a0p-4         0X13A0P-4

Octal floating point literals (with "0" prefix):

    01.164p+8         01.164P+8
    01.164p8          01.164P8
    011640p-4         011640P-4

Octal floating point literals (with "0o" prefix) (requires v5.34.0):

    0o1.164p+8        0O1.164P+8
    0o1.164p8         0O1.164P8
    0o11640p-4        0O11640P-4

Binary floating point literals:

    0b1.0011101p+8    0B1.0011101P+8
    0b1.0011101p8     0B1.0011101P8
    0b10011101000p-2  0B10011101000P-2

=head1 PERFORMANCE

Using the form $x += $y; etc over $x = $x + $y is faster, since a copy of $x
must be made in the second case. For long numbers, the copy can eat up to 20%
of the work (in the case of addition/subtraction, less for
multiplication/division). If $y is very small compared to $x, the form $x += $y
is MUCH faster than $x = $x + $y since making the copy of $x takes more time
then the actual addition.

With a technique called copy-on-write, the cost of copying with overload could
be minimized or even completely avoided. A test implementation of COW did show
performance gains for overloaded math, but introduced a performance loss due to
a constant overhead for all other operations. So Math::BigInt does currently
not COW.

The rewritten version of this module (vs. v0.01) is slower on certain
operations, like C<new()>, C<bstr()> and C<numify()>. The reason are that it
does now more work and handles much more cases. The time spent in these
operations is usually gained in the other math operations so that code on the
average should get (much) faster. If they don't, please contact the author.

Some operations may be slower for small numbers, but are significantly faster
for big numbers. Other operations are now constant (O(1), like C<bneg()>,
C<babs()> etc), instead of O(N) and thus nearly always take much less time.
These optimizations were done on purpose.

If you find the Calc module to slow, try to install any of the replacement
modules and see if they help you.

=head2 Alternative math libraries

You can use an alternative library to drive Math::BigInt. See the section
L</MATH LIBRARY> for more information.

For more benchmark results see L<http://bloodgate.com/perl/benchmarks.html>.

=head1 SUBCLASSING

=head2 Subclassing Math::BigInt

The basic design of Math::BigInt allows simple subclasses with very little
work, as long as a few simple rules are followed:

=over

=item *

The public API must remain consistent, i.e. if a sub-class is overloading
addition, the sub-class must use the same name, in this case badd(). The reason
for this is that Math::BigInt is optimized to call the object methods directly.

=item *

The private object hash keys like C<< $x->{sign} >> may not be changed, but
additional keys can be added, like C<< $x->{_custom} >>.

=item *

Accessor functions are available for all existing object hash keys and should
be used instead of directly accessing the internal hash keys. The reason for
this is that Math::BigInt itself has a pluggable interface which permits it to
support different storage methods.

=back

More complex sub-classes may have to replicate more of the logic internal of
Math::BigInt if they need to change more basic behaviors. A subclass that needs
to merely change the output only needs to overload C<bstr()>.

All other object methods and overloaded functions can be directly inherited
from the parent class.

At the very minimum, any subclass needs to provide its own C<new()> and can
store additional hash keys in the object. There are also some package globals
that must be defined, e.g.:

    # Globals
    $accuracy = undef;
    $precision = -2;       # round to 2 decimal places
    $round_mode = 'even';
    $div_scale = 40;

Additionally, you might want to provide the following two globals to allow
auto-upgrading and auto-downgrading to work correctly:

    $upgrade = undef;
    $downgrade = undef;

This allows Math::BigInt to correctly retrieve package globals from the
subclass, like C<$SubClass::precision>. See t/Math/BigInt/Subclass.pm or
t/Math/BigFloat/SubClass.pm completely functional subclass examples.

Don't forget to

    use overload;

in your subclass to automatically inherit the overloading from the parent. If
you like, you can change part of the overloading, look at Math::String for an
example.

=head1 UPGRADING

When used like this:

    use Math::BigInt upgrade => 'Foo::Bar';

certain operations 'upgrade' their calculation and thus the result to the class
Foo::Bar. Usually this is used in conjunction with Math::BigFloat:

    use Math::BigInt upgrade => 'Math::BigFloat';

As a shortcut, you can use the module L<bignum>:

    use bignum;

Also good for one-liners:

    perl -Mbignum -le 'print 2 ** 255'

This makes it possible to mix arguments of different classes (as in 2.5 + 2) as
well es preserve accuracy (as in sqrt(3)).

Beware: This feature is not fully implemented yet.

=head2 Auto-upgrade

The following methods upgrade themselves unconditionally; that is if upgrade is
in effect, they always hands up their work:

    div bsqrt blog bexp bpi bsin bcos batan batan2

All other methods upgrade themselves only when one (or all) of their arguments
are of the class mentioned in $upgrade.

=head1 EXPORTS

C<Math::BigInt> exports nothing by default, but can export the following
methods:

    bgcd
    blcm

=head1 CAVEATS

Some things might not work as you expect them. Below is documented what is
known to be troublesome:

=over

=item Comparing numbers as strings

Both C<bstr()> and C<bsstr()> as well as stringify via overload drop the
leading '+'. This is to be consistent with Perl and to make C<cmp> (especially
with overloading) to work as you expect. It also solves problems with
C<Test.pm> and L<Test::More>, which stringify arguments before comparing them.

Mark Biggar said, when asked about to drop the '+' altogether, or make only
C<cmp> work:

    I agree (with the first alternative), don't add the '+' on positive
    numbers.  It's not as important anymore with the new internal form
    for numbers.  It made doing things like abs and neg easier, but
    those have to be done differently now anyway.

So, the following examples now works as expected:

    use Test::More tests => 1;
    use Math::BigInt;

    my $x = Math::BigInt -> new(3*3);
    my $y = Math::BigInt -> new(3*3);

    is($x,3*3, 'multiplication');
    print "$x eq 9" if $x eq $y;
    print "$x eq 9" if $x eq '9';
    print "$x eq 9" if $x eq 3*3;

Additionally, the following still works:

    print "$x == 9" if $x == $y;
    print "$x == 9" if $x == 9;
    print "$x == 9" if $x == 3*3;

There is now a C<bsstr()> method to get the string in scientific notation aka
C<1e+2> instead of C<100>. Be advised that overloaded 'eq' always uses bstr()
for comparison, but Perl represents some numbers as 100 and others as 1e+308.
If in doubt, convert both arguments to Math::BigInt before comparing them as
strings:

    use Test::More tests => 3;
    use Math::BigInt;

    $x = Math::BigInt->new('1e56'); $y = 1e56;
    is($x,$y);                     # fails
    is($x->bsstr(),$y);            # okay
    $y = Math::BigInt->new($y);
    is($x,$y);                     # okay

Alternatively, simply use C<< <=> >> for comparisons, this always gets it
right. There is not yet a way to get a number automatically represented as a
string that matches exactly the way Perl represents it.

See also the section about L<Infinity and Not a Number> for problems in
comparing NaNs.

=item int()

C<int()> returns (at least for Perl v5.7.1 and up) another Math::BigInt, not a
Perl scalar:

    $x = Math::BigInt->new(123);
    $y = int($x);                           # 123 as a Math::BigInt
    $x = Math::BigFloat->new(123.45);
    $y = int($x);                           # 123 as a Math::BigFloat

If you want a real Perl scalar, use C<numify()>:

    $y = $x->numify();                      # 123 as a scalar

This is seldom necessary, though, because this is done automatically, like when
you access an array:

    $z = $array[$x];                        # does work automatically

=item Modifying and =

Beware of:

    $x = Math::BigFloat->new(5);
    $y = $x;

This makes a second reference to the B<same> object and stores it in $y. Thus
anything that modifies $x (except overloaded operators) also modifies $y, and
vice versa. Or in other words, C<=> is only safe if you modify your
Math::BigInt objects only via overloaded math. As soon as you use a method call
it breaks:

    $x->bmul(2);
    print "$x, $y\n";       # prints '10, 10'

If you want a true copy of $x, use:

    $y = $x->copy();

You can also chain the calls like this, this first makes a copy and then
multiply it by 2:

    $y = $x->copy()->bmul(2);

See also the documentation for overload.pm regarding C<=>.

=item Overloading -$x

The following:

    $x = -$x;

is slower than

    $x->bneg();

since overload calls C<sub($x,0,1);> instead of C<neg($x)>. The first variant
needs to preserve $x since it does not know that it later gets overwritten.
This makes a copy of $x and takes O(N), but $x->bneg() is O(1).

=item Mixing different object types

With overloaded operators, it is the first (dominating) operand that determines
which method is called. Here are some examples showing what actually gets
called in various cases.

    use Math::BigInt;
    use Math::BigFloat;

    $mbf  = Math::BigFloat->new(5);
    $mbi2 = Math::BigInt->new(5);
    $mbi  = Math::BigInt->new(2);
                                    # what actually gets called:
    $float = $mbf + $mbi;           # $mbf->badd($mbi)
    $float = $mbf / $mbi;           # $mbf->bdiv($mbi)
    $integer = $mbi + $mbf;         # $mbi->badd($mbf)
    $integer = $mbi2 / $mbi;        # $mbi2->bdiv($mbi)
    $integer = $mbi2 / $mbf;        # $mbi2->bdiv($mbf)

For instance, Math::BigInt->bdiv() always returns a Math::BigInt, regardless of
whether the second operant is a Math::BigFloat. To get a Math::BigFloat you
either need to call the operation manually, make sure each operand already is a
Math::BigFloat, or cast to that type via Math::BigFloat->new():

    $float = Math::BigFloat->new($mbi2) / $mbi;     # = 2.5

Beware of casting the entire expression, as this would cast the
result, at which point it is too late:

    $float = Math::BigFloat->new($mbi2 / $mbi);     # = 2

Beware also of the order of more complicated expressions like:

    $integer = ($mbi2 + $mbi) / $mbf;               # int / float => int
    $integer = $mbi2 / Math::BigFloat->new($mbi);   # ditto

If in doubt, break the expression into simpler terms, or cast all operands
to the desired resulting type.

Scalar values are a bit different, since:

    $float = 2 + $mbf;
    $float = $mbf + 2;

both result in the proper type due to the way the overloaded math works.

This section also applies to other overloaded math packages, like Math::String.

One solution to you problem might be autoupgrading|upgrading. See the
pragmas L<bignum>, L<bigint> and L<bigrat> for an easy way to do this.

=back

=head1 BUGS

Please report any bugs or feature requests to
C<bug-math-bigint at rt.cpan.org>, or through the web interface at
L<https://rt.cpan.org/Ticket/Create.html?Queue=Math-BigInt> (requires login).
We 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 perldoc command.

    perldoc Math::BigInt

You can also look for information at:

=over 4

=item * GitHub

L<https://github.com/pjacklam/p5-Math-BigInt>

=item * RT: CPAN's request tracker

L<https://rt.cpan.org/Dist/Display.html?Name=Math-BigInt>

=item * MetaCPAN

L<https://metacpan.org/release/Math-BigInt>

=item * CPAN Testers Matrix

L<http://matrix.cpantesters.org/?dist=Math-BigInt>

=item * CPAN Ratings

L<https://cpanratings.perl.org/dist/Math-BigInt>

=item * The Bignum mailing list

=over 4

=item * Post to mailing list

C<bignum at lists.scsys.co.uk>

=item * View mailing list

L<http://lists.scsys.co.uk/pipermail/bignum/>

=item * Subscribe/Unsubscribe

L<http://lists.scsys.co.uk/cgi-bin/mailman/listinfo/bignum>

=back

=back

=head1 LICENSE

This program is free software; you may redistribute it and/or modify it under
the same terms as Perl itself.

=head1 SEE ALSO

L<Math::BigFloat> and L<Math::BigRat> as well as the backends
L<Math::BigInt::FastCalc>, L<Math::BigInt::GMP>, and L<Math::BigInt::Pari>.

The pragmas L<bignum>, L<bigint> and L<bigrat> also might be of interest
because they solve the autoupgrading/downgrading issue, at least partly.

=head1 AUTHORS

=over 4

=item *

Mark Biggar, overloaded interface by Ilya Zakharevich, 1996-2001.

=item *

Completely rewritten by Tels L<http://bloodgate.com>, 2001-2008.

=item *

Florian Ragwitz E<lt>flora@cpan.orgE<gt>, 2010.

=item *

Peter John Acklam E<lt>pjacklam@gmail.comE<gt>, 2011-.

=back

Many people contributed in one or more ways to the final beast, see the file
CREDITS for an (incomplete) list. If you miss your name, please drop me a
mail. Thank you!

=cut
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             #
# "Tax the rat farms." - Lord Vetinari
#

# The following hash values are used:
#   sign : +,-,NaN,+inf,-inf
#   _d   : denominator
#   _n   : numerator (value = _n/_d)
#   _a   : accuracy
#   _p   : precision
# You should not look at the innards of a BigRat - use the methods for this.

package Math::BigRat;

use 5.006;
use strict;
use warnings;

use Carp         qw< carp croak >;
use Scalar::Util qw< blessed >;

use Math::BigFloat ();

our $VERSION = '0.2621';

our @ISA = qw(Math::BigFloat);

our ($accuracy, $precision, $round_mode, $div_scale,
     $upgrade, $downgrade, $_trap_nan, $_trap_inf);

use overload

  # overload key: with_assign

  '+'     =>      sub { $_[0] -> copy() -> badd($_[1]); },

  '-'     =>      sub { my $c = $_[0] -> copy;
                        $_[2] ? $c -> bneg() -> badd( $_[1])
                              : $c -> bsub($_[1]); },

  '*'     =>      sub { $_[0] -> copy() -> bmul($_[1]); },

  '/'     =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bdiv($_[0])
                              : $_[0] -> copy() -> bdiv($_[1]); },

  '%'     =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bmod($_[0])
                              : $_[0] -> copy() -> bmod($_[1]); },

  '**'    =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bpow($_[0])
                              : $_[0] -> copy() -> bpow($_[1]); },

  '<<'    =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> blsft($_[0])
                              : $_[0] -> copy() -> blsft($_[1]); },

  '>>'    =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> brsft($_[0])
                              : $_[0] -> copy() -> brsft($_[1]); },

  # overload key: assign

  '+='    =>      sub { $_[0]->badd($_[1]); },

  '-='    =>      sub { $_[0]->bsub($_[1]); },

  '*='    =>      sub { $_[0]->bmul($_[1]); },

  '/='    =>      sub { scalar $_[0]->bdiv($_[1]); },

  '%='    =>      sub { $_[0]->bmod($_[1]); },

  '**='   =>      sub { $_[0]->bpow($_[1]); },

  '<<='   =>      sub { $_[0]->blsft($_[1]); },

  '>>='   =>      sub { $_[0]->brsft($_[1]); },

#  'x='    =>      sub { },

#  '.='    =>      sub { },

  # overload key: num_comparison

  '<'     =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> blt($_[0])
                              : $_[0] -> blt($_[1]); },

  '<='    =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> ble($_[0])
                              : $_[0] -> ble($_[1]); },

  '>'     =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bgt($_[0])
                              : $_[0] -> bgt($_[1]); },

  '>='    =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bge($_[0])
                              : $_[0] -> bge($_[1]); },

  '=='    =>      sub { $_[0] -> beq($_[1]); },

  '!='    =>      sub { $_[0] -> bne($_[1]); },

  # overload key: 3way_comparison

  '<=>'   =>      sub { my $cmp = $_[0] -> bcmp($_[1]);
                        defined($cmp) && $_[2] ? -$cmp : $cmp; },

  'cmp'   =>      sub { $_[2] ? "$_[1]" cmp $_[0] -> bstr()
                              : $_[0] -> bstr() cmp "$_[1]"; },

  # overload key: str_comparison

#  'lt'     =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bstrlt($_[0])
#                              : $_[0] -> bstrlt($_[1]); },
#
#  'le'    =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bstrle($_[0])
#                              : $_[0] -> bstrle($_[1]); },
#
#  'gt'     =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bstrgt($_[0])
#                              : $_[0] -> bstrgt($_[1]); },
#
#  'ge'    =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bstrge($_[0])
#                              : $_[0] -> bstrge($_[1]); },
#
#  'eq'    =>      sub { $_[0] -> bstreq($_[1]); },
#
#  'ne'    =>      sub { $_[0] -> bstrne($_[1]); },

  # overload key: binary

  '&'     =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> band($_[0])
                              : $_[0] -> copy() -> band($_[1]); },

  '&='    =>      sub { $_[0] -> band($_[1]); },

  '|'     =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bior($_[0])
                              : $_[0] -> copy() -> bior($_[1]); },

  '|='    =>      sub { $_[0] -> bior($_[1]); },

  '^'     =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bxor($_[0])
                              : $_[0] -> copy() -> bxor($_[1]); },

  '^='    =>      sub { $_[0] -> bxor($_[1]); },

#  '&.'    =>      sub { },

#  '&.='   =>      sub { },

#  '|.'    =>      sub { },

#  '|.='   =>      sub { },

#  '^.'    =>      sub { },

#  '^.='   =>      sub { },

  # overload key: unary

  'neg'   =>      sub { $_[0] -> copy() -> bneg(); },

#  '!'     =>      sub { },

  '~'     =>      sub { $_[0] -> copy() -> bnot(); },

#  '~.'    =>      sub { },

  # overload key: mutators

  '++'    =>      sub { $_[0] -> binc() },

  '--'    =>      sub { $_[0] -> bdec() },

  # overload key: func

  'atan2' =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> batan2($_[0])
                              : $_[0] -> copy() -> batan2($_[1]); },

  'cos'   =>      sub { $_[0] -> copy() -> bcos(); },

  'sin'   =>      sub { $_[0] -> copy() -> bsin(); },

  'exp'   =>      sub { $_[0] -> copy() -> bexp($_[1]); },

  'abs'   =>      sub { $_[0] -> copy() -> babs(); },

  'log'   =>      sub { $_[0] -> copy() -> blog(); },

  'sqrt'  =>      sub { $_[0] -> copy() -> bsqrt(); },

  'int'   =>      sub { $_[0] -> copy() -> bint(); },

  # overload key: conversion

  'bool'  =>      sub { $_[0] -> is_zero() ? '' : 1; },

  '""'    =>      sub { $_[0] -> bstr(); },

  '0+'    =>      sub { $_[0] -> numify(); },

  '='     =>      sub { $_[0]->copy(); },

  ;

BEGIN {
    *objectify = \&Math::BigInt::objectify;  # inherit this from BigInt
    *AUTOLOAD  = \&Math::BigFloat::AUTOLOAD; # can't inherit AUTOLOAD
    # We inherit these from BigFloat because currently it is not possible that
    # Math::BigFloat has a different $LIB variable than we, because
    # Math::BigFloat also uses Math::BigInt::config->('lib') (there is always
    # only one library loaded)
    *_e_add = \&Math::BigFloat::_e_add;
    *_e_sub = \&Math::BigFloat::_e_sub;
    *as_number = \&as_int;
    *is_pos = \&is_positive;
    *is_neg = \&is_negative;
}

##############################################################################
# Global constants and flags. Access these only via the accessor methods!

$accuracy   = $precision = undef;
$round_mode = 'even';
$div_scale  = 40;
$upgrade    = undef;
$downgrade  = undef;

# These are internally, and not to be used from the outside at all!

$_trap_nan = 0;                         # are NaNs ok? set w/ config()
$_trap_inf = 0;                         # are infs ok? set w/ config()

# the math backend library

my $LIB = 'Math::BigInt::Calc';

my $nan   = 'NaN';
#my $class = 'Math::BigRat';

sub isa {
    return 0 if $_[1] =~ /^Math::Big(Int|Float)/;       # we aren't
    UNIVERSAL::isa(@_);
}

##############################################################################

sub new {
    my $proto    = shift;
    my $protoref = ref $proto;
    my $class    = $protoref || $proto;

    # Check the way we are called.

    if ($protoref) {
        croak("new() is a class method, not an instance method");
    }

    if (@_ < 1) {
        #carp("Using new() with no argument is deprecated;",
        #           " use bzero() or new(0) instead");
        return $class -> bzero();
    }

    if (@_ > 2) {
        carp("Superfluous arguments to new() ignored.");
    }

    # Get numerator and denominator. If any of the arguments is undefined,
    # return zero.

    my ($n, $d) = @_;

    if (@_ == 1 && !defined $n ||
        @_ == 2 && (!defined $n || !defined $d))
    {
        #carp("Use of uninitialized value in new()");
        return $class -> bzero();
    }

    # Initialize a new object.

    my $self = bless {}, $class;

    # One or two input arguments may be given. First handle the numerator $n.

    if (ref($n)) {
        $n = Math::BigFloat -> new($n, undef, undef)
          unless ($n -> isa('Math::BigRat') ||
                  $n -> isa('Math::BigInt') ||
                  $n -> isa('Math::BigFloat'));
    } else {
        if (defined $d) {
            # If the denominator is defined, the numerator is not a string
            # fraction, e.g., "355/113".
            $n = Math::BigFloat -> new($n, undef, undef);
        } else {
            # If the denominator is undefined, the numerator might be a string
            # fraction, e.g., "355/113".
            if ($n =~ m| ^ \s* (\S+) \s* / \s* (\S+) \s* $ |x) {
                $n = Math::BigFloat -> new($1, undef, undef);
                $d = Math::BigFloat -> new($2, undef, undef);
            } else {
                $n = Math::BigFloat -> new($n, undef, undef);
            }
        }
    }

    # At this point $n is an object and $d is either an object or undefined. An
    # undefined $d means that $d was not specified by the caller (not that $d
    # was specified as an undefined value).

    unless (defined $d) {
        #return $n -> copy($n)               if $n -> isa('Math::BigRat');
        if ($n -> isa('Math::BigRat')) {
            return $downgrade -> new($n) if defined($downgrade) && $n -> is_int();
            return $class -> copy($n);
        }

        if ($n -> is_nan()) {
            return $class -> bnan();
        }

        if ($n -> is_inf()) {
            return $class -> binf($n -> sign());
        }

        if ($n -> isa('Math::BigInt')) {
            $self -> {_n}   = $LIB -> _new($n -> copy() -> babs() -> bstr());
            $self -> {_d}   = $LIB -> _one();
            $self -> {sign} = $n -> sign();
            return $downgrade -> new($n) if defined $downgrade;
            return $self;
        }

        if ($n -> isa('Math::BigFloat')) {
            my $m = $n -> mantissa() -> babs();
            my $e = $n -> exponent();
            $self -> {_n} = $LIB -> _new($m -> bstr());
            $self -> {_d} = $LIB -> _one();

            if ($e > 0) {
                $self -> {_n} = $LIB -> _lsft($self -> {_n},
                                              $LIB -> _new($e -> bstr()), 10);
            } elsif ($e < 0) {
                $self -> {_d} = $LIB -> _lsft($self -> {_d},
                                              $LIB -> _new(-$e -> bstr()), 10);

                my $gcd = $LIB -> _gcd($LIB -> _copy($self -> {_n}), $self -> {_d});
                if (!$LIB -> _is_one($gcd)) {
                    $self -> {_n} = $LIB -> _div($self->{_n}, $gcd);
                    $self -> {_d} = $LIB -> _div($self->{_d}, $gcd);
                }
            }

            $self -> {sign} = $n -> sign();
            return $downgrade -> new($n) if defined($downgrade) && $n -> is_int();
            return $self;
        }

        die "I don't know how to handle this";  # should never get here
    }

    # At the point we know that both $n and $d are defined. We know that $n is
    # an object, but $d might still be a scalar. Now handle $d.

    $d = Math::BigFloat -> new($d, undef, undef)
      unless ref($d) && ($d -> isa('Math::BigRat') ||
                         $d -> isa('Math::BigInt') ||
                         $d -> isa('Math::BigFloat'));

    # At this point both $n and $d are objects.

    if ($n -> is_nan() || $d -> is_nan()) {
        return $class -> bnan();
    }

    # At this point neither $n nor $d is a NaN.

    if ($n -> is_zero()) {
        if ($d -> is_zero()) {     # 0/0 = NaN
            return $class -> bnan();
        }
        return $class -> bzero();
    }

    if ($d -> is_zero()) {
        return $class -> binf($d -> sign());
    }

    # At this point, neither $n nor $d is a NaN or a zero.

    # Copy them now before manipulating them.

    $n = $n -> copy();
    $d = $d -> copy();

    if ($d < 0) {               # make sure denominator is positive
        $n -> bneg();
        $d -> bneg();
    }

    if ($n -> is_inf()) {
        return $class -> bnan() if $d -> is_inf();      # Inf/Inf = NaN
        return $class -> binf($n -> sign());
    }

    # At this point $n is finite.

    return $class -> bzero()            if $d -> is_inf();
    return $class -> binf($d -> sign()) if $d -> is_zero();

    # At this point both $n and $d are finite and non-zero.

    if ($n < 0) {
        $n -> bneg();
        $self -> {sign} = '-';
    } else {
        $self -> {sign} = '+';
    }

    if ($n -> isa('Math::BigRat')) {

        if ($d -> isa('Math::BigRat')) {

            # At this point both $n and $d is a Math::BigRat.

            # p   r    p * s    (p / gcd(p, r)) * (s / gcd(s, q))
            # - / -  = ----- =  ---------------------------------
            # q   s    q * r    (q / gcd(s, q)) * (r / gcd(p, r))

            my $p = $n -> {_n};
            my $q = $n -> {_d};
            my $r = $d -> {_n};
            my $s = $d -> {_d};
            my $gcd_pr = $LIB -> _gcd($LIB -> _copy($p), $r);
            my $gcd_sq = $LIB -> _gcd($LIB -> _copy($s), $q);
            $self -> {_n} = $LIB -> _mul($LIB -> _div($LIB -> _copy($p), $gcd_pr),
                                         $LIB -> _div($LIB -> _copy($s), $gcd_sq));
            $self -> {_d} = $LIB -> _mul($LIB -> _div($LIB -> _copy($q), $gcd_sq),
                                         $LIB -> _div($LIB -> _copy($r), $gcd_pr));

            return $downgrade -> new($n->bstr())
              if defined($downgrade) && $self -> is_int();
            return $self;       # no need for $self -> bnorm() here
        }

        # At this point, $n is a Math::BigRat and $d is a Math::Big(Int|Float).

        my $p = $n -> {_n};
        my $q = $n -> {_d};
        my $m = $d -> mantissa();
        my $e = $d -> exponent();

        #                   /      p
        #                  |  ------------  if e > 0
        #                  |  q * m * 10^e
        #                  |
        # p                |    p
        # - / (m * 10^e) = |  -----         if e == 0
        # q                |  q * m
        #                  |
        #                  |  p * 10^-e
        #                  |  --------      if e < 0
        #                   \  q * m

        $self -> {_n} = $LIB -> _copy($p);
        $self -> {_d} = $LIB -> _mul($LIB -> _copy($q), $m);
        if ($e > 0) {
            $self -> {_d} = $LIB -> _lsft($self -> {_d}, $e, 10);
        } elsif ($e < 0) {
            $self -> {_n} = $LIB -> _lsft($self -> {_n}, -$e, 10);
        }

        return $self -> bnorm();

    } else {

        if ($d -> isa('Math::BigRat')) {

            # At this point $n is a Math::Big(Int|Float) and $d is a
            # Math::BigRat.

            my $m = $n -> mantissa();
            my $e = $n -> exponent();
            my $p = $d -> {_n};
            my $q = $d -> {_d};

            #                   /  q * m * 10^e
            #                  |   ------------  if e > 0
            #                  |        p
            #                  |
            #              p   |   m * q
            # (m * 10^e) / - = |   -----         if e == 0
            #              q   |     p
            #                  |
            #                  |     q * m
            #                  |   ---------     if e < 0
            #                   \  p * 10^-e

            $self -> {_n} = $LIB -> _mul($LIB -> _copy($q), $m);
            $self -> {_d} = $LIB -> _copy($p);
            if ($e > 0) {
                $self -> {_n} = $LIB -> _lsft($self -> {_n}, $e, 10);
            } elsif ($e < 0) {
                $self -> {_d} = $LIB -> _lsft($self -> {_d}, -$e, 10);
            }
            return $self -> bnorm();

        } else {

            # At this point $n and $d are both a Math::Big(Int|Float)

            my $m1 = $n -> mantissa();
            my $e1 = $n -> exponent();
            my $m2 = $d -> mantissa();
            my $e2 = $d -> exponent();

            #               /
            #              |  m1 * 10^(e1 - e2)
            #              |  -----------------  if e1 > e2
            #              |         m2
            #              |
            # m1 * 10^e1   |  m1
            # ---------- = |  --                 if e1 = e2
            # m2 * 10^e2   |  m2
            #              |
            #              |         m1
            #              |  -----------------  if e1 < e2
            #              |  m2 * 10^(e2 - e1)
            #               \

            $self -> {_n} = $LIB -> _new($m1 -> bstr());
            $self -> {_d} = $LIB -> _new($m2 -> bstr());
            my $ediff = $e1 - $e2;
            if ($ediff > 0) {
                $self -> {_n} = $LIB -> _lsft($self -> {_n},
                                              $LIB -> _new($ediff -> bstr()),
                                              10);
            } elsif ($ediff < 0) {
                $self -> {_d} = $LIB -> _lsft($self -> {_d},
                                              $LIB -> _new(-$ediff -> bstr()),
                                              10);
            }

            return $self -> bnorm();
        }
    }

    return $downgrade -> new($self -> bstr())
      if defined($downgrade) && $self -> is_int();
    return $self;
}

sub copy {
    my $self    = shift;
    my $selfref = ref $self;
    my $class   = $selfref || $self;

    # If called as a class method, the object to copy is the next argument.

    $self = shift() unless $selfref;

    my $copy = bless {}, $class;

    $copy->{sign} = $self->{sign};
    $copy->{_d} = $LIB->_copy($self->{_d});
    $copy->{_n} = $LIB->_copy($self->{_n});
    $copy->{_a} = $self->{_a} if defined $self->{_a};
    $copy->{_p} = $self->{_p} if defined $self->{_p};

    #($copy, $copy->{_a}, $copy->{_p})
    #  = $copy->_find_round_parameters(@_);

    return $copy;
}

sub bnan {
    my $self    = shift;
    my $selfref = ref $self;
    my $class   = $selfref || $self;

    $self = bless {}, $class unless $selfref;

    if ($_trap_nan) {
        croak ("Tried to set a variable to NaN in $class->bnan()");
    }

    return $downgrade -> bnan() if defined $downgrade;

    $self -> {sign} = $nan;
    $self -> {_n}   = $LIB -> _zero();
    $self -> {_d}   = $LIB -> _one();

    ($self, $self->{_a}, $self->{_p})
      = $self->_find_round_parameters(@_);

    return $self;
}

sub binf {
    my $self    = shift;
    my $selfref = ref $self;
    my $class   = $selfref || $self;

    $self = bless {}, $class unless $selfref;

    my $sign = shift();
    $sign = defined($sign) && substr($sign, 0, 1) eq '-' ? '-inf' : '+inf';

    if ($_trap_inf) {
        croak ("Tried to set a variable to +-inf in $class->binf()");
    }

    return $downgrade -> binf($sign) if defined $downgrade;

    $self -> {sign} = $sign;
    $self -> {_n}   = $LIB -> _zero();
    $self -> {_d}   = $LIB -> _one();

    ($self, $self->{_a}, $self->{_p})
      = $self->_find_round_parameters(@_);

    return $self;
}

sub bone {
    my $self    = shift;
    my $selfref = ref $self;
    my $class   = $selfref || $self;

    my $sign = shift();
    $sign = '+' unless defined($sign) && $sign eq '-';

    return $downgrade -> bone($sign) if defined $downgrade;

    $self = bless {}, $class unless $selfref;
    $self -> {sign} = $sign;
    $self -> {_n}   = $LIB -> _one();
    $self -> {_d}   = $LIB -> _one();

    ($self, $self->{_a}, $self->{_p})
      = $self->_find_round_parameters(@_);

    return $self;
}

sub bzero {
    my $self    = shift;
    my $selfref = ref $self;
    my $class   = $selfref || $self;

    return $downgrade -> bzero() if defined $downgrade;

    $self = bless {}, $class unless $selfref;
    $self -> {sign} = '+';
    $self -> {_n}   = $LIB -> _zero();
    $self -> {_d}   = $LIB -> _one();

    ($self, $self->{_a}, $self->{_p})
      = $self->_find_round_parameters(@_);

    return $self;
}

##############################################################################

sub config {
    # return (later set?) configuration data as hash ref
    my $class = shift() || 'Math::BigRat';

    if (@_ == 1 && ref($_[0]) ne 'HASH') {
        my $cfg = $class->SUPER::config();
        return $cfg->{$_[0]};
    }

    my $cfg = $class->SUPER::config(@_);

    # now we need only to override the ones that are different from our parent
    $cfg->{class} = $class;
    $cfg->{with}  = $LIB;

    $cfg;
}

##############################################################################

sub bstr {
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    if ($x->{sign} !~ /^[+-]$/) {               # inf, NaN etc
        my $s = $x->{sign};
        $s =~ s/^\+//;                          # +inf => inf
        return $s;
    }

    my $s = '';
    $s = $x->{sign} if $x->{sign} ne '+';       # '+3/2' => '3/2'

    return $s . $LIB->_str($x->{_n}) if $LIB->_is_one($x->{_d});
    $s . $LIB->_str($x->{_n}) . '/' . $LIB->_str($x->{_d});
}

sub bsstr {
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    if ($x->{sign} !~ /^[+-]$/) {               # inf, NaN etc
        my $s = $x->{sign};
        $s =~ s/^\+//;                          # +inf => inf
        return $s;
    }

    my $s = '';
    $s = $x->{sign} if $x->{sign} ne '+';       # +3 vs 3
    $s . $LIB->_str($x->{_n}) . '/' . $LIB->_str($x->{_d});
}

sub bnorm {
    # reduce the number to the shortest form
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    # Both parts must be objects of whatever we are using today.
    if (my $c = $LIB->_check($x->{_n})) {
        croak("n did not pass the self-check ($c) in bnorm()");
    }
    if (my $c = $LIB->_check($x->{_d})) {
        croak("d did not pass the self-check ($c) in bnorm()");
    }

    # no normalize for NaN, inf etc.
    if ($x->{sign} !~ /^[+-]$/) {
        return $downgrade -> new($x) if defined $downgrade;
        return $x;
    }

    # normalize zeros to 0/1
    if ($LIB->_is_zero($x->{_n})) {
        return $downgrade -> bzero() if defined($downgrade);
        $x->{sign} = '+';                               # never leave a -0
        $x->{_d} = $LIB->_one() unless $LIB->_is_one($x->{_d});
        return $x;
    }

    # n/1
    if ($LIB->_is_one($x->{_d})) {
        return $downgrade -> new($LIB -> _str($x->{_d})) if defined($downgrade);
        return $x;               # no need to reduce
    }

    # Compute the GCD.
    my $gcd = $LIB->_gcd($LIB->_copy($x->{_n}), $x->{_d});
    if (!$LIB->_is_one($gcd)) {
        $x->{_n} = $LIB->_div($x->{_n}, $gcd);
        $x->{_d} = $LIB->_div($x->{_d}, $gcd);
    }

    $x;
}

##############################################################################
# sign manipulation

sub bneg {
    # (BRAT or num_str) return BRAT
    # negate number or make a negated number from string
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    return $x if $x->modify('bneg');

    # for +0 do not negate (to have always normalized +0). Does nothing for 'NaN'
    $x->{sign} =~ tr/+-/-+/
      unless ($x->{sign} eq '+' && $LIB->_is_zero($x->{_n}));

    return $downgrade -> new($LIB -> _str($x->{_n}))
      if defined($downgrade) && $LIB -> _is_one($x->{_d});
    $x;
}

##############################################################################
# special values

sub _bnan {
    # used by parent class bnan() to initialize number to NaN
    my $self = shift;

    if ($_trap_nan) {
        my $class = ref($self);
        # "$self" below will stringify the object, this blows up if $self is a
        # partial object (happens under trap_nan), so fix it beforehand
        $self->{_d} = $LIB->_zero() unless defined $self->{_d};
        $self->{_n} = $LIB->_zero() unless defined $self->{_n};
        croak ("Tried to set $self to NaN in $class\::_bnan()");
    }
    $self->{_n} = $LIB->_zero();
    $self->{_d} = $LIB->_zero();
}

sub _binf {
    # used by parent class bone() to initialize number to +inf/-inf
    my $self = shift;

    if ($_trap_inf) {
        my $class = ref($self);
        # "$self" below will stringify the object, this blows up if $self is a
        # partial object (happens under trap_nan), so fix it beforehand
        $self->{_d} = $LIB->_zero() unless defined $self->{_d};
        $self->{_n} = $LIB->_zero() unless defined $self->{_n};
        croak ("Tried to set $self to inf in $class\::_binf()");
    }
    $self->{_n} = $LIB->_zero();
    $self->{_d} = $LIB->_zero();
}

sub _bone {
    # used by parent class bone() to initialize number to +1/-1
    my $self = shift;
    $self->{_n} = $LIB->_one();
    $self->{_d} = $LIB->_one();
}

sub _bzero {
    # used by parent class bzero() to initialize number to 0
    my $self = shift;
    $self->{_n} = $LIB->_zero();
    $self->{_d} = $LIB->_one();
}

##############################################################################
# mul/add/div etc

sub badd {
    # add two rational numbers

    # set up parameters
    my ($class, $x, $y, @r) = (ref($_[0]), @_);
    # objectify is costly, so avoid it
    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
        ($class, $x, $y, @r) = objectify(2, @_);
    }

    unless ($x -> is_finite() && $y -> is_finite()) {
        if ($x -> is_nan() || $y -> is_nan()) {
            return $x -> bnan(@r);
        } elsif ($x -> is_inf("+")) {
            return $x -> bnan(@r) if $y -> is_inf("-");
            return $x -> binf("+", @r);
        } elsif ($x -> is_inf("-")) {
            return $x -> bnan(@r) if $y -> is_inf("+");
            return $x -> binf("-", @r);
        } elsif ($y -> is_inf("+")) {
            return $x -> binf("+", @r);
        } elsif ($y -> is_inf("-")) {
            return $x -> binf("-", @r);
        }
    }

    #  1   1    gcd(3, 4) = 1    1*3 + 1*4    7
    #  - + -                  = --------- = --
    #  4   3                      4*3       12

    # we do not compute the gcd() here, but simple do:
    #  5   7    5*3 + 7*4   43
    #  - + -  = --------- = --
    #  4   3       4*3      12

    # and bnorm() will then take care of the rest

    # 5 * 3
    $x->{_n} = $LIB->_mul($x->{_n}, $y->{_d});

    # 7 * 4
    my $m = $LIB->_mul($LIB->_copy($y->{_n}), $x->{_d});

    # 5 * 3 + 7 * 4
    ($x->{_n}, $x->{sign}) = _e_add($x->{_n}, $m, $x->{sign}, $y->{sign});

    # 4 * 3
    $x->{_d} = $LIB->_mul($x->{_d}, $y->{_d});

    # normalize result, and possible round
    $x->bnorm()->round(@r);
}

sub bsub {
    # subtract two rational numbers

    # set up parameters
    my ($class, $x, $y, @r) = (ref($_[0]), @_);
    # objectify is costly, so avoid it
    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
        ($class, $x, $y, @r) = objectify(2, @_);
    }

    # flip sign of $x, call badd(), then flip sign of result
    $x->{sign} =~ tr/+-/-+/
      unless $x->{sign} eq '+' && $LIB->_is_zero($x->{_n}); # not -0
    $x->badd($y, @r);           # does norm and round
    $x->{sign} =~ tr/+-/-+/
      unless $x->{sign} eq '+' && $LIB->_is_zero($x->{_n}); # not -0

    $x->bnorm();
}

sub bmul {
    # multiply two rational numbers

    # set up parameters
    my ($class, $x, $y, @r) = (ref($_[0]), @_);
    # objectify is costly, so avoid it
    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
        ($class, $x, $y, @r) = objectify(2, @_);
    }

    return $x->bnan() if $x->{sign} eq 'NaN' || $y->{sign} eq 'NaN';

    # inf handling
    if ($x->{sign} =~ /^[+-]inf$/ || $y->{sign} =~ /^[+-]inf$/) {
        return $x->bnan() if $x->is_zero() || $y->is_zero();
        # result will always be +-inf:
        # +inf * +/+inf => +inf, -inf * -/-inf => +inf
        # +inf * -/-inf => -inf, -inf * +/+inf => -inf
        return $x->binf() if ($x->{sign} =~ /^\+/ && $y->{sign} =~ /^\+/);
        return $x->binf() if ($x->{sign} =~ /^-/ && $y->{sign} =~ /^-/);
        return $x->binf('-');
    }

    # x == 0  # also: or y == 1 or y == -1
    return wantarray ? ($x, $class->bzero()) : $x if $x -> is_zero();

    if ($y -> is_zero()) {
        $x -> bzero();
        return wantarray ? ($x, $class->bzero()) : $x;
    }

    # According to Knuth, this can be optimized by doing gcd twice (for d
    # and n) and reducing in one step. This saves us a bnorm() at the end.
    #
    # p   s    p * s    (p / gcd(p, r)) * (s / gcd(s, q))
    # - * -  = ----- =  ---------------------------------
    # q   r    q * r    (q / gcd(s, q)) * (r / gcd(p, r))

    my $gcd_pr = $LIB -> _gcd($LIB -> _copy($x->{_n}), $y->{_d});
    my $gcd_sq = $LIB -> _gcd($LIB -> _copy($y->{_n}), $x->{_d});

    $x->{_n} = $LIB -> _mul(scalar $LIB -> _div($x->{_n}, $gcd_pr),
                            scalar $LIB -> _div($LIB -> _copy($y->{_n}),
                                                $gcd_sq));
    $x->{_d} = $LIB -> _mul(scalar $LIB -> _div($x->{_d}, $gcd_sq),
                            scalar $LIB -> _div($LIB -> _copy($y->{_d}),
                                                $gcd_pr));

    # compute new sign
    $x->{sign} = $x->{sign} eq $y->{sign} ? '+' : '-';

    $x->bnorm()->round(@r);
}

sub bdiv {
    # (dividend: BRAT or num_str, divisor: BRAT or num_str) return
    # (BRAT, BRAT) (quo, rem) or BRAT (only rem)

    # set up parameters
    my ($class, $x, $y, @r) = (ref($_[0]), @_);
    # objectify is costly, so avoid it
    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
        ($class, $x, $y, @r) = objectify(2, @_);
    }

    return $x if $x->modify('bdiv');

    my $wantarray = wantarray;  # call only once

    # At least one argument is NaN. This is handled the same way as in
    # Math::BigInt -> bdiv(). See the comments in the code implementing that
    # method.

    if ($x -> is_nan() || $y -> is_nan()) {
        if ($wantarray) {
            return $downgrade -> bnan(), $downgrade -> bnan()
              if defined($downgrade) && $LIB -> _is_one($x->{_d});
            return $x -> bnan(), $class -> bnan();
        } else {
            return $downgrade -> bnan()
              if defined($downgrade) && $LIB -> _is_one($x->{_d});
            return $x -> bnan();
        }
    }

    # Divide by zero and modulo zero. This is handled the same way as in
    # Math::BigInt -> bdiv(). See the comments in the code implementing that
    # method.

    if ($y -> is_zero()) {
        my ($quo, $rem);
        if ($wantarray) {
            $rem = $x -> copy();
        }
        if ($x -> is_zero()) {
            $quo = $x -> bnan();
        } else {
            $quo = $x -> binf($x -> {sign});
        }

        $quo = $downgrade -> new($quo)
          if defined($downgrade) && $quo -> is_int();
        $rem = $downgrade -> new($rem)
          if $wantarray && defined($downgrade) && $rem -> is_int();
        return $wantarray ? ($quo, $rem) : $quo;
    }

    # Numerator (dividend) is +/-inf. This is handled the same way as in
    # Math::BigInt -> bdiv(). See the comments in the code implementing that
    # method.

    if ($x -> is_inf()) {
        my ($quo, $rem);
        $rem = $class -> bnan() if $wantarray;
        if ($y -> is_inf()) {
            $quo = $x -> bnan();
        } else {
            my $sign = $x -> bcmp(0) == $y -> bcmp(0) ? '+' : '-';
            $quo = $x -> binf($sign);
        }

        $quo = $downgrade -> new($quo)
          if defined($downgrade) && $quo -> is_int();
        $rem = $downgrade -> new($rem)
          if $wantarray && defined($downgrade) && $rem -> is_int();
        return $wantarray ? ($quo, $rem) : $quo;
    }

    # Denominator (divisor) is +/-inf. This is handled the same way as in
    # Math::BigFloat -> bdiv(). See the comments in the code implementing that
    # method.

    if ($y -> is_inf()) {
        my ($quo, $rem);
        if ($wantarray) {
            if ($x -> is_zero() || $x -> bcmp(0) == $y -> bcmp(0)) {
                $rem = $x -> copy();
                $quo = $x -> bzero();
            } else {
                $rem = $class -> binf($y -> {sign});
                $quo = $x -> bone('-');
            }
            $quo = $downgrade -> new($quo)
              if defined($downgrade) && $quo -> is_int();
            $rem = $downgrade -> new($rem)
              if defined($downgrade) && $rem -> is_int();
            return ($quo, $rem);
        } else {
            if ($y -> is_inf()) {
                if ($x -> is_nan() || $x -> is_inf()) {
                    return $downgrade -> bnan() if defined $downgrade;
                    return $x -> bnan();
                } else {
                    return $downgrade -> bzero() if defined $downgrade;
                    return $x -> bzero();
                }
            }
        }
    }

    # At this point, both the numerator and denominator are finite numbers, and
    # the denominator (divisor) is non-zero.

    # x == 0?
    if ($x->is_zero()) {
        return $wantarray ? ($downgrade -> bzero(), $downgrade -> bzero())
                          : $downgrade -> bzero() if defined $downgrade;
        return $wantarray ? ($x, $class->bzero()) : $x;
    }

    # XXX TODO: list context, upgrade
    # According to Knuth, this can be optimized by doing gcd twice (for d and n)
    # and reducing in one step. This would save us the bnorm() at the end.
    #
    # p   r    p * s    (p / gcd(p, r)) * (s / gcd(s, q))
    # - / -  = ----- =  ---------------------------------
    # q   s    q * r    (q / gcd(s, q)) * (r / gcd(p, r))

    $x->{_n} = $LIB->_mul($x->{_n}, $y->{_d});
    $x->{_d} = $LIB->_mul($x->{_d}, $y->{_n});

    # compute new sign
    $x->{sign} = $x->{sign} eq $y->{sign} ? '+' : '-';

    $x -> bnorm();
    if (wantarray) {
        my $rem = $x -> copy();
        $x = $x -> bfloor();
        $x = $x -> round(@r);
        $rem = $rem -> bsub($x -> copy()) -> bmul($y);
        $x   = $downgrade -> new($x)   if defined($downgrade) && $x -> is_int();
        $rem = $downgrade -> new($rem) if defined($downgrade) && $rem -> is_int();
        return $x, $rem;
    } else {
        return $x -> round(@r);
    }
}

sub bmod {
    # compute "remainder" (in Perl way) of $x / $y

    # set up parameters
    my ($class, $x, $y, @r) = (ref($_[0]), @_);
    # objectify is costly, so avoid it
    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
        ($class, $x, $y, @r) = objectify(2, @_);
    }

    return $x if $x->modify('bmod');

    # At least one argument is NaN. This is handled the same way as in
    # Math::BigInt -> bmod().

    if ($x -> is_nan() || $y -> is_nan()) {
        return $x -> bnan();
    }

    # Modulo zero. This is handled the same way as in Math::BigInt -> bmod().

    if ($y -> is_zero()) {
        return $downgrade -> bzero() if defined $downgrade;
        return $x;
    }

    # Numerator (dividend) is +/-inf. This is handled the same way as in
    # Math::BigInt -> bmod().

    if ($x -> is_inf()) {
        return $x -> bnan();
    }

    # Denominator (divisor) is +/-inf. This is handled the same way as in
    # Math::BigInt -> bmod().

    if ($y -> is_inf()) {
        if ($x -> is_zero() || $x -> bcmp(0) == $y -> bcmp(0)) {
            return $downgrade -> new($x) if defined($downgrade) && $x -> is_int();
            return $x;
        } else {
            return $downgrade -> binf($y -> sign()) if defined($downgrade);
            return $x -> binf($y -> sign());
        }
    }

    # At this point, both the numerator and denominator are finite numbers, and
    # the denominator (divisor) is non-zero.

    if ($x->is_zero()) {        # 0 / 7 = 0, mod 0
        return $downgrade -> bzero() if defined $downgrade;
        return $x;
    }

    # Compute $x - $y * floor($x/$y). This can probably be optimized by working
    # on a lower level.

    $x -> bsub($x -> copy() -> bdiv($y) -> bfloor() -> bmul($y));
    return $x -> round(@r);
}

##############################################################################
# bdec/binc

sub bdec {
    # decrement value (subtract 1)
    my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);

    if ($x->{sign} !~ /^[+-]$/) {       # NaN, inf, -inf
        return $downgrade -> new($x) if defined $downgrade;
        return $x;
    }

    if ($x->{sign} eq '-') {
        $x->{_n} = $LIB->_add($x->{_n}, $x->{_d}); # -5/2 => -7/2
    } else {
        if ($LIB->_acmp($x->{_n}, $x->{_d}) < 0) # n < d?
        {
            # 1/3 -- => -2/3
            $x->{_n} = $LIB->_sub($LIB->_copy($x->{_d}), $x->{_n});
            $x->{sign} = '-';
        } else {
            $x->{_n} = $LIB->_sub($x->{_n}, $x->{_d}); # 5/2 => 3/2
        }
    }
    $x->bnorm()->round(@r);
}

sub binc {
    # increment value (add 1)
    my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);

    if ($x->{sign} !~ /^[+-]$/) {       # NaN, inf, -inf
        return $downgrade -> new($x) if defined $downgrade;
        return $x;
    }

    if ($x->{sign} eq '-') {
        if ($LIB->_acmp($x->{_n}, $x->{_d}) < 0) {
            # -1/3 ++ => 2/3 (overflow at 0)
            $x->{_n} = $LIB->_sub($LIB->_copy($x->{_d}), $x->{_n});
            $x->{sign} = '+';
        } else {
            $x->{_n} = $LIB->_sub($x->{_n}, $x->{_d}); # -5/2 => -3/2
        }
    } else {
        $x->{_n} = $LIB->_add($x->{_n}, $x->{_d}); # 5/2 => 7/2
    }
    $x->bnorm()->round(@r);
}

sub binv {
    my $x = shift;
    my @r = @_;

    return $x if $x->modify('binv');

    return $x              if $x -> is_nan();
    return $x -> bzero()   if $x -> is_inf();
    return $x -> binf("+") if $x -> is_zero();

    ($x -> {_n}, $x -> {_d}) = ($x -> {_d}, $x -> {_n});
    $x -> round(@r);
}

##############################################################################
# is_foo methods (the rest is inherited)

sub is_int {
    # return true if arg (BRAT or num_str) is an integer
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    return 1 if ($x->{sign} =~ /^[+-]$/) && # NaN and +-inf aren't
      $LIB->_is_one($x->{_d});              # x/y && y != 1 => no integer
    0;
}

sub is_zero {
    # return true if arg (BRAT or num_str) is zero
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    return 1 if $x->{sign} eq '+' && $LIB->_is_zero($x->{_n});
    0;
}

sub is_one {
    # return true if arg (BRAT or num_str) is +1 or -1 if signis given
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    croak "too many arguments for is_one()" if @_ > 2;
    my $sign = $_[1] || '';
    $sign = '+' if $sign ne '-';
    return 1 if ($x->{sign} eq $sign &&
                 $LIB->_is_one($x->{_n}) && $LIB->_is_one($x->{_d}));
    0;
}

sub is_odd {
    # return true if arg (BFLOAT or num_str) is odd or false if even
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    return 1 if ($x->{sign} =~ /^[+-]$/) &&               # NaN & +-inf aren't
      ($LIB->_is_one($x->{_d}) && $LIB->_is_odd($x->{_n})); # x/2 is not, but 3/1
    0;
}

sub is_even {
    # return true if arg (BINT or num_str) is even or false if odd
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    return 0 if $x->{sign} !~ /^[+-]$/; # NaN & +-inf aren't
    return 1 if ($LIB->_is_one($x->{_d}) # x/3 is never
                 && $LIB->_is_even($x->{_n})); # but 4/1 is
    0;
}

##############################################################################
# parts() and friends

sub numerator {
    my ($class, $x) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_);

    # NaN, inf, -inf
    return Math::BigInt->new($x->{sign}) if ($x->{sign} !~ /^[+-]$/);

    my $n = Math::BigInt->new($LIB->_str($x->{_n}));
    $n->{sign} = $x->{sign};
    $n;
}

sub denominator {
    my ($class, $x) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_);

    # NaN
    return Math::BigInt->new($x->{sign}) if $x->{sign} eq 'NaN';
    # inf, -inf
    return Math::BigInt->bone() if $x->{sign} !~ /^[+-]$/;

    Math::BigInt->new($LIB->_str($x->{_d}));
}

sub parts {
    my ($class, $x) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_);

    my $c = 'Math::BigInt';

    return ($c->bnan(), $c->bnan()) if $x->{sign} eq 'NaN';
    return ($c->binf(), $c->binf()) if $x->{sign} eq '+inf';
    return ($c->binf('-'), $c->binf()) if $x->{sign} eq '-inf';

    my $n = $c->new($LIB->_str($x->{_n}));
    $n->{sign} = $x->{sign};
    my $d = $c->new($LIB->_str($x->{_d}));
    ($n, $d);
}

sub dparts {
    my $x = shift;
    my $class = ref $x;

    croak("dparts() is an instance method") unless $class;

    if ($x -> is_nan()) {
        return $class -> bnan(), $class -> bnan() if wantarray;
        return $class -> bnan();
    }

    if ($x -> is_inf()) {
        return $class -> binf($x -> sign()), $class -> bzero() if wantarray;
        return $class -> binf($x -> sign());
    }

    # 355/113 => 3 + 16/113

    my ($q, $r)  = $LIB -> _div($LIB -> _copy($x -> {_n}), $x -> {_d});

    my $int = Math::BigRat -> new($x -> {sign} . $LIB -> _str($q));
    return $int unless wantarray;

    my $frc = Math::BigRat -> new($x -> {sign} . $LIB -> _str($r),
                                  $LIB -> _str($x -> {_d}));

    return $int, $frc;
}

sub fparts {
    my $x = shift;
    my $class = ref $x;

    croak("fparts() is an instance method") unless $class;

    return ($class -> bnan(),
            $class -> bnan()) if $x -> is_nan();

    my $numer = $x -> copy();
    my $denom = $class -> bzero();

    $denom -> {_n} = $numer -> {_d};
    $numer -> {_d} = $LIB -> _one();

    return ($numer, $denom);
}

sub length {
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    return $nan unless $x->is_int();
    $LIB->_len($x->{_n});       # length(-123/1) => length(123)
}

sub digit {
    my ($class, $x, $n) = ref($_[0]) ? (undef, $_[0], $_[1]) : objectify(1, @_);

    return $nan unless $x->is_int();
    $LIB->_digit($x->{_n}, $n || 0); # digit(-123/1, 2) => digit(123, 2)
}

##############################################################################
# special calc routines

sub bceil {
    my ($class, $x) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_);

    if ($x->{sign} !~ /^[+-]$/ ||     # NaN or inf or
        $LIB->_is_one($x->{_d}))      # integer
    {
        return $downgrade -> new($x) if defined $downgrade;
        return $x;
    }

    $x->{_n} = $LIB->_div($x->{_n}, $x->{_d});  # 22/7 => 3/1 w/ truncate
    $x->{_d} = $LIB->_one();                    # d => 1
    $x->{_n} = $LIB->_inc($x->{_n}) if $x->{sign} eq '+';   # +22/7 => 4/1
    $x->{sign} = '+' if $x->{sign} eq '-' && $LIB->_is_zero($x->{_n}); # -0 => 0
    $x;
}

sub bfloor {
    my ($class, $x) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_);

    if ($x->{sign} !~ /^[+-]$/ ||     # NaN or inf or
        $LIB->_is_one($x->{_d}))      # integer
    {
        return $downgrade -> new($x) if defined $downgrade;
        return $x;
    }

    $x->{_n} = $LIB->_div($x->{_n}, $x->{_d});  # 22/7 => 3/1 w/ truncate
    $x->{_d} = $LIB->_one();                    # d => 1
    $x->{_n} = $LIB->_inc($x->{_n}) if $x->{sign} eq '-';   # -22/7 => -4/1
    $x;
}

sub bint {
    my ($class, $x) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_);

    if ($x->{sign} !~ /^[+-]$/ ||     # NaN or inf or
        $LIB->_is_one($x->{_d}))      # integer
    {
        return $downgrade -> new($x) if defined $downgrade;
        return $x;
    }

    $x->{_n} = $LIB->_div($x->{_n}, $x->{_d});  # 22/7 => 3/1 w/ truncate
    $x->{_d} = $LIB->_one();                    # d => 1
    $x->{sign} = '+' if $x->{sign} eq '-' && $LIB -> _is_zero($x->{_n});
    return $x;
}

sub bfac {
    my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);

    # if $x is not an integer
    if (($x->{sign} ne '+') || (!$LIB->_is_one($x->{_d}))) {
        return $x->bnan();
    }

    $x->{_n} = $LIB->_fac($x->{_n});
    # since _d is 1, we don't need to reduce/norm the result
    $x->round(@r);
}

sub bpow {
    # power ($x ** $y)

    # set up parameters
    my ($class, $x, $y, @r) = (ref($_[0]), @_);

    # objectify is costly, so avoid it
    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
        ($class, $x, $y, @r) = objectify(2, @_);
    }

    return $x if $x->modify('bpow');

    # $x and/or $y is a NaN
    return $x->bnan() if $x->is_nan() || $y->is_nan();

    # $x and/or $y is a +/-Inf
    if ($x->is_inf("-")) {
        return $x->bzero()   if $y->is_negative();
        return $x->bnan()    if $y->is_zero();
        return $x            if $y->is_odd();
        return $x->bneg();
    } elsif ($x->is_inf("+")) {
        return $x->bzero()   if $y->is_negative();
        return $x->bnan()    if $y->is_zero();
        return $x;
    } elsif ($y->is_inf("-")) {
        return $x->bnan()    if $x -> is_one("-");
        return $x->binf("+") if $x > -1 && $x < 1;
        return $x->bone()    if $x -> is_one("+");
        return $x->bzero();
    } elsif ($y->is_inf("+")) {
        return $x->bnan()    if $x -> is_one("-");
        return $x->bzero()   if $x > -1 && $x < 1;
        return $x->bone()    if $x -> is_one("+");
        return $x->binf("+");
    }

    if ($x -> is_zero()) {
        return $x -> bone() if $y -> is_zero();
        return $x -> binf() if $y -> is_negative();
        return $x;
    }

    # We don't support complex numbers, so upgrade or return NaN.

    if ($x -> is_negative() && !$y -> is_int()) {
        return $upgrade -> bpow($upgrade -> new($x), $y, @r)
          if defined $upgrade;
        return $x -> bnan();
    }

    if ($x -> is_one("+") || $y -> is_one()) {
        return $x;
    }

    if ($x -> is_one("-")) {
        return $x if $y -> is_odd();
        return $x -> bneg();
    }

    # (a/b)^-(c/d) = (b/a)^(c/d)
    ($x->{_n}, $x->{_d}) = ($x->{_d}, $x->{_n}) if $y->is_negative();

    unless ($LIB->_is_one($y->{_n})) {
        $x->{_n} = $LIB->_pow($x->{_n}, $y->{_n});
        $x->{_d} = $LIB->_pow($x->{_d}, $y->{_n});
        $x->{sign} = '+' if $x->{sign} eq '-' && $LIB->_is_even($y->{_n});
    }

    unless ($LIB->_is_one($y->{_d})) {
        return $x->bsqrt(@r) if $LIB->_is_two($y->{_d}); # 1/2 => sqrt
        return $x->broot($LIB->_str($y->{_d}), @r);      # 1/N => root(N)
    }

    return $x->round(@r);
}

sub blog {
    # Return the logarithm of the operand. If a second operand is defined, that
    # value is used as the base, otherwise the base is assumed to be Euler's
    # constant.

    my ($class, $x, $base, @r);

    # Don't objectify the base, since an undefined base, as in $x->blog() or
    # $x->blog(undef) signals that the base is Euler's number.

    if (!ref($_[0]) && $_[0] =~ /^[A-Za-z]|::/) {
        # E.g., Math::BigRat->blog(256, 2)
        ($class, $x, $base, @r) =
          defined $_[2] ? objectify(2, @_) : objectify(1, @_);
    } else {
        # E.g., Math::BigRat::blog(256, 2) or $x->blog(2)
        ($class, $x, $base, @r) =
          defined $_[1] ? objectify(2, @_) : objectify(1, @_);
    }

    return $x if $x->modify('blog');

    # Handle all exception cases and all trivial cases. I have used Wolfram Alpha
    # (http://www.wolframalpha.com) as the reference for these cases.

    return $x -> bnan() if $x -> is_nan();

    if (defined $base) {
        $base = $class -> new($base) unless ref $base;
        if ($base -> is_nan() || $base -> is_one()) {
            return $x -> bnan();
        } elsif ($base -> is_inf() || $base -> is_zero()) {
            return $x -> bnan() if $x -> is_inf() || $x -> is_zero();
            return $x -> bzero();
        } elsif ($base -> is_negative()) {        # -inf < base < 0
            return $x -> bzero() if $x -> is_one(); #     x = 1
            return $x -> bone()  if $x == $base;    #     x = base
            return $x -> bnan();                    #     otherwise
        }
        return $x -> bone() if $x == $base; # 0 < base && 0 < x < inf
    }

    # We now know that the base is either undefined or positive and finite.

    if ($x -> is_inf()) {       # x = +/-inf
        my $sign = defined $base && $base < 1 ? '-' : '+';
        return $x -> binf($sign);
    } elsif ($x -> is_neg()) {  # -inf < x < 0
        return $x -> bnan();
    } elsif ($x -> is_one()) {  # x = 1
        return $x -> bzero();
    } elsif ($x -> is_zero()) { # x = 0
        my $sign = defined $base && $base < 1 ? '+' : '-';
        return $x -> binf($sign);
    }

    # Now take care of the cases where $x and/or $base is 1/N.
    #
    #   log(1/N) / log(B)   = -log(N)/log(B)
    #   log(1/N) / log(1/B) =  log(N)/log(B)
    #   log(N)   / log(1/B) = -log(N)/log(B)

    my $neg = 0;
    if ($x -> numerator() -> is_one()) {
        $x -> binv();
        $neg = !$neg;
    }
    if (defined(blessed($base)) && $base -> isa($class)) {
        if ($base -> numerator() -> is_one()) {
            $base = $base -> copy() -> binv();
            $neg = !$neg;
        }
    }

    # At this point we are done handling all exception cases and trivial cases.

    $base = Math::BigFloat -> new($base) if defined $base;

    my $xn = Math::BigFloat -> new($LIB -> _str($x->{_n}));
    my $xd = Math::BigFloat -> new($LIB -> _str($x->{_d}));

    my $xtmp = Math::BigRat -> new($xn -> bdiv($xd) -> blog($base, @r) -> bsstr());

    $x -> {sign} = $xtmp -> {sign};
    $x -> {_n}   = $xtmp -> {_n};
    $x -> {_d}   = $xtmp -> {_d};

    return $neg ? $x -> bneg() : $x;
}

sub bexp {
    # set up parameters
    my ($class, $x, $y, @r) = (ref($_[0]), @_);

    # objectify is costly, so avoid it
    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
        ($class, $x, $y, @r) = objectify(1, @_);
    }

    return $x->binf(@r)  if $x->{sign} eq '+inf';
    return $x->bzero(@r) if $x->{sign} eq '-inf';

    # we need to limit the accuracy to protect against overflow
    my $fallback = 0;
    my ($scale, @params);
    ($x, @params) = $x->_find_round_parameters(@r);

    # also takes care of the "error in _find_round_parameters?" case
    return $x if $x->{sign} eq 'NaN';

    # no rounding at all, so must use fallback
    if (scalar @params == 0) {
        # simulate old behaviour
        $params[0] = $class->div_scale(); # and round to it as accuracy
        $params[1] = undef;              # P = undef
        $scale = $params[0]+4;           # at least four more for proper round
        $params[2] = $r[2];              # round mode by caller or undef
        $fallback = 1;                   # to clear a/p afterwards
    } else {
        # the 4 below is empirical, and there might be cases where it's not enough...
        $scale = abs($params[0] || $params[1]) + 4; # take whatever is defined
    }

    return $x->bone(@params) if $x->is_zero();

    # See the comments in Math::BigFloat on how this algorithm works.
    # Basically we calculate A and B (where B is faculty(N)) so that A/B = e

    my $x_org = $x->copy();
    if ($scale <= 75) {
        # set $x directly from a cached string form
        $x->{_n} =
          $LIB->_new("90933395208605785401971970164779391644753259799242");
        $x->{_d} =
          $LIB->_new("33452526613163807108170062053440751665152000000000");
        $x->{sign} = '+';
    } else {
        # compute A and B so that e = A / B.

        # After some terms we end up with this, so we use it as a starting point:
        my $A = $LIB->_new("90933395208605785401971970164779391644753259799242");
        my $F = $LIB->_new(42); my $step = 42;

        # Compute how many steps we need to take to get $A and $B sufficiently big
        my $steps = Math::BigFloat::_len_to_steps($scale - 4);
        #    print STDERR "# Doing $steps steps for ", $scale-4, " digits\n";
        while ($step++ <= $steps) {
            # calculate $a * $f + 1
            $A = $LIB->_mul($A, $F);
            $A = $LIB->_inc($A);
            # increment f
            $F = $LIB->_inc($F);
        }
        # compute $B as factorial of $steps (this is faster than doing it manually)
        my $B = $LIB->_fac($LIB->_new($steps));

        #  print "A ", $LIB->_str($A), "\nB ", $LIB->_str($B), "\n";

        $x->{_n} = $A;
        $x->{_d} = $B;
        $x->{sign} = '+';
    }

    # $x contains now an estimate of e, with some surplus digits, so we can round
    if (!$x_org->is_one()) {
        # raise $x to the wanted power and round it in one step:
        $x->bpow($x_org, @params);
    } else {
        # else just round the already computed result
        delete $x->{_a}; delete $x->{_p};
        # shortcut to not run through _find_round_parameters again
        if (defined $params[0]) {
            $x->bround($params[0], $params[2]); # then round accordingly
        } else {
            $x->bfround($params[1], $params[2]); # then round accordingly
        }
    }
    if ($fallback) {
        # clear a/p after round, since user did not request it
        delete $x->{_a}; delete $x->{_p};
    }

    $x;
}

sub bnok {
    # set up parameters
    my ($class, $x, $y, @r) = (ref($_[0]), @_);

    # objectify is costly, so avoid it
    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
        ($class, $x, $y, @r) = objectify(2, @_);
    }

    return $x->bnan() if $x->is_nan() || $y->is_nan();
    return $x->bnan() if (($x->is_finite() && !$x->is_int()) ||
                          ($y->is_finite() && !$y->is_int()));

    my $xint = Math::BigInt -> new($x -> bstr());
    my $yint = Math::BigInt -> new($y -> bstr());
    $xint -> bnok($yint);
    my $xrat = Math::BigRat -> new($xint);

    $x -> {sign} = $xrat -> {sign};
    $x -> {_n}   = $xrat -> {_n};
    $x -> {_d}   = $xrat -> {_d};

    return $x;
}

sub broot {
    # set up parameters
    my ($class, $x, $y, @r) = (ref($_[0]), @_);
    # objectify is costly, so avoid it
    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
        ($class, $x, $y, @r) = objectify(2, @_);
    }

    # Convert $x into a Math::BigFloat.

    my $xd   = Math::BigFloat -> new($LIB -> _str($x->{_d}));
    my $xflt = Math::BigFloat -> new($LIB -> _str($x->{_n})) -> bdiv($xd);
    $xflt -> {sign} = $x -> {sign};

    # Convert $y into a Math::BigFloat.

    my $yd   = Math::BigFloat -> new($LIB -> _str($y->{_d}));
    my $yflt = Math::BigFloat -> new($LIB -> _str($y->{_n})) -> bdiv($yd);
    $yflt -> {sign} = $y -> {sign};

    # Compute the root and convert back to a Math::BigRat.

    $xflt -> broot($yflt, @r);
    my $xtmp = Math::BigRat -> new($xflt -> bsstr());

    $x -> {sign} = $xtmp -> {sign};
    $x -> {_n}   = $xtmp -> {_n};
    $x -> {_d}   = $xtmp -> {_d};

    return $x;
}

sub bmodpow {
    # set up parameters
    my ($class, $x, $y, $m, @r) = (ref($_[0]), @_);
    # objectify is costly, so avoid it
    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
        ($class, $x, $y, $m, @r) = objectify(3, @_);
    }

    # Convert $x, $y, and $m into Math::BigInt objects.

    my $xint = Math::BigInt -> new($x -> copy() -> bint());
    my $yint = Math::BigInt -> new($y -> copy() -> bint());
    my $mint = Math::BigInt -> new($m -> copy() -> bint());

    $xint -> bmodpow($yint, $mint, @r);
    my $xtmp = Math::BigRat -> new($xint -> bsstr());

    $x -> {sign} = $xtmp -> {sign};
    $x -> {_n}   = $xtmp -> {_n};
    $x -> {_d}   = $xtmp -> {_d};
    return $x;
}

sub bmodinv {
    # set up parameters
    my ($class, $x, $y, @r) = (ref($_[0]), @_);
    # objectify is costly, so avoid it
    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
        ($class, $x, $y, @r) = objectify(2, @_);
    }

    # Convert $x and $y into Math::BigInt objects.

    my $xint = Math::BigInt -> new($x -> copy() -> bint());
    my $yint = Math::BigInt -> new($y -> copy() -> bint());

    $xint -> bmodinv($yint, @r);
    my $xtmp = Math::BigRat -> new($xint -> bsstr());

    $x -> {sign} = $xtmp -> {sign};
    $x -> {_n}   = $xtmp -> {_n};
    $x -> {_d}   = $xtmp -> {_d};
    return $x;
}

sub bsqrt {
    my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);

    return $x->bnan() if $x->{sign} !~ /^[+]/; # NaN, -inf or < 0
    return $x if $x->{sign} eq '+inf';         # sqrt(inf) == inf
    return $x->round(@r) if $x->is_zero() || $x->is_one();

    my $n = $x -> {_n};
    my $d = $x -> {_d};

    # Look for an exact solution. For the numerator and the denominator, take
    # the square root and square it and see if we got the original value. If we
    # did, for both the numerator and the denominator, we have an exact
    # solution.

    {
        my $nsqrt = $LIB -> _sqrt($LIB -> _copy($n));
        my $n2    = $LIB -> _mul($LIB -> _copy($nsqrt), $nsqrt);
        if ($LIB -> _acmp($n, $n2) == 0) {
            my $dsqrt = $LIB -> _sqrt($LIB -> _copy($d));
            my $d2    = $LIB -> _mul($LIB -> _copy($dsqrt), $dsqrt);
            if ($LIB -> _acmp($d, $d2) == 0) {
                $x -> {_n} = $nsqrt;
                $x -> {_d} = $dsqrt;
                return $x->round(@r);
            }
        }
    }

    local $Math::BigFloat::upgrade   = undef;
    local $Math::BigFloat::downgrade = undef;
    local $Math::BigFloat::precision = undef;
    local $Math::BigFloat::accuracy  = undef;
    local $Math::BigInt::upgrade     = undef;
    local $Math::BigInt::precision   = undef;
    local $Math::BigInt::accuracy    = undef;

    my $xn = Math::BigFloat -> new($LIB -> _str($n));
    my $xd = Math::BigFloat -> new($LIB -> _str($d));

    my $xtmp = Math::BigRat -> new($xn -> bdiv($xd) -> bsqrt() -> bsstr());

    $x -> {sign} = $xtmp -> {sign};
    $x -> {_n}   = $xtmp -> {_n};
    $x -> {_d}   = $xtmp -> {_d};

    $x->round(@r);
}

sub blsft {
    my ($class, $x, $y, $b) = objectify(2, @_);

    $b = 2 if !defined $b;
    $b = $class -> new($b) unless ref($b) && $b -> isa($class);

    return $x -> bnan() if $x -> is_nan() || $y -> is_nan() || $b -> is_nan();

    # shift by a negative amount?
    return $x -> brsft($y -> copy() -> babs(), $b) if $y -> {sign} =~ /^-/;

    $x -> bmul($b -> bpow($y));
}

sub brsft {
    my ($class, $x, $y, $b) = objectify(2, @_);

    $b = 2 if !defined $b;
    $b = $class -> new($b) unless ref($b) && $b -> isa($class);

    return $x -> bnan() if $x -> is_nan() || $y -> is_nan() || $b -> is_nan();

    # shift by a negative amount?
    return $x -> blsft($y -> copy() -> babs(), $b) if $y -> {sign} =~ /^-/;

    # the following call to bdiv() will return either quotient (scalar context)
    # or quotient and remainder (list context).
    $x -> bdiv($b -> bpow($y));
}

sub band {
    my $x     = shift;
    my $xref  = ref($x);
    my $class = $xref || $x;

    croak 'band() is an instance method, not a class method' unless $xref;
    croak 'Not enough arguments for band()' if @_ < 1;

    my $y = shift;
    $y = $class -> new($y) unless ref($y);

    my @r = @_;

    my $xtmp = Math::BigInt -> new($x -> bint());   # to Math::BigInt
    $xtmp -> band($y);
    $xtmp = $class -> new($xtmp);                   # back to Math::BigRat

    $x -> {sign} = $xtmp -> {sign};
    $x -> {_n}   = $xtmp -> {_n};
    $x -> {_d}   = $xtmp -> {_d};

    return $x -> round(@r);
}

sub bior {
    my $x     = shift;
    my $xref  = ref($x);
    my $class = $xref || $x;

    croak 'bior() is an instance method, not a class method' unless $xref;
    croak 'Not enough arguments for bior()' if @_ < 1;

    my $y = shift;
    $y = $class -> new($y) unless ref($y);

    my @r = @_;

    my $xtmp = Math::BigInt -> new($x -> bint());   # to Math::BigInt
    $xtmp -> bior($y);
    $xtmp = $class -> new($xtmp);                   # back to Math::BigRat

    $x -> {sign} = $xtmp -> {sign};
    $x -> {_n}   = $xtmp -> {_n};
    $x -> {_d}   = $xtmp -> {_d};

    return $x -> round(@r);
}

sub bxor {
    my $x     = shift;
    my $xref  = ref($x);
    my $class = $xref || $x;

    croak 'bxor() is an instance method, not a class method' unless $xref;
    croak 'Not enough arguments for bxor()' if @_ < 1;

    my $y = shift;
    $y = $class -> new($y) unless ref($y);

    my @r = @_;

    my $xtmp = Math::BigInt -> new($x -> bint());   # to Math::BigInt
    $xtmp -> bxor($y);
    $xtmp = $class -> new($xtmp);                   # back to Math::BigRat

    $x -> {sign} = $xtmp -> {sign};
    $x -> {_n}   = $xtmp -> {_n};
    $x -> {_d}   = $xtmp -> {_d};

    return $x -> round(@r);
}

sub bnot {
    my $x     = shift;
    my $xref  = ref($x);
    my $class = $xref || $x;

    croak 'bnot() is an instance method, not a class method' unless $xref;

    my @r = @_;

    my $xtmp = Math::BigInt -> new($x -> bint());   # to Math::BigInt
    $xtmp -> bnot();
    $xtmp = $class -> new($xtmp);                   # back to Math::BigRat

    $x -> {sign} = $xtmp -> {sign};
    $x -> {_n}   = $xtmp -> {_n};
    $x -> {_d}   = $xtmp -> {_d};

    return $x -> round(@r);
}

##############################################################################
# round

sub round {
    my $x = shift;
    $x = $downgrade -> new($x) if defined($downgrade) && $x -> is_int();
    $x;
}

sub bround {
    my $x = shift;
    $x = $downgrade -> new($x) if defined($downgrade) && $x -> is_int();
    $x;
}

sub bfround {
    my $x = shift;
    $x = $downgrade -> new($x) if defined($downgrade) && $x -> is_int();
    $x;
}

##############################################################################
# comparing

sub bcmp {
    # compare two signed numbers

    # set up parameters
    my ($class, $x, $y) = (ref($_[0]), @_);

    # objectify is costly, so avoid it
    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
        ($class, $x, $y) = objectify(2, @_);
    }

    if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/) {
        # $x is NaN and/or $y is NaN
        return       if $x->{sign} eq $nan || $y->{sign} eq $nan;
        # $x and $y are both either +inf or -inf
        return  0    if $x->{sign} eq $y->{sign} && $x->{sign} =~ /^[+-]inf$/;
        # $x = +inf and $y < +inf
        return +1    if $x->{sign} eq '+inf';
        # $x = -inf and $y > -inf
        return -1    if $x->{sign} eq '-inf';
        # $x < +inf and $y = +inf
        return -1    if $y->{sign} eq '+inf';
        # $x > -inf and $y = -inf
        return +1;
    }

    # $x >= 0 and $y < 0
    return  1 if $x->{sign} eq '+' && $y->{sign} eq '-';
    # $x < 0 and $y >= 0
    return -1 if $x->{sign} eq '-' && $y->{sign} eq '+';

    # At this point, we know that $x and $y have the same sign.

    # shortcut
    my $xz = $LIB->_is_zero($x->{_n});
    my $yz = $LIB->_is_zero($y->{_n});
    return  0 if $xz && $yz;               # 0 <=> 0
    return -1 if $xz && $y->{sign} eq '+'; # 0 <=> +y
    return  1 if $yz && $x->{sign} eq '+'; # +x <=> 0

    my $t = $LIB->_mul($LIB->_copy($x->{_n}), $y->{_d});
    my $u = $LIB->_mul($LIB->_copy($y->{_n}), $x->{_d});

    my $cmp = $LIB->_acmp($t, $u);     # signs are equal
    $cmp = -$cmp if $x->{sign} eq '-'; # both are '-' => reverse
    $cmp;
}

sub bacmp {
    # compare two numbers (as unsigned)

    # set up parameters
    my ($class, $x, $y) = (ref($_[0]), @_);
    # objectify is costly, so avoid it
    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
        ($class, $x, $y) = objectify(2, @_);
    }

    if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/)) {
        # handle +-inf and NaN
        return    if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
        return  0 if $x->{sign} =~ /^[+-]inf$/ && $y->{sign} =~ /^[+-]inf$/;
        return  1 if $x->{sign} =~ /^[+-]inf$/ && $y->{sign} !~ /^[+-]inf$/;
        return -1;
    }

    my $t = $LIB->_mul($LIB->_copy($x->{_n}), $y->{_d});
    my $u = $LIB->_mul($LIB->_copy($y->{_n}), $x->{_d});
    $LIB->_acmp($t, $u);        # ignore signs
}

sub beq {
    my $self    = shift;
    my $selfref = ref $self;
    #my $class   = $selfref || $self;

    croak 'beq() is an instance method, not a class method' unless $selfref;
    croak 'Wrong number of arguments for beq()' unless @_ == 1;

    my $cmp = $self -> bcmp(shift);
    return defined($cmp) && ! $cmp;
}

sub bne {
    my $self    = shift;
    my $selfref = ref $self;
    #my $class   = $selfref || $self;

    croak 'bne() is an instance method, not a class method' unless $selfref;
    croak 'Wrong number of arguments for bne()' unless @_ == 1;

    my $cmp = $self -> bcmp(shift);
    return defined($cmp) && ! $cmp ? '' : 1;
}

sub blt {
    my $self    = shift;
    my $selfref = ref $self;
    #my $class   = $selfref || $self;

    croak 'blt() is an instance method, not a class method' unless $selfref;
    croak 'Wrong number of arguments for blt()' unless @_ == 1;

    my $cmp = $self -> bcmp(shift);
    return defined($cmp) && $cmp < 0;
}

sub ble {
    my $self    = shift;
    my $selfref = ref $self;
    #my $class   = $selfref || $self;

    croak 'ble() is an instance method, not a class method' unless $selfref;
    croak 'Wrong number of arguments for ble()' unless @_ == 1;

    my $cmp = $self -> bcmp(shift);
    return defined($cmp) && $cmp <= 0;
}

sub bgt {
    my $self    = shift;
    my $selfref = ref $self;
    #my $class   = $selfref || $self;

    croak 'bgt() is an instance method, not a class method' unless $selfref;
    croak 'Wrong number of arguments for bgt()' unless @_ == 1;

    my $cmp = $self -> bcmp(shift);
    return defined($cmp) && $cmp > 0;
}

sub bge {
    my $self    = shift;
    my $selfref = ref $self;
    #my $class   = $selfref || $self;

    croak 'bge() is an instance method, not a class method'
        unless $selfref;
    croak 'Wrong number of arguments for bge()' unless @_ == 1;

    my $cmp = $self -> bcmp(shift);
    return defined($cmp) && $cmp >= 0;
}

##############################################################################
# output conversion

sub numify {
    # convert 17/8 => float (aka 2.125)
    my ($self, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    # Non-finite number.

    if ($x -> is_nan()) {
        require Math::Complex;
        my $inf = $Math::Complex::Inf;
        return $inf - $inf;
    }

    if ($x -> is_inf()) {
        require Math::Complex;
        my $inf = $Math::Complex::Inf;
        return $x -> is_negative() ? -$inf : $inf;
    }

    # Finite number.

    my $abs = $LIB->_is_one($x->{_d})
            ? $LIB->_num($x->{_n})
            : Math::BigFloat -> new($LIB->_str($x->{_n}))
                             -> bdiv($LIB->_str($x->{_d}))
                             -> bstr();
    return $x->{sign} eq '-' ? 0 - $abs : 0 + $abs;
}

sub as_int {
    my ($self, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    # NaN, inf etc
    return Math::BigInt->new($x->{sign}) if $x->{sign} !~ /^[+-]$/;

    my $u = Math::BigInt->bzero();
    $u->{value} = $LIB->_div($LIB->_copy($x->{_n}), $x->{_d}); # 22/7 => 3
    $u->bneg if $x->{sign} eq '-'; # no negative zero
    $u;
}

sub as_float {
    # return N/D as Math::BigFloat

    # set up parameters
    my ($class, $x, @r) = (ref($_[0]), @_);
    # objectify is costly, so avoid it
    ($class, $x, @r) = objectify(1, @_) unless ref $_[0];

    # NaN, inf etc
    return Math::BigFloat->new($x->{sign}) if $x->{sign} !~ /^[+-]$/;

    my $xflt = Math::BigFloat -> new($LIB -> _str($x->{_n}));
    $xflt -> {sign} = $x -> {sign};

    unless ($LIB -> _is_one($x->{_d})) {
        my $xd = Math::BigFloat -> new($LIB -> _str($x->{_d}));
        $xflt -> bdiv($xd, @r);
    }

    return $xflt;
}

sub as_bin {
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    return $x unless $x->is_int();

    my $s = $x->{sign};
    $s = '' if $s eq '+';
    $s . $LIB->_as_bin($x->{_n});
}

sub as_hex {
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    return $x unless $x->is_int();

    my $s = $x->{sign}; $s = '' if $s eq '+';
    $s . $LIB->_as_hex($x->{_n});
}

sub as_oct {
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    return $x unless $x->is_int();

    my $s = $x->{sign}; $s = '' if $s eq '+';
    $s . $LIB->_as_oct($x->{_n});
}

##############################################################################

sub from_hex {
    my $class = shift;

    # The relationship should probably go the otherway, i.e, that new() calls
    # from_hex(). Fixme!
    my ($x, @r) = @_;
    $x =~ s|^\s*(?:0?[Xx]_*)?|0x|;
    $class->new($x, @r);
}

sub from_bin {
    my $class = shift;

    # The relationship should probably go the otherway, i.e, that new() calls
    # from_bin(). Fixme!
    my ($x, @r) = @_;
    $x =~ s|^\s*(?:0?[Bb]_*)?|0b|;
    $class->new($x, @r);
}

sub from_oct {
    my $class = shift;

    # Why is this different from from_hex() and from_bin()? Fixme!
    my @parts;
    for my $c (@_) {
        push @parts, Math::BigInt->from_oct($c);
    }
    $class->new (@parts);
}

##############################################################################
# import

sub import {
    my $class = shift;
    my @a;                      # unrecognized arguments
    my $lib_param = '';
    my $lib_value = '';

    while (@_) {
        my $param = shift;

        # Enable overloading of constants.

        if ($param eq ':constant') {
            overload::constant

                integer => sub {
                    $class -> new(shift);
                },

                float   => sub {
                    $class -> new(shift);
                },

                binary  => sub {
                    # E.g., a literal 0377 shall result in an object whose value
                    # is decimal 255, but new("0377") returns decimal 377.
                    return $class -> from_oct($_[0]) if $_[0] =~ /^0_*[0-7]/;
                    $class -> new(shift);
                };
            next;
        }

        # Upgrading.

        if ($param eq 'upgrade') {
            $class -> upgrade(shift);
            next;
        }

        # Downgrading.

        if ($param eq 'downgrade') {
            $class -> downgrade(shift);
            next;
        }

        # Accuracy.

        if ($param eq 'accuracy') {
            $class -> accuracy(shift);
            next;
        }

        # Precision.

        if ($param eq 'precision') {
            $class -> precision(shift);
            next;
        }

        # Rounding mode.

        if ($param eq 'round_mode') {
            $class -> round_mode(shift);
            next;
        }

        # Backend library.

        if ($param =~ /^(lib|try|only)\z/) {
            # alternative library
            $lib_param = $param;        # "lib", "try", or "only"
            $lib_value = shift;
            next;
        }

        if ($param eq 'with') {
            # alternative class for our private parts()
            # XXX: no longer supported
            # $LIB = shift() || 'Calc';
            # carp "'with' is no longer supported, use 'lib', 'try', or 'only'";
            shift;
            next;
        }

        # Unrecognized parameter.

        push @a, $param;
    }

    require Math::BigInt;

    my @import = ('objectify');
    push @import, $lib_param, $lib_value if $lib_param ne '';
    Math::BigInt -> import(@import);

    # find out which one was actually loaded
    $LIB = Math::BigInt -> config("lib");

    # any non :constant stuff is handled by Exporter (loaded by parent class)
    # even if @_ is empty, to give it a chance
    $class->SUPER::import(@a);           # for subclasses
    $class->export_to_level(1, $class, @a); # need this, too
}

1;

__END__

=pod

=head1 NAME

Math::BigRat - arbitrary size rational number math package

=head1 SYNOPSIS

    use Math::BigRat;

    my $x = Math::BigRat->new('3/7'); $x += '5/9';

    print $x->bstr(), "\n";
    print $x ** 2, "\n";

    my $y = Math::BigRat->new('inf');
    print "$y ", ($y->is_inf ? 'is' : 'is not'), " infinity\n";

    my $z = Math::BigRat->new(144); $z->bsqrt();

=head1 DESCRIPTION

Math::BigRat complements Math::BigInt and Math::BigFloat by providing support
for arbitrary big rational numbers.

=head2 MATH LIBRARY

You can change the underlying module that does the low-level
math operations by using:

    use Math::BigRat try => 'GMP';

Note: This needs Math::BigInt::GMP installed.

The following would first try to find Math::BigInt::Foo, then
Math::BigInt::Bar, and when this also fails, revert to Math::BigInt::Calc:

    use Math::BigRat try => 'Foo,Math::BigInt::Bar';

If you want to get warned when the fallback occurs, replace "try" with "lib":

    use Math::BigRat lib => 'Foo,Math::BigInt::Bar';

If you want the code to die instead, replace "try" with "only":

    use Math::BigRat only => 'Foo,Math::BigInt::Bar';

=head1 METHODS

Any methods not listed here are derived from Math::BigFloat (or
Math::BigInt), so make sure you check these two modules for further
information.

=over

=item new()

    $x = Math::BigRat->new('1/3');

Create a new Math::BigRat object. Input can come in various forms:

    $x = Math::BigRat->new(123);                            # scalars
    $x = Math::BigRat->new('inf');                          # infinity
    $x = Math::BigRat->new('123.3');                        # float
    $x = Math::BigRat->new('1/3');                          # simple string
    $x = Math::BigRat->new('1 / 3');                        # spaced
    $x = Math::BigRat->new('1 / 0.1');                      # w/ floats
    $x = Math::BigRat->new(Math::BigInt->new(3));           # BigInt
    $x = Math::BigRat->new(Math::BigFloat->new('3.1'));     # BigFloat
    $x = Math::BigRat->new(Math::BigInt::Lite->new('2'));   # BigLite

    # You can also give D and N as different objects:
    $x = Math::BigRat->new(
            Math::BigInt->new(-123),
            Math::BigInt->new(7),
         );                      # => -123/7

=item numerator()

    $n = $x->numerator();

Returns a copy of the numerator (the part above the line) as signed BigInt.

=item denominator()

    $d = $x->denominator();

Returns a copy of the denominator (the part under the line) as positive BigInt.

=item parts()

    ($n, $d) = $x->parts();

Return a list consisting of (signed) numerator and (unsigned) denominator as
BigInts.

=item dparts()

Returns the integer part and the fraction part.

=item fparts()

Returns the smallest possible numerator and denominator so that the numerator
divided by the denominator gives back the original value. For finite numbers,
both values are integers. Mnemonic: fraction.

=item numify()

    my $y = $x->numify();

Returns the object as a scalar. This will lose some data if the object
cannot be represented by a normal Perl scalar (integer or float), so
use L</as_int()> or L</as_float()> instead.

This routine is automatically used whenever a scalar is required:

    my $x = Math::BigRat->new('3/1');
    @array = (0, 1, 2, 3);
    $y = $array[$x];                # set $y to 3

=item as_int()

=item as_number()

    $x = Math::BigRat->new('13/7');
    print $x->as_int(), "\n";               # '1'

Returns a copy of the object as BigInt, truncated to an integer.

C<as_number()> is an alias for C<as_int()>.

=item as_float()

    $x = Math::BigRat->new('13/7');
    print $x->as_float(), "\n";             # '1'

    $x = Math::BigRat->new('2/3');
    print $x->as_float(5), "\n";            # '0.66667'

Returns a copy of the object as BigFloat, preserving the
accuracy as wanted, or the default of 40 digits.

This method was added in v0.22 of Math::BigRat (April 2008).

=item as_hex()

    $x = Math::BigRat->new('13');
    print $x->as_hex(), "\n";               # '0xd'

Returns the BigRat as hexadecimal string. Works only for integers.

=item as_bin()

    $x = Math::BigRat->new('13');
    print $x->as_bin(), "\n";               # '0x1101'

Returns the BigRat as binary string. Works only for integers.

=item as_oct()

    $x = Math::BigRat->new('13');
    print $x->as_oct(), "\n";               # '015'

Returns the BigRat as octal string. Works only for integers.

=item from_hex()

    my $h = Math::BigRat->from_hex('0x10');

Create a BigRat from a hexadecimal number in string form.

=item from_oct()

    my $o = Math::BigRat->from_oct('020');

Create a BigRat from an octal number in string form.

=item from_bin()

    my $b = Math::BigRat->from_bin('0b10000000');

Create a BigRat from an binary number in string form.

=item bnan()

    $x = Math::BigRat->bnan();

Creates a new BigRat object representing NaN (Not A Number).
If used on an object, it will set it to NaN:

    $x->bnan();

=item bzero()

    $x = Math::BigRat->bzero();

Creates a new BigRat object representing zero.
If used on an object, it will set it to zero:

    $x->bzero();

=item binf()

    $x = Math::BigRat->binf($sign);

Creates a new BigRat object representing infinity. The optional argument is
either '-' or '+', indicating whether you want infinity or minus infinity.
If used on an object, it will set it to infinity:

    $x->binf();
    $x->binf('-');

=item bone()

    $x = Math::BigRat->bone($sign);

Creates a new BigRat object representing one. The optional argument is
either '-' or '+', indicating whether you want one or minus one.
If used on an object, it will set it to one:

    $x->bone();                 # +1
    $x->bone('-');              # -1

=item length()

    $len = $x->length();

Return the length of $x in digits for integer values.

=item digit()

    print Math::BigRat->new('123/1')->digit(1);     # 1
    print Math::BigRat->new('123/1')->digit(-1);    # 3

Return the N'ths digit from X when X is an integer value.

=item bnorm()

    $x->bnorm();

Reduce the number to the shortest form. This routine is called
automatically whenever it is needed.

=item bfac()

    $x->bfac();

Calculates the factorial of $x. For instance:

    print Math::BigRat->new('3/1')->bfac(), "\n";   # 1*2*3
    print Math::BigRat->new('5/1')->bfac(), "\n";   # 1*2*3*4*5

Works currently only for integers.

=item bround()/round()/bfround()

Are not yet implemented.

=item bmod()

    $x->bmod($y);

Returns $x modulo $y. When $x is finite, and $y is finite and non-zero, the
result is identical to the remainder after floored division (F-division). If,
in addition, both $x and $y are integers, the result is identical to the result
from Perl's % operator.

=item bmodinv()

    $x->bmodinv($mod);          # modular multiplicative inverse

Returns the multiplicative inverse of C<$x> modulo C<$mod>. If

    $y = $x -> copy() -> bmodinv($mod)

then C<$y> is the number closest to zero, and with the same sign as C<$mod>,
satisfying

    ($x * $y) % $mod = 1 % $mod

If C<$x> and C<$y> are non-zero, they must be relative primes, i.e.,
C<bgcd($y, $mod)==1>. 'C<NaN>' is returned when no modular multiplicative
inverse exists.

=item bmodpow()

    $num->bmodpow($exp,$mod);           # modular exponentiation
                                        # ($num**$exp % $mod)

Returns the value of C<$num> taken to the power C<$exp> in the modulus
C<$mod> using binary exponentiation.  C<bmodpow> is far superior to
writing

    $num ** $exp % $mod

because it is much faster - it reduces internal variables into
the modulus whenever possible, so it operates on smaller numbers.

C<bmodpow> also supports negative exponents.

    bmodpow($num, -1, $mod)

is exactly equivalent to

    bmodinv($num, $mod)

=item bneg()

    $x->bneg();

Used to negate the object in-place.

=item is_one()

    print "$x is 1\n" if $x->is_one();

Return true if $x is exactly one, otherwise false.

=item is_zero()

    print "$x is 0\n" if $x->is_zero();

Return true if $x is exactly zero, otherwise false.

=item is_pos()/is_positive()

    print "$x is >= 0\n" if $x->is_positive();

Return true if $x is positive (greater than or equal to zero), otherwise
false. Please note that '+inf' is also positive, while 'NaN' and '-inf' aren't.

C<is_positive()> is an alias for C<is_pos()>.

=item is_neg()/is_negative()

    print "$x is < 0\n" if $x->is_negative();

Return true if $x is negative (smaller than zero), otherwise false. Please
note that '-inf' is also negative, while 'NaN' and '+inf' aren't.

C<is_negative()> is an alias for C<is_neg()>.

=item is_int()

    print "$x is an integer\n" if $x->is_int();

Return true if $x has a denominator of 1 (e.g. no fraction parts), otherwise
false. Please note that '-inf', 'inf' and 'NaN' aren't integer.

=item is_odd()

    print "$x is odd\n" if $x->is_odd();

Return true if $x is odd, otherwise false.

=item is_even()

    print "$x is even\n" if $x->is_even();

Return true if $x is even, otherwise false.

=item bceil()

    $x->bceil();

Set $x to the next bigger integer value (e.g. truncate the number to integer
and then increment it by one).

=item bfloor()

    $x->bfloor();

Truncate $x to an integer value.

=item bint()

    $x->bint();

Round $x towards zero.

=item bsqrt()

    $x->bsqrt();

Calculate the square root of $x.

=item broot()

    $x->broot($n);

Calculate the N'th root of $x.

=item badd()

    $x->badd($y);

Adds $y to $x and returns the result.

=item bmul()

    $x->bmul($y);

Multiplies $y to $x and returns the result.

=item bsub()

    $x->bsub($y);

Subtracts $y from $x and returns the result.

=item bdiv()

    $q = $x->bdiv($y);
    ($q, $r) = $x->bdiv($y);

In scalar context, divides $x by $y and returns the result. In list context,
does floored division (F-division), returning an integer $q and a remainder $r
so that $x = $q * $y + $r. The remainer (modulo) is equal to what is returned
by C<< $x->bmod($y) >>.

=item binv()

    $x->binv();

Inverse of $x.

=item bdec()

    $x->bdec();

Decrements $x by 1 and returns the result.

=item binc()

    $x->binc();

Increments $x by 1 and returns the result.

=item copy()

    my $z = $x->copy();

Makes a deep copy of the object.

Please see the documentation in L<Math::BigInt> for further details.

=item bstr()/bsstr()

    my $x = Math::BigRat->new('8/4');
    print $x->bstr(), "\n";             # prints 1/2
    print $x->bsstr(), "\n";            # prints 1/2

Return a string representing this object.

=item bcmp()

    $x->bcmp($y);

Compares $x with $y and takes the sign into account.
Returns -1, 0, 1 or undef.

=item bacmp()

    $x->bacmp($y);

Compares $x with $y while ignoring their sign. Returns -1, 0, 1 or undef.

=item beq()

    $x -> beq($y);

Returns true if and only if $x is equal to $y, and false otherwise.

=item bne()

    $x -> bne($y);

Returns true if and only if $x is not equal to $y, and false otherwise.

=item blt()

    $x -> blt($y);

Returns true if and only if $x is equal to $y, and false otherwise.

=item ble()

    $x -> ble($y);

Returns true if and only if $x is less than or equal to $y, and false
otherwise.

=item bgt()

    $x -> bgt($y);

Returns true if and only if $x is greater than $y, and false otherwise.

=item bge()

    $x -> bge($y);

Returns true if and only if $x is greater than or equal to $y, and false
otherwise.

=item blsft()/brsft()

Used to shift numbers left/right.

Please see the documentation in L<Math::BigInt> for further details.

=item band()

    $x->band($y);               # bitwise and

=item bior()

    $x->bior($y);               # bitwise inclusive or

=item bxor()

    $x->bxor($y);               # bitwise exclusive or

=item bnot()

    $x->bnot();                 # bitwise not (two's complement)

=item bpow()

    $x->bpow($y);

Compute $x ** $y.

Please see the documentation in L<Math::BigInt> for further details.

=item blog()

    $x->blog($base, $accuracy);         # logarithm of x to the base $base

If C<$base> is not defined, Euler's number (e) is used:

    print $x->blog(undef, 100);         # log(x) to 100 digits

=item bexp()

    $x->bexp($accuracy);        # calculate e ** X

Calculates two integers A and B so that A/B is equal to C<e ** $x>, where C<e> is
Euler's number.

This method was added in v0.20 of Math::BigRat (May 2007).

See also C<blog()>.

=item bnok()

    $x->bnok($y);               # x over y (binomial coefficient n over k)

Calculates the binomial coefficient n over k, also called the "choose"
function. The result is equivalent to:

    ( n )      n!
    | - |  = -------
    ( k )    k!(n-k)!

This method was added in v0.20 of Math::BigRat (May 2007).

=item config()

    Math::BigRat->config("trap_nan" => 1);      # set
    $accu = Math::BigRat->config("accuracy");   # get

Set or get configuration parameter values. Read-only parameters are marked as
RO. Read-write parameters are marked as RW. The following parameters are
supported.

    Parameter       RO/RW   Description
                            Example
    ============================================================
    lib             RO      Name of the math backend library
                            Math::BigInt::Calc
    lib_version     RO      Version of the math backend library
                            0.30
    class           RO      The class of config you just called
                            Math::BigRat
    version         RO      version number of the class you used
                            0.10
    upgrade         RW      To which class numbers are upgraded
                            undef
    downgrade       RW      To which class numbers are downgraded
                            undef
    precision       RW      Global precision
                            undef
    accuracy        RW      Global accuracy
                            undef
    round_mode      RW      Global round mode
                            even
    div_scale       RW      Fallback accuracy for div, sqrt etc.
                            40
    trap_nan        RW      Trap NaNs
                            undef
    trap_inf        RW      Trap +inf/-inf
                            undef

=back

=head1 NUMERIC LITERALS

After C<use Math::BigRat ':constant'> all numeric literals in the given scope
are converted to C<Math::BigRat> objects. This conversion happens at compile
time. Every non-integer is convert to a NaN.

For example,

    perl -MMath::BigRat=:constant -le 'print 2**150'

prints the exact value of C<2**150>. Note that without conversion of constants
to objects the expression C<2**150> is calculated using Perl scalars, which
leads to an inaccurate result.

Please note that strings are not affected, so that

    use Math::BigRat qw/:constant/;

    $x = "1234567890123456789012345678901234567890"
            + "123456789123456789";

does give you what you expect. You need an explicit Math::BigRat->new() around
at least one of the operands. You should also quote large constants to prevent
loss of precision:

    use Math::BigRat;

    $x = Math::BigRat->new("1234567889123456789123456789123456789");

Without the quotes Perl first converts the large number to a floating point
constant at compile time, and then converts the result to a Math::BigRat object
at run time, which results in an inaccurate result.

=head2 Hexadecimal, octal, and binary floating point literals

Perl (and this module) accepts hexadecimal, octal, and binary floating point
literals, but use them with care with Perl versions before v5.32.0, because some
versions of Perl silently give the wrong result. Below are some examples of
different ways to write the number decimal 314.

Hexadecimal floating point literals:

    0x1.3ap+8         0X1.3AP+8
    0x1.3ap8          0X1.3AP8
    0x13a0p-4         0X13A0P-4

Octal floating point literals (with "0" prefix):

    01.164p+8         01.164P+8
    01.164p8          01.164P8
    011640p-4         011640P-4

Octal floating point literals (with "0o" prefix) (requires v5.34.0):

    0o1.164p+8        0O1.164P+8
    0o1.164p8         0O1.164P8
    0o11640p-4        0O11640P-4

Binary floating point literals:

    0b1.0011101p+8    0B1.0011101P+8
    0b1.0011101p8     0B1.0011101P8
    0b10011101000p-2  0B10011101000P-2

=head1 BUGS

Please report any bugs or feature requests to
C<bug-math-bigrat at rt.cpan.org>, or through the web interface at
L<https://rt.cpan.org/Ticket/Create.html?Queue=Math-BigRat>
(requires login).
We 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 perldoc command.

    perldoc Math::BigRat

You can also look for information at:

=over 4

=item * GitHub

L<https://github.com/pjacklam/p5-Math-BigRat>

=item * RT: CPAN's request tracker

L<https://rt.cpan.org/Dist/Display.html?Name=Math-BigRat>

=item * MetaCPAN

L<https://metacpan.org/release/Math-BigRat>

=item * CPAN Testers Matrix

L<http://matrix.cpantesters.org/?dist=Math-BigRat>

=item * CPAN Ratings

L<https://cpanratings.perl.org/dist/Math-BigRat>

=back

=head1 LICENSE

This program is free software; you may redistribute it and/or modify it under
the same terms as Perl itself.

=head1 SEE ALSO

L<bigrat>, L<Math::BigFloat> and L<Math::BigInt> as well as the backends
L<Math::BigInt::FastCalc>, L<Math::BigInt::GMP>, and L<Math::BigInt::Pari>.

=head1 AUTHORS

=over 4

=item *

Tels L<http://bloodgate.com/> 2001-2009.

=item *

Maintained by Peter John Acklam <pjacklam@gmail.com> 2011-

=back

=cut
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 package Net::Ping;

require 5.002;
require Exporter;

use strict;
use vars qw(@ISA @EXPORT @EXPORT_OK $VERSION
            $def_timeout $def_proto $def_factor $def_family
            $max_datasize $pingstring $hires $source_verify $syn_forking);
use Fcntl qw( F_GETFL F_SETFL O_NONBLOCK );
use Socket 2.007;
use Socket qw( SOCK_DGRAM SOCK_STREAM SOCK_RAW AF_INET PF_INET IPPROTO_TCP
	       SOL_SOCKET SO_ERROR SO_BROADCAST
               IPPROTO_IP IP_TOS IP_TTL
               inet_ntoa inet_aton getnameinfo sockaddr_in );
use POSIX qw( ENOTCONN ECONNREFUSED ECONNRESET EINPROGRESS EWOULDBLOCK EAGAIN
	      WNOHANG );
use FileHandle;
use Carp;
use Time::HiRes;

@ISA = qw(Exporter);
@EXPORT = qw(pingecho);
@EXPORT_OK = qw(wakeonlan);
$VERSION = "2.74";

# Globals

$def_timeout = 5;           # Default timeout to wait for a reply
$def_proto = "tcp";         # Default protocol to use for pinging
$def_factor = 1.2;          # Default exponential backoff rate.
$def_family = AF_INET;      # Default family.
$max_datasize = 65535;      # Maximum data bytes. recommended: 1472 (Ethernet MTU: 1500)
# The data we exchange with the server for the stream protocol
$pingstring = "pingschwingping!\n";
$source_verify = 1;         # Default is to verify source endpoint
$syn_forking = 0;

# Constants

my $AF_INET6  = eval { Socket::AF_INET6() } || 30;
my $AF_UNSPEC = eval { Socket::AF_UNSPEC() };
my $AI_NUMERICHOST = eval { Socket::AI_NUMERICHOST() } || 4;
my $NI_NUMERICHOST = eval { Socket::NI_NUMERICHOST() } || 2;
my $IPPROTO_IPV6   = eval { Socket::IPPROTO_IPV6() }   || 41;
my $NIx_NOSERV = eval { Socket::NIx_NOSERV() } || 2;
#my $IPV6_HOPLIMIT  = eval { Socket::IPV6_HOPLIMIT() };  # ping6 -h 0-255
my $qr_family = qr/^(?:(?:(:?ip)?v?(?:4|6))|${\AF_INET}|$AF_INET6)$/;
my $qr_family4 = qr/^(?:(?:(:?ip)?v?4)|${\AF_INET})$/;
my $Socket_VERSION = eval $Socket::VERSION;

if ($^O =~ /Win32/i) {
  # Hack to avoid this Win32 spewage:
  # Your vendor has not defined POSIX macro ECONNREFUSED
  my @pairs = (ECONNREFUSED => 10061, # "Unknown Error" Special Win32 Response?
	       ENOTCONN     => 10057,
	       ECONNRESET   => 10054,
	       EINPROGRESS  => 10036,
	       EWOULDBLOCK  => 10035,
	  );
  while (my $name = shift @pairs) {
    my $value = shift @pairs;
    # When defined, these all are non-zero
    unless (eval $name) {
      no strict 'refs';
      *{$name} = defined prototype \&{$name} ? sub () {$value} : sub {$value};
    }
  }
#  $syn_forking = 1;    # XXX possibly useful in < Win2K ?
};

# Description:  The pingecho() subroutine is provided for backward
# compatibility with the original Net::Ping.  It accepts a host
# name/IP and an optional timeout in seconds.  Create a tcp ping
# object and try pinging the host.  The result of the ping is returned.

sub pingecho
{
  my ($host,              # Name or IP number of host to ping
      $timeout            # Optional timeout in seconds
      ) = @_;
  my ($p);                # A ping object

  $p = Net::Ping->new("tcp", $timeout);
  $p->ping($host);        # Going out of scope closes the connection
}

# Description:  The new() method creates a new ping object.  Optional
# parameters may be specified for the protocol to use, the timeout in
# seconds and the size in bytes of additional data which should be
# included in the packet.
#   After the optional parameters are checked, the data is constructed
# and a socket is opened if appropriate.  The object is returned.

sub new
{
  my ($this,
      $proto,             # Optional protocol to use for pinging
      $timeout,           # Optional timeout in seconds
      $data_size,         # Optional additional bytes of data
      $device,            # Optional device to use
      $tos,               # Optional ToS to set
      $ttl,               # Optional TTL to set
      $family,            # Optional address family (AF_INET)
      ) = @_;
  my  $class = ref($this) || $this;
  my  $self = {};
  my ($cnt,               # Count through data bytes
      $min_datasize       # Minimum data bytes required
      );

  bless($self, $class);
  if (ref $proto eq 'HASH') { # support named args
    for my $k (qw(proto timeout data_size device tos ttl family
                  gateway host port bind retrans pingstring source_verify
                  econnrefused dontfrag
                  IPV6_USE_MIN_MTU IPV6_RECVPATHMTU IPV6_HOPLIMIT))
    {
      if (exists $proto->{$k}) {
        $self->{$k} = $proto->{$k};
        # some are still globals
        if ($k eq 'pingstring') { $pingstring = $proto->{$k} }
        if ($k eq 'source_verify') { $source_verify = $proto->{$k} }
        # and some are local
        $timeout = $proto->{$k}   if ($k eq 'timeout');
        $data_size = $proto->{$k} if ($k eq 'data_size');
        $device = $proto->{$k}    if ($k eq 'device');
        $tos = $proto->{$k}       if ($k eq 'tos');
        $ttl = $proto->{$k}       if ($k eq 'ttl');
        $family = $proto->{$k}    if ($k eq 'family');
        delete $proto->{$k};
      }
    }
    if (%$proto) {
      croak("Invalid named argument: ",join(" ",keys (%$proto)));
    }
    $proto = $self->{'proto'};
  }

  $proto = $def_proto unless $proto;          # Determine the protocol
  croak('Protocol for ping must be "icmp", "icmpv6", "udp", "tcp", "syn", "stream" or "external"')
    unless $proto =~ m/^(icmp|icmpv6|udp|tcp|syn|stream|external)$/;
  $self->{proto} = $proto;

  $timeout = $def_timeout unless defined $timeout;    # Determine the timeout
  croak("Default timeout for ping must be greater than 0 seconds")
    if $timeout <= 0;
  $self->{timeout} = $timeout;

  $self->{device} = $device;

  $self->{tos} = $tos;

  if ($self->{'host'}) {
    my $host = $self->{'host'};
    my $ip = $self->_resolv($host) or
      carp("could not resolve host $host");
    $self->{host} = $ip;
    $self->{family} = $ip->{family};
  }

  if ($self->{bind}) {
    my $addr = $self->{bind};
    my $ip = $self->_resolv($addr)
      or carp("could not resolve local addr $addr");
    $self->{local_addr} = $ip;
  } else {
    $self->{local_addr} = undef;              # Don't bind by default
  }

  if ($self->{proto} eq 'icmp') {
    croak('TTL must be from 0 to 255')
      if ($ttl && ($ttl < 0 || $ttl > 255));
    $self->{ttl} = $ttl;
  }

  if ($family) {
    if ($family =~ $qr_family) {
      if ($family =~ $qr_family4) {
        $self->{family} = AF_INET;
      } else {
        $self->{family} = $AF_INET6;
      }
    } else {
      croak('Family must be "ipv4" or "ipv6"')
    }
  } else {
    if ($self->{proto} eq 'icmpv6') {
      $self->{family} = $AF_INET6;
    } else {
      $self->{family} = $def_family;
    }
  }

  $min_datasize = ($proto eq "udp") ? 1 : 0;  # Determine data size
  $data_size = $min_datasize unless defined($data_size) && $proto ne "tcp";
  # allow for fragmented packets if data_size>1472 (MTU 1500)
  croak("Data for ping must be from $min_datasize to $max_datasize bytes")
    if ($data_size < $min_datasize) || ($data_size > $max_datasize);
  $data_size-- if $self->{proto} eq "udp";  # We provide the first byte
  $self->{data_size} = $data_size;

  $self->{data} = "";                       # Construct data bytes
  for ($cnt = 0; $cnt < $self->{data_size}; $cnt++)
  {
    $self->{data} .= chr($cnt % 256);
  }

  # Default exponential backoff rate
  $self->{retrans} = $def_factor unless exists $self->{retrans};
  # Default Connection refused behavior
  $self->{econnrefused} = undef unless exists $self->{econnrefused};

  $self->{seq} = 0;                         # For counting packets
  if ($self->{proto} eq "udp")              # Open a socket
  {
    $self->{proto_num} = eval { (getprotobyname('udp'))[2] } ||
      croak("Can't udp protocol by name");
    $self->{port_num} = $self->{port}
      || (getservbyname('echo', 'udp'))[2]
      || croak("Can't get udp echo port by name");
    $self->{fh} = FileHandle->new();
    socket($self->{fh}, PF_INET, SOCK_DGRAM,
           $self->{proto_num}) ||
             croak("udp socket error - $!");
    $self->_setopts();
  }
  elsif ($self->{proto} eq "icmp")
  {
    croak("icmp ping requires root privilege") if !_isroot();
    $self->{proto_num} = eval { (getprotobyname('icmp'))[2] } ||
      croak("Can't get icmp protocol by name");
    $self->{pid} = $$ & 0xffff;           # Save lower 16 bits of pid
    $self->{fh} = FileHandle->new();
    socket($self->{fh}, PF_INET, SOCK_RAW, $self->{proto_num}) ||
      croak("icmp socket error - $!");
    $self->_setopts();
    if ($self->{'ttl'}) {
      setsockopt($self->{fh}, IPPROTO_IP, IP_TTL, pack("I*", $self->{'ttl'}))
        or croak "error configuring ttl to $self->{'ttl'} $!";
    }
  }
  elsif ($self->{proto} eq "icmpv6")
  {
    #croak("icmpv6 ping requires root privilege") if !_isroot();
    croak("Wrong family $self->{family} for icmpv6 protocol")
      if $self->{family} and $self->{family} != $AF_INET6;
    $self->{family} = $AF_INET6;
    $self->{proto_num} = eval { (getprotobyname('ipv6-icmp'))[2] } ||
      croak("Can't get ipv6-icmp protocol by name"); # 58
    $self->{pid} = $$ & 0xffff;           # Save lower 16 bits of pid
    $self->{fh} = FileHandle->new();
    socket($self->{fh}, $AF_INET6, SOCK_RAW, $self->{proto_num}) ||
      croak("icmp socket error - $!");
    $self->_setopts();
    if ($self->{'gateway'}) {
      my $g = $self->{gateway};
      my $ip = $self->_resolv($g)
        or croak("nonexistent gateway $g");
      $self->{family} eq $AF_INET6
        or croak("gateway requires the AF_INET6 family");
      $ip->{family} eq $AF_INET6
        or croak("gateway address needs to be IPv6");
      my $IPV6_NEXTHOP = eval { Socket::IPV6_NEXTHOP() } || 48; # IPV6_3542NEXTHOP, or 21
      setsockopt($self->{fh}, $IPPROTO_IPV6, $IPV6_NEXTHOP, _pack_sockaddr_in($ip))
        or croak "error configuring gateway to $g NEXTHOP $!";
    }
    if (exists $self->{IPV6_USE_MIN_MTU}) {
      my $IPV6_USE_MIN_MTU = eval { Socket::IPV6_USE_MIN_MTU() } || 42;
      setsockopt($self->{fh}, $IPPROTO_IPV6, $IPV6_USE_MIN_MTU,
                 pack("I*", $self->{'IPV6_USE_MIN_MT'}))
        or croak "error configuring IPV6_USE_MIN_MT} $!";
    }
    if (exists $self->{IPV6_RECVPATHMTU}) {
      my $IPV6_RECVPATHMTU = eval { Socket::IPV6_RECVPATHMTU() } || 43;
      setsockopt($self->{fh}, $IPPROTO_IPV6, $IPV6_RECVPATHMTU,
                 pack("I*", $self->{'RECVPATHMTU'}))
        or croak "error configuring IPV6_RECVPATHMTU $!";
    }
    if ($self->{'tos'}) {
      my $proto = $self->{family} == AF_INET ? IPPROTO_IP : $IPPROTO_IPV6;
      setsockopt($self->{fh}, $proto, IP_TOS, pack("I*", $self->{'tos'}))
        or croak "error configuring tos to $self->{'tos'} $!";
    }
    if ($self->{'ttl'}) {
      my $proto = $self->{family} == AF_INET ? IPPROTO_IP : $IPPROTO_IPV6;
      setsockopt($self->{fh}, $proto, IP_TTL, pack("I*", $self->{'ttl'}))
        or croak "error configuring ttl to $self->{'ttl'} $!";
    }
  }
  elsif ($self->{proto} eq "tcp" || $self->{proto} eq "stream")
  {
    $self->{proto_num} = eval { (getprotobyname('tcp'))[2] } ||
      croak("Can't get tcp protocol by name");
    $self->{port_num} = $self->{port}
      || (getservbyname('echo', 'tcp'))[2]
      ||  croak("Can't get tcp echo port by name");
    $self->{fh} = FileHandle->new();
  }
  elsif ($self->{proto} eq "syn")
  {
    $self->{proto_num} = eval { (getprotobyname('tcp'))[2] } ||
      croak("Can't get tcp protocol by name");
    $self->{port_num} = (getservbyname('echo', 'tcp'))[2] ||
      croak("Can't get tcp echo port by name");
    if ($syn_forking) {
      $self->{fork_rd} = FileHandle->new();
      $self->{fork_wr} = FileHandle->new();
      pipe($self->{fork_rd}, $self->{fork_wr});
      $self->{fh} = FileHandle->new();
      $self->{good} = {};
      $self->{bad} = {};
    } else {
      $self->{wbits} = "";
      $self->{bad} = {};
    }
    $self->{syn} = {};
    $self->{stop_time} = 0;
  }

  return($self);
}

# Description: Set the local IP address from which pings will be sent.
# For ICMP, UDP and TCP pings, just saves the address to be used when 
# the socket is opened.  Returns non-zero if successful; croaks on error.
sub bind
{
  my ($self,
      $local_addr         # Name or IP number of local interface
      ) = @_;
  my ($ip,                # Hash of addr (string), addr_in (packed), family
      $h		  # resolved hash
      );

  croak("Usage: \$p->bind(\$local_addr)") unless @_ == 2;
  croak("already bound") if defined($self->{local_addr}) &&
    ($self->{proto} eq "udp" || $self->{proto} eq "icmp");

  $ip = $self->_resolv($local_addr);
  carp("nonexistent local address $local_addr") unless defined($ip);
  $self->{local_addr} = $ip;

  if (($self->{proto} ne "udp") && 
      ($self->{proto} ne "icmp") && 
      ($self->{proto} ne "tcp") && 
      ($self->{proto} ne "syn"))
  {
    croak("Unknown protocol \"$self->{proto}\" in bind()");
  }

  return 1;
}

# Description: A select() wrapper that compensates for platform
# peculiarities.
sub mselect
{
    if ($_[3] > 0 and $^O eq 'MSWin32') {
	# On windows, select() doesn't process the message loop,
	# but sleep() will, allowing alarm() to interrupt the latter.
	# So we chop up the timeout into smaller pieces and interleave
	# select() and sleep() calls.
	my $t = $_[3];
	my $gran = 0.5;  # polling granularity in seconds
	my @args = @_;
	while (1) {
	    $gran = $t if $gran > $t;
	    my $nfound = select($_[0], $_[1], $_[2], $gran);
	    undef $nfound if $nfound == -1;
	    $t -= $gran;
	    return $nfound if $nfound or !defined($nfound) or $t <= 0;

	    sleep(0);
	    ($_[0], $_[1], $_[2]) = @args;
	}
    }
    else {
	my $nfound = select($_[0], $_[1], $_[2], $_[3]);
	undef $nfound if $nfound == -1;
	return $nfound;
    }
}

# Description: Allow UDP source endpoint comparison to be
#              skipped for those remote interfaces that do
#              not response from the same endpoint.

sub source_verify
{
  my $self = shift;
  $source_verify = 1 unless defined
    ($source_verify = ((defined $self) && (ref $self)) ? shift() : $self);
}

# Description: Set whether or not the connect
# behavior should enforce remote service
# availability as well as reachability.

sub service_check
{
  my $self = shift;
  $self->{econnrefused} = 1 unless defined
    ($self->{econnrefused} = shift());
}

sub tcp_service_check
{
  service_check(@_);
}

# Description: Set exponential backoff for retransmission.
# Should be > 1 to retain exponential properties.
# If set to 0, retransmissions are disabled.

sub retrans
{
  my $self = shift;
  $self->{retrans} = shift;
}

sub _IsAdminUser {
  return unless $^O eq 'MSWin32' or $^O eq "cygwin";
  return unless eval { require Win32 };
  return unless defined &Win32::IsAdminUser;
  return Win32::IsAdminUser();
}

sub _isroot {
  if (($> and $^O ne 'VMS' and $^O ne 'cygwin')
    or (($^O eq 'MSWin32' or $^O eq 'cygwin')
        and !_IsAdminUser())
    or ($^O eq 'VMS'
        and (`write sys\$output f\$privilege("SYSPRV")` =~ m/FALSE/))) {
      return 0;
  }
  else {
    return 1;
  }
}

# Description: Sets ipv6 reachability
# REACHCONF was removed in RFC3542, ping6 -R supports it. requires root.

sub IPV6_REACHCONF
{
  my $self = shift;
  my $on = shift;
  if ($on) {
    my $reachconf = eval { Socket::IPV6_REACHCONF() };
    if (!$reachconf) {
      carp "IPV6_REACHCONF not supported on this platform";
      return 0;
    }
    if (!_isroot()) {
      carp "IPV6_REACHCONF requires root permissions";
      return 0;
    }
    $self->{IPV6_REACHCONF} = 1;
  }
  else {
    return $self->{IPV6_REACHCONF};
  }
}

# Description: set it on or off.

sub IPV6_USE_MIN_MTU
{
  my $self = shift;
  my $on = shift;
  if (defined $on) {
    my $IPV6_USE_MIN_MTU = eval { Socket::IPV6_USE_MIN_MTU() } || 43;
    #if (!$IPV6_USE_MIN_MTU) {
    #  carp "IPV6_USE_MIN_MTU not supported on this platform";
    #  return 0;
    #}
    $self->{IPV6_USE_MIN_MTU} = $on ? 1 : 0;
    setsockopt($self->{fh}, $IPPROTO_IPV6, $IPV6_USE_MIN_MTU,
               pack("I*", $self->{'IPV6_USE_MIN_MT'}))
      or croak "error configuring IPV6_USE_MIN_MT} $!";
  }
  else {
    return $self->{IPV6_USE_MIN_MTU};
  }
}

# Description: notify an according MTU

sub IPV6_RECVPATHMTU
{
  my $self = shift;
  my $on = shift;
  if ($on) {
    my $IPV6_RECVPATHMTU = eval { Socket::IPV6_RECVPATHMTU() } || 43;
    #if (!$RECVPATHMTU) {
    #  carp "IPV6_RECVPATHMTU not supported on this platform";
    #  return 0;
    #}
    $self->{IPV6_RECVPATHMTU} = 1;
    setsockopt($self->{fh}, $IPPROTO_IPV6, $IPV6_RECVPATHMTU,
               pack("I*", $self->{'IPV6_RECVPATHMTU'}))
      or croak "error configuring IPV6_RECVPATHMTU} $!";
  }
  else {
    return $self->{IPV6_RECVPATHMTU};
  }
}

# Description: allows the module to use milliseconds as returned by
# the Time::HiRes module

$hires = 1;
sub hires
{
  my $self = shift;
  $hires = 1 unless defined
    ($hires = ((defined $self) && (ref $self)) ? shift() : $self);
}

sub time
{
  return $hires ? Time::HiRes::time() : CORE::time();
}

# Description: Sets or clears the O_NONBLOCK flag on a file handle.
sub socket_blocking_mode
{
  my ($self,
      $fh,              # the file handle whose flags are to be modified
      $block) = @_;     # if true then set the blocking
                        # mode (clear O_NONBLOCK), otherwise
                        # set the non-blocking mode (set O_NONBLOCK)

  my $flags;
  if ($^O eq 'MSWin32' || $^O eq 'VMS') {
      # FIONBIO enables non-blocking sockets on windows and vms.
      # FIONBIO is (0x80000000|(4<<16)|(ord('f')<<8)|126), as per winsock.h, ioctl.h
      my $f = 0x8004667e;
      my $v = pack("L", $block ? 0 : 1);
      ioctl($fh, $f, $v) or croak("ioctl failed: $!");
      return;
  }
  if ($flags = fcntl($fh, F_GETFL, 0)) {
    $flags = $block ? ($flags & ~O_NONBLOCK) : ($flags | O_NONBLOCK);
    if (!fcntl($fh, F_SETFL, $flags)) {
      croak("fcntl F_SETFL: $!");
    }
  } else {
    croak("fcntl F_GETFL: $!");
  }
}

# Description: Ping a host name or IP number with an optional timeout.
# First lookup the host, and return undef if it is not found.  Otherwise
# perform the specific ping method based on the protocol.  Return the
# result of the ping.

sub ping
{
  my ($self,
      $host,              # Name or IP number of host to ping
      $timeout,           # Seconds after which ping times out
      $family,            # Address family
      ) = @_;
  my ($ip,                # Hash of addr (string), addr_in (packed), family
      $ret,               # The return value
      $ping_time,         # When ping began
      );

  $host = $self->{host} if !defined $host and $self->{host};
  croak("Usage: \$p->ping([ \$host [, \$timeout [, \$family]]])") if @_ > 4 or !$host;
  $timeout = $self->{timeout} unless $timeout;
  croak("Timeout must be greater than 0 seconds") if $timeout <= 0;

  if ($family) {
    if ($family =~ $qr_family) {
      if ($family =~ $qr_family4) {
        $self->{family_local} = AF_INET;
      } else {
        $self->{family_local} = $AF_INET6;
      }
    } else {
      croak('Family must be "ipv4" or "ipv6"')
    }
  } else {
    $self->{family_local} = $self->{family};
  }
  
  $ip = $self->_resolv($host);
  return () unless defined($ip);      # Does host exist?

  # Dispatch to the appropriate routine.
  $ping_time = &time();
  if ($self->{proto} eq "external") {
    $ret = $self->ping_external($ip, $timeout);
  }
  elsif ($self->{proto} eq "udp") {
    $ret = $self->ping_udp($ip, $timeout);
  }
  elsif ($self->{proto} eq "icmp") {
    $ret = $self->ping_icmp($ip, $timeout);
  }
  elsif ($self->{proto} eq "icmpv6") {
    $ret = $self->ping_icmpv6($ip, $timeout);
  }
  elsif ($self->{proto} eq "tcp") {
    $ret = $self->ping_tcp($ip, $timeout);
  }
  elsif ($self->{proto} eq "stream") {
    $ret = $self->ping_stream($ip, $timeout);
  }
  elsif ($self->{proto} eq "syn") {
    $ret = $self->ping_syn($host, $ip, $ping_time, $ping_time+$timeout);
  } else {
    croak("Unknown protocol \"$self->{proto}\" in ping()");
  }

  return wantarray ? ($ret, &time() - $ping_time, $self->ntop($ip)) : $ret;
}

# Uses Net::Ping::External to do an external ping.
sub ping_external {
  my ($self,
      $ip,                # Hash of addr (string), addr_in (packed), family
      $timeout,           # Seconds after which ping times out
      $family
     ) = @_;

  $ip = $self->{host} if !defined $ip and $self->{host};
  $timeout = $self->{timeout} if !defined $timeout and $self->{timeout};
  my @addr = exists $ip->{addr_in}
    ? ('ip' => $ip->{addr_in})
    : ('host' => $ip->{host});

  eval {
    local @INC = @INC;
    pop @INC if $INC[-1] eq '.';
    require Net::Ping::External;
  } or croak('Protocol "external" not supported on your system: Net::Ping::External not found');
  return Net::Ping::External::ping(@addr, timeout => $timeout,
                                   family => $family);
}

# h2ph "asm/socket.h"
# require "asm/socket.ph";
use constant SO_BINDTODEVICE  => 25;
use constant ICMP_ECHOREPLY   => 0;   # ICMP packet types
use constant ICMPv6_ECHOREPLY => 129; # ICMP packet types
use constant ICMP_UNREACHABLE => 3;   # ICMP packet types
use constant ICMPv6_UNREACHABLE => 1; # ICMP packet types
use constant ICMPv6_NI_REPLY => 140;  # ICMP packet types
use constant ICMP_ECHO        => 8;
use constant ICMPv6_ECHO      => 128;
use constant ICMP_TIME_EXCEEDED => 11; # ICMP packet types
use constant ICMP_PARAMETER_PROBLEM => 12; # ICMP packet types
use constant ICMP_TIMESTAMP   => 13;
use constant ICMP_TIMESTAMP_REPLY => 14;
use constant ICMP_STRUCT      => "C2 n3 A"; # Structure of a minimal ICMP packet
use constant ICMP_TIMESTAMP_STRUCT => "C2 n3 N3"; # Structure of a minimal timestamp ICMP packet
use constant SUBCODE          => 0; # No ICMP subcode for ECHO and ECHOREPLY
use constant ICMP_FLAGS       => 0; # No special flags for send or recv
use constant ICMP_PORT        => 0; # No port with ICMP
use constant IP_MTU_DISCOVER  => 10; # linux only

sub message_type
{
  my ($self,
      $type
      ) = @_;

  croak "Setting message type only supported on 'icmp' protocol"
    unless $self->{proto} eq 'icmp';

  return $self->{message_type} || 'echo'
    unless defined($type);

  croak "Supported icmp message type are limited to 'echo' and 'timestamp': '$type' not supported"
    unless $type =~ /^echo|timestamp$/i;

  $self->{message_type} = lc($type);
}

sub ping_icmp
{
  my ($self,
      $ip,                # Hash of addr (string), addr_in (packed), family
      $timeout            # Seconds after which ping times out
      ) = @_;

  my ($saddr,             # sockaddr_in with port and ip
      $checksum,          # Checksum of ICMP packet
      $msg,               # ICMP packet to send
      $len_msg,           # Length of $msg
      $rbits,             # Read bits, filehandles for reading
      $nfound,            # Number of ready filehandles found
      $finish_time,       # Time ping should be finished
      $done,              # set to 1 when we are done
      $ret,               # Return value
      $recv_msg,          # Received message including IP header
      $recv_msg_len,      # Length of recevied message, less any additional data
      $from_saddr,        # sockaddr_in of sender
      $from_port,         # Port packet was sent from
      $from_ip,           # Packed IP of sender
      $timestamp_msg,     # ICMP timestamp message type
      $from_type,         # ICMP type
      $from_subcode,      # ICMP subcode
      $from_chk,          # ICMP packet checksum
      $from_pid,          # ICMP packet id
      $from_seq,          # ICMP packet sequence
      $from_msg           # ICMP message
      );

  $ip = $self->{host} if !defined $ip and $self->{host};
  $timeout = $self->{timeout} if !defined $timeout and $self->{timeout};
  $timestamp_msg = $self->{message_type} && $self->{message_type} eq 'timestamp' ? 1 : 0;

  socket($self->{fh}, $ip->{family}, SOCK_RAW, $self->{proto_num}) ||
    croak("icmp socket error - $!");

  if (defined $self->{local_addr} &&
      !CORE::bind($self->{fh}, _pack_sockaddr_in(0, $self->{local_addr}))) {
    croak("icmp bind error - $!");
  }
  $self->_setopts();

  $self->{seq} = ($self->{seq} + 1) % 65536; # Increment sequence
  $checksum = 0;                          # No checksum for starters
  if ($ip->{family} == AF_INET) {
    if ($timestamp_msg) {
      $msg = pack(ICMP_TIMESTAMP_STRUCT, ICMP_TIMESTAMP, SUBCODE,
                  $checksum, $self->{pid}, $self->{seq}, 0, 0, 0);
    } else {
      $msg = pack(ICMP_STRUCT . $self->{data_size}, ICMP_ECHO, SUBCODE,
                  $checksum, $self->{pid}, $self->{seq}, $self->{data});
    }
  } else {
                                          # how to get SRC
    my $pseudo_header = pack('a16a16Nnn', $ip->{addr_in}, $ip->{addr_in}, 8+length($self->{data}), 0, 0x003a);
    $msg = pack(ICMP_STRUCT . $self->{data_size}, ICMPv6_ECHO, SUBCODE,
                $checksum, $self->{pid}, $self->{seq}, $self->{data});
    $msg = $pseudo_header.$msg
  }
  $checksum = Net::Ping->checksum($msg);
  if ($ip->{family} == AF_INET) {
    if ($timestamp_msg) {
      $msg = pack(ICMP_TIMESTAMP_STRUCT, ICMP_TIMESTAMP, SUBCODE,
                  $checksum, $self->{pid}, $self->{seq}, 0, 0, 0);
    } else {
      $msg = pack(ICMP_STRUCT . $self->{data_size}, ICMP_ECHO, SUBCODE,
                  $checksum, $self->{pid}, $self->{seq}, $self->{data});
    }
  } else {
    $msg = pack(ICMP_STRUCT . $self->{data_size}, ICMPv6_ECHO, SUBCODE,
                $checksum, $self->{pid}, $self->{seq}, $self->{data});
  }
  $len_msg = length($msg);
  $saddr = _pack_sockaddr_in(ICMP_PORT, $ip);
  $self->{from_ip} = undef;
  $self->{from_type} = undef;
  $self->{from_subcode} = undef;
  send($self->{fh}, $msg, ICMP_FLAGS, $saddr); # Send the message

  $rbits = "";
  vec($rbits, $self->{fh}->fileno(), 1) = 1;
  $ret = 0;
  $done = 0;
  $finish_time = &time() + $timeout;      # Must be done by this time
  while (!$done && $timeout > 0)          # Keep trying if we have time
  {
    $nfound = mselect((my $rout=$rbits), undef, undef, $timeout); # Wait for packet
    $timeout = $finish_time - &time();    # Get remaining time
    if (!defined($nfound))                # Hmm, a strange error
    {
      $ret = undef;
      $done = 1;
    }
    elsif ($nfound)                     # Got a packet from somewhere
    {
      $recv_msg = "";
      $from_pid = -1;
      $from_seq = -1;
      $from_saddr = recv($self->{fh}, $recv_msg, 1500, ICMP_FLAGS);
      $recv_msg_len = length($recv_msg) - length($self->{data});
      ($from_port, $from_ip) = _unpack_sockaddr_in($from_saddr, $ip->{family});
      # ICMP echo includes the header and ICMPv6 doesn't.
      # IPv4 length($recv_msg) is 28 (20 header + 8 payload)
      # while IPv6 length is only 8 (sans header).
      my $off = ($ip->{family} == AF_INET) ? 20 : 0; # payload offset
      ($from_type, $from_subcode) = unpack("C2", substr($recv_msg, $off, 2));
      if ($from_type == ICMP_TIMESTAMP_REPLY) {
        ($from_pid, $from_seq) = unpack("n3", substr($recv_msg, $off + 4, 4))
          if length $recv_msg >= $off + 8;
      } elsif ($from_type == ICMP_ECHOREPLY || $from_type == ICMPv6_ECHOREPLY) {
        #warn "ICMP_ECHOREPLY: ", $ip->{family}, " ",$recv_msg, ":", length($recv_msg);
        ($from_pid, $from_seq) = unpack("n2", substr($recv_msg, $off + 4, 4))
          if $recv_msg_len == $off + 8;
      } elsif ($from_type == ICMPv6_NI_REPLY) {
        ($from_pid, $from_seq) = unpack("n2", substr($recv_msg, 4, 4))
          if ($ip->{family} == $AF_INET6 && length $recv_msg == 8);
      } else {
        #warn "ICMP: ", $from_type, " ",$ip->{family}, " ",$recv_msg, ":", length($recv_msg);
        ($from_pid, $from_seq) = unpack("n2", substr($recv_msg, $off + 32, 4))
          if length $recv_msg >= $off + 36;
      }
      $self->{from_ip} = $from_ip;
      $self->{from_type} = $from_type;
      $self->{from_subcode} = $from_subcode;
      next if ($from_pid != $self->{pid});
      next if ($from_seq != $self->{seq});
      if (! $source_verify || ($self->ntop($from_ip) eq $self->ntop($ip))) { # Does the packet check out?
        if (!$timestamp_msg && (($from_type == ICMP_ECHOREPLY) || ($from_type == ICMPv6_ECHOREPLY))) {
          $ret = 1;
          $done = 1;
        } elsif ($timestamp_msg && $from_type == ICMP_TIMESTAMP_REPLY) {
          $ret = 1;
          $done = 1;
        } elsif (($from_type == ICMP_UNREACHABLE) || ($from_type == ICMPv6_UNREACHABLE)) {
          $done = 1;
        } elsif ($from_type == ICMP_TIME_EXCEEDED) {
          $ret = 0;
          $done = 1;
        }
      }
    } else {     # Oops, timed out
      $done = 1;
    }
  }
  return $ret;
}

sub ping_icmpv6
{
  shift->ping_icmp(@_);
}

sub icmp_result {
  my ($self) = @_;
  my $addr = $self->{from_ip} || "";
  $addr = "\0\0\0\0" unless 4 == length $addr;
  return ($self->ntop($addr),($self->{from_type} || 0), ($self->{from_subcode} || 0));
}

# Description:  Do a checksum on the message.  Basically sum all of
# the short words and fold the high order bits into the low order bits.

sub checksum
{
  my ($class,
      $msg            # The message to checksum
      ) = @_;
  my ($len_msg,       # Length of the message
      $num_short,     # The number of short words in the message
      $short,         # One short word
      $chk            # The checksum
      );

  $len_msg = length($msg);
  $num_short = int($len_msg / 2);
  $chk = 0;
  foreach $short (unpack("n$num_short", $msg))
  {
    $chk += $short;
  }                                           # Add the odd byte in
  $chk += (unpack("C", substr($msg, $len_msg - 1, 1)) << 8) if $len_msg % 2;
  $chk = ($chk >> 16) + ($chk & 0xffff);      # Fold high into low
  return(~(($chk >> 16) + $chk) & 0xffff);    # Again and complement
}


# Description:  Perform a tcp echo ping.  Since a tcp connection is
# host specific, we have to open and close each connection here.  We
# can't just leave a socket open.  Because of the robust nature of
# tcp, it will take a while before it gives up trying to establish a
# connection.  Therefore, we use select() on a non-blocking socket to
# check against our timeout.  No data bytes are actually
# sent since the successful establishment of a connection is proof
# enough of the reachability of the remote host.  Also, tcp is
# expensive and doesn't need our help to add to the overhead.

sub ping_tcp
{
  my ($self,
      $ip,                # Hash of addr (string), addr_in (packed), family
      $timeout            # Seconds after which ping times out
      ) = @_;
  my ($ret                # The return value
      );

  $ip = $self->{host} if !defined $ip and $self->{host};
  $timeout = $self->{timeout} if !defined $timeout and $self->{timeout};

  $! = 0;
  $ret = $self -> tcp_connect( $ip, $timeout);
  if (!$self->{econnrefused} &&
      $! == ECONNREFUSED) {
    $ret = 1;  # "Connection refused" means reachable
  }
  $self->{fh}->close();
  return $ret;
}

sub tcp_connect
{
  my ($self,
      $ip,                # Hash of addr (string), addr_in (packed), family
      $timeout            # Seconds after which connect times out
      ) = @_;
  my ($saddr);            # Packed IP and Port

  $ip = $self->{host} if !defined $ip and $self->{host};
  $timeout = $self->{timeout} if !defined $timeout and $self->{timeout};

  $saddr = _pack_sockaddr_in($self->{port_num}, $ip);

  my $ret = 0;            # Default to unreachable

  my $do_socket = sub {
    socket($self->{fh}, $ip->{family}, SOCK_STREAM, $self->{proto_num}) ||
      croak("tcp socket error - $!");
    if (defined $self->{local_addr} &&
        !CORE::bind($self->{fh}, _pack_sockaddr_in(0, $self->{local_addr}))) {
      croak("tcp bind error - $!");
    }
    $self->_setopts();
  };
  my $do_connect = sub {
    $self->{ip} = $ip->{addr_in};
    # ECONNREFUSED is 10061 on MSWin32. If we pass it as child error through $?,
    # we'll get (10061 & 255) = 77, so we cannot check it in the parent process.
    return ($ret = connect($self->{fh}, $saddr) || ($! == ECONNREFUSED && !$self->{econnrefused}));
  };
  my $do_connect_nb = sub {
    # Set O_NONBLOCK property on filehandle
    $self->socket_blocking_mode($self->{fh}, 0);

    # start the connection attempt
    if (!connect($self->{fh}, $saddr)) {
      if ($! == ECONNREFUSED) {
        $ret = 1 unless $self->{econnrefused};
      } elsif ($! != EINPROGRESS && ($^O ne 'MSWin32' || $! != EWOULDBLOCK)) {
        # EINPROGRESS is the expected error code after a connect()
        # on a non-blocking socket.  But if the kernel immediately
        # determined that this connect() will never work,
        # Simply respond with "unreachable" status.
        # (This can occur on some platforms with errno
        # EHOSTUNREACH or ENETUNREACH.)
        return 0;
      } else {
        # Got the expected EINPROGRESS.
        # Just wait for connection completion...
        my ($wbits, $wout, $wexc);
        $wout = $wexc = $wbits = "";
        vec($wbits, $self->{fh}->fileno, 1) = 1;

        my $nfound = mselect(undef,
			    ($wout = $wbits),
			    ($^O eq 'MSWin32' ? ($wexc = $wbits) : undef),
			    $timeout);
        warn("select: $!") unless defined $nfound;

        if ($nfound && vec($wout, $self->{fh}->fileno, 1)) {
          # the socket is ready for writing so the connection
          # attempt completed. test whether the connection
          # attempt was successful or not

          if (getpeername($self->{fh})) {
            # Connection established to remote host
            $ret = 1;
          } else {
            # TCP ACK will never come from this host
            # because there was an error connecting.

            # This should set $! to the correct error.
            my $char;
            sysread($self->{fh},$char,1);
            $! = ECONNREFUSED if ($! == EAGAIN && $^O =~ /cygwin/i);

            $ret = 1 if (!$self->{econnrefused}
                         && $! == ECONNREFUSED);
          }
        } else {
          # the connection attempt timed out (or there were connect
	  # errors on Windows)
	  if ($^O =~ 'MSWin32') {
	      # If the connect will fail on a non-blocking socket,
	      # winsock reports ECONNREFUSED as an exception, and we
	      # need to fetch the socket-level error code via getsockopt()
	      # instead of using the thread-level error code that is in $!.
	      if ($nfound && vec($wexc, $self->{fh}->fileno, 1)) {
		  $! = unpack("i", getsockopt($self->{fh}, SOL_SOCKET,
			                      SO_ERROR));
	      }
	  }
        }
      }
    } else {
      # Connection established to remote host
      $ret = 1;
    }

    # Unset O_NONBLOCK property on filehandle
    $self->socket_blocking_mode($self->{fh}, 1);
    $self->{ip} = $ip->{addr_in};
    return $ret;
  };

  if ($syn_forking) {
    # Buggy Winsock API doesn't allow nonblocking connect.
    # Hence, if our OS is Windows, we need to create a separate
    # process to do the blocking connect attempt.
    # XXX Above comments are not true at least for Win2K, where
    # nonblocking connect works.

    $| = 1; # Clear buffer prior to fork to prevent duplicate flushing.
    $self->{'tcp_chld'} = fork;
    if (!$self->{'tcp_chld'}) {
      if (!defined $self->{'tcp_chld'}) {
        # Fork did not work
        warn "Fork error: $!";
        return 0;
      }
      &{ $do_socket }();

      # Try a slow blocking connect() call
      # and report the status to the parent.
      if ( &{ $do_connect }() ) {
        $self->{fh}->close();
        # No error
        exit 0;
      } else {
        # Pass the error status to the parent
        # Make sure that $! <= 255
        exit($! <= 255 ? $! : 255);
      }
    }

    &{ $do_socket }();

    my $patience = &time() + $timeout;

    my ($child, $child_errno);
    $? = 0; $child_errno = 0;
    # Wait up to the timeout
    # And clean off the zombie
    do {
      $child = waitpid($self->{'tcp_chld'}, &WNOHANG());
      $child_errno = $? >> 8;
      select(undef, undef, undef, 0.1);
    } while &time() < $patience && $child != $self->{'tcp_chld'};

    if ($child == $self->{'tcp_chld'}) {
      if ($self->{proto} eq "stream") {
        # We need the socket connected here, in parent
        # Should be safe to connect because the child finished
        # within the timeout
        &{ $do_connect }();
      }
      # $ret cannot be set by the child process
      $ret = !$child_errno;
    } else {
      # Time must have run out.
      # Put that choking client out of its misery
      kill "KILL", $self->{'tcp_chld'};
      # Clean off the zombie
      waitpid($self->{'tcp_chld'}, 0);
      $ret = 0;
    }
    delete $self->{'tcp_chld'};
    $! = $child_errno;
  } else {
    # Otherwise don't waste the resources to fork

    &{ $do_socket }();

    &{ $do_connect_nb }();
  }

  return $ret;
}

sub DESTROY {
  my $self = shift;
  if ($self->{'proto'} eq 'tcp' &&
      $self->{'tcp_chld'}) {
    # Put that choking client out of its misery
    kill "KILL", $self->{'tcp_chld'};
    # Clean off the zombie
    waitpid($self->{'tcp_chld'}, 0);
  }
}

# This writes the given string to the socket and then reads it
# back.  It returns 1 on success, 0 on failure.
sub tcp_echo
{
  my ($self, $timeout, $pingstring) = @_;

  $timeout = $self->{timeout} if !defined $timeout and $self->{timeout};
  $pingstring = $self->{pingstring} if !defined $pingstring and $self->{pingstring};

  my $ret = undef;
  my $time = &time();
  my $wrstr = $pingstring;
  my $rdstr = "";

  eval <<'EOM';
    do {
      my $rin = "";
      vec($rin, $self->{fh}->fileno(), 1) = 1;

      my $rout = undef;
      if($wrstr) {
        $rout = "";
        vec($rout, $self->{fh}->fileno(), 1) = 1;
      }

      if(mselect($rin, $rout, undef, ($time + $timeout) - &time())) {

        if($rout && vec($rout,$self->{fh}->fileno(),1)) {
          my $num = syswrite($self->{fh}, $wrstr, length $wrstr);
          if($num) {
            # If it was a partial write, update and try again.
            $wrstr = substr($wrstr,$num);
          } else {
            # There was an error.
            $ret = 0;
          }
        }

        if(vec($rin,$self->{fh}->fileno(),1)) {
          my $reply;
          if(sysread($self->{fh},$reply,length($pingstring)-length($rdstr))) {
            $rdstr .= $reply;
            $ret = 1 if $rdstr eq $pingstring;
          } else {
            # There was an error.
            $ret = 0;
          }
        }

      }
    } until &time() > ($time + $timeout) || defined($ret);
EOM

  return $ret;
}

# Description: Perform a stream ping.  If the tcp connection isn't
# already open, it opens it.  It then sends some data and waits for
# a reply.  It leaves the stream open on exit.

sub ping_stream
{
  my ($self,
      $ip,                # Hash of addr (string), addr_in (packed), family
      $timeout            # Seconds after which ping times out
      ) = @_;

  # Open the stream if it's not already open
  if(!defined $self->{fh}->fileno()) {
    $self->tcp_connect($ip, $timeout) or return 0;
  }

  croak "tried to switch servers while stream pinging"
    if $self->{ip} ne $ip->{addr_in};

  return $self->tcp_echo($timeout, $pingstring);
}

# Description: opens the stream.  You would do this if you want to
# separate the overhead of opening the stream from the first ping.

sub open
{
  my ($self,
      $host,              # Host or IP address
      $timeout,           # Seconds after which open times out
      $family
      ) = @_;
  my $ip;                 # Hash of addr (string), addr_in (packed), family
  $host = $self->{host} unless defined $host;

  if ($family) {
    if ($family =~ $qr_family) {
      if ($family =~ $qr_family4) {
        $self->{family_local} = AF_INET;
      } else {
        $self->{family_local} = $AF_INET6;
      }
    } else {
      croak('Family must be "ipv4" or "ipv6"')
    }
  } else {
    $self->{family_local} = $self->{family};
  }

  $timeout = $self->{timeout} unless $timeout;
  $ip = $self->_resolv($host);

  if ($self->{proto} eq "stream") {
    if (defined($self->{fh}->fileno())) {
      croak("socket is already open");
    } else {
      return () unless $ip;
      $self->tcp_connect($ip, $timeout);
    }
  }
}

sub _dontfrag {
  my $self = shift;
  # bsd solaris
  my $IP_DONTFRAG = eval { Socket::IP_DONTFRAG() };
  if ($IP_DONTFRAG) {
    my $i = 1;
    setsockopt($self->{fh}, IPPROTO_IP, $IP_DONTFRAG, pack("I*", $i))
      or croak "error configuring IP_DONTFRAG $!";
    # Linux needs more: Path MTU Discovery as defined in RFC 1191
    # For non SOCK_STREAM sockets it is the user's responsibility to packetize
    # the data in MTU sized chunks and to do the retransmits if necessary.
    # The kernel will reject packets that are bigger than the known path
    # MTU if this flag is set (with EMSGSIZE).
    if ($^O eq 'linux') {
      my $i = 2; # IP_PMTUDISC_DO
      setsockopt($self->{fh}, IPPROTO_IP, IP_MTU_DISCOVER, pack("I*", $i))
        or croak "error configuring IP_MTU_DISCOVER $!";
    }
  }
}

# SO_BINDTODEVICE + IP_TOS
sub _setopts {
  my $self = shift;
  if ($self->{'device'}) {
    setsockopt($self->{fh}, SOL_SOCKET, SO_BINDTODEVICE, pack("Z*", $self->{'device'}))
      or croak "error binding to device $self->{'device'} $!";
  }
  if ($self->{'tos'}) { # need to re-apply ToS (RT #6706)
    setsockopt($self->{fh}, IPPROTO_IP, IP_TOS, pack("I*", $self->{'tos'}))
      or croak "error applying tos to $self->{'tos'} $!";
  }
  if ($self->{'dontfrag'}) {
    $self->_dontfrag;
  }
}  


# Description:  Perform a udp echo ping.  Construct a message of
# at least the one-byte sequence number and any additional data bytes.
# Send the message out and wait for a message to come back.  If we
# get a message, make sure all of its parts match.  If they do, we are
# done.  Otherwise go back and wait for the message until we run out
# of time.  Return the result of our efforts.

use constant UDP_FLAGS => 0; # Nothing special on send or recv
sub ping_udp
{
  my ($self,
      $ip,                # Hash of addr (string), addr_in (packed), family
      $timeout            # Seconds after which ping times out
      ) = @_;

  my ($saddr,             # sockaddr_in with port and ip
      $ret,               # The return value
      $msg,               # Message to be echoed
      $finish_time,       # Time ping should be finished
      $flush,             # Whether socket needs to be disconnected
      $connect,           # Whether socket needs to be connected
      $done,              # Set to 1 when we are done pinging
      $rbits,             # Read bits, filehandles for reading
      $nfound,            # Number of ready filehandles found
      $from_saddr,        # sockaddr_in of sender
      $from_msg,          # Characters echoed by $host
      $from_port,         # Port message was echoed from
      $from_ip            # Packed IP number of sender
      );

  $saddr = _pack_sockaddr_in($self->{port_num}, $ip);
  $self->{seq} = ($self->{seq} + 1) % 256;    # Increment sequence
  $msg = chr($self->{seq}) . $self->{data};   # Add data if any

  socket($self->{fh}, $ip->{family}, SOCK_DGRAM,
         $self->{proto_num}) ||
           croak("udp socket error - $!");

  if (defined $self->{local_addr} &&
      !CORE::bind($self->{fh}, _pack_sockaddr_in(0, $self->{local_addr}))) {
    croak("udp bind error - $!");
  }

  $self->_setopts();

  if ($self->{connected}) {
    if ($self->{connected} ne $saddr) {
      # Still connected to wrong destination.
      # Need to flush out the old one.
      $flush = 1;
    }
  } else {
    # Not connected yet.
    # Need to connect() before send()
    $connect = 1;
  }

  # Have to connect() and send() instead of sendto()
  # in order to pick up on the ECONNREFUSED setting
  # from recv() or double send() errno as utilized in
  # the concept by rdw @ perlmonks.  See:
  # http://perlmonks.thepen.com/42898.html
  if ($flush) {
    # Need to socket() again to flush the descriptor
    # This will disconnect from the old saddr.
    socket($self->{fh}, $ip->{family}, SOCK_DGRAM,
           $self->{proto_num});
    $self->_setopts();
  }
  # Connect the socket if it isn't already connected
  # to the right destination.
  if ($flush || $connect) {
    connect($self->{fh}, $saddr);               # Tie destination to socket
    $self->{connected} = $saddr;
  }
  send($self->{fh}, $msg, UDP_FLAGS);           # Send it

  $rbits = "";
  vec($rbits, $self->{fh}->fileno(), 1) = 1;
  $ret = 0;                   # Default to unreachable
  $done = 0;
  my $retrans = 0.01;
  my $factor = $self->{retrans};
  $finish_time = &time() + $timeout;       # Ping needs to be done by then
  while (!$done && $timeout > 0)
  {
    if ($factor > 1)
    {
      $timeout = $retrans if $timeout > $retrans;
      $retrans*= $factor; # Exponential backoff
    }
    $nfound  = mselect((my $rout=$rbits), undef, undef, $timeout); # Wait for response
    my $why = $!;
    $timeout = $finish_time - &time();   # Get remaining time

    if (!defined($nfound))  # Hmm, a strange error
    {
      $ret = undef;
      $done = 1;
    }
    elsif ($nfound)         # A packet is waiting
    {
      $from_msg = "";
      $from_saddr = recv($self->{fh}, $from_msg, 1500, UDP_FLAGS);
      if (!$from_saddr) {
        # For example an unreachable host will make recv() fail.
        if (!$self->{econnrefused} &&
            ($! == ECONNREFUSED ||
             $! == ECONNRESET)) {
          # "Connection refused" means reachable
          # Good, continue
          $ret = 1;
        }
        $done = 1;
      } else {
        ($from_port, $from_ip) = _unpack_sockaddr_in($from_saddr, $ip->{family});
        my $addr_in = ref($ip) eq "HASH" ? $ip->{addr_in} : $ip;
        if (!$source_verify ||
            (($from_ip eq $addr_in) &&        # Does the packet check out?
             ($from_port == $self->{port_num}) &&
             ($from_msg eq $msg)))
        {
          $ret = 1;       # It's a winner
          $done = 1;
        }
      }
    }
    elsif ($timeout <= 0)              # Oops, timed out
    {
      $done = 1;
    }
    else
    {
      # Send another in case the last one dropped
      if (send($self->{fh}, $msg, UDP_FLAGS)) {
        # Another send worked?  The previous udp packet
        # must have gotten lost or is still in transit.
        # Hopefully this new packet will arrive safely.
      } else {
        if (!$self->{econnrefused} &&
            $! == ECONNREFUSED) {
          # "Connection refused" means reachable
          # Good, continue
          $ret = 1;
        }
        $done = 1;
      }
    }
  }
  return $ret;
}

# Description: Send a TCP SYN packet to host specified.
sub ping_syn
{
  my $self = shift;
  my $host = shift;
  my $ip = shift;
  my $start_time = shift;
  my $stop_time = shift;

  if ($syn_forking) {
    return $self->ping_syn_fork($host, $ip, $start_time, $stop_time);
  }

  my $fh = FileHandle->new();
  my $saddr = _pack_sockaddr_in($self->{port_num}, $ip);

  # Create TCP socket
  if (!socket ($fh, $ip->{family}, SOCK_STREAM, $self->{proto_num})) {
    croak("tcp socket error - $!");
  }

  if (defined $self->{local_addr} &&
      !CORE::bind($fh, _pack_sockaddr_in(0, $self->{local_addr}))) {
    croak("tcp bind error - $!");
  }

  $self->_setopts();
  # Set O_NONBLOCK property on filehandle
  $self->socket_blocking_mode($fh, 0);

  # Attempt the non-blocking connect
  # by just sending the TCP SYN packet
  if (connect($fh, $saddr)) {
    # Non-blocking, yet still connected?
    # Must have connected very quickly,
    # or else it wasn't very non-blocking.
    #warn "WARNING: Nonblocking connect connected anyway? ($^O)";
  } else {
    # Error occurred connecting.
    if ($! == EINPROGRESS || ($^O eq 'MSWin32' && $! == EWOULDBLOCK)) {
      # The connection is just still in progress.
      # This is the expected condition.
    } else {
      # Just save the error and continue on.
      # The ack() can check the status later.
      $self->{bad}->{$host} = $!;
    }
  }

  my $entry = [ $host, $ip, $fh, $start_time, $stop_time, $self->{port_num} ];
  $self->{syn}->{$fh->fileno} = $entry;
  if ($self->{stop_time} < $stop_time) {
    $self->{stop_time} = $stop_time;
  }
  vec($self->{wbits}, $fh->fileno, 1) = 1;

  return 1;
}

sub ping_syn_fork {
  my ($self, $host, $ip, $start_time, $stop_time) = @_;

  # Buggy Winsock API doesn't allow nonblocking connect.
  # Hence, if our OS is Windows, we need to create a separate
  # process to do the blocking connect attempt.
  my $pid = fork();
  if (defined $pid) {
    if ($pid) {
      # Parent process
      my $entry = [ $host, $ip, $pid, $start_time, $stop_time ];
      $self->{syn}->{$pid} = $entry;
      if ($self->{stop_time} < $stop_time) {
        $self->{stop_time} = $stop_time;
      }
    } else {
      # Child process
      my $saddr = _pack_sockaddr_in($self->{port_num}, $ip);

      # Create TCP socket
      if (!socket ($self->{fh}, $ip->{family}, SOCK_STREAM, $self->{proto_num})) {
        croak("tcp socket error - $!");
      }

      if (defined $self->{local_addr} &&
          !CORE::bind($self->{fh}, _pack_sockaddr_in(0, $self->{local_addr}))) {
        croak("tcp bind error - $!");
      }

      $self->_setopts();

      $!=0;
      # Try to connect (could take a long time)
      connect($self->{fh}, $saddr);
      # Notify parent of connect error status
      my $err = $!+0;
      my $wrstr = "$$ $err";
      # Force to 16 chars including \n
      $wrstr .= " "x(15 - length $wrstr). "\n";
      syswrite($self->{fork_wr}, $wrstr, length $wrstr);
      exit;
    }
  } else {
    # fork() failed?
    die "fork: $!";
  }
  return 1;
}

# Description: Wait for TCP ACK from host specified
# from ping_syn above.  If no host is specified, wait
# for TCP ACK from any of the hosts in the SYN queue.
sub ack
{
  my $self = shift;

  if ($self->{proto} eq "syn") {
    if ($syn_forking) {
      my @answer = $self->ack_unfork(shift);
      return wantarray ? @answer : $answer[0];
    }
    my $wbits = "";
    my $stop_time = 0;
    if (my $host = shift or $self->{host}) {
      # Host passed as arg or as option to new
      $host = $self->{host} unless defined $host;
      if (exists $self->{bad}->{$host}) {
        if (!$self->{econnrefused} &&
            $self->{bad}->{ $host } &&
            (($! = ECONNREFUSED)>0) &&
            $self->{bad}->{ $host } eq "$!") {
          # "Connection refused" means reachable
          # Good, continue
        } else {
          # ECONNREFUSED means no good
          return ();
        }
      }
      my $host_fd = undef;
      foreach my $fd (keys %{ $self->{syn} }) {
        my $entry = $self->{syn}->{$fd};
        if ($entry->[0] eq $host) {
          $host_fd = $fd;
          $stop_time = $entry->[4]
            || croak("Corrupted SYN entry for [$host]");
          last;
        }
      }
      croak("ack called on [$host] without calling ping first!")
        unless defined $host_fd;
      vec($wbits, $host_fd, 1) = 1;
    } else {
      # No $host passed so scan all hosts
      # Use the latest stop_time
      $stop_time = $self->{stop_time};
      # Use all the bits
      $wbits = $self->{wbits};
    }

    while ($wbits !~ /^\0*\z/) {
      my $timeout = $stop_time - &time();
      # Force a minimum of 10 ms timeout.
      $timeout = 0.01 if $timeout <= 0.01;

      my $winner_fd = undef;
      my $wout = $wbits;
      my $fd = 0;
      # Do "bad" fds from $wbits first
      while ($wout !~ /^\0*\z/) {
        if (vec($wout, $fd, 1)) {
          # Wipe it from future scanning.
          vec($wout, $fd, 1) = 0;
          if (my $entry = $self->{syn}->{$fd}) {
            if ($self->{bad}->{ $entry->[0] }) {
              $winner_fd = $fd;
              last;
            }
          }
        }
        $fd++;
      }

      if (defined($winner_fd) or my $nfound = mselect(undef, ($wout=$wbits), undef, $timeout)) {
        if (defined $winner_fd) {
          $fd = $winner_fd;
        } else {
          # Done waiting for one of the ACKs
          $fd = 0;
          # Determine which one
          while ($wout !~ /^\0*\z/ &&
                 !vec($wout, $fd, 1)) {
            $fd++;
          }
        }
        if (my $entry = $self->{syn}->{$fd}) {
          # Wipe it from future scanning.
          delete $self->{syn}->{$fd};
          vec($self->{wbits}, $fd, 1) = 0;
          vec($wbits, $fd, 1) = 0;
          if (!$self->{econnrefused} &&
              $self->{bad}->{ $entry->[0] } &&
              (($! = ECONNREFUSED)>0) &&
              $self->{bad}->{ $entry->[0] } eq "$!") {
            # "Connection refused" means reachable
            # Good, continue
          } elsif (getpeername($entry->[2])) {
            # Connection established to remote host
            # Good, continue
          } else {
            # TCP ACK will never come from this host
            # because there was an error connecting.

            # This should set $! to the correct error.
            my $char;
            sysread($entry->[2],$char,1);
            # Store the excuse why the connection failed.
            $self->{bad}->{$entry->[0]} = $!;
            if (!$self->{econnrefused} &&
                (($! == ECONNREFUSED) ||
                 ($! == EAGAIN && $^O =~ /cygwin/i))) {
              # "Connection refused" means reachable
              # Good, continue
            } else {
              # No good, try the next socket...
              next;
            }
          }
          # Everything passed okay, return the answer
          return wantarray ?
            ($entry->[0], &time() - $entry->[3], $self->ntop($entry->[1]), $entry->[5])
            : $entry->[0];
        } else {
          warn "Corrupted SYN entry: unknown fd [$fd] ready!";
          vec($wbits, $fd, 1) = 0;
          vec($self->{wbits}, $fd, 1) = 0;
        }
      } elsif (defined $nfound) {
        # Timed out waiting for ACK
        foreach my $fd (keys %{ $self->{syn} }) {
          if (vec($wbits, $fd, 1)) {
            my $entry = $self->{syn}->{$fd};
            $self->{bad}->{$entry->[0]} = "Timed out";
            vec($wbits, $fd, 1) = 0;
            vec($self->{wbits}, $fd, 1) = 0;
            delete $self->{syn}->{$fd};
          }
        }
      } else {
        # Weird error occurred with select()
        warn("select: $!");
        $self->{syn} = {};
        $wbits = "";
      }
    }
  }
  return ();
}

sub ack_unfork {
  my ($self,$host) = @_;
  my $stop_time = $self->{stop_time};
  if ($host) {
    # Host passed as arg
    if (my $entry = $self->{good}->{$host}) {
      delete $self->{good}->{$host};
      return ($entry->[0], &time() - $entry->[3], $self->ntop($entry->[1]));
    }
  }

  my $rbits = "";
  my $timeout;

  if (keys %{ $self->{syn} }) {
    # Scan all hosts that are left
    vec($rbits, fileno($self->{fork_rd}), 1) = 1;
    $timeout = $stop_time - &time();
    # Force a minimum of 10 ms timeout.
    $timeout = 0.01 if $timeout < 0.01;
  } else {
    # No hosts left to wait for
    $timeout = 0;
  }

  if ($timeout > 0) {
    my $nfound;
    while ( keys %{ $self->{syn} } and
           $nfound = mselect((my $rout=$rbits), undef, undef, $timeout)) {
      # Done waiting for one of the ACKs
      if (!sysread($self->{fork_rd}, $_, 16)) {
        # Socket closed, which means all children are done.
        return ();
      }
      my ($pid, $how) = split;
      if ($pid) {
        # Flush the zombie
        waitpid($pid, 0);
        if (my $entry = $self->{syn}->{$pid}) {
          # Connection attempt to remote host is done
          delete $self->{syn}->{$pid};
          if (!$how || # If there was no error connecting
              (!$self->{econnrefused} &&
               $how == ECONNREFUSED)) {  # "Connection refused" means reachable
            if ($host && $entry->[0] ne $host) {
              # A good connection, but not the host we need.
              # Move it from the "syn" hash to the "good" hash.
              $self->{good}->{$entry->[0]} = $entry;
              # And wait for the next winner
              next;
            }
            return ($entry->[0], &time() - $entry->[3], $self->ntop($entry->[1]));
          }
        } else {
          # Should never happen
          die "Unknown ping from pid [$pid]";
        }
      } else {
        die "Empty response from status socket?";
      }
    }
    if (defined $nfound) {
      # Timed out waiting for ACK status
    } else {
      # Weird error occurred with select()
      warn("select: $!");
    }
  }
  if (my @synners = keys %{ $self->{syn} }) {
    # Kill all the synners
    kill 9, @synners;
    foreach my $pid (@synners) {
      # Wait for the deaths to finish
      # Then flush off the zombie
      waitpid($pid, 0);
    }
  }
  $self->{syn} = {};
  return ();
}

# Description:  Tell why the ack() failed
sub nack {
  my $self = shift;
  my $host = shift || croak('Usage> nack($failed_ack_host)');
  return $self->{bad}->{$host} || undef;
}

# Description:  Close the connection.

sub close
{
  my ($self) = @_;

  if ($self->{proto} eq "syn") {
    delete $self->{syn};
  } elsif ($self->{proto} eq "tcp") {
    # The connection will already be closed
  } elsif ($self->{proto} eq "external") {
    # Nothing to close
  } else {
    $self->{fh}->close();
  }
}

sub port_number {
   my $self = shift;
   if(@_) {
       $self->{port_num} = shift @_;
       $self->service_check(1);
   }
   return $self->{port_num};
}

sub ntop {
    my($self, $ip) = @_;

    # Vista doesn't define a inet_ntop.  It has InetNtop instead.
    # Not following ANSI... priceless.  getnameinfo() is defined
    # for Windows 2000 and later, so that may be the choice.

    # Any port will work, even undef, but this will work for now.
    # Socket warns when undef is passed in, but it still works.
    my $port = getservbyname('echo', 'udp');
    my $sockaddr = _pack_sockaddr_in($port, $ip);
    my ($error, $address) = getnameinfo($sockaddr, $NI_NUMERICHOST);
    croak $error if $error;
    return $address;
}

sub wakeonlan {
  my ($mac_addr, $host, $port) = @_;

  # use the discard service if $port not passed in
  if (! defined $host) { $host = '255.255.255.255' }
  if (! defined $port || $port !~ /^\d+$/ ) { $port = 9 }

  require IO::Socket::INET;
  my $sock = IO::Socket::INET->new(Proto=>'udp') || return undef;

  my $ip_addr = inet_aton($host);
  my $sock_addr = sockaddr_in($port, $ip_addr);
  $mac_addr =~ s/://g;
  my $packet = pack('C6H*', 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, $mac_addr x 16);

  setsockopt($sock, SOL_SOCKET, SO_BROADCAST, 1);
  send($sock, $packet, 0, $sock_addr);
  $sock->close;

  return 1;
}

########################################################
# DNS hostname resolution
# return:
#   $h->{name}    = host - as passed in
#   $h->{host}    = host - as passed in without :port
#   $h->{port}    = OPTIONAL - if :port, then value of port
#   $h->{addr}    = resolved numeric address
#   $h->{addr_in} = aton/pton result
#   $h->{family}  = AF_INET/6
############################
sub _resolv {
  my ($self,
      $name,
      ) = @_;

  my %h;
  $h{name} = $name;
  my $family = $self->{family};

  if (defined($self->{family_local})) {
    $family = $self->{family_local}
  }

# START - host:port
  my $cnt = 0;

  # Count ":"
  $cnt++ while ($name =~ m/:/g);

  # 0 = hostname or IPv4 address
  if ($cnt == 0) {
    $h{host} = $name
  # 1 = IPv4 address with port
  } elsif ($cnt == 1) {
    ($h{host}, $h{port}) = split /:/, $name
  # >=2 = IPv6 address
  } elsif ($cnt >= 2) {
    #IPv6 with port - [2001::1]:port
    if ($name =~ /^\[.*\]:\d{1,5}$/) {
      ($h{host}, $h{port}) = split /:([^:]+)$/, $name # split after last :
    # IPv6 without port
    } else {
      $h{host} = $name
    }
  }

  # Clean up host
  $h{host} =~ s/\[//g;
  $h{host} =~ s/\]//g;
  # Clean up port
  if (defined($h{port}) && (($h{port} !~ /^\d{1,5}$/) || ($h{port} < 1) || ($h{port} > 65535))) {
    croak("Invalid port `$h{port}' in `$name'");
    return undef;
  }
# END - host:port

  # address check
  # new way
  if ($Socket_VERSION > 1.94) {
    my %hints = (
      family   => $AF_UNSPEC,
      protocol => IPPROTO_TCP,
      flags => $AI_NUMERICHOST
    );

    # numeric address, return
    my ($err, @getaddr) = Socket::getaddrinfo($h{host}, undef, \%hints);
    if (defined($getaddr[0])) {
      $h{addr} = $h{host};
      $h{family} = $getaddr[0]->{family};
      if ($h{family} == AF_INET) {
        (undef, $h{addr_in}, undef, undef) = Socket::unpack_sockaddr_in $getaddr[0]->{addr};
      } else {
        (undef, $h{addr_in}, undef, undef) = Socket::unpack_sockaddr_in6 $getaddr[0]->{addr};
      }
      return \%h
    }
  # old way
  } else {
    # numeric address, return
    my $ret = gethostbyname($h{host});
    if (defined($ret) && (_inet_ntoa($ret) eq $h{host})) {
      $h{addr} = $h{host};
      $h{addr_in} = $ret;
      $h{family} = AF_INET;
      return \%h
    }
  }

  # resolve
  # new way
  if ($Socket_VERSION >= 1.94) {
    my %hints = (
      family   => $family,
      protocol => IPPROTO_TCP
    );

    my ($err, @getaddr) = Socket::getaddrinfo($h{host}, undef, \%hints);
    if (defined($getaddr[0])) {
      my ($err, $address) = Socket::getnameinfo($getaddr[0]->{addr}, $NI_NUMERICHOST, $NIx_NOSERV);
      if (defined($address)) {
        $h{addr} = $address;
        $h{addr} =~ s/\%(.)*$//; # remove %ifID if IPv6
        $h{family} = $getaddr[0]->{family};
        if ($h{family} == AF_INET) {
          (undef, $h{addr_in}, undef, undef) = Socket::unpack_sockaddr_in $getaddr[0]->{addr};
        } else {
          (undef, $h{addr_in}, undef, undef) = Socket::unpack_sockaddr_in6 $getaddr[0]->{addr};
        }
        return \%h;
      } else {
        carp("getnameinfo($getaddr[0]->{addr}) failed - $err");
        return undef;
      }
    } else {
      warn(sprintf("getaddrinfo($h{host},,%s) failed - $err",
                    $family == AF_INET ? "AF_INET" : "AF_INET6"));
      return undef;
    }
  # old way
  } else {
    if ($family == $AF_INET6) {
      croak("Socket >= 1.94 required for IPv6 - found Socket $Socket::VERSION");
      return undef;
    }

    my @gethost = gethostbyname($h{host});
    if (defined($gethost[4])) {
      $h{addr} = inet_ntoa($gethost[4]);
      $h{addr_in} = $gethost[4];
      $h{family} = AF_INET;
      return \%h
    } else {
      carp("gethostbyname($h{host}) failed - $^E");
      return undef;
    }
  }
  return undef;
}

sub _pack_sockaddr_in($$) {
  my ($port,
      $ip,
      ) = @_;

  my $addr = ref($ip) eq "HASH" ? $ip->{addr_in} : $ip;
  if (length($addr) <= 4 ) {
    return Socket::pack_sockaddr_in($port, $addr);
  } else {
    return Socket::pack_sockaddr_in6($port, $addr);
  }
}

sub _unpack_sockaddr_in($;$) {
  my ($addr,
      $family,
      ) = @_;

  my ($port, $host);
  if ($family == AF_INET || (!defined($family) and length($addr) <= 16 )) {
    ($port, $host) = Socket::unpack_sockaddr_in($addr);
  } else {
    ($port, $host) = Socket::unpack_sockaddr_in6($addr);
  }
  return $port, $host
}

sub _inet_ntoa {
  my ($addr
      ) = @_;

  my $ret;
  if ($Socket_VERSION >= 1.94) {
    my ($err, $address) = Socket::getnameinfo($addr, $NI_NUMERICHOST);
    if (defined($address)) {
      $ret = $address;
    } else {
      carp("getnameinfo($addr) failed - $err");
    }
  } else {
    $ret = inet_ntoa($addr)
  }
    
  return $ret
}

1;
__END__

=head1 NAME

Net::Ping - check a remote host for reachability

=head1 SYNOPSIS

    use Net::Ping;

    $p = Net::Ping->new();
    print "$host is alive.\n" if $p->ping($host);
    $p->close();

    $p = Net::Ping->new("icmp");
    $p->bind($my_addr); # Specify source interface of pings
    foreach $host (@host_array)
    {
        print "$host is ";
        print "NOT " unless $p->ping($host, 2);
        print "reachable.\n";
        sleep(1);
    }
    $p->close();

    $p = Net::Ping->new("icmpv6");
    $ip = "[fd00:dead:beef::4e]";
    print "$ip is alive.\n" if $p->ping($ip);

    $p = Net::Ping->new("tcp", 2);
    # Try connecting to the www port instead of the echo port
    $p->port_number(scalar(getservbyname("http", "tcp")));
    while ($stop_time > time())
    {
        print "$host not reachable ", scalar(localtime()), "\n"
            unless $p->ping($host);
        sleep(300);
    }
    undef($p);

    # Like tcp protocol, but with many hosts
    $p = Net::Ping->new("syn");
    $p->port_number(getservbyname("http", "tcp"));
    foreach $host (@host_array) {
      $p->ping($host);
    }
    while (($host,$rtt,$ip) = $p->ack) {
      print "HOST: $host [$ip] ACKed in $rtt seconds.\n";
    }

    # High precision syntax (requires Time::HiRes)
    $p = Net::Ping->new();
    $p->hires();
    ($ret, $duration, $ip) = $p->ping($host, 5.5);
    printf("$host [ip: $ip] is alive (packet return time: %.2f ms)\n",
            1000 * $duration)
      if $ret;
    $p->close();

    # For backward compatibility
    print "$host is alive.\n" if pingecho($host);

=head1 DESCRIPTION

This module contains methods to test the reachability of remote
hosts on a network.  A ping object is first created with optional
parameters, a variable number of hosts may be pinged multiple
times and then the connection is closed.

You may choose one of six different protocols to use for the
ping. The "tcp" protocol is the default. Note that a live remote host
may still fail to be pingable by one or more of these protocols. For
example, www.microsoft.com is generally alive but not "icmp" pingable.

With the "tcp" protocol the ping() method attempts to establish a
connection to the remote host's echo port.  If the connection is
successfully established, the remote host is considered reachable.  No
data is actually echoed.  This protocol does not require any special
privileges but has higher overhead than the "udp" and "icmp" protocols.

Specifying the "udp" protocol causes the ping() method to send a udp
packet to the remote host's echo port.  If the echoed packet is
received from the remote host and the received packet contains the
same data as the packet that was sent, the remote host is considered
reachable.  This protocol does not require any special privileges.
It should be borne in mind that, for a udp ping, a host
will be reported as unreachable if it is not running the
appropriate echo service.  For Unix-like systems see L<inetd(8)>
for more information.

If the "icmp" protocol is specified, the ping() method sends an icmp
echo message to the remote host, which is what the UNIX ping program
does.  If the echoed message is received from the remote host and
the echoed information is correct, the remote host is considered
reachable.  Specifying the "icmp" protocol requires that the program
be run as root or that the program be setuid to root.

If the "external" protocol is specified, the ping() method attempts to
use the C<Net::Ping::External> module to ping the remote host.
C<Net::Ping::External> interfaces with your system's default C<ping>
utility to perform the ping, and generally produces relatively
accurate results. If C<Net::Ping::External> if not installed on your
system, specifying the "external" protocol will result in an error.

If the "syn" protocol is specified, the L</ping> method will only
send a TCP SYN packet to the remote host then immediately return.
If the syn packet was sent successfully, it will return a true value,
otherwise it will return false.  NOTE: Unlike the other protocols,
the return value does NOT determine if the remote host is alive or
not since the full TCP three-way handshake may not have completed
yet.  The remote host is only considered reachable if it receives
a TCP ACK within the timeout specified.  To begin waiting for the
ACK packets, use the L</ack> method as explained below.  Use the
"syn" protocol instead the "tcp" protocol to determine reachability
of multiple destinations simultaneously by sending parallel TCP
SYN packets.  It will not block while testing each remote host.
This protocol does not require any special privileges.

=head2 Functions

=over 4

=item Net::Ping->new([proto, timeout, bytes, device, tos, ttl, family,
                      host, port, bind, gateway, retrans, pingstring,
                      source_verify econnrefused dontfrag
                      IPV6_USE_MIN_MTU IPV6_RECVPATHMTU])
X<new>

Create a new ping object.  All of the parameters are optional and can
be passed as hash ref.  All options besides the first 7 must be passed
as hash ref.

C<proto> specifies the protocol to use when doing a ping.  The current
choices are "tcp", "udp", "icmp", "icmpv6", "stream", "syn", or
"external".  The default is "tcp".

If a C<timeout> in seconds is provided, it is used
when a timeout is not given to the ping() method (below).  The timeout
must be greater than 0 and the default, if not specified, is 5 seconds.

If the number of data bytes (C<bytes>) is given, that many data bytes
are included in the ping packet sent to the remote host. The number of
data bytes is ignored if the protocol is "tcp".  The minimum (and
default) number of data bytes is 1 if the protocol is "udp" and 0
otherwise.  The maximum number of data bytes that can be specified is
65535, but staying below the MTU (1472 bytes for ICMP) is recommended.
Many small devices cannot deal with fragmented ICMP packets.

If C<device> is given, this device is used to bind the source endpoint
before sending the ping packet.  I believe this only works with
superuser privileges and with udp and icmp protocols at this time.

If <tos> is given, this ToS is configured into the socket.

For icmp, C<ttl> can be specified to set the TTL of the outgoing packet.

Valid C<family> values for IPv4:

   4, v4, ip4, ipv4, AF_INET (constant)

Valid C<family> values for IPv6:

   6, v6, ip6, ipv6, AF_INET6 (constant)

The C<host> argument implicitly specifies the family if the family
argument is not given.

The C<port> argument is only valid for a udp, tcp or stream ping, and will not
do what you think it does. ping returns true when we get a "Connection refused"!
The default is the echo port.

The C<bind> argument specifies the local_addr to bind to.
By specifying a bind argument you don't need the bind method.

The C<gateway> argument is only valid for IPv6, and requires a IPv6
address.

The C<retrans> argument the exponential backoff rate, default 1.2.
It matches the $def_factor global.

The C<dontfrag> argument sets the IP_DONTFRAG bit, but note that
IP_DONTFRAG is not yet defined by Socket, and not available on many
systems. Then it is ignored. On linux it also sets IP_MTU_DISCOVER to
IP_PMTUDISC_DO but need we don't chunk oversized packets. You need to
set $data_size manually.

=item $p->ping($host [, $timeout [, $family]]);
X<ping>

Ping the remote host and wait for a response.  $host can be either the
hostname or the IP number of the remote host.  The optional timeout
must be greater than 0 seconds and defaults to whatever was specified
when the ping object was created.  Returns a success flag.  If the
hostname cannot be found or there is a problem with the IP number, the
success flag returned will be undef.  Otherwise, the success flag will
be 1 if the host is reachable and 0 if it is not.  For most practical
purposes, undef and 0 and can be treated as the same case.  In array
context, the elapsed time as well as the string form of the ip the
host resolved to are also returned.  The elapsed time value will
be a float, as returned by the Time::HiRes::time() function, if hires()
has been previously called, otherwise it is returned as an integer.

=item $p->source_verify( { 0 | 1 } );
X<source_verify>

Allows source endpoint verification to be enabled or disabled.
This is useful for those remote destinations with multiples
interfaces where the response may not originate from the same
endpoint that the original destination endpoint was sent to.
This only affects udp and icmp protocol pings.

This is enabled by default.

=item $p->service_check( { 0 | 1 } );
X<service_check>

Set whether or not the connect behavior should enforce
remote service availability as well as reachability.  Normally,
if the remote server reported ECONNREFUSED, it must have been
reachable because of the status packet that it reported.
With this option enabled, the full three-way tcp handshake
must have been established successfully before it will
claim it is reachable.  NOTE:  It still does nothing more
than connect and disconnect.  It does not speak any protocol
(i.e., HTTP or FTP) to ensure the remote server is sane in
any way.  The remote server CPU could be grinding to a halt
and unresponsive to any clients connecting, but if the kernel
throws the ACK packet, it is considered alive anyway.  To
really determine if the server is responding well would be
application specific and is beyond the scope of Net::Ping.
For udp protocol, enabling this option demands that the
remote server replies with the same udp data that it was sent
as defined by the udp echo service.

This affects the "udp", "tcp", and "syn" protocols.

This is disabled by default.

=item $p->tcp_service_check( { 0 | 1 } );
X<tcp_service_check>

Deprecated method, but does the same as service_check() method.

=item $p->hires( { 0 | 1 } );
X<hires>

With 1 causes this module to use Time::HiRes module, allowing milliseconds
to be returned by subsequent calls to ping().

=item $p->time
X<time>

The current time, hires or not.

=item $p->socket_blocking_mode( $fh, $mode );
X<socket_blocking_mode>

Sets or clears the O_NONBLOCK flag on a file handle.

=item $p->IPV6_USE_MIN_MTU
X<IPV6_USE_MIN_MTU>

With argument sets the option.
Without returns the option value.

=item $p->IPV6_RECVPATHMTU
X<IPV6_RECVPATHMTU>

Notify an according IPv6 MTU.

With argument sets the option.
Without returns the option value.

=item $p->IPV6_HOPLIMIT
X<IPV6_HOPLIMIT>

With argument sets the option.
Without returns the option value.

=item $p->IPV6_REACHCONF I<NYI>
X<IPV6_REACHCONF>

Sets ipv6 reachability
IPV6_REACHCONF was removed in RFC3542. ping6 -R supports it.
IPV6_REACHCONF requires root/admin permissions.

With argument sets the option.
Without returns the option value.

Not yet implemented.

=item $p->bind($local_addr);
X<bind>

Sets the source address from which pings will be sent.  This must be
the address of one of the interfaces on the local host.  $local_addr
may be specified as a hostname or as a text IP address such as
"192.168.1.1".

If the protocol is set to "tcp", this method may be called any
number of times, and each call to the ping() method (below) will use
the most recent $local_addr.  If the protocol is "icmp" or "udp",
then bind() must be called at most once per object, and (if it is
called at all) must be called before the first call to ping() for that
object.

The bind() call can be omitted when specifying the C<bind> option to
new().

=item $p->message_type([$ping_type]);
X<message_type>

When you are using the "icmp" protocol, this call permit to change the
message type to 'echo' or 'timestamp' (only for IPv4, see RFC 792).

Without argument, it returns the currently used icmp protocol message type.
By default, it returns 'echo'.

=item $p->open($host);
X<open>

When you are using the "stream" protocol, this call pre-opens the
tcp socket.  It's only necessary to do this if you want to
provide a different timeout when creating the connection, or
remove the overhead of establishing the connection from the
first ping.  If you don't call C<open()>, the connection is
automatically opened the first time C<ping()> is called.
This call simply does nothing if you are using any protocol other
than stream.

The $host argument can be omitted when specifying the C<host> option to
new().

=item $p->ack( [ $host ] );
X<ack>

When using the "syn" protocol, use this method to determine
the reachability of the remote host.  This method is meant
to be called up to as many times as ping() was called.  Each
call returns the host (as passed to ping()) that came back
with the TCP ACK.  The order in which the hosts are returned
may not necessarily be the same order in which they were
SYN queued using the ping() method.  If the timeout is
reached before the TCP ACK is received, or if the remote
host is not listening on the port attempted, then the TCP
connection will not be established and ack() will return
undef.  In list context, the host, the ack time, the dotted ip 
string, and the port number will be returned instead of just the host.
If the optional C<$host> argument is specified, the return
value will be pertaining to that host only.
This call simply does nothing if you are using any protocol
other than "syn".

When L</new> had a host option, this host will be used.
Without C<$host> argument, all hosts are scanned.

=item $p->nack( $failed_ack_host );
X<nack>

The reason that C<host $failed_ack_host> did not receive a
valid ACK.  Useful to find out why when C<ack($fail_ack_host)>
returns a false value.

=item $p->ack_unfork($host)
X<ack_unfork>

The variant called by L</ack> with the "syn" protocol and C<$syn_forking>
enabled.

=item $p->ping_icmp([$host, $timeout, $family])
X<ping_icmp>

The L</ping> method used with the icmp protocol.

=item $p->ping_icmpv6([$host, $timeout, $family])
X<ping_icmpv6>

The L</ping> method used with the icmpv6 protocol.

=item $p->ping_stream([$host, $timeout, $family])
X<ping_stream>

The L</ping> method used with the stream protocol.

Perform a stream ping.  If the tcp connection isn't
already open, it opens it.  It then sends some data and waits for
a reply.  It leaves the stream open on exit.

=item $p->ping_syn([$host, $ip, $start_time, $stop_time])
X<ping_syn>

The L</ping> method used with the syn protocol.
Sends a TCP SYN packet to host specified.

=item $p->ping_syn_fork([$host, $timeout, $family])
X<ping_syn_fork>

The L</ping> method used with the forking syn protocol.

=item $p->ping_tcp([$host, $timeout, $family])
X<ping_tcp>

The L</ping> method used with the tcp protocol.

=item $p->ping_udp([$host, $timeout, $family])
X<ping_udp>

The L</ping> method used with the udp protocol.

Perform a udp echo ping.  Construct a message of
at least the one-byte sequence number and any additional data bytes.
Send the message out and wait for a message to come back.  If we
get a message, make sure all of its parts match.  If they do, we are
done.  Otherwise go back and wait for the message until we run out
of time.  Return the result of our efforts.

=item $p->ping_external([$host, $timeout, $family])
X<ping_external>

The L</ping> method used with the external protocol.
Uses L<Net::Ping::External> to do an external ping.

=item $p->tcp_connect([$ip, $timeout])
X<tcp_connect>

Initiates a TCP connection, for a tcp ping.

=item $p->tcp_echo([$ip, $timeout, $pingstring])
X<tcp_echo>

Performs a TCP echo.
It writes the given string to the socket and then reads it
back.  It returns 1 on success, 0 on failure.

=item $p->close();
X<close>

Close the network connection for this ping object.  The network
connection is also closed by "undef $p".  The network connection is
automatically closed if the ping object goes out of scope (e.g. $p is
local to a subroutine and you leave the subroutine).

=item $p->port_number([$port_number])
X<port_number>

When called with a port number, the port number used to ping is set to
C<$port_number> rather than using the echo port.  It also has the effect
of calling C<$p-E<gt>service_check(1)> causing a ping to return a successful
response only if that specific port is accessible.  This function returns
the value of the port that L</ping> will connect to.

=item $p->mselect
X<mselect>

A C<select()> wrapper that compensates for platform
peculiarities.

=item $p->ntop
X<ntop>

Platform abstraction over C<inet_ntop()>

=item $p->checksum($msg)
X<checksum>

Do a checksum on the message.  Basically sum all of
the short words and fold the high order bits into the low order bits.

=item $p->icmp_result
X<icmp_result>

Returns a list of addr, type, subcode.

=item pingecho($host [, $timeout]);
X<pingecho>

To provide backward compatibility with the previous version of
L<Net::Ping>, a C<pingecho()> subroutine is available with the same
functionality as before.  C<pingecho()> uses the tcp protocol.  The
return values and parameters are the same as described for the L</ping>
method.  This subroutine is obsolete and may be removed in a future
version of L<Net::Ping>.

=item wakeonlan($mac, [$host, [$port]])
X<wakeonlan>

Emit the popular wake-on-lan magic udp packet to wake up a local
device.  See also L<Net::Wake>, but this has the mac address as 1st arg.
C<$host> should be the local gateway. Without it will broadcast.

Default host: '255.255.255.255'
Default port: 9

  perl -MNet::Ping=wakeonlan -e'wakeonlan "e0:69:95:35:68:d2"'

=back

=head1 NOTES

There will be less network overhead (and some efficiency in your
program) if you specify either the udp or the icmp protocol.  The tcp
protocol will generate 2.5 times or more traffic for each ping than
either udp or icmp.  If many hosts are pinged frequently, you may wish
to implement a small wait (e.g. 25ms or more) between each ping to
avoid flooding your network with packets.

The icmp and icmpv6 protocols requires that the program be run as root
or that it be setuid to root.  The other protocols do not require
special privileges, but not all network devices implement tcp or udp
echo.

Local hosts should normally respond to pings within milliseconds.
However, on a very congested network it may take up to 3 seconds or
longer to receive an echo packet from the remote host.  If the timeout
is set too low under these conditions, it will appear that the remote
host is not reachable (which is almost the truth).

Reachability doesn't necessarily mean that the remote host is actually
functioning beyond its ability to echo packets.  tcp is slightly better
at indicating the health of a system than icmp because it uses more
of the networking stack to respond.

Because of a lack of anything better, this module uses its own
routines to pack and unpack ICMP packets.  It would be better for a
separate module to be written which understands all of the different
kinds of ICMP packets.

=head1 INSTALL

The latest source tree is available via git:

  git clone https://github.com/rurban/Net-Ping.git
  cd Net-Ping

The tarball can be created as follows:

  perl Makefile.PL ; make ; make dist

The latest Net::Ping releases are included in cperl and perl5.

=head1 BUGS

For a list of known issues, visit:

L<https://rt.cpan.org/NoAuth/Bugs.html?Dist=Net-Ping>
and
L<https://github.com/rurban/Net-Ping/issues>

To report a new bug, visit:

L<https://github.com/rurban/Net-Ping/issues>

=head1 AUTHORS

  Current maintainers:
    perl11 (for cperl, with IPv6 support and more)
    p5p    (for perl5)

  Previous maintainers:
    bbb@cpan.org (Rob Brown)
    Steve Peters

  External protocol:
    colinm@cpan.org (Colin McMillen)

  Stream protocol:
    bronson@trestle.com (Scott Bronson)

  Wake-on-lan:
    1999-2003 Clinton Wong

  Original pingecho():
    karrer@bernina.ethz.ch (Andreas Karrer)
    pmarquess@bfsec.bt.co.uk (Paul Marquess)

  Original Net::Ping author:
    mose@ns.ccsn.edu (Russell Mosemann)

=head1 COPYRIGHT

Copyright (c) 2017-2020, Reini Urban.  All rights reserved.

Copyright (c) 2016, cPanel Inc.  All rights reserved.

Copyright (c) 2012, Steve Peters.  All rights reserved.

Copyright (c) 2002-2003, Rob Brown.  All rights reserved.

Copyright (c) 2001, Colin McMillen.  All rights reserved.

This program is free software; you may redistribute it and/or
modify it under the same terms as Perl itself.

=cut
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            # Convert POD data to formatted *roff input.
#
# This module translates POD documentation into *roff markup using the man
# macro set, and is intended for converting POD documents written as Unix
# manual pages to manual pages that can be read by the man(1) command.  It is
# a replacement for the pod2man command distributed with versions of Perl
# prior to 5.6.
#
# SPDX-License-Identifier: GPL-1.0-or-later OR Artistic-1.0-Perl

##############################################################################
# Modules and declarations
##############################################################################

package Pod::Man;

use 5.008;
use strict;
use warnings;

use subs qw(makespace);
use vars qw(@ISA %ESCAPES $PREAMBLE $VERSION);

use Carp qw(carp croak);
use Pod::Simple ();

# Conditionally import Encode and set $HAS_ENCODE if it is available.  This is
# required to support building as part of Perl core, since podlators is built
# before Encode is.
our $HAS_ENCODE;
BEGIN {
    $HAS_ENCODE = eval { require Encode };
}

@ISA = qw(Pod::Simple);

$VERSION = '4.14';

# Set the debugging level.  If someone has inserted a debug function into this
# class already, use that.  Otherwise, use any Pod::Simple debug function
# that's defined, and failing that, define a debug level of 10.
BEGIN {
    my $parent = defined (&Pod::Simple::DEBUG) ? \&Pod::Simple::DEBUG : undef;
    unless (defined &DEBUG) {
        *DEBUG = $parent || sub () { 10 };
    }
}

# Import the ASCII constant from Pod::Simple.  This is true iff we're in an
# ASCII-based universe (including such things as ISO 8859-1 and UTF-8), and is
# generally only false for EBCDIC.
BEGIN { *ASCII = \&Pod::Simple::ASCII }

# Pretty-print a data structure.  Only used for debugging.
BEGIN { *pretty = \&Pod::Simple::pretty }

# Formatting instructions for various types of blocks.  cleanup makes hyphens
# hard, adds spaces between consecutive underscores, and escapes backslashes.
# convert translates characters into escapes.  guesswork means to apply the
# transformations done by the guesswork sub.  literal says to protect literal
# quotes from being turned into UTF-8 quotes.  By default, all transformations
# are on except literal, but some elements override.
#
# DEFAULT specifies the default settings.  All other elements should list only
# those settings that they are overriding.  Data indicates =for roff blocks,
# which should be passed along completely verbatim.
#
# Formatting inherits negatively, in the sense that if the parent has turned
# off guesswork, all child elements should leave it off.
my %FORMATTING = (
    DEFAULT  => { cleanup => 1, convert => 1, guesswork => 1, literal => 0 },
    Data     => { cleanup => 0, convert => 0, guesswork => 0, literal => 0 },
    Verbatim => {                             guesswork => 0, literal => 1 },
    C        => {                             guesswork => 0, literal => 1 },
    X        => { cleanup => 0,               guesswork => 0               },
);

##############################################################################
# Object initialization
##############################################################################

# Initialize the object and set various Pod::Simple options that we need.
# Here, we also process any additional options passed to the constructor or
# set up defaults if none were given.  Note that all internal object keys are
# in all-caps, reserving all lower-case object keys for Pod::Simple and user
# arguments.
sub new {
    my $class = shift;
    my $self = $class->SUPER::new;

    # Tell Pod::Simple not to handle S<> by automatically inserting &nbsp;.
    $self->nbsp_for_S (1);

    # Tell Pod::Simple to keep whitespace whenever possible.
    if (my $preserve_whitespace = $self->can ('preserve_whitespace')) {
        $self->$preserve_whitespace (1);
    } else {
        $self->fullstop_space_harden (1);
    }

    # The =for and =begin targets that we accept.
    $self->accept_targets (qw/man MAN roff ROFF/);

    # Ensure that contiguous blocks of code are merged together.  Otherwise,
    # some of the guesswork heuristics don't work right.
    $self->merge_text (1);

    # Pod::Simple doesn't do anything useful with our arguments, but we want
    # to put them in our object as hash keys and values.  This could cause
    # problems if we ever clash with Pod::Simple's own internal class
    # variables.
    %$self = (%$self, @_);

    # Send errors to stderr if requested.
    if ($$self{stderr} and not $$self{errors}) {
        $$self{errors} = 'stderr';
    }
    delete $$self{stderr};

    # Validate the errors parameter and act on it.
    if (not defined $$self{errors}) {
        $$self{errors} = 'pod';
    }
    if ($$self{errors} eq 'stderr' || $$self{errors} eq 'die') {
        $self->no_errata_section (1);
        $self->complain_stderr (1);
        if ($$self{errors} eq 'die') {
            $$self{complain_die} = 1;
        }
    } elsif ($$self{errors} eq 'pod') {
        $self->no_errata_section (0);
        $self->complain_stderr (0);
    } elsif ($$self{errors} eq 'none') {
        $self->no_errata_section (1);
        $self->no_whining (1);
    } else {
        croak (qq(Invalid errors setting: "$$self{errors}"));
    }
    delete $$self{errors};

    # Degrade back to non-utf8 if Encode is not available.
    #
    # Suppress the warning message when PERL_CORE is set, indicating this is
    # running as part of the core Perl build.  Perl builds podlators (and all
    # pure Perl modules) before Encode and other XS modules, so Encode won't
    # yet be available.  Rely on the Perl core build to generate man pages
    # later, after all the modules are available, so that UTF-8 handling will
    # be correct.
    if ($$self{utf8} and !$HAS_ENCODE) {
        if (!$ENV{PERL_CORE}) {
            carp ('utf8 mode requested but Encode module not available,'
                    . ' falling back to non-utf8');
        }
        delete $$self{utf8};
    }

    # Initialize various other internal constants based on our arguments.
    $self->init_fonts;
    $self->init_quotes;
    $self->init_page;

    # For right now, default to turning on all of the magic.
    $$self{MAGIC_CPP}       = 1;
    $$self{MAGIC_EMDASH}    = 1;
    $$self{MAGIC_FUNC}      = 1;
    $$self{MAGIC_MANREF}    = 1;
    $$self{MAGIC_SMALLCAPS} = 1;
    $$self{MAGIC_VARS}      = 1;

    return $self;
}

# Translate a font string into an escape.
sub toescape { (length ($_[0]) > 1 ? '\f(' : '\f') . $_[0] }

# Determine which fonts the user wishes to use and store them in the object.
# Regular, italic, bold, and bold-italic are constants, but the fixed width
# fonts may be set by the user.  Sets the internal hash key FONTS which is
# used to map our internal font escapes to actual *roff sequences later.
sub init_fonts {
    my ($self) = @_;

    # Figure out the fixed-width font.  If user-supplied, make sure that they
    # are the right length.
    for (qw/fixed fixedbold fixeditalic fixedbolditalic/) {
        my $font = $$self{$_};
        if (defined ($font) && (length ($font) < 1 || length ($font) > 2)) {
            croak qq(roff font should be 1 or 2 chars, not "$font");
        }
    }

    # Set the default fonts.  We can't be sure portably across different
    # implementations what fixed bold-italic may be called (if it's even
    # available), so default to just bold.
    $$self{fixed}           ||= 'CW';
    $$self{fixedbold}       ||= 'CB';
    $$self{fixeditalic}     ||= 'CI';
    $$self{fixedbolditalic} ||= 'CB';

    # Set up a table of font escapes.  First number is fixed-width, second is
    # bold, third is italic.
    $$self{FONTS} = { '000' => '\fR', '001' => '\fI',
                      '010' => '\fB', '011' => '\f(BI',
                      '100' => toescape ($$self{fixed}),
                      '101' => toescape ($$self{fixeditalic}),
                      '110' => toescape ($$self{fixedbold}),
                      '111' => toescape ($$self{fixedbolditalic}) };
}

# Initialize the quotes that we'll be using for C<> text.  This requires some
# special handling, both to parse the user parameters if given and to make
# sure that the quotes will be safe against *roff.  Sets the internal hash
# keys LQUOTE and RQUOTE.
sub init_quotes {
    my ($self) = (@_);

    # Handle the quotes option first, which sets both quotes at once.
    $$self{quotes} ||= '"';
    if ($$self{quotes} eq 'none') {
        $$self{LQUOTE} = $$self{RQUOTE} = '';
    } elsif (length ($$self{quotes}) == 1) {
        $$self{LQUOTE} = $$self{RQUOTE} = $$self{quotes};
    } elsif (length ($$self{quotes}) % 2 == 0) {
        my $length = length ($$self{quotes}) / 2;
        $$self{LQUOTE} = substr ($$self{quotes}, 0, $length);
        $$self{RQUOTE} = substr ($$self{quotes}, $length);
    } else {
        croak(qq(Invalid quote specification "$$self{quotes}"))
    }

    # Now handle the lquote and rquote options.
    if (defined $$self{lquote}) {
        $$self{LQUOTE} = $$self{lquote} eq 'none' ? q{} : $$self{lquote};
    }
    if (defined $$self{rquote}) {
        $$self{RQUOTE} = $$self{rquote} eq 'none' ? q{} : $$self{rquote};
    }

    # Double the first quote; note that this should not be s///g as two double
    # quotes is represented in *roff as three double quotes, not four.  Weird,
    # I know.
    $$self{LQUOTE} =~ s/\"/\"\"/;
    $$self{RQUOTE} =~ s/\"/\"\"/;
}

# Initialize the page title information and indentation from our arguments.
sub init_page {
    my ($self) = @_;

    # Get the version from the running Perl.
    my @version = ($] =~ /^(\d+)\.(\d{3})(\d+)$/);
    for (@version) { $_ += 0 }
    my $version = join ('.', @version);

    # Set the defaults for page titles and indentation if the user didn't
    # override anything.
    $$self{center} = 'User Contributed Perl Documentation'
        unless defined $$self{center};
    $$self{release} = 'perl v' . $version
        unless defined $$self{release};
    $$self{indent} = 4
        unless defined $$self{indent};

    # Double quotes in things that will be quoted.
    for (qw/center release/) {
        $$self{$_} =~ s/\"/\"\"/g if $$self{$_};
    }
}

##############################################################################
# Core parsing
##############################################################################

# This is the glue that connects the code below with Pod::Simple itself.  The
# goal is to convert the event stream coming from the POD parser into method
# calls to handlers once the complete content of a tag has been seen.  Each
# paragraph or POD command will have textual content associated with it, and
# as soon as all of a paragraph or POD command has been seen, that content
# will be passed in to the corresponding method for handling that type of
# object.  The exceptions are handlers for lists, which have opening tag
# handlers and closing tag handlers that will be called right away.
#
# The internal hash key PENDING is used to store the contents of a tag until
# all of it has been seen.  It holds a stack of open tags, each one
# represented by a tuple of the attributes hash for the tag, formatting
# options for the tag (which are inherited), and the contents of the tag.

# Add a block of text to the contents of the current node, formatting it
# according to the current formatting instructions as we do.
sub _handle_text {
    my ($self, $text) = @_;
    DEBUG > 3 and print "== $text\n";
    my $tag = $$self{PENDING}[-1];
    $$tag[2] .= $self->format_text ($$tag[1], $text);
}

# Given an element name, get the corresponding method name.
sub method_for_element {
    my ($self, $element) = @_;
    $element =~ tr/A-Z-/a-z_/;
    $element =~ tr/_a-z0-9//cd;
    return $element;
}

# Handle the start of a new element.  If cmd_element is defined, assume that
# we need to collect the entire tree for this element before passing it to the
# element method, and create a new tree into which we'll collect blocks of
# text and nested elements.  Otherwise, if start_element is defined, call it.
sub _handle_element_start {
    my ($self, $element, $attrs) = @_;
    DEBUG > 3 and print "++ $element (<", join ('> <', %$attrs), ">)\n";
    my $method = $self->method_for_element ($element);

    # If we have a command handler, we need to accumulate the contents of the
    # tag before calling it.  Turn off IN_NAME for any command other than
    # <Para> and the formatting codes so that IN_NAME isn't still set for the
    # first heading after the NAME heading.
    if ($self->can ("cmd_$method")) {
        DEBUG > 2 and print "<$element> starts saving a tag\n";
        $$self{IN_NAME} = 0 if ($element ne 'Para' && length ($element) > 1);

        # How we're going to format embedded text blocks depends on the tag
        # and also depends on our parent tags.  Thankfully, inside tags that
        # turn off guesswork and reformatting, nothing else can turn it back
        # on, so this can be strictly inherited.
        my $formatting = {
            %{ $$self{PENDING}[-1][1] || $FORMATTING{DEFAULT} },
            %{ $FORMATTING{$element} || {} },
        };
        push (@{ $$self{PENDING} }, [ $attrs, $formatting, '' ]);
        DEBUG > 4 and print "Pending: [", pretty ($$self{PENDING}), "]\n";
    } elsif (my $start_method = $self->can ("start_$method")) {
        $self->$start_method ($attrs, '');
    } else {
        DEBUG > 2 and print "No $method start method, skipping\n";
    }
}

# Handle the end of an element.  If we had a cmd_ method for this element,
# this is where we pass along the tree that we built.  Otherwise, if we have
# an end_ method for the element, call that.
sub _handle_element_end {
    my ($self, $element) = @_;
    DEBUG > 3 and print "-- $element\n";
    my $method = $self->method_for_element ($element);

    # If we have a command handler, pull off the pending text and pass it to
    # the handler along with the saved attribute hash.
    if (my $cmd_method = $self->can ("cmd_$method")) {
        DEBUG > 2 and print "</$element> stops saving a tag\n";
        my $tag = pop @{ $$self{PENDING} };
        DEBUG > 4 and print "Popped: [", pretty ($tag), "]\n";
        DEBUG > 4 and print "Pending: [", pretty ($$self{PENDING}), "]\n";
        my $text = $self->$cmd_method ($$tag[0], $$tag[2]);
        if (defined $text) {
            if (@{ $$self{PENDING} } > 1) {
                $$self{PENDING}[-1][2] .= $text;
            } else {
                $self->output ($text);
            }
        }
    } elsif (my $end_method = $self->can ("end_$method")) {
        $self->$end_method ();
    } else {
        DEBUG > 2 and print "No $method end method, skipping\n";
    }
}

##############################################################################
# General formatting
##############################################################################

# Format a text block.  Takes a hash of formatting options and the text to
# format.  Currently, the only formatting options are guesswork, cleanup, and
# convert, all of which are boolean.
sub format_text {
    my ($self, $options, $text) = @_;
    my $guesswork = $$options{guesswork} && !$$self{IN_NAME};
    my $cleanup = $$options{cleanup};
    my $convert = $$options{convert};
    my $literal = $$options{literal};

    # Cleanup just tidies up a few things, telling *roff that the hyphens are
    # hard, putting a bit of space between consecutive underscores, and
    # escaping backslashes.  Be careful not to mangle our character
    # translations by doing this before processing character translation.
    if ($cleanup) {
        $text =~ s/\\/\\e/g;
        $text =~ s/-/\\-/g;
        $text =~ s/_(?=_)/_\\|/g;
    }

    # Normally we do character translation, but we won't even do that in
    # <Data> blocks or if UTF-8 output is desired.
    if ($convert && !$$self{utf8} && ASCII) {
        $text =~ s/([^\x00-\x7F])/$ESCAPES{ord ($1)} || "X"/eg;
    }

    # Ensure that *roff doesn't convert literal quotes to UTF-8 single quotes,
    # but don't mess up our accept escapes.
    if ($literal) {
        $text =~ s/(?<!\\\*)\'/\\*\(Aq/g;
        $text =~ s/(?<!\\\*)\`/\\\`/g;
    }

    # If guesswork is asked for, do that.  This involves more substantial
    # formatting based on various heuristics that may only be appropriate for
    # particular documents.
    if ($guesswork) {
        $text = $self->guesswork ($text);
    }

    return $text;
}

# Handles C<> text, deciding whether to put \*C` around it or not.  This is a
# whole bunch of messy heuristics to try to avoid overquoting, originally from
# Barrie Slaymaker.  This largely duplicates similar code in Pod::Text.
sub quote_literal {
    my $self = shift;
    local $_ = shift;

    # A regex that matches the portion of a variable reference that's the
    # array or hash index, separated out just because we want to use it in
    # several places in the following regex.
    my $index = '(?: \[.*\] | \{.*\} )?';

    # If in NAME section, just return an ASCII quoted string to avoid
    # confusing tools like whatis.
    return qq{"$_"} if $$self{IN_NAME};

    # Check for things that we don't want to quote, and if we find any of
    # them, return the string with just a font change and no quoting.
    m{
      ^\s*
      (?:
         ( [\'\`\"] ) .* \1                             # already quoted
       | \\\*\(Aq .* \\\*\(Aq                           # quoted and escaped
       | \\?\` .* ( \' | \\\*\(Aq )                     # `quoted'
       | \$+ [\#^]? \S $index                           # special ($^Foo, $")
       | [\$\@%&*]+ \#? [:\'\w]+ $index                 # plain var or func
       | [\$\@%&*]* [:\'\w]+ (?: -> )? \(\s*[^\s,]\s*\) # 0/1-arg func call
       | [-+]? ( \d[\d.]* | \.\d+ ) (?: [eE][-+]?\d+ )? # a number
       | 0x [a-fA-F\d]+                                 # a hex constant
      )
      \s*\z
     }xso and return '\f(FS' . $_ . '\f(FE';

    # If we didn't return, go ahead and quote the text.
    return '\f(FS\*(C`' . $_ . "\\*(C'\\f(FE";
}

# Takes a text block to perform guesswork on.  Returns the text block with
# formatting codes added.  This is the code that marks up various Perl
# constructs and things commonly used in man pages without requiring the user
# to add any explicit markup, and is applied to all non-literal text.  We're
# guaranteed that the text we're applying guesswork to does not contain any
# *roff formatting codes.  Note that the inserted font sequences must be
# treated later with mapfonts or textmapfonts.
#
# This method is very fragile, both in the regular expressions it uses and in
# the ordering of those modifications.  Care and testing is required when
# modifying it.
sub guesswork {
    my $self = shift;
    local $_ = shift;
    DEBUG > 5 and print "   Guesswork called on [$_]\n";

    # By the time we reach this point, all hyphens will be escaped by adding a
    # backslash.  We want to undo that escaping if they're part of regular
    # words and there's only a single dash, since that's a real hyphen that
    # *roff gets to consider a possible break point.  Make sure that a dash
    # after the first character of a word stays non-breaking, however.
    #
    # Note that this is not user-controllable; we pretty much have to do this
    # transformation or *roff will mangle the output in unacceptable ways.
    s{
        ( (?:\G|^|\s) [\(\"]* [a-zA-Z] ) ( \\- )?
        ( (?: [a-zA-Z\']+ \\-)+ )
        ( [a-zA-Z\']+ ) (?= [\)\".?!,;:]* (?:\s|\Z|\\\ ) )
        \b
    } {
        my ($prefix, $hyphen, $main, $suffix) = ($1, $2, $3, $4);
        $hyphen ||= '';
        $main =~ s/\\-/-/g;
        $prefix . $hyphen . $main . $suffix;
    }egx;

    # Translate "--" into a real em-dash if it's used like one.  This means
    # that it's either surrounded by whitespace, it follows a regular word, or
    # it occurs between two regular words.
    if ($$self{MAGIC_EMDASH}) {
        s{          (\s) \\-\\- (\s)                } { $1 . '\*(--' . $2 }egx;
        s{ (\b[a-zA-Z]+) \\-\\- (\s|\Z|[a-zA-Z]+\b) } { $1 . '\*(--' . $2 }egx;
    }

    # Make words in all-caps a little bit smaller; they look better that way.
    # However, we don't want to change Perl code (like @ARGV), nor do we want
    # to fix the MIME in MIME-Version since it looks weird with the
    # full-height V.
    #
    # We change only a string of all caps (2) either at the beginning of the
    # line or following regular punctuation (like quotes) or whitespace (1),
    # and followed by either similar punctuation, an em-dash, or the end of
    # the line (3).
    #
    # Allow the text we're changing to small caps to include double quotes,
    # commas, newlines, and periods as long as it doesn't otherwise interrupt
    # the string of small caps and still fits the criteria.  This lets us turn
    # entire warranty disclaimers in man page output into small caps.
    if ($$self{MAGIC_SMALLCAPS}) {
        s{
            ( ^ | [\s\(\"\'\`\[\{<>] | \\[ ]  )                           # (1)
            ( [A-Z] [A-Z] (?: \s? [/A-Z+:\d_\$&] | \\- | \s? [.,\"] )* )  # (2)
            (?= [\s>\}\]\(\)\'\".?!,;] | \\*\(-- | \\[ ] | $ )            # (3)
        } {
            $1 . '\s-1' . $2 . '\s0'
        }egx;
    }

    # Note that from this point forward, we have to adjust for \s-1 and \s-0
    # strings inserted around things that we've made small-caps if later
    # transforms should work on those strings.

    # Embolden functions in the form func(), including functions that are in
    # all capitals, but don't embolden if there's anything between the parens.
    # The function must start with an alphabetic character or underscore and
    # then consist of word characters or colons.
    if ($$self{MAGIC_FUNC}) {
        s{
            ( \b | \\s-1 )
            ( [A-Za-z_] ([:\w] | \\s-?[01])+ \(\) )
        } {
            $1 . '\f(BS' . $2 . '\f(BE'
        }egx;
    }

    # Change references to manual pages to put the page name in bold but
    # the number in the regular font, with a thin space between the name and
    # the number.  Only recognize func(n) where func starts with an alphabetic
    # character or underscore and contains only word characters, periods (for
    # configuration file man pages), or colons, and n is a single digit,
    # optionally followed by some number of lowercase letters.  Note that this
    # does not recognize man page references like perl(l) or socket(3SOCKET).
    if ($$self{MAGIC_MANREF}) {
        s{
            ( \b | \\s-1 )
            (?<! \\ )                                   # rule out \s0(1)
            ( [A-Za-z_] (?:[.:\w] | \\- | \\s-?[01])+ )
            ( \( \d [a-z]* \) )
        } {
            $1 . '\f(BS' . $2 . '\f(BE\|' . $3
        }egx;
    }

    # Convert simple Perl variable references to a fixed-width font.  Be
    # careful not to convert functions, though; there are too many subtleties
    # with them to want to perform this transformation.
    if ($$self{MAGIC_VARS}) {
        s{
           ( ^ | \s+ )
           ( [\$\@%] [\w:]+ )
           (?! \( )
        } {
            $1 . '\f(FS' . $2 . '\f(FE'
        }egx;
    }

    # Fix up double quotes.  Unfortunately, we miss this transformation if the
    # quoted text contains any code with formatting codes and there's not much
    # we can effectively do about that, which makes it somewhat unclear if
    # this is really a good idea.
    s{ \" ([^\"]+) \" } { '\*(L"' . $1 . '\*(R"' }egx;

    # Make C++ into \*(C+, which is a squinched version.
    if ($$self{MAGIC_CPP}) {
        s{ \b C\+\+ } {\\*\(C+}gx;
    }

    # Done.
    DEBUG > 5 and print "   Guesswork returning [$_]\n";
    return $_;
}

##############################################################################
# Output
##############################################################################

# When building up the *roff code, we don't use real *roff fonts.  Instead, we
# embed font codes of the form \f(<font>[SE] where <font> is one of B, I, or
# F, S stands for start, and E stands for end.  This method turns these into
# the right start and end codes.
#
# We add this level of complexity because the old pod2man didn't get code like
# B<someI<thing> else> right; after I<> it switched back to normal text rather
# than bold.  We take care of this by using variables that state whether bold,
# italic, or fixed are turned on as a combined pointer to our current font
# sequence, and set each to the number of current nestings of start tags for
# that font.
#
# \fP changes to the previous font, but only one previous font is kept.  We
# don't know what the outside level font is; normally it's R, but if we're
# inside a heading it could be something else.  So arrange things so that the
# outside font is always the "previous" font and end with \fP instead of \fR.
# Idea from Zack Weinberg.
sub mapfonts {
    my ($self, $text) = @_;
    my ($fixed, $bold, $italic) = (0, 0, 0);
    my %magic = (F => \$fixed, B => \$bold, I => \$italic);
    my $last = '\fR';
    $text =~ s<
        \\f\((.)(.)
    > <
        my $sequence = '';
        my $f;
        if ($last ne '\fR') { $sequence = '\fP' }
        ${ $magic{$1} } += ($2 eq 'S') ? 1 : -1;
        $f = $$self{FONTS}{ ($fixed && 1) . ($bold && 1) . ($italic && 1) };
        if ($f eq $last) {
            '';
        } else {
            if ($f ne '\fR') { $sequence .= $f }
            $last = $f;
            $sequence;
        }
    >gxe;
    return $text;
}

# Unfortunately, there is a bug in Solaris 2.6 nroff (not present in GNU
# groff) where the sequence \fB\fP\f(CW\fP leaves the font set to B rather
# than R, presumably because \f(CW doesn't actually do a font change.  To work
# around this, use a separate textmapfonts for text blocks where the default
# font is always R and only use the smart mapfonts for headings.
sub textmapfonts {
    my ($self, $text) = @_;
    my ($fixed, $bold, $italic) = (0, 0, 0);
    my %magic = (F => \$fixed, B => \$bold, I => \$italic);
    $text =~ s<
        \\f\((.)(.)
    > <
        ${ $magic{$1} } += ($2 eq 'S') ? 1 : -1;
        $$self{FONTS}{ ($fixed && 1) . ($bold && 1) . ($italic && 1) };
    >gxe;
    return $text;
}

# Given a command and a single argument that may or may not contain double
# quotes, handle double-quote formatting for it.  If there are no double
# quotes, just return the command followed by the argument in double quotes.
# If there are double quotes, use an if statement to test for nroff, and for
# nroff output the command followed by the argument in double quotes with
# embedded double quotes doubled.  For other formatters, remap paired double
# quotes to LQUOTE and RQUOTE.
sub switchquotes {
    my ($self, $command, $text, $extra) = @_;
    $text =~ s/\\\*\([LR]\"/\"/g;

    # We also have to deal with \*C` and \*C', which are used to add the
    # quotes around C<> text, since they may expand to " and if they do this
    # confuses the .SH macros and the like no end.  Expand them ourselves.
    # Also separate troff from nroff if there are any fixed-width fonts in use
    # to work around problems with Solaris nroff.
    my $c_is_quote = ($$self{LQUOTE} =~ /\"/) || ($$self{RQUOTE} =~ /\"/);
    my $fixedpat = join '|', @{ $$self{FONTS} }{'100', '101', '110', '111'};
    $fixedpat =~ s/\\/\\\\/g;
    $fixedpat =~ s/\(/\\\(/g;
    if ($text =~ m/\"/ || $text =~ m/$fixedpat/) {
        $text =~ s/\"/\"\"/g;
        my $nroff = $text;
        my $troff = $text;
        $troff =~ s/\"\"([^\"]*)\"\"/\`\`$1\'\'/g;
        if ($c_is_quote and $text =~ m/\\\*\(C[\'\`]/) {
            $nroff =~ s/\\\*\(C\`/$$self{LQUOTE}/g;
            $nroff =~ s/\\\*\(C\'/$$self{RQUOTE}/g;
            $troff =~ s/\\\*\(C[\'\`]//g;
        }
        $nroff = qq("$nroff") . ($extra ? " $extra" : '');
        $troff = qq("$troff") . ($extra ? " $extra" : '');

        # Work around the Solaris nroff bug where \f(CW\fP leaves the font set
        # to Roman rather than the actual previous font when used in headings.
        # troff output may still be broken, but at least we can fix nroff by
        # just switching the font changes to the non-fixed versions.
        my $font_end = "(?:\\f[PR]|\Q$$self{FONTS}{100}\E)";
        $nroff =~ s/\Q$$self{FONTS}{100}\E(.*?)\\f([PR])/$1/g;
        $nroff =~ s/\Q$$self{FONTS}{101}\E(.*?)$font_end/\\fI$1\\fP/g;
        $nroff =~ s/\Q$$self{FONTS}{110}\E(.*?)$font_end/\\fB$1\\fP/g;
        $nroff =~ s/\Q$$self{FONTS}{111}\E(.*?)$font_end/\\f\(BI$1\\fP/g;

        # Now finally output the command.  Bother with .ie only if the nroff
        # and troff output aren't the same.
        if ($nroff ne $troff) {
            return ".ie n $command $nroff\n.el $command $troff\n";
        } else {
            return "$command $nroff\n";
        }
    } else {
        $text = qq("$text") . ($extra ? " $extra" : '');
        return "$command $text\n";
    }
}

# Protect leading quotes and periods against interpretation as commands.  Also
# protect anything starting with a backslash, since it could expand or hide
# something that *roff would interpret as a command.  This is overkill, but
# it's much simpler than trying to parse *roff here.
sub protect {
    my ($self, $text) = @_;
    $text =~ s/^([.\'\\])/\\&$1/mg;
    return $text;
}

# Make vertical whitespace if NEEDSPACE is set, appropriate to the indentation
# level the situation.  This function is needed since in *roff one has to
# create vertical whitespace after paragraphs and between some things, but
# other macros create their own whitespace.  Also close out a sequence of
# repeated =items, since calling makespace means we're about to begin the item
# body.
sub makespace {
    my ($self) = @_;
    $self->output (".PD\n") if $$self{ITEMS} > 1;
    $$self{ITEMS} = 0;
    $self->output ($$self{INDENT} > 0 ? ".Sp\n" : ".PP\n")
        if $$self{NEEDSPACE};
}

# Output any pending index entries, and optionally an index entry given as an
# argument.  Support multiple index entries in X<> separated by slashes, and
# strip special escapes from index entries.
sub outindex {
    my ($self, $section, $index) = @_;
    my @entries = map { split m%\s*/\s*% } @{ $$self{INDEX} };
    return unless ($section || @entries);

    # We're about to output all pending entries, so clear our pending queue.
    $$self{INDEX} = [];

    # Build the output.  Regular index entries are marked Xref, and headings
    # pass in their own section.  Undo some *roff formatting on headings.
    my @output;
    if (@entries) {
        push @output, [ 'Xref', join (' ', @entries) ];
    }
    if ($section) {
        $index =~ s/\\-/-/g;
        $index =~ s/\\(?:s-?\d|.\(..|.)//g;
        push @output, [ $section, $index ];
    }

    # Print out the .IX commands.
    for (@output) {
        my ($type, $entry) = @$_;
        $entry =~ s/\s+/ /g;
        $entry =~ s/\"/\"\"/g;
        $entry =~ s/\\/\\\\/g;
        $self->output (".IX $type " . '"' . $entry . '"' . "\n");
    }
}

# Output some text, without any additional changes.
sub output {
    my ($self, @text) = @_;
    if ($$self{ENCODE}) {
        print { $$self{output_fh} } Encode::encode ('UTF-8', join ('', @text));
    } else {
        print { $$self{output_fh} } @text;
    }
}

##############################################################################
# Document initialization
##############################################################################

# Handle the start of the document.  Here we handle empty documents, as well
# as setting up our basic macros in a preamble and building the page title.
sub start_document {
    my ($self, $attrs) = @_;
    if ($$attrs{contentless} && !$$self{ALWAYS_EMIT_SOMETHING}) {
        DEBUG and print "Document is contentless\n";
        $$self{CONTENTLESS} = 1;
    } else {
        delete $$self{CONTENTLESS};
    }

    # When UTF-8 output is set, check whether our output file handle already
    # has a PerlIO encoding layer set.  If it does not, we'll need to encode
    # our output before printing it (handled in the output() sub).  Wrap the
    # check in an eval to handle versions of Perl without PerlIO.
    #
    # PerlIO::get_layers still requires its argument be a glob, so coerce the
    # file handle to a glob.
    $$self{ENCODE} = 0;
    if ($$self{utf8}) {
        $$self{ENCODE} = 1;
        eval {
            my @options = (output => 1, details => 1);
            my @layers = PerlIO::get_layers (*{$$self{output_fh}}, @options);
            if ($layers[-1] && ($layers[-1] & PerlIO::F_UTF8 ())) {
                $$self{ENCODE} = 0;
            }
        }
    }

    # Determine information for the preamble and then output it unless the
    # document was content-free.
    if (!$$self{CONTENTLESS}) {
        my ($name, $section);
        if (defined $$self{name}) {
            $name = $$self{name};
            $section = $$self{section} || 1;
        } else {
            ($name, $section) = $self->devise_title;
        }
        my $date = defined($$self{date}) ? $$self{date} : $self->devise_date;
        $self->preamble ($name, $section, $date)
            unless $self->bare_output or DEBUG > 9;
    }

    # Initialize a few per-document variables.
    $$self{INDENT}    = 0;      # Current indentation level.
    $$self{INDENTS}   = [];     # Stack of indentations.
    $$self{INDEX}     = [];     # Index keys waiting to be printed.
    $$self{IN_NAME}   = 0;      # Whether processing the NAME section.
    $$self{ITEMS}     = 0;      # The number of consecutive =items.
    $$self{ITEMTYPES} = [];     # Stack of =item types, one per list.
    $$self{SHIFTWAIT} = 0;      # Whether there is a shift waiting.
    $$self{SHIFTS}    = [];     # Stack of .RS shifts.
    $$self{PENDING}   = [[]];   # Pending output.
}

# Handle the end of the document.  This handles dying on POD errors, since
# Pod::Parser currently doesn't.  Otherwise, does nothing but print out a
# final comment at the end of the document under debugging.
sub end_document {
    my ($self) = @_;
    if ($$self{complain_die} && $self->errors_seen) {
        croak ("POD document had syntax errors");
    }
    return if $self->bare_output;
    return if ($$self{CONTENTLESS} && !$$self{ALWAYS_EMIT_SOMETHING});
    $self->output (q(.\" [End document]) . "\n") if DEBUG;
}

# Try to figure out the name and section from the file name and return them as
# a list, returning an empty name and section 1 if we can't find any better
# information.  Uses File::Basename and File::Spec as necessary.
sub devise_title {
    my ($self) = @_;
    my $name = $self->source_filename || '';
    my $section = $$self{section} || 1;
    $section = 3 if (!$$self{section} && $name =~ /\.pm\z/i);
    $name =~ s/\.p(od|[lm])\z//i;

    # If Pod::Parser gave us an IO::File reference as the source file name,
    # convert that to the empty string as well.  Then, if we don't have a
    # valid name, convert it to STDIN.
    #
    # In podlators 4.00 through 4.07, this also produced a warning, but that
    # was surprising to a lot of programs that had expected to be able to pipe
    # POD through pod2man without specifying the name.  In the name of
    # backward compatibility, just quietly set STDIN as the page title.
    if ($name =~ /^IO::File(?:=\w+)\(0x[\da-f]+\)$/i) {
        $name = '';
    }
    if ($name eq '') {
        $name = 'STDIN';
    }

    # If the section isn't 3, then the name defaults to just the basename of
    # the file.
    if ($section !~ /^3/) {
        require File::Basename;
        $name = uc File::Basename::basename ($name);
    } else {
        require File::Spec;
        my ($volume, $dirs, $file) = File::Spec->splitpath ($name);

        # Otherwise, assume we're dealing with a module.  We want to figure
        # out the full module name from the path to the file, but we don't
        # want to include too much of the path into the module name.  Lose
        # anything up to the first of:
        #
        #     */lib/*perl*/         standard or site_perl module
        #     */*perl*/lib/         from -Dprefix=/opt/perl
        #     */*perl*/             random module hierarchy
        #
        # Also strip off a leading site, site_perl, or vendor_perl component,
        # any OS-specific component, and any version number component, and
        # strip off an initial component of "lib" or "blib/lib" since that's
        # what ExtUtils::MakeMaker creates.
        #
        # splitdir requires at least File::Spec 0.8.
        my @dirs = File::Spec->splitdir ($dirs);
        if (@dirs) {
            my $cut = 0;
            my $i;
            for ($i = 0; $i < @dirs; $i++) {
                if ($dirs[$i] =~ /perl/) {
                    $cut = $i + 1;
                    $cut++ if ($dirs[$i + 1] && $dirs[$i + 1] eq 'lib');
                    last;
                }
            }
            if ($cut > 0) {
                splice (@dirs, 0, $cut);
                shift @dirs if ($dirs[0] =~ /^(site|vendor)(_perl)?$/);
                shift @dirs if ($dirs[0] =~ /^[\d.]+$/);
                shift @dirs if ($dirs[0] =~ /^(.*-$^O|$^O-.*|$^O)$/);
            }
            shift @dirs if $dirs[0] eq 'lib';
            splice (@dirs, 0, 2) if ($dirs[0] eq 'blib' && $dirs[1] eq 'lib');
        }

        # Remove empty directories when building the module name; they
        # occur too easily on Unix by doubling slashes.
        $name = join ('::', (grep { $_ ? $_ : () } @dirs), $file);
    }
    return ($name, $section);
}

# Determine the modification date and return that, properly formatted in ISO
# format.
#
# If POD_MAN_DATE is set, that overrides anything else.  This can be used for
# reproducible generation of the same file even if the input file timestamps
# are unpredictable or the POD comes from standard input.
#
# Otherwise, if SOURCE_DATE_EPOCH is set and can be parsed as seconds since
# the UNIX epoch, base the timestamp on that.  See
# <https://reproducible-builds.org/specs/source-date-epoch/>
#
# Otherwise, use the modification date of the input if we can stat it.  Be
# aware that Pod::Simple returns the stringification of the file handle as
# source_filename for input from a file handle, so we'll stat some random ref
# string in that case.  If that fails, instead use the current time.
#
# $self - Pod::Man object, used to get the source file
#
# Returns: YYYY-MM-DD date suitable for the left-hand footer
sub devise_date {
    my ($self) = @_;

    # If POD_MAN_DATE is set, always use it.
    if (defined($ENV{POD_MAN_DATE})) {
        return $ENV{POD_MAN_DATE};
    }

    # If SOURCE_DATE_EPOCH is set and can be parsed, use that.
    my $time;
    if (defined($ENV{SOURCE_DATE_EPOCH}) && $ENV{SOURCE_DATE_EPOCH} !~ /\D/) {
        $time = $ENV{SOURCE_DATE_EPOCH};
    }

    # Otherwise, get the input filename and try to stat it.  If that fails,
    # use the current time.
    if (!defined $time) {
        my $input = $self->source_filename;
        if ($input) {
            $time = (stat($input))[9] || time();
        } else {
            $time = time();
        }
    }

    # Can't use POSIX::strftime(), which uses Fcntl, because MakeMaker uses
    # this and it has to work in the core which can't load dynamic libraries.
    # Use gmtime instead of localtime so that the generated man page does not
    # depend on the local time zone setting and is more reproducible
    my ($year, $month, $day) = (gmtime($time))[5,4,3];
    return sprintf("%04d-%02d-%02d", $year + 1900, $month + 1, $day);
}

# Print out the preamble and the title.  The meaning of the arguments to .TH
# unfortunately vary by system; some systems consider the fourth argument to
# be a "source" and others use it as a version number.  Generally it's just
# presented as the left-side footer, though, so it doesn't matter too much if
# a particular system gives it another interpretation.
#
# The order of date and release used to be reversed in older versions of this
# module, but this order is correct for both Solaris and Linux.
sub preamble {
    my ($self, $name, $section, $date) = @_;
    my $preamble = $self->preamble_template (!$$self{utf8});

    # Build the index line and make sure that it will be syntactically valid.
    my $index = "$name $section";
    $index =~ s/\"/\"\"/g;

    # If name or section contain spaces, quote them (section really never
    # should, but we may as well be cautious).
    for ($name, $section) {
        if (/\s/) {
            s/\"/\"\"/g;
            $_ = '"' . $_ . '"';
        }
    }

    # Double quotes in date, since it will be quoted.
    $date =~ s/\"/\"\"/g;

    # Substitute into the preamble the configuration options.
    $preamble =~ s/\@CFONT\@/$$self{fixed}/;
    $preamble =~ s/\@LQUOTE\@/$$self{LQUOTE}/;
    $preamble =~ s/\@RQUOTE\@/$$self{RQUOTE}/;
    chomp $preamble;

    # Get the version information.
    my $version = $self->version_report;

    # Finally output everything.
    $self->output (<<"----END OF HEADER----");
.\\" Automatically generated by $version
.\\"
.\\" Standard preamble:
.\\" ========================================================================
$preamble
.\\" ========================================================================
.\\"
.IX Title "$index"
.TH $name $section "$date" "$$self{release}" "$$self{center}"
.\\" For nroff, turn off justification.  Always turn off hyphenation; it makes
.\\" way too many mistakes in technical documents.
.if n .ad l
.nh
----END OF HEADER----
    $self->output (".\\\" [End of preamble]\n") if DEBUG;
}

##############################################################################
# Text blocks
##############################################################################

# Handle a basic block of text.  The only tricky part of this is if this is
# the first paragraph of text after an =over, in which case we have to change
# indentations for *roff.
sub cmd_para {
    my ($self, $attrs, $text) = @_;
    my $line = $$attrs{start_line};

    # Output the paragraph.  We also have to handle =over without =item.  If
    # there's an =over without =item, SHIFTWAIT will be set, and we need to
    # handle creation of the indent here.  Add the shift to SHIFTS so that it
    # will be cleaned up on =back.
    $self->makespace;
    if ($$self{SHIFTWAIT}) {
        $self->output (".RS $$self{INDENT}\n");
        push (@{ $$self{SHIFTS} }, $$self{INDENT});
        $$self{SHIFTWAIT} = 0;
    }

    # Add the line number for debugging, but not in the NAME section just in
    # case the comment would confuse apropos.
    $self->output (".\\\" [At source line $line]\n")
        if defined ($line) && DEBUG && !$$self{IN_NAME};

    # Force exactly one newline at the end and strip unwanted trailing
    # whitespace at the end, but leave "\ " backslashed space from an S< > at
    # the end of a line.  Reverse the text first, to avoid having to scan the
    # entire paragraph.
    $text = reverse $text;
    $text =~ s/\A\s*?(?= \\|\S|\z)/\n/;
    $text = reverse $text;

    # Output the paragraph.
    $self->output ($self->protect ($self->textmapfonts ($text)));
    $self->outindex;
    $$self{NEEDSPACE} = 1;
    return '';
}

# Handle a verbatim paragraph.  Put a null token at the beginning of each line
# to protect against commands and wrap in .Vb/.Ve (which we define in our
# prelude).
sub cmd_verbatim {
    my ($self, $attrs, $text) = @_;

    # Ignore an empty verbatim paragraph.
    return unless $text =~ /\S/;

    # Force exactly one newline at the end and strip unwanted trailing
    # whitespace at the end.  Reverse the text first, to avoid having to scan
    # the entire paragraph.
    $text = reverse $text;
    $text =~ s/\A\s*/\n/;
    $text = reverse $text;

    # Get a count of the number of lines before the first blank line, which
    # we'll pass to .Vb as its parameter.  This tells *roff to keep that many
    # lines together.  We don't want to tell *roff to keep huge blocks
    # together.
    my @lines = split (/\n/, $text);
    my $unbroken = 0;
    for (@lines) {
        last if /^\s*$/;
        $unbroken++;
    }
    $unbroken = 10 if ($unbroken > 12 && !$$self{MAGIC_VNOPAGEBREAK_LIMIT});

    # Prepend a null token to each line.
    $text =~ s/^/\\&/gm;

    # Output the results.
    $self->makespace;
    $self->output (".Vb $unbroken\n$text.Ve\n");
    $$self{NEEDSPACE} = 1;
    return '';
}

# Handle literal text (produced by =for and similar constructs).  Just output
# it with the minimum of changes.
sub cmd_data {
    my ($self, $attrs, $text) = @_;
    $text =~ s/^\n+//;
    $text =~ s/\n{0,2}$/\n/;
    $self->output ($text);
    return '';
}

##############################################################################
# Headings
##############################################################################

# Common code for all headings.  This is called before the actual heading is
# output.  It returns the cleaned up heading text (putting the heading all on
# one line) and may do other things, like closing bad =item blocks.
sub heading_common {
    my ($self, $text, $line) = @_;
    $text =~ s/\s+$//;
    $text =~ s/\s*\n\s*/ /g;

    # This should never happen; it means that we have a heading after =item
    # without an intervening =back.  But just in case, handle it anyway.
    if ($$self{ITEMS} > 1) {
        $$self{ITEMS} = 0;
        $self->output (".PD\n");
    }

    # Output the current source line.
    $self->output ( ".\\\" [At source line $line]\n" )
        if defined ($line) && DEBUG;
    return $text;
}

# First level heading.  We can't output .IX in the NAME section due to a bug
# in some versions of catman, so don't output a .IX for that section.  .SH
# already uses small caps, so remove \s0 and \s-1.  Maintain IN_NAME as
# appropriate.
sub cmd_head1 {
    my ($self, $attrs, $text) = @_;
    $text =~ s/\\s-?\d//g;
    $text = $self->heading_common ($text, $$attrs{start_line});
    my $isname = ($text eq 'NAME' || $text =~ /\(NAME\)/);
    $self->output ($self->switchquotes ('.SH', $self->mapfonts ($text)));
    $self->outindex ('Header', $text) unless $isname;
    $$self{NEEDSPACE} = 0;
    $$self{IN_NAME} = $isname;
    return '';
}

# Second level heading.
sub cmd_head2 {
    my ($self, $attrs, $text) = @_;
    $text = $self->heading_common ($text, $$attrs{start_line});
    $self->output ($self->switchquotes ('.SS', $self->mapfonts ($text)));
    $self->outindex ('Subsection', $text);
    $$self{NEEDSPACE} = 0;
    return '';
}

# Third level heading.  *roff doesn't have this concept, so just put the
# heading in italics as a normal paragraph.
sub cmd_head3 {
    my ($self, $attrs, $text) = @_;
    $text = $self->heading_common ($text, $$attrs{start_line});
    $self->makespace;
    $self->output ($self->textmapfonts ('\f(IS' . $text . '\f(IE') . "\n");
    $self->outindex ('Subsection', $text);
    $$self{NEEDSPACE} = 1;
    return '';
}

# Fourth level heading.  *roff doesn't have this concept, so just put the
# heading as a normal paragraph.
sub cmd_head4 {
    my ($self, $attrs, $text) = @_;
    $text = $self->heading_common ($text, $$attrs{start_line});
    $self->makespace;
    $self->output ($self->textmapfonts ($text) . "\n");
    $self->outindex ('Subsection', $text);
    $$self{NEEDSPACE} = 1;
    return '';
}

##############################################################################
# Formatting codes
##############################################################################

# All of the formatting codes that aren't handled internally by the parser,
# other than L<> and X<>.
sub cmd_b { return $_[0]->{IN_NAME} ? $_[2] : '\f(BS' . $_[2] . '\f(BE' }
sub cmd_i { return $_[0]->{IN_NAME} ? $_[2] : '\f(IS' . $_[2] . '\f(IE' }
sub cmd_f { return $_[0]->{IN_NAME} ? $_[2] : '\f(IS' . $_[2] . '\f(IE' }
sub cmd_c { return $_[0]->quote_literal ($_[2]) }

# Index entries are just added to the pending entries.
sub cmd_x {
    my ($self, $attrs, $text) = @_;
    push (@{ $$self{INDEX} }, $text);
    return '';
}

# Links reduce to the text that we're given, wrapped in angle brackets if it's
# a URL, followed by the URL.  We take an option to suppress the URL if anchor
# text is given.  We need to format the "to" value of the link before
# comparing it to the text since we may escape hyphens.
sub cmd_l {
    my ($self, $attrs, $text) = @_;
    if ($$attrs{type} eq 'url') {
        my $to = $$attrs{to};
        if (defined $to) {
            my $tag = $$self{PENDING}[-1];
            $to = $self->format_text ($$tag[1], $to);
        }
        if (not defined ($to) or $to eq $text) {
            return "<$text>";
        } elsif ($$self{nourls}) {
            return $text;
        } else {
            return "$text <$$attrs{to}>";
        }
    } else {
        return $text;
    }
}

##############################################################################
# List handling
##############################################################################

# Handle the beginning of an =over block.  Takes the type of the block as the
# first argument, and then the attr hash.  This is called by the handlers for
# the four different types of lists (bullet, number, text, and block).
sub over_common_start {
    my ($self, $type, $attrs) = @_;
    my $line = $$attrs{start_line};
    my $indent = $$attrs{indent};
    DEBUG > 3 and print " Starting =over $type (line $line, indent ",
        ($indent || '?'), "\n";

    # Find the indentation level.
    unless (defined ($indent) && $indent =~ /^[-+]?\d{1,4}\s*$/) {
        $indent = $$self{indent};
    }

    # If we've gotten multiple indentations in a row, we need to emit the
    # pending indentation for the last level that we saw and haven't acted on
    # yet.  SHIFTS is the stack of indentations that we've actually emitted
    # code for.
    if (@{ $$self{SHIFTS} } < @{ $$self{INDENTS} }) {
        $self->output (".RS $$self{INDENT}\n");
        push (@{ $$self{SHIFTS} }, $$self{INDENT});
    }

    # Now, do record-keeping.  INDENTS is a stack of indentations that we've
    # seen so far, and INDENT is the current level of indentation.  ITEMTYPES
    # is a stack of list types that we've seen.
    push (@{ $$self{INDENTS} }, $$self{INDENT});
    push (@{ $$self{ITEMTYPES} }, $type);
    $$self{INDENT} = $indent + 0;
    $$self{SHIFTWAIT} = 1;
}

# End an =over block.  Takes no options other than the class pointer.
# Normally, once we close a block and therefore remove something from INDENTS,
# INDENTS will now be longer than SHIFTS, indicating that we also need to emit
# *roff code to close the indent.  This isn't *always* true, depending on the
# circumstance.  If we're still inside an indentation, we need to emit another
# .RE and then a new .RS to unconfuse *roff.
sub over_common_end {
    my ($self) = @_;
    DEBUG > 3 and print " Ending =over\n";
    $$self{INDENT} = pop @{ $$self{INDENTS} };
    pop @{ $$self{ITEMTYPES} };

    # If we emitted code for that indentation, end it.
    if (@{ $$self{SHIFTS} } > @{ $$self{INDENTS} }) {
        $self->output (".RE\n");
        pop @{ $$self{SHIFTS} };
    }

    # If we're still in an indentation, *roff will have now lost track of the
    # right depth of that indentation, so fix that.
    if (@{ $$self{INDENTS} } > 0) {
        $self->output (".RE\n");
        $self->output (".RS $$self{INDENT}\n");
    }
    $$self{NEEDSPACE} = 1;
    $$self{SHIFTWAIT} = 0;
}

# Dispatch the start and end calls as appropriate.
sub start_over_bullet { my $s = shift; $s->over_common_start ('bullet', @_) }
sub start_over_number { my $s = shift; $s->over_common_start ('number', @_) }
sub start_over_text   { my $s = shift; $s->over_common_start ('text',   @_) }
sub start_over_block  { my $s = shift; $s->over_common_start ('block',  @_) }
sub end_over_bullet { $_[0]->over_common_end }
sub end_over_number { $_[0]->over_common_end }
sub end_over_text   { $_[0]->over_common_end }
sub end_over_block  { $_[0]->over_common_end }

# The common handler for all item commands.  Takes the type of the item, the
# attributes, and then the text of the item.
#
# Emit an index entry for anything that's interesting, but don't emit index
# entries for things like bullets and numbers.  Newlines in an item title are
# turned into spaces since *roff can't handle them embedded.
sub item_common {
    my ($self, $type, $attrs, $text) = @_;
    my $line = $$attrs{start_line};
    DEBUG > 3 and print "  $type item (line $line): $text\n";

    # Clean up the text.  We want to end up with two variables, one ($text)
    # which contains any body text after taking out the item portion, and
    # another ($item) which contains the actual item text.
    $text =~ s/\s+$//;
    my ($item, $index);
    if ($type eq 'bullet') {
        $item = "\\\(bu";
        $text =~ s/\n*$/\n/;
    } elsif ($type eq 'number') {
        $item = $$attrs{number} . '.';
    } else {
        $item = $text;
        $item =~ s/\s*\n\s*/ /g;
        $text = '';
        $index = $item if ($item =~ /\w/);
    }

    # Take care of the indentation.  If shifts and indents are equal, close
    # the top shift, since we're about to create an indentation with .IP.
    # Also output .PD 0 to turn off spacing between items if this item is
    # directly following another one.  We only have to do that once for a
    # whole chain of items so do it for the second item in the change.  Note
    # that makespace is what undoes this.
    if (@{ $$self{SHIFTS} } == @{ $$self{INDENTS} }) {
        $self->output (".RE\n");
        pop @{ $$self{SHIFTS} };
    }
    $self->output (".PD 0\n") if ($$self{ITEMS} == 1);

    # Now, output the item tag itself.
    $item = $self->textmapfonts ($item);
    $self->output ($self->switchquotes ('.IP', $item, $$self{INDENT}));
    $$self{NEEDSPACE} = 0;
    $$self{ITEMS}++;
    $$self{SHIFTWAIT} = 0;

    # If body text for this item was included, go ahead and output that now.
    if ($text) {
        $text =~ s/\s*$/\n/;
        $self->makespace;
        $self->output ($self->protect ($self->textmapfonts ($text)));
        $$self{NEEDSPACE} = 1;
    }
    $self->outindex ($index ? ('Item', $index) : ());
}

# Dispatch the item commands to the appropriate place.
sub cmd_item_bullet { my $self = shift; $self->item_common ('bullet', @_) }
sub cmd_item_number { my $self = shift; $self->item_common ('number', @_) }
sub cmd_item_text   { my $self = shift; $self->item_common ('text',   @_) }
sub cmd_item_block  { my $self = shift; $self->item_common ('block',  @_) }

##############################################################################
# Backward compatibility
##############################################################################

# Reset the underlying Pod::Simple object between calls to parse_from_file so
# that the same object can be reused to convert multiple pages.
sub parse_from_file {
    my $self = shift;
    $self->reinit;

    # Fake the old cutting option to Pod::Parser.  This fiddles with internal
    # Pod::Simple state and is quite ugly; we need a better approach.
    if (ref ($_[0]) eq 'HASH') {
        my $opts = shift @_;
        if (defined ($$opts{-cutting}) && !$$opts{-cutting}) {
            $$self{in_pod} = 1;
            $$self{last_was_blank} = 1;
        }
    }

    # Do the work.
    my $retval = $self->SUPER::parse_from_file (@_);

    # Flush output, since Pod::Simple doesn't do this.  Ideally we should also
    # close the file descriptor if we had to open one, but we can't easily
    # figure this out.
    my $fh = $self->output_fh ();
    my $oldfh = select $fh;
    my $oldflush = $|;
    $| = 1;
    print $fh '';
    $| = $oldflush;
    select $oldfh;
    return $retval;
}

# Pod::Simple failed to provide this backward compatibility function, so
# implement it ourselves.  File handles are one of the inputs that
# parse_from_file supports.
sub parse_from_filehandle {
    my $self = shift;
    return $self->parse_from_file (@_);
}

# Pod::Simple's parse_file doesn't set output_fh.  Wrap the call and do so
# ourself unless it was already set by the caller, since our documentation has
# always said that this should work.
sub parse_file {
    my ($self, $in) = @_;
    unless (defined $$self{output_fh}) {
        $self->output_fh (\*STDOUT);
    }
    return $self->SUPER::parse_file ($in);
}

# Do the same for parse_lines, just to be polite.  Pod::Simple's man page
# implies that the caller is responsible for setting this, but I don't see any
# reason not to set a default.
sub parse_lines {
    my ($self, @lines) = @_;
    unless (defined $$self{output_fh}) {
        $self->output_fh (\*STDOUT);
    }
    return $self->SUPER::parse_lines (@lines);
}

# Likewise for parse_string_document.
sub parse_string_document {
    my ($self, $doc) = @_;
    unless (defined $$self{output_fh}) {
        $self->output_fh (\*STDOUT);
    }
    return $self->SUPER::parse_string_document ($doc);
}

##############################################################################
# Translation tables
##############################################################################

# The following table is adapted from Tom Christiansen's pod2man.  It assumes
# that the standard preamble has already been printed, since that's what
# defines all of the accent marks.  We really want to do something better than
# this when *roff actually supports other character sets itself, since these
# results are pretty poor.
#
# This only works in an ASCII world.  What to do in a non-ASCII world is very
# unclear -- hopefully we can assume UTF-8 and just leave well enough alone.
@ESCAPES{0xA0 .. 0xFF} = (
    "\\ ", undef, undef, undef,            undef, undef, undef, undef,
    undef, undef, undef, undef,            undef, "\\%", undef, undef,

    undef, undef, undef, undef,            undef, undef, undef, undef,
    undef, undef, undef, undef,            undef, undef, undef, undef,

    "A\\*`",  "A\\*'", "A\\*^", "A\\*~",   "A\\*:", "A\\*o", "\\*(Ae", "C\\*,",
    "E\\*`",  "E\\*'", "E\\*^", "E\\*:",   "I\\*`", "I\\*'", "I\\*^",  "I\\*:",

    "\\*(D-", "N\\*~", "O\\*`", "O\\*'",   "O\\*^", "O\\*~", "O\\*:",  undef,
    "O\\*/",  "U\\*`", "U\\*'", "U\\*^",   "U\\*:", "Y\\*'", "\\*(Th", "\\*8",

    "a\\*`",  "a\\*'", "a\\*^", "a\\*~",   "a\\*:", "a\\*o", "\\*(ae", "c\\*,",
    "e\\*`",  "e\\*'", "e\\*^", "e\\*:",   "i\\*`", "i\\*'", "i\\*^",  "i\\*:",

    "\\*(d-", "n\\*~", "o\\*`", "o\\*'",   "o\\*^", "o\\*~", "o\\*:",  undef,
    "o\\*/" , "u\\*`", "u\\*'", "u\\*^",   "u\\*:", "y\\*'", "\\*(th", "y\\*:",
) if ASCII;

##############################################################################
# Premable
##############################################################################

# The following is the static preamble which starts all *roff output we
# generate.  Most is static except for the font to use as a fixed-width font,
# which is designed by @CFONT@, and the left and right quotes to use for C<>
# text, designated by @LQOUTE@ and @RQUOTE@.  However, the second part, which
# defines the accent marks, is only used if $escapes is set to true.
sub preamble_template {
    my ($self, $accents) = @_;
    my $preamble = <<'----END OF PREAMBLE----';
.de Sp \" Vertical space (when we can't use .PP)
.if t .sp .5v
.if n .sp
..
.de Vb \" Begin verbatim text
.ft @CFONT@
.nf
.ne \\$1
..
.de Ve \" End verbatim text
.ft R
.fi
..
.\" Set up some character translations and predefined strings.  \*(-- will
.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
.\" double quote, and \*(R" will give a right double quote.  \*(C+ will
.\" give a nicer C++.  Capital omega is used to do unbreakable dashes and
.\" therefore won't be available.  \*(C` and \*(C' expand to `' in nroff,
.\" nothing in troff, for use with C<>.
.tr \(*W-
.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
.ie n \{\
.    ds -- \(*W-
.    ds PI pi
.    if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
.    if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\"  diablo 12 pitch
.    ds L" ""
.    ds R" ""
.    ds C` @LQUOTE@
.    ds C' @RQUOTE@
'br\}
.el\{\
.    ds -- \|\(em\|
.    ds PI \(*p
.    ds L" ``
.    ds R" ''
.    ds C`
.    ds C'
'br\}
.\"
.\" Escape single quotes in literal strings from groff's Unicode transform.
.ie \n(.g .ds Aq \(aq
.el       .ds Aq '
.\"
.\" If the F register is >0, we'll generate index entries on stderr for
.\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index
.\" entries marked with X<> in POD.  Of course, you'll have to process the
.\" output yourself in some meaningful fashion.
.\"
.\" Avoid warning from groff about undefined register 'F'.
.de IX
..
.nr rF 0
.if \n(.g .if rF .nr rF 1
.if (\n(rF:(\n(.g==0)) \{\
.    if \nF \{\
.        de IX
.        tm Index:\\$1\t\\n%\t"\\$2"
..
.        if !\nF==2 \{\
.            nr % 0
.            nr F 2
.        \}
.    \}
.\}
.rr rF
----END OF PREAMBLE----
#'# for cperl-mode

    if ($accents) {
        $preamble .= <<'----END OF PREAMBLE----'
.\"
.\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
.\" Fear.  Run.  Save yourself.  No user-serviceable parts.
.    \" fudge factors for nroff and troff
.if n \{\
.    ds #H 0
.    ds #V .8m
.    ds #F .3m
.    ds #[ \f1
.    ds #] \fP
.\}
.if t \{\
.    ds #H ((1u-(\\\\n(.fu%2u))*.13m)
.    ds #V .6m
.    ds #F 0
.    ds #[ \&
.    ds #] \&
.\}
.    \" simple accents for nroff and troff
.if n \{\
.    ds ' \&
.    ds ` \&
.    ds ^ \&
.    ds , \&
.    ds ~ ~
.    ds /
.\}
.if t \{\
.    ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
.    ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
.    ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
.    ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
.    ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
.    ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
.\}
.    \" troff and (daisy-wheel) nroff accents
.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
.ds 8 \h'\*(#H'\(*b\h'-\*(#H'
.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
.ds ae a\h'-(\w'a'u*4/10)'e
.ds Ae A\h'-(\w'A'u*4/10)'E
.    \" corrections for vroff
.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
.    \" for low resolution devices (crt and lpr)
.if \n(.H>23 .if \n(.V>19 \
\{\
.    ds : e
.    ds 8 ss
.    ds o a
.    ds d- d\h'-1'\(ga
.    ds D- D\h'-1'\(hy
.    ds th \o'bp'
.    ds Th \o'LP'
.    ds ae ae
.    ds Ae AE
.\}
.rm #[ #] #H #V #F C
----END OF PREAMBLE----
#`# for cperl-mode
    }
    return $preamble;
}

##############################################################################
# Module return value and documentation
##############################################################################

1;
__END__

=for stopwords
en em ALLCAPS teeny fixedbold fixeditalic fixedbolditalic stderr utf8 UTF-8
Allbery Sean Burke Ossanna Solaris formatters troff uppercased Christiansen
nourls parsers Kernighan lquote rquote

=head1 NAME

Pod::Man - Convert POD data to formatted *roff input

=head1 SYNOPSIS

    use Pod::Man;
    my $parser = Pod::Man->new (release => $VERSION, section => 8);

    # Read POD from STDIN and write to STDOUT.
    $parser->parse_file (\*STDIN);

    # Read POD from file.pod and write to file.1.
    $parser->parse_from_file ('file.pod', 'file.1');

=head1 DESCRIPTION

Pod::Man is a module to convert documentation in the POD format (the
preferred language for documenting Perl) into *roff input using the man
macro set.  The resulting *roff code is suitable for display on a terminal
using L<nroff(1)>, normally via L<man(1)>, or printing using L<troff(1)>.
It is conventionally invoked using the driver script B<pod2man>, but it can
also be used directly.

As a derived class from Pod::Simple, Pod::Man supports the same methods and
interfaces.  See L<Pod::Simple> for all the details.

new() can take options, in the form of key/value pairs that control the
behavior of the parser.  See below for details.

If no options are given, Pod::Man uses the name of the input file with any
trailing C<.pod>, C<.pm>, or C<.pl> stripped as the man page title, to
section 1 unless the file ended in C<.pm> in which case it defaults to
section 3, to a centered title of "User Contributed Perl Documentation", to
a centered footer of the Perl version it is run with, and to a left-hand
footer of the modification date of its input (or the current date if given
C<STDIN> for input).

Pod::Man assumes that your *roff formatters have a fixed-width font named
C<CW>.  If yours is called something else (like C<CR>), use the C<fixed>
option to specify it.  This generally only matters for troff output for
printing.  Similarly, you can set the fonts used for bold, italic, and
bold italic fixed-width output.

Besides the obvious pod conversions, Pod::Man also takes care of
formatting func(), func(3), and simple variable references like $foo or
@bar so you don't have to use code escapes for them; complex expressions
like C<$fred{'stuff'}> will still need to be escaped, though.  It also
translates dashes that aren't used as hyphens into en dashes, makes long
dashes--like this--into proper em dashes, fixes "paired quotes," makes C++
look right, puts a little space between double underscores, makes ALLCAPS
a teeny bit smaller in B<troff>, and escapes stuff that *roff treats as
special so that you don't have to.

The recognized options to new() are as follows.  All options take a single
argument.

=over 4

=item center

Sets the centered page header for the C<.TH> macro.  The default, if this
option is not specified, is "User Contributed Perl Documentation".

=item date

Sets the left-hand footer for the C<.TH> macro.  If this option is not set,
the contents of the environment variable POD_MAN_DATE, if set, will be used.
Failing that, the value of SOURCE_DATE_EPOCH, the modification date of the
input file, or the current time if stat() can't find that file (which will be
the case if the input is from C<STDIN>) will be used.  If obtained from the
file modification date or the current time, the date will be formatted as
C<YYYY-MM-DD> and will be based on UTC (so that the output will be
reproducible regardless of local time zone).

=item errors

How to report errors.  C<die> says to throw an exception on any POD
formatting error.  C<stderr> says to report errors on standard error, but
not to throw an exception.  C<pod> says to include a POD ERRORS section
in the resulting documentation summarizing the errors.  C<none> ignores
POD errors entirely, as much as possible.

The default is C<pod>.

=item fixed

The fixed-width font to use for verbatim text and code.  Defaults to
C<CW>.  Some systems may want C<CR> instead.  Only matters for B<troff>
output.

=item fixedbold

Bold version of the fixed-width font.  Defaults to C<CB>.  Only matters
for B<troff> output.

=item fixeditalic

Italic version of the fixed-width font (actually, something of a misnomer,
since most fixed-width fonts only have an oblique version, not an italic
version).  Defaults to C<CI>.  Only matters for B<troff> output.

=item fixedbolditalic

Bold italic (probably actually oblique) version of the fixed-width font.
Pod::Man doesn't assume you have this, and defaults to C<CB>.  Some
systems (such as Solaris) have this font available as C<CX>.  Only matters
for B<troff> output.

=item lquote

=item rquote

Sets the quote marks used to surround CE<lt>> text.  C<lquote> sets the
left quote mark and C<rquote> sets the right quote mark.  Either may also
be set to the special value C<none>, in which case no quote mark is added
on that side of CE<lt>> text (but the font is still changed for troff
output).

Also see the C<quotes> option, which can be used to set both quotes at once.
If both C<quotes> and one of the other options is set, C<lquote> or C<rquote>
overrides C<quotes>.

=item name

Set the name of the manual page for the C<.TH> macro.  Without this
option, the manual name is set to the uppercased base name of the file
being converted unless the manual section is 3, in which case the path is
parsed to see if it is a Perl module path.  If it is, a path like
C<.../lib/Pod/Man.pm> is converted into a name like C<Pod::Man>.  This
option, if given, overrides any automatic determination of the name.

If generating a manual page from standard input, the name will be set to
C<STDIN> if this option is not provided.  Providing this option is strongly
recommended to set a meaningful manual page name.

=item nourls

Normally, LZ<><> formatting codes with a URL but anchor text are formatted
to show both the anchor text and the URL.  In other words:

    L<foo|http://example.com/>

is formatted as:

    foo <http://example.com/>

This option, if set to a true value, suppresses the URL when anchor text
is given, so this example would be formatted as just C<foo>.  This can
produce less cluttered output in cases where the URLs are not particularly
important.

=item quotes

Sets the quote marks used to surround CE<lt>> text.  If the value is a
single character, it is used as both the left and right quote.  Otherwise,
it is split in half, and the first half of the string is used as the left
quote and the second is used as the right quote.

This may also be set to the special value C<none>, in which case no quote
marks are added around CE<lt>> text (but the font is still changed for troff
output).

Also see the C<lquote> and C<rquote> options, which can be used to set the
left and right quotes independently.  If both C<quotes> and one of the other
options is set, C<lquote> or C<rquote> overrides C<quotes>.

=item release

Set the centered footer for the C<.TH> macro.  By default, this is set to
the version of Perl you run Pod::Man under.  Setting this to the empty
string will cause some *roff implementations to use the system default
value.

Note that some system C<an> macro sets assume that the centered footer
will be a modification date and will prepend something like "Last
modified: ".  If this is the case for your target system, you may want to
set C<release> to the last modified date and C<date> to the version
number.

=item section

Set the section for the C<.TH> macro.  The standard section numbering
convention is to use 1 for user commands, 2 for system calls, 3 for
functions, 4 for devices, 5 for file formats, 6 for games, 7 for
miscellaneous information, and 8 for administrator commands.  There is a lot
of variation here, however; some systems (like Solaris) use 4 for file
formats, 5 for miscellaneous information, and 7 for devices.  Still others
use 1m instead of 8, or some mix of both.  About the only section numbers
that are reliably consistent are 1, 2, and 3.

By default, section 1 will be used unless the file ends in C<.pm> in which
case section 3 will be selected.

=item stderr

Send error messages about invalid POD to standard error instead of
appending a POD ERRORS section to the generated *roff output.  This is
equivalent to setting C<errors> to C<stderr> if C<errors> is not already
set.  It is supported for backward compatibility.

=item utf8

By default, Pod::Man produces the most conservative possible *roff output
to try to ensure that it will work with as many different *roff
implementations as possible.  Many *roff implementations cannot handle
non-ASCII characters, so this means all non-ASCII characters are converted
either to a *roff escape sequence that tries to create a properly accented
character (at least for troff output) or to C<X>.

If this option is set, Pod::Man will instead output UTF-8.  If your *roff
implementation can handle it, this is the best output format to use and
avoids corruption of documents containing non-ASCII characters.  However,
be warned that *roff source with literal UTF-8 characters is not supported
by many implementations and may even result in segfaults and other bad
behavior.

Be aware that, when using this option, the input encoding of your POD
source should be properly declared unless it's US-ASCII.  Pod::Simple will
attempt to guess the encoding and may be successful if it's Latin-1 or
UTF-8, but it will produce warnings.  Use the C<=encoding> command to
declare the encoding.  See L<perlpod(1)> for more information.

=back

The standard Pod::Simple method parse_file() takes one argument naming the
POD file to read from.  By default, the output is sent to C<STDOUT>, but
this can be changed with the output_fh() method.

The standard Pod::Simple method parse_from_file() takes up to two
arguments, the first being the input file to read POD from and the second
being the file to write the formatted output to.

You can also call parse_lines() to parse an array of lines or
parse_string_document() to parse a document already in memory.  As with
parse_file(), parse_lines() and parse_string_document() default to sending
their output to C<STDOUT> unless changed with the output_fh() method.  Be
aware that parse_lines() and parse_string_document() both expect raw bytes,
not decoded characters.

To put the output from any parse method into a string instead of a file
handle, call the output_string() method instead of output_fh().

See L<Pod::Simple> for more specific details on the methods available to
all derived parsers.

=head1 DIAGNOSTICS

=over 4

=item roff font should be 1 or 2 chars, not "%s"

(F) You specified a *roff font (using C<fixed>, C<fixedbold>, etc.) that
wasn't either one or two characters.  Pod::Man doesn't support *roff fonts
longer than two characters, although some *roff extensions do (the
canonical versions of B<nroff> and B<troff> don't either).

=item Invalid errors setting "%s"

(F) The C<errors> parameter to the constructor was set to an unknown value.

=item Invalid quote specification "%s"

(F) The quote specification given (the C<quotes> option to the
constructor) was invalid.  A quote specification must be either one
character long or an even number (greater than one) characters long.

=item POD document had syntax errors

(F) The POD document being formatted had syntax errors and the C<errors>
option was set to C<die>.

=back

=head1 ENVIRONMENT

=over 4

=item PERL_CORE

If set and Encode is not available, silently fall back to non-UTF-8 mode
without complaining to standard error.  This environment variable is set
during Perl core builds, which build Encode after podlators.  Encode is
expected to not (yet) be available in that case.

=item POD_MAN_DATE

If set, this will be used as the value of the left-hand footer unless the
C<date> option is explicitly set, overriding the timestamp of the input
file or the current time.  This is primarily useful to ensure reproducible
builds of the same output file given the same source and Pod::Man version,
even when file timestamps may not be consistent.

=item SOURCE_DATE_EPOCH

If set, and POD_MAN_DATE and the C<date> options are not set, this will be
used as the modification time of the source file, overriding the timestamp of
the input file or the current time.  It should be set to the desired time in
seconds since UNIX epoch.  This is primarily useful to ensure reproducible
builds of the same output file given the same source and Pod::Man version,
even when file timestamps may not be consistent.  See
L<https://reproducible-builds.org/specs/source-date-epoch/> for the full
specification.

(Arguably, according to the specification, this variable should be used only
if the timestamp of the input file is not available and Pod::Man uses the
current time.  However, for reproducible builds in Debian, results were more
reliable if this variable overrode the timestamp of the input file.)

=back

=head1 BUGS

Encoding handling assumes that PerlIO is available and does not work
properly if it isn't.  The C<utf8> option is therefore not supported
unless Perl is built with PerlIO support.

There is currently no way to turn off the guesswork that tries to format
unmarked text appropriately, and sometimes it isn't wanted (particularly
when using POD to document something other than Perl).  Most of the work
toward fixing this has now been done, however, and all that's still needed
is a user interface.

The NAME section should be recognized specially and index entries emitted
for everything in that section.  This would have to be deferred until the
next section, since extraneous things in NAME tends to confuse various man
page processors.  Currently, no index entries are emitted for anything in
NAME.

Pod::Man doesn't handle font names longer than two characters.  Neither do
most B<troff> implementations, but GNU troff does as an extension.  It would
be nice to support as an option for those who want to use it.

The preamble added to each output file is rather verbose, and most of it
is only necessary in the presence of non-ASCII characters.  It would
ideally be nice if all of those definitions were only output if needed,
perhaps on the fly as the characters are used.

Pod::Man is excessively slow.

=head1 CAVEATS

If Pod::Man is given the C<utf8> option, the encoding of its output file
handle will be forced to UTF-8 if possible, overriding any existing
encoding.  This will be done even if the file handle is not created by
Pod::Man and was passed in from outside.  This maintains consistency
regardless of PERL_UNICODE and other settings.

The handling of hyphens and em dashes is somewhat fragile, and one may get
the wrong one under some circumstances.  This should only matter for
B<troff> output.

When and whether to use small caps is somewhat tricky, and Pod::Man doesn't
necessarily get it right.

Converting neutral double quotes to properly matched double quotes doesn't
work unless there are no formatting codes between the quote marks.  This
only matters for troff output.

=head1 AUTHOR

Russ Allbery <rra@cpan.org>, based I<very> heavily on the original B<pod2man>
by Tom Christiansen <tchrist@mox.perl.com>.  The modifications to work with
Pod::Simple instead of Pod::Parser were originally contributed by Sean Burke
<sburke@cpan.org> (but I've since hacked them beyond recognition and all bugs
are mine).

=head1 COPYRIGHT AND LICENSE

Copyright 1999-2010, 2012-2019 Russ Allbery <rra@cpan.org>

Substantial contributions by Sean Burke <sburke@cpan.org>.

This program is free software; you may redistribute it and/or modify it
under the same terms as Perl itself.

=head1 SEE ALSO

L<Pod::Simple>, L<perlpod(1)>, L<pod2man(1)>, L<nroff(1)>, L<troff(1)>,
L<man(1)>, L<man(7)>

Ossanna, Joseph F., and Brian W. Kernighan.  "Troff User's Manual,"
Computing Science Technical Report No. 54, AT&T Bell Laboratories.  This is
the best documentation of standard B<nroff> and B<troff>.  At the time of
this writing, it's available at L<http://www.troff.org/54.pdf>.

The man page documenting the man macro set may be L<man(5)> instead of
L<man(7)> on your system.  Also, please see L<pod2man(1)> for extensive
documentation on writing manual pages if you've not done it before and
aren't familiar with the conventions.

The current version of this module is always available from its web site at
L<https://www.eyrie.org/~eagle/software/podlators/>.  It is also part of the
Perl core distribution as of 5.6.0.

=cut

# Local Variables:
# copyright-at-end-flag: t
# End:
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          package Pod::Simple::BlackBox;
#
# "What's in the box?"  "Pain."
#
###########################################################################
#
# This is where all the scary things happen: parsing lines into
#  paragraphs; and then into directives, verbatims, and then also
#  turning formatting sequences into treelets.
#
# Are you really sure you want to read this code?
#
#-----------------------------------------------------------------------------
#
# The basic work of this module Pod::Simple::BlackBox is doing the dirty work
# of parsing Pod into treelets (generally one per non-verbatim paragraph), and
# to call the proper callbacks on the treelets.
#
# Every node in a treelet is a ['name', {attrhash}, ...children...]

use integer; # vroom!
use strict;
use Carp ();
use vars qw($VERSION );
$VERSION = '3.43';
#use constant DEBUG => 7;

sub my_qr ($$) {

    # $1 is a pattern to compile and return.  Older perls compile any
    # syntactically valid property, even if it isn't legal.  To cope with
    # this, return an empty string unless the compiled pattern also
    # successfully matches $2, which the caller furnishes.

    my ($input_re, $should_match) = @_;
    # XXX could have a third parameter $shouldnt_match for extra safety

    my $use_utf8 = ($] le 5.006002) ? 'use utf8;' : "";

    my $re = eval "no warnings; $use_utf8 qr/$input_re/";
    #print STDERR  __LINE__, ": $input_re: $@\n" if $@;
    return "" if $@;

    my $matches = eval "no warnings; $use_utf8 '$should_match' =~ /$re/";
    #print STDERR  __LINE__, ": $input_re: $@\n" if $@;
    return "" if $@;

    #print STDERR  __LINE__, ": SUCCESS: $re\n" if $matches;
    return $re if $matches;

    #print STDERR  __LINE__, ": $re: didn't match\n";
    return "";
}

BEGIN {
  require Pod::Simple;
  *DEBUG = \&Pod::Simple::DEBUG unless defined &DEBUG
}

# Matches a character iff the character will have a different meaning
# if we choose CP1252 vs UTF-8 if there is no =encoding line.
# This is broken for early Perls on non-ASCII platforms.
my $non_ascii_re = my_qr('[[:^ascii:]]', "\xB6");
$non_ascii_re = qr/[\x80-\xFF]/ unless $non_ascii_re;

# Use patterns understandable by Perl 5.6, if possible
my $cs_re = do { no warnings; my_qr('\p{IsCs}', "\x{D800}") };
my $cn_re = my_qr('\p{IsCn}', "\x{09E4}");  # <reserved> code point unlikely
                                            # to get assigned
my $rare_blocks_re = my_qr('[\p{InIPAExtensions}\p{InSpacingModifierLetters}]',
                           "\x{250}");
$rare_blocks_re = my_qr('[\x{0250}-\x{02FF}]', "\x{250}") unless $rare_blocks_re;

my $script_run_re = eval 'no warnings "experimental::script_run";
                          qr/(*script_run: ^ .* $ )/x';
my $latin_re = my_qr('[\p{IsLatin}\p{IsInherited}\p{IsCommon}]', "\x{100}");
unless ($latin_re) {
    # This was machine generated to be the ranges of the union of the above
    # three properties, with things that were undefined by Unicode 4.1 filling
    # gaps.  That is the version in use when Perl advanced enough to
    # successfully compile and execute the above pattern.
    $latin_re = my_qr('[\x00-\x{02E9}\x{02EC}-\x{0374}\x{037E}\x{0385}\x{0387}\x{0485}\x{0486}\x{0589}\x{060C}\x{061B}\x{061F}\x{0640}\x{064B}-\x{0655}\x{0670}\x{06DD}\x{0951}-\x{0954}\x{0964}\x{0965}\x{0E3F}\x{10FB}\x{16EB}-\x{16ED}\x{1735}\x{1736}\x{1802}\x{1803}\x{1805}\x{1D00}-\x{1D25}\x{1D2C}-\x{1D5C}\x{1D62}-\x{1D65}\x{1D6B}-\x{1D77}\x{1D79}-\x{1DBE}\x{1DC0}-\x{1EF9}\x{2000}-\x{2125}\x{2127}-\x{27FF}\x{2900}-\x{2B13}\x{2E00}-\x{2E1D}\x{2FF0}-\x{3004}\x{3006}\x{3008}-\x{3020}\x{302A}-\x{302D}\x{3030}-\x{3037}\x{303C}-\x{303F}\x{3099}-\x{309C}\x{30A0}\x{30FB}\x{30FC}\x{3190}-\x{319F}\x{31C0}-\x{31CF}\x{3220}-\x{325F}\x{327F}-\x{32CF}\x{3358}-\x{33FF}\x{4DC0}-\x{4DFF}\x{A700}-\x{A716}\x{FB00}-\x{FB06}\x{FD3E}\x{FD3F}\x{FE00}-\x{FE6B}\x{FEFF}-\x{FF65}\x{FF70}\x{FF9E}\x{FF9F}\x{FFE0}-\x{FFFD}\x{10100}-\x{1013F}\x{1D000}-\x{1D1DD}\x{1D300}-\x{1D7FF}]', "\x{100}");
}

my $every_char_is_latin_re = my_qr("^(?:$latin_re)*\\z", "A");

# Latin script code points not in the first release of Unicode
my $later_latin_re = my_qr('[^\P{IsLatin}\p{IsAge=1.1}]', "\x{1F6}");

# If this perl doesn't have the Deprecated property, there's only one code
# point in it that we need be concerned with.
my $deprecated_re = my_qr('\p{IsDeprecated}', "\x{149}");
$deprecated_re = qr/\x{149}/ unless $deprecated_re;

my $utf8_bom;
if (($] ge 5.007_003)) {
  $utf8_bom = "\x{FEFF}";
  utf8::encode($utf8_bom);
} else {
  $utf8_bom = "\xEF\xBB\xBF";   # No EBCDIC BOM detection for early Perls.
}

# This is used so that the 'content_seen' method doesn't return true on a
# file that just happens to have a line that matches /^=[a-zA-z]/.  Only if
# there is a valid =foo line will we return that content was seen.
my $seen_legal_directive = 0;

#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

sub parse_line { shift->parse_lines(@_) } # alias

# - - -  Turn back now!  Run away!  - - -

sub parse_lines {             # Usage: $parser->parse_lines(@lines)
  # an undef means end-of-stream
  my $self = shift;

  my $code_handler = $self->{'code_handler'};
  my $cut_handler  = $self->{'cut_handler'};
  my $wl_handler   = $self->{'whiteline_handler'};
  $self->{'line_count'} ||= 0;

  my $scratch;

  DEBUG > 4 and
   print STDERR "# Parsing starting at line ", $self->{'line_count'}, ".\n";

  DEBUG > 5 and
   print STDERR "#  About to parse lines: ",
     join(' ', map defined($_) ? "[$_]" : "EOF", @_), "\n";

  my $paras = ($self->{'paras'} ||= []);
   # paragraph buffer.  Because we need to defer processing of =over
   # directives and verbatim paragraphs.  We call _ponder_paragraph_buffer
   # to process this.

  $self->{'pod_para_count'} ||= 0;

  # An attempt to match the pod portions of a line.  This is not fool proof,
  # but is good enough to serve as part of the heuristic for guessing the pod
  # encoding if not specified.
  my $codes = join '', grep { / ^ [A-Za-z] $/x } sort keys %{$self->{accept_codes}};
  my $pod_chars_re = qr/ ^ = [A-Za-z]+ | [\Q$codes\E] < /x;

  my $line;
  foreach my $source_line (@_) {
    if( $self->{'source_dead'} ) {
      DEBUG > 4 and print STDERR "# Source is dead.\n";
      last;
    }

    unless( defined $source_line ) {
      DEBUG > 4 and print STDERR "# Undef-line seen.\n";

      push @$paras, ['~end', {'start_line' => $self->{'line_count'}}];
      push @$paras, $paras->[-1], $paras->[-1];
       # So that it definitely fills the buffer.
      $self->{'source_dead'} = 1;
      $self->_ponder_paragraph_buffer;
      next;
    }


    if( $self->{'line_count'}++ ) {
      ($line = $source_line) =~ tr/\n\r//d;
       # If we don't have two vars, we'll end up with that there
       # tr/// modding the (potentially read-only) original source line!

    } else {
      DEBUG > 2 and print STDERR "First line: [$source_line]\n";

      if( ($line = $source_line) =~ s/^$utf8_bom//s ) {
        DEBUG and print STDERR "UTF-8 BOM seen.  Faking a '=encoding utf8'.\n";
        $self->_handle_encoding_line( "=encoding utf8" );
        delete $self->{'_processed_encoding'};
        $line =~ tr/\n\r//d;

      } elsif( $line =~ s/^\xFE\xFF//s ) {
        DEBUG and print STDERR "Big-endian UTF-16 BOM seen.  Aborting parsing.\n";
        $self->scream(
          $self->{'line_count'},
          "UTF16-BE Byte Encoding Mark found; but Pod::Simple v$Pod::Simple::VERSION doesn't implement UTF16 yet."
        );
        splice @_;
        push @_, undef;
        next;

        # TODO: implement somehow?

      } elsif( $line =~ s/^\xFF\xFE//s ) {
        DEBUG and print STDERR "Little-endian UTF-16 BOM seen.  Aborting parsing.\n";
        $self->scream(
          $self->{'line_count'},
          "UTF16-LE Byte Encoding Mark found; but Pod::Simple v$Pod::Simple::VERSION doesn't implement UTF16 yet."
        );
        splice @_;
        push @_, undef;
        next;

        # TODO: implement somehow?

      } else {
        DEBUG > 2 and print STDERR "First line is BOM-less.\n";
        ($line = $source_line) =~ tr/\n\r//d;
      }
    }

    if(!$self->{'parse_characters'} && !$self->{'encoding'}
      && ($self->{'in_pod'} || $line =~ /^=/s)
      && $line =~ /$non_ascii_re/
    ) {

      my $encoding;

      # No =encoding line, and we are at the first pod line in the input that
      # contains a non-ascii byte, that is, one whose meaning varies depending
      # on whether the file is encoded in UTF-8 or CP1252, which are the two
      # possibilities permitted by the pod spec.  (ASCII is assumed if the
      # file only contains ASCII bytes.)  In order to process this line, we
      # need to figure out what encoding we will use for the file.
      #
      # Strictly speaking ISO 8859-1 (Latin 1) refers to the code points
      # 160-255, but it is used here, as it often colloquially is, to refer to
      # the complete set of code points 0-255, including ASCII (0-127), the C1
      # controls (128-159), and strict Latin 1 (160-255).
      #
      # CP1252 is effectively a superset of Latin 1, because it differs only
      # from colloquial 8859-1 in the C1 controls, which are very unlikely to
      # actually be present in 8859-1 files, so can be used for other purposes
      # without conflict.  CP 1252 uses most of them for graphic characters.
      #
      # Note that all ASCII-range bytes represent their corresponding code
      # points in both CP1252 and UTF-8.  In ASCII platform UTF-8, all other
      # code points require multiple (non-ASCII) bytes to represent.  (A
      # separate paragraph for EBCDIC is below.)  The multi-byte
      # representation is quite structured.  If we find an isolated byte that
      # would require multiple bytes to represent in UTF-8, we know that the
      # encoding is not UTF-8.  If we find a sequence of bytes that violates
      # the UTF-8 structure, we also can presume the encoding isn't UTF-8, and
      # hence must be 1252.
      #
      # But there are ambiguous cases where we could guess wrong.  If so, the
      # user will end up having to supply an =encoding line.  We use all
      # readily available information to improve our chances of guessing
      # right.  The odds of something not being UTF-8, but still passing a
      # UTF-8 validity test go down very rapidly with increasing length of the
      # sequence.  Therefore we look at all non-ascii sequences on the line.
      # If any of the sequences can't be UTF-8, we quit there and choose
      # CP1252.  If all could be UTF-8, we see if any of the code points
      # represented are unlikely to be in pod.  If so, we guess CP1252.  If
      # not, we check if the line is all in the same script; if not guess
      # CP1252; otherwise UTF-8.  For perls that don't have convenient script
      # run testing, see if there is both Latin and non-Latin.  If so, CP1252,
      # otherwise UTF-8.
      #
      # On EBCDIC platforms, the situation is somewhat different.  In
      # UTF-EBCDIC, not only do ASCII-range bytes represent their code points,
      # but so do the bytes that are for the C1 controls.  Recall that these
      # correspond to the unused portion of 8859-1 that 1252 mostly takes
      # over.  That means that there are fewer code points that are
      # represented by multi-bytes.  But, note that the these controls are
      # very unlikely to be in pod text.  So if we encounter one of them, it
      # means that it is quite likely CP1252 and not UTF-8.  The net result is
      # the same code below is used for both platforms.
      #
      # XXX probably if the line has E<foo> that evaluates to illegal CP1252,
      # then it is UTF-8.  But we haven't processed E<> yet.

      goto set_1252 if $] lt 5.006_000;    # No UTF-8 on very early perls

      my $copy;

      no warnings 'utf8';

      if ($] ge 5.007_003) {
        $copy = $line;

        # On perls that have this function, we can use it to easily see if the
        # sequence is valid UTF-8 or not; if valid it turns on the UTF-8 flag
        # needed below for script run detection
        goto set_1252 if ! utf8::decode($copy);
      }
      elsif (ord("A") != 65) {  # Early EBCDIC, assume UTF-8.  What's a windows
                                # code page doing here anyway?
        goto set_utf8;
      }
      else { # ASCII, no decode(): do it ourselves using the fundamental
             # characteristics of UTF-8
        use if $] le 5.006002, 'utf8';

        my $char_ord;
        my $needed;         # How many continuation bytes to gobble up

        # Initialize the translated line with a dummy character that will be
        # deleted after everything else is done.  This dummy makes sure that
        # $copy will be in UTF-8.  Doing it now avoids the bugs in early perls
        # with upgrading in the middle
        $copy = chr(0x100);

        # Parse through the line
        for (my $i = 0; $i < length $line; $i++) {
          my $byte = substr($line, $i, 1);

          # ASCII bytes are trivially dealt with
          if ($byte !~ $non_ascii_re) {
            $copy .= $byte;
            next;
          }

          my $b_ord = ord $byte;

          # Now figure out what this code point would be if the input is
          # actually in UTF-8.  If, in the process, we discover that it isn't
          # well-formed UTF-8, we guess CP1252.
          #
          # Start the process.  If it is UTF-8, we are at the first, start
          # byte, of a multi-byte sequence.  We look at this byte to figure
          # out how many continuation bytes are needed, and to initialize the
          # code point accumulator with the data from this byte.
          #
          # Normally the minimum continuation byte is 0x80, but in certain
          # instances the minimum is a higher number.  So the code below
          # overrides this for those instances.
          my $min_cont = 0x80;

          if ($b_ord < 0xC2) { #  A start byte < C2 is malformed
            goto set_1252;
          }
          elsif ($b_ord <= 0xDF) {
            $needed = 1;
            $char_ord = $b_ord & 0x1F;
          }
          elsif ($b_ord <= 0xEF) {
            $min_cont = 0xA0 if $b_ord == 0xE0;
            $needed = 2;
            $char_ord = $b_ord & (0x1F >> 1);
          }
          elsif ($b_ord <= 0xF4) {
            $min_cont = 0x90 if $b_ord == 0xF0;
            $needed = 3;
            $char_ord = $b_ord & (0x1F >> 2);
          }
          else { # F4 is the highest start byte for legal Unicode; higher is
                 # unlikely to be in pod.
            goto set_1252;
          }

          # ? not enough continuation bytes available
          goto set_1252 if $i + $needed >= length $line;

          # Accumulate the ordinal of the character from the remaining
          # (continuation) bytes.
          while ($needed-- > 0) {
            my $cont = substr($line, ++$i, 1);
            $b_ord = ord $cont;
            goto set_1252 if $b_ord < $min_cont || $b_ord > 0xBF;

            # In all cases, any next continuation bytes all have the same
            # minimum legal value
            $min_cont = 0x80;

            # Accumulate this byte's contribution to the code point
            $char_ord <<= 6;
            $char_ord |= ($b_ord & 0x3F);
          }

          # Here, the sequence that formed this code point was valid UTF-8,
          # so add the completed character to the output
          $copy .= chr $char_ord;
        } # End of loop through line

        # Delete the dummy first character
        $copy = substr($copy, 1);
      }

      # Here, $copy is legal UTF-8.

      # If it can't be legal CP1252, no need to look further.  (These bytes
      # aren't valid in CP1252.)  This test could have been placed higher in
      # the code, but it seemed wrong to set the encoding to UTF-8 without
      # making sure that the very first instance is well-formed.  But what if
      # it isn't legal CP1252 either?  We have to choose one or the other, and
      # It seems safer to favor the single-byte encoding over the multi-byte.
      goto set_utf8 if ord("A") == 65 && $line =~ /[\x81\x8D\x8F\x90\x9D]/;

      # The C1 controls are not likely to appear in pod
      goto set_1252 if ord("A") == 65 && $copy =~ /[\x80-\x9F]/;

      # Nor are surrogates nor unassigned, nor deprecated.
      DEBUG > 8 and print STDERR __LINE__, ": $copy: surrogate\n" if $copy =~ $cs_re;
      goto set_1252 if $cs_re && $copy =~ $cs_re;
      DEBUG > 8 and print STDERR __LINE__, ": $copy: unassigned\n" if $cn_re && $copy =~ $cn_re;
      goto set_1252 if $cn_re && $copy =~ $cn_re;
      DEBUG > 8 and print STDERR __LINE__, ": $copy: deprecated\n" if $copy =~ $deprecated_re;
      goto set_1252 if $copy =~ $deprecated_re;

      # Nor are rare code points.  But this is hard to determine.  khw
      # believes that IPA characters and the modifier letters are unlikely to
      # be in pod (and certainly very unlikely to be the in the first line in
      # the pod containing non-ASCII)
      DEBUG > 8 and print STDERR __LINE__, ": $copy: rare\n" if $copy =~ $rare_blocks_re;
      goto set_1252 if $rare_blocks_re && $copy =~ $rare_blocks_re;

      # The first Unicode version included essentially every Latin character
      # in modern usage.  So, a Latin character not in the first release will
      # unlikely be in pod.
      DEBUG > 8 and print STDERR __LINE__, ": $copy: later_latin\n" if $later_latin_re && $copy =~ $later_latin_re;
      goto set_1252 if $later_latin_re && $copy =~ $later_latin_re;

      # On perls that handle script runs, if the UTF-8 interpretation yields
      # a single script, we guess UTF-8, otherwise just having a mixture of
      # scripts is suspicious, so guess CP1252.  We first strip off, as best
      # we can, the ASCII characters that look like they are pod directives,
      # as these would always show as mixed with non-Latin text.
      $copy =~ s/$pod_chars_re//g;

      if ($script_run_re) {
        goto set_utf8 if $copy =~ $script_run_re;
        DEBUG > 8 and print STDERR __LINE__, ":  not script run\n";
        goto set_1252;
      }

      # Even without script runs, but on recent enough perls and Unicodes, we
      # can check if there is a mixture of both Latin and non-Latin.  Again,
      # having a mixture of scripts is suspicious, so assume CP1252

      # If it's all non-Latin, there is no CP1252, as that is Latin
      # characters and punct, etc.
      DEBUG > 8 and print STDERR __LINE__, ": $copy: not latin\n" if $copy !~ $latin_re;
      goto set_utf8 if $copy !~ $latin_re;

      DEBUG > 8 and print STDERR __LINE__, ": $copy: all latin\n" if $copy =~ $every_char_is_latin_re;
      goto set_utf8 if $copy =~ $every_char_is_latin_re;

      DEBUG > 8 and print STDERR __LINE__, ": $copy: mixed\n";

     set_1252:
      DEBUG > 9 and print STDERR __LINE__, ": $copy: is 1252\n";
      $encoding = 'CP1252';
      goto done_set;

     set_utf8:
      DEBUG > 9 and print STDERR __LINE__, ": $copy: is UTF-8\n";
      $encoding = 'UTF-8';

     done_set:
      $self->_handle_encoding_line( "=encoding $encoding" );
      delete $self->{'_processed_encoding'};
      $self->{'_transcoder'} && $self->{'_transcoder'}->($line);

      my ($word) = $line =~ /(\S*$non_ascii_re\S*)/;

      $self->whine(
        $self->{'line_count'},
        "Non-ASCII character seen before =encoding in '$word'. Assuming $encoding"
      );
    }

    DEBUG > 5 and print STDERR "# Parsing line: [$line]\n";

    if(!$self->{'in_pod'}) {
      if($line =~ m/^=([a-zA-Z][a-zA-Z0-9]*)(?:\s|$)/s) {
        if($1 eq 'cut') {
          $self->scream(
            $self->{'line_count'},
            "=cut found outside a pod block.  Skipping to next block."
          );

          ## Before there were errata sections in the world, it was
          ## least-pessimal to abort processing the file.  But now we can
          ## just barrel on thru (but still not start a pod block).
          #splice @_;
          #push @_, undef;

          next;
        } else {
          $self->{'in_pod'} = $self->{'start_of_pod_block'}
                            = $self->{'last_was_blank'}     = 1;
          # And fall thru to the pod-mode block further down
        }
      } else {
        DEBUG > 5 and print STDERR "# It's a code-line.\n";
        $code_handler->(map $_, $line, $self->{'line_count'}, $self)
         if $code_handler;
        # Note: this may cause code to be processed out of order relative
        #  to pods, but in order relative to cuts.

        # Note also that we haven't yet applied the transcoding to $line
        #  by time we call $code_handler!

        if( $line =~ m/^#\s*line\s+(\d+)\s*(?:\s"([^"]+)")?\s*$/ ) {
          # That RE is from perlsyn, section "Plain Old Comments (Not!)",
          #$fname = $2 if defined $2;
          #DEBUG > 1 and defined $2 and print STDERR "# Setting fname to \"$fname\"\n";
          DEBUG > 1 and print STDERR "# Setting nextline to $1\n";
          $self->{'line_count'} = $1 - 1;
        }

        next;
      }
    }

    # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
    # Else we're in pod mode:

    # Apply any necessary transcoding:
    $self->{'_transcoder'} && $self->{'_transcoder'}->($line);

    # HERE WE CATCH =encoding EARLY!
    if( $line =~ m/^=encoding\s+\S+\s*$/s ) {
      next if $self->parse_characters;   # Ignore this line
      $line = $self->_handle_encoding_line( $line );
    }

    if($line =~ m/^=cut/s) {
      # here ends the pod block, and therefore the previous pod para
      DEBUG > 1 and print STDERR "Noting =cut at line ${$self}{'line_count'}\n";
      $self->{'in_pod'} = 0;
      # ++$self->{'pod_para_count'};
      $self->_ponder_paragraph_buffer();
       # by now it's safe to consider the previous paragraph as done.
      DEBUG > 6 and print STDERR "Processing any cut handler, line ${$self}{'line_count'}\n";
      $cut_handler->(map $_, $line, $self->{'line_count'}, $self)
       if $cut_handler;

      # TODO: add to docs: Note: this may cause cuts to be processed out
      #  of order relative to pods, but in order relative to code.

    } elsif($line =~ m/^(\s*)$/s) {  # it's a blank line
      if (defined $1 and $1 =~ /[^\S\r\n]/) { # it's a white line
        $wl_handler->(map $_, $line, $self->{'line_count'}, $self)
          if $wl_handler;
      }

      if(!$self->{'start_of_pod_block'} and @$paras and $paras->[-1][0] eq '~Verbatim') {
        DEBUG > 1 and print STDERR "Saving blank line at line ${$self}{'line_count'}\n";
        push @{$paras->[-1]}, $line;
      }  # otherwise it's not interesting

      if(!$self->{'start_of_pod_block'} and !$self->{'last_was_blank'}) {
        DEBUG > 1 and print STDERR "Noting para ends with blank line at ${$self}{'line_count'}\n";
      }

      $self->{'last_was_blank'} = 1;

    } elsif($self->{'last_was_blank'}) {  # A non-blank line starting a new para...

      if($line =~ m/^(=[a-zA-Z][a-zA-Z0-9]*)(\s+|$)(.*)/s) {
        # THIS IS THE ONE PLACE WHERE WE CONSTRUCT NEW DIRECTIVE OBJECTS
        my $new = [$1, {'start_line' => $self->{'line_count'}}, $3];
        $new->[1]{'~orig_spacer'} = $2 if $2 && $2 ne " ";
         # Note that in "=head1 foo", the WS is lost.
         # Example: ['=head1', {'start_line' => 123}, ' foo']

        ++$self->{'pod_para_count'};

        $self->_ponder_paragraph_buffer();
         # by now it's safe to consider the previous paragraph as done.

        push @$paras, $new; # the new incipient paragraph
        DEBUG > 1 and print STDERR "Starting new ${$paras}[-1][0] para at line ${$self}{'line_count'}\n";

      } elsif($line =~ m/^\s/s) {

        if(!$self->{'start_of_pod_block'} and @$paras and $paras->[-1][0] eq '~Verbatim') {
          DEBUG > 1 and print STDERR "Resuming verbatim para at line ${$self}{'line_count'}\n";
          push @{$paras->[-1]}, $line;
        } else {
          ++$self->{'pod_para_count'};
          $self->_ponder_paragraph_buffer();
           # by now it's safe to consider the previous paragraph as done.
          DEBUG > 1 and print STDERR "Starting verbatim para at line ${$self}{'line_count'}\n";
          push @$paras, ['~Verbatim', {'start_line' => $self->{'line_count'}}, $line];
        }
      } else {
        ++$self->{'pod_para_count'};
        $self->_ponder_paragraph_buffer();
         # by now it's safe to consider the previous paragraph as done.
        push @$paras, ['~Para',  {'start_line' => $self->{'line_count'}}, $line];
        DEBUG > 1 and print STDERR "Starting plain para at line ${$self}{'line_count'}\n";
      }
      $self->{'last_was_blank'} = $self->{'start_of_pod_block'} = 0;

    } else {
      # It's a non-blank line /continuing/ the current para
      if(@$paras) {
        DEBUG > 2 and print STDERR "Line ${$self}{'line_count'} continues current paragraph\n";
        push @{$paras->[-1]}, $line;
      } else {
        # Unexpected case!
        die "Continuing a paragraph but \@\$paras is empty?";
      }
      $self->{'last_was_blank'} = $self->{'start_of_pod_block'} = 0;
    }

  } # ends the big while loop

  DEBUG > 1 and print STDERR (pretty(@$paras), "\n");
  return $self;
}

#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

sub _handle_encoding_line {
  my($self, $line) = @_;

  return if $self->parse_characters;

  # The point of this routine is to set $self->{'_transcoder'} as indicated.

  return $line unless $line =~ m/^=encoding\s+(\S+)\s*$/s;
  DEBUG > 1 and print STDERR "Found an encoding line \"=encoding $1\"\n";

  my $e    = $1;
  my $orig = $e;
  push @{ $self->{'encoding_command_reqs'} }, "=encoding $orig";

  my $enc_error;

  # Cf.   perldoc Encode   and   perldoc Encode::Supported

  require Pod::Simple::Transcode;

  if( $self->{'encoding'} ) {
    my $norm_current = $self->{'encoding'};
    my $norm_e = $e;
    foreach my $that ($norm_current, $norm_e) {
      $that =  lc($that);
      $that =~ s/[-_]//g;
    }
    if($norm_current eq $norm_e) {
      DEBUG > 1 and print STDERR "The '=encoding $orig' line is ",
       "redundant.  ($norm_current eq $norm_e).  Ignoring.\n";
      $enc_error = '';
       # But that doesn't necessarily mean that the earlier one went okay
    } else {
      $enc_error = "Encoding is already set to " . $self->{'encoding'};
      DEBUG > 1 and print STDERR $enc_error;
    }
  } elsif (
    # OK, let's turn on the encoding
    do {
      DEBUG > 1 and print STDERR " Setting encoding to $e\n";
      $self->{'encoding'} = $e;
      1;
    }
    and $e eq 'HACKRAW'
  ) {
    DEBUG and print STDERR " Putting in HACKRAW (no-op) encoding mode.\n";

  } elsif( Pod::Simple::Transcode::->encoding_is_available($e) ) {

    die($enc_error = "WHAT? _transcoder is already set?!")
     if $self->{'_transcoder'};   # should never happen
    require Pod::Simple::Transcode;
    $self->{'_transcoder'} = Pod::Simple::Transcode::->make_transcoder($e);
    eval {
      my @x = ('', "abc", "123");
      $self->{'_transcoder'}->(@x);
    };
    $@ && die( $enc_error =
      "Really unexpected error setting up encoding $e: $@\nAborting"
    );
    $self->{'detected_encoding'} = $e;

  } else {
    my @supported = Pod::Simple::Transcode::->all_encodings;

    # Note unsupported, and complain
    DEBUG and print STDERR " Encoding [$e] is unsupported.",
      "\nSupporteds: @supported\n";
    my $suggestion = '';

    # Look for a near match:
    my $norm = lc($e);
    $norm =~ tr[-_][]d;
    my $n;
    foreach my $enc (@supported) {
      $n = lc($enc);
      $n =~ tr[-_][]d;
      next unless $n eq $norm;
      $suggestion = "  (Maybe \"$e\" should be \"$enc\"?)";
      last;
    }
    my $encmodver = Pod::Simple::Transcode::->encmodver;
    $enc_error = join '' =>
      "This document probably does not appear as it should, because its ",
      "\"=encoding $e\" line calls for an unsupported encoding.",
      $suggestion, "  [$encmodver\'s supported encodings are: @supported]"
    ;

    $self->scream( $self->{'line_count'}, $enc_error );
  }
  push @{ $self->{'encoding_command_statuses'} }, $enc_error;
  if (defined($self->{'_processed_encoding'})) {
    # Double declaration.
    $self->scream( $self->{'line_count'}, 'Cannot have multiple =encoding directives');
  }
  $self->{'_processed_encoding'} = $orig;

  return $line;
}

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

sub _handle_encoding_second_level {
  # By time this is called, the encoding (if well formed) will already
  #  have been acted on.
  my($self, $para) = @_;
  my @x = @$para;
  my $content = join ' ', splice @x, 2;
  $content =~ s/^\s+//s;
  $content =~ s/\s+$//s;

  DEBUG > 2 and print STDERR "Ogling encoding directive: =encoding $content\n";

  if (defined($self->{'_processed_encoding'})) {
    #if($content ne $self->{'_processed_encoding'}) {
    #  Could it happen?
    #}
    delete $self->{'_processed_encoding'};
    # It's already been handled.  Check for errors.
    if(! $self->{'encoding_command_statuses'} ) {
      DEBUG > 2 and print STDERR " CRAZY ERROR: It wasn't really handled?!\n";
    } elsif( $self->{'encoding_command_statuses'}[-1] ) {
      $self->whine( $para->[1]{'start_line'},
        sprintf "Couldn't do %s: %s",
          $self->{'encoding_command_reqs'  }[-1],
          $self->{'encoding_command_statuses'}[-1],
      );
    } else {
      DEBUG > 2 and print STDERR " (Yup, it was successfully handled already.)\n";
    }

  } else {
    # Otherwise it's a syntax error
    $self->whine( $para->[1]{'start_line'},
      "Invalid =encoding syntax: $content"
    );
  }

  return;
}

#~`~`~`~`~`~`~`~`~`~`~`~`~`~`~`~`~`~`~`~`~`~`~`~`~`~`~`~`~`~`~`~`~`~`~`~`~`

{
my $m = -321;   # magic line number

sub _gen_errata {
  my $self = $_[0];
  # Return 0 or more fake-o paragraphs explaining the accumulated
  #  errors on this document.

  return() unless $self->{'errata'} and keys %{$self->{'errata'}};

  my @out;

  foreach my $line (sort {$a <=> $b} keys %{$self->{'errata'}}) {
    push @out,
      ['=item', {'start_line' => $m}, "Around line $line:"],
      map( ['~Para', {'start_line' => $m, '~cooked' => 1},
        #['~Top', {'start_line' => $m},
        $_
        #]
        ],
        @{$self->{'errata'}{$line}}
      )
    ;
  }

  # TODO: report of unknown entities? unrenderable characters?

  unshift @out,
    ['=head1', {'start_line' => $m, 'errata' => 1}, 'POD ERRORS'],
    ['~Para', {'start_line' => $m, '~cooked' => 1, 'errata' => 1},
     "Hey! ",
     ['B', {},
      'The above document had some coding errors, which are explained below:'
     ]
    ],
    ['=over',  {'start_line' => $m, 'errata' => 1}, ''],
  ;

  push @out,
    ['=back',  {'start_line' => $m, 'errata' => 1}, ''],
  ;

  DEBUG and print STDERR "\n<<\n", pretty(\@out), "\n>>\n\n";

  return @out;
}

}

#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

##############################################################################
##
##  stop reading now stop reading now stop reading now stop reading now stop
##
##                         HERE IT BECOMES REALLY SCARY
##
##  stop reading now stop reading now stop reading now stop reading now stop
##
##############################################################################

sub _ponder_paragraph_buffer {

  # Para-token types as found in the buffer.
  #   ~Verbatim, ~Para, ~end, =head1..4, =for, =begin, =end,
  #   =over, =back, =item
  #   and the null =pod (to be complained about if over one line)
  #
  # "~data" paragraphs are something we generate at this level, depending on
  # a currently open =over region

  # Events fired:  Begin and end for:
  #                   directivename (like head1 .. head4), item, extend,
  #                   for (from =begin...=end, =for),
  #                   over-bullet, over-number, over-text, over-block,
  #                   item-bullet, item-number, item-text,
  #                   Document,
  #                   Data, Para, Verbatim
  #                   B, C, longdirname (TODO -- wha?), etc. for all directives
  #

  my $self = $_[0];
  my $paras;
  return unless @{$paras = $self->{'paras'}};
  my $curr_open = ($self->{'curr_open'} ||= []);

  my $scratch;

  DEBUG > 10 and print STDERR "# Paragraph buffer: <<", pretty($paras), ">>\n";

  # We have something in our buffer.  So apparently the document has started.
  unless($self->{'doc_has_started'}) {
    $self->{'doc_has_started'} = 1;

    my $starting_contentless;
    $starting_contentless =
     (
       !@$curr_open
       and @$paras and ! grep $_->[0] ne '~end', @$paras
        # i.e., if the paras is all ~ends
     )
    ;
    DEBUG and print STDERR "# Starting ",
      $starting_contentless ? 'contentless' : 'contentful',
      " document\n"
    ;

    $self->_handle_element_start(
      ($scratch = 'Document'),
      {
        'start_line' => $paras->[0][1]{'start_line'},
        $starting_contentless ? ( 'contentless' => 1 ) : (),
      },
    );
  }

  my($para, $para_type);
  while(@$paras) {

    # If a directive, assume it's legal; subtract below if found not to be
    $seen_legal_directive++ if $paras->[0][0] =~ /^=/;

    last if      @$paras == 1
            and (    $paras->[0][0] eq '=over'
                 or  $paras->[0][0] eq '=item'
                 or ($paras->[0][0] eq '~Verbatim' and $self->{'in_pod'}));
    # Those're the three kinds of paragraphs that require lookahead.
    #   Actually, an "=item Foo" inside an <over type=text> region
    #   and any =item inside an <over type=block> region (rare)
    #   don't require any lookahead, but all others (bullets
    #   and numbers) do.
    # The verbatim is different from the other two, because those might be
    # like:
    #
    #   =item
    #   ...
    #   =cut
    #   ...
    #   =item
    #
    # The =cut here finishes the paragraph but doesn't terminate the =over
    # they should be in. (khw apologizes that he didn't comment at the time
    # why the 'in_pod' works, and no longer remembers why, and doesn't think
    # it is currently worth the effort to re-figure it out.)

# TODO: whinge about many kinds of directives in non-resolving =for regions?
# TODO: many?  like what?  =head1 etc?

    $para = shift @$paras;
    $para_type = $para->[0];

    DEBUG > 1 and print STDERR "Pondering a $para_type paragraph, given the stack: (",
      $self->_dump_curr_open(), ")\n";

    if($para_type eq '=for') {
      next if $self->_ponder_for($para,$curr_open,$paras);

    } elsif($para_type eq '=begin') {
      next if $self->_ponder_begin($para,$curr_open,$paras);

    } elsif($para_type eq '=end') {
      next if $self->_ponder_end($para,$curr_open,$paras);

    } elsif($para_type eq '~end') { # The virtual end-document signal
      next if $self->_ponder_doc_end($para,$curr_open,$paras);
    }


    # ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
    #~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
    if(grep $_->[1]{'~ignore'}, @$curr_open) {
      DEBUG > 1 and
       print STDERR "Skipping $para_type paragraph because in ignore mode.\n";
      next;
    }
    #~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
    # ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~

    if($para_type eq '=pod') {
      $self->_ponder_pod($para,$curr_open,$paras);

    } elsif($para_type eq '=over') {
      next if $self->_ponder_over($para,$curr_open,$paras);

    } elsif($para_type eq '=back') {
      next if $self->_ponder_back($para,$curr_open,$paras);

    } else {

      # All non-magical codes!!!

      # Here we start using $para_type for our own twisted purposes, to
      #  mean how it should get treated, not as what the element name
      #  should be.

      DEBUG > 1 and print STDERR "Pondering non-magical $para_type\n";

      my $i;

      # Enforce some =headN discipline
      if($para_type =~ m/^=head\d$/s
         and ! $self->{'accept_heads_anywhere'}
         and @$curr_open
         and $curr_open->[-1][0] eq '=over'
      ) {
        DEBUG > 2 and print STDERR "'=$para_type' inside an '=over'!\n";
        $self->whine(
          $para->[1]{'start_line'},
          "You forgot a '=back' before '$para_type'"
        );
        unshift @$paras, ['=back', {}, ''], $para;   # close the =over
        next;
      }


      if($para_type eq '=item') {

        my $over;
        unless(@$curr_open and
               $over = (grep { $_->[0] eq '=over' } @$curr_open)[-1]) {
          $self->whine(
            $para->[1]{'start_line'},
            "'=item' outside of any '=over'"
          );
          unshift @$paras,
            ['=over', {'start_line' => $para->[1]{'start_line'}}, ''],
            $para
          ;
          next;
        }


        my $over_type = $over->[1]{'~type'};

        if(!$over_type) {
          # Shouldn't happen1
          die "Typeless over in stack, starting at line "
           . $over->[1]{'start_line'};

        } elsif($over_type eq 'block') {
          unless($curr_open->[-1][1]{'~bitched_about'}) {
            $curr_open->[-1][1]{'~bitched_about'} = 1;
            $self->whine(
              $curr_open->[-1][1]{'start_line'},
              "You can't have =items (as at line "
              . $para->[1]{'start_line'}
              . ") unless the first thing after the =over is an =item"
            );
          }
          # Just turn it into a paragraph and reconsider it
          $para->[0] = '~Para';
          unshift @$paras, $para;
          next;

        } elsif($over_type eq 'text') {
          my $item_type = $self->_get_item_type($para);
            # That kills the content of the item if it's a number or bullet.
          DEBUG and print STDERR " Item is of type ", $para->[0], " under $over_type\n";

          if($item_type eq 'text') {
            # Nothing special needs doing for 'text'
          } elsif($item_type eq 'number' or $item_type eq 'bullet') {
            $self->whine(
              $para->[1]{'start_line'},
              "Expected text after =item, not a $item_type"
            );
            # Undo our clobbering:
            push @$para, $para->[1]{'~orig_content'};
            delete $para->[1]{'number'};
             # Only a PROPER item-number element is allowed
             #  to have a number attribute.
          } else {
            die "Unhandled item type $item_type"; # should never happen
          }

          # =item-text thingies don't need any assimilation, it seems.

        } elsif($over_type eq 'number') {
          my $item_type = $self->_get_item_type($para);
            # That kills the content of the item if it's a number or bullet.
          DEBUG and print STDERR " Item is of type ", $para->[0], " under $over_type\n";

          my $expected_value = ++ $curr_open->[-1][1]{'~counter'};

          if($item_type eq 'bullet') {
            # Hm, it's not numeric.  Correct for this.
            $para->[1]{'number'} = $expected_value;
            $self->whine(
              $para->[1]{'start_line'},
              "Expected '=item $expected_value'"
            );
            push @$para, $para->[1]{'~orig_content'};
              # restore the bullet, blocking the assimilation of next para

          } elsif($item_type eq 'text') {
            # Hm, it's not numeric.  Correct for this.
            $para->[1]{'number'} = $expected_value;
            $self->whine(
              $para->[1]{'start_line'},
              "Expected '=item $expected_value'"
            );
            # Text content will still be there and will block next ~Para

          } elsif($item_type ne 'number') {
            die "Unknown item type $item_type"; # should never happen

          } elsif($expected_value == $para->[1]{'number'}) {
            DEBUG > 1 and print STDERR " Numeric item has the expected value of $expected_value\n";

          } else {
            DEBUG > 1 and print STDERR " Numeric item has ", $para->[1]{'number'},
             " instead of the expected value of $expected_value\n";
            $self->whine(
              $para->[1]{'start_line'},
              "You have '=item " . $para->[1]{'number'} .
              "' instead of the expected '=item $expected_value'"
            );
            $para->[1]{'number'} = $expected_value;  # correcting!!
          }

          if(@$para == 2) {
            # For the cases where we /didn't/ push to @$para
            if($paras->[0][0] eq '~Para') {
              DEBUG and print STDERR "Assimilating following ~Para content into $over_type item\n";
              push @$para, splice @{shift @$paras},2;
            } else {
              DEBUG and print STDERR "Can't assimilate following ", $paras->[0][0], "\n";
              push @$para, '';  # Just so it's not contentless
            }
          }


        } elsif($over_type eq 'bullet') {
          my $item_type = $self->_get_item_type($para);
            # That kills the content of the item if it's a number or bullet.
          DEBUG and print STDERR " Item is of type ", $para->[0], " under $over_type\n";

          if($item_type eq 'bullet') {
            # as expected!

            if( $para->[1]{'~_freaky_para_hack'} ) {
              DEBUG and print STDERR "Accomodating '=item * Foo' tolerance hack.\n";
              push @$para, $para->[1]{'~_freaky_para_hack'};
            }

          } elsif($item_type eq 'number') {
            $self->whine(
              $para->[1]{'start_line'},
              "Expected '=item *'"
            );
            push @$para, $para->[1]{'~orig_content'};
             # and block assimilation of the next paragraph
            delete $para->[1]{'number'};
             # Only a PROPER item-number element is allowed
             #  to have a number attribute.
          } elsif($item_type eq 'text') {
            $self->whine(
              $para->[1]{'start_line'},
              "Expected '=item *'"
            );
             # But doesn't need processing.  But it'll block assimilation
             #  of the next para.
          } else {
            die "Unhandled item type $item_type"; # should never happen
          }

          if(@$para == 2) {
            # For the cases where we /didn't/ push to @$para
            if($paras->[0][0] eq '~Para') {
              DEBUG and print STDERR "Assimilating following ~Para content into $over_type item\n";
              push @$para, splice @{shift @$paras},2;
            } else {
              DEBUG and print STDERR "Can't assimilate following ", $paras->[0][0], "\n";
              push @$para, '';  # Just so it's not contentless
            }
          }

        } else {
          die "Unhandled =over type \"$over_type\"?";
          # Shouldn't happen!
        }

        $para_type = 'Plain';
        $para->[0] .= '-' . $over_type;
        # Whew.  Now fall thru and process it.


      } elsif($para_type eq '=extend') {
        # Well, might as well implement it here.
        $self->_ponder_extend($para);
        next;  # and skip
      } elsif($para_type eq '=encoding') {
        # Not actually acted on here, but we catch errors here.
        $self->_handle_encoding_second_level($para);
        next unless $self->keep_encoding_directive;
        $para_type = 'Plain';
      } elsif($para_type eq '~Verbatim') {
        $para->[0] = 'Verbatim';
        $para_type = '?Verbatim';
      } elsif($para_type eq '~Para') {
        $para->[0] = 'Para';
        $para_type = '?Plain';
      } elsif($para_type eq 'Data') {
        $para->[0] = 'Data';
        $para_type = '?Data';
      } elsif( $para_type =~ s/^=//s
        and defined( $para_type = $self->{'accept_directives'}{$para_type} )
      ) {
        DEBUG > 1 and print STDERR " Pondering known directive ${$para}[0] as $para_type\n";
      } else {
        # An unknown directive!
        $seen_legal_directive--;
        DEBUG > 1 and printf STDERR "Unhandled directive %s (Handled: %s)\n",
         $para->[0], join(' ', sort keys %{$self->{'accept_directives'}} )
        ;
        $self->whine(
          $para->[1]{'start_line'},
          "Unknown directive: $para->[0]"
        );

        # And maybe treat it as text instead of just letting it go?
        next;
      }

      if($para_type =~ s/^\?//s) {
        if(! @$curr_open) {  # usual case
          DEBUG and print STDERR "Treating $para_type paragraph as such because stack is empty.\n";
        } else {
          my @fors = grep $_->[0] eq '=for', @$curr_open;
          DEBUG > 1 and print STDERR "Containing fors: ",
            join(',', map $_->[1]{'target'}, @fors), "\n";

          if(! @fors) {
            DEBUG and print STDERR "Treating $para_type paragraph as such because stack has no =for's\n";

          #} elsif(grep $_->[1]{'~resolve'}, @fors) {
          #} elsif(not grep !$_->[1]{'~resolve'}, @fors) {
          } elsif( $fors[-1][1]{'~resolve'} ) {
            # Look to the immediately containing for

            if($para_type eq 'Data') {
              DEBUG and print STDERR "Treating Data paragraph as Plain/Verbatim because the containing =for ($fors[-1][1]{'target'}) is a resolver\n";
              $para->[0] = 'Para';
              $para_type = 'Plain';
            } else {
              DEBUG and print STDERR "Treating $para_type paragraph as such because the containing =for ($fors[-1][1]{'target'}) is a resolver\n";
            }
          } else {
            DEBUG and print STDERR "Treating $para_type paragraph as Data because the containing =for ($fors[-1][1]{'target'}) is a non-resolver\n";
            $para->[0] = $para_type = 'Data';
          }
        }
      }

      #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      if($para_type eq 'Plain') {
        $self->_ponder_Plain($para);
      } elsif($para_type eq 'Verbatim') {
        $self->_ponder_Verbatim($para);
      } elsif($para_type eq 'Data') {
        $self->_ponder_Data($para);
      } else {
        die "\$para type is $para_type -- how did that happen?";
        # Shouldn't happen.
      }

      #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      $para->[0] =~ s/^[~=]//s;

      DEBUG and print STDERR "\n", pretty($para), "\n";

      # traverse the treelet (which might well be just one string scalar)
      $self->{'content_seen'} ||= 1 if   $seen_legal_directive
                                    && ! $self->{'~tried_gen_errata'};
      $self->_traverse_treelet_bit(@$para);
    }
  }

  return;
}

###########################################################################
# The sub-ponderers...



sub _ponder_for {
  my ($self,$para,$curr_open,$paras) = @_;

  # Fake it out as a begin/end
  my $target;

  if(grep $_->[1]{'~ignore'}, @$curr_open) {
    DEBUG > 1 and print STDERR "Ignoring ignorable =for\n";
    return 1;
  }

  for(my $i = 2; $i < @$para; ++$i) {
    if($para->[$i] =~ s/^\s*(\S+)\s*//s) {
      $target = $1;
      last;
    }
  }
  unless(defined $target) {
    $self->whine(
      $para->[1]{'start_line'},
      "=for without a target?"
    );
    return 1;
  }
  DEBUG > 1 and
   print STDERR "Faking out a =for $target as a =begin $target / =end $target\n";

  $para->[0] = 'Data';

  unshift @$paras,
    ['=begin',
      {'start_line' => $para->[1]{'start_line'}, '~really' => '=for'},
      $target,
    ],
    $para,
    ['=end',
      {'start_line' => $para->[1]{'start_line'}, '~really' => '=for'},
      $target,
    ],
  ;

  return 1;
}

sub _ponder_begin {
  my ($self,$para,$curr_open,$paras) = @_;
  my $content = join ' ', splice @$para, 2;
  $content =~ s/^\s+//s;
  $content =~ s/\s+$//s;
  unless(length($content)) {
    $self->whine(
      $para->[1]{'start_line'},
      "=begin without a target?"
    );
    DEBUG and print STDERR "Ignoring targetless =begin\n";
    return 1;
  }

  my ($target, $title) = $content =~ m/^(\S+)\s*(.*)$/;
  $para->[1]{'title'} = $title if ($title);
  $para->[1]{'target'} = $target;  # without any ':'
  $content = $target; # strip off the title

  $content =~ s/^:!/!:/s;
  my $neg;  # whether this is a negation-match
  $neg = 1        if $content =~ s/^!//s;
  my $to_resolve;  # whether to process formatting codes
  $to_resolve = 1 if $content =~ s/^://s;

  my $dont_ignore; # whether this target matches us

  foreach my $target_name (
    split(',', $content, -1),
    $neg ? () : '*'
  ) {
    DEBUG > 2 and
     print STDERR " Considering whether =begin $content matches $target_name\n";
    next unless $self->{'accept_targets'}{$target_name};

    DEBUG > 2 and
     print STDERR "  It DOES match the acceptable target $target_name!\n";
    $to_resolve = 1
      if $self->{'accept_targets'}{$target_name} eq 'force_resolve';
    $dont_ignore = 1;
    $para->[1]{'target_matching'} = $target_name;
    last; # stop looking at other target names
  }

  if($neg) {
    if( $dont_ignore ) {
      $dont_ignore = '';
      delete $para->[1]{'target_matching'};
      DEBUG > 2 and print STDERR " But the leading ! means that this is a NON-match!\n";
    } else {
      $dont_ignore = 1;
      $para->[1]{'target_matching'} = '!';
      DEBUG > 2 and print STDERR " But the leading ! means that this IS a match!\n";
    }
  }

  $para->[0] = '=for';  # Just what we happen to call these, internally
  $para->[1]{'~really'} ||= '=begin';
  $para->[1]{'~ignore'}   = (! $dont_ignore) || 0;
  $para->[1]{'~resolve'}  = $to_resolve || 0;

  DEBUG > 1 and print STDERR " Making note to ", $dont_ignore ? 'not ' : '',
    "ignore contents of this region\n";
  DEBUG > 1 and $dont_ignore and print STDERR " Making note to treat contents as ",
    ($to_resolve ? 'verbatim/plain' : 'data'), " paragraphs\n";
  DEBUG > 1 and print STDERR " (Stack now: ", $self->_dump_curr_open(), ")\n";

  push @$curr_open, $para;
  if(!$dont_ignore or scalar grep $_->[1]{'~ignore'}, @$curr_open) {
    DEBUG > 1 and print STDERR "Ignoring ignorable =begin\n";
  } else {
    $self->{'content_seen'} ||= 1 unless $self->{'~tried_gen_errata'};
    $self->_handle_element_start((my $scratch='for'), $para->[1]);
  }

  return 1;
}

sub _ponder_end {
  my ($self,$para,$curr_open,$paras) = @_;
  my $content = join ' ', splice @$para, 2;
  $content =~ s/^\s+//s;
  $content =~ s/\s+$//s;
  DEBUG and print STDERR "Ogling '=end $content' directive\n";

  unless(length($content)) {
    $self->whine(
      $para->[1]{'start_line'},
      "'=end' without a target?" . (
        ( @$curr_open and $curr_open->[-1][0] eq '=for' )
        ? ( " (Should be \"=end " . $curr_open->[-1][1]{'target'} . '")' )
        : ''
      )
    );
    DEBUG and print STDERR "Ignoring targetless =end\n";
    return 1;
  }

  unless($content =~ m/^\S+$/) {  # i.e., unless it's one word
    $self->whine(
      $para->[1]{'start_line'},
      "'=end $content' is invalid.  (Stack: "
      . $self->_dump_curr_open() . ')'
    );
    DEBUG and print STDERR "Ignoring mistargetted =end $content\n";
    return 1;
  }

  unless(@$curr_open and $curr_open->[-1][0] eq '=for') {
    $self->whine(
      $para->[1]{'start_line'},
      "=end $content without matching =begin.  (Stack: "
      . $self->_dump_curr_open() . ')'
    );
    DEBUG and print STDERR "Ignoring mistargetted =end $content\n";
    return 1;
  }

  unless($content eq $curr_open->[-1][1]{'target'}) {
    $self->whine(
      $para->[1]{'start_line'},
      "=end $content doesn't match =begin "
      . $curr_open->[-1][1]{'target'}
      . ".  (Stack: "
      . $self->_dump_curr_open() . ')'
    );
    DEBUG and print STDERR "Ignoring mistargetted =end $content at line $para->[1]{'start_line'}\n";
    return 1;
  }

  # Else it's okay to close...
  if(grep $_->[1]{'~ignore'}, @$curr_open) {
    DEBUG > 1 and print STDERR "Not firing any event for this =end $content because in an ignored region\n";
    # And that may be because of this to-be-closed =for region, or some
    #  other one, but it doesn't matter.
  } else {
    $curr_open->[-1][1]{'start_line'} = $para->[1]{'start_line'};
      # what's that for?

    $self->{'content_seen'} ||= 1 unless $self->{'~tried_gen_errata'};
    $self->_handle_element_end( my $scratch = 'for', $para->[1]);
  }
  DEBUG > 1 and print STDERR "Popping $curr_open->[-1][0] $curr_open->[-1][1]{'target'} because of =end $content\n";
  pop @$curr_open;

  return 1;
}

sub _ponder_doc_end {
  my ($self,$para,$curr_open,$paras) = @_;
  if(@$curr_open) { # Deal with things left open
    DEBUG and print STDERR "Stack is nonempty at end-document: (",
      $self->_dump_curr_open(), ")\n";

    DEBUG > 9 and print STDERR "Stack: ", pretty($curr_open), "\n";
    unshift @$paras, $self->_closers_for_all_curr_open;
    # Make sure there is exactly one ~end in the parastack, at the end:
    @$paras = grep $_->[0] ne '~end', @$paras;
    push @$paras, $para, $para;
     # We need two -- once for the next cycle where we
     #  generate errata, and then another to be at the end
     #  when that loop back around to process the errata.
    return 1;

  } else {
    DEBUG and print STDERR "Okay, stack is empty now.\n";
  }

  # Try generating errata section, if applicable
  unless($self->{'~tried_gen_errata'}) {
    $self->{'~tried_gen_errata'} = 1;
    my @extras = $self->_gen_errata();
    if(@extras) {
      unshift @$paras, @extras;
      DEBUG and print STDERR "Generated errata... relooping...\n";
      return 1;  # I.e., loop around again to process these fake-o paragraphs
    }
  }

  splice @$paras; # Well, that's that for this paragraph buffer.
  DEBUG and print STDERR "Throwing end-document event.\n";

  $self->_handle_element_end( my $scratch = 'Document' );
  return 1; # Hasta la byebye
}

sub _ponder_pod {
  my ($self,$para,$curr_open,$paras) = @_;
  $self->whine(
    $para->[1]{'start_line'},
    "=pod directives shouldn't be over one line long!  Ignoring all "
     . (@$para - 2) . " lines of content"
  ) if @$para > 3;

  # Content ignored unless 'pod_handler' is set
  if (my $pod_handler = $self->{'pod_handler'}) {
      my ($line_num, $line) = map $_, $para->[1]{'start_line'}, $para->[2];
      $line = $line eq '' ? "=pod" : "=pod $line"; # imitate cut_handler output
      $pod_handler->($line, $line_num, $self);
  }

  # The surrounding methods set content_seen, so let us remain consistent.
  # I do not know why it was not here before -- should it not be here?
  # $self->{'content_seen'} ||= 1 unless $self->{'~tried_gen_errata'};

  return;
}

sub _ponder_over {
  my ($self,$para,$curr_open,$paras) = @_;
  return 1 unless @$paras;
  my $list_type;

  if($paras->[0][0] eq '=item') { # most common case
    $list_type = $self->_get_initial_item_type($paras->[0]);

  } elsif($paras->[0][0] eq '=back') {
    # Ignore empty lists by default
    if ($self->{'parse_empty_lists'}) {
      $list_type = 'empty';
    } else {
      shift @$paras;
      return 1;
    }
  } elsif($paras->[0][0] eq '~end') {
    $self->whine(
      $para->[1]{'start_line'},
      "=over is the last thing in the document?!"
    );
    return 1; # But feh, ignore it.
  } else {
    $list_type = 'block';
  }
  $para->[1]{'~type'} = $list_type;
  push @$curr_open, $para;
   # yes, we reuse the paragraph as a stack item

  my $content = join ' ', splice @$para, 2;
  $para->[1]{'~orig_content'} = $content;
  my $overness;
  if($content =~ m/^\s*$/s) {
    $para->[1]{'indent'} = 4;
  } elsif($content =~ m/^\s*((?:\d*\.)?\d+)\s*$/s) {
    no integer;
    $para->[1]{'indent'} = $1;
    if($1 == 0) {
      $self->whine(
        $para->[1]{'start_line'},
        "Can't have a 0 in =over $content"
      );
      $para->[1]{'indent'} = 4;
    }
  } else {
    $self->whine(
      $para->[1]{'start_line'},
      "=over should be: '=over' or '=over positive_number'"
    );
    $para->[1]{'indent'} = 4;
  }
  DEBUG > 1 and print STDERR "=over found of type $list_type\n";

  $self->{'content_seen'} ||= 1 unless $self->{'~tried_gen_errata'};
  $self->_handle_element_start((my $scratch = 'over-' . $list_type), $para->[1]);

  return;
}

sub _ponder_back {
  my ($self,$para,$curr_open,$paras) = @_;
  # TODO: fire off </item-number> or </item-bullet> or </item-text> ??

  my $content = join ' ', splice @$para, 2;
  if($content =~ m/\S/) {
    $self->whine(
      $para->[1]{'start_line'},
      "=back doesn't take any parameters, but you said =back $content"
    );
  }

  if(@$curr_open and $curr_open->[-1][0] eq '=over') {
    DEBUG > 1 and print STDERR "=back happily closes matching =over\n";
    # Expected case: we're closing the most recently opened thing
    #my $over = pop @$curr_open;
    $self->{'content_seen'} ||= 1 unless $self->{'~tried_gen_errata'};
    $self->_handle_element_end( my $scratch =
      'over-' . ( (pop @$curr_open)->[1]{'~type'} ), $para->[1]
    );
  } else {
    DEBUG > 1 and print STDERR "=back found without a matching =over.  Stack: (",
        join(', ', map $_->[0], @$curr_open), ").\n";
    $self->whine(
      $para->[1]{'start_line'},
      '=back without =over'
    );
    return 1; # and ignore it
  }
}

sub _ponder_item {
  my ($self,$para,$curr_open,$paras) = @_;
  my $over;
  unless(@$curr_open and
         $over = (grep { $_->[0] eq '=over' } @$curr_open)[-1]) {
    $self->whine(
      $para->[1]{'start_line'},
      "'=item' outside of any '=over'"
    );
    unshift @$paras,
      ['=over', {'start_line' => $para->[1]{'start_line'}}, ''],
      $para
    ;
    return 1;
  }


  my $over_type = $over->[1]{'~type'};

  if(!$over_type) {
    # Shouldn't happen1
    die "Typeless over in stack, starting at line "
     . $over->[1]{'start_line'};

  } elsif($over_type eq 'block') {
    unless($curr_open->[-1][1]{'~bitched_about'}) {
      $curr_open->[-1][1]{'~bitched_about'} = 1;
      $self->whine(
        $curr_open->[-1][1]{'start_line'},
        "You can't have =items (as at line "
        . $para->[1]{'start_line'}
        . ") unless the first thing after the =over is an =item"
      );
    }
    # Just turn it into a paragraph and reconsider it
    $para->[0] = '~Para';
    unshift @$paras, $para;
    return 1;

  } elsif($over_type eq 'text') {
    my $item_type = $self->_get_item_type($para);
      # That kills the content of the item if it's a number or bullet.
    DEBUG and print STDERR " Item is of type ", $para->[0], " under $over_type\n";

    if($item_type eq 'text') {
      # Nothing special needs doing for 'text'
    } elsif($item_type eq 'number' or $item_type eq 'bullet') {
      $self->whine(
          $para->[1]{'start_line'},
          "Expected text after =item, not a $item_type"
      );
      # Undo our clobbering:
      push @$para, $para->[1]{'~orig_content'};
      delete $para->[1]{'number'};
       # Only a PROPER item-number element is allowed
       #  to have a number attribute.
    } else {
      die "Unhandled item type $item_type"; # should never happen
    }

    # =item-text thingies don't need any assimilation, it seems.

  } elsif($over_type eq 'number') {
    my $item_type = $self->_get_item_type($para);
      # That kills the content of the item if it's a number or bullet.
    DEBUG and print STDERR " Item is of type ", $para->[0], " under $over_type\n";

    my $expected_value = ++ $curr_open->[-1][1]{'~counter'};

    if($item_type eq 'bullet') {
      # Hm, it's not numeric.  Correct for this.
      $para->[1]{'number'} = $expected_value;
      $self->whine(
        $para->[1]{'start_line'},
        "Expected '=item $expected_value'"
      );
      push @$para, $para->[1]{'~orig_content'};
        # restore the bullet, blocking the assimilation of next para

    } elsif($item_type eq 'text') {
      # Hm, it's not numeric.  Correct for this.
      $para->[1]{'number'} = $expected_value;
      $self->whine(
        $para->[1]{'start_line'},
        "Expected '=item $expected_value'"
      );
      # Text content will still be there and will block next ~Para

    } elsif($item_type ne 'number') {
      die "Unknown item type $item_type"; # should never happen

    } elsif($expected_value == $para->[1]{'number'}) {
      DEBUG > 1 and print STDERR " Numeric item has the expected value of $expected_value\n";

    } else {
      DEBUG > 1 and print STDERR " Numeric item has ", $para->[1]{'number'},
       " instead of the expected value of $expected_value\n";
      $self->whine(
        $para->[1]{'start_line'},
        "You have '=item " . $para->[1]{'number'} .
        "' instead of the expected '=item $expected_value'"
      );
      $para->[1]{'number'} = $expected_value;  # correcting!!
    }

    if(@$para == 2) {
      # For the cases where we /didn't/ push to @$para
      if($paras->[0][0] eq '~Para') {
        DEBUG and print STDERR "Assimilating following ~Para content into $over_type item\n";
        push @$para, splice @{shift @$paras},2;
      } else {
        DEBUG and print STDERR "Can't assimilate following ", $paras->[0][0], "\n";
        push @$para, '';  # Just so it's not contentless
      }
    }


  } elsif($over_type eq 'bullet') {
    my $item_type = $self->_get_item_type($para);
      # That kills the content of the item if it's a number or bullet.
    DEBUG and print STDERR " Item is of type ", $para->[0], " under $over_type\n";

    if($item_type eq 'bullet') {
      # as expected!

      if( $para->[1]{'~_freaky_para_hack'} ) {
        DEBUG and print STDERR "Accomodating '=item * Foo' tolerance hack.\n";
        push @$para, $para->[1]{'~_freaky_para_hack'};
      }

    } elsif($item_type eq 'number') {
      $self->whine(
        $para->[1]{'start_line'},
        "Expected '=item *'"
      );
      push @$para, $para->[1]{'~orig_content'};
       # and block assimilation of the next paragraph
      delete $para->[1]{'number'};
       # Only a PROPER item-number element is allowed
       #  to have a number attribute.
    } elsif($item_type eq 'text') {
      $self->whine(
        $para->[1]{'start_line'},
        "Expected '=item *'"
      );
       # But doesn't need processing.  But it'll block assimilation
       #  of the next para.
    } else {
      die "Unhandled item type $item_type"; # should never happen
    }

    if(@$para == 2) {
      # For the cases where we /didn't/ push to @$para
      if($paras->[0][0] eq '~Para') {
        DEBUG and print STDERR "Assimilating following ~Para content into $over_type item\n";
        push @$para, splice @{shift @$paras},2;
      } else {
        DEBUG and print STDERR "Can't assimilate following ", $paras->[0][0], "\n";
        push @$para, '';  # Just so it's not contentless
      }
    }

  } else {
    die "Unhandled =over type \"$over_type\"?";
    # Shouldn't happen!
  }
  $para->[0] .= '-' . $over_type;

  return;
}

sub _ponder_Plain {
  my ($self,$para) = @_;
  DEBUG and print STDERR " giving plain treatment...\n";
  unless( @$para == 2 or ( @$para == 3 and $para->[2] eq '' )
    or $para->[1]{'~cooked'}
  ) {
    push @$para,
    @{$self->_make_treelet(
      join("\n", splice(@$para, 2)),
      $para->[1]{'start_line'}
    )};
  }
  # Empty paragraphs don't need a treelet for any reason I can see.
  # And precooked paragraphs already have a treelet.
  return;
}

sub _ponder_Verbatim {
  my ($self,$para) = @_;
  DEBUG and print STDERR " giving verbatim treatment...\n";

  $para->[1]{'xml:space'} = 'preserve';

  unless ($self->{'_output_is_for_JustPod'}) {
    # Fix illegal settings for expand_verbatim_tabs()
    # This is because this module doesn't do input error checking, but khw
    # doesn't want to add yet another instance of that.
    $self->expand_verbatim_tabs(8)
                            if ! defined $self->expand_verbatim_tabs()
                            ||   $self->expand_verbatim_tabs() =~ /\D/;

    my $indent = $self->strip_verbatim_indent;
    if ($indent && ref $indent eq 'CODE') {
        my @shifted = (shift @{$para}, shift @{$para});
        $indent = $indent->($para);
        unshift @{$para}, @shifted;
    }

    for(my $i = 2; $i < @$para; $i++) {
      foreach my $line ($para->[$i]) { # just for aliasing
        # Strip indentation.
        $line =~ s/^\Q$indent// if $indent;
        next unless $self->expand_verbatim_tabs;

            # This is commented out because of github issue #85, and the
            # current maintainers don't know why it was there in the first
            # place.
            #&& !($self->{accept_codes} && $self->{accept_codes}{VerbatimFormatted});
        while( $line =~
          # Sort of adapted from Text::Tabs.
          s/^([^\t]*)(\t+)/$1.(" " x ((length($2)
                                       * $self->expand_verbatim_tabs)
                                       -(length($1)&7)))/e
        ) {}

        # TODO: whinge about (or otherwise treat) unindented or overlong lines

      }
    }
  }

  # Now the VerbatimFormatted hoodoo...
  if( $self->{'accept_codes'} and
      $self->{'accept_codes'}{'VerbatimFormatted'}
  ) {
    while(@$para > 3 and $para->[-1] !~ m/\S/) { pop @$para }
     # Kill any number of terminal newlines
    $self->_verbatim_format($para);
  } elsif ($self->{'codes_in_verbatim'}) {
    push @$para,
    @{$self->_make_treelet(
      join("\n", splice(@$para, 2)),
      $para->[1]{'start_line'}, $para->[1]{'xml:space'}
    )};
    $para->[-1] =~ s/\n+$//s; # Kill any number of terminal newlines
  } else {
    push @$para, join "\n", splice(@$para, 2) if @$para > 3;
    $para->[-1] =~ s/\n+$//s; # Kill any number of terminal newlines
  }
  return;
}

sub _ponder_Data {
  my ($self,$para) = @_;
  DEBUG and print STDERR " giving data treatment...\n";
  $para->[1]{'xml:space'} = 'preserve';
  push @$para, join "\n", splice(@$para, 2) if @$para > 3;
  return;
}




###########################################################################

sub _traverse_treelet_bit {  # for use only by the routine above
  my($self, $name) = splice @_,0,2;

  my $scratch;
  $self->_handle_element_start(($scratch=$name), shift @_);

  while (@_) {
    my $x = shift;
    if (ref($x)) {
      &_traverse_treelet_bit($self, @$x);
    } else {
      $x .= shift while @_ && !ref($_[0]);
      $self->_handle_text($x);
    }
  }

  $self->_handle_element_end($scratch=$name);
  return;
}

#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

sub _closers_for_all_curr_open {
  my $self = $_[0];
  my @closers;
  foreach my $still_open (@{  $self->{'curr_open'} || return  }) {
    my @copy = @$still_open;
    $copy[1] = {%{ $copy[1] }};
    #$copy[1]{'start_line'} = -1;
    if($copy[0] eq '=for') {
      $copy[0] = '=end';
    } elsif($copy[0] eq '=over') {
      $self->whine(
        $still_open->[1]{start_line} ,
        "=over without closing =back"
      );

      $copy[0] = '=back';
    } else {
      die "I don't know how to auto-close an open $copy[0] region";
    }

    unless( @copy > 2 ) {
      push @copy, $copy[1]{'target'};
      $copy[-1] = '' unless defined $copy[-1];
       # since =over's don't have targets
    }

    $copy[1]{'fake-closer'} = 1;

    DEBUG and print STDERR "Queuing up fake-o event: ", pretty(\@copy), "\n";
    unshift @closers, \@copy;
  }
  return @closers;
}

#--------------------------------------------------------------------------

sub _verbatim_format {
  my($it, $p) = @_;

  my $formatting;

  for(my $i = 2; $i < @$p; $i++) { # work backwards over the lines
    DEBUG and print STDERR "_verbatim_format appends a newline to $i: $p->[$i]\n";
    $p->[$i] .= "\n";
     # Unlike with simple Verbatim blocks, we don't end up just doing
     # a join("\n", ...) on the contents, so we have to append a
     # newline to every line, and then nix the last one later.
  }

  if( DEBUG > 4 ) {
    print STDERR "<<\n";
    for(my $i = $#$p; $i >= 2; $i--) { # work backwards over the lines
      print STDERR "_verbatim_format $i: $p->[$i]";
    }
    print STDERR ">>\n";
  }

  for(my $i = $#$p; $i > 2; $i--) {
    # work backwards over the lines, except the first (#2)

    #next unless $p->[$i]   =~ m{^#:([ \^\/\%]*)\n?$}s
    #        and $p->[$i-1] !~ m{^#:[ \^\/\%]*\n?$}s;
     # look at a formatty line preceding a nonformatty one
    DEBUG > 5 and print STDERR "Scrutinizing line $i: $$p[$i]\n";
    if($p->[$i]   =~ m{^#:([ \^\/\%]*)\n?$}s) {
      DEBUG > 5 and print STDERR "  It's a formatty line.  ",
       "Peeking at previous line ", $i-1, ": $$p[$i-1]: \n";

      if( $p->[$i-1] =~ m{^#:[ \^\/\%]*\n?$}s ) {
        DEBUG > 5 and print STDERR "  Previous line is formatty!  Skipping this one.\n";
        next;
      } else {
        DEBUG > 5 and print STDERR "  Previous line is non-formatty!  Yay!\n";
      }
    } else {
      DEBUG > 5 and print STDERR "  It's not a formatty line.  Ignoring\n";
      next;
    }

    # A formatty line has to have #: in the first two columns, and uses
    # "^" to mean bold, "/" to mean underline, and "%" to mean bold italic.
    # Example:
    #   What do you want?  i like pie. [or whatever]
    # #:^^^^^^^^^^^^^^^^^              /////////////


    DEBUG > 4 and print STDERR "_verbatim_format considers:\n<$p->[$i-1]>\n<$p->[$i]>\n";

    $formatting = '  ' . $1;
    $formatting =~ s/\s+$//s; # nix trailing whitespace
    unless(length $formatting and $p->[$i-1] =~ m/\S/) { # no-op
      splice @$p,$i,1; # remove this line
      $i--; # don't consider next line
      next;
    }

    if( length($formatting) >= length($p->[$i-1]) ) {
      $formatting = substr($formatting, 0, length($p->[$i-1]) - 1) . ' ';
    } else {
      $formatting .= ' ' x (length($p->[$i-1]) - length($formatting));
    }
    # Make $formatting and the previous line be exactly the same length,
    # with $formatting having a " " as the last character.

    DEBUG > 4 and print STDERR "Formatting <$formatting>    on <", $p->[$i-1], ">\n";


    my @new_line;
    while( $formatting =~ m{\G(( +)|(\^+)|(\/+)|(\%+))}g ) {
      #print STDERR "Format matches $1\n";

      if($2) {
        #print STDERR "SKIPPING <$2>\n";
        push @new_line,
          substr($p->[$i-1], pos($formatting)-length($1), length($1));
      } else {
        #print STDERR "SNARING $+\n";
        push @new_line, [
          (
            $3 ? 'VerbatimB'  :
            $4 ? 'VerbatimI'  :
            $5 ? 'VerbatimBI' : die("Should never get called")
          ), {},
          substr($p->[$i-1], pos($formatting)-length($1), length($1))
        ];
        #print STDERR "Formatting <$new_line[-1][-1]> as $new_line[-1][0]\n";
      }
    }
    my @nixed =
      splice @$p, $i-1, 2, @new_line; # replace myself and the next line
    DEBUG > 10 and print STDERR "Nixed count: ", scalar(@nixed), "\n";

    DEBUG > 6 and print STDERR "New version of the above line is these tokens (",
      scalar(@new_line), "):",
      map( ref($_)?"<@$_> ":"<$_>", @new_line ), "\n";
    $i--; # So the next line we scrutinize is the line before the one
          #  that we just went and formatted
  }

  $p->[0] = 'VerbatimFormatted';

  # Collapse adjacent text nodes, just for kicks.
  for( my $i = 2; $i > $#$p; $i++ ) { # work forwards over the tokens except for the last
    if( !ref($p->[$i]) and !ref($p->[$i + 1]) ) {
      DEBUG > 5 and print STDERR "_verbatim_format merges {$p->[$i]} and {$p->[$i+1]}\n";
      $p->[$i] .= splice @$p, $i+1, 1; # merge
      --$i;  # and back up
    }
  }

  # Now look for the last text token, and remove the terminal newline
  for( my $i = $#$p; $i >= 2; $i-- ) {
    # work backwards over the tokens, even the first
    if( !ref($p->[$i]) ) {
      if($p->[$i] =~ s/\n$//s) {
        DEBUG > 5 and print STDERR "_verbatim_format killed the terminal newline on #$i: {$p->[$i]}, after {$p->[$i-1]}\n";
      } else {
        DEBUG > 5 and print STDERR
         "No terminal newline on #$i: {$p->[$i]}, after {$p->[$i-1]} !?\n";
      }
      last; # we only want the next one
    }
  }

  return;
}


#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@


sub _treelet_from_formatting_codes {
  # Given a paragraph, returns a treelet.  Full of scary tokenizing code.
  #  Like [ '~Top', {'start_line' => $start_line},
  #            "I like ",
  #            [ 'B', {}, "pie" ],
  #            "!"
  #       ]
  # This illustrates the general format of a treelet.  It is an array:
  #     [0]       is a scalar indicating its type.  In the example above, the
  #               types are '~Top' and 'B'
  #     [1]       is a hash of various flags about it, possibly empty
  #     [2] - [N] are an ordered list of the subcomponents of the treelet.
  #               Scalars are literal text, refs are sub-treelets, to
  #               arbitrary levels.  Stringifying a treelet will recursively
  #               stringify the sub-treelets, concatentating everything
  #               together to form the exact text of the treelet.

  my($self, $para, $start_line, $preserve_space) = @_;

  my $treelet = ['~Top', {'start_line' => $start_line},];

  unless ($preserve_space || $self->{'preserve_whitespace'}) {
    $para =~ s/\s+/ /g; # collapse and trim all whitespace first.
    $para =~ s/ $//;
    $para =~ s/^ //;
  }

  # Only apparent problem the above code is that N<<  >> turns into
  # N<< >>.  But then, word wrapping does that too!  So don't do that!


  # As a Start-code is encountered, the number of opening bracket '<'
  # characters minus 1 is pushed onto @stack (so 0 means a single bracket,
  # etc).  When closing brackets are found in the text, at least this number
  # (plus the 1) will be required to mean the Start-code is terminated.  When
  # those are found, @stack is popped.
  my @stack;

  my @lineage = ($treelet);
  my $raw = ''; # raw content of L<> fcode before splitting/processing
    # XXX 'raw' is not 100% accurate: all surrounding whitespace is condensed
    # into just 1 ' '. Is this the regex's doing or 'raw's?  Answer is it's
    # the 'collapse and trim all whitespace first' lines just above.
  my $inL = 0;

  DEBUG > 4 and print STDERR "Paragraph:\n$para\n\n";

  # Here begins our frightening tokenizer RE.  The following regex matches
  # text in four main parts:
  #
  #  * Start-codes.  The first alternative matches C< or C<<, the latter
  #    followed by some whitespace.  $1 will hold the entire start code
  #    (including any space following a multiple-angle-bracket delimiter),
  #    and $2 will hold only the additional brackets past the first in a
  #    multiple-bracket delimiter.  length($2) + 1 will be the number of
  #    closing brackets we have to find.
  #
  #  * Closing brackets.  Match some amount of whitespace followed by
  #    multiple close brackets.  The logic to see if this closes anything
  #    is down below.  Note that in order to parse C<<  >> correctly, we
  #    have to use look-behind (?<=\s\s), since the match of the starting
  #    code will have consumed the whitespace.
  #
  #  * A single closing bracket, to close a simple code like C<>.
  #
  #  * Something that isn't a start or end code.  We have to be careful
  #    about accepting whitespace, since perlpodspec says that any whitespace
  #    before a multiple-bracket closing delimiter should be ignored.
  #
  while($para =~
    m/\G
      (?:
        # Match starting codes, including the whitespace following a
        # multiple-delimiter start code.  $1 gets the whole start code and
        # $2 gets all but one of the <s in the multiple-bracket case.
        ([A-Z]<(?:(<+)\s+)?)
        |
        # Match multiple-bracket end codes.  $3 gets the whitespace that
        # should be discarded before an end bracket but kept in other cases
        # and $4 gets the end brackets themselves.  ($3 can be empty if the
        # construct is empty, like C<<  >>, and all the white-space has been
        # gobbled up already, considered to be space after the opening
        # bracket.  In this case we use look-behind to verify that there are
        # at least 2 spaces in a row before the ">".)
        (\s+|(?<=\s\s))(>{2,})
        |
        (\s?>)          # $5: simple end-codes
        |
        (               # $6: stuff containing no start-codes or end-codes
          (?:
            [^A-Z\s>]
            |
            (?:
              [A-Z](?!<)
            )
            |
            # whitespace is ok, but we don't want to eat the whitespace before
            # a multiple-bracket end code.
            # NOTE: we may still have problems with e.g. S<<    >>
            (?:
              \s(?!\s*>{2,})
            )
          )+
        )
      )
    /xgo
  ) {
    DEBUG > 4 and print STDERR "\nParagraphic tokenstack = (@stack)\n";
    if(defined $1) {
      my $bracket_count;    # How many '<<<' in a row this has.  Needed for
                            # Pod::Simple::JustPod
      if(defined $2) {
        DEBUG > 3 and print STDERR "Found complex start-text code \"$1\"\n";
        $bracket_count = length($2) + 1;
        push @stack, $bracket_count; # length of the necessary complex
                                     # end-code string
      } else {
        DEBUG > 3 and print STDERR "Found simple start-text code \"$1\"\n";
        push @stack, 0;  # signal that we're looking for simple
        $bracket_count = 1;
      }
      my $code = substr($1,0,1);
      if ('L' eq $code) {
        if ($inL) {
            $raw .= $1;
            $self->scream( $start_line,
                           'Nested L<> are illegal.  Pretending inner one is '
                         . 'X<...> so can continue looking for other errors.');
            $code = "X";
        }
        else {
            $raw = ""; # reset raw content accumulator
            $inL = @stack;
        }
      } else {
        $raw .= $1 if $inL;
      }
      push @lineage, [ $code, {}, ];  # new node object

      # Tell Pod::Simple::JustPod how many brackets there were, but to save
      # space, not in the most usual case of there was just 1.  It can be
      # inferred by the absence of this element.  Similarly, if there is more
      # than one bracket, extract the white space between the final bracket
      # and the real beginning of the interior.  Save that if it isn't just a
      # single space
      if ($self->{'_output_is_for_JustPod'} && $bracket_count > 1) {
        $lineage[-1][1]{'~bracket_count'} = $bracket_count;
        my $lspacer = substr($1, 1 + $bracket_count);
        $lineage[-1][1]{'~lspacer'} = $lspacer if $lspacer ne " ";
      }
      push @{ $lineage[-2] }, $lineage[-1];
    } elsif(defined $4) {
      DEBUG > 3 and print STDERR "Found apparent complex end-text code \"$3$4\"\n";
      # This is where it gets messy...
      if(! @stack) {
        # We saw " >>>>" but needed nothing.  This is ALL just stuff then.
        DEBUG > 4 and print STDERR " But it's really just stuff.\n";
        push @{ $lineage[-1] }, $3, $4;
        next;
      } elsif(!$stack[-1]) {
        # We saw " >>>>" but needed only ">".  Back pos up.
        DEBUG > 4 and print STDERR " And that's more than we needed to close simple.\n";
        push @{ $lineage[-1] }, $3; # That was a for-real space, too.
        pos($para) = pos($para) - length($4) + 1;
      } elsif($stack[-1] == length($4)) {
        # We found " >>>>", and it was exactly what we needed.  Commonest case.
        DEBUG > 4 and print STDERR " And that's exactly what we needed to close complex.\n";
      } elsif($stack[-1] < length($4)) {
        # We saw " >>>>" but needed only " >>".  Back pos up.
        DEBUG > 4 and print STDERR " And that's more than we needed to close complex.\n";
        pos($para) = pos($para) - length($4) + $stack[-1];
      } else {
        # We saw " >>>>" but needed " >>>>>>".  So this is all just stuff!
        DEBUG > 4 and print STDERR " But it's really just stuff, because we needed more.\n";
        push @{ $lineage[-1] }, $3, $4;
        next;
      }
      #print STDERR "\nHOOBOY ", scalar(@{$lineage[-1]}), "!!!\n";

      if ($3 ne " " && $self->{'_output_is_for_JustPod'}) {
        if ($3 ne "") {
          $lineage[-1][1]{'~rspacer'} = $3;
        }
        elsif ($lineage[-1][1]{'~lspacer'} eq "  ") {

          # Here we had something like C<<  >> which was a false positive
          delete $lineage[-1][1]{'~lspacer'};
        }
        else {
          $lineage[-1][1]{'~rspacer'}
                                = substr($lineage[-1][1]{'~lspacer'}, -1, 1);
          chop $lineage[-1][1]{'~lspacer'};
        }
      }

      push @{ $lineage[-1] }, '' if 2 == @{ $lineage[-1] };
      # Keep the element from being childless

      if ($inL == @stack) {
        $lineage[-1][1]{'raw'} = $raw;
        $inL = 0;
      }

      pop @stack;
      pop @lineage;

      $raw .= $3.$4 if $inL;

    } elsif(defined $5) {
      DEBUG > 3 and print STDERR "Found apparent simple end-text code \"$5\"\n";

      if(@stack and ! $stack[-1]) {
        # We're indeed expecting a simple end-code
        DEBUG > 4 and print STDERR " It's indeed an end-code.\n";

        if(length($5) == 2) { # There was a space there: " >"
          push @{ $lineage[-1] }, ' ';
        } elsif( 2 == @{ $lineage[-1] } ) { # Closing a childless element
          push @{ $lineage[-1] }, ''; # keep it from being really childless
        }

        if ($inL == @stack) {
          $lineage[-1][1]{'raw'} = $raw;
          $inL = 0;
        }

        pop @stack;
        pop @lineage;
      } else {
        DEBUG > 4 and print STDERR " It's just stuff.\n";
        push @{ $lineage[-1] }, $5;
      }

      $raw .= $5 if $inL;

    } elsif(defined $6) {
      DEBUG > 3 and print STDERR "Found stuff \"$6\"\n";
      push @{ $lineage[-1] }, $6;
      $raw .= $6 if $inL;
        # XXX does not capture multiplace whitespaces -- 'raw' ends up with
        #     at most 1 leading/trailing whitespace, why not all of it?
        #     Answer, because we deliberately trimmed it above

    } else {
      # should never ever ever ever happen
      DEBUG and print STDERR "AYYAYAAAAA at line ", __LINE__, "\n";
      die "SPORK 512512!";
    }
  }

  if(@stack) { # Uhoh, some sequences weren't closed.
    my $x= "...";
    while(@stack) {
      push @{ $lineage[-1] }, '' if 2 == @{ $lineage[-1] };
      # Hmmmmm!

      my $code         = (pop @lineage)->[0];
      my $ender_length =  pop @stack;
      if($ender_length) {
        --$ender_length;
        $x = $code . ("<" x $ender_length) . " $x " . (">" x $ender_length);
      } else {
        $x = $code . "<$x>";
      }
    }
    DEBUG > 1 and print STDERR "Unterminated $x sequence\n";
    $self->whine($start_line,
      "Unterminated $x sequence",
    );
  }

  return $treelet;
}

#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

sub text_content_of_treelet {  # method: $parser->text_content_of_treelet($lol)
  return stringify_lol($_[1]);
}

sub stringify_lol {  # function: stringify_lol($lol)
  my $string_form = '';
  _stringify_lol( $_[0] => \$string_form );
  return $string_form;
}

sub _stringify_lol {  # the real recursor
  my($lol, $to) = @_;
  for(my $i = 2; $i < @$lol; ++$i) {
    if( ref($lol->[$i] || '') and UNIVERSAL::isa($lol->[$i], 'ARRAY') ) {
      _stringify_lol( $lol->[$i], $to);  # recurse!
    } else {
      $$to .= $lol->[$i];
    }
  }
  return;
}

#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

sub _dump_curr_open { # return a string representation of the stack
  my $curr_open = $_[0]{'curr_open'};

  return '[empty]' unless @$curr_open;
  return join '; ',
    map {;
           ($_->[0] eq '=for')
             ? ( ($_->[1]{'~really'} || '=over')
               . ' ' . $_->[1]{'target'})
             : $_->[0]
        }
    @$curr_open
  ;
}

###########################################################################
my %pretty_form = (
  "\a" => '\a', # ding!
  "\b" => '\b', # BS
  "\e" => '\e', # ESC
  "\f" => '\f', # FF
  "\t" => '\t', # tab
  "\cm" => '\cm',
  "\cj" => '\cj',
  "\n" => '\n', # probably overrides one of either \cm or \cj
  '"' => '\"',
  '\\' => '\\\\',
  '$' => '\\$',
  '@' => '\\@',
  '%' => '\\%',
  '#' => '\\#',
);

sub pretty { # adopted from Class::Classless
  # Not the most brilliant routine, but passable.
  # Don't give it a cyclic data structure!
  my @stuff = @_; # copy
  my $x;
  my $out =
    # join ",\n" .
    join ", ",
    map {;
    if(!defined($_)) {
      "undef";
    } elsif(ref($_) eq 'ARRAY' or ref($_) eq 'Pod::Simple::LinkSection') {
      $x = "[ " . pretty(@$_) . " ]" ;
      $x;
    } elsif(ref($_) eq 'SCALAR') {
      $x = "\\" . pretty($$_) ;
      $x;
    } elsif(ref($_) eq 'HASH') {
      my $hr = $_;
      $x = "{" . join(", ",
        map(pretty($_) . '=>' . pretty($hr->{$_}),
            sort keys %$hr ) ) . "}" ;
      $x;
    } elsif(!length($_)) { q{''} # empty string
    } elsif(
      $_ eq '0' # very common case
      or(
         m/^-?(?:[123456789]\d*|0)(?:\.\d+)?$/s
         and $_ ne '-0' # the strange case that RE lets thru
      )
    ) { $_;
    } else {
        # Yes, explicitly name every character desired. There are shorcuts one
        # could make, but I (Karl Williamson) was afraid that some Perl
        # releases would have bugs in some of them. For example [A-Z] works
        # even on EBCDIC platforms to match exactly the 26 uppercase English
        # letters, but I don't know if it has always worked without bugs. It
        # seemed safest just to list the characters.
        # s<([^\x20\x21\x23\x27-\x3F\x41-\x5B\x5D-\x7E])>
        s<([^ !"#'()*+,\-./0123456789:;\<=\>?ABCDEFGHIJKLMNOPQRSTUVWXYZ\[\]^_`abcdefghijklmnopqrstuvwxyz{|}~])>
         <$pretty_form{$1} || '\\x{'.sprintf("%x", ord($1)).'}'>eg;
         #<$pretty_form{$1} || '\\x'.(unpack("H2",$1))>eg;
      qq{"$_"};
    }
  } @stuff;
  # $out =~ s/\n */ /g if length($out) < 75;
  return $out;
}

#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

# A rather unsubtle method of blowing away all the state information
# from a parser object so it can be reused. Provided as a utility for
# backward compatibility in Pod::Man, etc. but not recommended for
# general use.

sub reinit {
  my $self = shift;
  foreach (qw(source_dead source_filename doc_has_started
start_of_pod_block content_seen last_was_blank paras curr_open
line_count pod_para_count in_pod ~tried_gen_errata all_errata errata errors_seen
Title)) {

    delete $self->{$_};
  }
}

#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
1;

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                # Copyright (C) 1997-2001 Damian Conway.  All rights reserved.
# Copyright (C) 2009 Adam Kennedy.
# Copyright (C) 2015 Steve Hay.  All rights reserved.

# This module is free software; you can redistribute it and/or modify it under
# the same terms as Perl itself, i.e. under the terms of either the GNU General
# Public License or the Artistic License, as specified in the F<LICENCE> file.

package Text::Balanced;

# EXTRACT VARIOUSLY DELIMITED TEXT SEQUENCES FROM STRINGS.
# FOR FULL DOCUMENTATION SEE Balanced.pod

use 5.008001;
use strict;
use Exporter ();

use vars qw { $VERSION @ISA %EXPORT_TAGS };
BEGIN {
    $VERSION     = '2.04';
    @ISA         = 'Exporter';
    %EXPORT_TAGS = (
        ALL => [ qw{
            &extract_delimited
            &extract_bracketed
            &extract_quotelike
            &extract_codeblock
            &extract_variable
            &extract_tagged
            &extract_multiple
            &gen_delimited_pat
            &gen_extract_tagged
            &delimited_pat
        } ],
    );
}

Exporter::export_ok_tags('ALL');

## no critic (Subroutines::ProhibitSubroutinePrototypes)

# PROTOTYPES

sub _match_bracketed($$$$$$);
sub _match_variable($$);
sub _match_codeblock($$$$$$$);
sub _match_quotelike($$$$);

# HANDLE RETURN VALUES IN VARIOUS CONTEXTS

sub _failmsg {
    my ($message, $pos) = @_;
    $@ = bless {
        error => $message,
        pos   => $pos,
    }, 'Text::Balanced::ErrorMsg';
}

sub _fail {
    my ($wantarray, $textref, $message, $pos) = @_;
    _failmsg $message, $pos if $message;
    return (undef, $$textref, undef) if $wantarray;
    return;
}

sub _succeed {
    $@ = undef;
    my ($wantarray,$textref) = splice @_, 0, 2;
    my ($extrapos, $extralen) = @_ > 18
        ? splice(@_, -2, 2)
        : (0, 0);
    my ($startlen, $oppos) = @_[5,6];
    my $remainderpos = $_[2];
    if ( $wantarray ) {
        my @res;
        while (my ($from, $len) = splice @_, 0, 2) {
            push @res, substr($$textref, $from, $len);
        }
        if ( $extralen ) { # CORRECT FILLET
            my $extra = substr($res[0], $extrapos-$oppos, $extralen, "\n");
            $res[1] = "$extra$res[1]";
            eval { substr($$textref,$remainderpos,0) = $extra;
                   substr($$textref,$extrapos,$extralen,"\n")} ;
                    #REARRANGE HERE DOC AND FILLET IF POSSIBLE
            pos($$textref) = $remainderpos-$extralen+1; # RESET \G
        } else {
            pos($$textref) = $remainderpos;             # RESET \G
        }
        return @res;
    } else {
        my $match = substr($$textref,$_[0],$_[1]);
        substr($match,$extrapos-$_[0]-$startlen,$extralen,"") if $extralen;
        my $extra = $extralen
            ? substr($$textref, $extrapos, $extralen)."\n" : "";
        eval {substr($$textref,$_[4],$_[1]+$_[5])=$extra} ;     #CHOP OUT PREFIX & MATCH, IF POSSIBLE
        pos($$textref) = $_[4];                         # RESET \G
        return $match;
    }
}

# BUILD A PATTERN MATCHING A SIMPLE DELIMITED STRING

sub gen_delimited_pat($;$)  # ($delimiters;$escapes)
{
    my ($dels, $escs) = @_;
    return "" unless $dels =~ /\S/;
    $escs = '\\' unless $escs;
    $escs .= substr($escs,-1) x (length($dels)-length($escs));
    my @pat = ();
    my $i;
    for ($i=0; $i<length $dels; $i++)
    {
        my $del = quotemeta substr($dels,$i,1);
        my $esc = quotemeta substr($escs,$i,1);
        if ($del eq $esc)
        {
            push @pat, "$del(?:[^$del]*(?:(?:$del$del)[^$del]*)*)$del";
        }
        else
        {
            push @pat, "$del(?:[^$esc$del]*(?:$esc.[^$esc$del]*)*)$del";
        }
    }
    my $pat = join '|', @pat;
    return "(?:$pat)";
}

*delimited_pat = \&gen_delimited_pat;

# THE EXTRACTION FUNCTIONS

sub extract_delimited (;$$$$)
{
    my $textref = defined $_[0] ? \$_[0] : \$_;
    my $wantarray = wantarray;
    my $del  = defined $_[1] ? $_[1] : qq{\'\"\`};
    my $pre  = defined $_[2] ? $_[2] : '\s*';
    my $esc  = defined $_[3] ? $_[3] : qq{\\};
    my $pat = gen_delimited_pat($del, $esc);
    my $startpos = pos $$textref || 0;
    return _fail($wantarray, $textref, "Not a delimited pattern", 0)
        unless $$textref =~ m/\G($pre)($pat)/gc;
    my $prelen = length($1);
    my $matchpos = $startpos+$prelen;
    my $endpos = pos $$textref;
    return _succeed $wantarray, $textref,
                    $matchpos, $endpos-$matchpos,               # MATCH
                    $endpos,   length($$textref)-$endpos,       # REMAINDER
                    $startpos, $prelen;                         # PREFIX
}

sub extract_bracketed (;$$$)
{
    my $textref = defined $_[0] ? \$_[0] : \$_;
    my $ldel = defined $_[1] ? $_[1] : '{([<';
    my $pre  = defined $_[2] ? $_[2] : '\s*';
    my $wantarray = wantarray;
    my $qdel = "";
    my $quotelike;
    $ldel =~ s/'//g and $qdel .= q{'};
    $ldel =~ s/"//g and $qdel .= q{"};
    $ldel =~ s/`//g and $qdel .= q{`};
    $ldel =~ s/q//g and $quotelike = 1;
    $ldel =~ tr/[](){}<>\0-\377/[[(({{<</ds;
    my $rdel = $ldel;
    unless ($rdel =~ tr/[({</])}>/)
    {
        return _fail $wantarray, $textref,
                     "Did not find a suitable bracket in delimiter: \"$_[1]\"",
                     0;
    }
    my $posbug = pos;
    $ldel = join('|', map { quotemeta $_ } split('', $ldel));
    $rdel = join('|', map { quotemeta $_ } split('', $rdel));
    pos = $posbug;

    my $startpos = pos $$textref || 0;
    my @match = _match_bracketed($textref,$pre, $ldel, $qdel, $quotelike, $rdel);

    return _fail ($wantarray, $textref) unless @match;

    return _succeed ( $wantarray, $textref,
                      $match[2], $match[5]+2,           # MATCH
                      @match[8,9],                      # REMAINDER
                      @match[0,1],                      # PREFIX
                    );
}

sub _match_bracketed($$$$$$)    # $textref, $pre, $ldel, $qdel, $quotelike, $rdel
{
    my ($textref, $pre, $ldel, $qdel, $quotelike, $rdel) = @_;
    my ($startpos, $ldelpos, $endpos) = (pos $$textref = pos $$textref||0);
    unless ($$textref =~ m/\G$pre/gc)
    {
        _failmsg "Did not find prefix: /$pre/", $startpos;
        return;
    }

    $ldelpos = pos $$textref;

    unless ($$textref =~ m/\G($ldel)/gc)
    {
        _failmsg "Did not find opening bracket after prefix: \"$pre\"",
                 pos $$textref;
        pos $$textref = $startpos;
        return;
    }

    my @nesting = ( $1 );
    my $textlen = length $$textref;
    while (pos $$textref < $textlen)
    {
        next if $$textref =~ m/\G\\./gcs;

        if ($$textref =~ m/\G($ldel)/gc)
        {
            push @nesting, $1;
        }
        elsif ($$textref =~ m/\G($rdel)/gc)
        {
            my ($found, $brackettype) = ($1, $1);
            if ($#nesting < 0)
            {
                _failmsg "Unmatched closing bracket: \"$found\"",
                         pos $$textref;
                pos $$textref = $startpos;
                return;
            }
            my $expected = pop(@nesting);
            $expected =~ tr/({[</)}]>/;
            if ($expected ne $brackettype)
            {
                _failmsg qq{Mismatched closing bracket: expected "$expected" but found "$found"},
                         pos $$textref;
                pos $$textref = $startpos;
                return;
            }
            last if $#nesting < 0;
        }
        elsif ($qdel && $$textref =~ m/\G([$qdel])/gc)
        {
            $$textref =~ m/\G[^\\$1]*(?:\\.[^\\$1]*)*(\Q$1\E)/gsc and next;
            _failmsg "Unmatched embedded quote ($1)",
                     pos $$textref;
            pos $$textref = $startpos;
            return;
        }
        elsif ($quotelike && _match_quotelike($textref,"",1,0))
        {
            next;
        }

        else { $$textref =~ m/\G(?:[a-zA-Z0-9]+|.)/gcs }
    }
    if ($#nesting>=0)
    {
        _failmsg "Unmatched opening bracket(s): "
                     . join("..",@nesting)."..",
                 pos $$textref;
        pos $$textref = $startpos;
        return;
    }

    $endpos = pos $$textref;

    return (
        $startpos,  $ldelpos-$startpos,         # PREFIX
        $ldelpos,   1,                          # OPENING BRACKET
        $ldelpos+1, $endpos-$ldelpos-2,         # CONTENTS
        $endpos-1,  1,                          # CLOSING BRACKET
        $endpos,    length($$textref)-$endpos,  # REMAINDER
    );
}

sub _revbracket($)
{
    my $brack = reverse $_[0];
    $brack =~ tr/[({</])}>/;
    return $brack;
}

my $XMLNAME = q{[a-zA-Z_:][a-zA-Z0-9_:.-]*};

sub extract_tagged (;$$$$$) # ($text, $opentag, $closetag, $pre, \%options)
{
    my $textref = defined $_[0] ? \$_[0] : \$_;
    my $ldel    = $_[1];
    my $rdel    = $_[2];
    my $pre     = defined $_[3] ? $_[3] : '\s*';
    my %options = defined $_[4] ? %{$_[4]} : ();
    my $omode   = defined $options{fail} ? $options{fail} : '';
    my $bad     = ref($options{reject}) eq 'ARRAY' ? join('|', @{$options{reject}})
                : defined($options{reject})        ? $options{reject}
                :                                    ''
                ;
    my $ignore  = ref($options{ignore}) eq 'ARRAY' ? join('|', @{$options{ignore}})
                : defined($options{ignore})        ? $options{ignore}
                :                                    ''
                ;

    if (!defined $ldel) { $ldel = '<\w+(?:' . gen_delimited_pat(q{'"}) . '|[^>])*>'; }
    $@ = undef;

    my @match = _match_tagged($textref, $pre, $ldel, $rdel, $omode, $bad, $ignore);

    return _fail(wantarray, $textref) unless @match;
    return _succeed wantarray, $textref,
            $match[2], $match[3]+$match[5]+$match[7],    # MATCH
            @match[8..9,0..1,2..7];                      # REM, PRE, BITS
}

sub _match_tagged       # ($$$$$$$)
{
    my ($textref, $pre, $ldel, $rdel, $omode, $bad, $ignore) = @_;
    my $rdelspec;

    my ($startpos, $opentagpos, $textpos, $parapos, $closetagpos, $endpos) = ( pos($$textref) = pos($$textref)||0 );

    unless ($$textref =~ m/\G($pre)/gc)
    {
        _failmsg "Did not find prefix: /$pre/", pos $$textref;
        goto failed;
    }

    $opentagpos = pos($$textref);

    unless ($$textref =~ m/\G$ldel/gc)
    {
        _failmsg "Did not find opening tag: /$ldel/", pos $$textref;
        goto failed;
    }

    $textpos = pos($$textref);

    if (!defined $rdel)
    {
        $rdelspec = substr($$textref, $-[0], $+[0] - $-[0]);
        unless ($rdelspec =~ s/\A([[(<{]+)($XMLNAME).*/ quotemeta "$1\/$2". _revbracket($1) /oes)
        {
            _failmsg "Unable to construct closing tag to match: $rdel",
                     pos $$textref;
            goto failed;
        }
    }
    else
    {
        ## no critic (BuiltinFunctions::ProhibitStringyEval)
        $rdelspec = eval "qq{$rdel}" || do {
            my $del;
            for (qw,~ ! ^ & * ) _ + - = } ] : " ; ' > . ? / | ',)
                { next if $rdel =~ /\Q$_/; $del = $_; last }
            unless ($del) {
                use Carp;
                croak "Can't interpolate right delimiter $rdel"
            }
            eval "qq$del$rdel$del";
        };
    }

    while (pos($$textref) < length($$textref))
    {
        next if $$textref =~ m/\G\\./gc;

        if ($$textref =~ m/\G(\n[ \t]*\n)/gc )
        {
            $parapos = pos($$textref) - length($1)
                unless defined $parapos;
        }
        elsif ($$textref =~ m/\G($rdelspec)/gc )
        {
            $closetagpos = pos($$textref)-length($1);
            goto matched;
        }
        elsif ($ignore && $$textref =~ m/\G(?:$ignore)/gc)
        {
            next;
        }
        elsif ($bad && $$textref =~ m/\G($bad)/gcs)
        {
            pos($$textref) -= length($1);       # CUT OFF WHATEVER CAUSED THE SHORTNESS
            goto short if ($omode eq 'PARA' || $omode eq 'MAX');
            _failmsg "Found invalid nested tag: $1", pos $$textref;
            goto failed;
        }
        elsif ($$textref =~ m/\G($ldel)/gc)
        {
            my $tag = $1;
            pos($$textref) -= length($tag);     # REWIND TO NESTED TAG
            unless (_match_tagged(@_))  # MATCH NESTED TAG
            {
                goto short if $omode eq 'PARA' || $omode eq 'MAX';
                _failmsg "Found unbalanced nested tag: $tag",
                         pos $$textref;
                goto failed;
            }
        }
        else { $$textref =~ m/./gcs }
    }

short:
    $closetagpos = pos($$textref);
    goto matched if $omode eq 'MAX';
    goto failed unless $omode eq 'PARA';

    if (defined $parapos) { pos($$textref) = $parapos }
    else                  { $parapos = pos($$textref) }

    return (
        $startpos,    $opentagpos-$startpos,            # PREFIX
        $opentagpos,  $textpos-$opentagpos,             # OPENING TAG
        $textpos,     $parapos-$textpos,                # TEXT
        $parapos,     0,                                # NO CLOSING TAG
        $parapos,     length($$textref)-$parapos,       # REMAINDER
    );

matched:
    $endpos = pos($$textref);
    return (
        $startpos,    $opentagpos-$startpos,            # PREFIX
        $opentagpos,  $textpos-$opentagpos,             # OPENING TAG
        $textpos,     $closetagpos-$textpos,            # TEXT
        $closetagpos, $endpos-$closetagpos,             # CLOSING TAG
        $endpos,      length($$textref)-$endpos,        # REMAINDER
    );

failed:
    _failmsg "Did not find closing tag", pos $$textref unless $@;
    pos($$textref) = $startpos;
    return;
}

sub extract_variable (;$$)
{
    my $textref = defined $_[0] ? \$_[0] : \$_;
    return ("","","") unless defined $$textref;
    my $pre  = defined $_[1] ? $_[1] : '\s*';

    my @match = _match_variable($textref,$pre);

    return _fail wantarray, $textref unless @match;

    return _succeed wantarray, $textref,
                    @match[2..3,4..5,0..1];        # MATCH, REMAINDER, PREFIX
}

sub _match_variable($$)
{
#  $#
#  $^
#  $$
    my ($textref, $pre) = @_;
    my $startpos = pos($$textref) = pos($$textref)||0;
    unless ($$textref =~ m/\G($pre)/gc)
    {
        _failmsg "Did not find prefix: /$pre/", pos $$textref;
        return;
    }
    my $varpos = pos($$textref);
    unless ($$textref =~ m{\G\$\s*(?!::)(\d+|[][&`'+*./|,";%=~:?!\@<>()-]|\^[a-z]?)}gci)
    {
        unless ($$textref =~ m/\G((\$#?|[*\@\%]|\\&)+)/gc)
        {
            _failmsg "Did not find leading dereferencer", pos $$textref;
            pos $$textref = $startpos;
            return;
        }
        my $deref = $1;

        unless ($$textref =~ m/\G\s*(?:::|')?(?:[_a-z]\w*(?:::|'))*[_a-z]\w*/gci
            or _match_codeblock($textref, "", '\{', '\}', '\{', '\}', 0)
            or $deref eq '$#' or $deref eq '$$' )
        {
            _failmsg "Bad identifier after dereferencer", pos $$textref;
            pos $$textref = $startpos;
            return;
        }
    }

    while (1)
    {
        next if $$textref =~ m/\G\s*(?:->)?\s*[{]\w+[}]/gc;
        next if _match_codeblock($textref,
                                 qr/\s*->\s*(?:[_a-zA-Z]\w+\s*)?/,
                                 qr/[({[]/, qr/[)}\]]/,
                                 qr/[({[]/, qr/[)}\]]/, 0);
        next if _match_codeblock($textref,
                                 qr/\s*/, qr/[{[]/, qr/[}\]]/,
                                 qr/[{[]/, qr/[}\]]/, 0);
        next if _match_variable($textref,'\s*->\s*');
        next if $$textref =~ m/\G\s*->\s*\w+(?![{([])/gc;
        last;
    }

    my $endpos = pos($$textref);
    return ($startpos, $varpos-$startpos,
            $varpos,   $endpos-$varpos,
            $endpos,   length($$textref)-$endpos
    );
}

sub extract_codeblock (;$$$$$)
{
    my $textref = defined $_[0] ? \$_[0] : \$_;
    my $wantarray = wantarray;
    my $ldel_inner = defined $_[1] ? $_[1] : '{';
    my $pre        = defined $_[2] ? $_[2] : '\s*';
    my $ldel_outer = defined $_[3] ? $_[3] : $ldel_inner;
    my $rd         = $_[4];
    my $rdel_inner = $ldel_inner;
    my $rdel_outer = $ldel_outer;
    my $posbug = pos;
    for ($ldel_inner, $ldel_outer) { tr/[]()<>{}\0-\377/[[((<<{{/ds }
    for ($rdel_inner, $rdel_outer) { tr/[]()<>{}\0-\377/]]))>>}}/ds }
    for ($ldel_inner, $ldel_outer, $rdel_inner, $rdel_outer)
    {
        $_ = '('.join('|',map { quotemeta $_ } split('',$_)).')'
    }
    pos = $posbug;

    my @match = _match_codeblock($textref, $pre,
                                 $ldel_outer, $rdel_outer,
                                 $ldel_inner, $rdel_inner,
                                 $rd);
    return _fail($wantarray, $textref) unless @match;
    return _succeed($wantarray, $textref,
                    @match[2..3,4..5,0..1]    # MATCH, REMAINDER, PREFIX
    );

}

sub _match_codeblock($$$$$$$)
{
    my ($textref, $pre, $ldel_outer, $rdel_outer, $ldel_inner, $rdel_inner, $rd) = @_;
    my $startpos = pos($$textref) = pos($$textref) || 0;
    unless ($$textref =~ m/\G($pre)/gc)
    {
        _failmsg qq{Did not match prefix /$pre/ at"} .
                     substr($$textref,pos($$textref),20) .
                     q{..."},
                 pos $$textref;
        return;
    }
    my $codepos = pos($$textref);
    unless ($$textref =~ m/\G($ldel_outer)/gc)  # OUTERMOST DELIMITER
    {
        _failmsg qq{Did not find expected opening bracket at "} .
                     substr($$textref,pos($$textref),20) .
                     q{..."},
                 pos $$textref;
        pos $$textref = $startpos;
        return;
    }
    my $closing = $1;
       $closing =~ tr/([<{/)]>}/;
    my $matched;
    my $patvalid = 1;
    while (pos($$textref) < length($$textref))
    {
        $matched = '';
        if ($rd && $$textref =~ m#\G(\Q(?)\E|\Q(s?)\E|\Q(s)\E)#gc)
        {
            $patvalid = 0;
            next;
        }

        if ($$textref =~ m/\G\s*#.*/gc)
        {
            next;
        }

        if ($$textref =~ m/\G\s*($rdel_outer)/gc)
        {
            unless ($matched = ($closing && $1 eq $closing) )
            {
                next if $1 eq '>';      # MIGHT BE A "LESS THAN"
                _failmsg q{Mismatched closing bracket at "} .
                             substr($$textref,pos($$textref),20) .
                             qq{...". Expected '$closing'},
                         pos $$textref;
            }
            last;
        }

        if (_match_variable($textref,'\s*') ||
            _match_quotelike($textref,'\s*',$patvalid,$patvalid) )
        {
            $patvalid = 0;
            next;
        }


        # NEED TO COVER MANY MORE CASES HERE!!!
        if ($$textref =~ m#\G\s*(?!$ldel_inner)
                                ( [-+*x/%^&|.]=?
                                | [!=]~
                                | =(?!>)
                                | (\*\*|&&|\|\||<<|>>)=?
                                | split|grep|map|return
                                | [([]
                                )#gcx)
        {
            $patvalid = 1;
            next;
        }

        if ( _match_codeblock($textref, '\s*', $ldel_inner, $rdel_inner, $ldel_inner, $rdel_inner, $rd) )
        {
            $patvalid = 1;
            next;
        }

        if ($$textref =~ m/\G\s*$ldel_outer/gc)
        {
            _failmsg q{Improperly nested codeblock at "} .
                         substr($$textref,pos($$textref),20) .
                         q{..."},
                     pos $$textref;
            last;
        }

        $patvalid = 0;
        $$textref =~ m/\G\s*(\w+|[-=>]>|.|\Z)/gc;
    }
    continue { $@ = undef }

    unless ($matched)
    {
        _failmsg 'No match found for opening bracket', pos $$textref
                unless $@;
        return;
    }

    my $endpos = pos($$textref);
    return ( $startpos, $codepos-$startpos,
             $codepos, $endpos-$codepos,
             $endpos,  length($$textref)-$endpos,
    );
}


my %mods   = (
    'none' => '[cgimsox]*',
    'm'    => '[cgimsox]*',
    's'    => '[cegimsox]*',
    'tr'   => '[cds]*',
    'y'    => '[cds]*',
    'qq'   => '',
    'qx'   => '',
    'qw'   => '',
    'qr'   => '[imsx]*',
    'q'    => '',
);

sub extract_quotelike (;$$)
{
    my $textref = $_[0] ? \$_[0] : \$_;
    my $wantarray = wantarray;
    my $pre  = defined $_[1] ? $_[1] : '\s*';

    my @match = _match_quotelike($textref,$pre,1,0);
    return _fail($wantarray, $textref) unless @match;
    return _succeed($wantarray, $textref,
                    $match[2], $match[18]-$match[2],    # MATCH
                    @match[18,19],                      # REMAINDER
                    @match[0,1],                        # PREFIX
                    @match[2..17],                      # THE BITS
                    @match[20,21],                      # ANY FILLET?
    );
};

sub _match_quotelike($$$$)      # ($textref, $prepat, $allow_raw_match)
{
    my ($textref, $pre, $rawmatch, $qmark) = @_;

    my ($textlen,$startpos,
        $oppos,
        $preld1pos,$ld1pos,$str1pos,$rd1pos,
        $preld2pos,$ld2pos,$str2pos,$rd2pos,
        $modpos) = ( length($$textref), pos($$textref) = pos($$textref) || 0 );

    unless ($$textref =~ m/\G($pre)/gc)
    {
        _failmsg qq{Did not find prefix /$pre/ at "} .
                     substr($$textref, pos($$textref), 20) .
                     q{..."},
                 pos $$textref;
        return;
    }
    $oppos = pos($$textref);

    my $initial = substr($$textref,$oppos,1);

    if ($initial && $initial =~ m|^[\"\'\`]|
                 || $rawmatch && $initial =~ m|^/|
                 || $qmark && $initial =~ m|^\?|)
    {
        unless ($$textref =~ m/ \Q$initial\E [^\\$initial]* (\\.[^\\$initial]*)* \Q$initial\E /gcsx)
        {
            _failmsg qq{Did not find closing delimiter to match '$initial' at "} .
                         substr($$textref, $oppos, 20) .
                         q{..."},
                     pos $$textref;
            pos $$textref = $startpos;
            return;
        }
        $modpos= pos($$textref);
        $rd1pos = $modpos-1;

        if ($initial eq '/' || $initial eq '?')
        {
            $$textref =~ m/\G$mods{none}/gc
        }

        my $endpos = pos($$textref);
        return (
            $startpos,  $oppos-$startpos,       # PREFIX
            $oppos,     0,                      # NO OPERATOR
            $oppos,     1,                      # LEFT DEL
            $oppos+1,   $rd1pos-$oppos-1,       # STR/PAT
            $rd1pos,    1,                      # RIGHT DEL
            $modpos,    0,                      # NO 2ND LDEL
            $modpos,    0,                      # NO 2ND STR
            $modpos,    0,                      # NO 2ND RDEL
            $modpos,    $endpos-$modpos,        # MODIFIERS
            $endpos,    $textlen-$endpos,       # REMAINDER
        );
    }

    unless ($$textref =~ m{\G(\b(?:m|s|qq|qx|qw|q|qr|tr|y)\b(?=\s*\S)|<<)}gc)
    {
        _failmsg q{No quotelike operator found after prefix at "} .
                     substr($$textref, pos($$textref), 20) .
                     q{..."},
                 pos $$textref;
        pos $$textref = $startpos;
        return;
    }

    my $op = $1;
    $preld1pos = pos($$textref);
    if ($op eq '<<') {
        $ld1pos = pos($$textref);
        my $label;
        if ($$textref =~ m{\G([A-Za-z_]\w*)}gc) {
            $label = $1;
        }
        elsif ($$textref =~ m{ \G ' ([^'\\]* (?:\\.[^'\\]*)*) '
                             | \G " ([^"\\]* (?:\\.[^"\\]*)*) "
                             | \G ` ([^`\\]* (?:\\.[^`\\]*)*) `
                             }gcsx) {
            $label = $+;
        }
        else {
            $label = "";
        }
        my $extrapos = pos($$textref);
        $$textref =~ m{.*\n}gc;
        $str1pos = pos($$textref)--;
        unless ($$textref =~ m{.*?\n(?=\Q$label\E\n)}gc) {
            _failmsg qq{Missing here doc terminator ('$label') after "} .
                         substr($$textref, $startpos, 20) .
                         q{..."},
                     pos $$textref;
            pos $$textref = $startpos;
            return;
        }
        $rd1pos = pos($$textref);
        $$textref =~ m{\Q$label\E\n}gc;
        $ld2pos = pos($$textref);
        return (
            $startpos,  $oppos-$startpos,       # PREFIX
            $oppos,     length($op),            # OPERATOR
            $ld1pos,    $extrapos-$ld1pos,      # LEFT DEL
            $str1pos,   $rd1pos-$str1pos,       # STR/PAT
            $rd1pos,    $ld2pos-$rd1pos,        # RIGHT DEL
            $ld2pos,    0,                      # NO 2ND LDEL
            $ld2pos,    0,                      # NO 2ND STR
            $ld2pos,    0,                      # NO 2ND RDEL
            $ld2pos,    0,                      # NO MODIFIERS
            $ld2pos,    $textlen-$ld2pos,       # REMAINDER
            $extrapos,  $str1pos-$extrapos,     # FILLETED BIT
        );
    }

    $$textref =~ m/\G\s*/gc;
    $ld1pos = pos($$textref);
    $str1pos = $ld1pos+1;

    unless ($$textref =~ m/\G(\S)/gc)   # SHOULD USE LOOKAHEAD
    {
        _failmsg "No block delimiter found after quotelike $op",
                 pos $$textref;
        pos $$textref = $startpos;
        return;
    }
    pos($$textref) = $ld1pos;   # HAVE TO DO THIS BECAUSE LOOKAHEAD BROKEN
    my ($ldel1, $rdel1) = ("\Q$1","\Q$1");
    if ($ldel1 =~ /[[(<{]/)
    {
        $rdel1 =~ tr/[({</])}>/;
        defined(_match_bracketed($textref,"",$ldel1,"","",$rdel1))
            || do { pos $$textref = $startpos; return };
        $ld2pos = pos($$textref);
        $rd1pos = $ld2pos-1;
    }
    else
    {
        $$textref =~ /\G$ldel1[^\\$ldel1]*(\\.[^\\$ldel1]*)*$ldel1/gcs
            || do { pos $$textref = $startpos; return };
        $ld2pos = $rd1pos = pos($$textref)-1;
    }

    my $second_arg = $op =~ /s|tr|y/ ? 1 : 0;
    if ($second_arg)
    {
        my ($ldel2, $rdel2);
        if ($ldel1 =~ /[[(<{]/)
        {
            unless ($$textref =~ /\G\s*(\S)/gc) # SHOULD USE LOOKAHEAD
            {
                _failmsg "Missing second block for quotelike $op",
                         pos $$textref;
                pos $$textref = $startpos;
                return;
            }
            $ldel2 = $rdel2 = "\Q$1";
            $rdel2 =~ tr/[({</])}>/;
        }
        else
        {
            $ldel2 = $rdel2 = $ldel1;
        }
        $str2pos = $ld2pos+1;

        if ($ldel2 =~ /[[(<{]/)
        {
            pos($$textref)--;   # OVERCOME BROKEN LOOKAHEAD
            defined(_match_bracketed($textref,"",$ldel2,"","",$rdel2))
                || do { pos $$textref = $startpos; return };
        }
        else
        {
            $$textref =~ /[^\\$ldel2]*(\\.[^\\$ldel2]*)*$ldel2/gcs
                || do { pos $$textref = $startpos; return };
        }
        $rd2pos = pos($$textref)-1;
    }
    else
    {
        $ld2pos = $str2pos = $rd2pos = $rd1pos;
    }

    $modpos = pos $$textref;

    $$textref =~ m/\G($mods{$op})/gc;
    my $endpos = pos $$textref;

    return (
        $startpos,      $oppos-$startpos,       # PREFIX
        $oppos,         length($op),            # OPERATOR
        $ld1pos,        1,                      # LEFT DEL
        $str1pos,       $rd1pos-$str1pos,       # STR/PAT
        $rd1pos,        1,                      # RIGHT DEL
        $ld2pos,        $second_arg,            # 2ND LDEL (MAYBE)
        $str2pos,       $rd2pos-$str2pos,       # 2ND STR (MAYBE)
        $rd2pos,        $second_arg,            # 2ND RDEL (MAYBE)
        $modpos,        $endpos-$modpos,        # MODIFIERS
        $endpos,        $textlen-$endpos,       # REMAINDER
    );
}

my $def_func = [
    sub { extract_variable($_[0], '') },
    sub { extract_quotelike($_[0],'') },
    sub { extract_codeblock($_[0],'{}','') },
];

sub extract_multiple (;$$$$)    # ($text, $functions_ref, $max_fields, $ignoreunknown)
{
    my $textref = defined($_[0]) ? \$_[0] : \$_;
    my $posbug = pos;
    my ($lastpos, $firstpos);
    my @fields = ();

    #for ($$textref)
    {
        my @func = defined $_[1] ? @{$_[1]} : @{$def_func};
        my $max  = defined $_[2] && $_[2]>0 ? $_[2] : 1_000_000_000;
        my $igunk = $_[3];

        pos $$textref ||= 0;

        unless (wantarray)
        {
            use Carp;
            carp "extract_multiple reset maximal count to 1 in scalar context"
                    if $^W && defined($_[2]) && $max > 1;
            $max = 1
        }

        my $unkpos;
        my $class;

        my @class;
        foreach my $func ( @func )
        {
            if (ref($func) eq 'HASH')
            {
                push @class, (keys %$func)[0];
                $func = (values %$func)[0];
            }
            else
            {
                push @class, undef;
            }
        }

        FIELD: while (pos($$textref) < length($$textref))
        {
            my ($field, $rem);
            my @bits;
            foreach my $i ( 0..$#func )
            {
                my $pref;
                my $func = $func[$i];
                $class = $class[$i];
                $lastpos = pos $$textref;
                if (ref($func) eq 'CODE')
                    { ($field,$rem,$pref) = @bits = $func->($$textref) }
                elsif (ref($func) eq 'Text::Balanced::Extractor')
                    { @bits = $field = $func->extract($$textref) }
                elsif( $$textref =~ m/\G$func/gc )
                    { @bits = $field = defined($1)
                        ? $1
                        : substr($$textref, $-[0], $+[0] - $-[0])
                    }
                $pref ||= "";
                if (defined($field) && length($field))
                {
                    if (!$igunk) {
                        $unkpos = $lastpos
                            if length($pref) && !defined($unkpos);
                        if (defined $unkpos)
                        {
                            push @fields, substr($$textref, $unkpos, $lastpos-$unkpos).$pref;
                            $firstpos = $unkpos unless defined $firstpos;
                            undef $unkpos;
                            last FIELD if @fields == $max;
                        }
                    }
                    push @fields, $class
                            ? bless (\$field, $class)
                            : $field;
                    $firstpos = $lastpos unless defined $firstpos;
                    $lastpos = pos $$textref;
                    last FIELD if @fields == $max;
                    next FIELD;
                }
            }
            if ($$textref =~ /\G(.)/gcs)
            {
                $unkpos = pos($$textref)-1
                    unless $igunk || defined $unkpos;
            }
        }

        if (defined $unkpos)
        {
            push @fields, substr($$textref, $unkpos);
            $firstpos = $unkpos unless defined $firstpos;
            $lastpos = length $$textref;
        }
        last;
    }

    pos $$textref = $lastpos;
    return @fields if wantarray;

    $firstpos ||= 0;
    eval { substr($$textref,$firstpos,$lastpos-$firstpos)="";
           pos $$textref = $firstpos };
    return $fields[0];
}

sub gen_extract_tagged # ($opentag, $closetag, $pre, \%options)
{
    my $ldel    = $_[0];
    my $rdel    = $_[1];
    my $pre     = defined $_[2] ? $_[2] : '\s*';
    my %options = defined $_[3] ? %{$_[3]} : ();
    my $omode   = defined $options{fail} ? $options{fail} : '';
    my $bad     = ref($options{reject}) eq 'ARRAY' ? join('|', @{$options{reject}})
                : defined($options{reject})        ? $options{reject}
                :                                    ''
                ;
    my $ignore  = ref($options{ignore}) eq 'ARRAY' ? join('|', @{$options{ignore}})
                : defined($options{ignore})        ? $options{ignore}
                :                                    ''
                ;

    if (!defined $ldel) { $ldel = '<\w+(?:' . gen_delimited_pat(q{'"}) . '|[^>])*>'; }

    my $posbug = pos;
    for ($ldel, $pre, $bad, $ignore) { $_ = qr/$_/ if $_ }
    pos = $posbug;

    my $closure = sub
    {
        my $textref = defined $_[0] ? \$_[0] : \$_;
        my @match = Text::Balanced::_match_tagged($textref, $pre, $ldel, $rdel, $omode, $bad, $ignore);

        return _fail(wantarray, $textref) unless @match;
        return _succeed wantarray, $textref,
                        $match[2], $match[3]+$match[5]+$match[7],   # MATCH
                        @match[8..9,0..1,2..7];                     # REM, PRE, BITS
    };

    bless $closure, 'Text::Balanced::Extractor';
}

package Text::Balanced::Extractor;

sub extract($$) # ($self, $text)
{
    &{$_[0]}($_[1]);
}

package Text::Balanced::ErrorMsg;

use overload '""' => sub { "$_[0]->{error}, detected at offset $_[0]->{pos}" };

1;

__END__

=pod

=head1 NAME

Text::Balanced - Extract delimited text sequences from strings.

=head1 SYNOPSIS

    use Text::Balanced qw (
        extract_delimited
        extract_bracketed
        extract_quotelike
        extract_codeblock
        extract_variable
        extract_tagged
        extract_multiple
        gen_delimited_pat
        gen_extract_tagged
    );

    # Extract the initial substring of $text that is delimited by
    # two (unescaped) instances of the first character in $delim.

    ($extracted, $remainder) = extract_delimited($text,$delim);

    # Extract the initial substring of $text that is bracketed
    # with a delimiter(s) specified by $delim (where the string
    # in $delim contains one or more of '(){}[]<>').

    ($extracted, $remainder) = extract_bracketed($text,$delim);

    # Extract the initial substring of $text that is bounded by
    # an XML tag.

    ($extracted, $remainder) = extract_tagged($text);

    # Extract the initial substring of $text that is bounded by
    # a C<BEGIN>...C<END> pair. Don't allow nested C<BEGIN> tags

    ($extracted, $remainder) =
        extract_tagged($text,"BEGIN","END",undef,{bad=>["BEGIN"]});

    # Extract the initial substring of $text that represents a
    # Perl "quote or quote-like operation"

    ($extracted, $remainder) = extract_quotelike($text);

    # Extract the initial substring of $text that represents a block
    # of Perl code, bracketed by any of character(s) specified by $delim
    # (where the string $delim contains one or more of '(){}[]<>').

    ($extracted, $remainder) = extract_codeblock($text,$delim);

    # Extract the initial substrings of $text that would be extracted by
    # one or more sequential applications of the specified functions
    # or regular expressions

    @extracted = extract_multiple($text,
                                  [ \&extract_bracketed,
                                    \&extract_quotelike,
                                    \&some_other_extractor_sub,
                                    qr/[xyz]*/,
                                    'literal',
                                  ]);

    # Create a string representing an optimized pattern (a la Friedl)
    # that matches a substring delimited by any of the specified characters
    # (in this case: any type of quote or a slash)

    $patstring = gen_delimited_pat(q{'"`/});

    # Generate a reference to an anonymous sub that is just like extract_tagged
    # but pre-compiled and optimized for a specific pair of tags, and
    # consequently much faster (i.e. 3 times faster). It uses qr// for better
    # performance on repeated calls.

    $extract_head = gen_extract_tagged('<HEAD>','</HEAD>');
    ($extracted, $remainder) = $extract_head->($text);

=head1 DESCRIPTION

The various C<extract_...> subroutines may be used to
extract a delimited substring, possibly after skipping a
specified prefix string. By default, that prefix is
optional whitespace (C</\s*/>), but you can change it to whatever
you wish (see below).

The substring to be extracted must appear at the
current C<pos> location of the string's variable
(or at index zero, if no C<pos> position is defined).
In other words, the C<extract_...> subroutines I<don't>
extract the first occurrence of a substring anywhere
in a string (like an unanchored regex would). Rather,
they extract an occurrence of the substring appearing
immediately at the current matching position in the
string (like a C<\G>-anchored regex would).

=head2 General Behaviour in List Contexts

In a list context, all the subroutines return a list, the first three
elements of which are always:

=over 4

=item [0]

The extracted string, including the specified delimiters.
If the extraction fails C<undef> is returned.

=item [1]

The remainder of the input string (i.e. the characters after the
extracted string). On failure, the entire string is returned.

=item [2]

The skipped prefix (i.e. the characters before the extracted string).
On failure, C<undef> is returned.

=back

Note that in a list context, the contents of the original input text (the first
argument) are not modified in any way.

However, if the input text was passed in a variable, that variable's
C<pos> value is updated to point at the first character after the
extracted text. That means that in a list context the various
subroutines can be used much like regular expressions. For example:

    while ( $next = (extract_quotelike($text))[0] )
    {
        # process next quote-like (in $next)
    }

=head2 General Behaviour in Scalar and Void Contexts

In a scalar context, the extracted string is returned, having first been
removed from the input text. Thus, the following code also processes
each quote-like operation, but actually removes them from $text:

    while ( $next = extract_quotelike($text) )
    {
        # process next quote-like (in $next)
    }

Note that if the input text is a read-only string (i.e. a literal),
no attempt is made to remove the extracted text.

In a void context the behaviour of the extraction subroutines is
exactly the same as in a scalar context, except (of course) that the
extracted substring is not returned.

=head2 A Note About Prefixes

Prefix patterns are matched without any trailing modifiers (C</gimsox> etc.)
This can bite you if you're expecting a prefix specification like
'.*?(?=<H1>)' to skip everything up to the first <H1> tag. Such a prefix
pattern will only succeed if the <H1> tag is on the current line, since
. normally doesn't match newlines.

To overcome this limitation, you need to turn on /s matching within
the prefix pattern, using the C<(?s)> directive: '(?s).*?(?=<H1>)'

=head2 Functions

=over 4

=item C<extract_delimited>

The C<extract_delimited> function formalizes the common idiom
of extracting a single-character-delimited substring from the start of
a string. For example, to extract a single-quote delimited string, the
following code is typically used:

    ($remainder = $text) =~ s/\A('(\\.|[^'])*')//s;
    $extracted = $1;

but with C<extract_delimited> it can be simplified to:

    ($extracted,$remainder) = extract_delimited($text, "'");

C<extract_delimited> takes up to four scalars (the input text, the
delimiters, a prefix pattern to be skipped, and any escape characters)
and extracts the initial substring of the text that
is appropriately delimited. If the delimiter string has multiple
characters, the first one encountered in the text is taken to delimit
the substring.
The third argument specifies a prefix pattern that is to be skipped
(but must be present!) before the substring is extracted.
The final argument specifies the escape character to be used for each
delimiter.

All arguments are optional. If the escape characters are not specified,
every delimiter is escaped with a backslash (C<\>).
If the prefix is not specified, the
pattern C<'\s*'> - optional whitespace - is used. If the delimiter set
is also not specified, the set C</["'`]/> is used. If the text to be processed
is not specified either, C<$_> is used.

In list context, C<extract_delimited> returns a array of three
elements, the extracted substring (I<including the surrounding
delimiters>), the remainder of the text, and the skipped prefix (if
any). If a suitable delimited substring is not found, the first
element of the array is the empty string, the second is the complete
original text, and the prefix returned in the third element is an
empty string.

In a scalar context, just the extracted substring is returned. In
a void context, the extracted substring (and any prefix) are simply
removed from the beginning of the first argument.

Examples:

    # Remove a single-quoted substring from the very beginning of $text:

        $substring = extract_delimited($text, "'", '');

    # Remove a single-quoted Pascalish substring (i.e. one in which
    # doubling the quote character escapes it) from the very
    # beginning of $text:

        $substring = extract_delimited($text, "'", '', "'");

    # Extract a single- or double- quoted substring from the
    # beginning of $text, optionally after some whitespace
    # (note the list context to protect $text from modification):

        ($substring) = extract_delimited $text, q{"'};

    # Delete the substring delimited by the first '/' in $text:

        $text = join '', (extract_delimited($text,'/','[^/]*')[2,1];

Note that this last example is I<not> the same as deleting the first
quote-like pattern. For instance, if C<$text> contained the string:

    "if ('./cmd' =~ m/$UNIXCMD/s) { $cmd = $1; }"

then after the deletion it would contain:

    "if ('.$UNIXCMD/s) { $cmd = $1; }"

not:

    "if ('./cmd' =~ ms) { $cmd = $1; }"

See L<"extract_quotelike"> for a (partial) solution to this problem.

=item C<extract_bracketed>

Like C<"extract_delimited">, the C<extract_bracketed> function takes
up to three optional scalar arguments: a string to extract from, a delimiter
specifier, and a prefix pattern. As before, a missing prefix defaults to
optional whitespace and a missing text defaults to C<$_>. However, a missing
delimiter specifier defaults to C<'{}()[]E<lt>E<gt>'> (see below).

C<extract_bracketed> extracts a balanced-bracket-delimited
substring (using any one (or more) of the user-specified delimiter
brackets: '(..)', '{..}', '[..]', or '<..>'). Optionally it will also
respect quoted unbalanced brackets (see below).

A "delimiter bracket" is a bracket in list of delimiters passed as
C<extract_bracketed>'s second argument. Delimiter brackets are
specified by giving either the left or right (or both!) versions
of the required bracket(s). Note that the order in which
two or more delimiter brackets are specified is not significant.

A "balanced-bracket-delimited substring" is a substring bounded by
matched brackets, such that any other (left or right) delimiter
bracket I<within> the substring is also matched by an opposite
(right or left) delimiter bracket I<at the same level of nesting>. Any
type of bracket not in the delimiter list is treated as an ordinary
character.

In other words, each type of bracket specified as a delimiter must be
balanced and correctly nested within the substring, and any other kind of
("non-delimiter") bracket in the substring is ignored.

For example, given the string:

    $text = "{ an '[irregularly :-(] {} parenthesized >:-)' string }";

then a call to C<extract_bracketed> in a list context:

    @result = extract_bracketed( $text, '{}' );

would return:

    ( "{ an '[irregularly :-(] {} parenthesized >:-)' string }" , "" , "" )

since both sets of C<'{..}'> brackets are properly nested and evenly balanced.
(In a scalar context just the first element of the array would be returned. In
a void context, C<$text> would be replaced by an empty string.)

Likewise the call in:

    @result = extract_bracketed( $text, '{[' );

would return the same result, since all sets of both types of specified
delimiter brackets are correctly nested and balanced.

However, the call in:

    @result = extract_bracketed( $text, '{([<' );

would fail, returning:

    ( undef , "{ an '[irregularly :-(] {} parenthesized >:-)' string }"  );

because the embedded pairs of C<'(..)'>s and C<'[..]'>s are "cross-nested" and
the embedded C<'E<gt>'> is unbalanced. (In a scalar context, this call would
return an empty string. In a void context, C<$text> would be unchanged.)

Note that the embedded single-quotes in the string don't help in this
case, since they have not been specified as acceptable delimiters and are
therefore treated as non-delimiter characters (and ignored).

However, if a particular species of quote character is included in the
delimiter specification, then that type of quote will be correctly handled.
for example, if C<$text> is:

    $text = '<A HREF=">>>>">link</A>';

then

    @result = extract_bracketed( $text, '<">' );

returns:

    ( '<A HREF=">>>>">', 'link</A>', "" )

as expected. Without the specification of C<"> as an embedded quoter:

    @result = extract_bracketed( $text, '<>' );

the result would be:

    ( '<A HREF=">', '>>>">link</A>', "" )

In addition to the quote delimiters C<'>, C<">, and C<`>, full Perl quote-like
quoting (i.e. q{string}, qq{string}, etc) can be specified by including the
letter 'q' as a delimiter. Hence:

    @result = extract_bracketed( $text, '<q>' );

would correctly match something like this:

    $text = '<leftop: conj /and/ conj>';

See also: C<"extract_quotelike"> and C<"extract_codeblock">.

=item C<extract_variable>

C<extract_variable> extracts any valid Perl variable or
variable-involved expression, including scalars, arrays, hashes, array
accesses, hash look-ups, method calls through objects, subroutine calls
through subroutine references, etc.

The subroutine takes up to two optional arguments:

=over 4

=item 1.

A string to be processed (C<$_> if the string is omitted or C<undef>)

=item 2.

A string specifying a pattern to be matched as a prefix (which is to be
skipped). If omitted, optional whitespace is skipped.

=back

On success in a list context, an array of 3 elements is returned. The
elements are:

=over 4

=item [0]

the extracted variable, or variablish expression

=item [1]

the remainder of the input text,

=item [2]

the prefix substring (if any),

=back

On failure, all of these values (except the remaining text) are C<undef>.

In a scalar context, C<extract_variable> returns just the complete
substring that matched a variablish expression. C<undef> is returned on
failure. In addition, the original input text has the returned substring
(and any prefix) removed from it.

In a void context, the input text just has the matched substring (and
any specified prefix) removed.

=item C<extract_tagged>

C<extract_tagged> extracts and segments text between (balanced)
specified tags.

The subroutine takes up to five optional arguments:

=over 4

=item 1.

A string to be processed (C<$_> if the string is omitted or C<undef>)

=item 2.

A string specifying a pattern to be matched as the opening tag.
If the pattern string is omitted (or C<undef>) then a pattern
that matches any standard XML tag is used.

=item 3.

A string specifying a pattern to be matched at the closing tag.
If the pattern string is omitted (or C<undef>) then the closing
tag is constructed by inserting a C</> after any leading bracket
characters in the actual opening tag that was matched (I<not> the pattern
that matched the tag). For example, if the opening tag pattern
is specified as C<'{{\w+}}'> and actually matched the opening tag
C<"{{DATA}}">, then the constructed closing tag would be C<"{{/DATA}}">.

=item 4.

A string specifying a pattern to be matched as a prefix (which is to be
skipped). If omitted, optional whitespace is skipped.

=item 5.

A hash reference containing various parsing options (see below)

=back

The various options that can be specified are:

=over 4

=item C<reject =E<gt> $listref>

The list reference contains one or more strings specifying patterns
that must I<not> appear within the tagged text.

For example, to extract
an HTML link (which should not contain nested links) use:

        extract_tagged($text, '<A>', '</A>', undef, {reject => ['<A>']} );

=item C<ignore =E<gt> $listref>

The list reference contains one or more strings specifying patterns
that are I<not> to be treated as nested tags within the tagged text
(even if they would match the start tag pattern).

For example, to extract an arbitrary XML tag, but ignore "empty" elements:

        extract_tagged($text, undef, undef, undef, {ignore => ['<[^>]*/>']} );

(also see L<"gen_delimited_pat"> below).

=item C<fail =E<gt> $str>

The C<fail> option indicates the action to be taken if a matching end
tag is not encountered (i.e. before the end of the string or some
C<reject> pattern matches). By default, a failure to match a closing
tag causes C<extract_tagged> to immediately fail.

However, if the string value associated with <reject> is "MAX", then
C<extract_tagged> returns the complete text up to the point of failure.
If the string is "PARA", C<extract_tagged> returns only the first paragraph
after the tag (up to the first line that is either empty or contains
only whitespace characters).
If the string is "", the default behaviour (i.e. failure) is reinstated.

For example, suppose the start tag "/para" introduces a paragraph, which then
continues until the next "/endpara" tag or until another "/para" tag is
encountered:

        $text = "/para line 1\n\nline 3\n/para line 4";

        extract_tagged($text, '/para', '/endpara', undef,
                                {reject => '/para', fail => MAX );

        # EXTRACTED: "/para line 1\n\nline 3\n"

Suppose instead, that if no matching "/endpara" tag is found, the "/para"
tag refers only to the immediately following paragraph:

        $text = "/para line 1\n\nline 3\n/para line 4";

        extract_tagged($text, '/para', '/endpara', undef,
                        {reject => '/para', fail => MAX );

        # EXTRACTED: "/para line 1\n"

Note that the specified C<fail> behaviour applies to nested tags as well.

=back

On success in a list context, an array of 6 elements is returned. The elements are:

=over 4

=item [0]

the extracted tagged substring (including the outermost tags),

=item [1]

the remainder of the input text,

=item [2]

the prefix substring (if any),

=item [3]

the opening tag

=item [4]

the text between the opening and closing tags

=item [5]

the closing tag (or "" if no closing tag was found)

=back

On failure, all of these values (except the remaining text) are C<undef>.

In a scalar context, C<extract_tagged> returns just the complete
substring that matched a tagged text (including the start and end
tags). C<undef> is returned on failure. In addition, the original input
text has the returned substring (and any prefix) removed from it.

In a void context, the input text just has the matched substring (and
any specified prefix) removed.

=item C<gen_extract_tagged>

C<gen_extract_tagged> generates a new anonymous subroutine which
extracts text between (balanced) specified tags. In other words,
it generates a function identical in function to C<extract_tagged>.

The difference between C<extract_tagged> and the anonymous
subroutines generated by
C<gen_extract_tagged>, is that those generated subroutines:

=over 4

=item *

do not have to reparse tag specification or parsing options every time
they are called (whereas C<extract_tagged> has to effectively rebuild
its tag parser on every call);

=item *

make use of the new qr// construct to pre-compile the regexes they use
(whereas C<extract_tagged> uses standard string variable interpolation
to create tag-matching patterns).

=back

The subroutine takes up to four optional arguments (the same set as
C<extract_tagged> except for the string to be processed). It returns
a reference to a subroutine which in turn takes a single argument (the text to
be extracted from).

In other words, the implementation of C<extract_tagged> is exactly
equivalent to:

        sub extract_tagged
        {
                my $text = shift;
                $extractor = gen_extract_tagged(@_);
                return $extractor->($text);
        }

(although C<extract_tagged> is not currently implemented that way).

Using C<gen_extract_tagged> to create extraction functions for specific tags
is a good idea if those functions are going to be called more than once, since
their performance is typically twice as good as the more general-purpose
C<extract_tagged>.

=item C<extract_quotelike>

C<extract_quotelike> attempts to recognize, extract, and segment any
one of the various Perl quotes and quotelike operators (see
L<perlop(3)>) Nested backslashed delimiters, embedded balanced bracket
delimiters (for the quotelike operators), and trailing modifiers are
all caught. For example, in:

        extract_quotelike 'q # an octothorpe: \# (not the end of the q!) #'

        extract_quotelike '  "You said, \"Use sed\"."  '

        extract_quotelike ' s{([A-Z]{1,8}\.[A-Z]{3})} /\L$1\E/; '

        extract_quotelike ' tr/\\\/\\\\/\\\//ds; '

the full Perl quotelike operations are all extracted correctly.

Note too that, when using the /x modifier on a regex, any comment
containing the current pattern delimiter will cause the regex to be
immediately terminated. In other words:

        'm /
                (?i)            # CASE INSENSITIVE
                [a-z_]          # LEADING ALPHABETIC/UNDERSCORE
                [a-z0-9]*       # FOLLOWED BY ANY NUMBER OF ALPHANUMERICS
           /x'

will be extracted as if it were:

        'm /
                (?i)            # CASE INSENSITIVE
                [a-z_]          # LEADING ALPHABETIC/'

This behaviour is identical to that of the actual compiler.

C<extract_quotelike> takes two arguments: the text to be processed and
a prefix to be matched at the very beginning of the text. If no prefix
is specified, optional whitespace is the default. If no text is given,
C<$_> is used.

In a list context, an array of 11 elements is returned. The elements are:

=over 4

=item [0]

the extracted quotelike substring (including trailing modifiers),

=item [1]

the remainder of the input text,

=item [2]

the prefix substring (if any),

=item [3]

the name of the quotelike operator (if any),

=item [4]

the left delimiter of the first block of the operation,

=item [5]

the text of the first block of the operation
(that is, the contents of
a quote, the regex of a match or substitution or the target list of a
translation),

=item [6]

the right delimiter of the first block of the operation,

=item [7]

the left delimiter of the second block of the operation
(that is, if it is a C<s>, C<tr>, or C<y>),

=item [8]

the text of the second block of the operation
(that is, the replacement of a substitution or the translation list
of a translation),

=item [9]

the right delimiter of the second block of the operation (if any),

=item [10]

the trailing modifiers on the operation (if any).

=back

For each of the fields marked "(if any)" the default value on success is
an empty string.
On failure, all of these values (except the remaining text) are C<undef>.

In a scalar context, C<extract_quotelike> returns just the complete substring
that matched a quotelike operation (or C<undef> on failure). In a scalar or
void context, the input text has the same substring (and any specified
prefix) removed.

Examples:

        # Remove the first quotelike literal that appears in text

                $quotelike = extract_quotelike($text,'.*?');

        # Replace one or more leading whitespace-separated quotelike
        # literals in $_ with "<QLL>"

                do { $_ = join '<QLL>', (extract_quotelike)[2,1] } until $@;


        # Isolate the search pattern in a quotelike operation from $text

                ($op,$pat) = (extract_quotelike $text)[3,5];
                if ($op =~ /[ms]/)
                {
                        print "search pattern: $pat\n";
                }
                else
                {
                        print "$op is not a pattern matching operation\n";
                }

=item C<extract_quotelike>

C<extract_quotelike> can successfully extract "here documents" from an input
string, but with an important caveat in list contexts.

Unlike other types of quote-like literals, a here document is rarely
a contiguous substring. For example, a typical piece of code using
here document might look like this:

        <<'EOMSG' || die;
        This is the message.
        EOMSG
        exit;

Given this as an input string in a scalar context, C<extract_quotelike>
would correctly return the string "<<'EOMSG'\nThis is the message.\nEOMSG",
leaving the string " || die;\nexit;" in the original variable. In other words,
the two separate pieces of the here document are successfully extracted and
concatenated.

In a list context, C<extract_quotelike> would return the list

=over 4

=item [0]

"<<'EOMSG'\nThis is the message.\nEOMSG\n" (i.e. the full extracted here document,
including fore and aft delimiters),

=item [1]

" || die;\nexit;" (i.e. the remainder of the input text, concatenated),

=item [2]

"" (i.e. the prefix substring -- trivial in this case),

=item [3]

"<<" (i.e. the "name" of the quotelike operator)

=item [4]

"'EOMSG'" (i.e. the left delimiter of the here document, including any quotes),

=item [5]

"This is the message.\n" (i.e. the text of the here document),

=item [6]

"EOMSG" (i.e. the right delimiter of the here document),

=item [7..10]

"" (a here document has no second left delimiter, second text, second right
delimiter, or trailing modifiers).

=back

However, the matching position of the input variable would be set to
"exit;" (i.e. I<after> the closing delimiter of the here document),
which would cause the earlier " || die;\nexit;" to be skipped in any
sequence of code fragment extractions.

To avoid this problem, when it encounters a here document whilst
extracting from a modifiable string, C<extract_quotelike> silently
rearranges the string to an equivalent piece of Perl:

        <<'EOMSG'
        This is the message.
        EOMSG
        || die;
        exit;

in which the here document I<is> contiguous. It still leaves the
matching position after the here document, but now the rest of the line
on which the here document starts is not skipped.

To prevent <extract_quotelike> from mucking about with the input in this way
(this is the only case where a list-context C<extract_quotelike> does so),
you can pass the input variable as an interpolated literal:

        $quotelike = extract_quotelike("$var");

=item C<extract_codeblock>

C<extract_codeblock> attempts to recognize and extract a balanced
bracket delimited substring that may contain unbalanced brackets
inside Perl quotes or quotelike operations. That is, C<extract_codeblock>
is like a combination of C<"extract_bracketed"> and
C<"extract_quotelike">.

C<extract_codeblock> takes the same initial three parameters as C<extract_bracketed>:
a text to process, a set of delimiter brackets to look for, and a prefix to
match first. It also takes an optional fourth parameter, which allows the
outermost delimiter brackets to be specified separately (see below).

Omitting the first argument (input text) means process C<$_> instead.
Omitting the second argument (delimiter brackets) indicates that only C<'{'> is to be used.
Omitting the third argument (prefix argument) implies optional whitespace at the start.
Omitting the fourth argument (outermost delimiter brackets) indicates that the
value of the second argument is to be used for the outermost delimiters.

Once the prefix and the outermost opening delimiter bracket have been
recognized, code blocks are extracted by stepping through the input text and
trying the following alternatives in sequence:

=over 4

=item 1.

Try and match a closing delimiter bracket. If the bracket was the same
species as the last opening bracket, return the substring to that
point. If the bracket was mismatched, return an error.

=item 2.

Try to match a quote or quotelike operator. If found, call
C<extract_quotelike> to eat it. If C<extract_quotelike> fails, return
the error it returned. Otherwise go back to step 1.

=item 3.

Try to match an opening delimiter bracket. If found, call
C<extract_codeblock> recursively to eat the embedded block. If the
recursive call fails, return an error. Otherwise, go back to step 1.

=item 4.

Unconditionally match a bareword or any other single character, and
then go back to step 1.

=back

Examples:

        # Find a while loop in the text

                if ($text =~ s/.*?while\s*\{/{/)
                {
                        $loop = "while " . extract_codeblock($text);
                }

        # Remove the first round-bracketed list (which may include
        # round- or curly-bracketed code blocks or quotelike operators)

                extract_codeblock $text, "(){}", '[^(]*';


The ability to specify a different outermost delimiter bracket is useful
in some circumstances. For example, in the Parse::RecDescent module,
parser actions which are to be performed only on a successful parse
are specified using a C<E<lt>defer:...E<gt>> directive. For example:

        sentence: subject verb object
                        <defer: {$::theVerb = $item{verb}} >

Parse::RecDescent uses C<extract_codeblock($text, '{}E<lt>E<gt>')> to extract the code
within the C<E<lt>defer:...E<gt>> directive, but there's a problem.

A deferred action like this:

                        <defer: {if ($count>10) {$count--}} >

will be incorrectly parsed as:

                        <defer: {if ($count>

because the "less than" operator is interpreted as a closing delimiter.

But, by extracting the directive using
S<C<extract_codeblock($text, '{}', undef, 'E<lt>E<gt>')>>
the '>' character is only treated as a delimited at the outermost
level of the code block, so the directive is parsed correctly.

=item C<extract_multiple>

The C<extract_multiple> subroutine takes a string to be processed and a
list of extractors (subroutines or regular expressions) to apply to that string.

In an array context C<extract_multiple> returns an array of substrings
of the original string, as extracted by the specified extractors.
In a scalar context, C<extract_multiple> returns the first
substring successfully extracted from the original string. In both
scalar and void contexts the original string has the first successfully
extracted substring removed from it. In all contexts
C<extract_multiple> starts at the current C<pos> of the string, and
sets that C<pos> appropriately after it matches.

Hence, the aim of a call to C<extract_multiple> in a list context
is to split the processed string into as many non-overlapping fields as
possible, by repeatedly applying each of the specified extractors
to the remainder of the string. Thus C<extract_multiple> is
a generalized form of Perl's C<split> subroutine.

The subroutine takes up to four optional arguments:

=over 4

=item 1.

A string to be processed (C<$_> if the string is omitted or C<undef>)

=item 2.

A reference to a list of subroutine references and/or qr// objects and/or
literal strings and/or hash references, specifying the extractors
to be used to split the string. If this argument is omitted (or
C<undef>) the list:

        [
                sub { extract_variable($_[0], '') },
                sub { extract_quotelike($_[0],'') },
                sub { extract_codeblock($_[0],'{}','') },
        ]

is used.

=item 3.

An number specifying the maximum number of fields to return. If this
argument is omitted (or C<undef>), split continues as long as possible.

If the third argument is I<N>, then extraction continues until I<N> fields
have been successfully extracted, or until the string has been completely
processed.

Note that in scalar and void contexts the value of this argument is
automatically reset to 1 (under C<-w>, a warning is issued if the argument
has to be reset).

=item 4.

A value indicating whether unmatched substrings (see below) within the
text should be skipped or returned as fields. If the value is true,
such substrings are skipped. Otherwise, they are returned.

=back

The extraction process works by applying each extractor in
sequence to the text string.

If the extractor is a subroutine it is called in a list context and is
expected to return a list of a single element, namely the extracted
text. It may optionally also return two further arguments: a string
representing the text left after extraction (like $' for a pattern
match), and a string representing any prefix skipped before the
extraction (like $` in a pattern match). Note that this is designed
to facilitate the use of other Text::Balanced subroutines with
C<extract_multiple>. Note too that the value returned by an extractor
subroutine need not bear any relationship to the corresponding substring
of the original text (see examples below).

If the extractor is a precompiled regular expression or a string,
it is matched against the text in a scalar context with a leading
'\G' and the gc modifiers enabled. The extracted value is either
$1 if that variable is defined after the match, or else the
complete match (i.e. $&).

If the extractor is a hash reference, it must contain exactly one element.
The value of that element is one of the
above extractor types (subroutine reference, regular expression, or string).
The key of that element is the name of a class into which the successful
return value of the extractor will be blessed.

If an extractor returns a defined value, that value is immediately
treated as the next extracted field and pushed onto the list of fields.
If the extractor was specified in a hash reference, the field is also
blessed into the appropriate class,

If the extractor fails to match (in the case of a regex extractor), or returns an empty list or an undefined value (in the case of a subroutine extractor), it is
assumed to have failed to extract.
If none of the extractor subroutines succeeds, then one
character is extracted from the start of the text and the extraction
subroutines reapplied. Characters which are thus removed are accumulated and
eventually become the next field (unless the fourth argument is true, in which
case they are discarded).

For example, the following extracts substrings that are valid Perl variables:

        @fields = extract_multiple($text,
                                   [ sub { extract_variable($_[0]) } ],
                                   undef, 1);

This example separates a text into fields which are quote delimited,
curly bracketed, and anything else. The delimited and bracketed
parts are also blessed to identify them (the "anything else" is unblessed):

        @fields = extract_multiple($text,
                   [
                        { Delim => sub { extract_delimited($_[0],q{'"}) } },
                        { Brack => sub { extract_bracketed($_[0],'{}') } },
                   ]);

This call extracts the next single substring that is a valid Perl quotelike
operator (and removes it from $text):

        $quotelike = extract_multiple($text,
                                      [
                                        sub { extract_quotelike($_[0]) },
                                      ], undef, 1);

Finally, here is yet another way to do comma-separated value parsing:

        @fields = extract_multiple($csv_text,
                                  [
                                        sub { extract_delimited($_[0],q{'"}) },
                                        qr/([^,]+)(.*)/,
                                  ],
                                  undef,1);

The list in the second argument means:
I<"Try and extract a ' or " delimited string, otherwise extract anything up to a comma...">.
The undef third argument means:
I<"...as many times as possible...">,
and the true value in the fourth argument means
I<"...discarding anything else that appears (i.e. the commas)">.

If you wanted the commas preserved as separate fields (i.e. like split
does if your split pattern has capturing parentheses), you would
just make the last parameter undefined (or remove it).

=item C<gen_delimited_pat>

The C<gen_delimited_pat> subroutine takes a single (string) argument and
   > builds a Friedl-style optimized regex that matches a string delimited
by any one of the characters in the single argument. For example:

        gen_delimited_pat(q{'"})

returns the regex:

        (?:\"(?:\\\"|(?!\").)*\"|\'(?:\\\'|(?!\').)*\')

Note that the specified delimiters are automatically quotemeta'd.

A typical use of C<gen_delimited_pat> would be to build special purpose tags
for C<extract_tagged>. For example, to properly ignore "empty" XML elements
(which might contain quoted strings):

        my $empty_tag = '<(' . gen_delimited_pat(q{'"}) . '|.)+/>';

        extract_tagged($text, undef, undef, undef, {ignore => [$empty_tag]} );

C<gen_delimited_pat> may also be called with an optional second argument,
which specifies the "escape" character(s) to be used for each delimiter.
For example to match a Pascal-style string (where ' is the delimiter
and '' is a literal ' within the string):

        gen_delimited_pat(q{'},q{'});

Different escape characters can be specified for different delimiters.
For example, to specify that '/' is the escape for single quotes
and '%' is the escape for double quotes:

        gen_delimited_pat(q{'"},q{/%});

If more delimiters than escape chars are specified, the last escape char
is used for the remaining delimiters.
If no escape char is specified for a given specified delimiter, '\' is used.

=item C<delimited_pat>

Note that C<gen_delimited_pat> was previously called C<delimited_pat>.
That name may still be used, but is now deprecated.

=back

=head1 DIAGNOSTICS

In a list context, all the functions return C<(undef,$original_text)>
on failure. In a scalar context, failure is indicated by returning C<undef>
(in this case the input text is not modified in any way).

In addition, on failure in I<any> context, the C<$@> variable is set.
Accessing C<$@-E<gt>{error}> returns one of the error diagnostics listed
below.
Accessing C<$@-E<gt>{pos}> returns the offset into the original string at
which the error was detected (although not necessarily where it occurred!)
Printing C<$@> directly produces the error message, with the offset appended.
On success, the C<$@> variable is guaranteed to be C<undef>.

The available diagnostics are:

=over 4

=item  C<Did not find a suitable bracket: "%s">

The delimiter provided to C<extract_bracketed> was not one of
C<'()[]E<lt>E<gt>{}'>.

=item  C<Did not find prefix: /%s/>

A non-optional prefix was specified but wasn't found at the start of the text.

=item  C<Did not find opening bracket after prefix: "%s">

C<extract_bracketed> or C<extract_codeblock> was expecting a
particular kind of bracket at the start of the text, and didn't find it.

=item  C<No quotelike operator found after prefix: "%s">

C<extract_quotelike> didn't find one of the quotelike operators C<q>,
C<qq>, C<qw>, C<qx>, C<s>, C<tr> or C<y> at the start of the substring
it was extracting.

=item  C<Unmatched closing bracket: "%c">

C<extract_bracketed>, C<extract_quotelike> or C<extract_codeblock> encountered
a closing bracket where none was expected.

=item  C<Unmatched opening bracket(s): "%s">

C<extract_bracketed>, C<extract_quotelike> or C<extract_codeblock> ran
out of characters in the text before closing one or more levels of nested
brackets.

=item C<Unmatched embedded quote (%s)>

C<extract_bracketed> attempted to match an embedded quoted substring, but
failed to find a closing quote to match it.

=item C<Did not find closing delimiter to match '%s'>

C<extract_quotelike> was unable to find a closing delimiter to match the
one that opened the quote-like operation.

=item  C<Mismatched closing bracket: expected "%c" but found "%s">

C<extract_bracketed>, C<extract_quotelike> or C<extract_codeblock> found
a valid bracket delimiter, but it was the wrong species. This usually
indicates a nesting error, but may indicate incorrect quoting or escaping.

=item  C<No block delimiter found after quotelike "%s">

C<extract_quotelike> or C<extract_codeblock> found one of the
quotelike operators C<q>, C<qq>, C<qw>, C<qx>, C<s>, C<tr> or C<y>
without a suitable block after it.

=item C<Did not find leading dereferencer>

C<extract_variable> was expecting one of '$', '@', or '%' at the start of
a variable, but didn't find any of them.

=item C<Bad identifier after dereferencer>

C<extract_variable> found a '$', '@', or '%' indicating a variable, but that
character was not followed by a legal Perl identifier.

=item C<Did not find expected opening bracket at %s>

C<extract_codeblock> failed to find any of the outermost opening brackets
that were specified.

=item C<Improperly nested codeblock at %s>

A nested code block was found that started with a delimiter that was specified
as being only to be used as an outermost bracket.

=item  C<Missing second block for quotelike "%s">

C<extract_codeblock> or C<extract_quotelike> found one of the
quotelike operators C<s>, C<tr> or C<y> followed by only one block.

=item C<No match found for opening bracket>

C<extract_codeblock> failed to find a closing bracket to match the outermost
opening bracket.

=item C<Did not find opening tag: /%s/>

C<extract_tagged> did not find a suitable opening tag (after any specified
prefix was removed).

=item C<Unable to construct closing tag to match: /%s/>

C<extract_tagged> matched the specified opening tag and tried to
modify the matched text to produce a matching closing tag (because
none was specified). It failed to generate the closing tag, almost
certainly because the opening tag did not start with a
bracket of some kind.

=item C<Found invalid nested tag: %s>

C<extract_tagged> found a nested tag that appeared in the "reject" list
(and the failure mode was not "MAX" or "PARA").

=item C<Found unbalanced nested tag: %s>

C<extract_tagged> found a nested opening tag that was not matched by a
corresponding nested closing tag (and the failure mode was not "MAX" or "PARA").

=item C<Did not find closing tag>

C<extract_tagged> reached the end of the text without finding a closing tag
to match the original opening tag (and the failure mode was not
"MAX" or "PARA").

=back

=head1 EXPORTS

The following symbols are, or can be, exported by this module:

=over 4

=item Default Exports

I<None>.

=item Optional Exports

C<extract_delimited>,
C<extract_bracketed>,
C<extract_quotelike>,
C<extract_codeblock>,
C<extract_variable>,
C<extract_tagged>,
C<extract_multiple>,
C<gen_delimited_pat>,
C<gen_extract_tagged>,
C<delimited_pat>.

=item Export Tags

=over 4

=item C<:ALL>

C<extract_delimited>,
C<extract_bracketed>,
C<extract_quotelike>,
C<extract_codeblock>,
C<extract_variable>,
C<extract_tagged>,
C<extract_multiple>,
C<gen_delimited_pat>,
C<gen_extract_tagged>,
C<delimited_pat>.

=back

=back

=head1 KNOWN BUGS

See L<https://rt.cpan.org/Dist/Display.html?Status=Active&Queue=Text-Balanced>.

=head1 FEEDBACK

Patches, bug reports, suggestions or any other feedback is welcome.

Patches can be sent as GitHub pull requests at
L<https://github.com/steve-m-hay/Text-Balanced/pulls>.

Bug reports and suggestions can be made on the CPAN Request Tracker at
L<https://rt.cpan.org/Public/Bug/Report.html?Queue=Text-Balanced>.

Currently active requests on the CPAN Request Tracker can be viewed at
L<https://rt.cpan.org/Public/Dist/Display.html?Status=Active;Queue=Text-Balanced>.

Please test this distribution.  See CPAN Testers Reports at
L<https://www.cpantesters.org/> for details of how to get involved.

Previous test results on CPAN Testers Reports can be viewed at
L<https://www.cpantesters.org/distro/T/Text-Balanced.html>.

Please rate this distribution on CPAN Ratings at
L<https://cpanratings.perl.org/rate/?distribution=Text-Balanced>.

=head1 AVAILABILITY

The latest version of this module is available from CPAN (see
L<perlmodlib/"CPAN"> for details) at

L<https://metacpan.org/release/Text-Balanced> or

L<https://www.cpan.org/authors/id/S/SH/SHAY/> or

L<https://www.cpan.org/modules/by-module/Text/>.

The latest source code is available from GitHub at
L<https://github.com/steve-m-hay/Text-Balanced>.

=head1 INSTALLATION

See the F<INSTALL> file.

=head1 AUTHOR

Damian Conway E<lt>L<damian@conway.org|mailto:damian@conway.org>E<gt>.

Steve Hay E<lt>L<shay@cpan.org|mailto:shay@cpan.org>E<gt> is now maintaining
Text::Balanced as of version 2.03.

=head1 COPYRIGHT

Copyright (C) 1997-2001 Damian Conway.  All rights reserved.

Copyright (C) 2009 Adam Kennedy.

Copyright (C) 2015, 2020 Steve Hay.  All rights reserved.

=head1 LICENCE

This module is free software; you can redistribute it and/or modify it under the
same terms as Perl itself, i.e. under the terms of either the GNU General Public
License or the Artistic License, as specified in the F<LICENCE> file.

=head1 VERSION

Version 2.04

=head1 DATE

11 Dec 2020

=head1 HISTORY

See the F<Changes> file.

=cut
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   package Tie::File;

require 5.005;

use strict;
use warnings;

use Carp ':DEFAULT', 'confess';
use POSIX 'SEEK_SET';
use Fcntl 'O_CREAT', 'O_RDWR', 'LOCK_EX', 'LOCK_SH', 'O_WRONLY', 'O_RDONLY';
sub O_ACCMODE () { O_RDONLY | O_RDWR | O_WRONLY }


our $VERSION = "1.06";
my $DEFAULT_MEMORY_SIZE = 1<<21;    # 2 megabytes
my $DEFAULT_AUTODEFER_THRESHHOLD = 3; # 3 records
my $DEFAULT_AUTODEFER_FILELEN_THRESHHOLD = 65536; # 16 disk blocksful

my %good_opt = map {$_ => 1, "-$_" => 1}
                 qw(memory dw_size mode recsep discipline 
                    autodefer autochomp autodefer_threshhold concurrent);

our $DIAGNOSTIC = 0;
our @OFF; # used as a temporary alias in some subroutines.
our @H; # used as a temporary alias in _annotate_ad_history

sub TIEARRAY {
  if (@_ % 2 != 0) {
    croak "usage: tie \@array, $_[0], filename, [option => value]...";
  }
  my ($pack, $file, %opts) = @_;

  # transform '-foo' keys into 'foo' keys
  for my $key (keys %opts) {
    unless ($good_opt{$key}) {
      croak("$pack: Unrecognized option '$key'\n");
    }
    my $okey = $key;
    if ($key =~ s/^-+//) {
      $opts{$key} = delete $opts{$okey};
    }
  }

  if ($opts{concurrent}) {
    croak("$pack: concurrent access not supported yet\n");
  }

  unless (defined $opts{memory}) {
    # default is the larger of the default cache size and the 
    # deferred-write buffer size (if specified)
    $opts{memory} = $DEFAULT_MEMORY_SIZE;
    $opts{memory} = $opts{dw_size}
      if defined $opts{dw_size} && $opts{dw_size} > $DEFAULT_MEMORY_SIZE;
    # Dora Winifred Read
  }
  $opts{dw_size} = $opts{memory} unless defined $opts{dw_size};
  if ($opts{dw_size} > $opts{memory}) {
      croak("$pack: dw_size may not be larger than total memory allocation\n");
  }
  # are we in deferred-write mode?
  $opts{defer} = 0 unless defined $opts{defer};
  $opts{deferred} = {};         # no records are presently deferred
  $opts{deferred_s} = 0;        # count of total bytes in ->{deferred}
  $opts{deferred_max} = -1;     # empty

  # What's a good way to arrange that this class can be overridden?
  $opts{cache} = Tie::File::Cache->new($opts{memory});

  # autodeferment is enabled by default
  $opts{autodefer} = 1 unless defined $opts{autodefer};
  $opts{autodeferring} = 0;     # but is not initially active
  $opts{ad_history} = [];
  $opts{autodefer_threshhold} = $DEFAULT_AUTODEFER_THRESHHOLD
    unless defined $opts{autodefer_threshhold};
  $opts{autodefer_filelen_threshhold} = $DEFAULT_AUTODEFER_FILELEN_THRESHHOLD
    unless defined $opts{autodefer_filelen_threshhold};

  $opts{offsets} = [0];
  $opts{filename} = $file;
  unless (defined $opts{recsep}) { 
    $opts{recsep} = _default_recsep();
  }
  $opts{recseplen} = length($opts{recsep});
  if ($opts{recseplen} == 0) {
    croak "Empty record separator not supported by $pack";
  }

  $opts{autochomp} = 1 unless defined $opts{autochomp};

  $opts{mode} = O_CREAT|O_RDWR unless defined $opts{mode};
  $opts{rdonly} = (($opts{mode} & O_ACCMODE) == O_RDONLY);
  $opts{sawlastrec} = undef;

  my $fh;

  if (UNIVERSAL::isa($file, 'GLOB')) {
    # We use 1 here on the theory that some systems 
    # may not indicate failure if we use 0.
    # MSWin32 does not indicate failure with 0, but I don't know if
    # it will indicate failure with 1 or not.
    unless (seek $file, 1, SEEK_SET) {
      croak "$pack: your filehandle does not appear to be seekable";
    }
    seek $file, 0, SEEK_SET;    # put it back
    $fh = $file;                # setting binmode is the user's problem
  } elsif (ref $file) {
    croak "usage: tie \@array, $pack, filename, [option => value]...";
  } else {
    # $fh = \do { local *FH };  # XXX this is buggy
    if ($] < 5.006) {
	# perl 5.005 and earlier don't autovivify filehandles
	require Symbol;
	$fh = Symbol::gensym();
    }
    sysopen $fh, $file, $opts{mode}, 0666 or return;
    binmode $fh;
    ++$opts{ourfh};
  }
  { my $ofh = select $fh; $| = 1; select $ofh } # autoflush on write
  if (defined $opts{discipline} && $] >= 5.006) {
    # This avoids a compile-time warning under 5.005
    eval 'binmode($fh, $opts{discipline})';
    croak $@ if $@ =~ /unknown discipline/i;
    die if $@;
  }
  $opts{fh} = $fh;

  bless \%opts => $pack;
}

sub FETCH {
  my ($self, $n) = @_;
  my $rec;

  # check the defer buffer
  $rec = $self->{deferred}{$n} if exists $self->{deferred}{$n};
  $rec = $self->_fetch($n) unless defined $rec;

  # inlined _chomp1
  substr($rec, - $self->{recseplen}) = ""
    if defined $rec && $self->{autochomp};
  $rec;
}

# Chomp many records in-place; return nothing useful
sub _chomp {
  my $self = shift;
  return unless $self->{autochomp};
  if ($self->{autochomp}) {
    for (@_) {
      next unless defined;
      substr($_, - $self->{recseplen}) = "";
    }
  }
}

# Chomp one record in-place; return modified record
sub _chomp1 {
  my ($self, $rec) = @_;
  return $rec unless $self->{autochomp};
  return unless defined $rec;
  substr($rec, - $self->{recseplen}) = "";
  $rec;
}

sub _fetch {
  my ($self, $n) = @_;

  # check the record cache
  { my $cached = $self->{cache}->lookup($n);
    return $cached if defined $cached;
  }

  if ($#{$self->{offsets}} < $n) {
    return if $self->{eof};  # request for record beyond end of file
    my $o = $self->_fill_offsets_to($n);
    # If it's still undefined, there is no such record, so return 'undef'
    return unless defined $o;
  }

  my $fh = $self->{FH};
  $self->_seek($n);             # we can do this now that offsets is populated
  my $rec = $self->_read_record;

# If we happen to have just read the first record, check to see if
# the length of the record matches what 'tell' says.  If not, Tie::File
# won't work, and should drop dead.
#
#  if ($n == 0 && defined($rec) && tell($self->{fh}) != length($rec)) {
#    if (defined $self->{discipline}) {
#      croak "I/O discipline $self->{discipline} not supported";
#    } else {
#      croak "File encoding not supported";
#    }
#  }

  $self->{cache}->insert($n, $rec) if defined $rec && not $self->{flushing};
  $rec;
}

sub STORE {
  my ($self, $n, $rec) = @_;
  die "STORE called from _check_integrity!" if $DIAGNOSTIC;

  $self->_fixrecs($rec);

  if ($self->{autodefer}) {
    $self->_annotate_ad_history($n);
  }

  return $self->_store_deferred($n, $rec) if $self->_is_deferring;


  # We need this to decide whether the new record will fit
  # It incidentally populates the offsets table 
  # Note we have to do this before we alter the cache
  # 20020324 Wait, but this DOES alter the cache.  TODO BUG?
  my $oldrec = $self->_fetch($n);

  if (not defined $oldrec) {
    # We're storing a record beyond the end of the file
    $self->_extend_file_to($n+1);
    $oldrec = $self->{recsep};
  }
#  return if $oldrec eq $rec;    # don't bother
  my $len_diff = length($rec) - length($oldrec);

  # length($oldrec) here is not consistent with text mode  TODO XXX BUG
  $self->_mtwrite($rec, $self->{offsets}[$n], length($oldrec));
  $self->_oadjust([$n, 1, $rec]);
  $self->{cache}->update($n, $rec);
}

sub _store_deferred {
  my ($self, $n, $rec) = @_;
  $self->{cache}->remove($n);
  my $old_deferred = $self->{deferred}{$n};

  if (defined $self->{deferred_max} && $n > $self->{deferred_max}) {
    $self->{deferred_max} = $n;
  }
  $self->{deferred}{$n} = $rec;

  my $len_diff = length($rec);
  $len_diff -= length($old_deferred) if defined $old_deferred;
  $self->{deferred_s} += $len_diff;
  $self->{cache}->adj_limit(-$len_diff);
  if ($self->{deferred_s} > $self->{dw_size}) {
    $self->_flush;
  } elsif ($self->_cache_too_full) {
    $self->_cache_flush;
  }
}

# Remove a single record from the deferred-write buffer without writing it
# The record need not be present
sub _delete_deferred {
  my ($self, $n) = @_;
  my $rec = delete $self->{deferred}{$n};
  return unless defined $rec;

  if (defined $self->{deferred_max} 
      && $n == $self->{deferred_max}) {
    undef $self->{deferred_max};
  }

  $self->{deferred_s} -= length $rec;
  $self->{cache}->adj_limit(length $rec);
}

sub FETCHSIZE {
  my $self = shift;
  my $n = $self->{eof} ? $#{$self->{offsets}} : $self->_fill_offsets;

  my $top_deferred = $self->_defer_max;
  $n = $top_deferred+1 if defined $top_deferred && $n < $top_deferred+1;
  $n;
}

sub STORESIZE {
  my ($self, $len) = @_;

  if ($self->{autodefer}) {
    $self->_annotate_ad_history('STORESIZE');
  }

  my $olen = $self->FETCHSIZE;
  return if $len == $olen;      # Woo-hoo!

  # file gets longer
  if ($len > $olen) {
    if ($self->_is_deferring) {
      for ($olen .. $len-1) {
        $self->_store_deferred($_, $self->{recsep});
      }
    } else {
      $self->_extend_file_to($len);
    }
    return;
  }

  # file gets shorter
  if ($self->_is_deferring) {
    # TODO maybe replace this with map-plus-assignment?
    for (grep $_ >= $len, keys %{$self->{deferred}}) {
      $self->_delete_deferred($_);
    }
    $self->{deferred_max} = $len-1;
  }

  $self->_seek($len);
  $self->_chop_file;
  $#{$self->{offsets}} = $len;
#  $self->{offsets}[0] = 0;      # in case we just chopped this

  $self->{cache}->remove(grep $_ >= $len, $self->{cache}->ckeys);
}

### OPTIMIZE ME
### It should not be necessary to do FETCHSIZE
### Just seek to the end of the file.
sub PUSH {
  my $self = shift;
  $self->SPLICE($self->FETCHSIZE, scalar(@_), @_);

  # No need to return:
  #  $self->FETCHSIZE;  # because av.c takes care of this for me
}

sub POP {
  my $self = shift;
  my $size = $self->FETCHSIZE;
  return if $size == 0;
#  print STDERR "# POPPITY POP POP POP\n";
  scalar $self->SPLICE($size-1, 1);
}

sub SHIFT {
  my $self = shift;
  scalar $self->SPLICE(0, 1);
}

sub UNSHIFT {
  my $self = shift;
  $self->SPLICE(0, 0, @_);
  # $self->FETCHSIZE; # av.c takes care of this for me
}

sub CLEAR {
  my $self = shift;

  if ($self->{autodefer}) {
    $self->_annotate_ad_history('CLEAR');
  }

  $self->_seekb(0);
  $self->_chop_file;
    $self->{cache}->set_limit($self->{memory});
    $self->{cache}->empty;
  @{$self->{offsets}} = (0);
  %{$self->{deferred}}= ();
    $self->{deferred_s} = 0;
    $self->{deferred_max} = -1;
}

sub EXTEND {
  my ($self, $n) = @_;

  # No need to pre-extend anything in this case
  return if $self->_is_deferring;

  $self->_fill_offsets_to($n);
  $self->_extend_file_to($n);
}

sub DELETE {
  my ($self, $n) = @_;

  if ($self->{autodefer}) {
    $self->_annotate_ad_history('DELETE');
  }

  my $lastrec = $self->FETCHSIZE-1;
  my $rec = $self->FETCH($n);
  $self->_delete_deferred($n) if $self->_is_deferring;
  if ($n == $lastrec) {
    $self->_seek($n);
    $self->_chop_file;
    $#{$self->{offsets}}--;
    $self->{cache}->remove($n);
    # perhaps in this case I should also remove trailing null records?
    # 20020316
    # Note that delete @a[-3..-1] deletes the records in the wrong order,
    # so we only chop the very last one out of the file.  We could repair this
    # by tracking deleted records inside the object.
  } elsif ($n < $lastrec) {
    $self->STORE($n, "");
  }
  $rec;
}

sub EXISTS {
  my ($self, $n) = @_;
  return 1 if exists $self->{deferred}{$n};
  $n < $self->FETCHSIZE;
}

sub SPLICE {
  my $self = shift;

  if ($self->{autodefer}) {
    $self->_annotate_ad_history('SPLICE');
  }

  $self->_flush if $self->_is_deferring; # move this up?
  if (wantarray) {
    $self->_chomp(my @a = $self->_splice(@_));
    @a;
  } else {
    $self->_chomp1(scalar $self->_splice(@_));
  }
}

sub DESTROY {
  my $self = shift;
  $self->flush if $self->_is_deferring;
  $self->{cache}->delink if defined $self->{cache}; # break circular link
  if ($self->{fh} and $self->{ourfh}) {
      delete $self->{ourfh};
      close delete $self->{fh};
  }
}

sub _splice {
  my ($self, $pos, $nrecs, @data) = @_;
  my @result;

  $pos = 0 unless defined $pos;

  # Deal with negative and other out-of-range positions
  # Also set default for $nrecs 
  {
    my $oldsize = $self->FETCHSIZE;
    $nrecs = $oldsize unless defined $nrecs;
    my $oldpos = $pos;

    if ($pos < 0) {
      $pos += $oldsize;
      if ($pos < 0) {
        croak "Modification of non-creatable array value attempted, " .
              "subscript $oldpos";
      }
    }

    if ($pos > $oldsize) {
      return unless @data;
      $pos = $oldsize;          # This is what perl does for normal arrays
    }

    # The manual is very unclear here
    if ($nrecs < 0) {
      $nrecs = $oldsize - $pos + $nrecs;
      $nrecs = 0 if $nrecs < 0;
    }

    # nrecs is too big---it really means "until the end"
    # 20030507
    if ($nrecs + $pos > $oldsize) {
      $nrecs = $oldsize - $pos;
    }
  }

  $self->_fixrecs(@data);
  my $data = join '', @data;
  my $datalen = length $data;
  my $oldlen = 0;

  # compute length of data being removed
  for ($pos .. $pos+$nrecs-1) {
    last unless defined $self->_fill_offsets_to($_);
    my $rec = $self->_fetch($_);
    last unless defined $rec;
    push @result, $rec;

    # Why don't we just use length($rec) here?
    # Because that record might have come from the cache.  _splice
    # might have been called to flush out the deferred-write records,
    # and in this case length($rec) is the length of the record to be
    # *written*, not the length of the actual record in the file.  But
    # the offsets are still true. 20020322
    $oldlen += $self->{offsets}[$_+1] - $self->{offsets}[$_]
      if defined $self->{offsets}[$_+1];
  }
  $self->_fill_offsets_to($pos+$nrecs);

  # Modify the file
  $self->_mtwrite($data, $self->{offsets}[$pos], $oldlen);
  # Adjust the offsets table
  $self->_oadjust([$pos, $nrecs, @data]);

  { # Take this read cache stuff out into a separate function
    # You made a half-attempt to put it into _oadjust.  
    # Finish something like that up eventually.
    # STORE also needs to do something similarish

    # update the read cache, part 1
    # modified records
    for ($pos .. $pos+$nrecs-1) {
      my $new = $data[$_-$pos];
      if (defined $new) {
        $self->{cache}->update($_, $new);
      } else {
        $self->{cache}->remove($_);
      }
    }
    
    # update the read cache, part 2
    # moved records - records past the site of the change
    # need to be renumbered
    # Maybe merge this with the previous block?
    {
      my @oldkeys = grep $_ >= $pos + $nrecs, $self->{cache}->ckeys;
      my @newkeys = map $_-$nrecs+@data, @oldkeys;
      $self->{cache}->rekey(\@oldkeys, \@newkeys);
    }

    # Now there might be too much data in the cache, if we spliced out
    # some short records and spliced in some long ones.  If so, flush
    # the cache.
    $self->_cache_flush;
  }

  # Yes, the return value of 'splice' *is* actually this complicated
  wantarray ? @result : @result ? $result[-1] : undef;
}


# write data into the file
# $data is the data to be written.
# it should be written at position $pos, and should overwrite
# exactly $len of the following bytes.  
# Note that if length($data) > $len, the subsequent bytes will have to 
# be moved up, and if length($data) < $len, they will have to
# be moved down
sub _twrite {
  my ($self, $data, $pos, $len) = @_;

  unless (defined $pos) {
    die "\$pos was undefined in _twrite";
  }

  my $len_diff = length($data) - $len;

  if ($len_diff == 0) {          # Woo-hoo!
    my $fh = $self->{fh};
    $self->_seekb($pos);
    $self->_write_record($data);
    return;                     # well, that was easy.
  }

  # the two records are of different lengths
  # our strategy here: rewrite the tail of the file,
  # reading ahead one buffer at a time
  # $bufsize is required to be at least as large as the data we're overwriting
  my $bufsize = _bufsize($len_diff);
  my ($writepos, $readpos) = ($pos, $pos+$len);
  my $next_block;
  my $more_data;

  # Seems like there ought to be a way to avoid the repeated code
  # and the special case here.  The read(1) is also a little weird.
  # Think about this.
  do {
    $self->_seekb($readpos);
    my $br = read $self->{fh}, $next_block, $bufsize;
    $more_data = read $self->{fh}, my($dummy), 1;
    $self->_seekb($writepos);
    $self->_write_record($data);
    $readpos += $br;
    $writepos += length $data;
    $data = $next_block;
  } while $more_data;
  $self->_seekb($writepos);
  $self->_write_record($next_block);

  # There might be leftover data at the end of the file
  $self->_chop_file if $len_diff < 0;
}

# _iwrite(D, S, E)
# Insert text D at position S.
# Let C = E-S-|D|.  If C < 0; die.  
# Data in [S,S+C) is copied to [S+D,S+D+C) = [S+D,E).
# Data in [S+C = E-D, E) is returned.  Data in [E, oo) is untouched.
#
# In a later version, don't read the entire intervening area into
# memory at once; do the copying block by block.
sub _iwrite {
  my $self = shift;
  my ($D, $s, $e) = @_;
  my $d = length $D;
  my $c = $e-$s-$d;
  local *FH = $self->{fh};
  confess "Not enough space to insert $d bytes between $s and $e"
    if $c < 0;
  confess "[$s,$e) is an invalid insertion range" if $e < $s;

  $self->_seekb($s);
  read FH, my $buf, $e-$s;

  $D .= substr($buf, 0, $c, "");

  $self->_seekb($s);
  $self->_write_record($D);

  return $buf;
}

# Like _twrite, but the data-pos-len triple may be repeated; you may
# write several chunks.  All the writing will be done in
# one pass.   Chunks SHALL be in ascending order and SHALL NOT overlap.
sub _mtwrite {
  my $self = shift;
  my $unwritten = "";
  my $delta = 0;

  @_ % 3 == 0 
    or die "Arguments to _mtwrite did not come in groups of three";

  while (@_) {
    my ($data, $pos, $len) = splice @_, 0, 3;
    my $end = $pos + $len;  # The OLD end of the segment to be replaced
    $data = $unwritten . $data;
    $delta -= length($unwritten);
    $unwritten  = "";
    $pos += $delta;             # This is where the data goes now
    my $dlen = length $data;
    $self->_seekb($pos);
    if ($len >= $dlen) {        # the data will fit
      $self->_write_record($data);
      $delta += ($dlen - $len); # everything following moves down by this much
      $data = ""; # All the data in the buffer has been written
    } else {                    # won't fit
      my $writable = substr($data, 0, $len - $delta, "");
      $self->_write_record($writable);
      $delta += ($dlen - $len); # everything following moves down by this much
    } 

    # At this point we've written some but maybe not all of the data.
    # There might be a gap to close up, or $data might still contain a
    # bunch of unwritten data that didn't fit.
    my $ndlen = length $data;
    if ($delta == 0) {
      $self->_write_record($data);
    } elsif ($delta < 0) {
      # upcopy (close up gap)
      if (@_) {
        $self->_upcopy($end, $end + $delta, $_[1] - $end);  
      } else {
        $self->_upcopy($end, $end + $delta);  
      }
    } else {
      # downcopy (insert data that didn't fit; replace this data in memory
      # with _later_ data that doesn't fit)
      if (@_) {
        $unwritten = $self->_downcopy($data, $end, $_[1] - $end);
      } else {
        # Make the file longer to accommodate the last segment that doesn't
        $unwritten = $self->_downcopy($data, $end);
      }
    }
  }
}

# Copy block of data of length $len from position $spos to position $dpos
# $dpos must be <= $spos
#
# If $len is undefined, go all the way to the end of the file
# and then truncate it ($spos - $dpos bytes will be removed)
sub _upcopy {
  my $blocksize = 8192;
  my ($self, $spos, $dpos, $len) = @_;
  if ($dpos > $spos) {
    die "source ($spos) was upstream of destination ($dpos) in _upcopy";
  } elsif ($dpos == $spos) {
    return;
  }

  while (! defined ($len) || $len > 0) {
    my $readsize = ! defined($len) ? $blocksize
               : $len > $blocksize ? $blocksize
               : $len;
      
    my $fh = $self->{fh};
    $self->_seekb($spos);
    my $bytes_read = read $fh, my($data), $readsize;
    $self->_seekb($dpos);
    if ($data eq "") { 
      $self->_chop_file;
      last;
    }
    $self->_write_record($data);
    $spos += $bytes_read;
    $dpos += $bytes_read;
    $len -= $bytes_read if defined $len;
  }
}

# Write $data into a block of length $len at position $pos,
# moving everything in the block forwards to make room.
# Instead of writing the last length($data) bytes from the block
# (because there isn't room for them any longer) return them.
#
# Undefined $len means 'until the end of the file'
sub _downcopy {
  my $blocksize = 8192;
  my ($self, $data, $pos, $len) = @_;
  my $fh = $self->{fh};

  while (! defined $len || $len > 0) {
    my $readsize = ! defined($len) ? $blocksize 
      : $len > $blocksize? $blocksize : $len;
    $self->_seekb($pos);
    read $fh, my($old), $readsize;
    my $last_read_was_short = length($old) < $readsize;
    $data .= $old;
    my $writable;
    if ($last_read_was_short) {
      # If last read was short, then $data now contains the entire rest
      # of the file, so there's no need to write only one block of it
      $writable = $data;
      $data = "";
    } else {
      $writable = substr($data, 0, $readsize, "");
    }
    last if $writable eq "";
    $self->_seekb($pos);
    $self->_write_record($writable);
    last if $last_read_was_short && $data eq "";
    $len -= $readsize if defined $len;
    $pos += $readsize;
  }
  return $data;
}

# Adjust the object data structures following an '_mtwrite'
# Arguments are
#  [$pos, $nrecs, @length]  items
# indicating that $nrecs records were removed at $recpos (a record offset)
# and replaced with records of length @length...
# Arguments guarantee that $recpos is strictly increasing.
# No return value
sub _oadjust {
  my $self = shift;
  my $delta = 0;
  my $delta_recs = 0;
  my $prev_end = -1;

  for (@_) {
    my ($pos, $nrecs, @data) = @$_;
    $pos += $delta_recs;

    # Adjust the offsets of the records after the previous batch up
    # to the first new one of this batch
    for my $i ($prev_end+2 .. $pos - 1) {
      $self->{offsets}[$i] += $delta;
    }

    $prev_end = $pos + @data - 1; # last record moved on this pass 

    # Remove the offsets for the removed records;
    # replace with the offsets for the inserted records
    my @newoff = ($self->{offsets}[$pos] + $delta);
    for my $i (0 .. $#data) {
      my $newlen = length $data[$i];
      push @newoff, $newoff[$i] + $newlen;
      $delta += $newlen;
    }

    for my $i ($pos .. $pos+$nrecs-1) {
      last if $i+1 > $#{$self->{offsets}};
      my $oldlen = $self->{offsets}[$i+1] - $self->{offsets}[$i];
      $delta -= $oldlen;
    }

    # replace old offsets with new
    splice @{$self->{offsets}}, $pos, $nrecs+1, @newoff;
    # What if we just spliced out the end of the offsets table?
    # shouldn't we clear $self->{eof}?   Test for this XXX BUG TODO

    $delta_recs += @data - $nrecs; # net change in total number of records
  }

  # The trailing records at the very end of the file
  if ($delta) {
    for my $i ($prev_end+2 .. $#{$self->{offsets}}) {
      $self->{offsets}[$i] += $delta;
    }
  }

  # If we scrubbed out all known offsets, regenerate the trivial table
  # that knows that the file does indeed start at 0.
  $self->{offsets}[0] = 0 unless @{$self->{offsets}};
  # If the file got longer, the offsets table is no longer complete
  # $self->{eof} = 0 if $delta_recs > 0;

  # Now there might be too much data in the cache, if we spliced out
  # some short records and spliced in some long ones.  If so, flush
  # the cache.
  $self->_cache_flush;
}

# If a record does not already end with the appropriate terminator
# string, append one.
sub _fixrecs {
  my $self = shift;
  for (@_) {
    $_ = "" unless defined $_;
    $_ .= $self->{recsep}
      unless substr($_, - $self->{recseplen}) eq $self->{recsep};
  }
}


################################################################
#
# Basic read, write, and seek
#

# seek to the beginning of record #$n
# Assumes that the offsets table is already correctly populated
#
# Note that $n=-1 has a special meaning here: It means the start of
# the last known record; this may or may not be the very last record
# in the file, depending on whether the offsets table is fully populated.
#
sub _seek {
  my ($self, $n) = @_;
  my $o = $self->{offsets}[$n];
  defined($o)
    or confess("logic error: undefined offset for record $n");
  seek $self->{fh}, $o, SEEK_SET
    or confess "Couldn't seek filehandle: $!";  # "Should never happen."
}

# seek to byte $b in the file
sub _seekb {
  my ($self, $b) = @_;
  seek $self->{fh}, $b, SEEK_SET
    or die "Couldn't seek filehandle: $!";  # "Should never happen."
}

# populate the offsets table up to the beginning of record $n
# return the offset of record $n
sub _fill_offsets_to {
  my ($self, $n) = @_;

  return $self->{offsets}[$n] if $self->{eof};

  my $fh = $self->{fh};
  local *OFF = $self->{offsets};
  my $rec;

  until ($#OFF >= $n) {
    $self->_seek(-1);           # tricky -- see comment at _seek
    $rec = $self->_read_record;
    if (defined $rec) {
      push @OFF, int(tell $fh);  # Tels says that int() saves memory here
    } else {
      $self->{eof} = 1;
      return;                   # It turns out there is no such record
    }
  }

  # we have now read all the records up to record n-1,
  # so we can return the offset of record n
  $OFF[$n];
}

sub _fill_offsets {
  my ($self) = @_;

  my $fh = $self->{fh};
  local *OFF = $self->{offsets};

  $self->_seek(-1);           # tricky -- see comment at _seek

  # Tels says that inlining read_record() would make this loop
  # five times faster. 20030508
  while ( defined $self->_read_record()) {
    # int() saves us memory here
    push @OFF, int(tell $fh);
  }

  $self->{eof} = 1;
  $#OFF;
}

# assumes that $rec is already suitably terminated
sub _write_record {
  my ($self, $rec) = @_;
  my $fh = $self->{fh};
  local $\ = "";
  print $fh $rec
    or die "Couldn't write record: $!";  # "Should never happen."
#  $self->{_written} += length($rec);
}

sub _read_record {
  my $self = shift;
  my $rec;
  { local $/ = $self->{recsep};
    my $fh = $self->{fh};
    $rec = <$fh>;
  }
  return unless defined $rec;
  if (substr($rec, -$self->{recseplen}) ne $self->{recsep}) {
    # improperly terminated final record --- quietly fix it.
#    my $ac = substr($rec, -$self->{recseplen});
#    $ac =~ s/\n/\\n/g;
    $self->{sawlastrec} = 1;
    unless ($self->{rdonly}) {
      local $\ = "";
      my $fh = $self->{fh};
      print $fh $self->{recsep};
    }
    $rec .= $self->{recsep};
  }
#  $self->{_read} += length($rec) if defined $rec;
  $rec;
}

sub _rw_stats {
  my $self = shift;
  @{$self}{'_read', '_written'};
}

################################################################
#
# Read cache management

sub _cache_flush {
  my ($self) = @_;
  $self->{cache}->reduce_size_to($self->{memory} - $self->{deferred_s});
}

sub _cache_too_full {
  my $self = shift;
  $self->{cache}->bytes + $self->{deferred_s} >= $self->{memory};
}

################################################################
#
# File custodial services
#


# We have read to the end of the file and have the offsets table
# entirely populated.  Now we need to write a new record beyond
# the end of the file.  We prepare for this by writing
# empty records into the file up to the position we want
#
# assumes that the offsets table already contains the offset of record $n,
# if it exists, and extends to the end of the file if not.
sub _extend_file_to {
  my ($self, $n) = @_;
  $self->_seek(-1);             # position after the end of the last record
  my $pos = $self->{offsets}[-1];

  # the offsets table has one entry more than the total number of records
  my $extras = $n - $#{$self->{offsets}};

  # Todo : just use $self->{recsep} x $extras here?
  while ($extras-- > 0) {
    $self->_write_record($self->{recsep});
    push @{$self->{offsets}}, int(tell $self->{fh});
  }
}

# Truncate the file at the current position
sub _chop_file {
  my $self = shift;
  truncate $self->{fh}, tell($self->{fh});
}


# compute the size of a buffer suitable for moving
# all the data in a file forward $n bytes
# ($n may be negative)
# The result should be at least $n.
sub _bufsize {
  my $n = shift;
  return 8192 if $n <= 0;
  my $b = $n & ~8191;
  $b += 8192 if $n & 8191;
  $b;
}

################################################################
#
# Miscellaneous public methods
#

# Lock the file
sub flock {
  my ($self, $op) = @_;
  unless (@_ <= 3) {
    my $pack = ref $self;
    croak "Usage: $pack\->flock([OPERATION])";
  }
  my $fh = $self->{fh};
  $op = LOCK_EX unless defined $op;
  my $locked = flock $fh, $op;

  if ($locked && ($op & (LOCK_EX | LOCK_SH))) {
    # If you're locking the file, then presumably it's because
    # there might have been a write access by another process.
    # In that case, the read cache contents and the offsets table
    # might be invalid, so discard them.  20030508
    $self->{offsets} = [0];
    $self->{cache}->empty;
  }

  $locked;
}

# Get/set autochomp option
sub autochomp {
  my $self = shift;
  if (@_) {
    my $old = $self->{autochomp};
    $self->{autochomp} = shift;
    $old;
  } else {
    $self->{autochomp};
  }
}

# Get offset table entries; returns offset of nth record
sub offset {
  my ($self, $n) = @_;

  if ($#{$self->{offsets}} < $n) {
    return if $self->{eof};     # request for record beyond the end of file
    my $o = $self->_fill_offsets_to($n);
    # If it's still undefined, there is no such record, so return 'undef'
    return unless defined $o;
   }

  $self->{offsets}[$n];
}

sub discard_offsets {
  my $self = shift;
  $self->{offsets} = [0];
}

################################################################
#
# Matters related to deferred writing
#

# Defer writes
sub defer {
  my $self = shift;
  $self->_stop_autodeferring;
  @{$self->{ad_history}} = ();
  $self->{defer} = 1;
}

# Flush deferred writes
#
# This could be better optimized to write the file in one pass, instead
# of one pass per block of records.  But that will require modifications
# to _twrite, so I should have a good _twrite test suite first.
sub flush {
  my $self = shift;

  $self->_flush;
  $self->{defer} = 0;
}

sub _old_flush {
  my $self = shift;
  my @writable = sort {$a<=>$b} (keys %{$self->{deferred}});

  while (@writable) {
    # gather all consecutive records from the front of @writable
    my $first_rec = shift @writable;
    my $last_rec = $first_rec+1;
    ++$last_rec, shift @writable while @writable && $last_rec == $writable[0];
    --$last_rec;
    $self->_fill_offsets_to($last_rec);
    $self->_extend_file_to($last_rec);
    $self->_splice($first_rec, $last_rec-$first_rec+1, 
                   @{$self->{deferred}}{$first_rec .. $last_rec});
  }

  $self->_discard;               # clear out defered-write-cache
}

sub _flush {
  my $self = shift;
  my @writable = sort {$a<=>$b} (keys %{$self->{deferred}});
  my @args;
  my @adjust;

  while (@writable) {
    # gather all consecutive records from the front of @writable
    my $first_rec = shift @writable;
    my $last_rec = $first_rec+1;
    ++$last_rec, shift @writable while @writable && $last_rec == $writable[0];
    --$last_rec;
    my $end = $self->_fill_offsets_to($last_rec+1);
    if (not defined $end) {
      $self->_extend_file_to($last_rec);
      $end = $self->{offsets}[$last_rec];
    }
    my ($start) = $self->{offsets}[$first_rec];
    push @args,
         join("", @{$self->{deferred}}{$first_rec .. $last_rec}), # data
         $start,                                                  # position
         $end-$start;                                             # length
    push @adjust, [$first_rec, # starting at this position...
                   $last_rec-$first_rec+1,  # this many records...
                   # are replaced with these...
                   @{$self->{deferred}}{$first_rec .. $last_rec},
                  ];
  }

  $self->_mtwrite(@args);  # write multiple record groups
  $self->_discard;               # clear out defered-write-cache
  $self->_oadjust(@adjust);
}

# Discard deferred writes and disable future deferred writes
sub discard {
  my $self = shift;
  $self->_discard;
  $self->{defer} = 0;
}

# Discard deferred writes, but retain old deferred writing mode
sub _discard {
  my $self = shift;
  %{$self->{deferred}} = ();
  $self->{deferred_s}  = 0;
  $self->{deferred_max}  = -1;
  $self->{cache}->set_limit($self->{memory});
}

# Deferred writing is enabled, either explicitly ($self->{defer})
# or automatically ($self->{autodeferring})
sub _is_deferring {
  my $self = shift;
  $self->{defer} || $self->{autodeferring};
}

# The largest record number of any deferred record
sub _defer_max {
  my $self = shift;
  return $self->{deferred_max} if defined $self->{deferred_max};
  my $max = -1;
  for my $key (keys %{$self->{deferred}}) {
    $max = $key if $key > $max;
  }
  $self->{deferred_max} = $max;
  $max;
}

################################################################
#
# Matters related to autodeferment
#

# Get/set autodefer option
sub autodefer {
  my $self = shift;
  if (@_) {
    my $old = $self->{autodefer};
    $self->{autodefer} = shift;
    if ($old) {
      $self->_stop_autodeferring;
      @{$self->{ad_history}} = ();
    }
    $old;
  } else {
    $self->{autodefer};
  }
}

# The user is trying to store record #$n Record that in the history,
# and then enable (or disable) autodeferment if that seems useful.
# Note that it's OK for $n to be a non-number, as long as the function
# is prepared to deal with that.  Nobody else looks at the ad_history.
#
# Now, what does the ad_history mean, and what is this function doing?
# Essentially, the idea is to enable autodeferring when we see that the
# user has made three consecutive STORE calls to three consecutive records.
# ("Three" is actually ->{autodefer_threshhold}.)
# A STORE call for record #$n inserts $n into the autodefer history,
# and if the history contains three consecutive records, we enable 
# autodeferment.  An ad_history of [X, Y] means that the most recent
# STOREs were for records X, X+1, ..., Y, in that order.  
#
# Inserting a nonconsecutive number erases the history and starts over.
#
# Performing a special operation like SPLICE erases the history.
#
# There's one special case: CLEAR means that CLEAR was just called.
# In this case, we prime the history with [-2, -1] so that if the next
# write is for record 0, autodeferring goes on immediately.  This is for
# the common special case of "@a = (...)".
#
sub _annotate_ad_history {
  my ($self, $n) = @_;
  return unless $self->{autodefer}; # feature is disabled
  return if $self->{defer};     # already in explicit defer mode
  return unless $self->{offsets}[-1] >= $self->{autodefer_filelen_threshhold};

  local *H = $self->{ad_history};
  if ($n eq 'CLEAR') {
    @H = (-2, -1);              # prime the history with fake records
    $self->_stop_autodeferring;
  } elsif ($n =~ /^\d+$/) {
    if (@H == 0) {
      @H =  ($n, $n);
    } else {                    # @H == 2
      if ($H[1] == $n-1) {      # another consecutive record
        $H[1]++;
        if ($H[1] - $H[0] + 1 >= $self->{autodefer_threshhold}) {
          $self->{autodeferring} = 1;
        }
      } else {                  # nonconsecutive- erase and start over
        @H = ($n, $n);
        $self->_stop_autodeferring;
      }
    }
  } else {                      # SPLICE or STORESIZE or some such
    @H = ();
    $self->_stop_autodeferring;
  }
}

# If autodeferring was enabled, cut it out and discard the history
sub _stop_autodeferring {
  my $self = shift;
  if ($self->{autodeferring}) {
    $self->_flush;
  }
  $self->{autodeferring} = 0;
}

################################################################


# This is NOT a method.  It is here for two reasons:
#  1. To factor a fairly complicated block out of the constructor
#  2. To provide access for the test suite, which need to be sure
#     files are being written properly.
sub _default_recsep {
  my $recsep = $/;
  if ($^O eq 'MSWin32') {       # Dos too?
    # Windows users expect files to be terminated with \r\n
    # But $/ is set to \n instead
    # Note that this also transforms \n\n into \r\n\r\n.
    # That is a feature.
    $recsep =~ s/\n/\r\n/g;
  }
  $recsep;
}

# Utility function for _check_integrity
sub _ci_warn {
  my $msg = shift;
  $msg =~ s/\n/\\n/g;
  $msg =~ s/\r/\\r/g;
  print "# $msg\n";
}

# Given a file, make sure the cache is consistent with the
# file contents and the internal data structures are consistent with
# each other.  Returns true if everything checks out, false if not
#
# The $file argument is no longer used.  It is retained for compatibility
# with the existing test suite.
sub _check_integrity {
  my ($self, $file, $warn) = @_;
  my $rsl = $self->{recseplen};
  my $rs  = $self->{recsep};
  my $good = 1; 
  local *_;                     # local $_ does not work here
  local $DIAGNOSTIC = 1;

  if (not defined $rs) {
    _ci_warn("recsep is undef!");
    $good = 0;
  } elsif ($rs eq "") {
    _ci_warn("recsep is empty!");
    $good = 0;
  } elsif ($rsl != length $rs) {
    my $ln = length $rs;
    _ci_warn("recsep <$rs> has length $ln, should be $rsl");
    $good = 0;
  }

  if (not defined $self->{offsets}[0]) {
    _ci_warn("offset 0 is missing!");
    $good = 0;

  } elsif ($self->{offsets}[0] != 0) {
    _ci_warn("rec 0: offset <$self->{offsets}[0]> s/b 0!");
    $good = 0;
  }

  my $cached = 0;
  {
    local *F = $self->{fh};
    seek F, 0, SEEK_SET;
    local $. = 0;
    local $/ = $rs;

    while (<F>) {
      my $n = $. - 1;
      my $cached = $self->{cache}->_produce($n);
      my $offset = $self->{offsets}[$.];
      my $ao = tell F;
      if (defined $offset && $offset != $ao) {
        _ci_warn("rec $n: offset <$offset> actual <$ao>");
        $good = 0;
      }
      if (defined $cached && $_ ne $cached && ! $self->{deferred}{$n}) {
        $good = 0;
        _ci_warn("rec $n: cached <$cached> actual <$_>");
      }
      if (defined $cached && substr($cached, -$rsl) ne $rs) {
        $good = 0;
        _ci_warn("rec $n in the cache is missing the record separator");
      }
      if (! defined $offset && $self->{eof}) {
        $good = 0;
        _ci_warn("The offset table was marked complete, but it is missing " .
                 "element $.");
      }
    }
    if (@{$self->{offsets}} > $.+1) {
        $good = 0;
        my $n = @{$self->{offsets}};
        _ci_warn("The offset table has $n items, but the file has only $.");
    }

    my $deferring = $self->_is_deferring;
    for my $n ($self->{cache}->ckeys) {
      my $r = $self->{cache}->_produce($n);
      $cached += length($r);
      next if $n+1 <= $.;         # checked this already
      _ci_warn("spurious caching of record $n");
      $good = 0;
    }
    my $b = $self->{cache}->bytes;
    if ($cached != $b) {
      _ci_warn("cache size is $b, should be $cached");
      $good = 0;
    }
  }

  # That cache has its own set of tests
  $good = 0 unless $self->{cache}->_check_integrity;

  # Now let's check the deferbuffer
  # Unless deferred writing is enabled, it should be empty
  if (! $self->_is_deferring && %{$self->{deferred}}) {
    _ci_warn("deferred writing disabled, but deferbuffer nonempty");
    $good = 0;
  }

  # Any record in the deferbuffer should *not* be present in the readcache
  my $deferred_s = 0;
  while (my ($n, $r) = each %{$self->{deferred}}) {
    $deferred_s += length($r);
    if (defined $self->{cache}->_produce($n)) {
      _ci_warn("record $n is in the deferbuffer *and* the readcache");
      $good = 0;
    }
    if (substr($r, -$rsl) ne $rs) {
      _ci_warn("rec $n in the deferbuffer is missing the record separator");
      $good = 0;
    }
  }

  # Total size of deferbuffer should match internal total
  if ($deferred_s != $self->{deferred_s}) {
    _ci_warn("buffer size is $self->{deferred_s}, should be $deferred_s");
    $good = 0;
  }

  # Total size of deferbuffer should not exceed the specified limit
  if ($deferred_s > $self->{dw_size}) {
    _ci_warn("buffer size is $self->{deferred_s} which exceeds the limit " .
             "of $self->{dw_size}");
    $good = 0;
  }

  # Total size of cached data should not exceed the specified limit
  if ($deferred_s + $cached > $self->{memory}) {
    my $total = $deferred_s + $cached;
    _ci_warn("total stored data size is $total which exceeds the limit " .
             "of $self->{memory}");
    $good = 0;
  }

  # Stuff related to autodeferment
  if (!$self->{autodefer} && @{$self->{ad_history}}) {
    _ci_warn("autodefer is disabled, but ad_history is nonempty");
    $good = 0;
  }
  if ($self->{autodeferring} && $self->{defer}) {
    _ci_warn("both autodeferring and explicit deferring are active");
    $good = 0;
  }
  if (@{$self->{ad_history}} == 0) {
    # That's OK, no additional tests required
  } elsif (@{$self->{ad_history}} == 2) {
    my @non_number = grep !/^-?\d+$/, @{$self->{ad_history}};
    if (@non_number) {
      my $msg;
      { local $" = ')(';
        $msg = "ad_history contains non-numbers (@{$self->{ad_history}})";
      }
      _ci_warn($msg);
      $good = 0;
    } elsif ($self->{ad_history}[1] < $self->{ad_history}[0]) {
      _ci_warn("ad_history has nonsensical values @{$self->{ad_history}}");
      $good = 0;
    }
  } else {
    _ci_warn("ad_history has bad length <@{$self->{ad_history}}>");
    $good = 0;
  }

  $good;
}

################################################################
#
# Tie::File::Cache
#
# Read cache

package Tie::File::Cache;
$Tie::File::Cache::VERSION = $Tie::File::VERSION;
use Carp ':DEFAULT', 'confess';

sub HEAP () { 0 }
sub HASH () { 1 }
sub MAX  () { 2 }
sub BYTES() { 3 }
#sub STAT () { 4 } # Array with request statistics for each record
#sub MISS () { 5 } # Total number of cache misses
#sub REQ  () { 6 } # Total number of cache requests 
use strict 'vars';

sub new {
  my ($pack, $max) = @_;
  local *_;
  croak "missing argument to ->new" unless defined $max;
  my $self = [];
  bless $self => $pack;
  @$self = (Tie::File::Heap->new($self), {}, $max, 0);
  $self;
}

sub adj_limit {
  my ($self, $n) = @_;
  $self->[MAX] += $n;
}

sub set_limit {
  my ($self, $n) = @_;
  $self->[MAX] = $n;
}

# For internal use only
# Will be called by the heap structure to notify us that a certain 
# piece of data has moved from one heap element to another.
# $k is the hash key of the item
# $n is the new index into the heap at which it is stored
# If $n is undefined, the item has been removed from the heap.
sub _heap_move {
  my ($self, $k, $n) = @_;
  if (defined $n) {
    $self->[HASH]{$k} = $n;
  } else {
    delete $self->[HASH]{$k};
  }
}

sub insert {
  my ($self, $key, $val) = @_;
  local *_;
  croak "missing argument to ->insert" unless defined $key;
  unless (defined $self->[MAX]) {
    confess "undefined max" ;
  }
  confess "undefined val" unless defined $val;
  return if length($val) > $self->[MAX];

#  if ($self->[STAT]) {
#    $self->[STAT][$key] = 1;
#    return;
#  }

  my $oldnode = $self->[HASH]{$key};
  if (defined $oldnode) {
    my $oldval = $self->[HEAP]->set_val($oldnode, $val);
    $self->[BYTES] -= length($oldval);
  } else {
    $self->[HEAP]->insert($key, $val);
  }
  $self->[BYTES] += length($val);
  $self->flush if $self->[BYTES] > $self->[MAX];
}

sub expire {
  my $self = shift;
  my $old_data = $self->[HEAP]->popheap;
  return unless defined $old_data;
  $self->[BYTES] -= length $old_data;
  $old_data;
}

sub remove {
  my ($self, @keys) = @_;
  my @result;

#  if ($self->[STAT]) {
#    for my $key (@keys) {
#      $self->[STAT][$key] = 0;
#    }
#    return;
#  }

  for my $key (@keys) {
    next unless exists $self->[HASH]{$key};
    my $old_data = $self->[HEAP]->remove($self->[HASH]{$key});
    $self->[BYTES] -= length $old_data;
    push @result, $old_data;
  }
  @result;
}

sub lookup {
  my ($self, $key) = @_;
  local *_;
  croak "missing argument to ->lookup" unless defined $key;

#  if ($self->[STAT]) {
#    $self->[MISS]++  if $self->[STAT][$key]++ == 0;
#    $self->[REQ]++;
#    my $hit_rate = 1 - $self->[MISS] / $self->[REQ];
#    # Do some testing to determine this threshhold
#    $#$self = STAT - 1 if $hit_rate > 0.20; 
#  }

  if (exists $self->[HASH]{$key}) {
    $self->[HEAP]->lookup($self->[HASH]{$key});
  } else {
    return;
  }
}

# For internal use only
sub _produce {
  my ($self, $key) = @_;
  my $loc = $self->[HASH]{$key};
  return unless defined $loc;
  $self->[HEAP][$loc][2];
}

# For internal use only
sub _promote {
  my ($self, $key) = @_;
  $self->[HEAP]->promote($self->[HASH]{$key});
}

sub empty {
  my ($self) = @_;
  %{$self->[HASH]} = ();
    $self->[BYTES] = 0;
    $self->[HEAP]->empty;
#  @{$self->[STAT]} = ();
#    $self->[MISS] = 0;
#    $self->[REQ] = 0;
}

sub is_empty {
  my ($self) = @_;
  keys %{$self->[HASH]} == 0;
}

sub update {
  my ($self, $key, $val) = @_;
  local *_;
  croak "missing argument to ->update" unless defined $key;
  if (length($val) > $self->[MAX]) {
    my ($oldval) = $self->remove($key);
    $self->[BYTES] -= length($oldval) if defined $oldval;
  } elsif (exists $self->[HASH]{$key}) {
    my $oldval = $self->[HEAP]->set_val($self->[HASH]{$key}, $val);
    $self->[BYTES] += length($val);
    $self->[BYTES] -= length($oldval) if defined $oldval;
  } else {
    $self->[HEAP]->insert($key, $val);
    $self->[BYTES] += length($val);
  }
  $self->flush;
}

sub rekey {
  my ($self, $okeys, $nkeys) = @_;
  local *_;
  my %map;
  @map{@$okeys} = @$nkeys;
  croak "missing argument to ->rekey" unless defined $nkeys;
  croak "length mismatch in ->rekey arguments" unless @$nkeys == @$okeys;
  my %adjusted;                 # map new keys to heap indices
  # You should be able to cut this to one loop TODO XXX
  for (0 .. $#$okeys) {
    $adjusted{$nkeys->[$_]} = delete $self->[HASH]{$okeys->[$_]};
  }
  while (my ($nk, $ix) = each %adjusted) {
    # @{$self->[HASH]}{keys %adjusted} = values %adjusted;
    $self->[HEAP]->rekey($ix, $nk);
    $self->[HASH]{$nk} = $ix;
  }
}

sub ckeys {
  my $self = shift;
  my @a = keys %{$self->[HASH]};
  @a;
}

# Return total amount of cached data
sub bytes {
  my $self = shift;
  $self->[BYTES];
}

# Expire oldest item from cache until cache size is smaller than $max
sub reduce_size_to {
  my ($self, $max) = @_;
  until ($self->[BYTES] <= $max) {
    # Note that Tie::File::Cache::expire has been inlined here
    my $old_data = $self->[HEAP]->popheap;
    return unless defined $old_data;
    $self->[BYTES] -= length $old_data;
  }
}

# Why not just $self->reduce_size_to($self->[MAX])?
# Try this when things stabilize   TODO XXX
# If the cache is too full, expire the oldest records
sub flush {
  my $self = shift;
  $self->reduce_size_to($self->[MAX]) if $self->[BYTES] > $self->[MAX];
}

# For internal use only
sub _produce_lru {
  my $self = shift;
  $self->[HEAP]->expire_order;
}

BEGIN { *_ci_warn = \&Tie::File::_ci_warn }

sub _check_integrity {          # For CACHE
  my $self = shift;
  my $good = 1;

  # Test HEAP
  $self->[HEAP]->_check_integrity or $good = 0;

  # Test HASH
  my $bytes = 0;
  for my $k (keys %{$self->[HASH]}) {
    if ($k ne '0' && $k !~ /^[1-9][0-9]*$/) {
      $good = 0;
      _ci_warn "Cache hash key <$k> is non-numeric";
    }

    my $h = $self->[HASH]{$k};
    if (! defined $h) {
      $good = 0;
      _ci_warn "Heap index number for key $k is undefined";
    } elsif ($h == 0) {
      $good = 0;
      _ci_warn "Heap index number for key $k is zero";
    } else {
      my $j = $self->[HEAP][$h];
      if (! defined $j) {
        $good = 0;
        _ci_warn "Heap contents key $k (=> $h) are undefined";
      } else {
        $bytes += length($j->[2]);
        if ($k ne $j->[1]) {
          $good = 0;
          _ci_warn "Heap contents key $k (=> $h) is $j->[1], should be $k";
        }
      }
    }
  }

  # Test BYTES
  if ($bytes != $self->[BYTES]) {
    $good = 0;
    _ci_warn "Total data in cache is $bytes, expected $self->[BYTES]";
  }

  # Test MAX
  if ($bytes > $self->[MAX]) {
    $good = 0;
    _ci_warn "Total data in cache is $bytes, exceeds maximum $self->[MAX]";
  }

  return $good;
}

sub delink {
  my $self = shift;
  $self->[HEAP] = undef;        # Bye bye heap
}

################################################################
#
# Tie::File::Heap
#
# Heap data structure for use by cache LRU routines

package Tie::File::Heap;
use Carp ':DEFAULT', 'confess';
$Tie::File::Heap::VERSION = $Tie::File::Cache::VERSION;
sub SEQ () { 0 };
sub KEY () { 1 };
sub DAT () { 2 };

sub new {
  my ($pack, $cache) = @_;
  die "$pack: Parent cache object $cache does not support _heap_move method"
    unless eval { $cache->can('_heap_move') };
  my $self = [[0,$cache,0]];
  bless $self => $pack;
}

# Allocate a new sequence number, larger than all previously allocated numbers
sub _nseq {
  my $self = shift;
  $self->[0][0]++;
}

sub _cache {
  my $self = shift;
  $self->[0][1];
}

sub _nelts {
  my $self = shift;
  $self->[0][2];
}

sub _nelts_inc {
  my $self = shift;
  ++$self->[0][2];
}  

sub _nelts_dec {
  my $self = shift;
  --$self->[0][2];
}  

sub is_empty {
  my $self = shift;
  $self->_nelts == 0;
}

sub empty {
  my $self = shift;
  $#$self = 0;
  $self->[0][2] = 0;
  $self->[0][0] = 0;            # might as well reset the sequence numbers
}

# notify the parent cache object that we moved something
sub _heap_move {
  my $self = shift;
  $self->_cache->_heap_move(@_);
}

# Insert a piece of data into the heap with the indicated sequence number.
# The item with the smallest sequence number is always at the top.
# If no sequence number is specified, allocate a new one and insert the
# item at the bottom.
sub insert {
  my ($self, $key, $data, $seq) = @_;
  $seq = $self->_nseq unless defined $seq;
  $self->_insert_new([$seq, $key, $data]);
}

# Insert a new, fresh item at the bottom of the heap
sub _insert_new {
  my ($self, $item) = @_;
  my $i = @$self;
  $i = int($i/2) until defined $self->[$i/2];
  $self->[$i] = $item;
  $self->[0][1]->_heap_move($self->[$i][KEY], $i);
  $self->_nelts_inc;
}

# Insert [$data, $seq] pair at or below item $i in the heap.
# If $i is omitted, default to 1 (the top element.)
sub _insert {
  my ($self, $item, $i) = @_;
#  $self->_check_loc($i) if defined $i;
  $i = 1 unless defined $i;
  until (! defined $self->[$i]) {
    if ($self->[$i][SEQ] > $item->[SEQ]) { # inserted item is older
      ($self->[$i], $item) = ($item, $self->[$i]);
      $self->[0][1]->_heap_move($self->[$i][KEY], $i);
    }
    # If either is undefined, go that way.  Otherwise, choose at random
    my $dir;
    $dir = 0 if !defined $self->[2*$i];
    $dir = 1 if !defined $self->[2*$i+1];
    $dir = int(rand(2)) unless defined $dir;
    $i = 2*$i + $dir;
  }
  $self->[$i] = $item;
  $self->[0][1]->_heap_move($self->[$i][KEY], $i);
  $self->_nelts_inc;
}

# Remove the item at node $i from the heap, moving child items upwards.
# The item with the smallest sequence number is always at the top.
# Moving items upwards maintains this condition.
# Return the removed item.  Return undef if there was no item at node $i.
sub remove {
  my ($self, $i) = @_;
  $i = 1 unless defined $i;
  my $top = $self->[$i];
  return unless defined $top;
  while (1) {
    my $ii;
    my ($L, $R) = (2*$i, 2*$i+1);

    # If either is undefined, go the other way.
    # Otherwise, go towards the smallest.
    last unless defined $self->[$L] || defined $self->[$R];
    $ii = $R if not defined $self->[$L];
    $ii = $L if not defined $self->[$R];
    unless (defined $ii) {
      $ii = $self->[$L][SEQ] < $self->[$R][SEQ] ? $L : $R;
    }

    $self->[$i] = $self->[$ii]; # Promote child to fill vacated spot
    $self->[0][1]->_heap_move($self->[$i][KEY], $i);
    $i = $ii; # Fill new vacated spot
  }
  $self->[0][1]->_heap_move($top->[KEY], undef);
  undef $self->[$i];
  $self->_nelts_dec;
  return $top->[DAT];
}

sub popheap {
  my $self = shift;
  $self->remove(1);
}

# set the sequence number of the indicated item to a higher number
# than any other item in the heap, and bubble the item down to the
# bottom.
sub promote {
  my ($self, $n) = @_;
#  $self->_check_loc($n);
  $self->[$n][SEQ] = $self->_nseq;
  my $i = $n;
  while (1) {
    my ($L, $R) = (2*$i, 2*$i+1);
    my $dir;
    last unless defined $self->[$L] || defined $self->[$R];
    $dir = $R unless defined $self->[$L];
    $dir = $L unless defined $self->[$R];
    unless (defined $dir) {
      $dir = $self->[$L][SEQ] < $self->[$R][SEQ] ? $L : $R;
    }
    @{$self}[$i, $dir] = @{$self}[$dir, $i];
    for ($i, $dir) {
      $self->[0][1]->_heap_move($self->[$_][KEY], $_) if defined $self->[$_];
    }
    $i = $dir;
  }
}

# Return item $n from the heap, promoting its LRU status
sub lookup {
  my ($self, $n) = @_;
#  $self->_check_loc($n);
  my $val = $self->[$n];
  $self->promote($n);
  $val->[DAT];
}


# Assign a new value for node $n, promoting it to the bottom of the heap
sub set_val {
  my ($self, $n, $val) = @_;
#  $self->_check_loc($n);
  my $oval = $self->[$n][DAT];
  $self->[$n][DAT] = $val;
  $self->promote($n);
  return $oval;
}

# The hash key has changed for an item;
# alter the heap's record of the hash key
sub rekey {
  my ($self, $n, $new_key) = @_;
#  $self->_check_loc($n);
  $self->[$n][KEY] = $new_key;
}

sub _check_loc {
  my ($self, $n) = @_;
  unless (1 || defined $self->[$n]) {
    confess "_check_loc($n) failed";
  }
}

BEGIN { *_ci_warn = \&Tie::File::_ci_warn }

sub _check_integrity {
  my $self = shift;
  my $good = 1;
  my %seq;

  unless (eval {$self->[0][1]->isa("Tie::File::Cache")}) {
    _ci_warn "Element 0 of heap corrupt";
    $good = 0;
  }
  $good = 0 unless $self->_satisfies_heap_condition(1);
  for my $i (2 .. $#{$self}) {
    my $p = int($i/2);          # index of parent node
    if (defined $self->[$i] && ! defined $self->[$p]) {
      _ci_warn "Element $i of heap defined, but parent $p isn't";
      $good = 0;
    }

    if (defined $self->[$i]) {
      if ($seq{$self->[$i][SEQ]}) {
        my $seq = $self->[$i][SEQ];
        _ci_warn "Nodes $i and $seq{$seq} both have SEQ=$seq";
        $good = 0;
      } else {
        $seq{$self->[$i][SEQ]} = $i;
      }
    }
  }

  return $good;
}

sub _satisfies_heap_condition {
  my $self = shift;
  my $n = shift || 1;
  my $good = 1;
  for (0, 1) {
    my $c = $n*2 + $_;
    next unless defined $self->[$c];
    if ($self->[$n][SEQ] >= $self->[$c]) {
      _ci_warn "Node $n of heap does not predate node $c";
      $good = 0 ;
    }
    $good = 0 unless $self->_satisfies_heap_condition($c);
  }
  return $good;
}

# Return a list of all the values, sorted by expiration order
sub expire_order {
  my $self = shift;
  my @nodes = sort {$a->[SEQ] <=> $b->[SEQ]} $self->_nodes;
  map { $_->[KEY] } @nodes;
}

sub _nodes {
  my $self = shift;
  my $i = shift || 1;
  return unless defined $self->[$i];
  ($self->[$i], $self->_nodes($i*2), $self->_nodes($i*2+1));
}

1;

__END__

=head1 NAME

Tie::File - Access the lines of a disk file via a Perl array

=head1 SYNOPSIS

 use Tie::File;

 tie @array, 'Tie::File', filename or die ...;

 $array[0] = 'blah';      # first line of the file is now 'blah'
                            # (line numbering starts at 0)
 print $array[42];        # display line 43 of the file

 $n_recs = @array;        # how many records are in the file?
 $#array -= 2;            # chop two records off the end


 for (@array) {
   s/PERL/Perl/g;        # Replace PERL with Perl everywhere in the file
 }

 # These are just like regular push, pop, unshift, shift, and splice
 # Except that they modify the file in the way you would expect

 push @array, new recs...;
 my $r1 = pop @array;
 unshift @array, new recs...;
 my $r2 = shift @array;
 @old_recs = splice @array, 3, 7, new recs...;

 untie @array;            # all finished


=head1 DESCRIPTION

C<Tie::File> represents a regular text file as a Perl array.  Each
element in the array corresponds to a record in the file.  The first
line of the file is element 0 of the array; the second line is element
1, and so on.

The file is I<not> loaded into memory, so this will work even for
gigantic files.

Changes to the array are reflected in the file immediately.

Lazy people and beginners may now stop reading the manual.

=head2 C<recsep>

What is a 'record'?  By default, the meaning is the same as for the
C<E<lt>...E<gt>> operator: It's a string terminated by C<$/>, which is
probably C<"\n">.  (Minor exception: on DOS and Win32 systems, a
'record' is a string terminated by C<"\r\n">.)  You may change the
definition of "record" by supplying the C<recsep> option in the C<tie>
call:

	tie @array, 'Tie::File', $file, recsep => 'es';

This says that records are delimited by the string C<es>.  If the file
contained the following data:

	Curse these pesky flies!\n

then the C<@array> would appear to have four elements:

	"Curse th"
	"e p"
	"ky fli"
	"!\n"

An undefined value is not permitted as a record separator.  Perl's
special "paragraph mode" semantics (E<agrave> la C<$/ = "">) are not
emulated.

Records read from the tied array do not have the record separator
string on the end; this is to allow

	$array[17] .= "extra";

to work as expected.

(See L<"autochomp">, below.)  Records stored into the array will have
the record separator string appended before they are written to the
file, if they don't have one already.  For example, if the record
separator string is C<"\n">, then the following two lines do exactly
the same thing:

	$array[17] = "Cherry pie";
	$array[17] = "Cherry pie\n";

The result is that the contents of line 17 of the file will be
replaced with "Cherry pie"; a newline character will separate line 17
from line 18.  This means that this code will do nothing:

	chomp $array[17];

Because the C<chomp>ed value will have the separator reattached when
it is written back to the file.  There is no way to create a file
whose trailing record separator string is missing.

Inserting records that I<contain> the record separator string is not
supported by this module.  It will probably produce a reasonable
result, but what this result will be may change in a future version.
Use 'splice' to insert records or to replace one record with several.

=head2 C<autochomp>

Normally, array elements have the record separator removed, so that if
the file contains the text

	Gold
	Frankincense
	Myrrh

the tied array will appear to contain C<("Gold", "Frankincense",
"Myrrh")>.  If you set C<autochomp> to a false value, the record
separator will not be removed.  If the file above was tied with

	tie @gifts, "Tie::File", $gifts, autochomp => 0;

then the array C<@gifts> would appear to contain C<("Gold\n",
"Frankincense\n", "Myrrh\n")>, or (on Win32 systems) C<("Gold\r\n",
"Frankincense\r\n", "Myrrh\r\n")>.

=head2 C<mode>

Normally, the specified file will be opened for read and write access,
and will be created if it does not exist.  (That is, the flags
C<O_RDWR | O_CREAT> are supplied in the C<open> call.)  If you want to
change this, you may supply alternative flags in the C<mode> option.
See L<Fcntl> for a listing of available flags.
For example:

	# open the file if it exists, but fail if it does not exist
	use Fcntl 'O_RDWR';
	tie @array, 'Tie::File', $file, mode => O_RDWR;

	# create the file if it does not exist
	use Fcntl 'O_RDWR', 'O_CREAT';
	tie @array, 'Tie::File', $file, mode => O_RDWR | O_CREAT;

	# open an existing file in read-only mode
	use Fcntl 'O_RDONLY';
	tie @array, 'Tie::File', $file, mode => O_RDONLY;

Opening the data file in write-only or append mode is not supported.

=head2 C<memory>

This is an upper limit on the amount of memory that C<Tie::File> will
consume at any time while managing the file.  This is used for two
things: managing the I<read cache> and managing the I<deferred write
buffer>.

Records read in from the file are cached, to avoid having to re-read
them repeatedly.  If you read the same record twice, the first time it
will be stored in memory, and the second time it will be fetched from
the I<read cache>.  The amount of data in the read cache will not
exceed the value you specified for C<memory>.  If C<Tie::File> wants
to cache a new record, but the read cache is full, it will make room
by expiring the least-recently visited records from the read cache.

The default memory limit is 2Mib.  You can adjust the maximum read
cache size by supplying the C<memory> option.  The argument is the
desired cache size, in bytes.

 # I have a lot of memory, so use a large cache to speed up access
 tie @array, 'Tie::File', $file, memory => 20_000_000;

Setting the memory limit to 0 will inhibit caching; records will be
fetched from disk every time you examine them.

The C<memory> value is not an absolute or exact limit on the memory
used.  C<Tie::File> objects contains some structures besides the read
cache and the deferred write buffer, whose sizes are not charged
against C<memory>. 

The cache itself consumes about 310 bytes per cached record, so if
your file has many short records, you may want to decrease the cache
memory limit, or else the cache overhead may exceed the size of the
cached data.


=head2 C<dw_size>

(This is an advanced feature.  Skip this section on first reading.)

If you use deferred writing (See L<"Deferred Writing">, below) then
data you write into the array will not be written directly to the
file; instead, it will be saved in the I<deferred write buffer> to be
written out later.  Data in the deferred write buffer is also charged
against the memory limit you set with the C<memory> option.

You may set the C<dw_size> option to limit the amount of data that can
be saved in the deferred write buffer.  This limit may not exceed the
total memory limit.  For example, if you set C<dw_size> to 1000 and
C<memory> to 2500, that means that no more than 1000 bytes of deferred
writes will be saved up.  The space available for the read cache will
vary, but it will always be at least 1500 bytes (if the deferred write
buffer is full) and it could grow as large as 2500 bytes (if the
deferred write buffer is empty.)

If you don't specify a C<dw_size>, it defaults to the entire memory
limit.

=head2 Option Format

C<-mode> is a synonym for C<mode>.  C<-recsep> is a synonym for
C<recsep>.  C<-memory> is a synonym for C<memory>.  You get the
idea.

=head1 Public Methods

The C<tie> call returns an object, say C<$o>.  You may call

	$rec = $o->FETCH($n);
	$o->STORE($n, $rec);

to fetch or store the record at line C<$n>, respectively; similarly
the other tied array methods.  (See L<perltie> for details.)  You may
also call the following methods on this object:

=head2 C<flock>

	$o->flock(MODE)

will lock the tied file.  C<MODE> has the same meaning as the second
argument to the Perl built-in C<flock> function; for example
C<LOCK_SH> or C<LOCK_EX | LOCK_NB>.  (These constants are provided by
the C<use Fcntl ':flock'> declaration.)

C<MODE> is optional; the default is C<LOCK_EX>.

C<Tie::File> maintains an internal table of the byte offset of each
record it has seen in the file.  

When you use C<flock> to lock the file, C<Tie::File> assumes that the
read cache is no longer trustworthy, because another process might
have modified the file since the last time it was read.  Therefore, a
successful call to C<flock> discards the contents of the read cache
and the internal record offset table.

C<Tie::File> promises that the following sequence of operations will
be safe:

	my $o = tie @array, "Tie::File", $filename;
	$o->flock;

In particular, C<Tie::File> will I<not> read or write the file during
the C<tie> call.  (Exception: Using C<mode =E<gt> O_TRUNC> will, of
course, erase the file during the C<tie> call.  If you want to do this
safely, then open the file without C<O_TRUNC>, lock the file, and use
C<@array = ()>.)

The best way to unlock a file is to discard the object and untie the
array.  It is probably unsafe to unlock the file without also untying
it, because if you do, changes may remain unwritten inside the object.
That is why there is no shortcut for unlocking.  If you really want to
unlock the file prematurely, you know what to do; if you don't know
what to do, then don't do it.

All the usual warnings about file locking apply here.  In particular,
note that file locking in Perl is B<advisory>, which means that
holding a lock will not prevent anyone else from reading, writing, or
erasing the file; it only prevents them from getting another lock at
the same time.  Locks are analogous to green traffic lights: If you
have a green light, that does not prevent the idiot coming the other
way from plowing into you sideways; it merely guarantees to you that
the idiot does not also have a green light at the same time.

=head2 C<autochomp>

	my $old_value = $o->autochomp(0);    # disable autochomp option
	my $old_value = $o->autochomp(1);    #  enable autochomp option

	my $ac = $o->autochomp();   # recover current value

See L<"autochomp">, above.

=head2 C<defer>, C<flush>, C<discard>, and C<autodefer>

See L<"Deferred Writing">, below.

=head2 C<offset>

	$off = $o->offset($n);

This method returns the byte offset of the start of the C<$n>th record
in the file.  If there is no such record, it returns an undefined
value.

=head1 Tying to an already-opened filehandle

If C<$fh> is a filehandle, such as is returned by C<IO::File> or one
of the other C<IO> modules, you may use:

	tie @array, 'Tie::File', $fh, ...;

Similarly if you opened that handle C<FH> with regular C<open> or
C<sysopen>, you may use:

	tie @array, 'Tie::File', \*FH, ...;

Handles that were opened write-only won't work.  Handles that were
opened read-only will work as long as you don't try to modify the
array.  Handles must be attached to seekable sources of data---that
means no pipes or sockets.  If C<Tie::File> can detect that you
supplied a non-seekable handle, the C<tie> call will throw an
exception.  (On Unix systems, it can detect this.)

Note that Tie::File will only close any filehandles that it opened
internally.  If you passed it a filehandle as above, you "own" the
filehandle, and are responsible for closing it after you have untied
the @array.

Tie::File calls C<binmode> on filehandles that it opens internally, 
but not on filehandles passed in by the user. For consistency,
especially if using the tied files cross-platform, you may wish to
call C<binmode> on the filehandle prior to tying the file. 

=head1 Deferred Writing

(This is an advanced feature.  Skip this section on first reading.)

Normally, modifying a C<Tie::File> array writes to the underlying file
immediately.  Every assignment like C<$a[3] = ...> rewrites as much of
the file as is necessary; typically, everything from line 3 through
the end will need to be rewritten.  This is the simplest and most
transparent behavior.  Performance even for large files is reasonably
good.

However, under some circumstances, this behavior may be excessively
slow.  For example, suppose you have a million-record file, and you
want to do:

	for (@FILE) {
	  $_ = "> $_";
	}

The first time through the loop, you will rewrite the entire file,
from line 0 through the end.  The second time through the loop, you
will rewrite the entire file from line 1 through the end.  The third
time through the loop, you will rewrite the entire file from line 2 to
the end.  And so on.

If the performance in such cases is unacceptable, you may defer the
actual writing, and then have it done all at once.  The following loop
will perform much better for large files:

	(tied @a)->defer;
	for (@a) {
	  $_ = "> $_";
	}
	(tied @a)->flush;

If C<Tie::File>'s memory limit is large enough, all the writing will
done in memory.  Then, when you call C<-E<gt>flush>, the entire file
will be rewritten in a single pass.

(Actually, the preceding discussion is something of a fib.  You don't
need to enable deferred writing to get good performance for this
common case, because C<Tie::File> will do it for you automatically
unless you specifically tell it not to.  See L</Autodeferring>,
below.)

Calling C<-E<gt>flush> returns the array to immediate-write mode.  If
you wish to discard the deferred writes, you may call C<-E<gt>discard>
instead of C<-E<gt>flush>.  Note that in some cases, some of the data
will have been written already, and it will be too late for
C<-E<gt>discard> to discard all the changes.  Support for
C<-E<gt>discard> may be withdrawn in a future version of C<Tie::File>.

Deferred writes are cached in memory up to the limit specified by the
C<dw_size> option (see above).  If the deferred-write buffer is full
and you try to write still more deferred data, the buffer will be
flushed.  All buffered data will be written immediately, the buffer
will be emptied, and the now-empty space will be used for future
deferred writes.

If the deferred-write buffer isn't yet full, but the total size of the
buffer and the read cache would exceed the C<memory> limit, the oldest
records will be expired from the read cache until the total size is
under the limit.

C<push>, C<pop>, C<shift>, C<unshift>, and C<splice> cannot be
deferred.  When you perform one of these operations, any deferred data
is written to the file and the operation is performed immediately.
This may change in a future version.

If you resize the array with deferred writing enabled, the file will
be resized immediately, but deferred records will not be written.
This has a surprising consequence: C<@a = (...)> erases the file
immediately, but the writing of the actual data is deferred.  This
might be a bug.  If it is a bug, it will be fixed in a future version.

=head2 Autodeferring

C<Tie::File> tries to guess when deferred writing might be helpful,
and to turn it on and off automatically. 

	for (@a) {
	  $_ = "> $_";
	}

In this example, only the first two assignments will be done
immediately; after this, all the changes to the file will be deferred
up to the user-specified memory limit.

You should usually be able to ignore this and just use the module
without thinking about deferring.  However, special applications may
require fine control over which writes are deferred, or may require
that all writes be immediate.  To disable the autodeferment feature,
use

	(tied @o)->autodefer(0);

or

       	tie @array, 'Tie::File', $file, autodefer => 0;


Similarly, C<-E<gt>autodefer(1)> re-enables autodeferment, and 
C<-E<gt>autodefer()> recovers the current value of the autodefer setting.


=head1 CONCURRENT ACCESS TO FILES

Caching and deferred writing are inappropriate if you want the same
file to be accessed simultaneously from more than one process.  Other
optimizations performed internally by this module are also
incompatible with concurrent access.  A future version of this module will
support a C<concurrent =E<gt> 1> option that enables safe concurrent access.

Previous versions of this documentation suggested using C<memory
=E<gt> 0> for safe concurrent access.  This was mistaken.  Tie::File
will not support safe concurrent access before version 0.96.

=head1 CAVEATS

(That's Latin for 'warnings'.)

=over 4

=item *

Reasonable effort was made to make this module efficient.  Nevertheless,
changing the size of a record in the middle of a large file will
always be fairly slow, because everything after the new record must be
moved.

=item *

The behavior of tied arrays is not precisely the same as for regular
arrays.  For example:

	# This DOES print "How unusual!"
	undef $a[10];  print "How unusual!\n" if defined $a[10];

C<undef>-ing a C<Tie::File> array element just blanks out the
corresponding record in the file.  When you read it back again, you'll
get the empty string, so the supposedly-C<undef>'ed value will be
defined.  Similarly, if you have C<autochomp> disabled, then

	# This DOES print "How unusual!" if 'autochomp' is disabled
	undef $a[10];
        print "How unusual!\n" if $a[10];

Because when C<autochomp> is disabled, C<$a[10]> will read back as
C<"\n"> (or whatever the record separator string is.)  

There are other minor differences, particularly regarding C<exists>
and C<delete>, but in general, the correspondence is extremely close.

=item *

I have supposed that since this module is concerned with file I/O,
almost all normal use of it will be heavily I/O bound.  This means
that the time to maintain complicated data structures inside the
module will be dominated by the time to actually perform the I/O.
When there was an opportunity to spend CPU time to avoid doing I/O, I
usually tried to take it.

=item *

You might be tempted to think that deferred writing is like
transactions, with C<flush> as C<commit> and C<discard> as
C<rollback>, but it isn't, so don't.

=item *

There is a large memory overhead for each record offset and for each
cache entry: about 310 bytes per cached data record, and about 21 bytes
per offset table entry.

The per-record overhead will limit the maximum number of records you
can access per file. Note that I<accessing> the length of the array
via C<$x = scalar @tied_file> accesses B<all> records and stores their
offsets.  The same for C<foreach (@tied_file)>, even if you exit the
loop early.

=back

=head1 SUBCLASSING

This version promises absolutely nothing about the internals, which
may change without notice.  A future version of the module will have a
well-defined and stable subclassing API.

=head1 WHAT ABOUT C<DB_File>?

People sometimes point out that L<DB_File> will do something similar,
and ask why C<Tie::File> module is necessary.

There are a number of reasons that you might prefer C<Tie::File>.
A list is available at C<L<http://perl.plover.com/TieFile/why-not-DB_File>>.

=head1 AUTHOR

Mark Jason Dominus

To contact the author, send email to: C<mjd-perl-tiefile+@plover.com>

To receive an announcement whenever a new version of this module is
released, send a blank email message to
C<mjd-perl-tiefile-subscribe@plover.com>.

The most recent version of this module, including documentation and
any news of importance, will be available at

	http://perl.plover.com/TieFile/


=head1 LICENSE

C<Tie::File> version 0.96 is copyright (C) 2003 Mark Jason Dominus.

This library is free software; you may redistribute it and/or modify
it under the same terms as Perl itself.

These terms are your choice of any of (1) the Perl Artistic Licence,
or (2) version 2 of the GNU General Public License as published by the
Free Software Foundation, or (3) any later version of the GNU General
Public License.

This library 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.

You should have received a copy of the GNU General Public License
along with this library program; it should be in the file C<COPYING>.
If not, write to the Free Software Foundation, Inc., 51 Franklin Street,
Fifth Floor, Boston, MA  02110-1301, USA

For licensing inquiries, contact the author at:

	Mark Jason Dominus
	255 S. Warnock St.
	Philadelphia, PA 19107

=head1 WARRANTY

C<Tie::File> version 0.98 comes with ABSOLUTELY NO WARRANTY.
For details, see the license.

=head1 THANKS

Gigantic thanks to Jarkko Hietaniemi, for agreeing to put this in the
core when I hadn't written it yet, and for generally being helpful,
supportive, and competent.  (Usually the rule is "choose any one.")
Also big thanks to Abhijit Menon-Sen for all of the same things.

Special thanks to Craig Berry and Peter Prymmer (for VMS portability
help), Randy Kobes (for Win32 portability help), Clinton Pierce and
Autrijus Tang (for heroic eleventh-hour Win32 testing above and beyond
the call of duty), Michael G Schwern (for testing advice), and the
rest of the CPAN testers (for testing generally).

Special thanks to Tels for suggesting several speed and memory
optimizations.

Additional thanks to:
Edward Avis /
Mattia Barbon /
Tom Christiansen /
Gerrit Haase /
Gurusamy Sarathy /
Jarkko Hietaniemi (again) /
Nikola Knezevic /
John Kominetz /
Nick Ing-Simmons /
Tassilo von Parseval /
H. Dieter Pearcey /
Slaven Rezic /
Eric Roode /
Peter Scott /
Peter Somu /
Autrijus Tang (again) /
Tels (again) /
Juerd Waalboer /
Todd Rinaldo

=head1 TODO

More tests.  (Stuff I didn't think of yet.)

Paragraph mode?

Fixed-length mode.  Leave-blanks mode.

Maybe an autolocking mode?

For many common uses of the module, the read cache is a liability.
For example, a program that inserts a single record, or that scans the
file once, will have a cache hit rate of zero.  This suggests a major
optimization: The cache should be initially disabled.  Here's a hybrid
approach: Initially, the cache is disabled, but the cache code
maintains statistics about how high the hit rate would be *if* it were
enabled.  When it sees the hit rate get high enough, it enables
itself.  The STAT comments in this code are the beginning of an
implementation of this.

Record locking with fcntl()?  Then the module might support an undo
log and get real transactions.  What a tour de force that would be.

Keeping track of the highest cached record. This would allow reads-in-a-row
to skip the cache lookup faster (if reading from 1..N with empty cache at
start, the last cached value will be always N-1).

More tests.

=cut

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     