/*
**  DataPlot v1.00
**  Written by Stefan Zeiger of ! Wizard Works ! in 10/1991
**  PUBLIC DOMAIN.
*/


/************************************************************ INCLUDE FILES */

#include <exec/types.h>
#include <math.h>
#include <stdio.h>
#include <proto/tool.h>


/**************************************************** DECLARE OUR FUNCTIONS */

void cleanup(UBYTE *,int);


/************************************************************* LIBRARY BASE */

struct ToolBase *ToolBase=NULL;


/********************************************************* GLOBAL VARIABLES */

APTR Konstanten=NULL;
struct Block *Funktion=NULL;


/************************************************************ MAIN FUNCTION */

void main(int argc,char **argv)
{
  ULONG i;
  double zero=0.0,xval,yval,xmin,xmax,step;

  if(argc!=5) cleanup("Usage: DataPlot >file function xmin xmax step",10);

  ToolBase=(struct ToolBase *)OpenLibrary("tool.library",0L);
  if(!ToolBase) cleanup("Can't open TOOL.LIBRARY.",10);

  Konstanten=Init_Konst();
  if(!Konstanten) cleanup("Can't allocate memory for constants.",10);
  for(i=0;i<26;i++) Set_Konst_P(Konstanten,i,&zero);

  Funktion=Init_Mem(argv[1]);
  if(!Funktion) cleanup("Can't allocate memory for function.",10);
  if(Init_Block(Funktion)) cleanup("Illegal function.",10);
  if(PreCalc(Funktion,Konstanten)) cleanup("Error in function.",10);

  fprintf(stdout,"*LEGEND* y=%s\n\n",argv[1]);

  sscanf(argv[2],"%lf",&xmin);
  sscanf(argv[3],"%lf",&xmax);
  sscanf(argv[4],"%lf",&step);

  for(xval=xmin;xval<=xmax;xval+=step)
  {
    if(Calc_P(&yval,Funktion,&xval)) fprintf(stderr,"Error at x=%lf.\n",xval);
    else fprintf(stdout,"%lf %lf \n",xval,yval);
  }

  fprintf(stdout,"\n");

  cleanup("Finished.",0);
}


/***************************************************************** CLEAN UP */

void cleanup(UBYTE *cltext,int excode)
{
  if(Funktion) Free_Block(Funktion);
  if(Konstanten) Free_Konst(Konstanten);
  if(ToolBase) CloseLibrary((struct Library *)ToolBase);
  fprintf(stderr,"%s\n",cltext);
  exit(excode);
}
