/*
 * Builtin Functions
 *
 * Author(s) : Catalin Dumitrescu (catalind@acm.org)
 *
 * File: builtin.cc
 * Created: Mon Aug 27 10:15:57 CDT 2001
 *
 */

#include "object.hh"
#include "ints.hh"
#include "chars.hh"
#include "expression.hh"
#include "func.hh"
#include "list.hh"
#include "error.hh"
#include "success.hh"
#include "builtin.hh"

object* 
__add (object* obj)
{
  vector<object*> *cnt = NULL;
  list *lst = dynamic_cast<list*> (obj);

  if (obj->getType () == LIST)
    {
      cnt = (vector<object*>*)lst->pvalue ();
      ints *n = new ints (0);
      for (int i = 0; i < cnt->size(); i++)
	*(int*)(n->pvalue()) += *(int*)((*cnt)[i]->pvalue());
      return n;
    }
  return new error ("wrong argument"); 
}

object* 
__sub (object* obj)
{
  vector<object*> *cnt = NULL;
  list *lst = dynamic_cast<list*> (obj);

  if (obj->getType () == LIST)
    {
      cnt = (vector<object*>*)lst->pvalue ();
      ints *n = new ints (0);
      if (cnt->size () > 0)
	{
	  *(int*)(n->pvalue ()) = *(int*)((*cnt)[0]->pvalue());
	  for (int i = 1; i < cnt->size(); i++)
	    *(int*)(n->pvalue()) -= *(int*)((*cnt)[i]->pvalue());
	}
      return n;
    }
  return new error ("wrong argument"); 
}

object* 
__mul (object* obj)
{
  vector<object*> *cnt = NULL;
  list *lst = dynamic_cast<list*> (obj);

  if (obj->getType () == LIST)
    {
      cnt = (vector<object*>*)lst->pvalue ();
      ints *n = new ints (1);
      for (int i = 0; i < cnt->size(); i++)
	*(int*)(n->pvalue()) *= *(int*)((*cnt)[i]->pvalue());
      return n;
    }
  return new error ("wrong argument"); 
}

object* 
__div (object* obj)
{
  vector<object*> *cnt = NULL;
  list *lst = dynamic_cast<list*> (obj);

  if (obj->getType () == LIST)
    {
      cnt = (vector<object*>*)lst->pvalue ();
      ints *n = new ints (0);
      if (cnt->size () > 0)
	{
	  *(int*)(n->pvalue ()) = *(int*)((*cnt)[0]->pvalue());
	  for (int i = 1; i < cnt->size(); i++)
	    *(int*)(n->pvalue()) /= *(int*)((*cnt)[i]->pvalue());
	}
      return n;
    }
  return new error ("wrong argument"); 
}

object* 
__print (object* obj)
{
  vector<object*> *cnt = NULL;
  list *lst = dynamic_cast<list*> (obj);
  
  if (obj->getType () == LIST)
    {
      cnt = (vector<object*>*)lst->pvalue ();
      for (int i = 0; i < cnt->size(); i++)
	cout << *(int*)((*cnt)[i]->pvalue());
    }
  return new success ("");
}

