unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls, FatExpression;

type
  TFormMain = class(TForm)
    Button1: TButton;
    LogList: TListBox;
    FuncList: TMemo;
    FatExpression1: TFatExpression;
    Label1: TLabel;
    EvalOrder: TComboBox;
    Label2: TLabel;
    Label3: TLabel;
    Label4: TLabel;
    Label5: TLabel;
    ExprEdit: TComboBox;
    procedure FormCreate(Sender: TObject);
    procedure EvalOrderChange(Sender: TObject);
    procedure ExprEditKeyPress(Sender: TObject; var Key: Char);
    procedure Button1Click(Sender: TObject);
    procedure FatExpression1Evaluate(Sender: TObject; Eval: String;
      Args: array of Double; ArgCount: Integer; var Value: Double;
      var Done: Boolean);
  private
    { Private declarations }
    procedure Execute;
  public
    { Public declarations }
    procedure Log(const Msg: String);
  end;

var
  FormMain: TFormMain;

implementation

{$R *.DFM}

procedure TFormMain.Log(const Msg: String);
begin
  LogList.Items.Add(Msg);
  LogList.TopIndex := LogList.Items.Count - 1;
  LogList.ItemIndex := LogList.Items.Count - 1;
end;

procedure TFormMain.FormCreate(Sender: TObject);
begin
  EvalOrder.ItemIndex := 0;
  EvalOrderChange(NIL);
  ExprEdit.ItemIndex := 0;
end;

procedure TFormMain.EvalOrderChange(Sender: TObject);
begin
  if EvalOrder.ItemIndex = 0 then
    FatExpression1.EvaluateOrder := eoInternalFirst else
    FatExpression1.EvaluateOrder := eoEventFirst;
end;

procedure TFormMain.ExprEditKeyPress(Sender: TObject; var Key: Char);
begin
  if Key = #13 then begin
    Execute;
    Key := #0;
  end;
end;

procedure TFormMain.Execute;
var S: String;
begin
  FatExpression1.Functions.Assign(FuncList.Lines);
  S := ExprEdit.Text;
  if (ExprEdit.Items.IndexOf(S) < 0) and (S <> '') then
    ExprEdit.Items.Insert(0, S);
  ExprEdit.Text := '';
  
  FatExpression1.Text := S;
  Log('result=' + FloatToStr(FatExpression1.Value));
end;

procedure TFormMain.Button1Click(Sender: TObject);
begin
  Log('*** evaluating ' + ExprEdit.Text);
  Execute;
end;

procedure TFormMain.FatExpression1Evaluate(Sender: TObject; Eval: String;
  Args: array of Double; ArgCount: Integer; var Value: Double;
  var Done: Boolean);
var S: String;
  I: Integer;
begin
  // this code is used only to display some information
  S := '';
  if ArgCount > 0 then begin
    for I := 0 to ArgCount - 1 do
      S := S + ' ' + FloatToStr(Args[I]);
    Delete(S, 1, 1);
  end;

  Log(Format('eval %s (%d) [ %s ]', [Eval, ArgCount, S]));

  Done := True;
  // here we handle the "Pi" function
  if UpperCase(Eval) = 'PI' then Value := Pi else
  // here we handle the "Add" function, whichs adds together any number of parameters
  if UpperCase(Eval) = 'ADD' then begin
    for I := 0 to ArgCount - 1 do
      Value := Value + Args[I];
  end else
  Done := False;
end;

end.





