' ******************************************************************
' Plotting routines : plot function
' ******************************************************************

' ------------------------------------------------------------------
' Constants
' ------------------------------------------------------------------

#DEFINE LinScale 0
' Linear scale

#DEFINE LogScale 1
' Logarithmic scale

' ------------------------------------------------------------------
' Global variables
' ------------------------------------------------------------------

COMMON SHARED AS INTEGER XminPixel, XmaxPixel
' Window coordinates in pixels
'
COMMON SHARED AS DOUBLE Xmin, Xmax
' Window coordinates in user units

COMMON SHARED AS INTEGER XScale, YScale
' Axis scales

' ------------------------------------------------------------------
' External functions
' ------------------------------------------------------------------

DECLARE FUNCTION MathErr() AS INTEGER
' Returns the error code from the last procedure call

DECLARE FUNCTION Exp10(X AS DOUBLE) AS DOUBLE
' 10^X

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

DECLARE FUNCTION Xpixel(X AS DOUBLE) AS INTEGER
' Converts user abscissa X to screen coordinate

DECLARE FUNCTION Ypixel(X AS DOUBLE) AS INTEGER
' Converts user ordinate Y to screen coordinate

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

SUB PlotFunc(Func AS FUNCTION(X AS DOUBLE) AS DOUBLE)
' ------------------------------------------------------------------
' Plots a function
' ------------------------------------------------------------------

  DIM AS DOUBLE  X, Y, H
  DIM AS INTEGER I, Npt, Xp, Yp

  ' Nb of points to be plotted = number of pixels on Ox
  Npt = XmaxPixel - XminPixel

  H = (Xmax - Xmin) / Npt
  
  FOR I = 0 TO Npt
    X = Xmin + I * H
    IF XScale = LinScale THEN Y = Func(X) ELSE Y = Func(Exp10(X))
    IF MathErr = 0 THEN
      IF YScale = LogScale THEN Y = Log10(Y)
      Xp = Xpixel(X)
      Yp = Ypixel(Y)
      IF I = 0 THEN PSET (Xp, Yp) ELSE LINE -(Xp, Yp)
    END IF
  NEXT I
END SUB
