/* This file is part of cardwords
   (c) 1999 Tobias Peters
   see file COPYING for the copyright terms.
   
   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
*/

// cardwords_stringconverters.cc

#include "cardwords_stringconverters.hh"
#include <stdlib.h>
#include <strstream.h>
#include "cardwords_gettext.hh"
#include "cardwords_exceptions.hh"

unsigned
string2unsigned(const string & s)
{
  return strtoul(s.c_str(), 0, 10);
}

string
unsigned2string(unsigned u,
		CardWords_StringConverterFlags f = CSC_DEFAULT,
		size_t length = 0)
{
  ostrstream ostr;
  ostr << u << ends;
  ostr.freeze(true);
  string s(ostr.str());
  ostr.freeze(false);

  if (f & (CSC_STRICT_SIZE | CSC_MINIMUM_SIZE) != 0
      &&
      s.length() < length) {
    return (string(length - s.length(),
		   f & CSC_LEADING_ZEROES != 0 ? '0' : ' ')
	    + s
	    );
  }
  if (f & CSC_STRICT_SIZE != 0
      &&
      s.length() != length) {
    assert (s.length() > length);
    ostrstream error_message;
    error_message << gettext("Number ")
		  << u
		  << gettext(" was too large to  be displayed within ")
		  << length
		  << gettext(" digits.")
		  << ends;
    error_message.freeze(true);
    CardWords_XOutOfRange exception(error_message.str());
    error_message.freeze(false);
    throw exception;
  }
  return s;
}

string
int2string(int i,
           CardWords_StringConverterFlags f = CSC_DEFAULT,
           size_t length = 0)
{
  if (i >= 0) {
    return unsigned2string((unsigned) i, f, length);
  }
  
  // !!! i < 0
  // We will create a positive number with width length-1.
  // So, if the length is important, assert that it is not 0 now:
  if (length == 0 && (f & (CSC_STRICT_SIZE | CSC_MINIMUM_SIZE)) != 0) {
    ostrstream error_message;
    error_message << gettext("Number ")
		  << i
		  << gettext(" was too large to  be displayed within ")
		  << length
		  << gettext(" digits.")
		  << ends;
    error_message.freeze(true);
    CardWords_XOutOfRange exception(error_message.str());
    error_message.freeze(false);
    throw exception;
  }
    
  string s = unsigned2string((unsigned) (-i), f, length - 1);

  s.insert(s.find_first_not_of(' '), "-");

  return s;
}
  
