/*
 * Copyright (c) 2011, Robert E. Cousins
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the <organization> nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * $Id: exp.c,v 1.3 2011/09/06 22:08:19 rec Exp $
 */
#include <stdio.h>
#include <stdlib.h>
#include <err.h>
#include <math.h>
#include <string.h>
#include "exp.h"

#define STACK_SIZE (1<<6)

typedef enum {
  tok_unknown, 
  tok_number, 
  tok_uminus, 
  tok_variable, 
  tok_const, 
  tok_function, 
  tok_operator,
  tok_lparen, 
  tok_comma, 
  tok_rparen, 
  tok_end
} Tokens;

typedef struct symbol_table_node SymbolTableNode, *SymbolTableNodePtr;

struct symbol_table_node {
  char ch;			/* character to match */
  char terminal;		/* 0 = no, 1 = yes */
  char token;			/* see Tokens above */
  char args;			/* number of args if function or operator */
  char precidence;		/* if an operator */
  char right_associative;	/* if an operator */
  int len;			/* length of string (or 0) */
  double (*func)();		/* function pointer */
  void (*op)();			/* operator pointer */
  char *string;			/* the string (if present) */
  SymbolTableNodePtr sibling,child; /* other pointers */
  double value;			/* value */
};

static void my_add(), my_sub(), my_mul(), my_div(), my_mod(), my_pow(), my_neg();
/*
 * Basic operators
 */
static struct {
  char *name;
  int args;
  int prec;
  int right;
  void (*f)();
} priv_ops[] = { 
  {"+", 2, 2, 0, my_add },
  {"-", 2, 2, 0, my_sub },
  {"*", 2, 3, 0, my_mul },
  {"/", 2, 3, 0, my_div },
  {"%", 2, 3, 0, my_mod },
  {"^", 2, 4, 1, my_pow },
  {"**",2, 4, 1, my_pow },
  //  {"_", 1, 5, 0, my_neg }
};

/*
 * Basic constants
 */
static struct {
  char *name;
  double value;
} priv_const[] = { 
  //  { "PI", M_PI },
  //  { "e", M_E }
};
/*
 * Basic variables
 */
static struct {
  char *name;
  double value;
} priv_vars[] = { 
  //  { "a", 3.0},
};
/*
 * Basic Use callable functions
 */
static struct {
  char *name;
  int args;
  double (*f)();
} priv_funs[] = {
  { "sin", 1, sin },
  { "cos", 1, cos },
  { "tan", 1, tan },
  { "pow", 2, pow },
  { "log", 1, log },
  { "exp", 1, exp },
};

static SymbolTableNodePtr root;
static  SymbolTableNodePtr uminus;
static double nstack[STACK_SIZE];
static SymbolTableNodePtr ostack[STACK_SIZE];
int nsp, osp;

static char *tok_names[] = {
  "tok_unknown",
  "tok_number",
  "tok_uminus",
  "tok_variable",
  "tok_const",
  "tok_function",
  "tok_operator",
  "tok_lparen",
  "tok_comma",
  "tok_rparen",
  "tok_end"
};

/*
 * Stack operations (don't make static or user can't add operators)
 */
void
exp_num_push(double t)
{
  nstack[nsp++] = t;
  if (nsp >= STACK_SIZE)
    errx(1,"Numeric stack overflow.");
}

double
exp_num_pop()
{
  if (nsp < 1)
    errx(1,"numeric stack underflow");
  return nstack[--nsp];
}

static void
op_push(SymbolTableNodePtr t)
{
  ostack[osp++] = t;
  if (osp >= STACK_SIZE)
    errx(1,"Operand stack overflow.");
}
/*
 * Symbol Table operations
 */
static void
symbol_table_free_node(SymbolTableNodePtr p)
{
  if (p == NULL) 
    return;
  symbol_table_free_node(p->sibling);
  symbol_table_free_node(p->child);

  if (p->string) 
    free(p->string);
  free(p);
}

static void
symbol_table_destroy()
{
  symbol_table_free_node(root);
  root = NULL;
}

static SymbolTableNodePtr
symbol_table_search_siblings(SymbolTableNodePtr p, char ch)
{
  if (p == NULL) 
    return NULL;
  for (; p; p = p->sibling)
    if (p->ch == ch) return p;
  return NULL;
}

static SymbolTableNodePtr
symbol_table_new_node(char ch)
{
  SymbolTableNodePtr t;

  if ((t = malloc(sizeof(*t))) == NULL) 
    err(1,"Can't allocate a new node.");
  memset(t, 0, sizeof(*t));	/* clear it to zeros */
  t->ch = ch;
  t->sibling = t->child = NULL;
  t->terminal = 0;
  return t;
}

static SymbolTableNodePtr
symbol_table_add_string(char *str)
{
  SymbolTableNodePtr *q = &root;
  SymbolTableNodePtr t,p = *q;
  char *last = str;
  char *orig = str;

  while (1) {
    t = symbol_table_search_siblings(*q,*str);
    if (t == NULL) {
      t = symbol_table_new_node(*str);
      t->sibling = *q;
      *q = t;
    }
    q = &t->child;
    last = str++;
    if (*str == '\0') {
      t->terminal = 1;
      t->string = strdup(orig);
      t->len = strlen(orig);
      return t;
    }
  }
}

static SymbolTableNodePtr
symbol_table_lookup_string(char *str)
{
  SymbolTableNodePtr last,q,p = root;

  last = NULL;
  while (1) {
    q = symbol_table_search_siblings(p,*str);
    if (q == NULL) 
      return last;
    if (q->terminal) last = q;
    str++;
    if (*str == '\0') 
      return last;
    p = q->child;
  }
}

static void
exp_dump_symboltable_r(SymbolTableNodePtr p, int level)
{
  int i;
  SymbolTableNodePtr q;
  if (p == NULL) return;


  for (i = 1; i < level; i++)   
    printf("   ");
  printf("+--");
  printf("| %c ", p->ch);
  if (p->terminal) printf("<-Terminal");
  printf("\n");
  exp_dump_symboltable_r(p->child, level+1);
  exp_dump_symboltable_r(p->sibling, level);
}

void
exp_dump_symboltable()
{
  printf("Tree dump:\n");
  exp_dump_symboltable_r(root, 1);
  printf("End of dump\n");
}

void *
exp_add_operator(char *name,	/* name of operator */
		 int args,	/* number of arguments */
		 int prec,	/* precidence */
		 int right_associative,
		 void (*f)())
{
  SymbolTableNodePtr t;
  t = symbol_table_add_string(name);
  t->token = tok_operator;
  t->args = args;
  t->precidence = prec;
  t->right_associative = right_associative;
  t->op = f;
  return t;
}

int
exp_add_function(char *name,
		 int args,
		 double (*f)())
{
  SymbolTableNodePtr t;
  
  t = symbol_table_add_string(name);
  if (t == NULL)
    return 1;
  t->token = tok_function;
  t->args = args;
  t->func = f;
  return 0;
}

int
exp_add_constant(char *name,
		 double value)
{
  SymbolTableNodePtr t;
  
  t = symbol_table_add_string(name);
  if (t == NULL)
    return 1;
  t->token = tok_const;
  t->value = value;
  return 0;
}

int
exp_add_variable(char *name,
		 double value)
{
  SymbolTableNodePtr t;
  
  t = symbol_table_add_string(name);
  if (t == NULL) 
    return 1;
  t->token = tok_variable;
  t->value = value;
  return 0;
}

int
exp_update_variable(char *name,
		    double value)
{
  SymbolTableNodePtr t;
  
  t = symbol_table_lookup_string(name);
  if (t == NULL) 
    return 1;			/* error */
  if (t->token != tok_variable)
    return 2;			/* error */
  t->value = value;
  return 0;
}
int
exp_fetch_variable(char *name,
		    double *value)
{
  SymbolTableNodePtr t;
  
  t = symbol_table_lookup_string(name);
  if (t == NULL) 
    return 1;			/* error */
  if (t->token != tok_variable)
    return 2;			/* error */
  *value = t->value;
  return 0;
}

int
exp_shutdown()
{
  symbol_table_destroy();
  return 0;
}

int
exp_init()
{
  int i;
  SymbolTableNodePtr t;

  for (i = 0; i < sizeof(priv_ops)/sizeof(priv_ops[0]); i++) 
    exp_add_operator(priv_ops[i].name, 
		     priv_ops[i].args,
		     priv_ops[i].prec,
		     priv_ops[i].right,
		     priv_ops[i].f);
  uminus = exp_add_operator("_", 1, 5, 0, my_neg);

  for (i = 0; i < sizeof(priv_funs)/sizeof(priv_funs[0]); i++) 
    exp_add_function(priv_funs[i].name,
		     priv_funs[i].args,
		     priv_funs[i].f);

  for (i = 0; i < sizeof(priv_const)/sizeof(priv_const[0]); i++)
    exp_add_constant(priv_const[i].name,priv_const[i].value);

  for (i = 0; i < sizeof(priv_vars)/sizeof(priv_vars[0]); i++)
    exp_add_variable(priv_vars[i].name,priv_vars[i].value);

  t = symbol_table_add_string("(");  
  t->token = tok_lparen;
  t = symbol_table_add_string(")");  
  t->token = tok_rparen;
  t = symbol_table_add_string(",");  
  t->token = tok_comma;
  return 0;
}

static void
my_add()
{
  double a, b, c;

  a = exp_num_pop(); b = exp_num_pop();
  c = a + b;
  exp_num_push(c);
}

static void
my_sub()
{
  double a, b, c;

  a = exp_num_pop(); b = exp_num_pop();
  c = a - b;
  exp_num_push(c);
}

static void
my_mul()
{
  double a, b, c;

  a = exp_num_pop(); b = exp_num_pop();
  c = a * b;
  exp_num_push(c);
}

static void
my_div()
{
  double a, b, c;

  b = exp_num_pop(); 
  a = exp_num_pop();
  c = a / b;
  exp_num_push(c);
}

static void
my_mod()
{
  double a, b, c;

  b = exp_num_pop(); 
  a = exp_num_pop();
  c = fmod(a,b);
  exp_num_push(c);
}

static void
my_pow()
{
  double a, b, c;

  b = exp_num_pop();
  a = exp_num_pop(); 
  c = pow(a,b);
  exp_num_push(c);
}

static void
my_neg()
{
  double a;

  a = exp_num_pop(); 
  exp_num_push(-a);
}

static void
execute(SymbolTableNodePtr s)
{
  double a,b,c,t;
  if (s->token == tok_operator) {
    s->op();
    return;
  }
  if (s->token == tok_function) {
    switch (s->args) {
    case 0:
      t = s->func();
      exp_num_push(t);
      //      printf("execute %s() = %g\n", s->string, t);
      break;
    case 1:
      a = exp_num_pop();
      t = s->func(a);
      exp_num_push(t);
      //      printf("execute %s(%g) = %g\n", s->string, a, t);
      break;
    case 2:
      b = exp_num_pop();
      a = exp_num_pop();
      t = s->func(a,b);
      exp_num_push(t); 
      //      printf("execute %s(%g,%g) = %g\n", s->string, a,b, t);
      break;
    case 3:
      c = exp_num_pop();
      b = exp_num_pop();
      a = exp_num_pop();
      t = s->func(a,b,c);
      exp_num_push(t);
      //      printf("execute %s(%g,%g,c) = %g\n", s->string, a,b,c, t);
      break;
    default:
      errx(1,"Too many args (%d)\n", s->args);
    }
    return;
  }
  errx(1,"Unexpected token type");
}

double
exp_eval(char *p)
{
  char *next;
  double t;
  SymbolTableNodePtr s, sc;
  int pe, um;

  um = 1;			/* if we find a '-' next it is a unary minus */
  while (*p) {
    next = p;			/* make them match */
    if (strchr(" \t\n\r\f",*p)) { /* skip blanks */
      p++;
      continue;
    } 
    /*
     * try to parse a number
     */
    if ((*p != '-') && (*p != '+')) /* don't parse negative constants, for unary minus */
      t = strtod(p, &next);
    if (next != p) {		/* we parsed a number */
      //      printf("Parsed a number: %g\n", t);
      exp_num_push(t);
      p = next;
      um = 0;			/* can't have unary minus after a number */
      continue;
    }
    /* 
     * Else try to parse as anything else
     */
    s = symbol_table_lookup_string(p);
    if (s == NULL) 
      err(1,"Syntax error at \"%s\"", p);
    //    printf("Parsed something: %s\n", s->string);
    if (um && 			/* if we can have unary minus */
	(s->token == tok_operator) && /* and this is an operator */
	(s->op == my_sub)) {	      /* and this operator is a subtract */
      s = uminus;		      /* crowbar it to be a unary minus */
      um = 0;			      /* can't have unary minus after a unary minus */
    }
    switch (s->token) {
    case tok_variable:
      //      printf("\tVariable (%s) -> Pushing %g\n", s->string, s->value);
      exp_num_push(s->value);
      p += s->len;
      um = 0;			/* can't have unary minus after a variable */
      break;
      
    case tok_const:
      //      printf("\tConstant (%s) -> Pushing %g\n", s->string, s->value);
      exp_num_push(s->value);
      p += s->len;
      um = 0;			/* can't have unary minus after a constant */
      break;

    case tok_operator:
      //      printf("\tOperator (%s) -> Handling precidence\n", s->string);
      while (osp) {		/* while operand stack not empty */
	sc = ostack[osp-1];	/* get top */
	if ((sc->token == tok_operator) &&
	    ((!s->right_associative && (s->precidence <= sc->precidence))) ||
	    ((s->right_associative && (s->precidence < sc->precidence)))) {
	  execute(sc);
	  osp--;
	} else break;
      }
      op_push(s);
      p += s->len;
      um = 1;			/* can have unary minus after an operator */
      break;

    case tok_function:
      //      printf("\tFunction -> pushing on operator stack\n");
      op_push(s);
      p += s->len;
      break;

    case tok_lparen:
      //      printf("\tLeft paren -> Push onto operator stack\n");
      op_push(s);
      p += s->len;
      um = 1;			/* can have unary minus after left paren */
      break;

    case tok_comma:
      //      printf("\tComma -> do lots of thinking\n");
      p += s->len;		/* skip over it */
      pe = 0;			/* not a parenthesis error */
      while (osp) {		/* while operand stack not empty */
	sc = ostack[osp-1];	/* get top */
	if (sc->token == tok_lparen) {
	  pe = 1;
	  break;
	}
	execute(sc);
	osp--;
      }
      if (!pe)
	errx(1,"Error: Separator or parenthesis mismatch in tok_comma");
      um = 1;			/* can have unary minus after comma */
      break;

    case tok_rparen:
      p += s->len;		/* skip over it */
      pe = 0;
      while (osp) {
	sc = ostack[osp-1];	/* get top */
	if (sc->token == tok_lparen) {
	  pe = 1;
	  break;
	} 
	execute(sc);
	osp--;
      }
      if (!pe)
	errx(1,"Error: parenthesis mismatched in tok_rparen");
      osp--;			/* throw away the left parenthesis */
      if (osp) {
	sc = ostack[osp-1];	/* get top */
	if (sc->token == tok_function) {
	  execute(sc);
	  osp--;
	} else {
	  //	  printf("Didn't execute the token of type %d (%s)\n", sc->token,tok_names[sc->token]);
	}
      }
      um = 0;			/* cannot have unary minus after right paren */
      break;
    case tok_unknown:
    case tok_number:
    case tok_uminus:
    default:
      errx(1,"Unknown token type %d (%s).\n", s->token, tok_names[s->token]);
    }
  }						
  while (osp) {
    sc = ostack[osp-1];	/* get top */
    if ((sc->token == tok_lparen) ||(sc->token == tok_rparen))
      errx(1,"Error: Parenthesis Mismatched at bottom");
    execute(sc);
    osp--;
  }
  t = exp_num_pop();
  //  printf("The result is: %g\n", t);
  return t;
}
