
// SPDX-License-Identifier: CC-BY-NC-SA-4.0
//
// Copyright (C) 2026 Bit by Bit Signal Processing LLC (https://bxbsp.com)
//
// This work is placed under the "Creative Commons Attribution
// NonCommercial ShareAlike 4.0 International" license, known
// by the shortened acronym "CC-BY-NC-SA-4.0".
//
// This work 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.
//
// A CC-BY-NC-SA-4.0 license allows you to use this work for
// noncommercial purposes so long as attribution is made to the
// original author.  Modified versions of this work may be distributed,
// but only under the same license.  For further details, see the
// Creative Commons License "CC-BY-NC-SA-4.0".
//
// You should have received a copy of the CC-BY-NC-SA-4.0 license
// along with this work. If not, see
// <https://creativecommons.org/licenses/by-nc-sa/4.0/>.
//

#include "language_support.hh"
#include <stdio.h>

bool use_comma_for_decimal_point = false;

//
// This converts numbers to compact text, keeping in mind whether
// decimal points should be periods or commas in the current setting.
//
// Note that this relies on the current locale being one which has
// printf produce periods as decimal points, rather than commas.
//
void float2text(double f, char* text)
{
  int i;
  char s0[200];
  char s1[200];
  char s2[200];

  sprintf(s0, "%.10g", f);
  sprintf(s1, "%.10f", f);
  sprintf(s2, "%.10e", f);

  //printf("in float2text: string0=\"%s\", string1=\"%s\", string2=\"%s\".\n", s0, s1, s2);

  //
  // Fix s0
  //
  bool has_period = false;
  for(i=0; s0[i]; i++)
    if(s0[i]=='.')
      has_period = true;

  if(has_period)
    {
      for(i--; s0[i]=='0'; i--)
	;
      if(s0[i]=='.')
	i--;
      s0[i+1] = 0;
    }
  
  int s0_length = i;

  //
  // Fix s1
  //
  for(i=0; s1[i]; i++)
    ;
  for(i--; s1[i]=='0'; i--)
    ;
  if(s1[i]=='.')
    i--;
  s1[i+1] = 0;

  int s1_length = i;

  //
  // Fix s2
  //
  int exponent_start = 0;
  for(i=0; s2[i]; i++)
    if(s2[i]=='e')
      exponent_start = i;

  if(exponent_start)
    {
      for(i=exponent_start-1; i>0 && s2[i]=='0' && s2[i-1] != '0'; i--)
	;

      if(s2[i-1]=='.')
	i++;
      
      for(int j=exponent_start; s2[j]!=0; j++)
	s2[i++] = s2[j];
      s2[i--] = 0;
    }
  else
    {
      for(i--; s2[i]=='0'; i--)
	;
      if(s2[i]=='.')
	i--;
      s2[i+1] = 0;
    }
  
  int s2_length = i;

  char* s = ( (s0_length<s1_length) && (s0_length<s2_length) ? s0 :
	      (s1_length<s2_length)                          ? s1 :
	      /**/                                             s2 );

  if(use_comma_for_decimal_point)
    {
      for(i=0;;i++)
	{
	  text[i] = s[i];
	  if(text[i]=='.')
	    text[i]=',';
	  else if(!text[i])
	    break;
	}
    }
  else
    {
      for(i=0;;i++)
	{
	  text[i] = s[i];
	  if(!text[i])
	    break;
	}
    }
}
