' ******************************************************************
' Compute an appropriate interval for a set of values
' ******************************************************************

' ------------------------------------------------------------------
' External function
' ------------------------------------------------------------------

DECLARE FUNCTION Log10(X AS DOUBLE) AS DOUBLE
' Decimal logarithm

' ******************************************************************

SUB Interval(      X1     AS DOUBLE,  _
                   X2     AS DOUBLE,  _
                   MinSub AS INTEGER, _
                   MaxSub AS INTEGER, _
             BYREF XMin   AS DOUBLE,  _
             BYREF XMax   AS DOUBLE,  _
             BYREF XStep  AS DOUBLE)
' ------------------------------------------------------------------
' Determines an interval [XMin, XMax] including the values from X1
' to X2, and a subdivision XStep of this interval
' ------------------------------------------------------------------
' Input parameters  : X1, X2 = range of values to be included
'                     MinSub = minimum nb of subdivisions
'                     MaxSub = maximum nb of subdivisions
' Output parameters : XMin, XMax, XStep
' ------------------------------------------------------------------

  IF X1 >= X2 THEN EXIT SUB

  DIM AS DOUBLE  H 
  DIM AS INTEGER K, N

  H = X2 - X1
  N = INT(Log10(H))
  IF H < 1 THEN N = N - 1
  XStep = 10 ^ N

  DO
    K = INT(H / XStep)
    IF K < MinSub THEN XStep = .5 * XStep
    IF K > MaxSub THEN XStep = 2 * XStep
  LOOP UNTIL K >= MinSub AND K <= MaxSub

  XMin = XStep * INT(X1 / XStep)
  XMax = XStep * INT(X2 / XStep)

  WHILE XMin > X1: XMin = XMin - XStep: WEND
  WHILE XMax < X2: XMax = XMax + XStep: WEND
END SUB
