#!/usr/bin/perl
#
# base27 - converts text to different number bases
# Copyright (C) 1999  Steven E. Hugg (hugg@pobox.com)
# 
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#

use Math::BigInt;
use Getopt::Std;

getopt('C');

$codes = '@ABCDEFGHIJKLMNOPQRSTUVWXYZ';

$reverse = defined($opt_d);
$upper = !defined($opt_u);
if(defined($opt_C)) { $codes = $opt_C; }

$bias = ord(substr($codes, 0, 1));
$qmcodes = quotemeta($codes);

undef $/;
$_ = <>;

$n = new Math::BigInt '0';
$f = new Math::BigInt '1';

if ($reverse)
{
	for ($i=0; $i<length; $i++)
	{
		$n += ord(substr($_, $i, 1))*$f;
		$f *= 256;
	}
	$f = 1;
	while ($n > 0)
	{
		print chr($n % length($codes) + $bias);
		$n /= length($codes);
	} 
} else {
	if ($upper) { $_ = uc $_; }
	s/[^\s$qmcodes]+//gm;
	s/\s+/@/gm;
	s/^\@//m;
	s/\@$//m;
	for ($i=0; $i<length; $i++)
	{
		$n += (ord(substr($_, $i, 1))-$bias)*$f;
		$f *= length($codes);
	}
	while ($n > 0)
	{
		print chr($n % 256);
		$n /= 256;
	} 
}
