Upgrade to Math::BigInt 1.51.
[p5sagit/p5-mst-13.2.git] / lib / Math / BigInt.pm
1 # The following hash values are used:
2 #   value: unsigned int with actual value (as a Math::BigInt::Calc or similiar)
3 #   sign : +,-,NaN,+inf,-inf
4 #   _a   : accuracy
5 #   _p   : precision
6 #   _f   : flags, used by MBF to flag parts of a float as untouchable
7
8 # Remember not to take shortcuts ala $xs = $x->{value}; $CALC->foo($xs); since
9 # underlying lib might change the reference!
10
11 package Math::BigInt;
12 my $class = "Math::BigInt";
13 require 5.005;
14
15 $VERSION = '1.51';
16 use Exporter;
17 @ISA =       qw( Exporter );
18 @EXPORT_OK = qw( objectify _swap bgcd blcm); 
19 use vars qw/$round_mode $accuracy $precision $div_scale $rnd_mode/;
20 use vars qw/$upgrade $downgrade/;
21 use strict;
22
23 # Inside overload, the first arg is always an object. If the original code had
24 # it reversed (like $x = 2 * $y), then the third paramater indicates this
25 # swapping. To make it work, we use a helper routine which not only reswaps the
26 # params, but also makes a new object in this case. See _swap() for details,
27 # especially the cases of operators with different classes.
28
29 # For overloaded ops with only one argument we simple use $_[0]->copy() to
30 # preserve the argument.
31
32 # Thus inheritance of overload operators becomes possible and transparent for
33 # our subclasses without the need to repeat the entire overload section there.
34
35 use overload
36 '='     =>      sub { $_[0]->copy(); },
37
38 # '+' and '-' do not use _swap, since it is a triffle slower. If you want to
39 # override _swap (if ever), then override overload of '+' and '-', too!
40 # for sub it is a bit tricky to keep b: b-a => -a+b
41 '-'     =>      sub { my $c = $_[0]->copy; $_[2] ?
42                    $c->bneg()->badd($_[1]) :
43                    $c->bsub( $_[1]) },
44 '+'     =>      sub { $_[0]->copy()->badd($_[1]); },
45
46 # some shortcuts for speed (assumes that reversed order of arguments is routed
47 # to normal '+' and we thus can always modify first arg. If this is changed,
48 # this breaks and must be adjusted.)
49 '+='    =>      sub { $_[0]->badd($_[1]); },
50 '-='    =>      sub { $_[0]->bsub($_[1]); },
51 '*='    =>      sub { $_[0]->bmul($_[1]); },
52 '/='    =>      sub { scalar $_[0]->bdiv($_[1]); },
53 '%='    =>      sub { $_[0]->bmod($_[1]); },
54 '^='    =>      sub { $_[0]->bxor($_[1]); },
55 '&='    =>      sub { $_[0]->band($_[1]); },
56 '|='    =>      sub { $_[0]->bior($_[1]); },
57 '**='   =>      sub { $_[0]->bpow($_[1]); },
58
59 # not supported by Perl yet
60 '..'    =>      \&_pointpoint,
61
62 '<=>'   =>      sub { $_[2] ?
63                       ref($_[0])->bcmp($_[1],$_[0]) : 
64                       ref($_[0])->bcmp($_[0],$_[1])},
65 'cmp'   =>      sub {
66          $_[2] ? 
67                "$_[1]" cmp $_[0]->bstr() :
68                $_[0]->bstr() cmp "$_[1]" },
69
70 'log'   =>      sub { $_[0]->copy()->blog(); }, 
71 'int'   =>      sub { $_[0]->copy(); }, 
72 'neg'   =>      sub { $_[0]->copy()->bneg(); }, 
73 'abs'   =>      sub { $_[0]->copy()->babs(); },
74 'sqrt'  =>      sub { $_[0]->copy()->bsqrt(); },
75 '~'     =>      sub { $_[0]->copy()->bnot(); },
76
77 '*'     =>      sub { my @a = ref($_[0])->_swap(@_); $a[0]->bmul($a[1]); },
78 '/'     =>      sub { my @a = ref($_[0])->_swap(@_);scalar $a[0]->bdiv($a[1]);},
79 '%'     =>      sub { my @a = ref($_[0])->_swap(@_); $a[0]->bmod($a[1]); },
80 '**'    =>      sub { my @a = ref($_[0])->_swap(@_); $a[0]->bpow($a[1]); },
81 '<<'    =>      sub { my @a = ref($_[0])->_swap(@_); $a[0]->blsft($a[1]); },
82 '>>'    =>      sub { my @a = ref($_[0])->_swap(@_); $a[0]->brsft($a[1]); },
83
84 '&'     =>      sub { my @a = ref($_[0])->_swap(@_); $a[0]->band($a[1]); },
85 '|'     =>      sub { my @a = ref($_[0])->_swap(@_); $a[0]->bior($a[1]); },
86 '^'     =>      sub { my @a = ref($_[0])->_swap(@_); $a[0]->bxor($a[1]); },
87
88 # can modify arg of ++ and --, so avoid a new-copy for speed, but don't
89 # use $_[0]->__one(), it modifies $_[0] to be 1!
90 '++'    =>      sub { $_[0]->binc() },
91 '--'    =>      sub { $_[0]->bdec() },
92
93 # if overloaded, O(1) instead of O(N) and twice as fast for small numbers
94 'bool'  =>      sub {
95   # this kludge is needed for perl prior 5.6.0 since returning 0 here fails :-/
96   # v5.6.1 dumps on that: return !$_[0]->is_zero() || undef;                :-(
97   my $t = !$_[0]->is_zero();
98   undef $t if $t == 0;
99   $t;
100   },
101
102 # the original qw() does not work with the TIESCALAR below, why?
103 # Order of arguments unsignificant
104 '""' => sub { $_[0]->bstr(); },
105 '0+' => sub { $_[0]->numify(); }
106 ;
107
108 ##############################################################################
109 # global constants, flags and accessory
110
111 use constant MB_NEVER_ROUND => 0x0001;
112
113 my $NaNOK=1;                            # are NaNs ok?
114 my $nan = 'NaN';                        # constants for easier life
115
116 my $CALC = 'Math::BigInt::Calc';        # module to do low level math
117 my $IMPORT = 0;                         # did import() yet?
118
119 $round_mode = 'even'; # one of 'even', 'odd', '+inf', '-inf', 'zero' or 'trunc'
120 $accuracy   = undef;
121 $precision  = undef;
122 $div_scale  = 40;
123
124 $upgrade = undef;                       # default is no upgrade
125 $downgrade = undef;                     # default is no downgrade
126
127 ##############################################################################
128 # the old code had $rnd_mode, so we need to support it, too
129
130 $rnd_mode   = 'even';
131 sub TIESCALAR  { my ($class) = @_; bless \$round_mode, $class; }
132 sub FETCH      { return $round_mode; }
133 sub STORE      { $rnd_mode = $_[0]->round_mode($_[1]); }
134
135 BEGIN { tie $rnd_mode, 'Math::BigInt'; }
136
137 ############################################################################## 
138
139 sub round_mode
140   {
141   no strict 'refs';
142   # make Class->round_mode() work
143   my $self = shift;
144   my $class = ref($self) || $self || __PACKAGE__;
145   if (defined $_[0])
146     {
147     my $m = shift;
148     die "Unknown round mode $m"
149      if $m !~ /^(even|odd|\+inf|\-inf|zero|trunc)$/;
150     return ${"${class}::round_mode"} = $m;
151     }
152   return ${"${class}::round_mode"};
153   }
154
155 sub upgrade
156   {
157   no strict 'refs';
158   # make Class->round_mode() work
159   my $self = shift;
160   my $class = ref($self) || $self || __PACKAGE__;
161   if (defined $_[0])
162     {
163     my $u = shift;
164     return ${"${class}::upgrade"} = $u;
165     }
166   return ${"${class}::upgrade"};
167   }
168
169 sub div_scale
170   {
171   no strict 'refs';
172   # make Class->round_mode() work
173   my $self = shift;
174   my $class = ref($self) || $self || __PACKAGE__;
175   if (defined $_[0])
176     {
177     die ('div_scale must be greater than zero') if $_[0] < 0;
178     ${"${class}::div_scale"} = shift;
179     }
180   return ${"${class}::div_scale"};
181   }
182
183 sub accuracy
184   {
185   # $x->accuracy($a);           ref($x) $a
186   # $x->accuracy();             ref($x)
187   # Class->accuracy();          class
188   # Class->accuracy($a);        class $a
189
190   my $x = shift;
191   my $class = ref($x) || $x || __PACKAGE__;
192
193   no strict 'refs';
194   # need to set new value?
195   if (@_ > 0)
196     {
197     my $a = shift;
198     die ('accuracy must not be zero') if defined $a && $a == 0;
199     if (ref($x))
200       {
201       # $object->accuracy() or fallback to global
202       $x->bround($a) if defined $a;
203       $x->{_a} = $a;                    # set/overwrite, even if not rounded
204       $x->{_p} = undef;                 # clear P
205       }
206     else
207       {
208       # set global
209       ${"${class}::accuracy"} = $a;
210       ${"${class}::precision"} = undef; # clear P
211       }
212     return $a;                          # shortcut
213     }
214
215   if (ref($x))
216     {
217     # $object->accuracy() or fallback to global
218     return $x->{_a} || ${"${class}::accuracy"};
219     }
220   return ${"${class}::accuracy"};
221   } 
222
223 sub precision
224   {
225   # $x->precision($p);          ref($x) $p
226   # $x->precision();            ref($x)
227   # Class->precision();         class
228   # Class->precision($p);       class $p
229
230   my $x = shift;
231   my $class = ref($x) || $x || __PACKAGE__;
232
233   no strict 'refs';
234   # need to set new value?
235   if (@_ > 0)
236     {
237     my $p = shift;
238     if (ref($x))
239       {
240       # $object->precision() or fallback to global
241       $x->bfround($p) if defined $p;
242       $x->{_p} = $p;                    # set/overwrite, even if not rounded
243       $x->{_a} = undef;                 # clear A
244       }
245     else
246       {
247       # set global
248       ${"${class}::precision"} = $p;
249       ${"${class}::accuracy"} = undef;  # clear A
250       }
251     return $p;                          # shortcut
252     }
253
254   if (ref($x))
255     {
256     # $object->precision() or fallback to global
257     return $x->{_p} || ${"${class}::precision"};
258     }
259   return ${"${class}::precision"};
260   } 
261
262 sub config
263   {
264   # return (later set?) configuration data as hash ref
265   my $class = shift || 'Math::BigInt';
266
267   no strict 'refs';
268   my $lib = $CALC;
269   my $cfg = {
270     lib => $lib,
271     lib_version => ${"${lib}::VERSION"},
272     class => $class,
273     };
274   foreach (
275    qw/upgrade downgrade precisison accuracy round_mode VERSION div_scale/)
276     {
277     $cfg->{lc($_)} = ${"${class}::$_"};
278     };
279   $cfg;
280   }
281
282 sub _scale_a
283   { 
284   # select accuracy parameter based on precedence,
285   # used by bround() and bfround(), may return undef for scale (means no op)
286   my ($x,$s,$m,$scale,$mode) = @_;
287   $scale = $x->{_a} if !defined $scale;
288   $scale = $s if (!defined $scale);
289   $mode = $m if !defined $mode;
290   return ($scale,$mode);
291   }
292
293 sub _scale_p
294   { 
295   # select precision parameter based on precedence,
296   # used by bround() and bfround(), may return undef for scale (means no op)
297   my ($x,$s,$m,$scale,$mode) = @_;
298   $scale = $x->{_p} if !defined $scale;
299   $scale = $s if (!defined $scale);
300   $mode = $m if !defined $mode;
301   return ($scale,$mode);
302   }
303
304 ##############################################################################
305 # constructors
306
307 sub copy
308   {
309   my ($c,$x);
310   if (@_ > 1)
311     {
312     # if two arguments, the first one is the class to "swallow" subclasses
313     ($c,$x) = @_;
314     }
315   else
316     {
317     $x = shift;
318     $c = ref($x);
319     }
320   return unless ref($x); # only for objects
321
322   my $self = {}; bless $self,$c;
323   my $r;
324   foreach my $k (keys %$x)
325     {
326     if ($k eq 'value')
327       {
328       $self->{value} = $CALC->_copy($x->{value}); next;
329       }
330     if (!($r = ref($x->{$k})))
331       {
332       $self->{$k} = $x->{$k}; next;
333       }
334     if ($r eq 'SCALAR')
335       {
336       $self->{$k} = \${$x->{$k}};
337       }
338     elsif ($r eq 'ARRAY')
339       {
340       $self->{$k} = [ @{$x->{$k}} ];
341       }
342     elsif ($r eq 'HASH')
343       {
344       # only one level deep!
345       foreach my $h (keys %{$x->{$k}})
346         {
347         $self->{$k}->{$h} = $x->{$k}->{$h};
348         }
349       }
350     else # normal ref
351       {
352       my $xk = $x->{$k};
353       if ($xk->can('copy'))
354         {
355         $self->{$k} = $xk->copy();
356         }
357       else
358         {
359         $self->{$k} = $xk->new($xk);
360         }
361       }
362     }
363   $self;
364   }
365
366 sub new 
367   {
368   # create a new BigInt object from a string or another BigInt object. 
369   # see hash keys documented at top
370
371   # the argument could be an object, so avoid ||, && etc on it, this would
372   # cause costly overloaded code to be called. The only allowed ops are
373   # ref() and defined.
374
375   my ($class,$wanted,$a,$p,$r) = @_;
376  
377   # avoid numify-calls by not using || on $wanted!
378   return $class->bzero($a,$p) if !defined $wanted;      # default to 0
379   return $class->copy($wanted,$a,$p,$r) if ref($wanted);
380
381   $class->import() if $IMPORT == 0;             # make require work
382   
383   my $self = {}; bless $self, $class;
384   # handle '+inf', '-inf' first
385   if ($wanted =~ /^[+-]?inf$/)
386     {
387     $self->{value} = $CALC->_zero();
388     $self->{sign} = $wanted; $self->{sign} = '+inf' if $self->{sign} eq 'inf';
389     return $self;
390     }
391   # split str in m mantissa, e exponent, i integer, f fraction, v value, s sign
392   my ($mis,$miv,$mfv,$es,$ev) = _split(\$wanted);
393   if (!ref $mis)
394     {
395     die "$wanted is not a number initialized to $class" if !$NaNOK;
396     #print "NaN 1\n";
397     $self->{value} = $CALC->_zero();
398     $self->{sign} = $nan;
399     return $self;
400     }
401   if (!ref $miv)
402     {
403     # _from_hex or _from_bin
404     $self->{value} = $mis->{value};
405     $self->{sign} = $mis->{sign};
406     return $self;       # throw away $mis
407     }
408   # make integer from mantissa by adjusting exp, then convert to bigint
409   $self->{sign} = $$mis;                        # store sign
410   $self->{value} = $CALC->_zero();              # for all the NaN cases
411   my $e = int("$$es$$ev");                      # exponent (avoid recursion)
412   if ($e > 0)
413     {
414     my $diff = $e - CORE::length($$mfv);
415     if ($diff < 0)                              # Not integer
416       {
417       #print "NOI 1\n";
418       return $upgrade->new($wanted,$a,$p,$r) if defined $upgrade;
419       $self->{sign} = $nan;
420       }
421     else                                        # diff >= 0
422       {
423       # adjust fraction and add it to value
424       # print "diff > 0 $$miv\n";
425       $$miv = $$miv . ($$mfv . '0' x $diff);
426       }
427     }
428   else
429     {
430     if ($$mfv ne '')                            # e <= 0
431       {
432       # fraction and negative/zero E => NOI
433       #print "NOI 2 \$\$mfv '$$mfv'\n";
434       return $upgrade->new($wanted,$a,$p,$r) if defined $upgrade;
435       $self->{sign} = $nan;
436       }
437     elsif ($e < 0)
438       {
439       # xE-y, and empty mfv
440       #print "xE-y\n";
441       $e = abs($e);
442       if ($$miv !~ s/0{$e}$//)          # can strip so many zero's?
443         {
444         #print "NOI 3\n";
445         return $upgrade->new($wanted,$a,$p,$r) if defined $upgrade;
446         $self->{sign} = $nan;
447         }
448       }
449     }
450   $self->{sign} = '+' if $$miv eq '0';                  # normalize -0 => +0
451   $self->{value} = $CALC->_new($miv) if $self->{sign} =~ /^[+-]$/;
452   # if any of the globals is set, use them to round and store them inside $self
453   # do not round for new($x,undef,undef) since that is used by MBF to signal
454   # no rounding
455   $self->round($a,$p,$r) unless @_ == 4 && !defined $a && !defined $p;
456   # print "mbi new $self\n";
457   return $self;
458   }
459
460 sub bnan
461   {
462   # create a bigint 'NaN', if given a BigInt, set it to 'NaN'
463   my $self = shift;
464   $self = $class if !defined $self;
465   if (!ref($self))
466     {
467     my $c = $self; $self = {}; bless $self, $c;
468     }
469   $self->import() if $IMPORT == 0;              # make require work
470   return if $self->modify('bnan');
471   $self->{value} = $CALC->_zero();
472   $self->{sign} = $nan;
473   delete $self->{_a}; delete $self->{_p};       # rounding NaN is silly
474   return $self;
475   }
476
477 sub binf
478   {
479   # create a bigint '+-inf', if given a BigInt, set it to '+-inf'
480   # the sign is either '+', or if given, used from there
481   my $self = shift;
482   my $sign = shift; $sign = '+' if !defined $sign || $sign ne '-';
483   $self = $class if !defined $self;
484   if (!ref($self))
485     {
486     my $c = $self; $self = {}; bless $self, $c;
487     }
488   $self->import() if $IMPORT == 0;              # make require work
489   return if $self->modify('binf');
490   $self->{value} = $CALC->_zero();
491   $self->{sign} = $sign.'inf';
492   ($self->{_a},$self->{_p}) = @_;               # take over requested rounding
493   return $self;
494   }
495
496 sub bzero
497   {
498   # create a bigint '+0', if given a BigInt, set it to 0
499   my $self = shift;
500   $self = $class if !defined $self;
501  
502   if (!ref($self))
503     {
504     my $c = $self; $self = {}; bless $self, $c;
505     }
506   $self->import() if $IMPORT == 0;              # make require work
507   return if $self->modify('bzero');
508   $self->{value} = $CALC->_zero();
509   $self->{sign} = '+';
510   if (@_ > 0)
511     {
512     $self->{_a} = $_[0]
513      if (defined $self->{_a} && defined $_[0] && $_[0] > $self->{_a});
514     $self->{_p} = $_[1]
515      if (defined $self->{_p} && defined $_[1] && $_[1] < $self->{_p});
516     }
517   return $self;
518   }
519
520 sub bone
521   {
522   # create a bigint '+1' (or -1 if given sign '-'),
523   # if given a BigInt, set it to +1 or -1, respecively
524   my $self = shift;
525   my $sign = shift; $sign = '+' if !defined $sign || $sign ne '-';
526   $self = $class if !defined $self;
527   
528   if (!ref($self))
529     {
530     my $c = $self; $self = {}; bless $self, $c;
531     }
532   $self->import() if $IMPORT == 0;              # make require work
533   return if $self->modify('bone');
534   $self->{value} = $CALC->_one();
535   $self->{sign} = $sign;
536   if (@_ > 0)
537     {
538     $self->{_a} = $_[0]
539      if (defined $self->{_a} && defined $_[0] && $_[0] > $self->{_a});
540     $self->{_p} = $_[1]
541      if (defined $self->{_p} && defined $_[1] && $_[1] < $self->{_p});
542     }
543   return $self;
544   }
545
546 ##############################################################################
547 # string conversation
548
549 sub bsstr
550   {
551   # (ref to BFLOAT or num_str ) return num_str
552   # Convert number from internal format to scientific string format.
553   # internal format is always normalized (no leading zeros, "-0E0" => "+0E0")
554   my $x = shift; $class = ref($x) || $x; $x = $class->new(shift) if !ref($x); 
555   # my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_); 
556
557   if ($x->{sign} !~ /^[+-]$/)
558     {
559     return $x->{sign} unless $x->{sign} eq '+inf';      # -inf, NaN
560     return 'inf';                                       # +inf
561     }
562   my ($m,$e) = $x->parts();
563   # e can only be positive
564   my $sign = 'e+';      
565   # MBF: my $s = $e->{sign}; $s = '' if $s eq '-'; my $sep = 'e'.$s;
566   return $m->bstr().$sign.$e->bstr();
567   }
568
569 sub bstr 
570   {
571   # make a string from bigint object
572   my $x = shift; $class = ref($x) || $x; $x = $class->new(shift) if !ref($x); 
573   # my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_); 
574  
575   if ($x->{sign} !~ /^[+-]$/)
576     {
577     return $x->{sign} unless $x->{sign} eq '+inf';      # -inf, NaN
578     return 'inf';                                       # +inf
579     }
580   my $es = ''; $es = $x->{sign} if $x->{sign} eq '-';
581   return $es.${$CALC->_str($x->{value})};
582   }
583
584 sub numify 
585   {
586   # Make a "normal" scalar from a BigInt object
587   my $x = shift; $x = $class->new($x) unless ref $x;
588   return $x->{sign} if $x->{sign} !~ /^[+-]$/;
589   my $num = $CALC->_num($x->{value});
590   return -$num if $x->{sign} eq '-';
591   return $num;
592   }
593
594 ##############################################################################
595 # public stuff (usually prefixed with "b")
596
597 sub sign
598   {
599   # return the sign of the number: +/-/NaN
600   my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_); 
601   
602   return $x->{sign};
603   }
604
605 sub _find_round_parameters
606   {
607   # After any operation or when calling round(), the result is rounded by
608   # regarding the A & P from arguments, local parameters, or globals.
609
610   # This procedure finds the round parameters, but it is for speed reasons
611   # duplicated in round. Otherwise, it is tested by the testsuite and used
612   # by fdiv().
613   
614   my ($self,$a,$p,$r,@args) = @_;
615   # $a accuracy, if given by caller
616   # $p precision, if given by caller
617   # $r round_mode, if given by caller
618   # @args all 'other' arguments (0 for unary, 1 for binary ops)
619
620   # leave bigfloat parts alone
621   return ($self) if exists $self->{_f} && $self->{_f} & MB_NEVER_ROUND != 0;
622
623   my $c = ref($self);                           # find out class of argument(s)
624   no strict 'refs';
625
626   # now pick $a or $p, but only if we have got "arguments"
627   if (!defined $a)
628     {
629     foreach ($self,@args)
630       {
631       # take the defined one, or if both defined, the one that is smaller
632       $a = $_->{_a} if (defined $_->{_a}) && (!defined $a || $_->{_a} < $a);
633       }
634     }
635   if (!defined $p)
636     {
637     # even if $a is defined, take $p, to signal error for both defined
638     foreach ($self,@args)
639       {
640       # take the defined one, or if both defined, the one that is bigger
641       # -2 > -3, and 3 > 2
642       $p = $_->{_p} if (defined $_->{_p}) && (!defined $p || $_->{_p} > $p);
643       }
644     }
645   # if still none defined, use globals (#2)
646   $a = ${"$c\::accuracy"} unless defined $a;
647   $p = ${"$c\::precision"} unless defined $p;
648  
649   # no rounding today? 
650   return ($self) unless defined $a || defined $p;               # early out
651
652   # set A and set P is an fatal error
653   return ($self->bnan()) if defined $a && defined $p;
654
655   $r = ${"$c\::round_mode"} unless defined $r;
656   die "Unknown round mode '$r'" if $r !~ /^(even|odd|\+inf|\-inf|zero|trunc)$/;
657  
658   return ($self,$a,$p,$r);
659   }
660
661 sub round
662   {
663   # Round $self according to given parameters, or given second argument's
664   # parameters or global defaults 
665
666   # for speed reasons, _find_round_parameters is embeded here:
667
668   my ($self,$a,$p,$r,@args) = @_;
669   # $a accuracy, if given by caller
670   # $p precision, if given by caller
671   # $r round_mode, if given by caller
672   # @args all 'other' arguments (0 for unary, 1 for binary ops)
673
674   # leave bigfloat parts alone
675   return ($self) if exists $self->{_f} && $self->{_f} & MB_NEVER_ROUND != 0;
676
677   my $c = ref($self);                           # find out class of argument(s)
678   no strict 'refs';
679
680   # now pick $a or $p, but only if we have got "arguments"
681   if (!defined $a)
682     {
683     foreach ($self,@args)
684       {
685       # take the defined one, or if both defined, the one that is smaller
686       $a = $_->{_a} if (defined $_->{_a}) && (!defined $a || $_->{_a} < $a);
687       }
688     }
689   if (!defined $p)
690     {
691     # even if $a is defined, take $p, to signal error for both defined
692     foreach ($self,@args)
693       {
694       # take the defined one, or if both defined, the one that is bigger
695       # -2 > -3, and 3 > 2
696       $p = $_->{_p} if (defined $_->{_p}) && (!defined $p || $_->{_p} > $p);
697       }
698     }
699   # if still none defined, use globals (#2)
700   $a = ${"$c\::accuracy"} unless defined $a;
701   $p = ${"$c\::precision"} unless defined $p;
702  
703   # no rounding today? 
704   return $self unless defined $a || defined $p;         # early out
705
706   # set A and set P is an fatal error
707   return $self->bnan() if defined $a && defined $p;
708
709   $r = ${"$c\::round_mode"} unless defined $r;
710   die "Unknown round mode '$r'" if $r !~ /^(even|odd|\+inf|\-inf|zero|trunc)$/;
711
712   # now round, by calling either fround or ffround:
713   if (defined $a)
714     {
715     $self->bround($a,$r) if !defined $self->{_a} || $self->{_a} >= $a;
716     }
717   else # both can't be undefined due to early out
718     {
719     $self->bfround($p,$r) if !defined $self->{_p} || $self->{_p} <= $p;
720     }
721   $self->bnorm();                       # after round, normalize
722   }
723
724 sub bnorm
725   { 
726   # (numstr or BINT) return BINT
727   # Normalize number -- no-op here
728   my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
729   $x;
730   }
731
732 sub babs 
733   {
734   # (BINT or num_str) return BINT
735   # make number absolute, or return absolute BINT from string
736   my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
737
738   return $x if $x->modify('babs');
739   # post-normalized abs for internal use (does nothing for NaN)
740   $x->{sign} =~ s/^-/+/;
741   $x;
742   }
743
744 sub bneg 
745   { 
746   # (BINT or num_str) return BINT
747   # negate number or make a negated number from string
748   my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
749   
750   return $x if $x->modify('bneg');
751
752   # for +0 dont negate (to have always normalized)
753   $x->{sign} =~ tr/+-/-+/ if !$x->is_zero();    # does nothing for NaN
754   $x;
755   }
756
757 sub bcmp 
758   {
759   # Compares 2 values.  Returns one of undef, <0, =0, >0. (suitable for sort)
760   # (BINT or num_str, BINT or num_str) return cond_code
761   my ($self,$x,$y) = objectify(2,@_);
762
763   if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/))
764     {
765     # handle +-inf and NaN
766     return undef if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
767     return 0 if $x->{sign} eq $y->{sign} && $x->{sign} =~ /^[+-]inf$/;
768     return +1 if $x->{sign} eq '+inf';
769     return -1 if $x->{sign} eq '-inf';
770     return -1 if $y->{sign} eq '+inf';
771     return +1;
772     }
773   # check sign for speed first
774   return 1 if $x->{sign} eq '+' && $y->{sign} eq '-';   # does also 0 <=> -y
775   return -1 if $x->{sign} eq '-' && $y->{sign} eq '+';  # does also -x <=> 0 
776
777   # shortcut
778   my $xz = $x->is_zero();
779   my $yz = $y->is_zero();
780   return 0 if $xz && $yz;                               # 0 <=> 0
781   return -1 if $xz && $y->{sign} eq '+';                # 0 <=> +y
782   return 1 if $yz && $x->{sign} eq '+';                 # +x <=> 0
783   
784   # post-normalized compare for internal use (honors signs)
785   if ($x->{sign} eq '+') 
786     {
787     return 1 if $y->{sign} eq '-'; # 0 check handled above
788     return $CALC->_acmp($x->{value},$y->{value});
789     }
790
791   # $x->{sign} eq '-'
792   return -1 if $y->{sign} eq '+';
793   $CALC->_acmp($y->{value},$x->{value});        # swaped (lib does only 0,1,-1)
794   }
795
796 sub bacmp 
797   {
798   # Compares 2 values, ignoring their signs. 
799   # Returns one of undef, <0, =0, >0. (suitable for sort)
800   # (BINT, BINT) return cond_code
801   my ($self,$x,$y) = objectify(2,@_);
802   
803   if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/))
804     {
805     # handle +-inf and NaN
806     return undef if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
807     return 0 if $x->{sign} =~ /^[+-]inf$/ && $y->{sign} =~ /^[+-]inf$/;
808     return +1;  # inf is always bigger
809     }
810   $CALC->_acmp($x->{value},$y->{value});        # lib does only 0,1,-1
811   }
812
813 sub badd 
814   {
815   # add second arg (BINT or string) to first (BINT) (modifies first)
816   # return result as BINT
817   my ($self,$x,$y,@r) = objectify(2,@_);
818
819   return $x if $x->modify('badd');
820 #  print "mbi badd ",join(' ',caller()),"\n";
821 #  print "upgrade => ",$upgrade||'undef',
822 #    " \$x (",ref($x),") \$y (",ref($y),")\n";
823 #  return $upgrade->badd($x,$y,@r) if defined $upgrade &&
824 #    ((ref($x) eq $upgrade) || (ref($y) eq $upgrade));
825 #  print "still badd\n";
826
827   $r[3] = $y;                           # no push!
828   # inf and NaN handling
829   if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/))
830     {
831     # NaN first
832     return $x->bnan() if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
833     # inf handline
834    if (($x->{sign} =~ /^[+-]inf$/) && ($y->{sign} =~ /^[+-]inf$/))
835       {
836       # +inf++inf or -inf+-inf => same, rest is NaN
837       return $x if $x->{sign} eq $y->{sign};
838       return $x->bnan();
839       }
840     # +-inf + something => +inf
841     # something +-inf => +-inf
842     $x->{sign} = $y->{sign}, return $x if $y->{sign} =~ /^[+-]inf$/;
843     return $x;
844     }
845     
846   my ($sx, $sy) = ( $x->{sign}, $y->{sign} ); # get signs
847
848   if ($sx eq $sy)  
849     {
850     $x->{value} = $CALC->_add($x->{value},$y->{value}); # same sign, abs add
851     $x->{sign} = $sx;
852     }
853   else 
854     {
855     my $a = $CALC->_acmp ($y->{value},$x->{value});     # absolute compare
856     if ($a > 0)                           
857       {
858       #print "swapped sub (a=$a)\n";
859       $x->{value} = $CALC->_sub($y->{value},$x->{value},1); # abs sub w/ swap
860       $x->{sign} = $sy;
861       } 
862     elsif ($a == 0)
863       {
864       # speedup, if equal, set result to 0
865       #print "equal sub, result = 0\n";
866       $x->{value} = $CALC->_zero();
867       $x->{sign} = '+';
868       }
869     else # a < 0
870       {
871       #print "unswapped sub (a=$a)\n";
872       $x->{value} = $CALC->_sub($x->{value}, $y->{value}); # abs sub
873       $x->{sign} = $sx;
874       }
875     }
876   $x->round(@r);
877   }
878
879 sub bsub 
880   {
881   # (BINT or num_str, BINT or num_str) return num_str
882   # subtract second arg from first, modify first
883   my ($self,$x,$y,@r) = objectify(2,@_);
884
885   return $x if $x->modify('bsub');
886 #  return $upgrade->badd($x,$y,@r) if defined $upgrade &&
887 #    ((ref($x) eq $upgrade) || (ref($y) eq $upgrade));
888
889   if ($y->is_zero())
890     { 
891     return $x->round(@r);
892     }
893
894   $y->{sign} =~ tr/+\-/-+/;     # does nothing for NaN
895   $x->badd($y,@r);              # badd does not leave internal zeros
896   $y->{sign} =~ tr/+\-/-+/;     # refix $y (does nothing for NaN)
897   $x;                           # already rounded by badd() or no round necc.
898   }
899
900 sub binc
901   {
902   # increment arg by one
903   my ($self,$x,$a,$p,$r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
904   return $x if $x->modify('binc');
905
906   if ($x->{sign} eq '+')
907     {
908     $x->{value} = $CALC->_inc($x->{value});
909     return $x->round($a,$p,$r);
910     }
911   elsif ($x->{sign} eq '-')
912     {
913     $x->{value} = $CALC->_dec($x->{value});
914     $x->{sign} = '+' if $CALC->_is_zero($x->{value}); # -1 +1 => -0 => +0
915     return $x->round($a,$p,$r);
916     }
917   # inf, nan handling etc
918   $x->badd($self->__one(),$a,$p,$r);            # badd does round
919   }
920
921 sub bdec
922   {
923   # decrement arg by one
924   my ($self,$x,$a,$p,$r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
925   return $x if $x->modify('bdec');
926   
927   my $zero = $CALC->_is_zero($x->{value}) && $x->{sign} eq '+';
928   # <= 0
929   if (($x->{sign} eq '-') || $zero) 
930     {
931     $x->{value} = $CALC->_inc($x->{value});
932     $x->{sign} = '-' if $zero;                  # 0 => 1 => -1
933     $x->{sign} = '+' if $CALC->_is_zero($x->{value}); # -1 +1 => -0 => +0
934     return $x->round($a,$p,$r);
935     }
936   # > 0
937   elsif ($x->{sign} eq '+')
938     {
939     $x->{value} = $CALC->_dec($x->{value});
940     return $x->round($a,$p,$r);
941     }
942   # inf, nan handling etc
943   $x->badd($self->__one('-'),$a,$p,$r);                 # badd does round
944   } 
945
946 sub blog
947   {
948   # not implemented yet
949   my ($self,$x,$base,$a,$p,$r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
950  
951   return $upgrade->blog($x,$base,$a,$p,$r) if defined $upgrade;
952
953   return $x->bnan();
954   }
955  
956 sub blcm 
957   { 
958   # (BINT or num_str, BINT or num_str) return BINT
959   # does not modify arguments, but returns new object
960   # Lowest Common Multiplicator
961
962   my $y = shift; my ($x);
963   if (ref($y))
964     {
965     $x = $y->copy();
966     }
967   else
968     {
969     $x = $class->new($y);
970     }
971   while (@_) { $x = __lcm($x,shift); } 
972   $x;
973   }
974
975 sub bgcd 
976   { 
977   # (BINT or num_str, BINT or num_str) return BINT
978   # does not modify arguments, but returns new object
979   # GCD -- Euclids algorithm, variant C (Knuth Vol 3, pg 341 ff)
980
981   my $y = shift;
982   $y = __PACKAGE__->new($y) if !ref($y);
983   my $self = ref($y);
984   my $x = $y->copy();           # keep arguments
985   if ($CALC->can('_gcd'))
986     {
987     while (@_)
988       {
989       $y = shift; $y = $self->new($y) if !ref($y);
990       next if $y->is_zero();
991       return $x->bnan() if $y->{sign} !~ /^[+-]$/;      # y NaN?
992       $x->{value} = $CALC->_gcd($x->{value},$y->{value}); last if $x->is_one();
993       }
994     }
995   else
996     {
997     while (@_)
998       {
999       $y = shift; $y = $self->new($y) if !ref($y);
1000       $x = __gcd($x,$y->copy()); last if $x->is_one();  # _gcd handles NaN
1001       } 
1002     }
1003   $x->babs();
1004   }
1005
1006 sub bnot 
1007   {
1008   # (num_str or BINT) return BINT
1009   # represent ~x as twos-complement number
1010   # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1011   my ($self,$x,$a,$p,$r) = ref($_[0]) ? (undef,@_) : objectify(1,@_);
1012  
1013   return $x if $x->modify('bnot');
1014   $x->bneg()->bdec();                   # bdec already does round
1015   }
1016
1017 # is_foo test routines
1018
1019 sub is_zero
1020   {
1021   # return true if arg (BINT or num_str) is zero (array '+', '0')
1022   # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1023   my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1024   
1025   return 0 if $x->{sign} !~ /^\+$/;                     # -, NaN & +-inf aren't
1026   $CALC->_is_zero($x->{value});
1027   }
1028
1029 sub is_nan
1030   {
1031   # return true if arg (BINT or num_str) is NaN
1032   my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
1033
1034   return 1 if $x->{sign} eq $nan;
1035   return 0;
1036   }
1037
1038 sub is_inf
1039   {
1040   # return true if arg (BINT or num_str) is +-inf
1041   my ($self,$x,$sign) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
1042
1043   $sign = '' if !defined $sign;
1044   return 0 if $sign !~ /^([+-]|)$/;
1045
1046   if ($sign eq '')
1047     {
1048     return 1 if ($x->{sign} =~ /^[+-]inf$/); 
1049     return 0;
1050     }
1051   $sign = quotemeta($sign.'inf');
1052   return 1 if ($x->{sign} =~ /^$sign$/);
1053   return 0;
1054   }
1055
1056 sub is_one
1057   {
1058   # return true if arg (BINT or num_str) is +1
1059   # or -1 if sign is given
1060   # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1061   my ($self,$x,$sign) = ref($_[0]) ? (undef,@_) : objectify(1,@_);
1062     
1063   $sign = '' if !defined $sign; $sign = '+' if $sign ne '-';
1064  
1065   return 0 if $x->{sign} ne $sign;      # -1 != +1, NaN, +-inf aren't either
1066   $CALC->_is_one($x->{value});
1067   }
1068
1069 sub is_odd
1070   {
1071   # return true when arg (BINT or num_str) is odd, false for even
1072   # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1073   my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1074
1075   return 0 if $x->{sign} !~ /^[+-]$/;                   # NaN & +-inf aren't
1076   $CALC->_is_odd($x->{value});
1077   }
1078
1079 sub is_even
1080   {
1081   # return true when arg (BINT or num_str) is even, false for odd
1082   # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1083   my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1084
1085   return 0 if $x->{sign} !~ /^[+-]$/;                   # NaN & +-inf aren't
1086   $CALC->_is_even($x->{value});
1087   }
1088
1089 sub is_positive
1090   {
1091   # return true when arg (BINT or num_str) is positive (>= 0)
1092   # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1093   my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1094   
1095   return 1 if $x->{sign} =~ /^\+/;
1096   0;
1097   }
1098
1099 sub is_negative
1100   {
1101   # return true when arg (BINT or num_str) is negative (< 0)
1102   # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1103   my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1104   
1105   return 1 if ($x->{sign} =~ /^-/);
1106   0;
1107   }
1108
1109 sub is_int
1110   {
1111   # return true when arg (BINT or num_str) is an integer
1112   # always true for BigInt, but different for Floats
1113   # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1114   my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1115   
1116   $x->{sign} =~ /^[+-]$/ ? 1 : 0;               # inf/-inf/NaN aren't
1117   }
1118
1119 ###############################################################################
1120
1121 sub bmul 
1122   { 
1123   # multiply two numbers -- stolen from Knuth Vol 2 pg 233
1124   # (BINT or num_str, BINT or num_str) return BINT
1125   my ($self,$x,$y,@r) = objectify(2,@_);
1126   
1127   return $x if $x->modify('bmul');
1128
1129   $r[3] = $y;                           # no push here
1130  
1131   return $x->bnan() if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
1132
1133   # inf handling
1134   if (($x->{sign} =~ /^[+-]inf$/) || ($y->{sign} =~ /^[+-]inf$/))
1135     {
1136     return $x->bnan() if $x->is_zero() || $y->is_zero();
1137     # result will always be +-inf:
1138     # +inf * +/+inf => +inf, -inf * -/-inf => +inf
1139     # +inf * -/-inf => -inf, -inf * +/+inf => -inf
1140     return $x->binf() if ($x->{sign} =~ /^\+/ && $y->{sign} =~ /^\+/); 
1141     return $x->binf() if ($x->{sign} =~ /^-/ && $y->{sign} =~ /^-/); 
1142     return $x->binf('-');
1143     }
1144
1145   $x->{sign} = $x->{sign} eq $y->{sign} ? '+' : '-'; # +1 * +1 or -1 * -1 => +
1146
1147   $x->{value} = $CALC->_mul($x->{value},$y->{value});   # do actual math
1148   $x->{sign} = '+' if $CALC->_is_zero($x->{value});     # no -0
1149   $x->round(@r);
1150   }
1151
1152 sub _div_inf
1153   {
1154   # helper function that handles +-inf cases for bdiv()/bmod() to reuse code
1155   my ($self,$x,$y) = @_;
1156
1157   # NaN if x == NaN or y == NaN or x==y==0
1158   return wantarray ? ($x->bnan(),$self->bnan()) : $x->bnan()
1159    if (($x->is_nan() || $y->is_nan())   ||
1160        ($x->is_zero() && $y->is_zero()));
1161  
1162   # +-inf / +-inf == NaN, reminder also NaN
1163   if (($x->{sign} =~ /^[+-]inf$/) && ($y->{sign} =~ /^[+-]inf$/))
1164     {
1165     return wantarray ? ($x->bnan(),$self->bnan()) : $x->bnan();
1166     }
1167   # x / +-inf => 0, remainder x (works even if x == 0)
1168   if ($y->{sign} =~ /^[+-]inf$/)
1169     {
1170     my $t = $x->copy();         # binf clobbers up $x
1171     return wantarray ? ($x->bzero(),$t) : $x->bzero()
1172     }
1173   
1174   # 5 / 0 => +inf, -6 / 0 => -inf
1175   # +inf / 0 = inf, inf,  and -inf / 0 => -inf, -inf 
1176   # exception:   -8 / 0 has remainder -8, not 8
1177   # exception: -inf / 0 has remainder -inf, not inf
1178   if ($y->is_zero())
1179     {
1180     # +-inf / 0 => special case for -inf
1181     return wantarray ?  ($x,$x->copy()) : $x if $x->is_inf();
1182     if (!$x->is_zero() && !$x->is_inf())
1183       {
1184       my $t = $x->copy();               # binf clobbers up $x
1185       return wantarray ?
1186        ($x->binf($x->{sign}),$t) : $x->binf($x->{sign})
1187       }
1188     }
1189   
1190   # last case: +-inf / ordinary number
1191   my $sign = '+inf';
1192   $sign = '-inf' if substr($x->{sign},0,1) ne $y->{sign};
1193   $x->{sign} = $sign;
1194   return wantarray ? ($x,$self->bzero()) : $x;
1195   }
1196
1197 sub bdiv 
1198   {
1199   # (dividend: BINT or num_str, divisor: BINT or num_str) return 
1200   # (BINT,BINT) (quo,rem) or BINT (only rem)
1201   my ($self,$x,$y,@r) = objectify(2,@_);
1202
1203   return $x if $x->modify('bdiv');
1204
1205   return $self->_div_inf($x,$y)
1206    if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/) || $y->is_zero());
1207
1208   $r[3] = $y;                                   # no push!
1209
1210   # 0 / something
1211   return
1212    wantarray ? ($x->round(@r),$self->bzero(@r)):$x->round(@r) if $x->is_zero();
1213  
1214   # Is $x in the interval [0, $y) (aka $x <= $y) ?
1215   my $cmp = $CALC->_acmp($x->{value},$y->{value});
1216   if (($cmp < 0) and (($x->{sign} eq $y->{sign}) or !wantarray))
1217     {
1218     return $upgrade->bdiv($x,$y,@r) if defined $upgrade;
1219
1220     return $x->bzero()->round(@r) unless wantarray;
1221     my $t = $x->copy();      # make copy first, because $x->bzero() clobbers $x
1222     return ($x->bzero()->round(@r),$t);
1223     }
1224   elsif ($cmp == 0)
1225     {
1226     # shortcut, both are the same, so set to +/- 1
1227     $x->__one( ($x->{sign} ne $y->{sign} ? '-' : '+') ); 
1228     return $x unless wantarray;
1229     return ($x->round(@r),$self->bzero(@r));
1230     }
1231    
1232   # calc new sign and in case $y == +/- 1, return $x
1233   my $xsign = $x->{sign};                               # keep
1234   $x->{sign} = ($x->{sign} ne $y->{sign} ? '-' : '+'); 
1235   # check for / +-1 (cant use $y->is_one due to '-'
1236   if ($CALC->_is_one($y->{value}))
1237     {
1238     return wantarray ? ($x->round(@r),$self->bzero(@r)) : $x->round(@r); 
1239     }
1240
1241   my $rem;
1242   if (wantarray)
1243     {
1244     my $rem = $self->bzero(); 
1245     ($x->{value},$rem->{value}) = $CALC->_div($x->{value},$y->{value});
1246     $x->{sign} = '+' if $CALC->_is_zero($x->{value});
1247     $x->round(@r); 
1248     if (! $CALC->_is_zero($rem->{value}))
1249       {
1250       $rem->{sign} = $y->{sign};
1251       $rem = $y-$rem if $xsign ne $y->{sign};   # one of them '-'
1252       }
1253     else
1254       {
1255       $rem->{sign} = '+';                       # dont leave -0
1256       }
1257     $rem->round(@r);
1258     return ($x,$rem);
1259     }
1260
1261   $x->{value} = $CALC->_div($x->{value},$y->{value});
1262   $x->{sign} = '+' if $CALC->_is_zero($x->{value});
1263   $x->round(@r); 
1264   $x;
1265   }
1266
1267 sub bmod 
1268   {
1269   # modulus (or remainder)
1270   # (BINT or num_str, BINT or num_str) return BINT
1271   my ($self,$x,$y,@r) = objectify(2,@_);
1272  
1273   return $x if $x->modify('bmod');
1274   $r[3] = $y;                                   # no push!
1275   if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/) || $y->is_zero())
1276     {
1277     my ($d,$r) = $self->_div_inf($x,$y);
1278     return $r->round(@r);
1279     }
1280
1281   if ($CALC->can('_mod'))
1282     {
1283     # calc new sign and in case $y == +/- 1, return $x
1284     $x->{value} = $CALC->_mod($x->{value},$y->{value});
1285     if (!$CALC->_is_zero($x->{value}))
1286       {
1287       my $xsign = $x->{sign};
1288       $x->{sign} = $y->{sign};
1289       $x = $y-$x if $xsign ne $y->{sign};       # one of them '-'
1290       }
1291     else
1292       {
1293       $x->{sign} = '+';                         # dont leave -0
1294       }
1295     return $x->round(@r);
1296     }
1297   my ($t,$rem) = $self->bdiv($x->copy(),$y,@r); # slow way (also rounds)
1298   # modify in place
1299   foreach (qw/value sign _a _p/)
1300     {
1301     $x->{$_} = $rem->{$_};
1302     }
1303   $x;
1304   }
1305
1306 sub bfac
1307   {
1308   # (BINT or num_str, BINT or num_str) return BINT
1309   # compute factorial numbers
1310   # modifies first argument
1311   my ($self,$x,@r) = objectify(1,@_);
1312
1313   return $x if $x->modify('bfac');
1314  
1315   return $x->bnan() if $x->{sign} ne '+';       # inf, NnN, <0 etc => NaN
1316   return $x->bone(@r) if $x->is_zero() || $x->is_one();         # 0 or 1 => 1
1317
1318   if ($CALC->can('_fac'))
1319     {
1320     $x->{value} = $CALC->_fac($x->{value});
1321     return $x->round(@r);
1322     }
1323
1324   my $n = $x->copy();
1325   $x->bone();
1326   my $f = $self->new(2);
1327   while ($f->bacmp($n) < 0)
1328     {
1329     $x->bmul($f); $f->binc();
1330     }
1331   $x->bmul($f);                                 # last step
1332   $x->round(@r);                                # round
1333   }
1334  
1335 sub bpow 
1336   {
1337   # (BINT or num_str, BINT or num_str) return BINT
1338   # compute power of two numbers -- stolen from Knuth Vol 2 pg 233
1339   # modifies first argument
1340   my ($self,$x,$y,@r) = objectify(2,@_);
1341
1342   return $x if $x->modify('bpow');
1343  
1344   $r[3] = $y;                                   # no push!
1345   return $x if $x->{sign} =~ /^[+-]inf$/;       # -inf/+inf ** x
1346   return $x->bnan() if $x->{sign} eq $nan || $y->{sign} eq $nan;
1347   return $x->bone(@r) if $y->is_zero();
1348   return $x->round(@r) if $x->is_one() || $y->is_one();
1349   if ($x->{sign} eq '-' && $CALC->_is_one($x->{value}))
1350     {
1351     # if $x == -1 and odd/even y => +1/-1
1352     return $y->is_odd() ? $x->round(@r) : $x->babs()->round(@r);
1353     # my Casio FX-5500L has a bug here: -1 ** 2 is -1, but -1 * -1 is 1;
1354     }
1355   # 1 ** -y => 1 / (1 ** |y|)
1356   # so do test for negative $y after above's clause
1357   return $x->bnan() if $y->{sign} eq '-';
1358   return $x->round(@r) if $x->is_zero();  # 0**y => 0 (if not y <= 0)
1359
1360   if ($CALC->can('_pow'))
1361     {
1362     $x->{value} = $CALC->_pow($x->{value},$y->{value});
1363     return $x->round(@r);
1364     }
1365
1366 # based on the assumption that shifting in base 10 is fast, and that mul
1367 # works faster if numbers are small: we count trailing zeros (this step is
1368 # O(1)..O(N), but in case of O(N) we save much more time due to this),
1369 # stripping them out of the multiplication, and add $count * $y zeros
1370 # afterwards like this:
1371 # 300 ** 3 == 300*300*300 == 3*3*3 . '0' x 2 * 3 == 27 . '0' x 6
1372 # creates deep recursion?
1373 #  my $zeros = $x->_trailing_zeros();
1374 #  if ($zeros > 0)
1375 #    {
1376 #    $x->brsft($zeros,10);      # remove zeros
1377 #    $x->bpow($y);              # recursion (will not branch into here again)
1378 #    $zeros = $y * $zeros;      # real number of zeros to add
1379 #    $x->blsft($zeros,10);
1380 #    return $x->round($a,$p,$r);
1381 #    }
1382
1383   my $pow2 = $self->__one();
1384   my $y1 = $class->new($y);
1385   my $two = $self->new(2);
1386   while (!$y1->is_one())
1387     {
1388     $pow2->bmul($x) if $y1->is_odd();
1389     $y1->bdiv($two);
1390     $x->bmul($x);
1391     }
1392   $x->bmul($pow2) unless $pow2->is_one();
1393   return $x->round(@r);
1394   }
1395
1396 sub blsft 
1397   {
1398   # (BINT or num_str, BINT or num_str) return BINT
1399   # compute x << y, base n, y >= 0
1400   my ($self,$x,$y,$n,$a,$p,$r) = objectify(2,@_);
1401   
1402   return $x if $x->modify('blsft');
1403   return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
1404   return $x->round($a,$p,$r) if $y->is_zero();
1405
1406   $n = 2 if !defined $n; return $x->bnan() if $n <= 0 || $y->{sign} eq '-';
1407
1408   my $t; $t = $CALC->_lsft($x->{value},$y->{value},$n) if $CALC->can('_lsft');
1409   if (defined $t)
1410     {
1411     $x->{value} = $t; return $x->round($a,$p,$r);
1412     }
1413   # fallback
1414   return $x->bmul( $self->bpow($n, $y, $a, $p, $r), $a, $p, $r );
1415   }
1416
1417 sub brsft 
1418   {
1419   # (BINT or num_str, BINT or num_str) return BINT
1420   # compute x >> y, base n, y >= 0
1421   my ($self,$x,$y,$n,$a,$p,$r) = objectify(2,@_);
1422
1423   return $x if $x->modify('brsft');
1424   return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
1425   return $x->round($a,$p,$r) if $y->is_zero();
1426   return $x->bzero($a,$p,$r) if $x->is_zero();          # 0 => 0
1427
1428   $n = 2 if !defined $n; return $x->bnan() if $n <= 0 || $y->{sign} eq '-';
1429
1430    # this only works for negative numbers when shifting in base 2
1431   if (($x->{sign} eq '-') && ($n == 2))
1432     {
1433     return $x->round($a,$p,$r) if $x->is_one('-');      # -1 => -1
1434     if (!$y->is_one())
1435       {
1436       # although this is O(N*N) in calc (as_bin!) it is O(N) in Pari et al
1437       # but perhaps there is a better emulation for two's complement shift...
1438       # if $y != 1, we must simulate it by doing:
1439       # convert to bin, flip all bits, shift, and be done
1440       $x->binc();                       # -3 => -2
1441       my $bin = $x->as_bin();
1442       $bin =~ s/^-0b//;                 # strip '-0b' prefix
1443       $bin =~ tr/10/01/;                # flip bits
1444       # now shift
1445       if (length($bin) <= $y)
1446         {
1447         $bin = '0';                     # shifting to far right creates -1
1448                                         # 0, because later increment makes 
1449                                         # that 1, attached '-' makes it '-1'
1450                                         # because -1 >> x == -1 !
1451         } 
1452       else
1453         {
1454         $bin =~ s/.{$y}$//;             # cut off at the right side
1455         $bin = '1' . $bin;              # extend left side by one dummy '1'
1456         $bin =~ tr/10/01/;              # flip bits back
1457         }
1458       my $res = $self->new('0b'.$bin);  # add prefix and convert back
1459       $res->binc();                     # remember to increment
1460       $x->{value} = $res->{value};      # take over value
1461       return $x->round($a,$p,$r);       # we are done now, magic, isn't?
1462       }
1463     $x->bdec();                         # n == 2, but $y == 1: this fixes it
1464     }
1465
1466   my $t; $t = $CALC->_rsft($x->{value},$y->{value},$n) if $CALC->can('_rsft');
1467   if (defined $t)
1468     {
1469     $x->{value} = $t;
1470     return $x->round($a,$p,$r);
1471     }
1472   # fallback
1473   $x->bdiv($self->bpow($n,$y, $a,$p,$r), $a,$p,$r);
1474   $x;
1475   }
1476
1477 sub band 
1478   {
1479   #(BINT or num_str, BINT or num_str) return BINT
1480   # compute x & y
1481   my ($self,$x,$y,$a,$p,$r) = objectify(2,@_);
1482   
1483   return $x if $x->modify('band');
1484
1485   local $Math::BigInt::upgrade = undef;
1486
1487   return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
1488   return $x->bzero() if $y->is_zero() || $x->is_zero();
1489
1490   my $sign = 0;                                 # sign of result
1491   $sign = 1 if ($x->{sign} eq '-') && ($y->{sign} eq '-');
1492   my $sx = 1; $sx = -1 if $x->{sign} eq '-';
1493   my $sy = 1; $sy = -1 if $y->{sign} eq '-';
1494   
1495   if ($CALC->can('_and') && $sx == 1 && $sy == 1)
1496     {
1497     $x->{value} = $CALC->_and($x->{value},$y->{value});
1498     return $x->round($a,$p,$r);
1499     }
1500
1501   my $m = $self->bone(); my ($xr,$yr);
1502   my $x10000 = $self->new (0x1000);
1503   my $y1 = copy(ref($x),$y);                    # make copy
1504   $y1->babs();                                  # and positive
1505   my $x1 = $x->copy()->babs(); $x->bzero();     # modify x in place!
1506   use integer;                                  # need this for negative bools
1507   while (!$x1->is_zero() && !$y1->is_zero())
1508     {
1509     ($x1, $xr) = bdiv($x1, $x10000);
1510     ($y1, $yr) = bdiv($y1, $x10000);
1511     # make both op's numbers!
1512     $x->badd( bmul( $class->new(
1513        abs($sx*int($xr->numify()) & $sy*int($yr->numify()))), 
1514       $m));
1515     $m->bmul($x10000);
1516     }
1517   $x->bneg() if $sign;
1518   return $x->round($a,$p,$r);
1519   }
1520
1521 sub bior 
1522   {
1523   #(BINT or num_str, BINT or num_str) return BINT
1524   # compute x | y
1525   my ($self,$x,$y,$a,$p,$r) = objectify(2,@_);
1526
1527   return $x if $x->modify('bior');
1528
1529   local $Math::BigInt::upgrade = undef;
1530
1531   return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
1532   return $x if $y->is_zero();
1533
1534   my $sign = 0;                                 # sign of result
1535   $sign = 1 if ($x->{sign} eq '-') || ($y->{sign} eq '-');
1536   my $sx = 1; $sx = -1 if $x->{sign} eq '-';
1537   my $sy = 1; $sy = -1 if $y->{sign} eq '-';
1538
1539   # don't use lib for negative values
1540   if ($CALC->can('_or') && $sx == 1 && $sy == 1)
1541     {
1542     $x->{value} = $CALC->_or($x->{value},$y->{value});
1543     return $x->round($a,$p,$r);
1544     }
1545
1546   my $m = $self->bone(); my ($xr,$yr);
1547   my $x10000 = $self->new(0x10000);
1548   my $y1 = copy(ref($x),$y);                    # make copy
1549   $y1->babs();                                  # and positive
1550   my $x1 = $x->copy()->babs(); $x->bzero();     # modify x in place!
1551   use integer;                                  # need this for negative bools
1552   while (!$x1->is_zero() || !$y1->is_zero())
1553     {
1554     ($x1, $xr) = bdiv($x1,$x10000);
1555     ($y1, $yr) = bdiv($y1,$x10000);
1556     # make both op's numbers!
1557     $x->badd( bmul( $class->new(
1558        abs($sx*int($xr->numify()) | $sy*int($yr->numify()))), 
1559       $m));
1560     $m->bmul($x10000);
1561     }
1562   $x->bneg() if $sign;
1563   return $x->round($a,$p,$r);
1564   }
1565
1566 sub bxor 
1567   {
1568   #(BINT or num_str, BINT or num_str) return BINT
1569   # compute x ^ y
1570   my ($self,$x,$y,$a,$p,$r) = objectify(2,@_);
1571
1572   return $x if $x->modify('bxor');
1573
1574   local $Math::BigInt::upgrade = undef;
1575
1576   return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
1577   return $x if $y->is_zero();
1578   
1579   my $sign = 0;                                 # sign of result
1580   $sign = 1 if $x->{sign} ne $y->{sign};
1581   my $sx = 1; $sx = -1 if $x->{sign} eq '-';
1582   my $sy = 1; $sy = -1 if $y->{sign} eq '-';
1583
1584   # don't use lib for negative values
1585   if ($CALC->can('_xor') && $sx == 1 && $sy == 1)
1586     {
1587     $x->{value} = $CALC->_xor($x->{value},$y->{value});
1588     return $x->round($a,$p,$r);
1589     }
1590
1591   my $m = $self->bone(); my ($xr,$yr);
1592   my $x10000 = $self->new(0x10000);
1593   my $y1 = copy(ref($x),$y);                    # make copy
1594   $y1->babs();                                  # and positive
1595   my $x1 = $x->copy()->babs(); $x->bzero();     # modify x in place!
1596   use integer;                                  # need this for negative bools
1597   while (!$x1->is_zero() || !$y1->is_zero())
1598     {
1599     ($x1, $xr) = bdiv($x1, $x10000);
1600     ($y1, $yr) = bdiv($y1, $x10000);
1601     # make both op's numbers!
1602     $x->badd( bmul( $class->new(
1603        abs($sx*int($xr->numify()) ^ $sy*int($yr->numify()))), 
1604       $m));
1605     $m->bmul($x10000);
1606     }
1607   $x->bneg() if $sign;
1608   return $x->round($a,$p,$r);
1609   }
1610
1611 sub length
1612   {
1613   my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
1614
1615   my $e = $CALC->_len($x->{value}); 
1616   return wantarray ? ($e,0) : $e;
1617   }
1618
1619 sub digit
1620   {
1621   # return the nth decimal digit, negative values count backward, 0 is right
1622   my $x = shift;
1623   my $n = shift || 0; 
1624
1625   return $CALC->_digit($x->{value},$n);
1626   }
1627
1628 sub _trailing_zeros
1629   {
1630   # return the amount of trailing zeros in $x
1631   my $x = shift;
1632   $x = $class->new($x) unless ref $x;
1633
1634   return 0 if $x->is_zero() || $x->is_odd() || $x->{sign} !~ /^[+-]$/;
1635
1636   return $CALC->_zeros($x->{value}) if $CALC->can('_zeros');
1637
1638   # if not: since we do not know underlying internal representation:
1639   my $es = "$x"; $es =~ /([0]*)$/;
1640   return 0 if !defined $1;      # no zeros
1641   return CORE::length("$1");    # as string, not as +0!
1642   }
1643
1644 sub bsqrt
1645   {
1646   my ($self,$x,$a,$p,$r) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
1647
1648   return $x if $x->modify('bsqrt');
1649
1650   return $x->bnan() if $x->{sign} ne '+';       # -x or inf or NaN => NaN
1651   return $x->bzero($a,$p) if $x->is_zero();                     # 0 => 0
1652   return $x->round($a,$p,$r) if $x->is_one();                   # 1 => 1
1653
1654   return $upgrade->bsqrt($x,$a,$p,$r) if defined $upgrade;
1655
1656   if ($CALC->can('_sqrt'))
1657     {
1658     $x->{value} = $CALC->_sqrt($x->{value});
1659     return $x->round($a,$p,$r);
1660     }
1661
1662   return $x->bone($a,$p) if $x < 4;                             # 2,3 => 1
1663   my $y = $x->copy();
1664   my $l = int($x->length()/2);
1665   
1666   $x->bone();                                   # keep ref($x), but modify it
1667   $x->blsft($l,10);
1668
1669   my $last = $self->bzero();
1670   my $two = $self->new(2);
1671   my $lastlast = $x+$two;
1672   while ($last != $x && $lastlast != $x)
1673     {
1674     $lastlast = $last; $last = $x; 
1675     $x += $y / $x; 
1676     $x /= $two;
1677     }
1678   $x-- if $x * $x > $y;                         # overshot?
1679   $x->round($a,$p,$r);
1680   }
1681
1682 sub exponent
1683   {
1684   # return a copy of the exponent (here always 0, NaN or 1 for $m == 0)
1685   my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
1686  
1687   if ($x->{sign} !~ /^[+-]$/)
1688     {
1689     my $s = $x->{sign}; $s =~ s/^[+-]//;
1690     return $self->new($s);              # -inf,+inf => inf
1691     }
1692   my $e = $class->bzero();
1693   return $e->binc() if $x->is_zero();
1694   $e += $x->_trailing_zeros();
1695   return $e;
1696   }
1697
1698 sub mantissa
1699   {
1700   # return the mantissa (compatible to Math::BigFloat, e.g. reduced)
1701   my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
1702
1703   if ($x->{sign} !~ /^[+-]$/)
1704     {
1705     my $s = $x->{sign}; $s =~ s/^[+]//;
1706     return $self->new($s);              # +inf => inf
1707     }
1708   my $m = $x->copy();
1709   # that's inefficient
1710   my $zeros = $m->_trailing_zeros();
1711   $m /= 10 ** $zeros if $zeros != 0;
1712   return $m;
1713   }
1714
1715 sub parts
1716   {
1717   # return a copy of both the exponent and the mantissa
1718   my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
1719
1720   return ($x->mantissa(),$x->exponent());
1721   }
1722    
1723 ##############################################################################
1724 # rounding functions
1725
1726 sub bfround
1727   {
1728   # precision: round to the $Nth digit left (+$n) or right (-$n) from the '.'
1729   # $n == 0 || $n == 1 => round to integer
1730   my $x = shift; $x = $class->new($x) unless ref $x;
1731   my ($scale,$mode) = $x->_scale_p($x->precision(),$x->round_mode(),@_);
1732   return $x if !defined $scale;         # no-op
1733   return $x if $x->modify('bfround');
1734
1735   # no-op for BigInts if $n <= 0
1736   if ($scale <= 0)
1737     {
1738     $x->{_a} = undef;                           # clear an eventual set A
1739     $x->{_p} = $scale; return $x;
1740     }
1741
1742   $x->bround( $x->length()-$scale, $mode);
1743   $x->{_a} = undef;                             # bround sets {_a}
1744   $x->{_p} = $scale;                            # so correct it
1745   $x;
1746   }
1747
1748 sub _scan_for_nonzero
1749   {
1750   my $x = shift;
1751   my $pad = shift;
1752   my $xs = shift;
1753  
1754   my $len = $x->length();
1755   return 0 if $len == 1;                # '5' is trailed by invisible zeros
1756   my $follow = $pad - 1;
1757   return 0 if $follow > $len || $follow < 1;
1758
1759   # since we do not know underlying represention of $x, use decimal string
1760   #my $r = substr ($$xs,-$follow);
1761   my $r = substr ("$x",-$follow);
1762   return 1 if $r =~ /[^0]/; return 0;
1763   }
1764
1765 sub fround
1766   {
1767   # to make life easier for switch between MBF and MBI (autoload fxxx()
1768   # like MBF does for bxxx()?)
1769   my $x = shift;
1770   return $x->bround(@_);
1771   }
1772
1773 sub bround
1774   {
1775   # accuracy: +$n preserve $n digits from left,
1776   #           -$n preserve $n digits from right (f.i. for 0.1234 style in MBF)
1777   # no-op for $n == 0
1778   # and overwrite the rest with 0's, return normalized number
1779   # do not return $x->bnorm(), but $x
1780
1781   my $x = shift; $x = $class->new($x) unless ref $x;
1782   my ($scale,$mode) = $x->_scale_a($x->accuracy(),$x->round_mode(),@_);
1783   return $x if !defined $scale;                 # no-op
1784   return $x if $x->modify('bround');
1785   
1786   if ($x->is_zero() || $scale == 0)
1787     {
1788     $x->{_a} = $scale if !defined $x->{_a} || $x->{_a} > $scale; # 3 > 2
1789     return $x;
1790     }
1791   return $x if $x->{sign} !~ /^[+-]$/;          # inf, NaN
1792
1793   # we have fewer digits than we want to scale to
1794   my $len = $x->length();
1795   # scale < 0, but > -len (not >=!)
1796   if (($scale < 0 && $scale < -$len-1) || ($scale >= $len))
1797     {
1798     $x->{_a} = $scale if !defined $x->{_a} || $x->{_a} > $scale; # 3 > 2
1799     return $x; 
1800     }
1801    
1802   # count of 0's to pad, from left (+) or right (-): 9 - +6 => 3, or |-6| => 6
1803   my ($pad,$digit_round,$digit_after);
1804   $pad = $len - $scale;
1805   $pad = abs($scale-1) if $scale < 0;
1806
1807   # do not use digit(), it is costly for binary => decimal
1808
1809   my $xs = $CALC->_str($x->{value});
1810   my $pl = -$pad-1;
1811  
1812   # pad:   123: 0 => -1, at 1 => -2, at 2 => -3, at 3 => -4
1813   # pad+1: 123: 0 => 0,  at 1 => -1, at 2 => -2, at 3 => -3
1814   $digit_round = '0'; $digit_round = substr($$xs,$pl,1) if $pad <= $len;
1815   $pl++; $pl ++ if $pad >= $len;
1816   $digit_after = '0'; $digit_after = substr($$xs,$pl,1) if $pad > 0;
1817
1818  #  print "$pad $pl $$xs dr $digit_round da $digit_after\n";
1819
1820   # in case of 01234 we round down, for 6789 up, and only in case 5 we look
1821   # closer at the remaining digits of the original $x, remember decision
1822   my $round_up = 1;                                     # default round up
1823   $round_up -- if
1824     ($mode eq 'trunc')                          ||      # trunc by round down
1825     ($digit_after =~ /[01234]/)                 ||      # round down anyway,
1826                                                         # 6789 => round up
1827     ($digit_after eq '5')                       &&      # not 5000...0000
1828     ($x->_scan_for_nonzero($pad,$xs) == 0)              &&
1829     (
1830      ($mode eq 'even') && ($digit_round =~ /[24680]/) ||
1831      ($mode eq 'odd')  && ($digit_round =~ /[13579]/) ||
1832      ($mode eq '+inf') && ($x->{sign} eq '-')   ||
1833      ($mode eq '-inf') && ($x->{sign} eq '+')   ||
1834      ($mode eq 'zero')          # round down if zero, sign adjusted below
1835     );
1836   my $put_back = 0;                                     # not yet modified
1837         
1838   # old code, depend on internal representation
1839   # split mantissa at $pad and then pad with zeros
1840   #my $s5 = int($pad / 5);
1841   #my $i = 0;
1842   #while ($i < $s5)
1843   #  {
1844   #  $x->{value}->[$i++] = 0;                           # replace with 5 x 0
1845   #  }
1846   #$x->{value}->[$s5] = '00000'.$x->{value}->[$s5];     # pad with 0
1847   #my $rem = $pad % 5;                          # so much left over
1848   #if ($rem > 0)
1849   #  {
1850   #  #print "remainder $rem\n";
1851   ##  #print "elem      $x->{value}->[$s5]\n";
1852   #  substr($x->{value}->[$s5],-$rem,$rem) = '0' x $rem;        # stamp w/ '0'
1853   #  }
1854   #$x->{value}->[$s5] = int ($x->{value}->[$s5]);       # str '05' => int '5'
1855   #print ${$CALC->_str($pad->{value})}," $len\n";
1856
1857   if (($pad > 0) && ($pad <= $len))
1858     {
1859     substr($$xs,-$pad,$pad) = '0' x $pad;
1860     $put_back = 1;
1861     }
1862   elsif ($pad > $len)
1863     {
1864     $x->bzero();                                        # round to '0'
1865     }
1866
1867   if ($round_up)                                        # what gave test above?
1868     {
1869     $put_back = 1;
1870     $pad = $len, $$xs = '0'x$pad if $scale < 0;         # tlr: whack 0.51=>1.0  
1871
1872     # we modify directly the string variant instead of creating a number and
1873     # adding it
1874     my $c = 0; $pad ++;                         # for $pad == $len case
1875     while ($pad <= $len)
1876       {
1877       $c = substr($$xs,-$pad,1) + 1; $c = '0' if $c eq '10';
1878       substr($$xs,-$pad,1) = $c; $pad++;
1879       last if $c != 0;                          # no overflow => early out
1880       }
1881     $$xs = '1'.$$xs if $c == 0;
1882
1883     # $x->badd( Math::BigInt->new($x->{sign}.'1'. '0' x $pad) );
1884     }
1885   $x->{value} = $CALC->_new($xs) if $put_back == 1;     # put back in
1886
1887   $x->{_a} = $scale if $scale >= 0;
1888   if ($scale < 0)
1889     {
1890     $x->{_a} = $len+$scale;
1891     $x->{_a} = 0 if $scale < -$len;
1892     }
1893   $x;
1894   }
1895
1896 sub bfloor
1897   {
1898   # return integer less or equal then number, since it is already integer,
1899   # always returns $self
1900   my ($self,$x,$a,$p,$r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
1901
1902   # not needed: return $x if $x->modify('bfloor');
1903   return $x->round($a,$p,$r);
1904   }
1905
1906 sub bceil
1907   {
1908   # return integer greater or equal then number, since it is already integer,
1909   # always returns $self
1910   my ($self,$x,$a,$p,$r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
1911
1912   # not needed: return $x if $x->modify('bceil');
1913   return $x->round($a,$p,$r);
1914   }
1915
1916 ##############################################################################
1917 # private stuff (internal use only)
1918
1919 sub __one
1920   {
1921   # internal speedup, set argument to 1, or create a +/- 1
1922   my $self = shift;
1923   my $x = $self->bone(); # $x->{value} = $CALC->_one();
1924   $x->{sign} = shift || '+';
1925   return $x;
1926   }
1927
1928 sub _swap
1929   {
1930   # Overload will swap params if first one is no object ref so that the first
1931   # one is always an object ref. In this case, third param is true.
1932   # This routine is to overcome the effect of scalar,$object creating an object
1933   # of the class of this package, instead of the second param $object. This
1934   # happens inside overload, when the overload section of this package is
1935   # inherited by sub classes.
1936   # For overload cases (and this is used only there), we need to preserve the
1937   # args, hence the copy().
1938   # You can override this method in a subclass, the overload section will call
1939   # $object->_swap() to make sure it arrives at the proper subclass, with some
1940   # exceptions like '+' and '-'. To make '+' and '-' work, you also need to
1941   # specify your own overload for them.
1942
1943   # object, (object|scalar) => preserve first and make copy
1944   # scalar, object          => swapped, re-swap and create new from first
1945   #                            (using class of second object, not $class!!)
1946   my $self = shift;                     # for override in subclass
1947   if ($_[2])
1948     {
1949     my $c = ref ($_[0]) || $class;      # fallback $class should not happen
1950     return ( $c->new($_[1]), $_[0] );
1951     }
1952   return ( $_[0]->copy(), $_[1] );
1953   }
1954
1955 sub objectify
1956   {
1957   # check for strings, if yes, return objects instead
1958  
1959   # the first argument is number of args objectify() should look at it will
1960   # return $count+1 elements, the first will be a classname. This is because
1961   # overloaded '""' calls bstr($object,undef,undef) and this would result in
1962   # useless objects beeing created and thrown away. So we cannot simple loop
1963   # over @_. If the given count is 0, all arguments will be used.
1964  
1965   # If the second arg is a ref, use it as class.
1966   # If not, try to use it as classname, unless undef, then use $class 
1967   # (aka Math::BigInt). The latter shouldn't happen,though.
1968
1969   # caller:                        gives us:
1970   # $x->badd(1);                => ref x, scalar y
1971   # Class->badd(1,2);           => classname x (scalar), scalar x, scalar y
1972   # Class->badd( Class->(1),2); => classname x (scalar), ref x, scalar y
1973   # Math::BigInt::badd(1,2);    => scalar x, scalar y
1974   # In the last case we check number of arguments to turn it silently into
1975   # $class,1,2. (We can not take '1' as class ;o)
1976   # badd($class,1) is not supported (it should, eventually, try to add undef)
1977   # currently it tries 'Math::BigInt' + 1, which will not work.
1978
1979   # some shortcut for the common cases
1980
1981   # $x->unary_op();
1982   return (ref($_[1]),$_[1]) if (@_ == 2) && ($_[0]||0 == 1) && ref($_[1]);
1983   # $x->binary_op($y);
1984   #return (ref($_[1]),$_[1],$_[2]) if (@_ == 3) && ($_[0]||0 == 2)
1985   # && ref($_[1]) && ref($_[2]);
1986
1987   my $count = abs(shift || 0);
1988   
1989   my @a;                        # resulting array 
1990   if (ref $_[0])
1991     {
1992     # okay, got object as first
1993     $a[0] = ref $_[0];
1994     }
1995   else
1996     {
1997     # nope, got 1,2 (Class->xxx(1) => Class,1 and not supported)
1998     $a[0] = $class;
1999     $a[0] = shift if $_[0] =~ /^[A-Z].*::/;     # classname as first?
2000     }
2001   # print "Now in objectify, my class is today $a[0]\n";
2002   my $k; 
2003   if ($count == 0)
2004     {
2005     while (@_)
2006       {
2007       $k = shift;
2008       if (!ref($k))
2009         {
2010         $k = $a[0]->new($k);
2011         }
2012       elsif (ref($k) ne $a[0])
2013         {
2014         # foreign object, try to convert to integer
2015         $k->can('as_number') ?  $k = $k->as_number() : $k = $a[0]->new($k);
2016         }
2017       push @a,$k;
2018       }
2019     }
2020   else
2021     {
2022     while ($count > 0)
2023       {
2024       $count--; 
2025       $k = shift; 
2026       if (!ref($k))
2027         {
2028         $k = $a[0]->new($k);
2029         }
2030       elsif (ref($k) ne $a[0])
2031         {
2032         # foreign object, try to convert to integer
2033         $k->can('as_number') ?  $k = $k->as_number() : $k = $a[0]->new($k);
2034         }
2035       push @a,$k;
2036       }
2037     push @a,@_;         # return other params, too
2038     }
2039   die "$class objectify needs list context" unless wantarray;
2040   @a;
2041   }
2042
2043 sub import 
2044   {
2045   my $self = shift;
2046
2047   $IMPORT++;
2048   my @a = @_; my $l = scalar @_; my $j = 0;
2049   for ( my $i = 0; $i < $l ; $i++,$j++ )
2050     {
2051     if ($_[$i] eq ':constant')
2052       {
2053       # this causes overlord er load to step in
2054       overload::constant integer => sub { $self->new(shift) };
2055       splice @a, $j, 1; $j --;
2056       }
2057     elsif ($_[$i] eq 'upgrade')
2058       {
2059       # this causes upgrading
2060       $upgrade = $_[$i+1];              # or undef to disable
2061       my $s = 2; $s = 1 if @a-$j < 2;   # avoid "can not modify non-existant..."
2062       splice @a, $j, $s; $j -= $s;
2063       }
2064     elsif ($_[$i] =~ /^lib$/i)
2065       {
2066       # this causes a different low lib to take care...
2067       $CALC = $_[$i+1] || '';
2068       my $s = 2; $s = 1 if @a-$j < 2;   # avoid "can not modify non-existant..."
2069       splice @a, $j, $s; $j -= $s;
2070       }
2071     }
2072   # any non :constant stuff is handled by our parent, Exporter
2073   # even if @_ is empty, to give it a chance 
2074   $self->SUPER::import(@a);                     # need it for subclasses
2075   $self->export_to_level(1,$self,@a);           # need it for MBF
2076
2077   # try to load core math lib
2078   my @c = split /\s*,\s*/,$CALC;
2079   push @c,'Calc';                               # if all fail, try this
2080   $CALC = '';                                   # signal error
2081   foreach my $lib (@c)
2082     {
2083     $lib = 'Math::BigInt::'.$lib if $lib !~ /^Math::BigInt/i;
2084     $lib =~ s/\.pm$//;
2085     if ($] < 5.006)
2086       {
2087       # Perl < 5.6.0 dies with "out of memory!" when eval() and ':constant' is
2088       # used in the same script, or eval inside import().
2089       (my $mod = $lib . '.pm') =~ s!::!/!g;
2090       # require does not automatically :: => /, so portability problems arise
2091       eval { require $mod; $lib->import( @c ); }
2092       }
2093     else
2094       {
2095       eval "use $lib qw/@c/;";
2096       }
2097     $CALC = $lib, last if $@ eq '';     # no error in loading lib?
2098     }
2099   die "Couldn't load any math lib, not even the default" if $CALC eq '';
2100   }
2101
2102 sub __from_hex
2103   {
2104   # convert a (ref to) big hex string to BigInt, return undef for error
2105   my $hs = shift;
2106
2107   my $x = Math::BigInt->bzero();
2108   
2109   # strip underscores
2110   $$hs =~ s/([0-9a-fA-F])_([0-9a-fA-F])/$1$2/g; 
2111   $$hs =~ s/([0-9a-fA-F])_([0-9a-fA-F])/$1$2/g; 
2112   
2113   return $x->bnan() if $$hs !~ /^[\-\+]?0x[0-9A-Fa-f]+$/;
2114
2115   my $sign = '+'; $sign = '-' if ($$hs =~ /^-/);
2116
2117   $$hs =~ s/^[+-]//;                    # strip sign
2118   if ($CALC->can('_from_hex'))
2119     {
2120     $x->{value} = $CALC->_from_hex($hs);
2121     }
2122   else
2123     {
2124     # fallback to pure perl
2125     my $mul = Math::BigInt->bzero(); $mul++;
2126     my $x65536 = Math::BigInt->new(65536);
2127     my $len = CORE::length($$hs)-2;
2128     $len = int($len/4);                 # 4-digit parts, w/o '0x'
2129     my $val; my $i = -4;
2130     while ($len >= 0)
2131       {
2132       $val = substr($$hs,$i,4);
2133       $val =~ s/^[+-]?0x// if $len == 0;        # for last part only because
2134       $val = hex($val);                         # hex does not like wrong chars
2135       $i -= 4; $len --;
2136       $x += $mul * $val if $val != 0;
2137       $mul *= $x65536 if $len >= 0;             # skip last mul
2138       }
2139     }
2140   $x->{sign} = $sign if !$x->is_zero();         # no '-0'
2141   return $x;
2142   }
2143
2144 sub __from_bin
2145   {
2146   # convert a (ref to) big binary string to BigInt, return undef for error
2147   my $bs = shift;
2148
2149   my $x = Math::BigInt->bzero();
2150   # strip underscores
2151   $$bs =~ s/([01])_([01])/$1$2/g;       
2152   $$bs =~ s/([01])_([01])/$1$2/g;       
2153   return $x->bnan() if $$bs !~ /^[+-]?0b[01]+$/;
2154
2155   my $mul = Math::BigInt->bzero(); $mul++;
2156   my $x256 = Math::BigInt->new(256);
2157
2158   my $sign = '+'; $sign = '-' if ($$bs =~ /^\-/);
2159   $$bs =~ s/^[+-]//;                            # strip sign
2160   if ($CALC->can('_from_bin'))
2161     {
2162     $x->{value} = $CALC->_from_bin($bs);
2163     }
2164   else
2165     {
2166     my $len = CORE::length($$bs)-2;
2167     $len = int($len/8);                         # 8-digit parts, w/o '0b'
2168     my $val; my $i = -8;
2169     while ($len >= 0)
2170       {
2171       $val = substr($$bs,$i,8);
2172       $val =~ s/^[+-]?0b// if $len == 0;        # for last part only
2173       #$val = oct('0b'.$val);   # does not work on Perl prior to 5.6.0
2174       # slower:
2175       # $val = ('0' x (8-CORE::length($val))).$val if CORE::length($val) < 8;
2176       $val = ord(pack('B8',substr('00000000'.$val,-8,8)));
2177       $i -= 8; $len --;
2178       $x += $mul * $val if $val != 0;
2179       $mul *= $x256 if $len >= 0;               # skip last mul
2180       }
2181     }
2182   $x->{sign} = $sign if !$x->is_zero();
2183   return $x;
2184   }
2185
2186 sub _split
2187   {
2188   # (ref to num_str) return num_str
2189   # internal, take apart a string and return the pieces
2190   # strip leading/trailing whitespace, leading zeros, underscore and reject
2191   # invalid input
2192   my $x = shift;
2193
2194   # strip white space at front, also extranous leading zeros
2195   $$x =~ s/^\s*([-]?)0*([0-9])/$1$2/g;  # will not strip '  .2'
2196   $$x =~ s/^\s+//;                      # but this will                 
2197   $$x =~ s/\s+$//g;                     # strip white space at end
2198
2199   # shortcut, if nothing to split, return early
2200   if ($$x =~ /^[+-]?\d+$/)
2201     {
2202     $$x =~ s/^([+-])0*([0-9])/$2/; my $sign = $1 || '+';
2203     return (\$sign, $x, \'', \'', \0);
2204     }
2205
2206   # invalid starting char?
2207   return if $$x !~ /^[+-]?(\.?[0-9]|0b[0-1]|0x[0-9a-fA-F])/;
2208
2209   return __from_hex($x) if $$x =~ /^[\-\+]?0x/; # hex string
2210   return __from_bin($x) if $$x =~ /^[\-\+]?0b/; # binary string
2211   
2212   # strip underscores between digits
2213   $$x =~ s/(\d)_(\d)/$1$2/g;
2214   $$x =~ s/(\d)_(\d)/$1$2/g;            # do twice for 1_2_3
2215
2216   # some possible inputs: 
2217   # 2.1234 # 0.12        # 1          # 1E1 # 2.134E1 # 434E-10 # 1.02009E-2 
2218   # .2     # 1_2_3.4_5_6 # 1.4E1_2_3  # 1e3 # +.2
2219
2220   return if $$x =~ /[Ee].*[Ee]/;        # more than one E => error
2221
2222   my ($m,$e) = split /[Ee]/,$$x;
2223   $e = '0' if !defined $e || $e eq "";
2224   # sign,value for exponent,mantint,mantfrac
2225   my ($es,$ev,$mis,$miv,$mfv);
2226   # valid exponent?
2227   if ($e =~ /^([+-]?)0*(\d+)$/) # strip leading zeros
2228     {
2229     $es = $1; $ev = $2;
2230     # valid mantissa?
2231     return if $m eq '.' || $m eq '';
2232     my ($mi,$mf) = split /\./,$m;
2233     $mi = '0' if !defined $mi;
2234     $mi .= '0' if $mi =~ /^[\-\+]?$/;
2235     $mf = '0' if !defined $mf || $mf eq '';
2236     if ($mi =~ /^([+-]?)0*(\d+)$/) # strip leading zeros
2237       {
2238       $mis = $1||'+'; $miv = $2;
2239       return unless ($mf =~ /^(\d*?)0*$/);      # strip trailing zeros
2240       $mfv = $1;
2241       return (\$mis,\$miv,\$mfv,\$es,\$ev);
2242       }
2243     }
2244   return; # NaN, not a number
2245   }
2246
2247 sub as_number
2248   {
2249   # an object might be asked to return itself as bigint on certain overloaded
2250   # operations, this does exactly this, so that sub classes can simple inherit
2251   # it or override with their own integer conversion routine
2252   my $self = shift;
2253
2254   $self->copy();
2255   }
2256
2257 sub as_hex
2258   {
2259   # return as hex string, with prefixed 0x
2260   my $x = shift; $x = $class->new($x) if !ref($x);
2261
2262   return $x->bstr() if $x->{sign} !~ /^[+-]$/;  # inf, nan etc
2263   return '0x0' if $x->is_zero();
2264
2265   my $es = ''; my $s = '';
2266   $s = $x->{sign} if $x->{sign} eq '-';
2267   if ($CALC->can('_as_hex'))
2268     {
2269     $es = ${$CALC->_as_hex($x->{value})};
2270     }
2271   else
2272     {
2273     my $x1 = $x->copy()->babs(); my $xr;
2274     my $x10000 = Math::BigInt->new (0x10000);
2275     while (!$x1->is_zero())
2276       {
2277       ($x1, $xr) = bdiv($x1,$x10000);
2278       $es .= unpack('h4',pack('v',$xr->numify()));
2279       }
2280     $es = reverse $es;
2281     $es =~ s/^[0]+//;   # strip leading zeros
2282     $s .= '0x';
2283     }
2284   $s . $es;
2285   }
2286
2287 sub as_bin
2288   {
2289   # return as binary string, with prefixed 0b
2290   my $x = shift; $x = $class->new($x) if !ref($x);
2291
2292   return $x->bstr() if $x->{sign} !~ /^[+-]$/;  # inf, nan etc
2293   return '0b0' if $x->is_zero();
2294
2295   my $es = ''; my $s = '';
2296   $s = $x->{sign} if $x->{sign} eq '-';
2297   if ($CALC->can('_as_bin'))
2298     {
2299     $es = ${$CALC->_as_bin($x->{value})};
2300     }
2301   else
2302     {
2303     my $x1 = $x->copy()->babs(); my $xr;
2304     my $x10000 = Math::BigInt->new (0x10000);
2305     while (!$x1->is_zero())
2306       {
2307       ($x1, $xr) = bdiv($x1,$x10000);
2308       $es .= unpack('b16',pack('v',$xr->numify()));
2309       }
2310     $es = reverse $es; 
2311     $es =~ s/^[0]+//;   # strip leading zeros
2312     $s .= '0b';
2313     }
2314   $s . $es;
2315   }
2316
2317 ##############################################################################
2318 # internal calculation routines (others are in Math::BigInt::Calc etc)
2319
2320 sub __lcm 
2321   { 
2322   # (BINT or num_str, BINT or num_str) return BINT
2323   # does modify first argument
2324   # LCM
2325  
2326   my $x = shift; my $ty = shift;
2327   return $x->bnan() if ($x->{sign} eq $nan) || ($ty->{sign} eq $nan);
2328   return $x * $ty / bgcd($x,$ty);
2329   }
2330
2331 sub __gcd
2332   { 
2333   # (BINT or num_str, BINT or num_str) return BINT
2334   # does modify both arguments
2335   # GCD -- Euclids algorithm E, Knuth Vol 2 pg 296
2336   my ($x,$ty) = @_;
2337
2338   return $x->bnan() if $x->{sign} !~ /^[+-]$/ || $ty->{sign} !~ /^[+-]$/;
2339
2340   while (!$ty->is_zero())
2341     {
2342     ($x, $ty) = ($ty,bmod($x,$ty));
2343     }
2344   $x;
2345   }
2346
2347 ###############################################################################
2348 # this method return 0 if the object can be modified, or 1 for not
2349 # We use a fast use constant statement here, to avoid costly calls. Subclasses
2350 # may override it with special code (f.i. Math::BigInt::Constant does so)
2351
2352 sub modify () { 0; }
2353
2354 1;
2355 __END__
2356
2357 =head1 NAME
2358
2359 Math::BigInt - Arbitrary size integer math package
2360
2361 =head1 SYNOPSIS
2362
2363   use Math::BigInt;
2364
2365   # Number creation     
2366   $x = Math::BigInt->new($str);         # defaults to 0
2367   $nan  = Math::BigInt->bnan();         # create a NotANumber
2368   $zero = Math::BigInt->bzero();        # create a +0
2369   $inf = Math::BigInt->binf();          # create a +inf
2370   $inf = Math::BigInt->binf('-');       # create a -inf
2371   $one = Math::BigInt->bone();          # create a +1
2372   $one = Math::BigInt->bone('-');       # create a -1
2373
2374   # Testing
2375   $x->is_zero();                # true if arg is +0
2376   $x->is_nan();                 # true if arg is NaN
2377   $x->is_one();                 # true if arg is +1
2378   $x->is_one('-');              # true if arg is -1
2379   $x->is_odd();                 # true if odd, false for even
2380   $x->is_even();                # true if even, false for odd
2381   $x->is_positive();            # true if >= 0
2382   $x->is_negative();            # true if <  0
2383   $x->is_inf(sign);             # true if +inf, or -inf (sign is default '+')
2384   $x->is_int();                 # true if $x is an integer (not a float)
2385
2386   $x->bcmp($y);                 # compare numbers (undef,<0,=0,>0)
2387   $x->bacmp($y);                # compare absolutely (undef,<0,=0,>0)
2388   $x->sign();                   # return the sign, either +,- or NaN
2389   $x->digit($n);                # return the nth digit, counting from right
2390   $x->digit(-$n);               # return the nth digit, counting from left
2391
2392   # The following all modify their first argument:
2393
2394   # set 
2395   $x->bzero();                  # set $x to 0
2396   $x->bnan();                   # set $x to NaN
2397   $x->bone();                   # set $x to +1
2398   $x->bone('-');                # set $x to -1
2399   $x->binf();                   # set $x to inf
2400   $x->binf('-');                # set $x to -inf
2401
2402   $x->bneg();                   # negation
2403   $x->babs();                   # absolute value
2404   $x->bnorm();                  # normalize (no-op)
2405   $x->bnot();                   # two's complement (bit wise not)
2406   $x->binc();                   # increment x by 1
2407   $x->bdec();                   # decrement x by 1
2408   
2409   $x->badd($y);                 # addition (add $y to $x)
2410   $x->bsub($y);                 # subtraction (subtract $y from $x)
2411   $x->bmul($y);                 # multiplication (multiply $x by $y)
2412   $x->bdiv($y);                 # divide, set $x to quotient
2413                                 # return (quo,rem) or quo if scalar
2414
2415   $x->bmod($y);                 # modulus (x % y)
2416   $x->bpow($y);                 # power of arguments (x ** y)
2417   $x->blsft($y);                # left shift
2418   $x->brsft($y);                # right shift 
2419   $x->blsft($y,$n);             # left shift, by base $n (like 10)
2420   $x->brsft($y,$n);             # right shift, by base $n (like 10)
2421   
2422   $x->band($y);                 # bitwise and
2423   $x->bior($y);                 # bitwise inclusive or
2424   $x->bxor($y);                 # bitwise exclusive or
2425   $x->bnot();                   # bitwise not (two's complement)
2426
2427   $x->bsqrt();                  # calculate square-root
2428   $x->bfac();                   # factorial of $x (1*2*3*4*..$x)
2429
2430   $x->round($A,$P,$round_mode); # round to accuracy or precision using mode $r
2431   $x->bround($N);               # accuracy: preserve $N digits
2432   $x->bfround($N);              # round to $Nth digit, no-op for BigInts
2433
2434   # The following do not modify their arguments in BigInt, but do in BigFloat:
2435   $x->bfloor();                 # return integer less or equal than $x
2436   $x->bceil();                  # return integer greater or equal than $x
2437   
2438   # The following do not modify their arguments:
2439
2440   bgcd(@values);                # greatest common divisor (no OO style)
2441   blcm(@values);                # lowest common multiplicator (no OO style)
2442  
2443   $x->length();                 # return number of digits in number
2444   ($x,$f) = $x->length();       # length of number and length of fraction part,
2445                                 # latter is always 0 digits long for BigInt's
2446
2447   $x->exponent();               # return exponent as BigInt
2448   $x->mantissa();               # return (signed) mantissa as BigInt
2449   $x->parts();                  # return (mantissa,exponent) as BigInt
2450   $x->copy();                   # make a true copy of $x (unlike $y = $x;)
2451   $x->as_number();              # return as BigInt (in BigInt: same as copy())
2452   
2453   # conversation to string 
2454   $x->bstr();                   # normalized string
2455   $x->bsstr();                  # normalized string in scientific notation
2456   $x->as_hex();                 # as signed hexadecimal string with prefixed 0x
2457   $x->as_bin();                 # as signed binary string with prefixed 0b
2458
2459 =head1 DESCRIPTION
2460
2461 All operators (inlcuding basic math operations) are overloaded if you
2462 declare your big integers as
2463
2464   $i = new Math::BigInt '123_456_789_123_456_789';
2465
2466 Operations with overloaded operators preserve the arguments which is
2467 exactly what you expect.
2468
2469 =over 2
2470
2471 =item Canonical notation
2472
2473 Big integer values are strings of the form C</^[+-]\d+$/> with leading
2474 zeros suppressed.
2475
2476    '-0'                            canonical value '-0', normalized '0'
2477    '   -123_123_123'               canonical value '-123123123'
2478    '1_23_456_7890'                 canonical value '1234567890'
2479
2480 =item Input
2481
2482 Input values to these routines may be either Math::BigInt objects or
2483 strings of the form C</^\s*[+-]?[\d]+\.?[\d]*E?[+-]?[\d]*$/>.
2484
2485 You can include one underscore between any two digits.
2486
2487 This means integer values like 1.01E2 or even 1000E-2 are also accepted.
2488 Non integer values result in NaN.
2489
2490 Math::BigInt::new() defaults to 0, while Math::BigInt::new('') results
2491 in 'NaN'.
2492
2493 bnorm() on a BigInt object is now effectively a no-op, since the numbers 
2494 are always stored in normalized form. On a string, it creates a BigInt 
2495 object.
2496
2497 =item Output
2498
2499 Output values are BigInt objects (normalized), except for bstr(), which
2500 returns a string in normalized form.
2501 Some routines (C<is_odd()>, C<is_even()>, C<is_zero()>, C<is_one()>,
2502 C<is_nan()>) return true or false, while others (C<bcmp()>, C<bacmp()>)
2503 return either undef, <0, 0 or >0 and are suited for sort.
2504
2505 =back
2506
2507 =head1 METHODS
2508
2509 Each of the methods below accepts three additional parameters. These arguments
2510 $A, $P and $R are accuracy, precision and round_mode. Please see more in the
2511 section about ACCURACY and ROUNDIND.
2512
2513 =head2 brsft
2514
2515         $x->brsft($y,$n);               
2516
2517 Shifts $x right by $y in base $n. Default is base 2, used are usually 10 and
2518 2, but others work, too.
2519
2520 Right shifting usually amounts to dividing $x by $n ** $y and truncating the
2521 result:
2522
2523
2524         $x = Math::BigInt->new(10);
2525         $x->brsft(1);                   # same as $x >> 1: 5
2526         $x = Math::BigInt->new(1234);
2527         $x->brsft(2,10);                # result 12
2528
2529 There is one exception, and that is base 2 with negative $x:
2530
2531
2532         $x = Math::BigInt->new(-5);
2533         print $x->brsft(1);
2534
2535 This will print -3, not -2 (as it would if you divide -5 by 2 and truncate the
2536 result).
2537
2538 =head2 new
2539
2540         $x = Math::BigInt->new($str,$A,$P,$R);
2541
2542 Creates a new BigInt object from a string or another BigInt object. The
2543 input is accepted as decimal, hex (with leading '0x') or binary (with leading
2544 '0b').
2545
2546 =head2 bnan
2547
2548         $x = Math::BigInt->bnan();
2549
2550 Creates a new BigInt object representing NaN (Not A Number).
2551 If used on an object, it will set it to NaN:
2552
2553         $x->bnan();
2554
2555 =head2 bzero
2556
2557         $x = Math::BigInt->bzero();
2558
2559 Creates a new BigInt object representing zero.
2560 If used on an object, it will set it to zero:
2561
2562         $x->bzero();
2563
2564 =head2 binf
2565
2566         $x = Math::BigInt->binf($sign);
2567
2568 Creates a new BigInt object representing infinity. The optional argument is
2569 either '-' or '+', indicating whether you want infinity or minus infinity.
2570 If used on an object, it will set it to infinity:
2571
2572         $x->binf();
2573         $x->binf('-');
2574
2575 =head2 bone
2576
2577         $x = Math::BigInt->binf($sign);
2578
2579 Creates a new BigInt object representing one. The optional argument is
2580 either '-' or '+', indicating whether you want one or minus one.
2581 If used on an object, it will set it to one:
2582
2583         $x->bone();             # +1
2584         $x->bone('-');          # -1
2585
2586 =head2 is_one()/is_zero()/is_nan()/is_positive()/is_negative()/is_inf()/is_odd()/is_even()/is_int()
2587   
2588         $x->is_zero();                  # true if arg is +0
2589         $x->is_nan();                   # true if arg is NaN
2590         $x->is_one();                   # true if arg is +1
2591         $x->is_one('-');                # true if arg is -1
2592         $x->is_odd();                   # true if odd, false for even
2593         $x->is_even();                  # true if even, false for odd
2594         $x->is_positive();              # true if >= 0
2595         $x->is_negative();              # true if <  0
2596         $x->is_inf();                   # true if +inf
2597         $x->is_inf('-');                # true if -inf (sign is default '+')
2598         $x->is_int();                   # true if $x is an integer
2599
2600 These methods all test the BigInt for one condition and return true or false
2601 depending on the input.
2602
2603 =head2 bcmp
2604
2605   $x->bcmp($y);                 # compare numbers (undef,<0,=0,>0)
2606
2607 =head2 bacmp
2608
2609   $x->bacmp($y);                # compare absolutely (undef,<0,=0,>0)
2610
2611 =head2 sign
2612
2613   $x->sign();                   # return the sign, either +,- or NaN
2614
2615 =head2 bcmp
2616
2617   $x->digit($n);                # return the nth digit, counting from right
2618
2619 =head2 bneg
2620
2621         $x->bneg();
2622
2623 Negate the number, e.g. change the sign between '+' and '-', or between '+inf'
2624 and '-inf', respectively. Does nothing for NaN or zero.
2625
2626 =head2 babs
2627
2628         $x->babs();
2629
2630 Set the number to it's absolute value, e.g. change the sign from '-' to '+'
2631 and from '-inf' to '+inf', respectively. Does nothing for NaN or positive
2632 numbers.
2633
2634 =head2 bnorm
2635
2636   $x->bnorm();                  # normalize (no-op)
2637
2638 =head2 bnot
2639
2640   $x->bnot();                   # two's complement (bit wise not)
2641
2642 =head2 binc
2643
2644   $x->binc();                   # increment x by 1
2645
2646 =head2 bdec
2647
2648   $x->bdec();                   # decrement x by 1
2649
2650 =head2 badd
2651
2652   $x->badd($y);                 # addition (add $y to $x)
2653
2654 =head2 bsub
2655
2656   $x->bsub($y);                 # subtraction (subtract $y from $x)
2657
2658 =head2 bmul
2659
2660   $x->bmul($y);                 # multiplication (multiply $x by $y)
2661
2662 =head2 bdiv
2663
2664   $x->bdiv($y);                 # divide, set $x to quotient
2665                                 # return (quo,rem) or quo if scalar
2666
2667 =head2 bmod
2668
2669   $x->bmod($y);                 # modulus (x % y)
2670
2671 =head2 bpow
2672
2673   $x->bpow($y);                 # power of arguments (x ** y)
2674
2675 =head2 blsft
2676
2677   $x->blsft($y);                # left shift
2678   $x->blsft($y,$n);             # left shift, by base $n (like 10)
2679
2680 =head2 brsft
2681
2682   $x->brsft($y);                # right shift 
2683   $x->brsft($y,$n);             # right shift, by base $n (like 10)
2684
2685 =head2 band
2686
2687   $x->band($y);                 # bitwise and
2688
2689 =head2 bior
2690
2691   $x->bior($y);                 # bitwise inclusive or
2692
2693 =head2 bxor
2694
2695   $x->bxor($y);                 # bitwise exclusive or
2696
2697 =head2 bnot
2698
2699   $x->bnot();                   # bitwise not (two's complement)
2700
2701 =head2 bsqrt
2702
2703   $x->bsqrt();                  # calculate square-root
2704
2705 =head2 bfac
2706
2707   $x->bfac();                   # factorial of $x (1*2*3*4*..$x)
2708
2709 =head2 round
2710
2711   $x->round($A,$P,$round_mode); # round to accuracy or precision using mode $r
2712
2713 =head2 bround
2714
2715   $x->bround($N);               # accuracy: preserve $N digits
2716
2717 =head2 bfround
2718
2719   $x->bfround($N);              # round to $Nth digit, no-op for BigInts
2720
2721 =head2 bfloor
2722
2723         $x->bfloor();                   
2724
2725 Set $x to the integer less or equal than $x. This is a no-op in BigInt, but
2726 does change $x in BigFloat.
2727
2728 =head2 bceil
2729
2730         $x->bceil();
2731
2732 Set $x to the integer greater or equal than $x. This is a no-op in BigInt, but
2733 does change $x in BigFloat.
2734
2735 =head2 bgcd
2736
2737   bgcd(@values);                # greatest common divisor (no OO style)
2738
2739 =head2 blcm
2740
2741   blcm(@values);                # lowest common multiplicator (no OO style)
2742  
2743 head2 length
2744
2745         $x->length();
2746         ($xl,$fl) = $x->length();
2747
2748 Returns the number of digits in the decimal representation of the number.
2749 In list context, returns the length of the integer and fraction part. For
2750 BigInt's, the length of the fraction part will always be 0.
2751
2752 =head2 exponent
2753
2754         $x->exponent();
2755
2756 Return the exponent of $x as BigInt.
2757
2758 =head2 mantissa
2759
2760         $x->mantissa();
2761
2762 Return the signed mantissa of $x as BigInt.
2763
2764 =head2 parts
2765
2766   $x->parts();                  # return (mantissa,exponent) as BigInt
2767
2768 =head2 copy
2769
2770   $x->copy();                   # make a true copy of $x (unlike $y = $x;)
2771
2772 =head2 as_number
2773
2774   $x->as_number();              # return as BigInt (in BigInt: same as copy())
2775   
2776 =head2 bsrt
2777
2778   $x->bstr();                   # normalized string
2779
2780 =head2 bsstr
2781
2782   $x->bsstr();                  # normalized string in scientific notation
2783
2784 =head2 as_hex
2785
2786   $x->as_hex();                 # as signed hexadecimal string with prefixed 0x
2787
2788 =head2 as_bin
2789
2790   $x->as_bin();                 # as signed binary string with prefixed 0b
2791
2792 =head1 ACCURACY and PRECISION
2793
2794 Since version v1.33, Math::BigInt and Math::BigFloat have full support for
2795 accuracy and precision based rounding, both automatically after every
2796 operation as well as manually.
2797
2798 This section describes the accuracy/precision handling in Math::Big* as it
2799 used to be and as it is now, complete with an explanation of all terms and
2800 abbreviations.
2801
2802 Not yet implemented things (but with correct description) are marked with '!',
2803 things that need to be answered are marked with '?'.
2804
2805 In the next paragraph follows a short description of terms used here (because
2806 these may differ from terms used by others people or documentation).
2807
2808 During the rest of this document, the shortcuts A (for accuracy), P (for
2809 precision), F (fallback) and R (rounding mode) will be used.
2810
2811 =head2 Precision P
2812
2813 A fixed number of digits before (positive) or after (negative)
2814 the decimal point. For example, 123.45 has a precision of -2. 0 means an
2815 integer like 123 (or 120). A precision of 2 means two digits to the left
2816 of the decimal point are zero, so 123 with P = 1 becomes 120. Note that
2817 numbers with zeros before the decimal point may have different precisions,
2818 because 1200 can have p = 0, 1 or 2 (depending on what the inital value
2819 was). It could also have p < 0, when the digits after the decimal point
2820 are zero.
2821
2822 The string output (of floating point numbers) will be padded with zeros:
2823  
2824         Initial value   P       A       Result          String
2825         ------------------------------------------------------------
2826         1234.01         -3              1000            1000
2827         1234            -2              1200            1200
2828         1234.5          -1              1230            1230
2829         1234.001        1               1234            1234.0
2830         1234.01         0               1234            1234
2831         1234.01         2               1234.01         1234.01
2832         1234.01         5               1234.01         1234.01000
2833
2834 For BigInts, no padding occurs.
2835
2836 =head2 Accuracy A
2837
2838 Number of significant digits. Leading zeros are not counted. A
2839 number may have an accuracy greater than the non-zero digits
2840 when there are zeros in it or trailing zeros. For example, 123.456 has
2841 A of 6, 10203 has 5, 123.0506 has 7, 123.450000 has 8 and 0.000123 has 3.
2842
2843 The string output (of floating point numbers) will be padded with zeros:
2844
2845         Initial value   P       A       Result          String
2846         ------------------------------------------------------------
2847         1234.01                 3       1230            1230
2848         1234.01                 6       1234.01         1234.01
2849         1234.1                  8       1234.1          1234.1000
2850
2851 For BigInts, no padding occurs.
2852
2853 =head2 Fallback F
2854
2855 When both A and P are undefined, this is used as a fallback accuracy when
2856 dividing numbers.
2857
2858 =head2 Rounding mode R
2859
2860 When rounding a number, different 'styles' or 'kinds'
2861 of rounding are possible. (Note that random rounding, as in
2862 Math::Round, is not implemented.)
2863
2864 =over 2
2865
2866 =item 'trunc'
2867
2868 truncation invariably removes all digits following the
2869 rounding place, replacing them with zeros. Thus, 987.65 rounded
2870 to tens (P=1) becomes 980, and rounded to the fourth sigdig
2871 becomes 987.6 (A=4). 123.456 rounded to the second place after the
2872 decimal point (P=-2) becomes 123.46.
2873
2874 All other implemented styles of rounding attempt to round to the
2875 "nearest digit." If the digit D immediately to the right of the
2876 rounding place (skipping the decimal point) is greater than 5, the
2877 number is incremented at the rounding place (possibly causing a
2878 cascade of incrementation): e.g. when rounding to units, 0.9 rounds
2879 to 1, and -19.9 rounds to -20. If D < 5, the number is similarly
2880 truncated at the rounding place: e.g. when rounding to units, 0.4
2881 rounds to 0, and -19.4 rounds to -19.
2882
2883 However the results of other styles of rounding differ if the
2884 digit immediately to the right of the rounding place (skipping the
2885 decimal point) is 5 and if there are no digits, or no digits other
2886 than 0, after that 5. In such cases:
2887
2888 =item 'even'
2889
2890 rounds the digit at the rounding place to 0, 2, 4, 6, or 8
2891 if it is not already. E.g., when rounding to the first sigdig, 0.45
2892 becomes 0.4, -0.55 becomes -0.6, but 0.4501 becomes 0.5.
2893
2894 =item 'odd'
2895
2896 rounds the digit at the rounding place to 1, 3, 5, 7, or 9 if
2897 it is not already. E.g., when rounding to the first sigdig, 0.45
2898 becomes 0.5, -0.55 becomes -0.5, but 0.5501 becomes 0.6.
2899
2900 =item '+inf'
2901
2902 round to plus infinity, i.e. always round up. E.g., when
2903 rounding to the first sigdig, 0.45 becomes 0.5, -0.55 becomes -0.5,
2904 and 0.4501 also becomes 0.5.
2905
2906 =item '-inf'
2907
2908 round to minus infinity, i.e. always round down. E.g., when
2909 rounding to the first sigdig, 0.45 becomes 0.4, -0.55 becomes -0.6,
2910 but 0.4501 becomes 0.5.
2911
2912 =item 'zero'
2913
2914 round to zero, i.e. positive numbers down, negative ones up.
2915 E.g., when rounding to the first sigdig, 0.45 becomes 0.4, -0.55
2916 becomes -0.5, but 0.4501 becomes 0.5.
2917
2918 =back
2919
2920 The handling of A & P in MBI/MBF (the old core code shipped with Perl
2921 versions <= 5.7.2) is like this:
2922
2923 =over 2
2924
2925 =item Precision
2926
2927   * ffround($p) is able to round to $p number of digits after the decimal
2928     point
2929   * otherwise P is unused
2930
2931 =item Accuracy (significant digits)
2932
2933   * fround($a) rounds to $a significant digits
2934   * only fdiv() and fsqrt() take A as (optional) paramater
2935     + other operations simply create the same number (fneg etc), or more (fmul)
2936       of digits
2937     + rounding/truncating is only done when explicitly calling one of fround
2938       or ffround, and never for BigInt (not implemented)
2939   * fsqrt() simply hands its accuracy argument over to fdiv.
2940   * the documentation and the comment in the code indicate two different ways
2941     on how fdiv() determines the maximum number of digits it should calculate,
2942     and the actual code does yet another thing
2943     POD:
2944       max($Math::BigFloat::div_scale,length(dividend)+length(divisor))
2945     Comment:
2946       result has at most max(scale, length(dividend), length(divisor)) digits
2947     Actual code:
2948       scale = max(scale, length(dividend)-1,length(divisor)-1);
2949       scale += length(divisior) - length(dividend);
2950     So for lx = 3, ly = 9, scale = 10, scale will actually be 16 (10+9-3).
2951     Actually, the 'difference' added to the scale is calculated from the
2952     number of "significant digits" in dividend and divisor, which is derived
2953     by looking at the length of the mantissa. Which is wrong, since it includes
2954     the + sign (oups) and actually gets 2 for '+100' and 4 for '+101'. Oups
2955     again. Thus 124/3 with div_scale=1 will get you '41.3' based on the strange
2956     assumption that 124 has 3 significant digits, while 120/7 will get you
2957     '17', not '17.1' since 120 is thought to have 2 significant digits.
2958     The rounding after the division then uses the remainder and $y to determine
2959     wether it must round up or down.
2960  ?  I have no idea which is the right way. That's why I used a slightly more
2961  ?  simple scheme and tweaked the few failing testcases to match it.
2962
2963 =back
2964
2965 This is how it works now:
2966
2967 =over 2
2968
2969 =item Setting/Accessing
2970
2971   * You can set the A global via Math::BigInt->accuracy() or
2972     Math::BigFloat->accuracy() or whatever class you are using.
2973   * You can also set P globally by using Math::SomeClass->precision() likewise.
2974   * Globals are classwide, and not inherited by subclasses.
2975   * to undefine A, use Math::SomeCLass->accuracy(undef);
2976   * to undefine P, use Math::SomeClass->precision(undef);
2977   * Setting Math::SomeClass->accuracy() clears automatically
2978     Math::SomeClass->precision(), and vice versa.
2979   * To be valid, A must be > 0, P can have any value.
2980   * If P is negative, this means round to the P'th place to the right of the
2981     decimal point; positive values mean to the left of the decimal point.
2982     P of 0 means round to integer.
2983   * to find out the current global A, take Math::SomeClass->accuracy()
2984   * to find out the current global P, take Math::SomeClass->precision()
2985   * use $x->accuracy() respective $x->precision() for the local setting of $x.
2986   * Please note that $x->accuracy() respecive $x->precision() fall back to the
2987     defined globals, when $x's A or P is not set.
2988
2989 =item Creating numbers
2990
2991   * When you create a number, you can give it's desired A or P via:
2992     $x = Math::BigInt->new($number,$A,$P);
2993   * Only one of A or P can be defined, otherwise the result is NaN
2994   * If no A or P is give ($x = Math::BigInt->new($number) form), then the
2995     globals (if set) will be used. Thus changing the global defaults later on
2996     will not change the A or P of previously created numbers (i.e., A and P of
2997     $x will be what was in effect when $x was created)
2998   * If given undef for A and P, B<no> rounding will occur, and the globals will
2999     B<not> be used. This is used by subclasses to create numbers without
3000     suffering rounding in the parent. Thus a subclass is able to have it's own
3001     globals enforced upon creation of a number by using
3002     $x = Math::BigInt->new($number,undef,undef):
3003
3004         use Math::Bigint::SomeSubclass;
3005         use Math::BigInt;
3006
3007         Math::BigInt->accuracy(2);
3008         Math::BigInt::SomeSubClass->accuracy(3);
3009         $x = Math::BigInt::SomeSubClass->new(1234);     
3010
3011     $x is now 1230, and not 1200. A subclass might choose to implement
3012     this otherwise, e.g. falling back to the parent's A and P.
3013
3014 =item Usage
3015
3016   * If A or P are enabled/defined, they are used to round the result of each
3017     operation according to the rules below
3018   * Negative P is ignored in Math::BigInt, since BigInts never have digits
3019     after the decimal point
3020   * Math::BigFloat uses Math::BigInts internally, but setting A or P inside
3021     Math::BigInt as globals should not tamper with the parts of a BigFloat.
3022     Thus a flag is used to mark all Math::BigFloat numbers as 'never round'
3023
3024 =item Precedence
3025
3026   * It only makes sense that a number has only one of A or P at a time.
3027     Since you can set/get both A and P, there is a rule that will practically
3028     enforce only A or P to be in effect at a time, even if both are set.
3029     This is called precedence.
3030   * If two objects are involved in an operation, and one of them has A in
3031     effect, and the other P, this results in an error (NaN).
3032   * A takes precendence over P (Hint: A comes before P). If A is defined, it
3033     is used, otherwise P is used. If neither of them is defined, nothing is
3034     used, i.e. the result will have as many digits as it can (with an
3035     exception for fdiv/fsqrt) and will not be rounded.
3036   * There is another setting for fdiv() (and thus for fsqrt()). If neither of
3037     A or P is defined, fdiv() will use a fallback (F) of $div_scale digits.
3038     If either the dividend's or the divisor's mantissa has more digits than
3039     the value of F, the higher value will be used instead of F.
3040     This is to limit the digits (A) of the result (just consider what would
3041     happen with unlimited A and P in the case of 1/3 :-)
3042   * fdiv will calculate (at least) 4 more digits than required (determined by
3043     A, P or F), and, if F is not used, round the result
3044     (this will still fail in the case of a result like 0.12345000000001 with A
3045     or P of 5, but this can not be helped - or can it?)
3046   * Thus you can have the math done by on Math::Big* class in three modes:
3047     + never round (this is the default):
3048       This is done by setting A and P to undef. No math operation
3049       will round the result, with fdiv() and fsqrt() as exceptions to guard
3050       against overflows. You must explicitely call bround(), bfround() or
3051       round() (the latter with parameters).
3052       Note: Once you have rounded a number, the settings will 'stick' on it
3053       and 'infect' all other numbers engaged in math operations with it, since
3054       local settings have the highest precedence. So, to get SaferRound[tm],
3055       use a copy() before rounding like this:
3056
3057         $x = Math::BigFloat->new(12.34);
3058         $y = Math::BigFloat->new(98.76);
3059         $z = $x * $y;                           # 1218.6984
3060         print $x->copy()->fround(3);            # 12.3 (but A is now 3!)
3061         $z = $x * $y;                           # still 1218.6984, without
3062                                                 # copy would have been 1210!
3063
3064     + round after each op:
3065       After each single operation (except for testing like is_zero()), the
3066       method round() is called and the result is rounded appropriately. By
3067       setting proper values for A and P, you can have all-the-same-A or
3068       all-the-same-P modes. For example, Math::Currency might set A to undef,
3069       and P to -2, globally.
3070
3071  ?Maybe an extra option that forbids local A & P settings would be in order,
3072  ?so that intermediate rounding does not 'poison' further math? 
3073
3074 =item Overriding globals
3075
3076   * you will be able to give A, P and R as an argument to all the calculation
3077     routines; the second parameter is A, the third one is P, and the fourth is
3078     R (shift right by one for binary operations like badd). P is used only if
3079     the first parameter (A) is undefined. These three parameters override the
3080     globals in the order detailed as follows, i.e. the first defined value
3081     wins:
3082     (local: per object, global: global default, parameter: argument to sub)
3083       + parameter A
3084       + parameter P
3085       + local A (if defined on both of the operands: smaller one is taken)
3086       + local P (if defined on both of the operands: bigger one is taken)
3087       + global A
3088       + global P
3089       + global F
3090   * fsqrt() will hand its arguments to fdiv(), as it used to, only now for two
3091     arguments (A and P) instead of one
3092
3093 =item Local settings
3094
3095   * You can set A and P locally by using $x->accuracy() and $x->precision()
3096     and thus force different A and P for different objects/numbers.
3097   * Setting A or P this way immediately rounds $x to the new value.
3098   * $x->accuracy() clears $x->precision(), and vice versa.
3099
3100 =item Rounding
3101
3102   * the rounding routines will use the respective global or local settings.
3103     fround()/bround() is for accuracy rounding, while ffround()/bfround()
3104     is for precision
3105   * the two rounding functions take as the second parameter one of the
3106     following rounding modes (R):
3107     'even', 'odd', '+inf', '-inf', 'zero', 'trunc'
3108   * you can set and get the global R by using Math::SomeClass->round_mode()
3109     or by setting $Math::SomeClass::round_mode
3110   * after each operation, $result->round() is called, and the result may
3111     eventually be rounded (that is, if A or P were set either locally,
3112     globally or as parameter to the operation)
3113   * to manually round a number, call $x->round($A,$P,$round_mode);
3114     this will round the number by using the appropriate rounding function
3115     and then normalize it.
3116   * rounding modifies the local settings of the number:
3117
3118         $x = Math::BigFloat->new(123.456);
3119         $x->accuracy(5);
3120         $x->bround(4);
3121
3122     Here 4 takes precedence over 5, so 123.5 is the result and $x->accuracy()
3123     will be 4 from now on.
3124
3125 =item Default values
3126
3127   * R: 'even'
3128   * F: 40
3129   * A: undef
3130   * P: undef
3131
3132 =item Remarks
3133
3134   * The defaults are set up so that the new code gives the same results as
3135     the old code (except in a few cases on fdiv):
3136     + Both A and P are undefined and thus will not be used for rounding
3137       after each operation.
3138     + round() is thus a no-op, unless given extra parameters A and P
3139
3140 =back
3141
3142 =head1 INTERNALS
3143
3144 The actual numbers are stored as unsigned big integers (with seperate sign).
3145 You should neither care about nor depend on the internal representation; it
3146 might change without notice. Use only method calls like C<< $x->sign(); >>
3147 instead relying on the internal hash keys like in C<< $x->{sign}; >>. 
3148
3149 =head2 MATH LIBRARY
3150
3151 Math with the numbers is done (by default) by a module called
3152 Math::BigInt::Calc. This is equivalent to saying:
3153
3154         use Math::BigInt lib => 'Calc';
3155
3156 You can change this by using:
3157
3158         use Math::BigInt lib => 'BitVect';
3159
3160 The following would first try to find Math::BigInt::Foo, then
3161 Math::BigInt::Bar, and when this also fails, revert to Math::BigInt::Calc:
3162
3163         use Math::BigInt lib => 'Foo,Math::BigInt::Bar';
3164
3165 Calc.pm uses as internal format an array of elements of some decimal base
3166 (usually 1e5 or 1e7) with the least significant digit first, while BitVect.pm
3167 uses a bit vector of base 2, most significant bit first. Other modules might
3168 use even different means of representing the numbers. See the respective
3169 module documentation for further details.
3170
3171 =head2 SIGN
3172
3173 The sign is either '+', '-', 'NaN', '+inf' or '-inf' and stored seperately.
3174
3175 A sign of 'NaN' is used to represent the result when input arguments are not
3176 numbers or as a result of 0/0. '+inf' and '-inf' represent plus respectively
3177 minus infinity. You will get '+inf' when dividing a positive number by 0, and
3178 '-inf' when dividing any negative number by 0.
3179
3180 =head2 mantissa(), exponent() and parts()
3181
3182 C<mantissa()> and C<exponent()> return the said parts of the BigInt such
3183 that:
3184
3185         $m = $x->mantissa();
3186         $e = $x->exponent();
3187         $y = $m * ( 10 ** $e );
3188         print "ok\n" if $x == $y;
3189
3190 C<< ($m,$e) = $x->parts() >> is just a shortcut that gives you both of them
3191 in one go. Both the returned mantissa and exponent have a sign.
3192
3193 Currently, for BigInts C<$e> will be always 0, except for NaN, +inf and -inf,
3194 where it will be NaN; and for $x == 0, where it will be 1
3195 (to be compatible with Math::BigFloat's internal representation of a zero as
3196 C<0E1>).
3197
3198 C<$m> will always be a copy of the original number. The relation between $e
3199 and $m might change in the future, but will always be equivalent in a
3200 numerical sense, e.g. $m might get minimized.
3201
3202 =head1 EXAMPLES
3203  
3204   use Math::BigInt;
3205
3206   sub bint { Math::BigInt->new(shift); }
3207
3208   $x = Math::BigInt->bstr("1234")       # string "1234"
3209   $x = "$x";                            # same as bstr()
3210   $x = Math::BigInt->bneg("1234");      # Bigint "-1234"
3211   $x = Math::BigInt->babs("-12345");    # Bigint "12345"
3212   $x = Math::BigInt->bnorm("-0 00");    # BigInt "0"
3213   $x = bint(1) + bint(2);               # BigInt "3"
3214   $x = bint(1) + "2";                   # ditto (auto-BigIntify of "2")
3215   $x = bint(1);                         # BigInt "1"
3216   $x = $x + 5 / 2;                      # BigInt "3"
3217   $x = $x ** 3;                         # BigInt "27"
3218   $x *= 2;                              # BigInt "54"
3219   $x = Math::BigInt->new(0);            # BigInt "0"
3220   $x--;                                 # BigInt "-1"
3221   $x = Math::BigInt->badd(4,5)          # BigInt "9"
3222   print $x->bsstr();                    # 9e+0
3223
3224 Examples for rounding:
3225
3226   use Math::BigFloat;
3227   use Test;
3228
3229   $x = Math::BigFloat->new(123.4567);
3230   $y = Math::BigFloat->new(123.456789);
3231   Math::BigFloat->accuracy(4);          # no more A than 4
3232
3233   ok ($x->copy()->fround(),123.4);      # even rounding
3234   print $x->copy()->fround(),"\n";      # 123.4
3235   Math::BigFloat->round_mode('odd');    # round to odd
3236   print $x->copy()->fround(),"\n";      # 123.5
3237   Math::BigFloat->accuracy(5);          # no more A than 5
3238   Math::BigFloat->round_mode('odd');    # round to odd
3239   print $x->copy()->fround(),"\n";      # 123.46
3240   $y = $x->copy()->fround(4),"\n";      # A = 4: 123.4
3241   print "$y, ",$y->accuracy(),"\n";     # 123.4, 4
3242
3243   Math::BigFloat->accuracy(undef);      # A not important now
3244   Math::BigFloat->precision(2);         # P important
3245   print $x->copy()->bnorm(),"\n";       # 123.46
3246   print $x->copy()->fround(),"\n";      # 123.46
3247
3248 Examples for converting:
3249
3250   my $x = Math::BigInt->new('0b1'.'01' x 123);
3251   print "bin: ",$x->as_bin()," hex:",$x->as_hex()," dec: ",$x,"\n";
3252
3253 =head1 Autocreating constants
3254
3255 After C<use Math::BigInt ':constant'> all the B<integer> decimal constants
3256 in the given scope are converted to C<Math::BigInt>. This conversion
3257 happens at compile time.
3258
3259 In particular,
3260
3261   perl -MMath::BigInt=:constant -e 'print 2**100,"\n"'
3262
3263 prints the integer value of C<2**100>.  Note that without conversion of 
3264 constants the expression 2**100 will be calculated as perl scalar.
3265
3266 Please note that strings and floating point constants are not affected,
3267 so that
3268
3269         use Math::BigInt qw/:constant/;
3270
3271         $x = 1234567890123456789012345678901234567890
3272                 + 123456789123456789;
3273         $y = '1234567890123456789012345678901234567890'
3274                 + '123456789123456789';
3275
3276 do not work. You need an explicit Math::BigInt->new() around one of the
3277 operands. You should also quote large constants to protect loss of precision:
3278
3279         use Math::Bigint;
3280
3281         $x = Math::BigInt->new('1234567889123456789123456789123456789');
3282
3283 Without the quotes Perl would convert the large number to a floating point
3284 constant at compile time and then hand the result to BigInt, which results in
3285 an truncated result or a NaN.
3286
3287 =head1 PERFORMANCE
3288
3289 Using the form $x += $y; etc over $x = $x + $y is faster, since a copy of $x
3290 must be made in the second case. For long numbers, the copy can eat up to 20%
3291 of the work (in the case of addition/subtraction, less for
3292 multiplication/division). If $y is very small compared to $x, the form
3293 $x += $y is MUCH faster than $x = $x + $y since making the copy of $x takes
3294 more time then the actual addition.
3295
3296 With a technique called copy-on-write, the cost of copying with overload could
3297 be minimized or even completely avoided. A test implementation of COW did show
3298 performance gains for overloaded math, but introduced a performance loss due
3299 to a constant overhead for all other operatons.
3300
3301 The rewritten version of this module is slower on certain operations, like
3302 new(), bstr() and numify(). The reason are that it does now more work and
3303 handles more cases. The time spent in these operations is usually gained in
3304 the other operations so that programs on the average should get faster. If
3305 they don't, please contect the author.
3306
3307 Some operations may be slower for small numbers, but are significantly faster
3308 for big numbers. Other operations are now constant (O(1), like bneg(), babs()
3309 etc), instead of O(N) and thus nearly always take much less time. These
3310 optimizations were done on purpose.
3311
3312 If you find the Calc module to slow, try to install any of the replacement
3313 modules and see if they help you. 
3314
3315 =head2 Alternative math libraries
3316
3317 You can use an alternative library to drive Math::BigInt via:
3318
3319         use Math::BigInt lib => 'Module';
3320
3321 See L<MATH LIBRARY> for more information.
3322
3323 For more benchmark results see L<http://bloodgate.com/perl/benchmarks.html>.
3324
3325 =head2 SUBCLASSING
3326
3327 =head1 Subclassing Math::BigInt
3328
3329 The basic design of Math::BigInt allows simple subclasses with very little
3330 work, as long as a few simple rules are followed:
3331
3332 =over 2
3333
3334 =item *
3335
3336 The public API must remain consistent, i.e. if a sub-class is overloading
3337 addition, the sub-class must use the same name, in this case badd(). The
3338 reason for this is that Math::BigInt is optimized to call the object methods
3339 directly.
3340
3341 =item *
3342
3343 The private object hash keys like C<$x->{sign}> may not be changed, but
3344 additional keys can be added, like C<$x->{_custom}>.
3345
3346 =item *
3347
3348 Accessor functions are available for all existing object hash keys and should
3349 be used instead of directly accessing the internal hash keys. The reason for
3350 this is that Math::BigInt itself has a pluggable interface which permits it
3351 to support different storage methods.
3352
3353 =back
3354
3355 More complex sub-classes may have to replicate more of the logic internal of
3356 Math::BigInt if they need to change more basic behaviors. A subclass that
3357 needs to merely change the output only needs to overload C<bstr()>. 
3358
3359 All other object methods and overloaded functions can be directly inherited
3360 from the parent class.
3361
3362 At the very minimum, any subclass will need to provide it's own C<new()> and can
3363 store additional hash keys in the object. There are also some package globals
3364 that must be defined, e.g.:
3365
3366   # Globals
3367   $accuracy = undef;
3368   $precision = -2;       # round to 2 decimal places
3369   $round_mode = 'even';
3370   $div_scale = 40;
3371
3372 Additionally, you might want to provide the following two globals to allow
3373 auto-upgrading and auto-downgrading to work correctly:
3374
3375   $upgrade = undef;
3376   $downgrade = undef;
3377
3378 This allows Math::BigInt to correctly retrieve package globals from the 
3379 subclass, like C<$SubClass::precision>.  See t/Math/BigInt/Subclass.pm or
3380 t/Math/BigFloat/SubClass.pm completely functional subclass examples.
3381
3382 Don't forget to 
3383
3384         use overload;
3385
3386 in your subclass to automatically inherit the overloading from the parent. If
3387 you like, you can change part of the overloading, look at Math::String for an
3388 example.
3389
3390 =head1 UPGRADING
3391
3392 When used like this:
3393
3394         use Math::BigInt upgrade => 'Foo::Bar';
3395
3396 certain operations will 'upgrade' their calculation and thus the result to
3397 the class Foo::Bar. Usually this is used in conjunction with Math::BigFloat:
3398
3399         use Math::BigInt upgrade => 'Math::BigFloat';
3400
3401 As a shortcut, you can use the module C<bignum>:
3402
3403         use bignum;
3404
3405 Also good for oneliners:
3406
3407         perl -Mbignum -le 'print 2 ** 255'
3408
3409 This makes it possible to mix arguments of different classes (as in 2.5 + 2)
3410 as well es preserve accuracy (as in sqrt(3)).
3411
3412 Beware: This feature is not fully implemented yet.
3413
3414 =head2 Auto-upgrade
3415
3416 The following methods upgrade themselves unconditionally; that is if upgrade
3417 is in effect, they will always hand up their work:
3418
3419 =over 2
3420
3421 =item bsqrt()
3422
3423 =item div()
3424
3425 =item blog()
3426
3427 =back
3428
3429 Beware: This list is not complete.
3430
3431 All other methods upgrade themselves only when one (or all) of their
3432 arguments are of the class mentioned in $upgrade (This might change in later
3433 versions to a more sophisticated scheme):
3434
3435 =head1 BUGS
3436
3437 =over 2
3438
3439 =item Out of Memory!
3440
3441 Under Perl prior to 5.6.0 having an C<use Math::BigInt ':constant';> and 
3442 C<eval()> in your code will crash with "Out of memory". This is probably an
3443 overload/exporter bug. You can workaround by not having C<eval()> 
3444 and ':constant' at the same time or upgrade your Perl to a newer version.
3445
3446 =item Fails to load Calc on Perl prior 5.6.0
3447
3448 Since eval(' use ...') can not be used in conjunction with ':constant', BigInt
3449 will fall back to eval { require ... } when loading the math lib on Perls
3450 prior to 5.6.0. This simple replaces '::' with '/' and thus might fail on
3451 filesystems using a different seperator.  
3452
3453 =back
3454
3455 =head1 CAVEATS
3456
3457 Some things might not work as you expect them. Below is documented what is
3458 known to be troublesome:
3459
3460 =over 1
3461
3462 =item stringify, bstr(), bsstr() and 'cmp'
3463
3464 Both stringify and bstr() now drop the leading '+'. The old code would return
3465 '+3', the new returns '3'. This is to be consistent with Perl and to make
3466 cmp (especially with overloading) to work as you expect. It also solves
3467 problems with Test.pm, it's ok() uses 'eq' internally. 
3468
3469 Mark said, when asked about to drop the '+' altogether, or make only cmp work:
3470
3471         I agree (with the first alternative), don't add the '+' on positive
3472         numbers.  It's not as important anymore with the new internal 
3473         form for numbers.  It made doing things like abs and neg easier,
3474         but those have to be done differently now anyway.
3475
3476 So, the following examples will now work all as expected:
3477
3478         use Test;
3479         BEGIN { plan tests => 1 }
3480         use Math::BigInt;
3481
3482         my $x = new Math::BigInt 3*3;
3483         my $y = new Math::BigInt 3*3;
3484
3485         ok ($x,3*3);
3486         print "$x eq 9" if $x eq $y;
3487         print "$x eq 9" if $x eq '9';
3488         print "$x eq 9" if $x eq 3*3;
3489
3490 Additionally, the following still works:
3491         
3492         print "$x == 9" if $x == $y;
3493         print "$x == 9" if $x == 9;
3494         print "$x == 9" if $x == 3*3;
3495
3496 There is now a C<bsstr()> method to get the string in scientific notation aka
3497 C<1e+2> instead of C<100>. Be advised that overloaded 'eq' always uses bstr()
3498 for comparisation, but Perl will represent some numbers as 100 and others
3499 as 1e+308. If in doubt, convert both arguments to Math::BigInt before doing eq:
3500
3501         use Test;
3502         BEGIN { plan tests => 3 }
3503         use Math::BigInt;
3504
3505         $x = Math::BigInt->new('1e56'); $y = 1e56;
3506         ok ($x,$y);                     # will fail
3507         ok ($x->bsstr(),$y);            # okay
3508         $y = Math::BigInt->new($y);
3509         ok ($x,$y);                     # okay
3510
3511 Alternatively, simple use <=> for comparisations, that will get it always
3512 right. There is not yet a way to get a number automatically represented as
3513 a string that matches exactly the way Perl represents it.
3514
3515 =item int()
3516
3517 C<int()> will return (at least for Perl v5.7.1 and up) another BigInt, not a 
3518 Perl scalar:
3519
3520         $x = Math::BigInt->new(123);
3521         $y = int($x);                           # BigInt 123
3522         $x = Math::BigFloat->new(123.45);
3523         $y = int($x);                           # BigInt 123
3524
3525 In all Perl versions you can use C<as_number()> for the same effect:
3526
3527         $x = Math::BigFloat->new(123.45);
3528         $y = $x->as_number();                   # BigInt 123
3529
3530 This also works for other subclasses, like Math::String.
3531
3532 It is yet unlcear whether overloaded int() should return a scalar or a BigInt.
3533
3534 =item length
3535
3536 The following will probably not do what you expect:
3537
3538         $c = Math::BigInt->new(123);
3539         print $c->length(),"\n";                # prints 30
3540
3541 It prints both the number of digits in the number and in the fraction part
3542 since print calls C<length()> in list context. Use something like: 
3543         
3544         print scalar $c->length(),"\n";         # prints 3 
3545
3546 =item bdiv
3547
3548 The following will probably not do what you expect:
3549
3550         print $c->bdiv(10000),"\n";
3551
3552 It prints both quotient and remainder since print calls C<bdiv()> in list
3553 context. Also, C<bdiv()> will modify $c, so be carefull. You probably want
3554 to use
3555         
3556         print $c / 10000,"\n";
3557         print scalar $c->bdiv(10000),"\n";  # or if you want to modify $c
3558
3559 instead.
3560
3561 The quotient is always the greatest integer less than or equal to the
3562 real-valued quotient of the two operands, and the remainder (when it is
3563 nonzero) always has the same sign as the second operand; so, for
3564 example,
3565
3566           1 / 4  => ( 0, 1)
3567           1 / -4 => (-1,-3)
3568          -3 / 4  => (-1, 1)
3569          -3 / -4 => ( 0,-3)
3570         -11 / 2  => (-5,1)
3571          11 /-2  => (-5,-1)
3572
3573 As a consequence, the behavior of the operator % agrees with the
3574 behavior of Perl's built-in % operator (as documented in the perlop
3575 manpage), and the equation
3576
3577         $x == ($x / $y) * $y + ($x % $y)
3578
3579 holds true for any $x and $y, which justifies calling the two return
3580 values of bdiv() the quotient and remainder. The only exception to this rule
3581 are when $y == 0 and $x is negative, then the remainder will also be
3582 negative. See below under "infinity handling" for the reasoning behing this.
3583
3584 Perl's 'use integer;' changes the behaviour of % and / for scalars, but will
3585 not change BigInt's way to do things. This is because under 'use integer' Perl
3586 will do what the underlying C thinks is right and this is different for each
3587 system. If you need BigInt's behaving exactly like Perl's 'use integer', bug
3588 the author to implement it ;)
3589
3590 =item infinity handling
3591
3592 Here are some examples that explain the reasons why certain results occur while
3593 handling infinity:
3594
3595 The following table shows the result of the division and the remainder, so that
3596 the equation above holds true. Some "ordinary" cases are strewn in to show more
3597 clearly the reasoning:
3598
3599         A /  B  =   C,     R so that C *    B +    R =    A
3600      =========================================================
3601         5 /   8 =   0,     5         0 *    8 +    5 =    5
3602         0 /   8 =   0,     0         0 *    8 +    0 =    0
3603         0 / inf =   0,     0         0 *  inf +    0 =    0
3604         0 /-inf =   0,     0         0 * -inf +    0 =    0
3605         5 / inf =   0,     5         0 *  inf +    5 =    5
3606         5 /-inf =   0,     5         0 * -inf +    5 =    5
3607         -5/ inf =   0,    -5         0 *  inf +   -5 =   -5
3608         -5/-inf =   0,    -5         0 * -inf +   -5 =   -5
3609        inf/   5 =  inf,    0       inf *    5 +    0 =  inf
3610       -inf/   5 = -inf,    0      -inf *    5 +    0 = -inf
3611        inf/  -5 = -inf,    0      -inf *   -5 +    0 =  inf
3612       -inf/  -5 =  inf,    0       inf *   -5 +    0 = -inf
3613          5/   5 =    1,    0         1 *    5 +    0 =    5
3614         -5/  -5 =    1,    0         1 *   -5 +    0 =   -5
3615        inf/ inf =    1,    0         1 *  inf +    0 =  inf
3616       -inf/-inf =    1,    0         1 * -inf +    0 = -inf
3617        inf/-inf =   -1,    0        -1 * -inf +    0 =  inf
3618       -inf/ inf =   -1,    0         1 * -inf +    0 = -inf
3619          8/   0 =  inf,    8       inf *    0 +    8 =    8 
3620        inf/   0 =  inf,  inf       inf *    0 +  inf =  inf 
3621          0/   0 =  NaN
3622
3623 These cases below violate the "remainder has the sign of the second of the two
3624 arguments", since they wouldn't match up otherwise.
3625
3626         A /  B  =   C,     R so that C *    B +    R =    A
3627      ========================================================
3628       -inf/   0 = -inf, -inf      -inf *    0 +  inf = -inf 
3629         -8/   0 = -inf,   -8      -inf *    0 +    8 = -8 
3630
3631 =item Modifying and =
3632
3633 Beware of:
3634
3635         $x = Math::BigFloat->new(5);
3636         $y = $x;
3637
3638 It will not do what you think, e.g. making a copy of $x. Instead it just makes
3639 a second reference to the B<same> object and stores it in $y. Thus anything
3640 that modifies $x (except overloaded operators) will modify $y, and vice versa.
3641 Or in other words, C<=> is only safe if you modify your BigInts only via
3642 overloaded math. As soon as you use a method call it breaks:
3643
3644         $x->bmul(2);
3645         print "$x, $y\n";       # prints '10, 10'
3646
3647 If you want a true copy of $x, use:
3648
3649         $y = $x->copy();
3650
3651 You can also chain the calls like this, this will make first a copy and then
3652 multiply it by 2:
3653
3654         $y = $x->copy()->bmul(2);
3655
3656 See also the documentation for overload.pm regarding C<=>.
3657
3658 =item bpow
3659
3660 C<bpow()> (and the rounding functions) now modifies the first argument and
3661 returns it, unlike the old code which left it alone and only returned the
3662 result. This is to be consistent with C<badd()> etc. The first three will
3663 modify $x, the last one won't:
3664
3665         print bpow($x,$i),"\n";         # modify $x
3666         print $x->bpow($i),"\n";        # ditto
3667         print $x **= $i,"\n";           # the same
3668         print $x ** $i,"\n";            # leave $x alone 
3669
3670 The form C<$x **= $y> is faster than C<$x = $x ** $y;>, though.
3671
3672 =item Overloading -$x
3673
3674 The following:
3675
3676         $x = -$x;
3677
3678 is slower than
3679
3680         $x->bneg();
3681
3682 since overload calls C<sub($x,0,1);> instead of C<neg($x)>. The first variant
3683 needs to preserve $x since it does not know that it later will get overwritten.
3684 This makes a copy of $x and takes O(N), but $x->bneg() is O(1).
3685
3686 With Copy-On-Write, this issue would be gone, but C-o-W is not implemented
3687 since it is slower for all other things.
3688
3689 =item Mixing different object types
3690
3691 In Perl you will get a floating point value if you do one of the following:
3692
3693         $float = 5.0 + 2;
3694         $float = 2 + 5.0;
3695         $float = 5 / 2;
3696
3697 With overloaded math, only the first two variants will result in a BigFloat:
3698
3699         use Math::BigInt;
3700         use Math::BigFloat;
3701         
3702         $mbf = Math::BigFloat->new(5);
3703         $mbi2 = Math::BigInteger->new(5);
3704         $mbi = Math::BigInteger->new(2);
3705
3706                                         # what actually gets called:
3707         $float = $mbf + $mbi;           # $mbf->badd()
3708         $float = $mbf / $mbi;           # $mbf->bdiv()
3709         $integer = $mbi + $mbf;         # $mbi->badd()
3710         $integer = $mbi2 / $mbi;        # $mbi2->bdiv()
3711         $integer = $mbi2 / $mbf;        # $mbi2->bdiv()
3712
3713 This is because math with overloaded operators follows the first (dominating)
3714 operand, and the operation of that is called and returns thus the result. So,
3715 Math::BigInt::bdiv() will always return a Math::BigInt, regardless whether
3716 the result should be a Math::BigFloat or the second operant is one.
3717
3718 To get a Math::BigFloat you either need to call the operation manually,
3719 make sure the operands are already of the proper type or casted to that type
3720 via Math::BigFloat->new():
3721         
3722         $float = Math::BigFloat->new($mbi2) / $mbi;     # = 2.5
3723
3724 Beware of simple "casting" the entire expression, this would only convert
3725 the already computed result:
3726
3727         $float = Math::BigFloat->new($mbi2 / $mbi);     # = 2.0 thus wrong!
3728
3729 Beware also of the order of more complicated expressions like:
3730
3731         $integer = ($mbi2 + $mbi) / $mbf;               # int / float => int
3732         $integer = $mbi2 / Math::BigFloat->new($mbi);   # ditto
3733
3734 If in doubt, break the expression into simpler terms, or cast all operands
3735 to the desired resulting type.
3736
3737 Scalar values are a bit different, since:
3738         
3739         $float = 2 + $mbf;
3740         $float = $mbf + 2;
3741
3742 will both result in the proper type due to the way the overloaded math works.
3743
3744 This section also applies to other overloaded math packages, like Math::String.
3745
3746 One solution to you problem might be L<autoupgrading|upgrading>.
3747
3748 =item bsqrt()
3749
3750 C<bsqrt()> works only good if the result is a big integer, e.g. the square
3751 root of 144 is 12, but from 12 the square root is 3, regardless of rounding
3752 mode.
3753
3754 If you want a better approximation of the square root, then use:
3755
3756         $x = Math::BigFloat->new(12);
3757         Math::BigFloat->precision(0);
3758         Math::BigFloat->round_mode('even');
3759         print $x->copy->bsqrt(),"\n";           # 4
3760
3761         Math::BigFloat->precision(2);
3762         print $x->bsqrt(),"\n";                 # 3.46
3763         print $x->bsqrt(3),"\n";                # 3.464
3764
3765 =item brsft()
3766
3767 For negative numbers in base see also L<brsft|brsft>.
3768
3769 =back
3770
3771 =head1 LICENSE
3772
3773 This program is free software; you may redistribute it and/or modify it under
3774 the same terms as Perl itself.
3775
3776 =head1 SEE ALSO
3777
3778 L<Math::BigFloat> and L<Math::Big> as well as L<Math::BigInt::BitVect>,
3779 L<Math::BigInt::Pari> and  L<Math::BigInt::GMP>.
3780
3781 The package at
3782 L<http://search.cpan.org/search?mode=module&query=Math%3A%3ABigInt> contains
3783 more documentation including a full version history, testcases, empty
3784 subclass files and benchmarks.
3785
3786 =head1 AUTHORS
3787
3788 Original code by Mark Biggar, overloaded interface by Ilya Zakharevich.
3789 Completely rewritten by Tels http://bloodgate.com in late 2000, 2001.
3790
3791 =cut