// testrp4.cpp  
// Copyright (c) Menno Rubingh 2016.  Web: [http://rubinghsoftware.de]
//
// MR Mar 2016.
// 
// Test of the RPInterpreter class.
// 
//---
// Uses:
//    rpinterpreter.h      -- RPInterpreter.
//    rpinterpreter.a      -- Static library containing RPInterpreter implementation.
//
//
//---
// Build:
//    g++  -Wall -ggdb  -o testrp4  testrp4.cpp  rpinterpreter.a  -lm
//


#include "rpinterpreter.h"  //RPInterpreter.

#include <stdio.h>
#include <fenv.h>           //feclearexcept(), fetestexcept().



//-------------------------------------------------------------------------------------
// MAIN:
// - Read RP expression string from cmd line;
// - Evaluate the expression on variables with hardcoded input values;
// - After evaluation, print all variable values.
//-------------------------------------------------------------------------------------

void usage()
{
	fprintf( stderr, 
	  "Usage: testrp4 'RPEXPRESSION'\n" 
	  "Note: Put RPEXPRESSION between single quotes to prevent shell expansion.\n" 
	);

	fprintf( stderr, "\n%s\n", 
		RPInterpreter::helptxt() );
}

int main( int argc, char ** argv )
{
	if ( argc < 2 ) { usage(); return -1; }
	char const * arg_expr = argv[1];

	printf( "expr = [%s]\n", arg_expr );



	// Parse the expression.

	RPInterpreter rp;

	if ( ! rp.scanFromString( arg_expr ) ) { return -1; }
	rp.dump( stdout );



	// Evaluate the expression, on variables with hardcoded initial values.
	// All variables left at initial value zero, except 'a', 'b', 'c'.

	rp.putVar( 'a', 0.2 );
	rp.putVar( 'b', 1.3 );
	rp.putVar( 'c', 2.5 );

	feclearexcept( FE_ALL_EXCEPT );

	rp.evaluate();

	if ( fetestexcept( FE_INVALID ) )
	{
		printf( "Runtime DomainError\n" );
	}


	// Print all the variables (compactly, in three columns).

	int NCOL = 3;
	int NROW = (26+2)/NCOL;
	for ( int kRow = 0; kRow < NROW; kRow++ )
	{
		for ( int kCol = 0; kCol < NCOL; kCol++ )
		{
			char c = 'a' + kCol*NROW + kRow;
			printf( "     |     " );
			if ( c <= 'z' ) 
			{
				double val;
				bool   f = rp.getVar( c, &val );

				printf( "%c = %10g%s", 
					c, 
					val,
					( f ? "      " : "(EDOM)" ) );
					//     012345     012345
			}
		}
		printf( "\n" ); 
	}

	

	return 0;
}