#
# Complex numbers and associated mathematical functions
# -- Raphael Manfredi	Since Sep 1996
# -- Jarkko Hietaniemi	Since Mar 1997
# -- Daniel S. Lewart	Since Sep 1997
#

package Math::Complex;

{ use 5.006; }
use strict;

our $VERSION = 1.59_02;

use Config;

our ($Inf, $ExpInf);
our ($vax_float, $has_inf, $has_nan);

BEGIN {
    $vax_float = (pack("d",1) =~ /^[\x80\x10]\x40/);
    $has_inf   = !$vax_float;
    $has_nan   = !$vax_float;

    unless ($has_inf) {
      # For example in vax, there is no Inf,
      # and just mentioning the DBL_MAX (1.70141183460469229e+38)
      # causes SIGFPE.

      # These are pretty useless without a real infinity,
      # but setting them makes for less warnings about their
      # undefined values.
      $Inf = "Inf";
      $ExpInf = "Inf";
      return;
    }

    my %DBL_MAX =  # These are IEEE 754 maxima.
	(
	  4  => '1.70141183460469229e+38',
	  8  => '1.7976931348623157e+308',
	 # AFAICT the 10, 12, and 16-byte long doubles
	 # all have the same maximum.
	 10 => '1.1897314953572317650857593266280070162E+4932',
	 12 => '1.1897314953572317650857593266280070162E+4932',
	 16 => '1.1897314953572317650857593266280070162E+4932',
	);

    my $nvsize = $Config{nvsize} ||
	        ($Config{uselongdouble} && $Config{longdblsize}) ||
                 $Config{doublesize};
    die "Math::Complex: Could not figure out nvsize\n"
	unless defined $nvsize;
    die "Math::Complex: Cannot not figure out max nv (nvsize = $nvsize)\n"
	unless defined $DBL_MAX{$nvsize};
    my $DBL_MAX = eval $DBL_MAX{$nvsize};
    die "Math::Complex: Could not figure out max nv (nvsize = $nvsize)\n"
	unless defined $DBL_MAX;
    my $BIGGER_THAN_THIS = 1e30;  # Must find something bigger than this.
    if ($^O eq 'unicosmk') {
	$Inf = $DBL_MAX;
    } else {
	local $SIG{FPE} = sub { };
        local $!;
	# We do want an arithmetic overflow, Inf INF inf Infinity.
	for my $t (
	    'exp(99999)',  # Enough even with 128-bit long doubles.
	    'inf',
	    'Inf',
	    'INF',
	    'infinity',
	    'Infinity',
	    'INFINITY',
	    '1e99999',
	    ) {
	    local $^W = 0;
	    my $i = eval "$t+1.0";
	    if (defined $i && $i > $BIGGER_THAN_THIS) {
		$Inf = $i;
		last;
	    }
          }
	$Inf = $DBL_MAX unless defined $Inf;  # Oh well, close enough.
	die "Math::Complex: Could not get Infinity"
	    unless $Inf > $BIGGER_THAN_THIS;
	$ExpInf = eval 'exp(99999)';
      }
    # print "# On this machine, Inf = '$Inf'\n";
}

use Scalar::Util qw(set_prototype);

use warnings;
no warnings 'syntax';  # To avoid the (_) warnings.

BEGIN {
    # For certain functions that we override, in 5.10 or better
    # we can set a smarter prototype that will handle the lexical $_
    # (also a 5.10+ feature).
    if ($] >= 5.010000) {
        set_prototype \&abs, '_';
        set_prototype \&cos, '_';
        set_prototype \&exp, '_';
        set_prototype \&log, '_';
        set_prototype \&sin, '_';
        set_prototype \&sqrt, '_';
    }
}

my $i;
my %LOGN;

# Regular expression for floating point numbers.
# These days we could use Scalar::Util::lln(), I guess.
my $gre = qr'\s*([\+\-]?(?:(?:(?:\d+(?:_\d+)*(?:\.\d*(?:_\d+)*)?|\.\d+(?:_\d+)*)(?:[eE][\+\-]?\d+(?:_\d+)*)?))|inf)'i;

require Exporter;

our @ISA = qw(Exporter);

my @trig = qw(
	      pi
	      tan
	      csc cosec sec cot cotan
	      asin acos atan
	      acsc acosec asec acot acotan
	      sinh cosh tanh
	      csch cosech sech coth cotanh
	      asinh acosh atanh
	      acsch acosech asech acoth acotanh
	     );

our @EXPORT = (qw(
	     i Re Im rho theta arg
	     sqrt log ln
	     log10 logn cbrt root
	     cplx cplxe
	     atan2
	     ),
	   @trig);

my @pi = qw(pi pi2 pi4 pip2 pip4 Inf);

our @EXPORT_OK = @pi;

our %EXPORT_TAGS = (
    'trig' => [@trig],
    'pi' => [@pi],
);

use overload
	'='	=> \&_copy,
	'+='	=> \&_plus,
	'+'	=> \&_plus,
	'-='	=> \&_minus,
	'-'	=> \&_minus,
	'*='	=> \&_multiply,
	'*'	=> \&_multiply,
	'/='	=> \&_divide,
	'/'	=> \&_divide,
	'**='	=> \&_power,
	'**'	=> \&_power,
	'=='	=> \&_numeq,
	'<=>'	=> \&_spaceship,
	'neg'	=> \&_negate,
	'~'	=> \&_conjugate,
	'abs'	=> \&abs,
	'sqrt'	=> \&sqrt,
	'exp'	=> \&exp,
	'log'	=> \&log,
	'sin'	=> \&sin,
	'cos'	=> \&cos,
	'atan2'	=> \&atan2,
        '""'    => \&_stringify;

#
# Package "privates"
#

my %DISPLAY_FORMAT = ('style' => 'cartesian',
		      'polar_pretty_print' => 1);
my $eps            = 1e-14;		# Epsilon

#
# Object attributes (internal):
#	cartesian	[real, imaginary] -- cartesian form
#	polar		[rho, theta] -- polar form
#	c_dirty		cartesian form not up-to-date
#	p_dirty		polar form not up-to-date
#	display		display format (package's global when not set)
#

# Die on bad *make() arguments.

sub _cannot_make {
    die "@{[(caller(1))[3]]}: Cannot take $_[0] of '$_[1]'.\n";
}

sub _make {
    my $arg = shift;
    my ($p, $q);

    if ($arg =~ /^$gre$/) {
	($p, $q) = ($1, 0);
    } elsif ($arg =~ /^(?:$gre)?$gre\s*i\s*$/) {
	($p, $q) = ($1 || 0, $2);
    } elsif ($arg =~ /^\s*\(\s*$gre\s*(?:,\s*$gre\s*)?\)\s*$/) {
	($p, $q) = ($1, $2 || 0);
    }

    if (defined $p) {
	$p =~ s/^\+//;
	$p =~ s/^(-?)inf$/"${1}9**9**9"/e if $has_inf;
	$q =~ s/^\+//;
	$q =~ s/^(-?)inf$/"${1}9**9**9"/e if $has_inf;
    }

    return ($p, $q);
}

sub _emake {
    my $arg = shift;
    my ($p, $q);

    if ($arg =~ /^\s*\[\s*$gre\s*(?:,\s*$gre\s*)?\]\s*$/) {
	($p, $q) = ($1, $2 || 0);
    } elsif ($arg =~ m!^\s*\[\s*$gre\s*(?:,\s*([-+]?\d*\s*)?pi(?:/\s*(\d+))?\s*)?\]\s*$!) {
	($p, $q) = ($1, ($2 eq '-' ? -1 : ($2 || 1)) * pi() / ($3 || 1));
    } elsif ($arg =~ /^\s*\[\s*$gre\s*\]\s*$/) {
	($p, $q) = ($1, 0);
    } elsif ($arg =~ /^\s*$gre\s*$/) {
	($p, $q) = ($1, 0);
    }

    if (defined $p) {
	$p =~ s/^\+//;
	$q =~ s/^\+//;
	$p =~ s/^(-?)inf$/"${1}9**9**9"/e if $has_inf;
	$q =~ s/^(-?)inf$/"${1}9**9**9"/e if $has_inf;
    }

    return ($p, $q);
}

sub _copy {
    my $self = shift;
    my $clone = {%$self};
    if ($self->{'cartesian'}) {
	$clone->{'cartesian'} = [@{$self->{'cartesian'}}];
    }
    if ($self->{'polar'}) {
	$clone->{'polar'} = [@{$self->{'polar'}}];
    }
    bless $clone,__PACKAGE__;
    return $clone;
}

#
# ->make
#
# Create a new complex number (cartesian form)
#
sub make {
    my $self = bless {}, shift;
    my ($re, $im);
    if (@_ == 0) {
	($re, $im) = (0, 0);
    } elsif (@_ == 1) {
	return (ref $self)->emake($_[0])
	    if ($_[0] =~ /^\s*\[/);
	($re, $im) = _make($_[0]);
    } elsif (@_ == 2) {
	($re, $im) = @_;
    }
    if (defined $re) {
	_cannot_make("real part",      $re) unless $re =~ /^$gre$/;
    }
    $im ||= 0;
    _cannot_make("imaginary part", $im) unless $im =~ /^$gre$/;
    $self->_set_cartesian([$re, $im ]);
    $self->display_format('cartesian');

    return $self;
}

#
# ->emake
#
# Create a new complex number (exponential form)
#
sub emake {
    my $self = bless {}, shift;
    my ($rho, $theta);
    if (@_ == 0) {
	($rho, $theta) = (0, 0);
    } elsif (@_ == 1) {
	return (ref $self)->make($_[0])
	    if ($_[0] =~ /^\s*\(/ || $_[0] =~ /i\s*$/);
	($rho, $theta) = _emake($_[0]);
    } elsif (@_ == 2) {
	($rho, $theta) = @_;
    }
    if (defined $rho && defined $theta) {
	if ($rho < 0) {
	    $rho   = -$rho;
	    $theta = ($theta <= 0) ? $theta + pi() : $theta - pi();
	}
    }
    if (defined $rho) {
	_cannot_make("rho",   $rho)   unless $rho   =~ /^$gre$/;
    }
    $theta ||= 0;
    _cannot_make("theta", $theta) unless $theta =~ /^$gre$/;
    $self->_set_polar([$rho, $theta]);
    $self->display_format('polar');

    return $self;
}

sub new { &make }		# For backward compatibility only.

#
# cplx
#
# Creates a complex number from a (re, im) tuple.
# This avoids the burden of writing Math::Complex->make(re, im).
#
sub cplx {
	return __PACKAGE__->make(@_);
}

#
# cplxe
#
# Creates a complex number from a (rho, theta) tuple.
# This avoids the burden of writing Math::Complex->emake(rho, theta).
#
sub cplxe {
	return __PACKAGE__->emake(@_);
}

#
# pi
#
# The number defined as pi = 180 degrees
#
sub pi () { 4 * CORE::atan2(1, 1) }

#
# pi2
#
# The full circle
#
sub pi2 () { 2 * pi }

#
# pi4
#
# The full circle twice.
#
sub pi4 () { 4 * pi }

#
# pip2
#
# The quarter circle
#
sub pip2 () { pi / 2 }

#
# pip4
#
# The eighth circle.
#
sub pip4 () { pi / 4 }

#
# _uplog10
#
# Used in log10().
#
sub _uplog10 () { 1 / CORE::log(10) }

#
# i
#
# The number defined as i*i = -1;
#
sub i () {
        return $i if ($i);
	$i = bless {};
	$i->{'cartesian'} = [0, 1];
	$i->{'polar'}     = [1, pip2];
	$i->{c_dirty} = 0;
	$i->{p_dirty} = 0;
	return $i;
}

#
# _ip2
#
# Half of i.
#
sub _ip2 () { i / 2 }

#
# Attribute access/set routines
#

sub _cartesian {$_[0]->{c_dirty} ?
		   $_[0]->_update_cartesian : $_[0]->{'cartesian'}}
sub _polar     {$_[0]->{p_dirty} ?
		   $_[0]->_update_polar : $_[0]->{'polar'}}

sub _set_cartesian { $_[0]->{p_dirty}++; $_[0]->{c_dirty} = 0;
		     $_[0]->{'cartesian'} = $_[1] }
sub _set_polar     { $_[0]->{c_dirty}++; $_[0]->{p_dirty} = 0;
		     $_[0]->{'polar'} = $_[1] }

#
# ->_update_cartesian
#
# Recompute and return the cartesian form, given accurate polar form.
#
sub _update_cartesian {
	my $self = shift;
	my ($r, $t) = @{$self->{'polar'}};
	$self->{c_dirty} = 0;
	return $self->{'cartesian'} = [$r * CORE::cos($t), $r * CORE::sin($t)];
}

#
#
# ->_update_polar
#
# Recompute and return the polar form, given accurate cartesian form.
#
sub _update_polar {
	my $self = shift;
	my ($x, $y) = @{$self->{'cartesian'}};
	$self->{p_dirty} = 0;
	return $self->{'polar'} = [0, 0] if $x == 0 && $y == 0;
	return $self->{'polar'} = [CORE::sqrt($x*$x + $y*$y),
				   CORE::atan2($y, $x)];
}

#
# (_plus)
#
# Computes z1+z2.
#
sub _plus {
	my ($z1, $z2, $regular) = @_;
	my ($re1, $im1) = @{$z1->_cartesian};
	$z2 = cplx($z2) unless ref $z2;
	my ($re2, $im2) = ref $z2 ? @{$z2->_cartesian} : ($z2, 0);
	unless (defined $regular) {
		$z1->_set_cartesian([$re1 + $re2, $im1 + $im2]);
		return $z1;
	}
	return (ref $z1)->make($re1 + $re2, $im1 + $im2);
}

#
# (_minus)
#
# Computes z1-z2.
#
sub _minus {
	my ($z1, $z2, $inverted) = @_;
	my ($re1, $im1) = @{$z1->_cartesian};
	$z2 = cplx($z2) unless ref $z2;
	my ($re2, $im2) = @{$z2->_cartesian};
	unless (defined $inverted) {
		$z1->_set_cartesian([$re1 - $re2, $im1 - $im2]);
		return $z1;
	}
	return $inverted ?
		(ref $z1)->make($re2 - $re1, $im2 - $im1) :
		(ref $z1)->make($re1 - $re2, $im1 - $im2);

}

#
# (_multiply)
#
# Computes z1*z2.
#
sub _multiply {
        my ($z1, $z2, $regular) = @_;
	if ($z1->{p_dirty} == 0 and ref $z2 and $z2->{p_dirty} == 0) {
	    # if both polar better use polar to avoid rounding errors
	    my ($r1, $t1) = @{$z1->_polar};
	    my ($r2, $t2) = @{$z2->_polar};
	    my $t = $t1 + $t2;
	    if    ($t >   pi()) { $t -= pi2 }
	    elsif ($t <= -pi()) { $t += pi2 }
	    unless (defined $regular) {
		$z1->_set_polar([$r1 * $r2, $t]);
		return $z1;
	    }
	    return (ref $z1)->emake($r1 * $r2, $t);
	} else {
	    my ($x1, $y1) = @{$z1->_cartesian};
	    if (ref $z2) {
		my ($x2, $y2) = @{$z2->_cartesian};
		return (ref $z1)->make($x1*$x2-$y1*$y2, $x1*$y2+$y1*$x2);
	    } else {
		return (ref $z1)->make($x1*$z2, $y1*$z2);
	    }
	}
}

#
# _divbyzero
#
# Die on division by zero.
#
sub _divbyzero {
    my $mess = "$_[0]: Division by zero.\n";

    if (defined $_[1]) {
	$mess .= "(Because in the definition of $_[0], the divisor ";
	$mess .= "$_[1] " unless ("$_[1]" eq '0');
	$mess .= "is 0)\n";
    }

    my @up = caller(1);

    $mess .= "Died at $up[1] line $up[2].\n";

    die $mess;
}

#
# (_divide)
#
# Computes z1/z2.
#
sub _divide {
	my ($z1, $z2, $inverted) = @_;
	if ($z1->{p_dirty} == 0 and ref $z2 and $z2->{p_dirty} == 0) {
	    # if both polar better use polar to avoid rounding errors
	    my ($r1, $t1) = @{$z1->_polar};
	    my ($r2, $t2) = @{$z2->_polar};
	    my $t;
	    if ($inverted) {
		_divbyzero "$z2/0" if ($r1 == 0);
		$t = $t2 - $t1;
		if    ($t >   pi()) { $t -= pi2 }
		elsif ($t <= -pi()) { $t += pi2 }
		return (ref $z1)->emake($r2 / $r1, $t);
	    } else {
		_divbyzero "$z1/0" if ($r2 == 0);
		$t = $t1 - $t2;
		if    ($t >   pi()) { $t -= pi2 }
		elsif ($t <= -pi()) { $t += pi2 }
		return (ref $z1)->emake($r1 / $r2, $t);
	    }
	} else {
	    my ($d, $x2, $y2);
	    if ($inverted) {
		($x2, $y2) = @{$z1->_cartesian};
		$d = $x2*$x2 + $ern, $message_spec)>

The result is the same as C<xhdr> except the is will be restricted to
headers where the text of the header matches C<$pattern>

=item C<xrover($message_spec)>

The XROVER command returns reference information for the article(s)
specified.

Returns a reference to a HASH where the keys are the message numbers and the
values are the References: lines from the articles

=item C<listgroup([$group])>

Returns a reference to a list of all the active messages in C<$group>, or
the current group if C<$group> is not specified.

=item C<reader()>

Tell the server that you are a reader and not another server.

This is required by some servers. For example if you are connecting to
an INN server and you have transfer permission your connection will
be connected to the transfer daemon, not the NNTP daemon. Issuing
this command will cause the transfer daemon to hand over control
to the NNTP daemon.

Some servers do not understand this command, but issuing it and ignoring
the response is harmless.

=back

=head2 Unsupported

The following NNTP command are unsupported by the package, and there are
no plans to do so.

    AUTHINFO GENERIC
    XTHREAD
    XSEARCH
    XINDEX

=head2 Definitions

=over 4

=item $message_spec

C<$message_spec> is either a single message-id, a single message number, or
a reference to a list of two message numbers.

If C<$message_spec> is a reference to a list of two message numbers and the
second number in a range is less than or equal to the first then the range
represents all messages in the group after the first message number.

B<NOTE> For compatibility reasons only with earlier versions of Net::NNTP
a message spec can be passed as a list of two numbers, this is deprecated
and a reference to the list should now be passed

=item $pattern

The C<NNTP> protocol uses the C<WILDMAT> format for patterns.
The WILDMAT format was first developed by Rich Salz based on
the format used in the UNIX "find" command to articulate
file names. It was developed to provide a uniform mechanism
for matching patterns in the same manner that the UNIX shell
matches filenames.

Patterns are implicitly anchored at the
beginning and end of each string when testing for a match.

There are five pattern matching operations other than a strict
one-to-one match between the pattern and the source to be
checked for a match.

The first is an asterisk C<*> to match any sequence of zero or more
characters.

The second is a question mark C<?> to match any single character. The
third specifies a specific set of characters.

The set is specified as a list of characters, or as a range of characters
where the beginning and end of the range are separated by a minus (or dash)
character, or as any combination of lists and ranges. The dash can
also be included in the set as a character it if is the beginning
or end of the set. This set is enclosed in square brackets. The
close square bracket C<]> may be used in a set if it is the first
character in the set.

The fourth operation is the same as the
logical not of the third operation and is specified the same
way as the third with the addition of a caret character C<^> at
the beginning of the test string just inside the open square
bracket.

The final operation uses the backslash character to
invalidate the special meaning of an open square bracket C<[>,
the asterisk, backslash or the question mark. Two backslashes in
sequence will result in the evaluation of the backslash as a
character with no special meaning.

=over 4

=item Examples

=item C<[^]-]>

matches any single character other than a close square
bracket or a minus sign/dash.

=item C<*bdc>

matches any string that ends with the string "bdc"
including the string "bdc" (without quotes).

=item C<[0-9a-zA-Z]>

matches any single printable alphanumeric ASCII character.

=item C<a??d>

matches any four character string which begins
with a and ends with d.

=back

=back

=head1 EXPORTS

I<None>.

=head1 KNOWN BUGS

See L<https://rt.cpan.org/Dist/Display.html?Status=Active&Queue=libnet>.

=head1 SEE ALSO

L<Net::Cmd>,
L<IO::Socket::SSL>.

=head1 AUTHOR

Graham Barr E<lt>L<gbarr@pobox.com|mailto:gbarr@pobox.com>E<gt>.

Steve Hay E<lt>L<shay@cpan.org|mailto:shay@cpan.org>E<gt> is now maintaining
libnet as of version 1.22_02.

=head1 COPYRIGHT

Copyright (C) 1995-1997 Graham Barr.  All rights reserved.

Copyright (C) 2013-2016, 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 3.14

=head1 DATE

23 Dec 2020

=head1 HISTORY

See the F<Changes> file.

=cut
