' ******************************************************************
' Plotting routines : write legends
' ******************************************************************

' ------------------------------------------------------------------
' Type definition
' ------------------------------------------------------------------

TYPE TCurvParam         ' Curve plot parameters
  Col     AS INTEGER    ' Color
  Symbol  AS INTEGER    ' Point type
  Size    AS INTEGER    ' Point size
  Connect AS INTEGER    ' Points connected ?
  Text    AS STRING*20  ' Curve legend
END TYPE

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

COMMON SHARED AS INTEGER CharWidth, CharHeight
' Character Width and Height (pixels)

COMMON SHARED AS INTEGER XmaxPixel, YminPixel
' Window coordinates in pixels

COMMON SHARED AS INTEGER FgCol, BgCol
' Save foreground and background colors

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

DECLARE SUB PlotPoint(X      AS INTEGER, _
                      Y      AS INTEGER, _
                      Symbol AS INTEGER = 1, _
                      Size   AS INTEGER = 2)
' Plots a point

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

SUB WriteLegend(CurvParam() AS TCurvParam)

  DIM AS INTEGER I, L, Lb, Ub, LongMax, N, X1, X2, Y1, Y2, DY
  DIM AS STRING  S

  Lb = LBOUND(CurvParam)
  Ub = UBOUND(CurvParam)
  
  N = 0            ' Number of legends
  LongMax = 0      ' Length of longest string

  FOR I = Lb TO Ub
    S = TRIM$(CurvParam(I).Text)
    IF S <> "" THEN
      N = N + 1
      L = LEN(S)
      IF L > LongMax THEN LongMax = L
    END IF
  NEXT I

  IF N = 0 THEN EXIT SUB

  X1 = XmaxPixel + 2 * CharWidth  ' Border coordinates
  X2 = X1 + (LongMax + 5) * CharWidth
  Y1 = YminPixel
  Y2 = Y1 + (1.5 * N + 0.5) * CharHeight

  COLOR FgCol, BgCol
  LINE (X1, Y1)-(X2, Y2), , B     ' Draw border

  X1 = XmaxPixel + 4 * CharWidth
  X2 = X1 + 2 * CharWidth
  Y1 = YminPixel + CharHeight
  Y2 = YminPixel + 0.5 * CharHeight
  DY = 1.5 * CharHeight

  FOR I = Lb TO Ub
    WITH CurvParam(I)
      IF TRIM$(.Text) <> "" THEN
        COLOR .Col
        PlotPoint X1, Y1, .Symbol, .Size   ' Draw symbol
        DRAW STRING (X2, Y2), .Text, .Col  ' Write legend
        Y1 = Y1 + DY
        Y2 = Y2 + DY
      END IF
    END WITH
  NEXT I
END SUB
