#
# Library inspired by the Perl 4 code from base64.pl by A. P. Barrett 
# <barrett@ee.und.ac.za>, October 1993, and subsequent changes by 
# Earl Hood <earl@earlhood.com> to use MIME::Base64 if available.
#

package base64;

my $use_MIMEBase64 = eval { require MIME::Base64; };

sub b64decode
{
    return &MIME::Base64::decode_base64(@_) if $use_MIMEBase64;

    local($^W) = 0;
    use integer; # should be faster and more accurate

    ( my $str = shift ) =~ tr|A-Za-z0-9+=/||cd;
    $str =~ s/=+$//;
    $str =~ tr|A-Za-z0-9+/| -_|; # collapse base64 unto continuous set of chars
                                 # (by convention the uuencode set, for unpack)

    return "" unless $str;
    return unpack("u", join('', map( chr(32 + length($_)*3/4) . $_,
                                $str =~ /(.{1,60})/gs) ) );
}

sub b64encode
{
    return &MIME::Base64::encode_base64(@_) if $use_MIMEBase64;

    local ($_) = shift;
    local($^W) = 0;
    use integer; # should be faster and more accurate
    
    my $result = pack("u", $_[0]);
    $result =~ s/^.//mg;
    $result =~ s/\n//g;

    $result =~ tr| -_|A-Za-z0-9+/|;
    my $padding = (3 - length($_[0]) % 3) % 3;

    $result =~ s/.{$padding}$/'=' x $padding/e if $padding;
    if (length $eol) {
	$result =~ s/(.{1,76})/$1$eol/g;
    }
    return $result;
}

1;
