#include "__until.h"
#include "Exception.h"
#include "Operand.h"
#include <iostream>

namespace jet {
   
   __until::__until(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local) : Tag(in, parentOut, global, parent, this) {

      coreutils::MString result;
      bool booleanResult = false;
      bool exprMethod = false;
      coreutils::MString exprSaved;
      
      if(keywordDefined("value1")) {
	 
	 if(keywordDefined("expr"))
	   throw coreutils::Exception("either value1 or expr can be specified but not both.");
	 if(!keywordDefined("value2")) 
	   throw coreutils::Exception("value2 required if value1 specified.");
	 if(!keywordDefined("type")) 
	   throw coreutils::Exception("type expected if value1 and value2 specified.");
	 
	 int rc = keywords[resolveKeyword("value1")].compare(keywords[resolveKeyword("value2")]);
	 if(((keywords[resolveKeyword("type")] == "eq") && (rc == 0)) ||
	    ((keywords[resolveKeyword("type")] == "ne") && (rc != 0)) ||
	    ((keywords[resolveKeyword("type")] == "lt") && (rc == -1)) ||
	    ((keywords[resolveKeyword("type")] == "le") && (rc != 1)) ||
	    ((keywords[resolveKeyword("type")] == "gt") && (rc == 1)) ||
	    ((keywords[resolveKeyword("type")] == "ge") && (rc != -1)))
	   booleanResult = true;
	 else
	   throw coreutils::Exception("type value must be 'eq','ne','lt','le','gt','ge'.");
      }
      else if(keywordDefined("expr")) {
	 if(keywordDefined("value2"))
	   throw coreutils::Exception("value2 should not be specified with expr.");
	 if(keywordDefined("type"))
	   throw coreutils::Exception("type should not be specified with expr.");
	 exprMethod = true;
	 exprSaved = keywords["expr"];
      }
      do {
	 processContainer(container);
	 container.reset();
	 if(exprMethod) {
	    keywords["expr"].reset();
	    keywords["expr"] = exprSaved;
	    resolveKeyword("expr");
	    booleanResult = Operand(keywords["expr"], *this).boolean;
	 } else {
	    booleanResult = false;
	    int rc = keywords[resolveKeyword("value1")].compare(keywords[resolveKeyword("value2")]);
	    if(((keywords[resolveKeyword("type")] == "eq") && (rc == 0)) ||
	       ((keywords[resolveKeyword("type")] == "ne") && (rc != 0)) ||
	       ((keywords[resolveKeyword("type")] == "lt") && (rc == -1)) ||
	       ((keywords[resolveKeyword("type")] == "le") && (rc != 1)) ||
	       ((keywords[resolveKeyword("type")] == "gt") && (rc == 1)) ||
	       ((keywords[resolveKeyword("type")] == "ge") && (rc != -1)))
	      booleanResult = true;  
	 }	 
      } while(booleanResult);
      
   }
   
}
