/*
 * hexavigesimal.cpp
 *
 * Created on: 19. 4. 2014
 * Author: Tomas Pecka
 */

#include "hexavigesimal.h"
#include <stdexcept>

namespace ext {

namespace {
	static const int BASE26 = 26;
}

unsigned fromBase26( const std::string & rep ) {
	unsigned n = 0;
	for ( char repSymbol : rep ) {
		unsigned remainder = repSymbol - 'A';
		if(remainder > BASE26)
			throw std::invalid_argument(rep);
		n = n * BASE26 + remainder;
	}

	return n;
}

std::string toBase26( unsigned n ) {
	std::string name;
	do {
		name += ( char )( n % BASE26 + 'A' );
		n = n / BASE26;
	} while (n > 0);

	return std::string( name.rbegin( ), name.rend( ) );
}

unsigned bijectiveFromBase26 ( const std::string & rep ) {
	unsigned n = 0;
	for ( char repSymbol : rep ) {
		unsigned remainder = repSymbol - 'A';
		if(remainder > BASE26)
			throw std::invalid_argument(rep);
		n = n * BASE26 + remainder + 1;
	}
	return n;
}

std::string bijectiveToBase26(unsigned n) {
	std::string name;
	while(n > 0) {
		--n;
		name += (char) (n % BASE26 + 'A');
		n /= BASE26;
	}
	return std::string(name.rbegin(), name.rend());
}

} /* namespace ext */
