' ******************************************************************
' String functions
' ******************************************************************

#include "string.bi"

FUNCTION FloatToStr(X    AS DOUBLE,       _
                    Ntot AS INTEGER = 10, _
                    Ndec AS INTEGER = 4,  _
                    E    AS INTEGER = 0) AS STRING
' ------------------------------------------------------------------
' Converts a floating point number to a string with Ntot characters 
' and Ndec decimal places. E = True for exponential notation
' ------------------------------------------------------------------

  DIM AS INTEGER I
  DIM AS STRING  S

  IF Ndec = 0 THEN
    IF E THEN
      S = Format(X, "0E+000")
    ELSE
      S = Format(X, "0")
    END IF  
  ELSE
    S = "0." + STRING$(Ndec, "0")
    IF E THEN
      S = Format(X, S + "0E+000")
    ELSEIF ABS(X) >= 10^(- Ndec) THEN
      S = Format(X, S)
    END IF  
  END IF
  
  ' Replace comma by point if necessary
  I = INSTR(S, ",") : IF I > 0 THEN MID$(S, I, 1) = "."

  ' Add leading spaces
  I = LEN(S) : IF I < Ntot THEN S = SPACE$(Ntot - I) + S

  FloatToStr = S
END FUNCTION

FUNCTION RemZero(S AS STRING) AS STRING
' ------------------------------------------------------------------
' Remove non-significant zeroes
' ------------------------------------------------------------------

  DIM AS INTEGER  I
  DIM AS STRING   S1, S2
  DIM AS STRING*1 C

  I = INSTR(S, ".")

  IF I = 0 THEN 
    RemZero = S
    EXIT FUNCTION
  END IF

  I = INSTR(S, "E") : IF I = 0 THEN I = INSTR(S, "e")

  IF I > 0 THEN 
    S1 = LEFT$(S, I - 1)  
    S2 = RIGHT$(S, LEN(S) - I + 1)
  ELSE
    S1 = S
    S2 = ""
  END IF

  DO
    I = LEN(S1)
    C = MID$(S1, I, 1)
    IF C = "0" OR C = "." THEN S1 = LEFT$(S1, I - 1)
  LOOP UNTIL C <> "0"  
  
  RemZero = S1 + S2
END FUNCTION
