/*-- Rev Header - do NOT edit!
 *
 *  Filename : CED_Support.c
 *  Purpose  : Einige Hilfsroutinen für CED
 *
 *  Program  : -
 *  Author   : Gerhard Müller
 *  Copyright: (c) by Gerhard Müller
 *  Creation : Fri Sep 10 00:41:01 1993
 *
 *  compile  : makefile
 *
 *  Compile version  : 0.1
 *  Ext. Version     : 0.1
 *
 *  REVISION HISTORY
 *
 *  Date                     Comment
 *  ------------------------ -------------------------------------------------
 *  Fri Sep 17 00:51:36 1993 seems to work
 *
 *
 *
 *-- REV_END --
 */

extern "C" {
#include <exec/types.h>
}
	/*
	 * Diese Funktion wandelt eine Zahl in einen ascii-String.
	 * Besonderheiten:
	 *
	 * 1) nur ganze Zahlen (bis LONG/ULONG)
	 * 2) beliebige Basis (2-36)
	 * 3) Länge des Buffers
	 * 4) signed/unsigned
	 * 5) groß/kleinbuchstaben
	 *
	 *
	 * Ergebnis: Zeiger auf Buffer (ok) oder 0 bei Fehler (Bufferüberlauf etc.)
	 *
	 */


	/*
	 * This function makes an ascii-string out of a long.
	 * Some things to mention
	 *
	 * 1) only LONG/ULONGs are supported (yet)
	 * 2) basis is selectable from 2 to 36
	 * 3) length of buffer is noticed
	 * 4) signed/unsigned
	 * 5) upper/down case letters
	 *
	 *
	 * Result: pointer to buffer (ok) or 0 if any error occurred (buffer-overflow etc.)
	 *
	 */

//           Your LONG   Buffer      Buffer-len    default=down         default base=10   default signed
char *ltostr(LONG tzahl, char *dest, ULONG BufLen, BOOL Uppercase=FALSE,ULONG base=10, BOOL unsigned_zahl=FALSE)
{
	BOOL ok=TRUE;
	char *s=dest;
	ULONG digit;
	ULONG zahl;
	BOOL minus=FALSE;

	/* Lower-case digits.  */
	static const char lower_digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
	/* Upper-case digits.  */
	static const char upper_digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	/* Base-36 digits for numbers.  */

	const char *digits;

	if(Uppercase)
		digits = upper_digits;
	else
		digits = lower_digits;


	// test arguements

	if(base<2 || base >36) return NULL;
	if(BufLen < 2) return NULL;
	if(dest==NULL) return NULL;


	// Minus ?

	if(unsigned_zahl)
	{
		zahl=tzahl;
	}
	else
	{
		if(tzahl < 0)
		{
			minus=TRUE;
			zahl=-tzahl;
		}
		else
			zahl=tzahl;
	}

	if(zahl==0) { *s='0'; s++; *s=0; return dest;}
	else
	{
		while(zahl && ok)
		{
			digit=zahl%base;
			*s++=digits[digit];
			zahl/=base;

			if( (s-dest) >= (BufLen-1) ) ok=FALSE;	// string nicht zu lang werden lassen
		}
	}

	if(ok)
	{

		if(minus) *s++='-';
		if( (s-dest) <= (BufLen-1) )
		{
			*s=0;	// String 0 terminieren

			int len=s-dest;
			s--;

			// string umdrehen
			char temp;
			int x;

			for(x = 0 ; x < (len/2); x++)
			{
				temp=dest[x];
				dest[x]=s[-x];
				s[-x]=temp;
			}
		}
		else return NULL;
	}
	else return NULL;

	// alles ok
	return(dest);
}
