#include "__if.h"
#include "Exception.h"
#include <iostream>
#include "Expression.h"

namespace jet {

   __if::__if(coreutils::ZString &in, coreutils::MString &parent, Global &global) : Tag(in, parent, global, "else") {

      coreutils::MString result;
      bool booleanResult = false;
      
      if(variableDefined("value1")) {
	 if(variableDefined("expr"))
	   throw coreutils::Exception("Either value1 or expr can be specified but not both.");
	 if(variableDefined("value2")) {
	    if(variableDefined("type")) {
	       result = Expression(variables["expr"]);
	    } else
	      throw coreutils::Exception("type expected if value1 and value2 specified.");
	 } else
	   throw coreutils::Exception("value2 required if value1 specified.");
	 if(!variableDefined("type"))
	   throw coreutils::Exception("type required for a value1 and value2 comparison.");
	 int rc = variables["value1"].compare(variables["value2"]);
	 if(((variables["type"] == "eq") && (rc == 0)) ||
	    ((variables["type"] == "ne") && (rc != 0)) ||
	    ((variables["type"] == "lt") && (rc == -1)) || 
	    ((variables["type"] == "le") && (rc != 1)) ||
	    ((variables["type"] == "gt") && (rc == 1)) ||
	    ((variables["type"] == "ge") && (rc != -1)))
	   booleanResult = true;
	 else
	   throw coreutils::Exception("type value must be 'eq','ne','lt','le','gt','ge'.");
      } else if(variableDefined("expr")) {
	 if(variableDefined("value2"))
	   throw coreutils::Exception("value2 should not be specified with expr.");
	 if(variableDefined("type"))
	   throw coreutils::Exception("type should not be specified with expr.");
	 result = Expression(variables["expr"]);
	 booleanResult = true;
      }
      if(booleanResult) 
	processContainer(container);
      else if(hasContainer2)
	processContainer(container2);
      
   }

}
