/*
  Maze editor: utility functions
  Copyright (C) 1998 by Jorrit Tyberghein
  Written by Andrew Zabolotny <bit@eltech.ru>

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Library General Public
  License as published by the Free Software Foundation; either
  version 2 of the License, or (at your option) any later version.

  This library 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
  Library General Public License for more details.

  You should have received a copy of the GNU Library General Public
  License along with this library; if not, write to the Free
  Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include <math.h>
#include <stdio.h>
#include "sysdef.h"
#include "cssys/common/system.h"

void ftoa (char *dest, float f)
{
  float val = fabs (f);
  float epsilon;
  if (val < 0.001)
    epsilon = 0.0000001;
  else if (val < 0.01)
    epsilon = 0.000001;
  else if (val < 0.1)
    epsilon = 0.00001;
  else if (val < 1)
    epsilon = 0.0001;
  else if (val < 10)
    epsilon = 0.001;
  else if (val < 100)
    epsilon = 0.01;
  else
    epsilon = 0.1;

  int digits;
  for (digits = 0; digits < 16; digits++, val *= 10)
  {
    if ((val - floor (val) < epsilon)
     || (val - floor (val) > 1 - epsilon))
      break;
  }
  char format[10];
  sprintf (format, "%%.%df", digits);
  sprintf (dest, format, f);
  int sl = strlen (dest);
  while (sl
      && ((dest [sl - 1] == '0')
       || (dest [sl - 1] == '.')
       || (dest [sl - 1] == '-')))
    dest [--sl] = 0;
  if (!sl)
    dest [0] = '0';
}

void ftoalp (char *dest, float f)
{
  float val = fabs (f);
  int digits;
  if (val < 0.001)
    digits = 5;
  else if (val < 0.01)
    digits = 4;
  else if (val < 0.1)
    digits = 3;
  else if (val < 1)
    digits = 2;
  else if (val < 10)
    digits = 1;
  else
    digits = 0;

  char format[10];
  sprintf (format, "%%.%df", digits);
  sprintf (dest, format, f);
  int sl = strlen (dest);
  while (sl
      && ((dest [sl - 1] == '0')
       || (dest [sl - 1] == '.')
       || (dest [sl - 1] == '-')))
    dest [--sl] = 0;
  if (!sl)
    dest [0] = '0';
}
