#include <stdio.h>
#include <stdlib.h>
#include <USENIX.h>

int main (int ac, char **av)
{
  USENIX_Factory f;
  USENIX_Calculator c;
  ILU_C_ENVIRONMENT e;
  char *line;
  char buf[1000];
  ilu_real val;
  ilu_real newval = 0.0;

  USENIX__Initialize();

  f = (USENIX_Factory) ILU_C_LookupObject("0@USENIX_Factory",
					  USENIX_Factory__MSType);
  if (f == NULL)
    {
      fprintf (stderr, "Couldn't find calculator server\n");
      exit(1);
    }

  c = USENIX_Factory_NewCalculator (f, &e);
  if (! ILU_C_SUCCESSFUL(&e))
    {
      fprintf (stderr, "Couldn't create calculator, error %s signalled.\n",
	       ILU_C_EXCEPTION_ID(&e));
      exit(1);
    }
  USENIX_Calculator_Clear(c, &e);
  do {
    printf ("%.5f\n> ", newval);
    fflush(stdout);

    *buf = 'q';
    line = gets(buf);

    switch (buf[0]) {
    case '+':
      val = atof(buf+1);
      if (!((USENIX_Calculator_Add(c, &e, val), ILU_C_SUCCESSFUL(&e))
	    && (newval = USENIX_Calculator_CurrentValue(c, &e),
		ILU_C_SUCCESSFUL(&e))))
	{
	  fprintf (stderr, "Operation <%s> signals error <%s>.\n",
		   buf, ILU_C_EXCEPTION_ID(&e));
	}	
      break;
    case '-':
      val = atof(buf+1);
      if (!((USENIX_Calculator_Subtract(c, &e, val), ILU_C_SUCCESSFUL(&e))
	    && (newval = USENIX_Calculator_CurrentValue(c, &e),
		ILU_C_SUCCESSFUL(&e))))
	{
	  fprintf (stderr, "Operation <%s> signals error <%s>.\n",
		   buf, ILU_C_EXCEPTION_ID(&e));
	}	
      break;
    case '*':
      val = atof(buf+1);
      if (!((USENIX_Calculator_Multiply(c, &e, val), ILU_C_SUCCESSFUL(&e))
	    && (newval = USENIX_Calculator_CurrentValue(c, &e),
		ILU_C_SUCCESSFUL(&e))))
	{
	  fprintf (stderr, "Operation <%s> signals error <%s>.\n",
		   buf, ILU_C_EXCEPTION_ID(&e));
	}	
      break;
    case '/':
      val = atof(buf+1);
      if (!((USENIX_Calculator_Divide(c, &e, val), ILU_C_SUCCESSFUL(&e))
	    && (newval = USENIX_Calculator_CurrentValue(c, &e),
		ILU_C_SUCCESSFUL(&e))))
	{
	  fprintf (stderr, "Operation <%s> signals error <%s>.\n",
		   buf, ILU_C_EXCEPTION_ID(&e));
	}	
      break;
    case 'c':
      if (!(USENIX_Calculator_Clear(c, &e), ILU_C_SUCCESSFUL(&e)))
	{
	  fprintf (stderr, "Operation <%s> signals error <%s>.\n",
		   buf, ILU_C_EXCEPTION_ID(&e));
	}	
      break;
    case 'q':
      line = NULL;
      break;
    default:
      fprintf (stderr, "Invalid operation <%s>\n", buf);
      fprintf (stderr, "Valid ops are +, -, *, /, clear, quit\n");
    };

  } while (line != NULL);

  return (0);
}
