/*
   Tools.c, Copyright  (c) by Lukas Ruf, lr@lpr.ch,
   Swiss Federal Institute of Technology,
   Computer Engineering and Networks Laboratory.
 
   TOPSY -- A Teachable Operating System.
            Implementation of a tiny and simple
            micro kernel for teaching purposes.
 
   For further information, please visit http://www.tik.ee.ethz.ch/~topsy
 
   This software is provided under the terms of the GNU General Public Licence.
 
   A full copy of the GNU GPL is provided in the file COPYING found in the 
   development root of Topsy.
 */
/*
	
	File:                  $Source: /home/ruf/cvs_Topsy/cvs/Topsy/Topsy/ia32/Tools.c,v $
	Author(s):             Lukas Ruf, lr@lpr.ch
	Affiliation:           ETH Zuerich, TIK
	Version:               $Revision: 2936 $
	Creation Date:         
	Last Date of Change:   $Date: 2007-03-21 15:23:42 +0100 (Mit, 21 Mär 2007) $      by: $Author: baderma $
*/

#include "Support.h"

static char sign(int pi)
{
  char xret = 0;
  if (pi < 0)
    xret = -1;
  if (pi > 0)
    xret =  1;
  return xret;
}

void itoa(int pi, char *pstr)
{
  char tmp[17];
  int ti = pi * sign(pi);
  int di = 10, i = 0, j = 0;
  if (ti > 0)
    while (((i < 11) && (ti)) || (i==0))
    {
      tmp[i++] = ti % di + '0';
      ti /= di;
    }
  else
    tmp[i++] = '0';
  i--;
  if (pi < 0)
    pstr[j++] = '-';
  for (; i >= 0; i--)
    pstr[j++] = tmp[i];
  pstr[j] = 0;
  return;
}

void itoal(int pi, char *pstr, unsigned char plength)
{
  int i = 0;
  itoa(pi,pstr);
  i = str_len(pstr);
  if (plength > i)
  {
    pstr[plength] = 0;
    for (;(plength > 0);)
    {
      pstr[--plength] = ' ';
      if (i > 0)
        pstr[plength] = pstr[--i];
    }
  }
  return;
}

void itoah(int pi, char *pstr)
{
  char hex[0x11] = "0123456789ABCDEF";
  char tmp[11];
  int i = 0, j = 0;
  if (pi > 0)
    while (pi > 0)
    {
      tmp[i++] = hex[pi % 0x10];
      pi = pi >> 4;
    }
  else
    tmp[i++] = '0';
  tmp[i] = 0;
  for (;(i);)
    pstr[j++] = tmp[--i];
  pstr[j] = 0;
  return;
}

void itoahl(int pi, char *pstr, unsigned char plength)
{
  int i = 0;
  itoah(pi,pstr);
  i = str_len(pstr);
  if (plength > i)
  {
    pstr[plength] = 0;
    for (;(plength > 0);)
    {
      pstr[--plength] = '0';
      if (i > 0)
        pstr[plength] = pstr[--i];
    }
  }
  return;
}

/* expect at least ps[9] = '\0' */
void itob(char b, char *ps)
{
  int i = 0;
  char c = 1;
  for (i = 0; i < 8; i++)
    ps[i] = '0';
  if (ps)
    for (i = 7; (i >= 0); i--)
    {
      ps[i] = '0';
      if (b & c)
        ps[i] = '1';
      c *= 2;
    }
  ps[8] = 0;
}

int BCDtoBIN(int pBCD)
{
  int xret = 0, xmul = 1;
  while (pBCD)
  {
    xret += (pBCD & 0xF) * xmul;
    xmul *= 10;
    pBCD  = pBCD >> 4;
  }
  return xret;
}

