/*******************************************************************************
Copyright (c) 2010 Tecella LLC
Licensed under the MIT License
*******************************************************************************/

#include "tc_utility_shared.h"

namespace tcu
{

static double tcu_abs(double v)
{
	if(v>0) { return v; }
	return -v;
}

//Does a dumb copy from a std::wstring to a std::string
std::string wstr2str(const std::wstring &src) {
	return std::string( src.begin(), src.end() );
}

//structure to represent metric bases and conversions
MetricBase::MetricBase(double base, std::string prefix)
 : base(base), prefix(prefix)
{}

MetricBase MetricBase::bestBase(double n)
{
	typedef MetricBase mb;

	n = tcu_abs(n);

	if( n==0 ) {
		return mb(1,"");
	}

	if( n >= 1e3 )
	{
		if     ( n<=1e6  ) { return mb(1e3,  "k"); }
		else if( n<=1e9  ) { return mb(1e6,  "M"); }
		else if( n<=1e12 ) { return mb(1e9,  "G"); }
		else if( n<=1e15 ) { return mb(1e12, "T"); }
		else if( n<=1e18 ) { return mb(1e15, "P"); }
		else if( n<=1e21 ) { return mb(1e18, "E"); }
		else if( n<=1e24 ) { return mb(1e21, "Z"); }
		else               { return mb(1e24, "Y"); }
	}

	if( n < 1  )
	{
		if     ( n>=1e-3  ) { return mb(1e-3,  "m"); }
		else if( n>=1e-6  ) { return mb(1e-6,  "u"); }
		else if( n>=1e-9  ) { return mb(1e-9,  "n"); }
		else if( n>=1e-12 ) { return mb(1e-12, "p"); }
		else if( n>=1e-15 ) { return mb(1e-15, "f"); }
		else if( n>=1e-18 ) { return mb(1e-18, "a"); }
		else if( n>=1e-21 ) { return mb(1e-21, "z"); }
		else               { return mb(1e-24, "y"); }
	}

	return mb(1, "");
}

}
