// Copyright, 2001-2003, Astra Network Inc.  All Rights Reserved

// This source code has been published by Astra Network Inc. However, any
// use, reproduction, modification, distribution or transfer of this
// software, or any software which includes or is based upon any of this
// code, is only permitted if expressly authorized by a written license
// agreement from Astra. Contact your Astra representative directly for
// more information.


#include "sixfourbit.h"
// include space for sign and null terminator
// based on LLONG_MIN of -9223372036854775807 (20 chars)
// and      ULLONG_MAX of 18446744073709551615 (20 chars)

#include <stdio.h>
#include <string.h>
#include <ctype.h>

___quad_t
quad_strtoq (char *str)
{
  ___quad_t r = quad_ltoq (0);
  char *p = str;
  int neg = 0;

  if (*p == '-')
    {
      neg++;
      p++;
    }
  while (isdigit (*p))
    {
      ___quad_t d;
      r = quad_mul (r, quad_ltoq (10));
      d = quad_ltoq (*p - 0x30);
      r = quad_add (r, d);
      p++;
    }

  return neg ? quad_neg (r) : r;
}

char *
QTOSTR (quad_t a)
{
  static char buf[QUAD_STR_SIZE];

  return QTOSTRBUF (a, buf);
}

char *
quad_qtostrbuf (quad_t a, char *buf)
{
  quad_t zero = LTOQ (0);
  char *result;
  char *p, *q;;

  result = buf;
  p = result;
  if (QLT (a, zero))
    {
      a = QNEG (a);
      *p = '-';
      p++;
    }

  q = p;
  while (!QEQ (a, zero))
    {
      int64_t r = QMOD (a, LTOQ (10));
      *p = 0x30 + QTOL (r);
      a = QDIV (a, LTOQ (10));
      p++;
    }

  if (q == p)			// printing a zero
    {
      *p = '0';
      p++;
    }

  *p = '\0';
  p--;
  while (p > q)
    {
      char t;
      t = *p;
      *p = *q;
      *q = t;
      p--;
      q++;
    }
  return result;
}
