merged asterix_stabilization r1109 through r1168 into asterix_stabilization_issue_251


git-svn-id: https://asterixdb.googlecode.com/svn/branches/asterix_stabilization_issue_251@1169 eaa15691-b419-025a-1212-ee371bd00084
diff --git a/asterix-algebra/pom.xml b/asterix-algebra/pom.xml
index f950800..70f8c53 100644
--- a/asterix-algebra/pom.xml
+++ b/asterix-algebra/pom.xml
@@ -5,9 +5,7 @@
 		<groupId>edu.uci.ics.asterix</groupId>
 		<version>0.0.4-SNAPSHOT</version>
 	</parent>
-	<groupId>edu.uci.ics.asterix</groupId>
 	<artifactId>asterix-algebra</artifactId>
-	<version>0.0.4-SNAPSHOT</version>
 
 	<build>
 		<plugins>
@@ -60,8 +58,7 @@
 		</dependency>
 		<dependency>
 			<groupId>edu.uci.ics.hyracks</groupId>
-			<artifactId>hyracks-algebricks-compiler</artifactId>
-			<version>0.2.2-SNAPSHOT</version>
+			<artifactId>algebricks-compiler</artifactId>
 		</dependency>
 		<dependency>
 			<groupId>org.json</groupId>
diff --git a/asterix-algebra/src/main/java/edu/uci/ics/asterix/algebra/operators/physical/BTreeSearchPOperator.java b/asterix-algebra/src/main/java/edu/uci/ics/asterix/algebra/operators/physical/BTreeSearchPOperator.java
index 09a4c6b..f0880ec 100644
--- a/asterix-algebra/src/main/java/edu/uci/ics/asterix/algebra/operators/physical/BTreeSearchPOperator.java
+++ b/asterix-algebra/src/main/java/edu/uci/ics/asterix/algebra/operators/physical/BTreeSearchPOperator.java
@@ -45,12 +45,14 @@
 
     private final List<LogicalVariable> lowKeyVarList;
     private final List<LogicalVariable> highKeyVarList;
-    private boolean isPrimaryIndex;
+    private final boolean isPrimaryIndex;
+    private final boolean isEqCondition;
 
     public BTreeSearchPOperator(IDataSourceIndex<String, AqlSourceId> idx, boolean requiresBroadcast,
-            boolean isPrimaryIndex, List<LogicalVariable> lowKeyVarList, List<LogicalVariable> highKeyVarList) {
+            boolean isPrimaryIndex, boolean isEqCondition, List<LogicalVariable> lowKeyVarList, List<LogicalVariable> highKeyVarList) {
         super(idx, requiresBroadcast);
         this.isPrimaryIndex = isPrimaryIndex;
+        this.isEqCondition = isEqCondition;
         this.lowKeyVarList = lowKeyVarList;
         this.highKeyVarList = highKeyVarList;
     }
@@ -100,13 +102,13 @@
     public PhysicalRequirements getRequiredPropertiesForChildren(ILogicalOperator op,
             IPhysicalPropertiesVector reqdByParent) {
         if (requiresBroadcast) {
-            if (isPrimaryIndex) {
-                // For primary indexes, we require re-partitioning on the primary key, and not a broadcast.
-                // Also, add a local sorting property to enforce a sort before the primary-index operator.
+            // For primary indexes optimizing an equality condition we can reduce the broadcast requirement to hash partitioning.
+            if (isPrimaryIndex && isEqCondition) {
                 StructuralPropertiesVector[] pv = new StructuralPropertiesVector[1];
                 ListSet<LogicalVariable> searchKeyVars = new ListSet<LogicalVariable>();
                 searchKeyVars.addAll(lowKeyVarList);
                 searchKeyVars.addAll(highKeyVarList);
+                // Also, add a local sorting property to enforce a sort before the primary-index operator.
                 List<ILocalStructuralProperty> propsLocal = new ArrayList<ILocalStructuralProperty>();
                 for (LogicalVariable orderVar : searchKeyVars) {
                     propsLocal.add(new LocalOrderProperty(new OrderColumn(orderVar, OrderKind.ASC)));
diff --git a/asterix-algebra/src/main/java/edu/uci/ics/asterix/optimizer/rules/ConstantFoldingRule.java b/asterix-algebra/src/main/java/edu/uci/ics/asterix/optimizer/rules/ConstantFoldingRule.java
index 47e957b..bc61c49 100644
--- a/asterix-algebra/src/main/java/edu/uci/ics/asterix/optimizer/rules/ConstantFoldingRule.java
+++ b/asterix-algebra/src/main/java/edu/uci/ics/asterix/optimizer/rules/ConstantFoldingRule.java
@@ -28,6 +28,7 @@
 import edu.uci.ics.asterix.formats.nontagged.AqlBinaryBooleanInspectorImpl;
 import edu.uci.ics.asterix.formats.nontagged.AqlBinaryComparatorFactoryProvider;
 import edu.uci.ics.asterix.formats.nontagged.AqlBinaryHashFunctionFactoryProvider;
+import edu.uci.ics.asterix.formats.nontagged.AqlBinaryHashFunctionFamilyProvider;
 import edu.uci.ics.asterix.formats.nontagged.AqlBinaryIntegerInspector;
 import edu.uci.ics.asterix.formats.nontagged.AqlPrinterFactoryProvider;
 import edu.uci.ics.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
@@ -106,8 +107,8 @@
 
     private static final JobGenContext _jobGenCtx = new JobGenContext(null, null, null,
             AqlSerializerDeserializerProvider.INSTANCE, AqlBinaryHashFunctionFactoryProvider.INSTANCE,
-            AqlBinaryComparatorFactoryProvider.INSTANCE, AqlTypeTraitProvider.INSTANCE,
-            AqlBinaryBooleanInspectorImpl.FACTORY, AqlBinaryIntegerInspector.FACTORY,
+            AqlBinaryHashFunctionFamilyProvider.INSTANCE, AqlBinaryComparatorFactoryProvider.INSTANCE,
+            AqlTypeTraitProvider.INSTANCE, AqlBinaryBooleanInspectorImpl.FACTORY, AqlBinaryIntegerInspector.FACTORY,
             AqlPrinterFactoryProvider.INSTANCE, AqlNullWriterFactory.INSTANCE, null,
             new LogicalExpressionJobGenToExpressionRuntimeProviderAdapter(AqlLogicalExpressionJobGen.INSTANCE),
             AqlExpressionTypeComputer.INSTANCE, AqlNullableTypeComputer.INSTANCE, null, null, null,
diff --git a/asterix-algebra/src/main/java/edu/uci/ics/asterix/optimizer/rules/SetAsterixPhysicalOperatorsRule.java b/asterix-algebra/src/main/java/edu/uci/ics/asterix/optimizer/rules/SetAsterixPhysicalOperatorsRule.java
index 19791e3..e19466e 100644
--- a/asterix-algebra/src/main/java/edu/uci/ics/asterix/optimizer/rules/SetAsterixPhysicalOperatorsRule.java
+++ b/asterix-algebra/src/main/java/edu/uci/ics/asterix/optimizer/rules/SetAsterixPhysicalOperatorsRule.java
@@ -165,8 +165,8 @@
                                 BTreeJobGenParams btreeJobGenParams = new BTreeJobGenParams();
                                 btreeJobGenParams.readFromFuncArgs(f.getArguments());
                                 op.setPhysicalOperator(new BTreeSearchPOperator(dsi, requiresBroadcast,
-                                        btreeJobGenParams.isPrimaryIndex(), btreeJobGenParams.getLowKeyVarList(),
-                                        btreeJobGenParams.getHighKeyVarList()));
+                                        btreeJobGenParams.isPrimaryIndex(), btreeJobGenParams.isEqCondition(),
+                                        btreeJobGenParams.getLowKeyVarList(), btreeJobGenParams.getHighKeyVarList()));
                                 break;
                             }
                             case RTREE: {
diff --git a/asterix-algebra/src/main/java/edu/uci/ics/asterix/optimizer/rules/SetClosedRecordConstructorsRule.java b/asterix-algebra/src/main/java/edu/uci/ics/asterix/optimizer/rules/SetClosedRecordConstructorsRule.java
index ad70d6f..3dad464 100644
--- a/asterix-algebra/src/main/java/edu/uci/ics/asterix/optimizer/rules/SetClosedRecordConstructorsRule.java
+++ b/asterix-algebra/src/main/java/edu/uci/ics/asterix/optimizer/rules/SetClosedRecordConstructorsRule.java
@@ -186,6 +186,7 @@
                 case DATE:
                 case TIME:
                 case DURATION:
+                case INTERVAL:
                 case POINT:
                 case POINT3D:
                 case POLYGON:
diff --git a/asterix-algebra/src/main/java/edu/uci/ics/asterix/optimizer/rules/SimilarityCheckRule.java b/asterix-algebra/src/main/java/edu/uci/ics/asterix/optimizer/rules/SimilarityCheckRule.java
index c90b3f1..e88e5b0 100644
--- a/asterix-algebra/src/main/java/edu/uci/ics/asterix/optimizer/rules/SimilarityCheckRule.java
+++ b/asterix-algebra/src/main/java/edu/uci/ics/asterix/optimizer/rules/SimilarityCheckRule.java
@@ -33,24 +33,22 @@
 
 /**
  * Looks for a select operator, containing a condition:
- * 
  * similarity-function GE/GT/LE/LE constant/variable
- * 
  * Rewrites the select condition (and possibly the assign expr) with the equivalent similarity-check function.
- * 
  */
 public class SimilarityCheckRule implements IAlgebraicRewriteRule {
 
     @Override
-    public boolean rewritePost(Mutable<ILogicalOperator> opRef, IOptimizationContext context) throws AlgebricksException {
-    	AbstractLogicalOperator op = (AbstractLogicalOperator) opRef.getValue();
+    public boolean rewritePost(Mutable<ILogicalOperator> opRef, IOptimizationContext context)
+            throws AlgebricksException {
+        AbstractLogicalOperator op = (AbstractLogicalOperator) opRef.getValue();
         // Look for select.
         if (op.getOperatorTag() != LogicalOperatorTag.SELECT) {
             return false;
         }
         SelectOperator select = (SelectOperator) op;
         Mutable<ILogicalExpression> condExpr = select.getCondition();
-        
+
         // Gather assigns below this select.
         List<AssignOperator> assigns = new ArrayList<AssignOperator>();
         AbstractLogicalOperator childOp = (AbstractLogicalOperator) select.getInputs().get(0).getValue();
@@ -60,12 +58,13 @@
         }
         while (childOp.getOperatorTag() == LogicalOperatorTag.ASSIGN) {
             assigns.add((AssignOperator) childOp);
-        	childOp = (AbstractLogicalOperator) childOp.getInputs().get(0).getValue();
+            childOp = (AbstractLogicalOperator) childOp.getInputs().get(0).getValue();
         }
         return replaceSelectConditionExprs(condExpr, assigns, context);
     }
 
-    private boolean replaceSelectConditionExprs(Mutable<ILogicalExpression> expRef, List<AssignOperator> assigns, IOptimizationContext context) throws AlgebricksException {
+    private boolean replaceSelectConditionExprs(Mutable<ILogicalExpression> expRef, List<AssignOperator> assigns,
+            IOptimizationContext context) throws AlgebricksException {
         ILogicalExpression expr = expRef.getValue();
         if (expr.getExpressionTag() != LogicalExpressionTag.FUNCTION_CALL) {
             return false;
@@ -83,10 +82,10 @@
             }
             return found;
         }
-        
+
         // Look for GE/GT/LE/LT.
-        if (funcIdent != AlgebricksBuiltinFunctions.GE && funcIdent != AlgebricksBuiltinFunctions.GT &&
-                funcIdent != AlgebricksBuiltinFunctions.LE && funcIdent != AlgebricksBuiltinFunctions.LT) {
+        if (funcIdent != AlgebricksBuiltinFunctions.GE && funcIdent != AlgebricksBuiltinFunctions.GT
+                && funcIdent != AlgebricksBuiltinFunctions.LE && funcIdent != AlgebricksBuiltinFunctions.LT) {
             return false;
         }
 
@@ -98,8 +97,8 @@
         // Normalized GE/GT/LE/LT as if constant was on the right hand side.
         FunctionIdentifier normFuncIdent = null;
         // One of the args must be a constant.
-        if (arg1.getExpressionTag() == LogicalExpressionTag.CONSTANT) {                    	
-        	ConstantExpression constExpr = (ConstantExpression) arg1;
+        if (arg1.getExpressionTag() == LogicalExpressionTag.CONSTANT) {
+            ConstantExpression constExpr = (ConstantExpression) arg1;
             constVal = (AsterixConstantValue) constExpr.getValue();
             nonConstExpr = arg2;
             // Get func ident as if swapping lhs and rhs.            
@@ -113,91 +112,101 @@
         } else {
             return false;
         }
-        
+
         // The other arg is a function call. We can directly replace the select condition with an equivalent similarity check expression.
         if (nonConstExpr.getExpressionTag() == LogicalExpressionTag.FUNCTION_CALL) {
-        	return replaceWithFunctionCallArg(expRef, normFuncIdent, constVal, (AbstractFunctionCallExpression) nonConstExpr);
+            return replaceWithFunctionCallArg(expRef, normFuncIdent, constVal,
+                    (AbstractFunctionCallExpression) nonConstExpr);
         }
         // The other arg ist a variable. We may have to introduce an assign operator that assigns the result of a similarity-check function to a variable.
         if (nonConstExpr.getExpressionTag() == LogicalExpressionTag.VARIABLE) {
-        	return replaceWithVariableArg(expRef, normFuncIdent, constVal, (VariableReferenceExpression) nonConstExpr, assigns, context);
+            return replaceWithVariableArg(expRef, normFuncIdent, constVal, (VariableReferenceExpression) nonConstExpr,
+                    assigns, context);
         }
         return false;
     }
-    
+
     private boolean replaceWithVariableArg(Mutable<ILogicalExpression> expRef, FunctionIdentifier normFuncIdent,
-    		AsterixConstantValue constVal, VariableReferenceExpression varRefExpr, List<AssignOperator> assigns, IOptimizationContext context) throws AlgebricksException {
-    	
-    	// Find variable in assigns to determine its originating function.    	
-    	LogicalVariable var = varRefExpr.getVariableReference();
-    	Mutable<ILogicalExpression> simFuncExprRef = null;
-    	ScalarFunctionCallExpression simCheckFuncExpr = null;
-    	AssignOperator matchingAssign = null;
-     	for (int i = 0; i < assigns.size(); i++) {
-    		AssignOperator assign = assigns.get(i);
-    		for (int j = 0; j < assign.getVariables().size(); j++) {
-    			// Check if variables match.
-    			if (var != assign.getVariables().get(j)) {
-    				continue;
-    			}
-    			// Check if corresponding expr is a function call.
-    			if (assign.getExpressions().get(j).getValue().getExpressionTag() != LogicalExpressionTag.FUNCTION_CALL) {
-    				continue;
-    			}
-    			simFuncExprRef = assign.getExpressions().get(j);
-    			// Analyze function expression and get equivalent similarity check function.
-    			simCheckFuncExpr = getSimilarityCheckExpr(normFuncIdent, constVal, (AbstractFunctionCallExpression) simFuncExprRef.getValue());
-    			matchingAssign = assign;
-    			break;
-    		}
-    		if (simCheckFuncExpr != null) {
-    			break;
-    		}
-    	}
-    	
-    	// Only non-null if we found that varRefExpr refers to an optimizable similarity function call. 
-    	if (simCheckFuncExpr != null) {
-    		// Create a new assign under matchingAssign which assigns the result of our similarity-check function to a variable.
-    		LogicalVariable newVar = context.newVar();
-    		AssignOperator newAssign = new AssignOperator(newVar, new MutableObject<ILogicalExpression>(simCheckFuncExpr));
-    		// Hook up inputs. 
-    		newAssign.getInputs().add(new MutableObject<ILogicalOperator>(matchingAssign.getInputs().get(0).getValue()));
-    		matchingAssign.getInputs().get(0).setValue(newAssign);    		
-    		
-    		// Replace select condition with a get-item on newVar.
+            AsterixConstantValue constVal, VariableReferenceExpression varRefExpr, List<AssignOperator> assigns,
+            IOptimizationContext context) throws AlgebricksException {
+
+        // Find variable in assigns to determine its originating function.    	
+        LogicalVariable var = varRefExpr.getVariableReference();
+        Mutable<ILogicalExpression> simFuncExprRef = null;
+        ScalarFunctionCallExpression simCheckFuncExpr = null;
+        AssignOperator matchingAssign = null;
+        for (int i = 0; i < assigns.size(); i++) {
+            AssignOperator assign = assigns.get(i);
+            for (int j = 0; j < assign.getVariables().size(); j++) {
+                // Check if variables match.
+                if (var != assign.getVariables().get(j)) {
+                    continue;
+                }
+                // Check if corresponding expr is a function call.
+                if (assign.getExpressions().get(j).getValue().getExpressionTag() != LogicalExpressionTag.FUNCTION_CALL) {
+                    continue;
+                }
+                simFuncExprRef = assign.getExpressions().get(j);
+                // Analyze function expression and get equivalent similarity check function.
+                simCheckFuncExpr = getSimilarityCheckExpr(normFuncIdent, constVal,
+                        (AbstractFunctionCallExpression) simFuncExprRef.getValue());
+                matchingAssign = assign;
+                break;
+            }
+            if (simCheckFuncExpr != null) {
+                break;
+            }
+        }
+
+        // Only non-null if we found that varRefExpr refers to an optimizable similarity function call. 
+        if (simCheckFuncExpr != null) {
+            // Create a new assign under matchingAssign which assigns the result of our similarity-check function to a variable.
+            LogicalVariable newVar = context.newVar();
+            AssignOperator newAssign = new AssignOperator(newVar, new MutableObject<ILogicalExpression>(
+                    simCheckFuncExpr));
+            // Hook up inputs. 
+            newAssign.getInputs()
+                    .add(new MutableObject<ILogicalOperator>(matchingAssign.getInputs().get(0).getValue()));
+            matchingAssign.getInputs().get(0).setValue(newAssign);
+
+            // Replace select condition with a get-item on newVar.
             List<Mutable<ILogicalExpression>> selectGetItemArgs = new ArrayList<Mutable<ILogicalExpression>>();
             // First arg is a variable reference expr on newVar.
             selectGetItemArgs.add(new MutableObject<ILogicalExpression>(new VariableReferenceExpression(newVar)));
             // Second arg is the item index to be accessed, here 0.
-            selectGetItemArgs.add(new MutableObject<ILogicalExpression>(new ConstantExpression(new AsterixConstantValue(new AInt32(0)))));
-            ILogicalExpression selectGetItemExpr = new ScalarFunctionCallExpression(FunctionUtils.getFunctionInfo(AsterixBuiltinFunctions.GET_ITEM), selectGetItemArgs);
+            selectGetItemArgs.add(new MutableObject<ILogicalExpression>(new ConstantExpression(
+                    new AsterixConstantValue(new AInt32(0)))));
+            ILogicalExpression selectGetItemExpr = new ScalarFunctionCallExpression(
+                    FunctionUtils.getFunctionInfo(AsterixBuiltinFunctions.GET_ITEM), selectGetItemArgs);
             // Replace the old similarity function call with the new getItemExpr.
             expRef.setValue(selectGetItemExpr);
-    		
+
             // Replace expr corresponding to original variable in the original assign with a get-item on newVar.
             List<Mutable<ILogicalExpression>> assignGetItemArgs = new ArrayList<Mutable<ILogicalExpression>>();
             // First arg is a variable reference expr on newVar.
             assignGetItemArgs.add(new MutableObject<ILogicalExpression>(new VariableReferenceExpression(newVar)));
             // Second arg is the item index to be accessed, here 1.
-            assignGetItemArgs.add(new MutableObject<ILogicalExpression>(new ConstantExpression(new AsterixConstantValue(new AInt32(1)))));
-            ILogicalExpression assignGetItemExpr = new ScalarFunctionCallExpression(FunctionUtils.getFunctionInfo(AsterixBuiltinFunctions.GET_ITEM), assignGetItemArgs);
+            assignGetItemArgs.add(new MutableObject<ILogicalExpression>(new ConstantExpression(
+                    new AsterixConstantValue(new AInt32(1)))));
+            ILogicalExpression assignGetItemExpr = new ScalarFunctionCallExpression(
+                    FunctionUtils.getFunctionInfo(AsterixBuiltinFunctions.GET_ITEM), assignGetItemArgs);
             // Replace the original assign expr with the get-item expr.
             simFuncExprRef.setValue(assignGetItemExpr);
-    		
+
             context.computeAndSetTypeEnvironmentForOperator(newAssign);
             context.computeAndSetTypeEnvironmentForOperator(matchingAssign);
-            
-    		return true;
-    	}
-    	
-    	return false;
+
+            return true;
+        }
+
+        return false;
     }
-    
+
     private boolean replaceWithFunctionCallArg(Mutable<ILogicalExpression> expRef, FunctionIdentifier normFuncIdent,
-    		AsterixConstantValue constVal, AbstractFunctionCallExpression funcExpr) {
-    	// Analyze func expr to see if it is an optimizable similarity function.
-        ScalarFunctionCallExpression simCheckFuncExpr = getSimilarityCheckExpr(normFuncIdent, constVal, funcExpr); 
-        
+            AsterixConstantValue constVal, AbstractFunctionCallExpression funcExpr) {
+        // Analyze func expr to see if it is an optimizable similarity function.
+        ScalarFunctionCallExpression simCheckFuncExpr = getSimilarityCheckExpr(normFuncIdent, constVal, funcExpr);
+
         // Replace the expr in the select condition.
         if (simCheckFuncExpr != null) {
             // Get item 0 from var.
@@ -205,8 +214,10 @@
             // First arg is the similarity-check function call.
             getItemArgs.add(new MutableObject<ILogicalExpression>(simCheckFuncExpr));
             // Second arg is the item index to be accessed.
-            getItemArgs.add(new MutableObject<ILogicalExpression>(new ConstantExpression(new AsterixConstantValue(new AInt32(0)))));
-            ILogicalExpression getItemExpr = new ScalarFunctionCallExpression(FunctionUtils.getFunctionInfo(AsterixBuiltinFunctions.GET_ITEM), getItemArgs);
+            getItemArgs.add(new MutableObject<ILogicalExpression>(new ConstantExpression(new AsterixConstantValue(
+                    new AInt32(0)))));
+            ILogicalExpression getItemExpr = new ScalarFunctionCallExpression(
+                    FunctionUtils.getFunctionInfo(AsterixBuiltinFunctions.GET_ITEM), getItemArgs);
             // Replace the old similarity function call with the new getItemExpr.
             expRef.setValue(getItemExpr);
             return true;
@@ -214,10 +225,10 @@
 
         return false;
     }
-    
+
     private ScalarFunctionCallExpression getSimilarityCheckExpr(FunctionIdentifier normFuncIdent,
-    		AsterixConstantValue constVal, AbstractFunctionCallExpression funcExpr) {
-    	// Remember args from original similarity function to add them to the similarity-check function later.
+            AsterixConstantValue constVal, AbstractFunctionCallExpression funcExpr) {
+        // Remember args from original similarity function to add them to the similarity-check function later.
         ArrayList<Mutable<ILogicalExpression>> similarityArgs = null;
         ScalarFunctionCallExpression simCheckFuncExpr = null; 
         // Look for jaccard function call, and GE or GT.
@@ -270,11 +281,11 @@
         }
         // Preserve all annotations.
         if (simCheckFuncExpr != null) {
-        	simCheckFuncExpr.getAnnotations().putAll(funcExpr.getAnnotations());
+            simCheckFuncExpr.getAnnotations().putAll(funcExpr.getAnnotations());
         }
         return simCheckFuncExpr;
     }
-    
+
     private FunctionIdentifier getLhsAndRhsSwappedFuncIdent(FunctionIdentifier oldFuncIdent) {
         if (oldFuncIdent == AlgebricksBuiltinFunctions.GE) {
             return AlgebricksBuiltinFunctions.LE;
@@ -290,7 +301,7 @@
         }
         throw new IllegalStateException();
     }
-    
+
     @Override
     public boolean rewritePre(Mutable<ILogicalOperator> opRef, IOptimizationContext context) throws AlgebricksException {
         return false;
diff --git a/asterix-algebra/src/main/java/edu/uci/ics/asterix/optimizer/rules/am/BTreeAccessMethod.java b/asterix-algebra/src/main/java/edu/uci/ics/asterix/optimizer/rules/am/BTreeAccessMethod.java
index 1379bf4..5c65299 100644
--- a/asterix-algebra/src/main/java/edu/uci/ics/asterix/optimizer/rules/am/BTreeAccessMethod.java
+++ b/asterix-algebra/src/main/java/edu/uci/ics/asterix/optimizer/rules/am/BTreeAccessMethod.java
@@ -191,6 +191,7 @@
         // If we can't figure out how to integrate a certain funcExpr into the current predicate, we just bail by setting this flag.
         boolean couldntFigureOut = false;
         boolean doneWithExprs = false;
+        boolean isEqCondition = false;
         // TODO: For now don't consider prefix searches.
         BitSet setLowKeys = new BitSet(numSecondaryKeys);
         BitSet setHighKeys = new BitSet(numSecondaryKeys);
@@ -212,7 +213,7 @@
             }
             ILogicalExpression searchKeyExpr = AccessMethodUtils.createSearchKeyExpr(optFuncExpr, indexSubTree,
                     probeSubTree);
-            LimitType limit = getLimitType(optFuncExpr);
+            LimitType limit = getLimitType(optFuncExpr, probeSubTree);
             switch (limit) {
                 case EQUAL: {
                     if (lowKeyLimits[keyPos] == null && highKeyLimits[keyPos] == null) {
@@ -221,14 +222,23 @@
                         lowKeyExprs[keyPos] = highKeyExprs[keyPos] = searchKeyExpr;
                         setLowKeys.set(keyPos);
                         setHighKeys.set(keyPos);
+                        isEqCondition = true;
                     } else {
+                        // Has already been set to the identical values. When optimizing join we may encounter the same optimizable expression twice
+                        // (once from analyzing each side of the join)
+                        if (lowKeyLimits[keyPos] == limit && lowKeyInclusive[keyPos] == true
+                                && lowKeyExprs[keyPos].equals(searchKeyExpr) && highKeyLimits[keyPos] == limit
+                                && highKeyInclusive[keyPos] == true && highKeyExprs[keyPos].equals(searchKeyExpr)) {
+                            isEqCondition = true;
+                            break;
+                        }
                         couldntFigureOut = true;
                     }
                     // TODO: For now don't consider prefix searches.
                     // If high and low keys are set, we exit for now.
                     if (setLowKeys.cardinality() == numSecondaryKeys && setHighKeys.cardinality() == numSecondaryKeys) {
                         doneWithExprs = true;
-                    }
+                    }                    
                     break;
                 }
                 case HIGH_EXCLUSIVE: {
@@ -237,6 +247,12 @@
                         highKeyExprs[keyPos] = searchKeyExpr;
                         highKeyInclusive[keyPos] = false;
                     } else {
+                        // Has already been set to the identical values. When optimizing join we may encounter the same optimizable expression twice
+                        // (once from analyzing each side of the join)
+                        if (highKeyLimits[keyPos] == limit && highKeyInclusive[keyPos] == false
+                                && highKeyExprs[keyPos].equals(searchKeyExpr)) {
+                            break;
+                        }
                         couldntFigureOut = true;
                         doneWithExprs = true;
                     }
@@ -248,6 +264,12 @@
                         highKeyExprs[keyPos] = searchKeyExpr;
                         highKeyInclusive[keyPos] = true;
                     } else {
+                        // Has already been set to the identical values. When optimizing join we may encounter the same optimizable expression twice
+                        // (once from analyzing each side of the join)
+                        if (highKeyLimits[keyPos] == limit && highKeyInclusive[keyPos] == true
+                                && highKeyExprs[keyPos].equals(searchKeyExpr)) {
+                            break;
+                        }
                         couldntFigureOut = true;
                         doneWithExprs = true;
                     }
@@ -259,6 +281,12 @@
                         lowKeyExprs[keyPos] = searchKeyExpr;
                         lowKeyInclusive[keyPos] = false;
                     } else {
+                        // Has already been set to the identical values. When optimizing join we may encounter the same optimizable expression twice
+                        // (once from analyzing each side of the join)
+                        if (lowKeyLimits[keyPos] == limit && lowKeyInclusive[keyPos] == false
+                                && lowKeyExprs[keyPos].equals(searchKeyExpr)) {
+                            break;
+                        }
                         couldntFigureOut = true;
                         doneWithExprs = true;
                     }
@@ -270,6 +298,12 @@
                         lowKeyExprs[keyPos] = searchKeyExpr;
                         lowKeyInclusive[keyPos] = true;
                     } else {
+                        // Has already been set to the identical values. When optimizing join we may encounter the same optimizable expression twice
+                        // (once from analyzing each side of the join)
+                        if (lowKeyLimits[keyPos] == limit && lowKeyInclusive[keyPos] == true
+                                && lowKeyExprs[keyPos].equals(searchKeyExpr)) {
+                            break;
+                        }
                         couldntFigureOut = true;
                         doneWithExprs = true;
                     }
@@ -328,6 +362,7 @@
                 dataset.getDataverseName(), dataset.getDatasetName(), retainInput, requiresBroadcast);
         jobGenParams.setLowKeyInclusive(lowKeyInclusive[0]);
         jobGenParams.setHighKeyInclusive(highKeyInclusive[0]);
+        jobGenParams.setIsEqCondition(isEqCondition);
         jobGenParams.setLowKeyVarList(keyVarList, 0, numLowKeys);
         jobGenParams.setHighKeyVarList(keyVarList, numLowKeys, numHighKeys);
 
@@ -441,7 +476,7 @@
         return -1;
     }
 
-    private LimitType getLimitType(IOptimizableFuncExpr optFuncExpr) {
+    private LimitType getLimitType(IOptimizableFuncExpr optFuncExpr, OptimizableOperatorSubTree probeSubTree) {
         ComparisonKind ck = AlgebricksBuiltinFunctions.getComparisonType(optFuncExpr.getFuncExpr()
                 .getFunctionIdentifier());
         LimitType limit = null;
@@ -451,19 +486,19 @@
                 break;
             }
             case GE: {
-                limit = constantIsOnLhs(optFuncExpr) ? LimitType.HIGH_INCLUSIVE : LimitType.LOW_INCLUSIVE;
+                limit = probeIsOnLhs(optFuncExpr, probeSubTree) ? LimitType.HIGH_INCLUSIVE : LimitType.LOW_INCLUSIVE;
                 break;
             }
             case GT: {
-                limit = constantIsOnLhs(optFuncExpr) ? LimitType.HIGH_EXCLUSIVE : LimitType.LOW_EXCLUSIVE;
+                limit = probeIsOnLhs(optFuncExpr, probeSubTree) ? LimitType.HIGH_EXCLUSIVE : LimitType.LOW_EXCLUSIVE;
                 break;
             }
             case LE: {
-                limit = constantIsOnLhs(optFuncExpr) ? LimitType.LOW_INCLUSIVE : LimitType.HIGH_INCLUSIVE;
+                limit = probeIsOnLhs(optFuncExpr, probeSubTree) ? LimitType.LOW_INCLUSIVE : LimitType.HIGH_INCLUSIVE;
                 break;
             }
             case LT: {
-                limit = constantIsOnLhs(optFuncExpr) ? LimitType.LOW_EXCLUSIVE : LimitType.HIGH_EXCLUSIVE;
+                limit = probeIsOnLhs(optFuncExpr, probeSubTree) ? LimitType.LOW_EXCLUSIVE : LimitType.HIGH_EXCLUSIVE;
                 break;
             }
             case NEQ: {
@@ -477,11 +512,16 @@
         return limit;
     }
 
-    // Returns true if there is a constant value on the left-hand side  if the given optimizable function (assuming a binary function).
-    public boolean constantIsOnLhs(IOptimizableFuncExpr optFuncExpr) {
-        return optFuncExpr.getFuncExpr().getArguments().get(0) == optFuncExpr.getConstantVal(0);
+    private boolean probeIsOnLhs(IOptimizableFuncExpr optFuncExpr, OptimizableOperatorSubTree probeSubTree) {
+        if (probeSubTree == null) {
+            // We are optimizing a selection query. Search key is a constant. Return true if constant is on lhs.
+            return optFuncExpr.getFuncExpr().getArguments().get(0) == optFuncExpr.getConstantVal(0);
+        } else {
+            // We are optimizing a join query. Determine whether the feeding variable is on the lhs. 
+            return (optFuncExpr.getOperatorSubTree(0) == null || optFuncExpr.getOperatorSubTree(0) == probeSubTree);
+        }
     }
-
+    
     private ILogicalExpression createSelectCondition(List<Mutable<ILogicalExpression>> predList) {
         if (predList.size() > 1) {
             IFunctionInfo finfo = AsterixBuiltinFunctions.getAsterixFunctionInfo(AlgebricksBuiltinFunctions.AND);
diff --git a/asterix-algebra/src/main/java/edu/uci/ics/asterix/optimizer/rules/am/BTreeJobGenParams.java b/asterix-algebra/src/main/java/edu/uci/ics/asterix/optimizer/rules/am/BTreeJobGenParams.java
index 9a735c9..8b7636b 100644
--- a/asterix-algebra/src/main/java/edu/uci/ics/asterix/optimizer/rules/am/BTreeJobGenParams.java
+++ b/asterix-algebra/src/main/java/edu/uci/ics/asterix/optimizer/rules/am/BTreeJobGenParams.java
@@ -22,13 +22,14 @@
 
     protected boolean lowKeyInclusive;
     protected boolean highKeyInclusive;
+    protected boolean isEqCondition;
 
     public BTreeJobGenParams() {
         super();
     }
 
-    public BTreeJobGenParams(String indexName, IndexType indexType, String dataverseName, String datasetName, boolean retainInput,
-            boolean requiresBroadcast) {
+    public BTreeJobGenParams(String indexName, IndexType indexType, String dataverseName, String datasetName,
+            boolean retainInput, boolean requiresBroadcast) {
         super(indexName, indexType, dataverseName, datasetName, retainInput, requiresBroadcast);
     }
 
@@ -56,12 +57,17 @@
         this.highKeyInclusive = highKeyInclusive;
     }
 
+    public void setIsEqCondition(boolean isEqConsition) {
+        this.isEqCondition = isEqConsition;
+    }
+
     public void writeToFuncArgs(List<Mutable<ILogicalExpression>> funcArgs) {
         super.writeToFuncArgs(funcArgs);
         writeVarList(lowKeyVarList, funcArgs);
         writeVarList(highKeyVarList, funcArgs);
-        writeKeyInclusive(lowKeyInclusive, funcArgs);
-        writeKeyInclusive(highKeyInclusive, funcArgs);
+        writeBoolean(lowKeyInclusive, funcArgs);
+        writeBoolean(highKeyInclusive, funcArgs);
+        writeBoolean(isEqCondition, funcArgs);
     }
 
     public void readFromFuncArgs(List<Mutable<ILogicalExpression>> funcArgs) {
@@ -71,16 +77,24 @@
         highKeyVarList = new ArrayList<LogicalVariable>();
         int nextIndex = readVarList(funcArgs, index, lowKeyVarList);
         nextIndex = readVarList(funcArgs, nextIndex, highKeyVarList);
-        readKeyInclusives(funcArgs, nextIndex);
+        nextIndex = readKeyInclusives(funcArgs, nextIndex);
+        readIsEqCondition(funcArgs, nextIndex);
     }
 
-    private void readKeyInclusives(List<Mutable<ILogicalExpression>> funcArgs, int index) {
+    private int readKeyInclusives(List<Mutable<ILogicalExpression>> funcArgs, int index) {
         lowKeyInclusive = ((ConstantExpression) funcArgs.get(index).getValue()).getValue().isTrue();
+        // Read the next function argument at index + 1.
         highKeyInclusive = ((ConstantExpression) funcArgs.get(index + 1).getValue()).getValue().isTrue();
+        // We have read two of the function arguments, so the next index is at index + 2.
+        return index + 2;
     }
 
-    private void writeKeyInclusive(boolean keyInclusive, List<Mutable<ILogicalExpression>> funcArgs) {
-        ILogicalExpression keyExpr = keyInclusive ? ConstantExpression.TRUE : ConstantExpression.FALSE;
+    private void readIsEqCondition(List<Mutable<ILogicalExpression>> funcArgs, int index) {
+        isEqCondition = ((ConstantExpression) funcArgs.get(index).getValue()).getValue().isTrue();
+    }
+
+    private void writeBoolean(boolean val, List<Mutable<ILogicalExpression>> funcArgs) {
+        ILogicalExpression keyExpr = val ? ConstantExpression.TRUE : ConstantExpression.FALSE;
         funcArgs.add(new MutableObject<ILogicalExpression>(keyExpr));
     }
 
@@ -92,6 +106,10 @@
         return highKeyVarList;
     }
 
+    public boolean isEqCondition() {
+        return isEqCondition;
+    }
+
     public boolean isLowKeyInclusive() {
         return lowKeyInclusive;
     }
diff --git a/asterix-algebra/src/main/java/edu/uci/ics/asterix/optimizer/rules/typecast/StaticTypeCastUtil.java b/asterix-algebra/src/main/java/edu/uci/ics/asterix/optimizer/rules/typecast/StaticTypeCastUtil.java
index 0c6f2ea..3ba3e96 100644
--- a/asterix-algebra/src/main/java/edu/uci/ics/asterix/optimizer/rules/typecast/StaticTypeCastUtil.java
+++ b/asterix-algebra/src/main/java/edu/uci/ics/asterix/optimizer/rules/typecast/StaticTypeCastUtil.java
@@ -26,6 +26,7 @@
 import edu.uci.ics.asterix.om.base.AString;
 import edu.uci.ics.asterix.om.constants.AsterixConstantValue;
 import edu.uci.ics.asterix.om.functions.AsterixBuiltinFunctions;
+import edu.uci.ics.asterix.om.functions.AsterixFunctionInfo;
 import edu.uci.ics.asterix.om.pointables.base.DefaultOpenFieldType;
 import edu.uci.ics.asterix.om.typecomputer.base.TypeComputerUtilities;
 import edu.uci.ics.asterix.om.types.ARecordType;
@@ -261,6 +262,7 @@
                 String reqFieldName = reqFieldNames[j];
                 IAType reqFieldType = reqFieldTypes[j];
                 if (fieldName.equals(reqFieldName)) {
+                    //type matched
                     if (fieldType.equals(reqFieldType)) {
                         fieldPermutation[j] = i;
                         openFields[i] = false;
@@ -293,6 +295,26 @@
                         }
                     }
 
+                    // match the optional type input for a non-optional field
+                    // delay that to runtime by calling the not-null function
+                    if (fieldType.getTypeTag() == ATypeTag.UNION
+                            && NonTaggedFormatUtil.isOptionalField((AUnionType) fieldType)) {
+                        IAType itemType = ((AUnionType) fieldType).getUnionList().get(
+                                NonTaggedFormatUtil.OPTIONAL_TYPE_INDEX_IN_UNION_LIST);
+                        if (reqFieldType.equals(itemType)) {
+                            fieldPermutation[j] = i;
+                            openFields[i] = false;
+                            matched = true;
+
+                            ScalarFunctionCallExpression notNullFunc = new ScalarFunctionCallExpression(
+                                    new AsterixFunctionInfo(AsterixBuiltinFunctions.NOT_NULL));
+                            notNullFunc.getArguments().add(new MutableObject<ILogicalExpression>(arg));
+                            //wrap the not null function to the original function
+                            func.getArguments().get(2 * i + 1).setValue(notNullFunc);
+                            break;
+                        }
+                    }
+
                     // match the record field: need cast
                     if (arg.getExpressionTag() == LogicalExpressionTag.FUNCTION_CALL) {
                         ScalarFunctionCallExpression scalarFunc = (ScalarFunctionCallExpression) arg;
diff --git a/asterix-algebra/src/main/java/edu/uci/ics/asterix/translator/DatasetHints.java b/asterix-algebra/src/main/java/edu/uci/ics/asterix/translator/DatasetHints.java
index 6ebdd35..0b66c30 100644
--- a/asterix-algebra/src/main/java/edu/uci/ics/asterix/translator/DatasetHints.java
+++ b/asterix-algebra/src/main/java/edu/uci/ics/asterix/translator/DatasetHints.java
@@ -53,35 +53,35 @@
         hints.add(new DatasetCardinalityHint());
         return hints;
     }
-}
 
-/**
- * Hint representing the expected number of tuples in the dataset.
- */
-class DatasetCardinalityHint implements IHint {
-    private static final String name = "CARDINALITY";
+    /**
+     * Hint representing the expected number of tuples in the dataset.
+     */
+    public static class DatasetCardinalityHint implements IHint {
+        public static final String NAME = "CARDINALITY";
 
-    public static final long DEFAULT = 1000000L;
+        public static final long DEFAULT = 1000000L;
 
-    @Override
-    public String getName() {
-        return name;
-    }
-
-    @Override
-    public Pair<Boolean, String> validateValue(String value) {
-        boolean valid = true;
-        long longValue;
-        try {
-            longValue = Long.parseLong(value);
-            if (longValue < 0) {
-                return new Pair<Boolean, String>(false, "Value must be >= 0");
-            }
-        } catch (NumberFormatException nfe) {
-            valid = false;
-            return new Pair<Boolean, String>(valid, "Inappropriate value");
+        @Override
+        public String getName() {
+            return NAME;
         }
-        return new Pair<Boolean, String>(true, null);
-    }
 
+        @Override
+        public Pair<Boolean, String> validateValue(String value) {
+            boolean valid = true;
+            long longValue;
+            try {
+                longValue = Long.parseLong(value);
+                if (longValue < 0) {
+                    return new Pair<Boolean, String>(false, "Value must be >= 0");
+                }
+            } catch (NumberFormatException nfe) {
+                valid = false;
+                return new Pair<Boolean, String>(valid, "Inappropriate value");
+            }
+            return new Pair<Boolean, String>(true, null);
+        }
+
+    }
 }
diff --git a/asterix-algebra/src/main/java/edu/uci/ics/asterix/translator/IHint.java b/asterix-algebra/src/main/java/edu/uci/ics/asterix/translator/IHint.java
index 13eb59a..1c9fd7b 100644
--- a/asterix-algebra/src/main/java/edu/uci/ics/asterix/translator/IHint.java
+++ b/asterix-algebra/src/main/java/edu/uci/ics/asterix/translator/IHint.java
@@ -33,7 +33,9 @@
      * 
      * @param value
      *            the value associated with the hint.
-     * @return
+     * @return a Pair with
+     *         first element as a boolean that represents the validation result.
+     *         second element as the error message if the validation result is false
      */
     public Pair<Boolean, String> validateValue(String value);
 
diff --git a/asterix-app/data/temporal/temporalData.json b/asterix-app/data/temporal/temporalData.json
new file mode 100644
index 0000000..520fd4b
--- /dev/null
+++ b/asterix-app/data/temporal/temporalData.json
@@ -0,0 +1,3 @@
+{"id": "001", "dateField": date("-2012-12-12"), "dateFieldPlus": date("0990-01-01"), "timeField": time("23:49:12.39Z"), "timeFieldPlus": time("03:23:12.2"), "datetimeField": datetime("2012-12-12T00:00:00.001"), "datetimeFieldPlus": datetime("-00130810T221015398"), "durationField": duration("P20Y19DT3H74M23.34S"), "durationFieldPlus": duration("-P2MT4M300.68S"), "intervalField": dtinterval("2012-12-12T00:00:00.001,20130810T221015398") }
+{"id": "002", "datetimeField": datetime("19201220T232918478") }
+{"id": "003", "intervalPlus": tinterval("19:23:32.328Z,23:20:20") }
\ No newline at end of file
diff --git a/asterix-app/data/temporal/temporalData.txt b/asterix-app/data/temporal/temporalData.txt
new file mode 100644
index 0000000..9ce94f5
--- /dev/null
+++ b/asterix-app/data/temporal/temporalData.txt
@@ -0,0 +1,4 @@
+001|-2012-12-12|23:49:12.39Z|3827-12-12T11:43:29.329|P20Y19DT3H74M23.34S
+002|1993-12-12|03:32:00|-2012-12-12T05:00:23.071|P20Y19D
+003|1839-03-12|12:30:49.382|1012-06-12T00:37:00|PT3H74M23.34S
+999|0003-11-02|23:19:32.382Z|2012-12-12T00:00:00.001|P20YT300H9.34S
diff --git a/asterix-app/pom.xml b/asterix-app/pom.xml
index b47aadc..2f80c30 100644
--- a/asterix-app/pom.xml
+++ b/asterix-app/pom.xml
@@ -129,17 +129,14 @@
 		<dependency>
 			<groupId>edu.uci.ics.hyracks</groupId>
 			<artifactId>hyracks-control-cc</artifactId>
-			<version>0.2.2-SNAPSHOT</version>
 		</dependency>
 		<dependency>
 			<groupId>edu.uci.ics.hyracks</groupId>
 			<artifactId>hyracks-control-nc</artifactId>
-			<version>0.2.2-SNAPSHOT</version>
 		</dependency>
 		<dependency>
 			<groupId>edu.uci.ics.hyracks</groupId>
-			<artifactId>hyracks-algebricks-compiler</artifactId>
-			<version>0.2.2-SNAPSHOT</version>
+			<artifactId>algebricks-compiler</artifactId>
 		</dependency>
 		<dependency>
 			<groupId>edu.uci.ics.asterix</groupId>
diff --git a/asterix-app/src/main/java/edu/uci/ics/asterix/api/aqlj/client/ADMCursor.java b/asterix-app/src/main/java/edu/uci/ics/asterix/api/aqlj/client/ADMCursor.java
index cad8760..a48feba 100644
--- a/asterix-app/src/main/java/edu/uci/ics/asterix/api/aqlj/client/ADMCursor.java
+++ b/asterix-app/src/main/java/edu/uci/ics/asterix/api/aqlj/client/ADMCursor.java
@@ -28,6 +28,7 @@
 import edu.uci.ics.asterix.om.base.AInt32;
 import edu.uci.ics.asterix.om.base.AInt64;
 import edu.uci.ics.asterix.om.base.AInt8;
+import edu.uci.ics.asterix.om.base.AInterval;
 import edu.uci.ics.asterix.om.base.ALine;
 import edu.uci.ics.asterix.om.base.APoint;
 import edu.uci.ics.asterix.om.base.APoint3D;
@@ -228,6 +229,19 @@
     }
 
     @Override
+    public AInterval getInterval() throws AQLJException {
+        checkTypeTag(currentObject, ATypeTag.INTERVAL);
+        return ((AInterval) currentObject);
+    }
+
+    @Override
+    public AInterval getInterval(String field) throws AQLJException {
+        IAObject o = getObjectByField(field);
+        checkTypeTag(o, ATypeTag.INTERVAL);
+        return (AInterval) o;
+    }
+
+    @Override
     public AFloat getFloat() throws AQLJException {
         checkTypeTag(currentObject, ATypeTag.FLOAT);
         return ((AFloat) currentObject);
diff --git a/asterix-app/src/main/java/edu/uci/ics/asterix/api/aqlj/client/IADMCursor.java b/asterix-app/src/main/java/edu/uci/ics/asterix/api/aqlj/client/IADMCursor.java
index a7500c9..51318a1 100644
--- a/asterix-app/src/main/java/edu/uci/ics/asterix/api/aqlj/client/IADMCursor.java
+++ b/asterix-app/src/main/java/edu/uci/ics/asterix/api/aqlj/client/IADMCursor.java
@@ -28,6 +28,7 @@
 import edu.uci.ics.asterix.om.base.AInt32;
 import edu.uci.ics.asterix.om.base.AInt64;
 import edu.uci.ics.asterix.om.base.AInt8;
+import edu.uci.ics.asterix.om.base.AInterval;
 import edu.uci.ics.asterix.om.base.ALine;
 import edu.uci.ics.asterix.om.base.APoint;
 import edu.uci.ics.asterix.om.base.APoint3D;
@@ -79,6 +80,10 @@
 
     public ADuration getDuration(String field) throws AQLJException;
 
+    public AInterval getInterval() throws AQLJException;
+
+    public AInterval getInterval(String field) throws AQLJException;
+
     public AFloat getFloat() throws AQLJException;
 
     public AFloat getFloat(String field) throws AQLJException;
diff --git a/asterix-app/src/main/java/edu/uci/ics/asterix/api/common/APIFramework.java b/asterix-app/src/main/java/edu/uci/ics/asterix/api/common/APIFramework.java
index ac87c4b..1eb37cd 100644
--- a/asterix-app/src/main/java/edu/uci/ics/asterix/api/common/APIFramework.java
+++ b/asterix-app/src/main/java/edu/uci/ics/asterix/api/common/APIFramework.java
@@ -149,8 +149,9 @@
         HTML
     }
 
-    public static Pair<Query, Integer> reWriteQuery(List<FunctionDecl> declaredFunctions, AqlMetadataProvider metadataProvider,
-            Query q, SessionConfig pc, PrintWriter out, DisplayFormat pdf) throws AsterixException {
+    public static Pair<Query, Integer> reWriteQuery(List<FunctionDecl> declaredFunctions,
+            AqlMetadataProvider metadataProvider, Query q, SessionConfig pc, PrintWriter out, DisplayFormat pdf)
+            throws AsterixException {
         if (!pc.isPrintPhysicalOpsOnly() && pc.isPrintExprParam()) {
             out.println();
             switch (pdf) {
@@ -279,7 +280,7 @@
 
         OptimizationConfUtil.getPhysicalOptimizationConfig().setFrameSize(frameSize);
         builder.setPhysicalOptimizationConfig(OptimizationConfUtil.getPhysicalOptimizationConfig());
-        
+
         ICompiler compiler = compilerFactory.createCompiler(plan, queryMetadataProvider, t.getVarCounter());
         if (pc.isOptimize()) {
             compiler.optimize();
@@ -328,6 +329,7 @@
         builder.setExpressionRuntimeProvider(new LogicalExpressionJobGenToExpressionRuntimeProviderAdapter(
                 AqlLogicalExpressionJobGen.INSTANCE));
         builder.setHashFunctionFactoryProvider(format.getBinaryHashFunctionFactoryProvider());
+        builder.setHashFunctionFamilyProvider(format.getBinaryHashFunctionFamilyProvider());
         builder.setNullWriterFactory(format.getNullWriterFactory());
         builder.setPrinterProvider(format.getPrinterFactoryProvider());
         builder.setSerializerDeserializerProvider(format.getSerdeProvider());
diff --git a/asterix-app/src/test/resources/metadata/results/basic/meta17.adm b/asterix-app/src/test/resources/metadata/results/basic/meta17.adm
index f3b7fc0..2de89a6 100644
--- a/asterix-app/src/test/resources/metadata/results/basic/meta17.adm
+++ b/asterix-app/src/test/resources/metadata/results/basic/meta17.adm
@@ -1,59 +1,60 @@
-{ "DataverseName": "Metadata", "DatatypeName": "DatasetRecordType", "Derived": { "Tag": "RECORD", "IsAnonymous": false, "EnumValues": null, "Record": { "IsOpen": true, "Fields": [ { "FieldName": "DataverseName", "FieldType": "string" }, { "FieldName": "DatasetName", "FieldType": "string" }, { "FieldName": "DataTypeName", "FieldType": "string" }, { "FieldName": "DatasetType", "FieldType": "string" }, { "FieldName": "InternalDetails", "FieldType": "Field_InternalDetails_in_DatasetRecordType" }, { "FieldName": "ExternalDetails", "FieldType": "Field_ExternalDetails_in_DatasetRecordType" }, { "FieldName": "FeedDetails", "FieldType": "Field_FeedDetails_in_DatasetRecordType" }, { "FieldName": "Hints", "FieldType": "Field_Hints_in_DatasetRecordType" }, { "FieldName": "Timestamp", "FieldType": "string" } ] }, "Union": null, "UnorderedList": null, "OrderedList": null }, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "DatasourceAdapterRecordType", "Derived": { "Tag": "RECORD", "IsAnonymous": false, "EnumValues": null, "Record": { "IsOpen": true, "Fields": [ { "FieldName": "DataverseName", "FieldType": "string" }, { "FieldName": "Name", "FieldType": "string" }, { "FieldName": "Classname", "FieldType": "string" }, { "FieldName": "Type", "FieldType": "string" }, { "FieldName": "Timestamp", "FieldType": "string" } ] }, "Union": null, "UnorderedList": null, "OrderedList": null }, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "DatatypeRecordType", "Derived": { "Tag": "RECORD", "IsAnonymous": false, "EnumValues": null, "Record": { "IsOpen": true, "Fields": [ { "FieldName": "DataverseName", "FieldType": "string" }, { "FieldName": "DatatypeName", "FieldType": "string" }, { "FieldName": "Derived", "FieldType": "Field_Derived_in_DatatypeRecordType" }, { "FieldName": "Timestamp", "FieldType": "string" } ] }, "Union": null, "UnorderedList": null, "OrderedList": null }, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "DataverseRecordType", "Derived": { "Tag": "RECORD", "IsAnonymous": false, "EnumValues": null, "Record": { "IsOpen": true, "Fields": [ { "FieldName": "DataverseName", "FieldType": "string" }, { "FieldName": "DataFormat", "FieldType": "string" }, { "FieldName": "Timestamp", "FieldType": "string" } ] }, "Union": null, "UnorderedList": null, "OrderedList": null }, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "Field_Derived_in_DatatypeRecordType", "Derived": { "Tag": "UNION", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": [ "null", "Type_#1_UnionType_Field_Derived_in_DatatypeRecordType" ], "UnorderedList": null, "OrderedList": null }, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "Field_EnumValues_in_Type_#1_UnionType_Field_Derived_in_DatatypeRecordType", "Derived": { "Tag": "UNION", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": [ "null", "Type_#1_UnionType_Field_EnumValues_in_Type_#1_UnionType_Field_Derived_in_DatatypeRecordType" ], "UnorderedList": null, "OrderedList": null }, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "Field_ExternalDetails_in_DatasetRecordType", "Derived": { "Tag": "UNION", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": [ "null", "Type_#1_UnionType_Field_ExternalDetails_in_DatasetRecordType" ], "UnorderedList": null, "OrderedList": null }, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "Field_FeedDetails_in_DatasetRecordType", "Derived": { "Tag": "UNION", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": [ "null", "Type_#1_UnionType_Field_FeedDetails_in_DatasetRecordType" ], "UnorderedList": null, "OrderedList": null }, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "Field_Fields_in_Type_#1_UnionType_Field_Record_in_Type_#1_UnionType_Field_Derived_in_DatatypeRecordType", "Derived": { "Tag": "ORDEREDLIST", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": null, "UnorderedList": null, "OrderedList": "Field_Fields_in_Type_#1_UnionType_Field_Record_in_Type_#1_UnionType_Field_Derived_in_DatatypeRecordType_ItemType" }, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "Field_Fields_in_Type_#1_UnionType_Field_Record_in_Type_#1_UnionType_Field_Derived_in_DatatypeRecordType_ItemType", "Derived": { "Tag": "RECORD", "IsAnonymous": true, "EnumValues": null, "Record": { "IsOpen": true, "Fields": [ { "FieldName": "FieldName", "FieldType": "string" }, { "FieldName": "FieldType", "FieldType": "string" } ] }, "Union": null, "UnorderedList": null, "OrderedList": null }, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "Field_Function_in_Type_#1_UnionType_Field_FeedDetails_in_DatasetRecordType", "Derived": { "Tag": "UNION", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": [ "null", "string" ], "UnorderedList": null, "OrderedList": null }, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "Field_Hints_in_DatasetRecordType", "Derived": { "Tag": "UNORDEREDLIST", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": null, "UnorderedList": "Field_Hints_in_DatasetRecordType_ItemType", "OrderedList": null }, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "Field_Hints_in_DatasetRecordType_ItemType", "Derived": { "Tag": "RECORD", "IsAnonymous": true, "EnumValues": null, "Record": { "IsOpen": true, "Fields": [ { "FieldName": "Name", "FieldType": "string" }, { "FieldName": "Value", "FieldType": "string" } ] }, "Union": null, "UnorderedList": null, "OrderedList": null }, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "Field_InternalDetails_in_DatasetRecordType", "Derived": { "Tag": "UNION", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": [ "null", "Type_#1_UnionType_Field_InternalDetails_in_DatasetRecordType" ], "UnorderedList": null, "OrderedList": null }, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "Field_NodeNames_in_NodeGroupRecordType", "Derived": { "Tag": "UNORDEREDLIST", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": null, "UnorderedList": "string", "OrderedList": null }, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "Field_OrderedList_in_Type_#1_UnionType_Field_Derived_in_DatatypeRecordType", "Derived": { "Tag": "UNION", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": [ "null", "string" ], "UnorderedList": null, "OrderedList": null }, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "Field_Params_in_FunctionRecordType", "Derived": { "Tag": "ORDEREDLIST", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": null, "UnorderedList": null, "OrderedList": "string" }, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "Field_PartitioningKey_in_Type_#1_UnionType_Field_FeedDetails_in_DatasetRecordType", "Derived": { "Tag": "ORDEREDLIST", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": null, "UnorderedList": null, "OrderedList": "string" }, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "Field_PartitioningKey_in_Type_#1_UnionType_Field_InternalDetails_in_DatasetRecordType", "Derived": { "Tag": "ORDEREDLIST", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": null, "UnorderedList": null, "OrderedList": "string" }, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "Field_PrimaryKey_in_Type_#1_UnionType_Field_FeedDetails_in_DatasetRecordType", "Derived": { "Tag": "ORDEREDLIST", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": null, "UnorderedList": null, "OrderedList": "string" }, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "Field_PrimaryKey_in_Type_#1_UnionType_Field_InternalDetails_in_DatasetRecordType", "Derived": { "Tag": "ORDEREDLIST", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": null, "UnorderedList": null, "OrderedList": "string" }, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "Field_Properties_in_Type_#1_UnionType_Field_ExternalDetails_in_DatasetRecordType", "Derived": { "Tag": "ORDEREDLIST", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": null, "UnorderedList": null, "OrderedList": "Field_Properties_in_Type_#1_UnionType_Field_ExternalDetails_in_DatasetRecordType_ItemType" }, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "Field_Properties_in_Type_#1_UnionType_Field_ExternalDetails_in_DatasetRecordType_ItemType", "Derived": { "Tag": "RECORD", "IsAnonymous": true, "EnumValues": null, "Record": { "IsOpen": true, "Fields": [ { "FieldName": "Name", "FieldType": "string" }, { "FieldName": "Value", "FieldType": "string" } ] }, "Union": null, "UnorderedList": null, "OrderedList": null }, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "Field_Properties_in_Type_#1_UnionType_Field_FeedDetails_in_DatasetRecordType", "Derived": { "Tag": "ORDEREDLIST", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": null, "UnorderedList": null, "OrderedList": "Field_Properties_in_Type_#1_UnionType_Field_FeedDetails_in_DatasetRecordType_ItemType" }, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "Field_Properties_in_Type_#1_UnionType_Field_FeedDetails_in_DatasetRecordType_ItemType", "Derived": { "Tag": "RECORD", "IsAnonymous": true, "EnumValues": null, "Record": { "IsOpen": true, "Fields": [ { "FieldName": "Name", "FieldType": "string" }, { "FieldName": "Value", "FieldType": "string" } ] }, "Union": null, "UnorderedList": null, "OrderedList": null }, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "Field_Record_in_Type_#1_UnionType_Field_Derived_in_DatatypeRecordType", "Derived": { "Tag": "UNION", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": [ "null", "Type_#1_UnionType_Field_Record_in_Type_#1_UnionType_Field_Derived_in_DatatypeRecordType" ], "UnorderedList": null, "OrderedList": null }, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "Field_SearchKey_in_IndexRecordType", "Derived": { "Tag": "ORDEREDLIST", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": null, "UnorderedList": null, "OrderedList": "string" }, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "Field_Union_in_Type_#1_UnionType_Field_Derived_in_DatatypeRecordType", "Derived": { "Tag": "UNION", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": [ "null", "Type_#1_UnionType_Field_Union_in_Type_#1_UnionType_Field_Derived_in_DatatypeRecordType" ], "UnorderedList": null, "OrderedList": null }, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "Field_UnorderedList_in_Type_#1_UnionType_Field_Derived_in_DatatypeRecordType", "Derived": { "Tag": "UNION", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": [ "null", "string" ], "UnorderedList": null, "OrderedList": null }, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "FunctionRecordType", "Derived": { "Tag": "RECORD", "IsAnonymous": false, "EnumValues": null, "Record": { "IsOpen": true, "Fields": [ { "FieldName": "DataverseName", "FieldType": "string" }, { "FieldName": "Name", "FieldType": "string" }, { "FieldName": "Arity", "FieldType": "string" }, { "FieldName": "Params", "FieldType": "Field_Params_in_FunctionRecordType" }, { "FieldName": "ReturnType", "FieldType": "string" }, { "FieldName": "Definition", "FieldType": "string" }, { "FieldName": "Language", "FieldType": "string" }, { "FieldName": "Kind", "FieldType": "string" } ] }, "Union": null, "UnorderedList": null, "OrderedList": null }, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "IndexRecordType", "Derived": { "Tag": "RECORD", "IsAnonymous": false, "EnumValues": null, "Record": { "IsOpen": true, "Fields": [ { "FieldName": "DataverseName", "FieldType": "string" }, { "FieldName": "DatasetName", "FieldType": "string" }, { "FieldName": "IndexName", "FieldType": "string" }, { "FieldName": "IndexStructure", "FieldType": "string" }, { "FieldName": "SearchKey", "FieldType": "Field_SearchKey_in_IndexRecordType" }, { "FieldName": "IsPrimary", "FieldType": "boolean" }, { "FieldName": "Timestamp", "FieldType": "string" } ] }, "Union": null, "UnorderedList": null, "OrderedList": null }, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "NodeGroupRecordType", "Derived": { "Tag": "RECORD", "IsAnonymous": false, "EnumValues": null, "Record": { "IsOpen": true, "Fields": [ { "FieldName": "GroupName", "FieldType": "string" }, { "FieldName": "NodeNames", "FieldType": "Field_NodeNames_in_NodeGroupRecordType" }, { "FieldName": "Timestamp", "FieldType": "string" } ] }, "Union": null, "UnorderedList": null, "OrderedList": null }, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "NodeRecordType", "Derived": { "Tag": "RECORD", "IsAnonymous": false, "EnumValues": null, "Record": { "IsOpen": true, "Fields": [ { "FieldName": "NodeName", "FieldType": "string" }, { "FieldName": "NumberOfCores", "FieldType": "int32" }, { "FieldName": "WorkingMemorySize", "FieldType": "int32" } ] }, "Union": null, "UnorderedList": null, "OrderedList": null }, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "Type_#1_UnionType_Field_Derived_in_DatatypeRecordType", "Derived": { "Tag": "RECORD", "IsAnonymous": true, "EnumValues": null, "Record": { "IsOpen": true, "Fields": [ { "FieldName": "Tag", "FieldType": "string" }, { "FieldName": "IsAnonymous", "FieldType": "boolean" }, { "FieldName": "EnumValues", "FieldType": "Field_EnumValues_in_Type_#1_UnionType_Field_Derived_in_DatatypeRecordType" }, { "FieldName": "Record", "FieldType": "Field_Record_in_Type_#1_UnionType_Field_Derived_in_DatatypeRecordType" }, { "FieldName": "Union", "FieldType": "Field_Union_in_Type_#1_UnionType_Field_Derived_in_DatatypeRecordType" }, { "FieldName": "UnorderedList", "FieldType": "Field_UnorderedList_in_Type_#1_UnionType_Field_Derived_in_DatatypeRecordType" }, { "FieldName": "OrderedList", "FieldType": "Field_OrderedList_in_Type_#1_UnionType_Field_Derived_in_DatatypeRecordType" } ] }, "Union": null, "UnorderedList": null, "OrderedList": null }, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "Type_#1_UnionType_Field_EnumValues_in_Type_#1_UnionType_Field_Derived_in_DatatypeRecordType", "Derived": { "Tag": "ORDEREDLIST", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": null, "UnorderedList": null, "OrderedList": "string" }, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "Type_#1_UnionType_Field_ExternalDetails_in_DatasetRecordType", "Derived": { "Tag": "RECORD", "IsAnonymous": true, "EnumValues": null, "Record": { "IsOpen": true, "Fields": [ { "FieldName": "DatasourceAdapter", "FieldType": "string" }, { "FieldName": "Properties", "FieldType": "Field_Properties_in_Type_#1_UnionType_Field_ExternalDetails_in_DatasetRecordType" } ] }, "Union": null, "UnorderedList": null, "OrderedList": null }, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "Type_#1_UnionType_Field_FeedDetails_in_DatasetRecordType", "Derived": { "Tag": "RECORD", "IsAnonymous": true, "EnumValues": null, "Record": { "IsOpen": true, "Fields": [ { "FieldName": "FileStructure", "FieldType": "string" }, { "FieldName": "PartitioningStrategy", "FieldType": "string" }, { "FieldName": "PartitioningKey", "FieldType": "Field_PartitioningKey_in_Type_#1_UnionType_Field_FeedDetails_in_DatasetRecordType" }, { "FieldName": "PrimaryKey", "FieldType": "Field_PrimaryKey_in_Type_#1_UnionType_Field_FeedDetails_in_DatasetRecordType" }, { "FieldName": "GroupName", "FieldType": "string" }, { "FieldName": "DatasourceAdapter", "FieldType": "string" }, { "FieldName": "Properties", "FieldType": "Field_Properties_in_Type_#1_UnionType_Field_FeedDetails_in_DatasetRecordType" }, { "FieldName": "Function", "FieldType": "Field_Function_in_Type_#1_UnionType_Field_FeedDetails_in_DatasetRecordType" }, { "FieldName": "Status", "FieldType": "string" } ] }, "Union": null, "UnorderedList": null, "OrderedList": null }, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "Type_#1_UnionType_Field_InternalDetails_in_DatasetRecordType", "Derived": { "Tag": "RECORD", "IsAnonymous": true, "EnumValues": null, "Record": { "IsOpen": true, "Fields": [ { "FieldName": "FileStructure", "FieldType": "string" }, { "FieldName": "PartitioningStrategy", "FieldType": "string" }, { "FieldName": "PartitioningKey", "FieldType": "Field_PartitioningKey_in_Type_#1_UnionType_Field_InternalDetails_in_DatasetRecordType" }, { "FieldName": "PrimaryKey", "FieldType": "Field_PrimaryKey_in_Type_#1_UnionType_Field_InternalDetails_in_DatasetRecordType" }, { "FieldName": "GroupName", "FieldType": "string" } ] }, "Union": null, "UnorderedList": null, "OrderedList": null }, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "Type_#1_UnionType_Field_Record_in_Type_#1_UnionType_Field_Derived_in_DatatypeRecordType", "Derived": { "Tag": "RECORD", "IsAnonymous": true, "EnumValues": null, "Record": { "IsOpen": true, "Fields": [ { "FieldName": "IsOpen", "FieldType": "boolean" }, { "FieldName": "Fields", "FieldType": "Field_Fields_in_Type_#1_UnionType_Field_Record_in_Type_#1_UnionType_Field_Derived_in_DatatypeRecordType" } ] }, "Union": null, "UnorderedList": null, "OrderedList": null }, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "Type_#1_UnionType_Field_Union_in_Type_#1_UnionType_Field_Derived_in_DatatypeRecordType", "Derived": { "Tag": "ORDEREDLIST", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": null, "UnorderedList": null, "OrderedList": "string" }, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "boolean", "Derived": null, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "circle", "Derived": null, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "date", "Derived": null, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "datetime", "Derived": null, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "double", "Derived": null, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "duration", "Derived": null, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "float", "Derived": null, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "int16", "Derived": null, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "int32", "Derived": null, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "int64", "Derived": null, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "int8", "Derived": null, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "line", "Derived": null, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "null", "Derived": null, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "point", "Derived": null, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "point3d", "Derived": null, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "polygon", "Derived": null, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "rectangle", "Derived": null, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "string", "Derived": null, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
-{ "DataverseName": "Metadata", "DatatypeName": "time", "Derived": null, "Timestamp": "Tue Jan 29 18:54:03 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "DatasetRecordType", "Derived": { "Tag": "RECORD", "IsAnonymous": false, "EnumValues": null, "Record": { "IsOpen": true, "Fields": [ { "FieldName": "DataverseName", "FieldType": "string" }, { "FieldName": "DatasetName", "FieldType": "string" }, { "FieldName": "DataTypeName", "FieldType": "string" }, { "FieldName": "DatasetType", "FieldType": "string" }, { "FieldName": "InternalDetails", "FieldType": "Field_InternalDetails_in_DatasetRecordType" }, { "FieldName": "ExternalDetails", "FieldType": "Field_ExternalDetails_in_DatasetRecordType" }, { "FieldName": "FeedDetails", "FieldType": "Field_FeedDetails_in_DatasetRecordType" }, { "FieldName": "Hints", "FieldType": "Field_Hints_in_DatasetRecordType" }, { "FieldName": "Timestamp", "FieldType": "string" } ] }, "Union": null, "UnorderedList": null, "OrderedList": null }, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "DatasourceAdapterRecordType", "Derived": { "Tag": "RECORD", "IsAnonymous": false, "EnumValues": null, "Record": { "IsOpen": true, "Fields": [ { "FieldName": "DataverseName", "FieldType": "string" }, { "FieldName": "Name", "FieldType": "string" }, { "FieldName": "Classname", "FieldType": "string" }, { "FieldName": "Type", "FieldType": "string" }, { "FieldName": "Timestamp", "FieldType": "string" } ] }, "Union": null, "UnorderedList": null, "OrderedList": null }, "Timestamp": "Fri Feb 08 15:49:30 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "DatatypeRecordType", "Derived": { "Tag": "RECORD", "IsAnonymous": false, "EnumValues": null, "Record": { "IsOpen": true, "Fields": [ { "FieldName": "DataverseName", "FieldType": "string" }, { "FieldName": "DatatypeName", "FieldType": "string" }, { "FieldName": "Derived", "FieldType": "Field_Derived_in_DatatypeRecordType" }, { "FieldName": "Timestamp", "FieldType": "string" } ] }, "Union": null, "UnorderedList": null, "OrderedList": null }, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "DataverseRecordType", "Derived": { "Tag": "RECORD", "IsAnonymous": false, "EnumValues": null, "Record": { "IsOpen": true, "Fields": [ { "FieldName": "DataverseName", "FieldType": "string" }, { "FieldName": "DataFormat", "FieldType": "string" }, { "FieldName": "Timestamp", "FieldType": "string" } ] }, "Union": null, "UnorderedList": null, "OrderedList": null }, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "Field_Derived_in_DatatypeRecordType", "Derived": { "Tag": "UNION", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": [ "null", "Type_#1_UnionType_Field_Derived_in_DatatypeRecordType" ], "UnorderedList": null, "OrderedList": null }, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "Field_EnumValues_in_Type_#1_UnionType_Field_Derived_in_DatatypeRecordType", "Derived": { "Tag": "UNION", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": [ "null", "Type_#1_UnionType_Field_EnumValues_in_Type_#1_UnionType_Field_Derived_in_DatatypeRecordType" ], "UnorderedList": null, "OrderedList": null }, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "Field_ExternalDetails_in_DatasetRecordType", "Derived": { "Tag": "UNION", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": [ "null", "Type_#1_UnionType_Field_ExternalDetails_in_DatasetRecordType" ], "UnorderedList": null, "OrderedList": null }, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "Field_FeedDetails_in_DatasetRecordType", "Derived": { "Tag": "UNION", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": [ "null", "Type_#1_UnionType_Field_FeedDetails_in_DatasetRecordType" ], "UnorderedList": null, "OrderedList": null }, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "Field_Fields_in_Type_#1_UnionType_Field_Record_in_Type_#1_UnionType_Field_Derived_in_DatatypeRecordType", "Derived": { "Tag": "ORDEREDLIST", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": null, "UnorderedList": null, "OrderedList": "Field_Fields_in_Type_#1_UnionType_Field_Record_in_Type_#1_UnionType_Field_Derived_in_DatatypeRecordType_ItemType" }, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "Field_Fields_in_Type_#1_UnionType_Field_Record_in_Type_#1_UnionType_Field_Derived_in_DatatypeRecordType_ItemType", "Derived": { "Tag": "RECORD", "IsAnonymous": true, "EnumValues": null, "Record": { "IsOpen": true, "Fields": [ { "FieldName": "FieldName", "FieldType": "string" }, { "FieldName": "FieldType", "FieldType": "string" } ] }, "Union": null, "UnorderedList": null, "OrderedList": null }, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "Field_Function_in_Type_#1_UnionType_Field_FeedDetails_in_DatasetRecordType", "Derived": { "Tag": "UNION", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": [ "null", "string" ], "UnorderedList": null, "OrderedList": null }, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "Field_Hints_in_DatasetRecordType", "Derived": { "Tag": "UNORDEREDLIST", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": null, "UnorderedList": "Field_Hints_in_DatasetRecordType_ItemType", "OrderedList": null }, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "Field_Hints_in_DatasetRecordType_ItemType", "Derived": { "Tag": "RECORD", "IsAnonymous": true, "EnumValues": null, "Record": { "IsOpen": true, "Fields": [ { "FieldName": "Name", "FieldType": "string" }, { "FieldName": "Value", "FieldType": "string" } ] }, "Union": null, "UnorderedList": null, "OrderedList": null }, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "Field_InternalDetails_in_DatasetRecordType", "Derived": { "Tag": "UNION", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": [ "null", "Type_#1_UnionType_Field_InternalDetails_in_DatasetRecordType" ], "UnorderedList": null, "OrderedList": null }, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "Field_NodeNames_in_NodeGroupRecordType", "Derived": { "Tag": "UNORDEREDLIST", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": null, "UnorderedList": "string", "OrderedList": null }, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "Field_OrderedList_in_Type_#1_UnionType_Field_Derived_in_DatatypeRecordType", "Derived": { "Tag": "UNION", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": [ "null", "string" ], "UnorderedList": null, "OrderedList": null }, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "Field_Params_in_FunctionRecordType", "Derived": { "Tag": "ORDEREDLIST", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": null, "UnorderedList": null, "OrderedList": "string" }, "Timestamp": "Fri Feb 08 15:49:30 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "Field_PartitioningKey_in_Type_#1_UnionType_Field_FeedDetails_in_DatasetRecordType", "Derived": { "Tag": "ORDEREDLIST", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": null, "UnorderedList": null, "OrderedList": "string" }, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "Field_PartitioningKey_in_Type_#1_UnionType_Field_InternalDetails_in_DatasetRecordType", "Derived": { "Tag": "ORDEREDLIST", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": null, "UnorderedList": null, "OrderedList": "string" }, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "Field_PrimaryKey_in_Type_#1_UnionType_Field_FeedDetails_in_DatasetRecordType", "Derived": { "Tag": "ORDEREDLIST", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": null, "UnorderedList": null, "OrderedList": "string" }, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "Field_PrimaryKey_in_Type_#1_UnionType_Field_InternalDetails_in_DatasetRecordType", "Derived": { "Tag": "ORDEREDLIST", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": null, "UnorderedList": null, "OrderedList": "string" }, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "Field_Properties_in_Type_#1_UnionType_Field_ExternalDetails_in_DatasetRecordType", "Derived": { "Tag": "ORDEREDLIST", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": null, "UnorderedList": null, "OrderedList": "Field_Properties_in_Type_#1_UnionType_Field_ExternalDetails_in_DatasetRecordType_ItemType" }, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "Field_Properties_in_Type_#1_UnionType_Field_ExternalDetails_in_DatasetRecordType_ItemType", "Derived": { "Tag": "RECORD", "IsAnonymous": true, "EnumValues": null, "Record": { "IsOpen": true, "Fields": [ { "FieldName": "Name", "FieldType": "string" }, { "FieldName": "Value", "FieldType": "string" } ] }, "Union": null, "UnorderedList": null, "OrderedList": null }, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "Field_Properties_in_Type_#1_UnionType_Field_FeedDetails_in_DatasetRecordType", "Derived": { "Tag": "ORDEREDLIST", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": null, "UnorderedList": null, "OrderedList": "Field_Properties_in_Type_#1_UnionType_Field_FeedDetails_in_DatasetRecordType_ItemType" }, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "Field_Properties_in_Type_#1_UnionType_Field_FeedDetails_in_DatasetRecordType_ItemType", "Derived": { "Tag": "RECORD", "IsAnonymous": true, "EnumValues": null, "Record": { "IsOpen": true, "Fields": [ { "FieldName": "Name", "FieldType": "string" }, { "FieldName": "Value", "FieldType": "string" } ] }, "Union": null, "UnorderedList": null, "OrderedList": null }, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "Field_Record_in_Type_#1_UnionType_Field_Derived_in_DatatypeRecordType", "Derived": { "Tag": "UNION", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": [ "null", "Type_#1_UnionType_Field_Record_in_Type_#1_UnionType_Field_Derived_in_DatatypeRecordType" ], "UnorderedList": null, "OrderedList": null }, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "Field_SearchKey_in_IndexRecordType", "Derived": { "Tag": "ORDEREDLIST", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": null, "UnorderedList": null, "OrderedList": "string" }, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "Field_Union_in_Type_#1_UnionType_Field_Derived_in_DatatypeRecordType", "Derived": { "Tag": "UNION", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": [ "null", "Type_#1_UnionType_Field_Union_in_Type_#1_UnionType_Field_Derived_in_DatatypeRecordType" ], "UnorderedList": null, "OrderedList": null }, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "Field_UnorderedList_in_Type_#1_UnionType_Field_Derived_in_DatatypeRecordType", "Derived": { "Tag": "UNION", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": [ "null", "string" ], "UnorderedList": null, "OrderedList": null }, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "FunctionRecordType", "Derived": { "Tag": "RECORD", "IsAnonymous": false, "EnumValues": null, "Record": { "IsOpen": true, "Fields": [ { "FieldName": "DataverseName", "FieldType": "string" }, { "FieldName": "Name", "FieldType": "string" }, { "FieldName": "Arity", "FieldType": "string" }, { "FieldName": "Params", "FieldType": "Field_Params_in_FunctionRecordType" }, { "FieldName": "ReturnType", "FieldType": "string" }, { "FieldName": "Definition", "FieldType": "string" }, { "FieldName": "Language", "FieldType": "string" }, { "FieldName": "Kind", "FieldType": "string" } ] }, "Union": null, "UnorderedList": null, "OrderedList": null }, "Timestamp": "Fri Feb 08 15:49:30 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "IndexRecordType", "Derived": { "Tag": "RECORD", "IsAnonymous": false, "EnumValues": null, "Record": { "IsOpen": true, "Fields": [ { "FieldName": "DataverseName", "FieldType": "string" }, { "FieldName": "DatasetName", "FieldType": "string" }, { "FieldName": "IndexName", "FieldType": "string" }, { "FieldName": "IndexStructure", "FieldType": "string" }, { "FieldName": "SearchKey", "FieldType": "Field_SearchKey_in_IndexRecordType" }, { "FieldName": "IsPrimary", "FieldType": "boolean" }, { "FieldName": "Timestamp", "FieldType": "string" } ] }, "Union": null, "UnorderedList": null, "OrderedList": null }, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "NodeGroupRecordType", "Derived": { "Tag": "RECORD", "IsAnonymous": false, "EnumValues": null, "Record": { "IsOpen": true, "Fields": [ { "FieldName": "GroupName", "FieldType": "string" }, { "FieldName": "NodeNames", "FieldType": "Field_NodeNames_in_NodeGroupRecordType" }, { "FieldName": "Timestamp", "FieldType": "string" } ] }, "Union": null, "UnorderedList": null, "OrderedList": null }, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "NodeRecordType", "Derived": { "Tag": "RECORD", "IsAnonymous": false, "EnumValues": null, "Record": { "IsOpen": true, "Fields": [ { "FieldName": "NodeName", "FieldType": "string" }, { "FieldName": "NumberOfCores", "FieldType": "int32" }, { "FieldName": "WorkingMemorySize", "FieldType": "int32" } ] }, "Union": null, "UnorderedList": null, "OrderedList": null }, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "Type_#1_UnionType_Field_Derived_in_DatatypeRecordType", "Derived": { "Tag": "RECORD", "IsAnonymous": true, "EnumValues": null, "Record": { "IsOpen": true, "Fields": [ { "FieldName": "Tag", "FieldType": "string" }, { "FieldName": "IsAnonymous", "FieldType": "boolean" }, { "FieldName": "EnumValues", "FieldType": "Field_EnumValues_in_Type_#1_UnionType_Field_Derived_in_DatatypeRecordType" }, { "FieldName": "Record", "FieldType": "Field_Record_in_Type_#1_UnionType_Field_Derived_in_DatatypeRecordType" }, { "FieldName": "Union", "FieldType": "Field_Union_in_Type_#1_UnionType_Field_Derived_in_DatatypeRecordType" }, { "FieldName": "UnorderedList", "FieldType": "Field_UnorderedList_in_Type_#1_UnionType_Field_Derived_in_DatatypeRecordType" }, { "FieldName": "OrderedList", "FieldType": "Field_OrderedList_in_Type_#1_UnionType_Field_Derived_in_DatatypeRecordType" } ] }, "Union": null, "UnorderedList": null, "OrderedList": null }, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "Type_#1_UnionType_Field_EnumValues_in_Type_#1_UnionType_Field_Derived_in_DatatypeRecordType", "Derived": { "Tag": "ORDEREDLIST", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": null, "UnorderedList": null, "OrderedList": "string" }, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "Type_#1_UnionType_Field_ExternalDetails_in_DatasetRecordType", "Derived": { "Tag": "RECORD", "IsAnonymous": true, "EnumValues": null, "Record": { "IsOpen": true, "Fields": [ { "FieldName": "DatasourceAdapter", "FieldType": "string" }, { "FieldName": "Properties", "FieldType": "Field_Properties_in_Type_#1_UnionType_Field_ExternalDetails_in_DatasetRecordType" } ] }, "Union": null, "UnorderedList": null, "OrderedList": null }, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "Type_#1_UnionType_Field_FeedDetails_in_DatasetRecordType", "Derived": { "Tag": "RECORD", "IsAnonymous": true, "EnumValues": null, "Record": { "IsOpen": true, "Fields": [ { "FieldName": "FileStructure", "FieldType": "string" }, { "FieldName": "PartitioningStrategy", "FieldType": "string" }, { "FieldName": "PartitioningKey", "FieldType": "Field_PartitioningKey_in_Type_#1_UnionType_Field_FeedDetails_in_DatasetRecordType" }, { "FieldName": "PrimaryKey", "FieldType": "Field_PrimaryKey_in_Type_#1_UnionType_Field_FeedDetails_in_DatasetRecordType" }, { "FieldName": "GroupName", "FieldType": "string" }, { "FieldName": "DatasourceAdapter", "FieldType": "string" }, { "FieldName": "Properties", "FieldType": "Field_Properties_in_Type_#1_UnionType_Field_FeedDetails_in_DatasetRecordType" }, { "FieldName": "Function", "FieldType": "Field_Function_in_Type_#1_UnionType_Field_FeedDetails_in_DatasetRecordType" }, { "FieldName": "Status", "FieldType": "string" } ] }, "Union": null, "UnorderedList": null, "OrderedList": null }, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "Type_#1_UnionType_Field_InternalDetails_in_DatasetRecordType", "Derived": { "Tag": "RECORD", "IsAnonymous": true, "EnumValues": null, "Record": { "IsOpen": true, "Fields": [ { "FieldName": "FileStructure", "FieldType": "string" }, { "FieldName": "PartitioningStrategy", "FieldType": "string" }, { "FieldName": "PartitioningKey", "FieldType": "Field_PartitioningKey_in_Type_#1_UnionType_Field_InternalDetails_in_DatasetRecordType" }, { "FieldName": "PrimaryKey", "FieldType": "Field_PrimaryKey_in_Type_#1_UnionType_Field_InternalDetails_in_DatasetRecordType" }, { "FieldName": "GroupName", "FieldType": "string" } ] }, "Union": null, "UnorderedList": null, "OrderedList": null }, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "Type_#1_UnionType_Field_Record_in_Type_#1_UnionType_Field_Derived_in_DatatypeRecordType", "Derived": { "Tag": "RECORD", "IsAnonymous": true, "EnumValues": null, "Record": { "IsOpen": true, "Fields": [ { "FieldName": "IsOpen", "FieldType": "boolean" }, { "FieldName": "Fields", "FieldType": "Field_Fields_in_Type_#1_UnionType_Field_Record_in_Type_#1_UnionType_Field_Derived_in_DatatypeRecordType" } ] }, "Union": null, "UnorderedList": null, "OrderedList": null }, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "Type_#1_UnionType_Field_Union_in_Type_#1_UnionType_Field_Derived_in_DatatypeRecordType", "Derived": { "Tag": "ORDEREDLIST", "IsAnonymous": true, "EnumValues": null, "Record": null, "Union": null, "UnorderedList": null, "OrderedList": "string" }, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "boolean", "Derived": null, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "circle", "Derived": null, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "date", "Derived": null, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "datetime", "Derived": null, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "double", "Derived": null, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "duration", "Derived": null, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "float", "Derived": null, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "int16", "Derived": null, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "int32", "Derived": null, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "int64", "Derived": null, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "int8", "Derived": null, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "interval", "Derived": null, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "line", "Derived": null, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "null", "Derived": null, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "point", "Derived": null, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "point3d", "Derived": null, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "polygon", "Derived": null, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "rectangle", "Derived": null, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "string", "Derived": null, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
+{ "DataverseName": "Metadata", "DatatypeName": "time", "Derived": null, "Timestamp": "Fri Feb 08 15:49:29 PST 2013" }
diff --git a/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-equi-join-neg_01.aql b/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-equi-join-neg_01.aql
new file mode 100644
index 0000000..75c522b
--- /dev/null
+++ b/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-equi-join-neg_01.aql
@@ -0,0 +1,29 @@
+/*
+ * Description  : This is a negative test, mis-spelt/incorrect HINT should result in
+ *                a plan not using an indexed-nested loops join strategy. We expect a hash join. 
+ * Expected Res : Success
+ * Date         : 29th November 2012
+ */
+
+drop dataverse test1 if exists;
+create dataverse test1;
+
+create type test1.TestType as open {
+          key1: int32,
+          key2: int32,
+          fname : string,
+          lname : string
+}
+
+create dataset test1.DsOne(TestType) partitioned by key key1;
+create dataset test1.DsTwo(TestType) partitioned by key key1;
+
+// Please note content enclosed in the comment in the predicate is the HINT to the optimizer
+
+write output to nc1:"rttest/btree-index-join_primary-equi-join-neg_01.adm";
+
+for $x in dataset('test1.DsOne')
+for $y in dataset('test1.DsTwo')
+where $x.key1 /*+ index */ = $y.key2
+return $x
+
diff --git a/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-equi-join-neg_02.aql b/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-equi-join-neg_02.aql
new file mode 100644
index 0000000..4dd0d00
--- /dev/null
+++ b/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-equi-join-neg_02.aql
@@ -0,0 +1,29 @@
+/*
+ * Description  : This is a negative test, mis-spelt/incorrect HINT should result in
+ *                a plan not using an indexed-nested loops join strategy. We expect a hash join. 
+ * Expected Res : Success
+ * Date         : 29th November 2012
+ */
+
+drop dataverse test1 if exists;
+create dataverse test1;
+
+create type test1.TestType as open {
+          key1: int32,
+          key2: int32,
+          fname : string,
+          lname : string
+}
+
+create dataset test1.DsOne(TestType) partitioned by key key1;
+create dataset test1.DsTwo(TestType) partitioned by key key1;
+
+// Please note content enclosed in the comment in the predicate is the HINT to the optimizer
+
+write output to nc1:"rttest/btree-index-join_primary-equi-join-neg_02.adm";
+
+for $x in dataset('test1.DsOne')
+for $y in dataset('test1.DsTwo')
+where $x.key2 /*+ index */ = $y.key1
+return $x
+
diff --git a/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-equi-join_01.aql b/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-equi-join_01.aql
index f7f8d6c..a0877ba 100644
--- a/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-equi-join_01.aql
+++ b/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-equi-join_01.aql
@@ -1,46 +1,29 @@
 /*
- * Description    : Equi joins two datasets, Customers and Orders, based on the customer id.
- *                  Given the 'indexnl' hint we expect the join to be transformed
- *                  into an indexed nested-loop join using Customers' primary index.
- * Success        : Yes
+ * Description  : Notice the query hint to use an indexed nested-loops join plan.
+ *              : We expect a plan that hash-exchanges internal dataset DsTwo, then probes internal dataset DsOne’s primary index.
+ * Expected Res : Success
+ * Date         : 29th November 2012
  */
 
-drop dataverse test if exists;
-create dataverse test;
-use dataverse test;
+drop dataverse test1 if exists;
+create dataverse test1;
 
-create type AddressType as closed {
-  number: int32, 
-  street: string,
-  city: string
+create type test1.TestType as open {
+          key1: int32,
+          key2: int32,
+          fname : string,
+          lname : string
 }
 
-create type CustomerType as closed {
-  cid: int32, 
-  name: string,
-  age: int32?,
-  address: AddressType?,
-  lastorder: {
-    oid: int32,
-    total: float
-  }
-}
+create dataset test1.DsOne(TestType) partitioned by key key1;
+create dataset test1.DsTwo(TestType) partitioned by key key1;
 
-create type OrderType as closed {
-  oid: int32,
-  cid: int32,
-  orderstatus: string,
-  orderpriority: string,
-  clerk: string,
-  total: float
-}
-
-create dataset Customers(CustomerType) partitioned by key cid;
-create dataset Orders(OrderType) partitioned by key oid;
+// Please note content enclosed in the comment in the predicate is a HINT to the optimizer
 
 write output to nc1:"rttest/btree-index-join_primary-equi-join_01.adm";
 
-for $c in dataset('Customers')
-for $o in dataset('Orders')
-where $c.cid /*+ indexnl */ = $o.cid
-return {"customer":$c, "order": $o} 
+for $x in dataset('test1.DsOne')
+for $y in dataset('test1.DsTwo')
+where $x.key1 /*+ indexnl */ = $y.key2
+return $x
+
diff --git a/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-equi-join_02.aql b/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-equi-join_02.aql
index 9ac6140..59db20b 100644
--- a/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-equi-join_02.aql
+++ b/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-equi-join_02.aql
@@ -1,46 +1,29 @@
 /*
- * Description    : Equi joins two datasets, Customers and Orders, based on the customer id.
- *                  Given the 'indexnl' hint we expect the join to be transformed
- *                  into an indexed nested-loop join using Customers' primary index.
- * Success        : Yes
+ * Description  : Notice the query hint to use an indexed nested-loops join plan. 
+ *              : We expect a plan that hash-exchanges internal dataset DsTwo, then probes internal dataset DsOne’s primary index. 
+ * Expected Res : Success
+ * Date         : 29th November 2012
  */
 
-drop dataverse test if exists;
-create dataverse test;
-use dataverse test;
+drop dataverse test1 if exists;
+create dataverse test1;
 
-create type AddressType as closed {
-  number: int32, 
-  street: string,
-  city: string
+create type test1.TestType as open {
+          key1: int32,
+          key2: int32,
+          fname : string,
+          lname : string
 }
 
-create type CustomerType as closed {
-  cid: int32, 
-  name: string,
-  age: int32?,
-  address: AddressType?,
-  lastorder: {
-    oid: int32,
-    total: float
-  }
-}
+create dataset test1.DsOne(TestType) partitioned by key key1;
+create dataset test1.DsTwo(TestType) partitioned by key key1;
 
-create type OrderType as closed {
-  oid: int32,
-  cid: int32,
-  orderstatus: string,
-  orderpriority: string,
-  clerk: string,
-  total: float
-}
-
-create dataset Customers(CustomerType) partitioned by key cid;
-create dataset Orders(OrderType) partitioned by key oid;
+// Please note content enclosed in the comment in the predicate is a HINT to the optimizer
 
 write output to nc1:"rttest/btree-index-join_primary-equi-join_02.adm";
 
-for $o in dataset('Orders')
-for $c in dataset('Customers')
-where $o.cid /*+ indexnl */ = $c.cid 
-return {"customer":$c, "order": $o} 
+for $x in dataset('test1.DsOne')
+for $y in dataset('test1.DsTwo')
+where $x.key2 /*+ indexnl */ = $y.key1
+return $x
+
diff --git a/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-equi-join_03.aql b/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-equi-join_03.aql
index e33e2a9..d60a8ac 100644
--- a/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-equi-join_03.aql
+++ b/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-equi-join_03.aql
@@ -1,5 +1,5 @@
 /*
- * Description    : Self-equi joins a dataset, Customers, based on the customer id.
+ * Description    : Equi joins two datasets, Customers and Orders, based on the customer id.
  *                  Given the 'indexnl' hint we expect the join to be transformed
  *                  into an indexed nested-loop join using Customers' primary index.
  * Success        : Yes
@@ -26,11 +26,21 @@
   }
 }
 
+create type OrderType as closed {
+  oid: int32,
+  cid: int32,
+  orderstatus: string,
+  orderpriority: string,
+  clerk: string,
+  total: float
+}
+
 create dataset Customers(CustomerType) partitioned by key cid;
+create dataset Orders(OrderType) partitioned by key oid;
 
-write output to nc1:"rttest/btree-index-join_primary-equi-join_03.adm";
+write output to nc1:"rttest/btree-index-join_primary-equi-join_04.adm";
 
-for $c1 in dataset('Customers')
-for $c2 in dataset('Customers')
-where $c1.cid /*+ indexnl */ = $c2.cid 
-return {"customer1":$c1, "customer2":$c2} 
+for $c in dataset('Customers')
+for $o in dataset('Orders')
+where $c.cid /*+ indexnl */ = $o.cid
+return {"customer":$c, "order": $o} 
diff --git a/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-equi-join_04.aql b/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-equi-join_04.aql
new file mode 100644
index 0000000..56211e8
--- /dev/null
+++ b/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-equi-join_04.aql
@@ -0,0 +1,46 @@
+/*
+ * Description    : Equi joins two datasets, Customers and Orders, based on the customer id.
+ *                  Given the 'indexnl' hint we expect the join to be transformed
+ *                  into an indexed nested-loop join using Customers' primary index.
+ * Success        : Yes
+ */
+
+drop dataverse test if exists;
+create dataverse test;
+use dataverse test;
+
+create type AddressType as closed {
+  number: int32, 
+  street: string,
+  city: string
+}
+
+create type CustomerType as closed {
+  cid: int32, 
+  name: string,
+  age: int32?,
+  address: AddressType?,
+  lastorder: {
+    oid: int32,
+    total: float
+  }
+}
+
+create type OrderType as closed {
+  oid: int32,
+  cid: int32,
+  orderstatus: string,
+  orderpriority: string,
+  clerk: string,
+  total: float
+}
+
+create dataset Customers(CustomerType) partitioned by key cid;
+create dataset Orders(OrderType) partitioned by key oid;
+
+write output to nc1:"rttest/btree-index-join_primary-equi-join_05.adm";
+
+for $o in dataset('Orders')
+for $c in dataset('Customers')
+where $o.cid /*+ indexnl */ = $c.cid 
+return {"customer":$c, "order": $o} 
diff --git a/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-equi-join_05.aql b/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-equi-join_05.aql
new file mode 100644
index 0000000..0e6efe8
--- /dev/null
+++ b/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-equi-join_05.aql
@@ -0,0 +1,36 @@
+/*
+ * Description    : Self-equi joins a dataset, Customers, based on the customer id.
+ *                  Given the 'indexnl' hint we expect the join to be transformed
+ *                  into an indexed nested-loop join using Customers' primary index.
+ * Success        : Yes
+ */
+
+drop dataverse test if exists;
+create dataverse test;
+use dataverse test;
+
+create type AddressType as closed {
+  number: int32, 
+  street: string,
+  city: string
+}
+
+create type CustomerType as closed {
+  cid: int32, 
+  name: string,
+  age: int32?,
+  address: AddressType?,
+  lastorder: {
+    oid: int32,
+    total: float
+  }
+}
+
+create dataset Customers(CustomerType) partitioned by key cid;
+
+write output to nc1:"rttest/btree-index-join_primary-equi-join_06.adm";
+
+for $c1 in dataset('Customers')
+for $c2 in dataset('Customers')
+where $c1.cid /*+ indexnl */ = $c2.cid 
+return {"customer1":$c1, "customer2":$c2} 
diff --git a/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-ge-join_01.aql b/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-ge-join_01.aql
new file mode 100644
index 0000000..559ede2
--- /dev/null
+++ b/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-ge-join_01.aql
@@ -0,0 +1,29 @@
+/*
+ * Description  : Notice the query hint to use an indexed nested-loops join plan. 
+ *              : We expect a plan that broadcasts internal dataset DsTwo, then probes internal dataset DsOne’s primary index. 
+ * Expected Res : Success
+ * Date         : 29th November 2012
+ */
+
+drop dataverse test1 if exists;
+create dataverse test1;
+
+create type test1.TestType as open {
+          key1: int32,
+          key2: int32,
+          fname : string,
+          lname : string
+}
+
+create dataset test1.DsOne(TestType) partitioned by key key1;
+create dataset test1.DsTwo(TestType) partitioned by key key1;
+
+// Please note content enclosed in the comment in the predicate is the HINT to the optimizer
+
+write output to nc1:"rttest/btree-index-join_primary-ge-join_01.adm";
+
+for $x in dataset('test1.DsOne')
+for $y in dataset('test1.DsTwo')
+where $x.key1 /*+ indexnl */ >= $y.key2
+return $x
+
diff --git a/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-ge-join_02.aql b/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-ge-join_02.aql
new file mode 100644
index 0000000..4948b6f
--- /dev/null
+++ b/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-ge-join_02.aql
@@ -0,0 +1,29 @@
+/*
+ * Description  : Notice the query hint to use an indexed nested-loops join plan. 
+ *              : We expect a plan that broadcasts internal dataset DsTwo, then probes internal dataset DsOne’s primary index. 
+ * Expected Res : Success
+ * Date         : 29th November 2012
+ */
+
+drop dataverse test1 if exists;
+create dataverse test1;
+
+create type test1.TestType as open {
+          key1: int32,
+          key2: int32,
+          fname : string,
+          lname : string
+}
+
+create dataset test1.DsOne(TestType) partitioned by key key1;
+create dataset test1.DsTwo(TestType) partitioned by key key1;
+
+// Please note content enclosed in the comment in the predicate is the HINT to the optimizer
+
+write output to nc1:"rttest/btree-index-join_primary-ge-join_02.adm";
+
+for $x in dataset('test1.DsOne')
+for $y in dataset('test1.DsTwo')
+where $x.key2 /*+ indexnl */ <= $y.key1
+return $x
+
diff --git a/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-gt-join_01.aql b/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-gt-join_01.aql
new file mode 100644
index 0000000..f48cfa3
--- /dev/null
+++ b/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-gt-join_01.aql
@@ -0,0 +1,29 @@
+/*
+ * Description  : Notice the query hint to use an indexed nested-loops join plan. 
+ *              : We expect a plan that broadcasts internal dataset DsTwo, then probes internal dataset DsOne’s primary index. 
+ * Expected Res : Success
+ * Date         : 29th November 2012
+ */
+
+drop dataverse test1 if exists;
+create dataverse test1;
+
+create type test1.TestType as open {
+          key1: int32,
+          key2: int32,
+          fname : string,
+          lname : string
+}
+
+create dataset test1.DsOne(TestType) partitioned by key key1;
+create dataset test1.DsTwo(TestType) partitioned by key key1;
+
+// Please note content enclosed in the comment in the predicate is the HINT to the optimizer
+
+write output to nc1:"rttest/btree-index-join_primary-gt-join_01.adm";
+
+for $x in dataset('test1.DsOne')
+for $y in dataset('test1.DsTwo')
+where $x.key1 /*+ indexnl */ > $y.key2
+return $x
+
diff --git a/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-gt-join_02.aql b/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-gt-join_02.aql
new file mode 100644
index 0000000..b2f67b3
--- /dev/null
+++ b/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-gt-join_02.aql
@@ -0,0 +1,29 @@
+/*
+ * Description  : Notice the query hint to use an indexed nested-loops join plan. 
+ *              : We expect a plan that broadcasts internal dataset DsTwo, then probes internal dataset DsOne’s primary index. 
+ * Expected Res : Success
+ * Date         : 29th November 2012
+ */
+
+drop dataverse test1 if exists;
+create dataverse test1;
+
+create type test1.TestType as open {
+          key1: int32,
+          key2: int32,
+          fname : string,
+          lname : string
+}
+
+create dataset test1.DsOne(TestType) partitioned by key key1;
+create dataset test1.DsTwo(TestType) partitioned by key key1;
+
+// Please note content enclosed in the comment in the predicate is the HINT to the optimizer
+
+write output to nc1:"rttest/btree-index-join_primary-gt-join_02.adm";
+
+for $x in dataset('test1.DsOne')
+for $y in dataset('test1.DsTwo')
+where $x.key2 /*+ indexnl */ < $y.key1
+return $x
+
diff --git a/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-le-join_01.aql b/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-le-join_01.aql
new file mode 100644
index 0000000..ef4dc05
--- /dev/null
+++ b/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-le-join_01.aql
@@ -0,0 +1,29 @@
+/*
+ * Description  : Notice the query hint to use an indexed nested-loops join plan. 
+ *              : We expect a plan that broadcasts internal dataset DsTwo, then probes internal dataset DsOne’s primary index. 
+ * Expected Res : Success
+ * Date         : 29th November 2012
+ */
+
+drop dataverse test1 if exists;
+create dataverse test1;
+
+create type test1.TestType as open {
+          key1: int32,
+          key2: int32,
+          fname : string,
+          lname : string
+}
+
+create dataset test1.DsOne(TestType) partitioned by key key1;
+create dataset test1.DsTwo(TestType) partitioned by key key1;
+
+// Please note content enclosed in the comment in the predicate is the HINT to the optimizer
+
+write output to nc1:"rttest/btree-index-join_primary-le-join_01.adm";
+
+for $x in dataset('test1.DsOne')
+for $y in dataset('test1.DsTwo')
+where $x.key1 /*+ indexnl */ <= $y.key2
+return $x
+
diff --git a/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-le-join_02.aql b/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-le-join_02.aql
new file mode 100644
index 0000000..4c62ebb
--- /dev/null
+++ b/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-le-join_02.aql
@@ -0,0 +1,29 @@
+/*
+ * Description  : Notice the query hint to use an indexed nested-loops join plan. 
+ *              : We expect a plan that broadcasts internal dataset DsTwo, then probes internal dataset DsOne’s primary index. 
+ * Expected Res : Success
+ * Date         : 29th November 2012
+ */
+
+drop dataverse test1 if exists;
+create dataverse test1;
+
+create type test1.TestType as open {
+          key1: int32,
+          key2: int32,
+          fname : string,
+          lname : string
+}
+
+create dataset test1.DsOne(TestType) partitioned by key key1;
+create dataset test1.DsTwo(TestType) partitioned by key key1;
+
+// Please note content enclosed in the comment in the predicate is the HINT to the optimizer
+
+write output to nc1:"rttest/btree-index-join_primary-le-join_02.adm";
+
+for $x in dataset('test1.DsOne')
+for $y in dataset('test1.DsTwo')
+where $x.key2 /*+ indexnl */ >= $y.key1
+return $x
+
diff --git a/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-lt-join_01.aql b/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-lt-join_01.aql
new file mode 100644
index 0000000..79e24cb
--- /dev/null
+++ b/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-lt-join_01.aql
@@ -0,0 +1,29 @@
+/*
+ * Description  : Notice the query hint to use an indexed nested-loops join plan. 
+ *              : We expect a plan that broadcasts internal dataset DsTwo, then probes internal dataset DsOne’s primary index. 
+ * Expected Res : Success
+ * Date         : 29th November 2012
+ */
+
+drop dataverse test1 if exists;
+create dataverse test1;
+
+create type test1.TestType as open {
+          key1: int32,
+          key2: int32,
+          fname : string,
+          lname : string
+}
+
+create dataset test1.DsOne(TestType) partitioned by key key1;
+create dataset test1.DsTwo(TestType) partitioned by key key1;
+
+// Please note content enclosed in the comment in the predicate is the HINT to the optimizer
+
+write output to nc1:"rttest/btree-index-join_primary-lt-join_01.adm";
+
+for $x in dataset('test1.DsOne')
+for $y in dataset('test1.DsTwo')
+where $x.key1 /*+ indexnl */ < $y.key2
+return $x
+
diff --git a/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-lt-join_02.aql b/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-lt-join_02.aql
new file mode 100644
index 0000000..9709acd
--- /dev/null
+++ b/asterix-app/src/test/resources/optimizerts/queries/btree-index-join/primary-lt-join_02.aql
@@ -0,0 +1,29 @@
+/*
+ * Description  : Notice the query hint to use an indexed nested-loops join plan. 
+ *              : We expect a plan that broadcasts internal dataset DsTwo, then probes internal dataset DsOne’s primary index. 
+ * Expected Res : Success
+ * Date         : 29th November 2012
+ */
+
+drop dataverse test1 if exists;
+create dataverse test1;
+
+create type test1.TestType as open {
+          key1: int32,
+          key2: int32,
+          fname : string,
+          lname : string
+}
+
+create dataset test1.DsOne(TestType) partitioned by key key1;
+create dataset test1.DsTwo(TestType) partitioned by key key1;
+
+// Please note content enclosed in the comment in the predicate is the HINT to the optimizer
+
+write output to nc1:"rttest/btree-index-join_primary-lt-join_02.adm";
+
+for $x in dataset('test1.DsOne')
+for $y in dataset('test1.DsTwo')
+where $x.key2 /*+ indexnl */ > $y.key1
+return $x
+
diff --git a/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-equi-join-neg_01.plan b/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-equi-join-neg_01.plan
new file mode 100644
index 0000000..5327887
--- /dev/null
+++ b/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-equi-join-neg_01.plan
@@ -0,0 +1,17 @@
+-- SINK_WRITE  |PARTITIONED|
+  -- RANDOM_MERGE_EXCHANGE  |PARTITIONED|
+    -- STREAM_PROJECT  |PARTITIONED|
+      -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+        -- HYBRID_HASH_JOIN [$$7][$$10]  |PARTITIONED|
+          -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+            -- DATASOURCE_SCAN  |PARTITIONED|
+              -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+                -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
+          -- HASH_PARTITION_EXCHANGE [$$10]  |PARTITIONED|
+            -- STREAM_PROJECT  |PARTITIONED|
+              -- ASSIGN  |PARTITIONED|
+                -- STREAM_PROJECT  |PARTITIONED|
+                  -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+                    -- DATASOURCE_SCAN  |PARTITIONED|
+                      -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+                        -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
diff --git a/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-equi-join-neg_02.plan b/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-equi-join-neg_02.plan
new file mode 100644
index 0000000..9eb8a7f
--- /dev/null
+++ b/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-equi-join-neg_02.plan
@@ -0,0 +1,18 @@
+-- SINK_WRITE  |PARTITIONED|
+  -- RANDOM_MERGE_EXCHANGE  |PARTITIONED|
+    -- STREAM_PROJECT  |PARTITIONED|
+      -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+        -- HYBRID_HASH_JOIN [$$9][$$8]  |PARTITIONED|
+          -- HASH_PARTITION_EXCHANGE [$$9]  |PARTITIONED|
+            -- ASSIGN  |PARTITIONED|
+              -- STREAM_PROJECT  |PARTITIONED|
+                -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+                  -- DATASOURCE_SCAN  |PARTITIONED|
+                    -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+                      -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
+          -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+            -- STREAM_PROJECT  |PARTITIONED|
+              -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+                -- DATASOURCE_SCAN  |PARTITIONED|
+                  -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+                    -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
diff --git a/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-equi-join_01.plan b/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-equi-join_01.plan
index a83e0eb..95a2309 100644
--- a/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-equi-join_01.plan
+++ b/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-equi-join_01.plan
@@ -1,16 +1,15 @@
 -- SINK_WRITE  |PARTITIONED|
   -- RANDOM_MERGE_EXCHANGE  |PARTITIONED|
     -- STREAM_PROJECT  |PARTITIONED|
-      -- ASSIGN  |PARTITIONED|
-        -- STREAM_PROJECT  |PARTITIONED|
+      -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+        -- BTREE_SEARCH  |PARTITIONED|
           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-            -- BTREE_SEARCH  |PARTITIONED|
-              -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                -- STABLE_SORT [$$11(ASC)]  |PARTITIONED|
-                  -- HASH_PARTITION_EXCHANGE [$$11]  |PARTITIONED|
-                    -- ASSIGN  |PARTITIONED|
-                      -- STREAM_PROJECT  |PARTITIONED|
-                        -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                          -- DATASOURCE_SCAN  |PARTITIONED|
-                            -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                              -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
+            -- STABLE_SORT [$$10(ASC)]  |PARTITIONED|
+              -- HASH_PARTITION_EXCHANGE [$$10]  |PARTITIONED|
+                -- STREAM_PROJECT  |PARTITIONED|
+                  -- ASSIGN  |PARTITIONED|
+                    -- STREAM_PROJECT  |PARTITIONED|
+                      -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+                        -- DATASOURCE_SCAN  |PARTITIONED|
+                          -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+                            -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
diff --git a/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-equi-join_02.plan b/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-equi-join_02.plan
index d6d4497..b2a3f65 100644
--- a/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-equi-join_02.plan
+++ b/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-equi-join_02.plan
@@ -1,16 +1,14 @@
 -- SINK_WRITE  |PARTITIONED|
   -- RANDOM_MERGE_EXCHANGE  |PARTITIONED|
     -- STREAM_PROJECT  |PARTITIONED|
-      -- ASSIGN  |PARTITIONED|
-        -- STREAM_PROJECT  |PARTITIONED|
+      -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+        -- BTREE_SEARCH  |PARTITIONED|
           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-            -- BTREE_SEARCH  |PARTITIONED|
-              -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                -- STABLE_SORT [$$10(ASC)]  |PARTITIONED|
-                  -- HASH_PARTITION_EXCHANGE [$$10]  |PARTITIONED|
-                    -- ASSIGN  |PARTITIONED|
-                      -- STREAM_PROJECT  |PARTITIONED|
+            -- STABLE_SORT [$$9(ASC)]  |PARTITIONED|
+              -- HASH_PARTITION_EXCHANGE [$$9]  |PARTITIONED|
+                -- ASSIGN  |PARTITIONED|
+                  -- STREAM_PROJECT  |PARTITIONED|
+                    -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+                      -- DATASOURCE_SCAN  |PARTITIONED|
                         -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                          -- DATASOURCE_SCAN  |PARTITIONED|
-                            -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                              -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
+                          -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
diff --git a/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-equi-join_03.plan b/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-equi-join_03.plan
index c5c0f4f..a83e0eb 100644
--- a/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-equi-join_03.plan
+++ b/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-equi-join_03.plan
@@ -6,6 +6,11 @@
           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
             -- BTREE_SEARCH  |PARTITIONED|
               -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                -- DATASOURCE_SCAN  |PARTITIONED|
-                  -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                    -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
+                -- STABLE_SORT [$$11(ASC)]  |PARTITIONED|
+                  -- HASH_PARTITION_EXCHANGE [$$11]  |PARTITIONED|
+                    -- ASSIGN  |PARTITIONED|
+                      -- STREAM_PROJECT  |PARTITIONED|
+                        -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+                          -- DATASOURCE_SCAN  |PARTITIONED|
+                            -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+                              -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
diff --git a/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-equi-join_04.plan b/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-equi-join_04.plan
new file mode 100644
index 0000000..d6d4497
--- /dev/null
+++ b/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-equi-join_04.plan
@@ -0,0 +1,16 @@
+-- SINK_WRITE  |PARTITIONED|
+  -- RANDOM_MERGE_EXCHANGE  |PARTITIONED|
+    -- STREAM_PROJECT  |PARTITIONED|
+      -- ASSIGN  |PARTITIONED|
+        -- STREAM_PROJECT  |PARTITIONED|
+          -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+            -- BTREE_SEARCH  |PARTITIONED|
+              -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+                -- STABLE_SORT [$$10(ASC)]  |PARTITIONED|
+                  -- HASH_PARTITION_EXCHANGE [$$10]  |PARTITIONED|
+                    -- ASSIGN  |PARTITIONED|
+                      -- STREAM_PROJECT  |PARTITIONED|
+                        -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+                          -- DATASOURCE_SCAN  |PARTITIONED|
+                            -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+                              -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
diff --git a/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-equi-join_05.plan b/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-equi-join_05.plan
new file mode 100644
index 0000000..c5c0f4f
--- /dev/null
+++ b/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-equi-join_05.plan
@@ -0,0 +1,11 @@
+-- SINK_WRITE  |PARTITIONED|
+  -- RANDOM_MERGE_EXCHANGE  |PARTITIONED|
+    -- STREAM_PROJECT  |PARTITIONED|
+      -- ASSIGN  |PARTITIONED|
+        -- STREAM_PROJECT  |PARTITIONED|
+          -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+            -- BTREE_SEARCH  |PARTITIONED|
+              -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+                -- DATASOURCE_SCAN  |PARTITIONED|
+                  -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+                    -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
diff --git a/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-ge-join_01.plan b/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-ge-join_01.plan
new file mode 100644
index 0000000..6575922
--- /dev/null
+++ b/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-ge-join_01.plan
@@ -0,0 +1,13 @@
+-- SINK_WRITE  |PARTITIONED|
+  -- RANDOM_MERGE_EXCHANGE  |PARTITIONED|
+    -- STREAM_PROJECT  |PARTITIONED|
+      -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+        -- BTREE_SEARCH  |PARTITIONED|
+          -- BROADCAST_EXCHANGE  |PARTITIONED|
+            -- STREAM_PROJECT  |PARTITIONED|
+              -- ASSIGN  |PARTITIONED|
+                -- STREAM_PROJECT  |PARTITIONED|
+                  -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+                    -- DATASOURCE_SCAN  |PARTITIONED|
+                      -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+                        -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
diff --git a/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-ge-join_02.plan b/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-ge-join_02.plan
new file mode 100644
index 0000000..0abc866
--- /dev/null
+++ b/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-ge-join_02.plan
@@ -0,0 +1,12 @@
+-- SINK_WRITE  |PARTITIONED|
+  -- RANDOM_MERGE_EXCHANGE  |PARTITIONED|
+    -- STREAM_PROJECT  |PARTITIONED|
+      -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+        -- BTREE_SEARCH  |PARTITIONED|
+          -- BROADCAST_EXCHANGE  |PARTITIONED|
+            -- ASSIGN  |PARTITIONED|
+              -- STREAM_PROJECT  |PARTITIONED|
+                -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+                  -- DATASOURCE_SCAN  |PARTITIONED|
+                    -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+                      -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
diff --git a/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-gt-join_01.plan b/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-gt-join_01.plan
new file mode 100644
index 0000000..6575922
--- /dev/null
+++ b/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-gt-join_01.plan
@@ -0,0 +1,13 @@
+-- SINK_WRITE  |PARTITIONED|
+  -- RANDOM_MERGE_EXCHANGE  |PARTITIONED|
+    -- STREAM_PROJECT  |PARTITIONED|
+      -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+        -- BTREE_SEARCH  |PARTITIONED|
+          -- BROADCAST_EXCHANGE  |PARTITIONED|
+            -- STREAM_PROJECT  |PARTITIONED|
+              -- ASSIGN  |PARTITIONED|
+                -- STREAM_PROJECT  |PARTITIONED|
+                  -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+                    -- DATASOURCE_SCAN  |PARTITIONED|
+                      -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+                        -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
diff --git a/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-gt-join_02.plan b/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-gt-join_02.plan
new file mode 100644
index 0000000..0abc866
--- /dev/null
+++ b/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-gt-join_02.plan
@@ -0,0 +1,12 @@
+-- SINK_WRITE  |PARTITIONED|
+  -- RANDOM_MERGE_EXCHANGE  |PARTITIONED|
+    -- STREAM_PROJECT  |PARTITIONED|
+      -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+        -- BTREE_SEARCH  |PARTITIONED|
+          -- BROADCAST_EXCHANGE  |PARTITIONED|
+            -- ASSIGN  |PARTITIONED|
+              -- STREAM_PROJECT  |PARTITIONED|
+                -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+                  -- DATASOURCE_SCAN  |PARTITIONED|
+                    -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+                      -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
diff --git a/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-le-join_01.plan b/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-le-join_01.plan
new file mode 100644
index 0000000..6575922
--- /dev/null
+++ b/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-le-join_01.plan
@@ -0,0 +1,13 @@
+-- SINK_WRITE  |PARTITIONED|
+  -- RANDOM_MERGE_EXCHANGE  |PARTITIONED|
+    -- STREAM_PROJECT  |PARTITIONED|
+      -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+        -- BTREE_SEARCH  |PARTITIONED|
+          -- BROADCAST_EXCHANGE  |PARTITIONED|
+            -- STREAM_PROJECT  |PARTITIONED|
+              -- ASSIGN  |PARTITIONED|
+                -- STREAM_PROJECT  |PARTITIONED|
+                  -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+                    -- DATASOURCE_SCAN  |PARTITIONED|
+                      -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+                        -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
diff --git a/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-le-join_02.plan b/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-le-join_02.plan
new file mode 100644
index 0000000..0abc866
--- /dev/null
+++ b/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-le-join_02.plan
@@ -0,0 +1,12 @@
+-- SINK_WRITE  |PARTITIONED|
+  -- RANDOM_MERGE_EXCHANGE  |PARTITIONED|
+    -- STREAM_PROJECT  |PARTITIONED|
+      -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+        -- BTREE_SEARCH  |PARTITIONED|
+          -- BROADCAST_EXCHANGE  |PARTITIONED|
+            -- ASSIGN  |PARTITIONED|
+              -- STREAM_PROJECT  |PARTITIONED|
+                -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+                  -- DATASOURCE_SCAN  |PARTITIONED|
+                    -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+                      -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
diff --git a/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-lt-join_01.plan b/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-lt-join_01.plan
new file mode 100644
index 0000000..6575922
--- /dev/null
+++ b/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-lt-join_01.plan
@@ -0,0 +1,13 @@
+-- SINK_WRITE  |PARTITIONED|
+  -- RANDOM_MERGE_EXCHANGE  |PARTITIONED|
+    -- STREAM_PROJECT  |PARTITIONED|
+      -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+        -- BTREE_SEARCH  |PARTITIONED|
+          -- BROADCAST_EXCHANGE  |PARTITIONED|
+            -- STREAM_PROJECT  |PARTITIONED|
+              -- ASSIGN  |PARTITIONED|
+                -- STREAM_PROJECT  |PARTITIONED|
+                  -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+                    -- DATASOURCE_SCAN  |PARTITIONED|
+                      -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+                        -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
diff --git a/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-lt-join_02.plan b/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-lt-join_02.plan
new file mode 100644
index 0000000..0abc866
--- /dev/null
+++ b/asterix-app/src/test/resources/optimizerts/results/btree-index-join/primary-lt-join_02.plan
@@ -0,0 +1,12 @@
+-- SINK_WRITE  |PARTITIONED|
+  -- RANDOM_MERGE_EXCHANGE  |PARTITIONED|
+    -- STREAM_PROJECT  |PARTITIONED|
+      -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+        -- BTREE_SEARCH  |PARTITIONED|
+          -- BROADCAST_EXCHANGE  |PARTITIONED|
+            -- ASSIGN  |PARTITIONED|
+              -- STREAM_PROJECT  |PARTITIONED|
+                -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+                  -- DATASOURCE_SCAN  |PARTITIONED|
+                    -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
+                      -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
diff --git a/asterix-app/src/test/resources/runtimets/queries/comparison/date_order.aql b/asterix-app/src/test/resources/runtimets/queries/comparison/date_order.aql
new file mode 100644
index 0000000..d38d386
--- /dev/null
+++ b/asterix-app/src/test/resources/runtimets/queries/comparison/date_order.aql
@@ -0,0 +1,16 @@
+drop dataverse test if exists;
+
+create dataverse test;
+
+write output to nc1:"rttest/comparison_date_order.adm";
+
+let $d1 := date("2049-04-23")
+let $d2 := date("2012-02-29")
+let $d3 := date("2021-03-01")
+let $d4 := date("1362-02-28")
+let $d5 := date("1600-02-29")
+let $d6 := date("-0500-03-21")
+
+for $d in [$d1, $d2, $d3, $d4, $d5, $d6]
+order by $d
+return $d
\ No newline at end of file
diff --git a/asterix-app/src/test/resources/runtimets/queries/comparison/time_order.aql b/asterix-app/src/test/resources/runtimets/queries/comparison/time_order.aql
new file mode 100644
index 0000000..ba0d211
--- /dev/null
+++ b/asterix-app/src/test/resources/runtimets/queries/comparison/time_order.aql
@@ -0,0 +1,16 @@
+drop dataverse test if exists;
+
+create dataverse test;
+
+write output to nc1:"rttest/comparison_time_order.adm";
+
+let $t1 := time("13:00:00.382-10:00")
+let $t2 := time("23:59:59.999Z")
+let $t3 := time("22:00:00+03:00")
+let $t4 := time("00:00:00.00Z")
+let $t5 := time("00:00:00.00-02:00")
+let $t6 := time("00:00:00.47+04:00")
+
+for $t in [$t1, $t2, $t3, $t4, $t5, $t6]
+order by $t
+return $t
\ No newline at end of file
diff --git a/asterix-app/src/test/resources/runtimets/queries/constructor/int_01.aql b/asterix-app/src/test/resources/runtimets/queries/constructor/int_01.aql
index d35c84f..683481f 100644
--- a/asterix-app/src/test/resources/runtimets/queries/constructor/int_01.aql
+++ b/asterix-app/src/test/resources/runtimets/queries/constructor/int_01.aql
@@ -12,5 +12,6 @@
 let $c6 := int16("-160i16")
 let $c7 := int32("-320")
 let $c8 := int64("-640i64")
-return {"int8": $c1,"int16": $c2,"int32": $c3, "int64": $c4, "int8": $c5,"int16": $c6,"int32": $c7, "int64": $c8}
+let $c9 := int64("-9223372036854775808")
+return {"int8": $c1,"int16": $c2,"int32": $c3, "int64": $c4, "int8": $c5,"int16": $c6,"int32": $c7, "int64": $c8, "int64_min" : $c9}
 
diff --git a/asterix-app/src/test/resources/runtimets/queries/constructor/interval.aql b/asterix-app/src/test/resources/runtimets/queries/constructor/interval.aql
new file mode 100644
index 0000000..71e90fa
--- /dev/null
+++ b/asterix-app/src/test/resources/runtimets/queries/constructor/interval.aql
@@ -0,0 +1,15 @@
+drop dataverse test if exists;
+create dataverse test;
+use dataverse test;
+
+write output to nc1:"rttest/constructor_interval.adm";
+
+let $itv1 := interval-from-date("2010-10-30", "2012-10-21")
+let $itv2 := interval-from-time("03:04:05.678", "232425267")
+let $itv3 := interval-from-datetime("-1987-11-19T02:43:57.938", "1999-11-12T12:49:35.948")
+let $itv4 := interval-start-from-date("0001-12-27", "P3Y394DT48H398.483S")
+let $itv5 := interval-start-from-time("20:03:20.948", "PT48M389.938S")
+let $itv6 := interval-start-from-datetime("-2043-11-19T15:32:39.293", "P439Y3M20DT20H39M58.949S")
+
+return {"interval1": $itv1, "interval2": $itv2, "interval3": $itv3, "interval4": $itv4, "interval5": $itv5, "interval6": $itv6}
+
diff --git a/asterix-app/src/test/resources/runtimets/queries/open-closed/query-issue236.aql b/asterix-app/src/test/resources/runtimets/queries/open-closed/query-issue236.aql
new file mode 100644
index 0000000..3d8ab69
--- /dev/null
+++ b/asterix-app/src/test/resources/runtimets/queries/open-closed/query-issue236.aql
@@ -0,0 +1,52 @@
+/*
+ * Description  : This test case is to verify the fix for issue236
+ 				: https://code.google.com/p/asterixdb/issues/detail?id=236
+ * Expected Res : Success
+ * Date         : 20 Dec. 2012
+ */
+
+drop dataverse SocialNetworkData if exists;
+
+create dataverse SocialNetworkData;
+use dataverse SocialNetworkData;
+
+create type TwitterUserType as open {
+screen-name: string,
+lang: string,
+friends_count: int32,
+statuses_count: int32,
+name: string,
+followers_count: int32
+}
+
+create type TweetMessageType as closed {
+tweetid: string,
+tweetid-copy: string,
+user: TwitterUserType,
+sender-location: point?,
+send-time: datetime,
+send-time-copy: datetime,
+referred-topics: {{ string }},
+message-text: string
+}
+
+create dataset TweetMessages(TweetMessageType)
+partitioned by key tweetid;
+
+
+insert into dataset TweetMessages(
+{ 
+"tweetid": "1111387810", 
+"tweetid-copy": "1111387810", 
+"user": { "screen-name": "TonyNapier#786", "lang": "en", "friends_count": 4241366, 
+"statuses_count": 97, "name": "Tony Napier", "followers_count": 5984113 }, 
+"sender-location": point("29.24,78.35"), 
+"send-time": datetime("2011-11-24T14:24:51.000Z"), 
+"send-time-copy": datetime("2011-11-24T14:24:51.000Z"), 
+"referred-topics": {{ "sprint", "wireless" }}, 
+"message-text": " love sprint its wireless is mind-blowing:)" 
+});
+
+write output to nc1:"rttest/open-closed_query-issue236.adm";
+for $r in dataset('TweetMessages')
+return $r
diff --git a/asterix-app/src/test/resources/runtimets/queries/temp/accessors.aql b/asterix-app/src/test/resources/runtimets/queries/temp/accessors.aql
new file mode 100644
index 0000000..9cc9f8d
--- /dev/null
+++ b/asterix-app/src/test/resources/runtimets/queries/temp/accessors.aql
@@ -0,0 +1,22 @@
+/*
+ * Description      :   Check temporal accessors for different types
+ * Expected Result  :   Success
+ * Date             :   31st Aug, 2012
+ */
+
+drop dataverse test if exists;
+create dataverse test;
+use dataverse test;
+
+write output to nc1:"rttest/temp_accessors.adm";
+
+let $c1 := date("2010-10-30")
+let $c2 := datetime("1987-11-19T23:49:23.938")
+let $c3 := date("-1987-11-19")
+let $c4 := date("09280329")
+let $c5 := datetime("19371229T20030628")
+let $c6 := time("12:23:34.930+07:00")
+let $c7 := string("-0003-01-09T23:12:12.39-07:00")
+let $c8 := duration("P3Y73M632DT49H743M3948.94S")
+
+return {"year1": year($c1), "year2": year($c2), "year3": year($c3), "year4": year($c4), "year5": year($c5), "year6": year($c7), "year7": year($c8), "month1": month($c1), "month2": month($c2), "month3": month($c3), "month4": month($c4), "month5": month($c5), "month6": month($c8), "day1": day($c1), "day2": day($c2), "day3": day($c3), "day4": day($c4), "day5": day($c5), "day6": day($c8), "hour1": hour($c2), "hour2": hour($c5), "hour3": hour($c6), "hour4": hour($c8), "min1": minute($c2), "min2": minute($c5), "min3": minute($c6), "min4": minute($c8), "second1": second($c2), "second2": second($c5), "second3": second($c6), "second4": second($c8), "ms1": millisecond($c2), "ms2": millisecond($c5), "ms3": millisecond($c6), "ms4": millisecond($c8)}
diff --git a/asterix-app/src/test/resources/runtimets/queries/temp/adjust_timezone.aql b/asterix-app/src/test/resources/runtimets/queries/temp/adjust_timezone.aql
new file mode 100644
index 0000000..9f6c60e
--- /dev/null
+++ b/asterix-app/src/test/resources/runtimets/queries/temp/adjust_timezone.aql
@@ -0,0 +1,17 @@
+/*
+ * Description      :   Check the adjust-timezone functions
+ * Expected Result  :   Success
+ * Date             :   15th Oct, 2012
+ */
+
+drop dataverse test if exists;
+create dataverse test;
+use dataverse test;
+
+write output to nc1:"rttest/temp_adjust_timezone.adm";
+
+let $t1 := time("20:15:10.327")
+let $dt1 := datetime("2010-10-23T01:12:13.329Z")
+let $s1 := adjust-time-for-timezone($t1, "+0800")
+let $s2 := adjust-datetime-for-timezone($dt1, "-0615")
+return { "string1" : $s1, "string2" : $s2 }
\ No newline at end of file
diff --git a/asterix-app/src/test/resources/runtimets/queries/temp/calendar_duration.aql b/asterix-app/src/test/resources/runtimets/queries/temp/calendar_duration.aql
new file mode 100644
index 0000000..67360ce
--- /dev/null
+++ b/asterix-app/src/test/resources/runtimets/queries/temp/calendar_duration.aql
@@ -0,0 +1,28 @@
+/*
+ * Description      :   Check the calendar-duration functions
+ * Expected Result  :   Success
+ * Date             :   15th Oct, 2012
+ */
+
+drop dataverse test if exists;
+create dataverse test;
+use dataverse test;
+
+write output to nc1:"rttest/temp_calendar_duration.adm";
+
+let $t1 := datetime("1987-11-19T23:49:23.938")
+let $t2 := date("-1328-10-23")
+let $dr1 := duration("P7382DT39283M3921.329S")
+let $dr2 := duration("-PT63H398212M3219.328S")
+let $dr3 := duration("P1Y90M")
+let $dr4 := duration("-P3Y89M4089DT47382.983S")
+let $cdr1 := calendar-duration-from-datetime($t1, $dr1)
+let $cdr2 := calendar-duration-from-datetime($t1, $dr2)
+let $cdr3 := calendar-duration-from-datetime($t1, $dr3)
+let $cdr4 := calendar-duration-from-datetime($t1, $dr4)
+let $cdr5 := calendar-duration-from-date($t2, $dr1)
+let $cdr6 := calendar-duration-from-date($t2, $dr2)
+let $cdr7 := calendar-duration-from-date($t2, $dr3)
+let $cdr8 := calendar-duration-from-date($t2, $dr4)
+
+return { "cduration1":$cdr1, "cduration2":$cdr2, "cduration3":$cdr3, "cduration4":$cdr4, "cduration5":$cdr5, "cduration6":$cdr6, "cduration7":$cdr7, "cduration8":$cdr8 }
diff --git a/asterix-app/src/test/resources/runtimets/queries/temp/date_functions.aql b/asterix-app/src/test/resources/runtimets/queries/temp/date_functions.aql
new file mode 100644
index 0000000..310fa43
--- /dev/null
+++ b/asterix-app/src/test/resources/runtimets/queries/temp/date_functions.aql
@@ -0,0 +1,24 @@
+/*
+ * Description      :   Check temporal functions for date type
+ * Expected Result  :   Success
+ * Date             :   24th Sep, 2012
+ */
+drop dataverse test if exists;
+create dataverse test;
+use dataverse test;
+
+write output to nc1:"rttest/temp_date_functions.adm";
+
+let $d1 := date-from-unix-time-in-days(15600)
+let $dt1 := datetime("1327-12-02T23:35:49.938Z")
+let $d2 := date-from-datetime($dt1)
+let $dt2 := datetime("2012-10-11T02:30:23+03:00")
+let $d3 := date-from-datetime($dt2)
+let $dr1 := duration("-P2Y1M90DT30H")
+let $d4 := add-date-duration($d1, $dr1)
+let $dr2 := duration("P300Y900MT360000M")
+let $d5 := add-date-duration($d2, $dr2)
+let $dr3 := subtract-date($d5, $d2)
+let $dr4 := subtract-date($d4, $d1)
+
+return { "date1" : $d1, "date2" : $d2, "date3" : $d3, "date4" : $d4, "date5" : $d5, "duration1" : $dr3, "duration2" : $dr4  }
\ No newline at end of file
diff --git a/asterix-app/src/test/resources/runtimets/queries/temp/datetime_functions.aql b/asterix-app/src/test/resources/runtimets/queries/temp/datetime_functions.aql
new file mode 100644
index 0000000..a70c9f2
--- /dev/null
+++ b/asterix-app/src/test/resources/runtimets/queries/temp/datetime_functions.aql
@@ -0,0 +1,20 @@
+/*
+ * Description      :   Check temporal functions for datetime
+ * Expected Result  :   Success
+ * Date             :   24th Sep, 2012
+ */
+
+drop dataverse test if exists;
+create dataverse test;
+use dataverse test;
+
+write output to nc1:"rttest/temp_datetime_functions.adm";
+
+let $dt1 := datetime-from-unix-time-in-ms(956007429)
+let $d1 := date("1327-12-02")
+let $t1 := time("23:35:49.938Z")
+let $dt2 := datetime-from-date-time($d1, $t1)
+let $dr1 := subtract-datetime($dt2, $dt1)
+let $dt3 := add-datetime-duration($dt1, $dr1)
+
+return { "datetime1" : $dt1, "datetime2" : $dt2, "datetime3" : $dt3, "duration1" : $dr1 }
\ No newline at end of file
diff --git a/asterix-app/src/test/resources/runtimets/queries/temp/insert_from_delimited_ds.aql b/asterix-app/src/test/resources/runtimets/queries/temp/insert_from_delimited_ds.aql
new file mode 100644
index 0000000..4520f46
--- /dev/null
+++ b/asterix-app/src/test/resources/runtimets/queries/temp/insert_from_delimited_ds.aql
@@ -0,0 +1,26 @@
+/*
+ * Test case name: date-insert.aql
+ * Description: verify insertion operation for date type
+ * Expected result: success
+ */
+ 
+drop dataverse testdvt if exists;
+create dataverse testdvt;
+use dataverse testdvt;
+
+create type testtype as closed {
+  id: string,
+  dateField: date,
+  timeField: time,
+  datetimeField: datetime,
+  durationField: duration
+}
+
+write output to nc1:"rttest/temp_insert_from_delimited_ds.adm";
+
+create external dataset testds(testtype)
+using "edu.uci.ics.asterix.external.dataset.adapter.NCFileSystemAdapter"
+(("path"="nc1://data/temporal/temporalData.txt"),("format"="delimited-text"),("delimiter"="|"));
+
+for $r in dataset("testds") 
+return {"date": $r.dateField, "time": $r.timeField, "datetime": $r.datetimeField, "duration": $r.durationField }
\ No newline at end of file
diff --git a/asterix-app/src/test/resources/runtimets/queries/temp/insert_from_ext_ds.aql b/asterix-app/src/test/resources/runtimets/queries/temp/insert_from_ext_ds.aql
new file mode 100644
index 0000000..5813696
--- /dev/null
+++ b/asterix-app/src/test/resources/runtimets/queries/temp/insert_from_ext_ds.aql
@@ -0,0 +1,27 @@
+/*
+ * Test case name: date-insert.aql
+ * Description: verify insertion operation for date type
+ * Expected result: success
+ */
+ 
+drop dataverse testdvt if exists;
+create dataverse testdvt;
+use dataverse testdvt;
+
+create type testtype as open {
+  id: string,
+  dateField: date?,
+  timeField: time?,
+  datetimeField: datetime?,
+  durationField: duration?,
+  intervalField: interval?
+}
+
+write output to nc1:"rttest/temp_insert_from_ext_ds.adm";
+
+create external dataset testds(testtype)
+using "edu.uci.ics.asterix.external.dataset.adapter.NCFileSystemAdapter"
+(("path"="nc1://data/temporal/temporalData.json"),("format"="adm"));
+
+for $r in dataset("testds") 
+return {"date": $r.dateField, "time": $r.timeField, "datetime": $r.datetimeField, "duration": $r.durationField, "interval": $r.intervalField }
\ No newline at end of file
diff --git a/asterix-app/src/test/resources/runtimets/queries/temp/interval_functions.aql b/asterix-app/src/test/resources/runtimets/queries/temp/interval_functions.aql
new file mode 100644
index 0000000..a29f7f5
--- /dev/null
+++ b/asterix-app/src/test/resources/runtimets/queries/temp/interval_functions.aql
@@ -0,0 +1,56 @@
+/*
+ * Description      :   Check temporal functions for interval
+ * Expected Result  :   Success
+ * Date             :   2nd Nov, 2012
+ */
+
+drop dataverse test if exists;
+create dataverse test;
+use dataverse test;
+
+write output to nc1:"rttest/temp_interval_functions.adm";
+
+let $itv1 := interval-from-date("2010-10-30", "2010-12-21")
+let $itv2 := interval-from-date("2011-10-30", "2012-10-21")
+let $itv3 := interval-from-date("2010-06-30", "2013-01-01")
+let $blnBefore1 := interval-before($itv1, $itv2)
+let $blnAfter1 := interval-after($itv2, $itv1)
+let $blnBefore2 := interval-before($itv1, $itv3)
+let $blnAfter2 := interval-after($itv3, $itv1)
+
+let $itv4 := interval-from-datetime("2012-06-26T01:01:01.111", "2012-07-27T02:02:02.222")
+let $itv5 := interval-from-datetime("20120727T020202222", "2013-08-08T03:03:03.333")
+let $itv6 := interval-from-datetime("19000707T020202222", "2013-08-07T03:03:03.333")
+let $blnMeet1 := interval-meets($itv4, $itv5)
+let $blnMetBy1 := interval-met-by($itv5, $itv4)
+let $blnMeet2 := interval-meets($itv6, $itv4)
+let $blnMetBy2 := interval-met-by($itv6, $itv4)
+
+let $itv7 := interval-from-time("12:32:38", "20:29:20")
+let $itv8 := interval-from-time("17:48:19", "22:19:49")
+let $itv9 := interval-from-time("01:32:49", "12:33:00")
+let $blnOverlaps1 := interval-overlaps($itv7, $itv8)
+let $blnOverlapped1 := interval-overlapped-by($itv8, $itv7)
+let $blnOverlaps2 := interval-overlaps($itv8, $itv7)
+let $blnOverlapped2 := interval-overlapped-by($itv7, $itv8)
+let $blnOverlap1 := overlap($itv9, $itv7)
+let $blnOverlap2 := overlap($itv9, $itv8)
+
+let $itv10 := interval-from-date("2010-10-30", "2010-11-30")
+let $blnStarts1 := interval-starts($itv10, $itv1)
+let $blnStarts2 := interval-starts($itv10, $itv2)
+let $blnStartedBy1 := interval-started-by($itv1, $itv10)
+let $blnStartedBy2 := interval-started-by($itv10, $itv2)
+
+let $blnCovers1 := interval-covers($itv6, $itv4)
+let $blnCovers2 := interval-covers($itv6, $itv5)
+let $blnCoveredBy1 := interval-covered-by($itv4, $itv6)
+let $blnCoveredBy2 := interval-covered-by($itv5, $itv6)
+
+let $itv11 := interval-from-time("19:00:00.009", "20:29:20.000")
+let $blnEnds1 := interval-ends($itv11, $itv7)
+let $blnEnds2 := interval-ends($itv11, $itv8)
+let $blnEndedBy1 := interval-ended-by($itv7, $itv11)
+let $blnEndedBy2 := interval-ended-by($itv8, $itv11)
+
+return { "before1" : $blnBefore1, "before2" : $blnBefore2, "after1" : $blnAfter1, "after2" : $blnAfter2, "meet1" : $blnMeet1, "meet2" : $blnMeet2, "metby1" : $blnMetBy1, "metby2" : $blnMetBy2, "overlaps1" : $blnOverlaps1, "overlaps2" : $blnOverlaps2, "overlapped1" : $blnOverlapped1, "overlapped2" : $blnOverlapped2, "overlap1" : $blnOverlap1, "overlap2" : $blnOverlap2, "starts1" : $blnStarts1, "starts2" : $blnStarts2, "startedby1" : $blnStartedBy1, "startedby2" : $blnStartedBy2, "covers1" : $blnCovers1, "covers2" : $blnCovers2, "coveredby1" : $blnCoveredBy1, "coveredby2" : $blnCoveredBy2, "ends1" : $blnEnds1, "ends2" : $blnEnds2, "endedby1" : $blnEndedBy1, "endedby2" : $blnEndedBy2 }
\ No newline at end of file
diff --git a/asterix-app/src/test/resources/runtimets/queries/temp/time_functions.aql b/asterix-app/src/test/resources/runtimets/queries/temp/time_functions.aql
new file mode 100644
index 0000000..29adcc0
--- /dev/null
+++ b/asterix-app/src/test/resources/runtimets/queries/temp/time_functions.aql
@@ -0,0 +1,28 @@
+/*
+ * Description      :   Check temporal functions for time
+ * Expected Result  :   Success
+ * Date             :   24th Sep, 2012
+ */
+
+drop dataverse test if exists;
+create dataverse test;
+use dataverse test;
+
+write output to nc1:"rttest/temp_time_functions.adm";
+
+let $t1 := time-from-unix-time-in-ms(1560074)
+let $dt1 := datetime("1327-12-02T23:35:49.938Z")
+let $t2 := time-from-datetime($dt1)
+let $dt2 := datetime("2012-10-11T02:30:23+03:00")
+let $t3 := time-from-datetime($dt2)
+let $dr1 := duration("-PT30H")
+let $t4 := add-time-duration($t1, $dr1)
+let $dr2 := duration("PT36M")
+let $t5 := add-time-duration($t2, $dr2)
+let $dr3 := subtract-time($t5, $t2)
+let $dr4 := subtract-time($t4, $t1)
+let $ct := current-time()
+let $cd := current-date()
+let $cdt := current-datetime()
+
+return { "time1" : $t1, "time2" : $t2, "time3" : $t3, "time4" : $t4, "time5" : $t5, "duration1" : $dr3, "duration2" : $dr4  }
\ No newline at end of file
diff --git a/asterix-app/src/test/resources/runtimets/queries/tpch/q10_returned_item_int64.aql b/asterix-app/src/test/resources/runtimets/queries/tpch/q10_returned_item_int64.aql
new file mode 100644
index 0000000..cfac014
--- /dev/null
+++ b/asterix-app/src/test/resources/runtimets/queries/tpch/q10_returned_item_int64.aql
@@ -0,0 +1,195 @@
+drop dataverse tpch if exists;
+create dataverse tpch;
+
+use dataverse tpch;
+
+create type LineItemType as closed {
+  l_orderkey: int64, 
+  l_partkey: int64, 
+  l_suppkey: int64, 
+  l_linenumber: int64, 
+  l_quantity: int64, 
+  l_extendedprice: double,
+  l_discount: double, 
+  l_tax: double,
+  l_returnflag: string, 
+  l_linestatus: string, 
+  l_shipdate: string,
+  l_commitdate: string, 
+  l_receiptdate: string, 
+  l_shipinstruct: string, 
+  l_shipmode: string, 
+  l_comment: string
+}
+
+create type OrderType as closed {
+  o_orderkey: int64, 
+  o_custkey: int64, 
+  o_orderstatus: string, 
+  o_totalprice: double, 
+  o_orderdate: string, 
+  o_orderpriority: string,
+  o_clerk: string, 
+  o_shippriority: int64, 
+  o_comment: string
+}
+
+create type CustomerType as closed {
+  c_custkey: int64, 
+  c_name: string, 
+  c_address: string, 
+  c_nationkey: int64, 
+  c_phone: string, 
+  c_acctbal: double, 
+  c_mktsegment: string,
+  c_comment: string
+}
+
+create type SupplierType as closed {
+  s_suppkey: int64, 
+  s_name: string,
+  s_address: string,
+  s_nationkey: int64,
+  s_phone: string,
+  s_acctbal: double,
+  s_comment: string
+}
+
+create type NationType as closed {
+  n_nationkey: int64,
+  n_name: string,
+  n_regionkey: int64,
+  n_comment: string
+}
+
+create type RegionType as closed {
+	r_regionkey: int64, 
+	r_name: string, 
+	r_comment: string
+} 
+
+create type PartType as closed {
+  p_partkey: int64, 
+  p_name: string, 
+  p_mfgr: string,
+  p_brand: string,
+  p_type: string,
+  p_size: int64,
+  p_container: string,
+  p_retailprice: double,
+  p_comment: string
+}
+
+create type PartSuppType as closed {
+  ps_partkey: int64, 
+  ps_suppkey: int64,
+  ps_availqty: int64,
+  ps_supplycost: double,
+  ps_comment: string 
+}
+
+create dataset LineItem(LineItemType)
+  partitioned by key l_orderkey, l_linenumber;
+create dataset Orders(OrderType)
+  partitioned by key o_orderkey;
+create dataset Supplier(SupplierType)
+  partitioned by key s_suppkey;
+create dataset Region(RegionType) 
+  partitioned by key r_regionkey;
+create dataset Nation(NationType) 
+  partitioned by key n_nationkey;
+create dataset Part(PartType)
+  partitioned by key p_partkey;
+create dataset Partsupp(PartSuppType)
+  partitioned by key ps_partkey, ps_suppkey;  
+create dataset Customer(CustomerType) 
+  partitioned by key c_custkey;
+
+load dataset LineItem 
+using "edu.uci.ics.asterix.external.dataset.adapter.NCFileSystemAdapter"
+(("path"="nc1://data/tpch0.001/lineitem.tbl"),("format"="delimited-text"),("delimiter"="|")) pre-sorted;
+
+load dataset Orders 
+using "edu.uci.ics.asterix.external.dataset.adapter.NCFileSystemAdapter"
+(("path"="nc1://data/tpch0.001/orders.tbl"),("format"="delimited-text"),("delimiter"="|")) pre-sorted;
+
+load dataset Supplier 
+using "edu.uci.ics.asterix.external.dataset.adapter.NCFileSystemAdapter"
+(("path"="nc1://data/tpch0.001/supplier.tbl"),("format"="delimited-text"),("delimiter"="|")) pre-sorted;
+
+load dataset Region 
+using "edu.uci.ics.asterix.external.dataset.adapter.NCFileSystemAdapter"
+(("path"="nc1://data/tpch0.001/region.tbl"),("format"="delimited-text"),("delimiter"="|")) pre-sorted;
+
+load dataset Nation 
+using "edu.uci.ics.asterix.external.dataset.adapter.NCFileSystemAdapter"
+(("path"="nc1://data/tpch0.001/nation.tbl"),("format"="delimited-text"),("delimiter"="|")) pre-sorted;
+
+load dataset Part 
+using "edu.uci.ics.asterix.external.dataset.adapter.NCFileSystemAdapter"
+(("path"="nc1://data/tpch0.001/part.tbl"),("format"="delimited-text"),("delimiter"="|")) pre-sorted;
+
+load dataset Partsupp 
+using "edu.uci.ics.asterix.external.dataset.adapter.NCFileSystemAdapter"
+(("path"="nc1://data/tpch0.001/partsupp.tbl"),("format"="delimited-text"),("delimiter"="|")) pre-sorted;
+
+load dataset Customer 
+using "edu.uci.ics.asterix.external.dataset.adapter.NCFileSystemAdapter"
+(("path"="nc1://data/tpch0.001/customer.tbl"),("format"="delimited-text"),("delimiter"="|")) pre-sorted;
+
+write output to nc1:"rttest/tpch_q10_returned_item_int64.adm";
+
+
+for $locn in (
+for $l in dataset('LineItem')
+for $ocn in (
+	for $o in dataset('Orders')
+	for $c in dataset('Customer')
+		where $c.c_custkey = $o.o_custkey and $o.o_orderdate >= '1993-10-01' and $o.o_orderdate < '1994-01-01'
+	for $n in dataset('Nation')
+		where $c.c_nationkey = $n.n_nationkey
+	return {
+		"c_custkey": $c.c_custkey, 
+		"c_name": $c.c_name,
+  		"c_acctbal": $c.c_acctbal, 
+  		"n_name": $n.n_name, 
+  		"c_address": $c.c_address, 
+  		"c_phone": $c.c_phone, 
+  		"c_comment": $c.c_comment,
+  		"o_orderkey": $o.o_orderkey
+	}
+)
+where
+   $l.l_orderkey = $ocn.o_orderkey and $l.l_returnflag = 'R'
+   return {
+		"c_custkey": $ocn.c_custkey, 
+		"c_name": $ocn.c_name,
+  		"c_acctbal": $ocn.c_acctbal, 
+  		"n_name": $ocn.n_name, 
+  		"c_address": $ocn.c_address, 
+  		"c_phone": $ocn.c_phone, 
+  		"c_comment": $ocn.c_comment,
+  		"l_extendedprice": $l.l_extendedprice,
+  		"l_discount": $l.l_discount
+	}	
+)
+group by $c_custkey:=$locn.c_custkey, 
+		$c_name:=$locn.c_name, 
+		$c_acctbal:=$locn.c_acctbal, $c_phone:=$locn.c_phone, 
+		$n_name:=$locn.n_name, $c_address:=$locn.c_address, $c_comment:=$locn.c_comment
+		with $locn
+let $revenue := sum(for $i in $locn return $i.l_extendedprice * (1 - $i.l_discount))
+order by $revenue desc
+limit 20
+return {
+		"c_custkey": $c_custkey, 
+		"c_name": $c_name,
+		"revenue": $revenue,
+  		"c_acctbal": $c_acctbal, 
+  		"n_name": $n_name, 
+  		"c_address": $c_address, 
+  		"c_phone": $c_phone, 
+  		"c_comment": $c_comment
+}
+		
+		
diff --git a/asterix-app/src/test/resources/runtimets/results/comparison/date_order.adm b/asterix-app/src/test/resources/runtimets/results/comparison/date_order.adm
new file mode 100644
index 0000000..3fd4c19
--- /dev/null
+++ b/asterix-app/src/test/resources/runtimets/results/comparison/date_order.adm
@@ -0,0 +1,6 @@
+date("-0500-03-21")
+date("1362-02-28")
+date("1600-02-29")
+date("2012-02-29")
+date("2021-03-01")
+date("2049-04-23")
\ No newline at end of file
diff --git a/asterix-app/src/test/resources/runtimets/results/comparison/time_order.adm b/asterix-app/src/test/resources/runtimets/results/comparison/time_order.adm
new file mode 100644
index 0000000..c937bdd
--- /dev/null
+++ b/asterix-app/src/test/resources/runtimets/results/comparison/time_order.adm
@@ -0,0 +1,6 @@
+time("00:00:00.000Z")
+time("02:00:00.000Z")
+time("19:00:00.000Z")
+time("20:00:00.470Z")
+time("23:00:00.382Z")
+time("23:59:59.999Z")
\ No newline at end of file
diff --git a/asterix-app/src/test/resources/runtimets/results/constructor/int_01.adm b/asterix-app/src/test/resources/runtimets/results/constructor/int_01.adm
index f9a1203..fb52e3b 100644
--- a/asterix-app/src/test/resources/runtimets/results/constructor/int_01.adm
+++ b/asterix-app/src/test/resources/runtimets/results/constructor/int_01.adm
@@ -1 +1 @@
-{ "int8": 80i8, "int16": 160i16, "int32": 320, "int64": 640i64, "int8": -80i8, "int16": -160i16, "int32": -320, "int64": -640i64 }
\ No newline at end of file
+{ "int8": 80i8, "int16": 160i16, "int32": 320, "int64": 640i64, "int8": -80i8, "int16": -160i16, "int32": -320, "int64": -640i64, "int64_min": -9223372036854775808i64 }
\ No newline at end of file
diff --git a/asterix-app/src/test/resources/runtimets/results/constructor/interval.adm b/asterix-app/src/test/resources/runtimets/results/constructor/interval.adm
new file mode 100644
index 0000000..8fb7e25
--- /dev/null
+++ b/asterix-app/src/test/resources/runtimets/results/constructor/interval.adm
@@ -0,0 +1 @@
+{ "interval1": interval("date("2010-10-30"), date("2012-10-21")"), "interval2": interval("time("03:04:05.678Z"), time("23:24:25.267Z")"), "interval3": interval("datetime("-1987-11-19T02:43:57.938Z"), datetime("1999-11-12T12:49:35.948Z")"), "interval4": interval("date("0001-12-27"), date("0006-01-27")"), "interval5": interval("time("20:03:20.948Z"), time("20:57:50.886Z")"), "interval6": interval("datetime("-2043-11-19T15:32:39.293Z"), datetime("-1603-03-12T12:12:38.242Z")") }
\ No newline at end of file
diff --git a/asterix-app/src/test/resources/runtimets/results/open-closed/query-issue236.adm b/asterix-app/src/test/resources/runtimets/results/open-closed/query-issue236.adm
new file mode 100644
index 0000000..65bdb8f
--- /dev/null
+++ b/asterix-app/src/test/resources/runtimets/results/open-closed/query-issue236.adm
@@ -0,0 +1 @@
+{ "tweetid": "1111387810", "tweetid-copy": "1111387810", "user": { "screen-name": "TonyNapier#786", "lang": "en", "friends_count": 4241366, "statuses_count": 97, "name": "Tony Napier", "followers_count": 5984113 }, "sender-location": point("29.24,78.35"), "send-time": datetime("2011-11-24T14:24:51.000Z"), "send-time-copy": datetime("2011-11-24T14:24:51.000Z"), "referred-topics": {{ "sprint", "wireless" }}, "message-text": " love sprint its wireless is mind-blowing:)" }
diff --git a/asterix-app/src/test/resources/runtimets/results/temp/accessors.adm b/asterix-app/src/test/resources/runtimets/results/temp/accessors.adm
new file mode 100644
index 0000000..4f36f91
--- /dev/null
+++ b/asterix-app/src/test/resources/runtimets/results/temp/accessors.adm
@@ -0,0 +1 @@
+{ "year1": 2010, "year2": 1987, "year3": -1987, "year4": 928, "year5": 1937, "year6": -3, "year7": 9, "month1": 10, "month2": 11, "month3": 11, "month4": 3, "month5": 12, "month6": 1, "day1": 30, "day2": 19, "day3": 19, "day4": 29, "day5": 29, "day6": 634, "hour1": 23, "hour2": 20, "hour3": 5, "hour4": 14, "min1": 49, "min2": 3, "min3": 23, "min4": 28, "second1": 23, "second2": 6, "second3": 34, "second4": 48, "ms1": 938, "ms2": 280, "ms3": 930, "ms4": 94 }
\ No newline at end of file
diff --git a/asterix-app/src/test/resources/runtimets/results/temp/adjust_timezone.adm b/asterix-app/src/test/resources/runtimets/results/temp/adjust_timezone.adm
new file mode 100644
index 0000000..1f80fd9
--- /dev/null
+++ b/asterix-app/src/test/resources/runtimets/results/temp/adjust_timezone.adm
@@ -0,0 +1 @@
+{ "string1": "04:15:10.327+08:00", "string2": "2010-10-22T18:57:13.329-06:15" }
\ No newline at end of file
diff --git a/asterix-app/src/test/resources/runtimets/results/temp/calendar_duration.adm b/asterix-app/src/test/resources/runtimets/results/temp/calendar_duration.adm
new file mode 100644
index 0000000..eb7d565
--- /dev/null
+++ b/asterix-app/src/test/resources/runtimets/results/temp/calendar_duration.adm
@@ -0,0 +1 @@
+{ "cduration1": duration("P20Y3M13DT7H48M21.329S"), "cduration2": duration("-P9M6DT4H45M39.328S"), "cduration3": duration("P8Y6M"), "cduration4": duration("-P21Y7M10DT13H9M42.983S"), "cduration5": duration("P20Y3M12DT7H48M21.329S"), "cduration6": duration("-P9M5DT4H45M39.328S"), "cduration7": duration("P8Y6M"), "cduration8": duration("-P21Y7M10DT13H9M42.983S") }
\ No newline at end of file
diff --git a/asterix-app/src/test/resources/runtimets/results/temp/date_functions.adm b/asterix-app/src/test/resources/runtimets/results/temp/date_functions.adm
new file mode 100644
index 0000000..2276f85
--- /dev/null
+++ b/asterix-app/src/test/resources/runtimets/results/temp/date_functions.adm
@@ -0,0 +1 @@
+{ "date1": date("2012-09-17"), "date2": date("1327-12-02"), "date3": date("2012-10-10"), "date4": date("2010-05-17"), "date5": date("1703-08-09"), "duration1": duration("P137216D"), "duration2": duration("-P854D") }
\ No newline at end of file
diff --git a/asterix-app/src/test/resources/runtimets/results/temp/datetime_functions.adm b/asterix-app/src/test/resources/runtimets/results/temp/datetime_functions.adm
new file mode 100644
index 0000000..6ebc562
--- /dev/null
+++ b/asterix-app/src/test/resources/runtimets/results/temp/datetime_functions.adm
@@ -0,0 +1 @@
+{ "datetime1": datetime("1970-01-12T01:33:27.429Z"), "datetime2": datetime("1327-12-02T23:35:49.938Z"), "datetime3": datetime("1327-12-02T23:35:49.938Z"), "duration1": duration("-P234526DT1H57M37.491S") }
\ No newline at end of file
diff --git a/asterix-app/src/test/resources/runtimets/results/temp/insert_from_delimited_ds.adm b/asterix-app/src/test/resources/runtimets/results/temp/insert_from_delimited_ds.adm
new file mode 100644
index 0000000..5c40e46
--- /dev/null
+++ b/asterix-app/src/test/resources/runtimets/results/temp/insert_from_delimited_ds.adm
@@ -0,0 +1,4 @@
+{ "date": date("-2012-12-12"), "time": time("23:49:12.390Z"), "datetime": datetime("3827-12-12T11:43:29.329Z"), "duration": duration("P20Y19DT4H14M23.34S") }
+{ "date": date("1993-12-12"), "time": time("03:32:00.000Z"), "datetime": datetime("-2012-12-12T05:00:23.071Z"), "duration": duration("P20Y19D") }
+{ "date": date("1839-03-12"), "time": time("12:30:49.382Z"), "datetime": datetime("1012-06-12T00:37:00.000Z"), "duration": duration("PT4H14M23.34S") }
+{ "date": date("0003-11-02"), "time": time("23:19:32.382Z"), "datetime": datetime("2012-12-12T00:00:00.001Z"), "duration": duration("P20Y12DT12H9.34S") }
\ No newline at end of file
diff --git a/asterix-app/src/test/resources/runtimets/results/temp/insert_from_ext_ds.adm b/asterix-app/src/test/resources/runtimets/results/temp/insert_from_ext_ds.adm
new file mode 100644
index 0000000..afe2ccc
--- /dev/null
+++ b/asterix-app/src/test/resources/runtimets/results/temp/insert_from_ext_ds.adm
@@ -0,0 +1,3 @@
+{ "date": date("-2012-12-12"), "time": time("23:49:12.390Z"), "datetime": datetime("2012-12-12T00:00:00.001Z"), "duration": duration("P20Y19DT4H14M23.34S"), "interval": interval("datetime("2012-12-12T00:00:00.001Z"), datetime("2013-08-10T22:10:15.398Z")") }
+{ "date": null, "time": null, "datetime": datetime("1920-12-20T23:29:18.478Z"), "duration": null, "interval": null }
+{ "date": null, "time": null, "datetime": null, "duration": null, "interval": null }
\ No newline at end of file
diff --git a/asterix-app/src/test/resources/runtimets/results/temp/interval_functions.adm b/asterix-app/src/test/resources/runtimets/results/temp/interval_functions.adm
new file mode 100644
index 0000000..9f9c9d3
--- /dev/null
+++ b/asterix-app/src/test/resources/runtimets/results/temp/interval_functions.adm
@@ -0,0 +1 @@
+{ "before1": true, "before2": false, "after1": true, "after2": false, "meet1": true, "meet2": false, "metby1": true, "metby2": false, "overlaps1": true, "overlaps2": false, "overlapped1": true, "overlapped2": false, "overlap1": true, "overlap2": false, "starts1": true, "starts2": false, "startedby1": true, "startedby2": false, "covers1": true, "covers2": false, "coveredby1": true, "coveredby2": false, "ends1": true, "ends2": false, "endedby1": true, "endedby2": false }
\ No newline at end of file
diff --git a/asterix-app/src/test/resources/runtimets/results/temp/time_functions.adm b/asterix-app/src/test/resources/runtimets/results/temp/time_functions.adm
new file mode 100644
index 0000000..56531bd
--- /dev/null
+++ b/asterix-app/src/test/resources/runtimets/results/temp/time_functions.adm
@@ -0,0 +1 @@
+{ "time1": time("00:26:00.074Z"), "time2": time("23:35:49.938Z"), "time3": time("23:30:23.000Z"), "time4": time("18:26:00.074Z"), "time5": time("00:11:49.938Z"), "duration1": duration("-PT23H24M"), "duration2": duration("PT18H") }
\ No newline at end of file
diff --git a/asterix-app/src/test/resources/runtimets/results/tpch/q10_returned_item_int64.adm b/asterix-app/src/test/resources/runtimets/results/tpch/q10_returned_item_int64.adm
new file mode 100644
index 0000000..422b480
--- /dev/null
+++ b/asterix-app/src/test/resources/runtimets/results/tpch/q10_returned_item_int64.adm
@@ -0,0 +1,20 @@
+{ "c_custkey": 121i64, "c_name": "Customer#000000121", "revenue": 282635.1719d, "c_acctbal": 6428.32d, "n_name": "PERU", "c_address": "tv nCR2YKupGN73mQudO", "c_phone": "27-411-990-2959", "c_comment": "uriously stealthy ideas. carefully final courts use carefully" }
+{ "c_custkey": 124i64, "c_name": "Customer#000000124", "revenue": 222182.5188d, "c_acctbal": 1842.49d, "n_name": "CHINA", "c_address": "aTbyVAW5tCd,v09O", "c_phone": "28-183-750-7809", "c_comment": "le fluffily even dependencies. quietly s" }
+{ "c_custkey": 106i64, "c_name": "Customer#000000106", "revenue": 190241.3334d, "c_acctbal": 3288.42d, "n_name": "ARGENTINA", "c_address": "xGCOEAUjUNG", "c_phone": "11-751-989-4627", "c_comment": "lose slyly. ironic accounts along the evenly regular theodolites wake about the special, final gifts. " }
+{ "c_custkey": 16i64, "c_name": "Customer#000000016", "revenue": 161422.04609999998d, "c_acctbal": 4681.03d, "n_name": "IRAN", "c_address": "cYiaeMLZSMAOQ2 d0W,", "c_phone": "20-781-609-3107", "c_comment": "kly silent courts. thinly regular theodolites sleep fluffily after " }
+{ "c_custkey": 44i64, "c_name": "Customer#000000044", "revenue": 149364.5652d, "c_acctbal": 7315.94d, "n_name": "MOZAMBIQUE", "c_address": "Oi,dOSPwDu4jo4x,,P85E0dmhZGvNtBwi", "c_phone": "26-190-260-5375", "c_comment": "r requests around the unusual, bold a" }
+{ "c_custkey": 71i64, "c_name": "Customer#000000071", "revenue": 129481.02450000001d, "c_acctbal": -611.19d, "n_name": "GERMANY", "c_address": "TlGalgdXWBmMV,6agLyWYDyIz9MKzcY8gl,w6t1B", "c_phone": "17-710-812-5403", "c_comment": "g courts across the regular, final pinto beans are blithely pending ac" }
+{ "c_custkey": 89i64, "c_name": "Customer#000000089", "revenue": 121663.1243d, "c_acctbal": 1530.76d, "n_name": "KENYA", "c_address": "dtR, y9JQWUO6FoJExyp8whOU", "c_phone": "24-394-451-5404", "c_comment": "counts are slyly beyond the slyly final accounts. quickly final ideas wake. r" }
+{ "c_custkey": 112i64, "c_name": "Customer#000000112", "revenue": 111137.7141d, "c_acctbal": 2953.35d, "n_name": "ROMANIA", "c_address": "RcfgG3bO7QeCnfjqJT1", "c_phone": "29-233-262-8382", "c_comment": "rmanently unusual multipliers. blithely ruthless deposits are furiously along the" }
+{ "c_custkey": 62i64, "c_name": "Customer#000000062", "revenue": 106368.0153d, "c_acctbal": 595.61d, "n_name": "GERMANY", "c_address": "upJK2Dnw13,", "c_phone": "17-361-978-7059", "c_comment": "kly special dolphins. pinto beans are slyly. quickly regular accounts are furiously a" }
+{ "c_custkey": 146i64, "c_name": "Customer#000000146", "revenue": 103265.98879999999d, "c_acctbal": 3328.68d, "n_name": "CANADA", "c_address": "GdxkdXG9u7iyI1,,y5tq4ZyrcEy", "c_phone": "13-835-723-3223", "c_comment": "ffily regular dinos are slyly unusual requests. slyly specia" }
+{ "c_custkey": 19i64, "c_name": "Customer#000000019", "revenue": 99306.0127d, "c_acctbal": 8914.71d, "n_name": "CHINA", "c_address": "uc,3bHIx84H,wdrmLOjVsiqXCq2tr", "c_phone": "28-396-526-5053", "c_comment": " nag. furiously careful packages are slyly at the accounts. furiously regular in" }
+{ "c_custkey": 145i64, "c_name": "Customer#000000145", "revenue": 99256.9018d, "c_acctbal": 9748.93d, "n_name": "JORDAN", "c_address": "kQjHmt2kcec cy3hfMh969u", "c_phone": "23-562-444-8454", "c_comment": "ests? express, express instructions use. blithely fina" }
+{ "c_custkey": 103i64, "c_name": "Customer#000000103", "revenue": 97311.77240000002d, "c_acctbal": 2757.45d, "n_name": "INDONESIA", "c_address": "8KIsQX4LJ7QMsj6DrtFtXu0nUEdV,8a", "c_phone": "19-216-107-2107", "c_comment": "furiously pending notornis boost slyly around the blithely ironic ideas? final, even instructions cajole fl" }
+{ "c_custkey": 136i64, "c_name": "Customer#000000136", "revenue": 95855.39799999999d, "c_acctbal": -842.39d, "n_name": "GERMANY", "c_address": "QoLsJ0v5C1IQbh,DS1", "c_phone": "17-501-210-4726", "c_comment": "ackages sleep ironic, final courts. even requests above the blithely bold requests g" }
+{ "c_custkey": 53i64, "c_name": "Customer#000000053", "revenue": 92568.9124d, "c_acctbal": 4113.64d, "n_name": "MOROCCO", "c_address": "HnaxHzTfFTZs8MuCpJyTbZ47Cm4wFOOgib", "c_phone": "25-168-852-5363", "c_comment": "ar accounts are. even foxes are blithely. fluffily pending deposits boost" }
+{ "c_custkey": 49i64, "c_name": "Customer#000000049", "revenue": 90965.7262d, "c_acctbal": 4573.94d, "n_name": "IRAN", "c_address": "cNgAeX7Fqrdf7HQN9EwjUa4nxT,68L FKAxzl", "c_phone": "20-908-631-4424", "c_comment": "nusual foxes! fluffily pending packages maintain to the regular " }
+{ "c_custkey": 37i64, "c_name": "Customer#000000037", "revenue": 88065.74579999999d, "c_acctbal": -917.75d, "n_name": "INDIA", "c_address": "7EV4Pwh,3SboctTWt", "c_phone": "18-385-235-7162", "c_comment": "ilent packages are carefully among the deposits. furiousl" }
+{ "c_custkey": 82i64, "c_name": "Customer#000000082", "revenue": 86998.9644d, "c_acctbal": 9468.34d, "n_name": "CHINA", "c_address": "zhG3EZbap4c992Gj3bK,3Ne,Xn", "c_phone": "28-159-442-5305", "c_comment": "s wake. bravely regular accounts are furiously. regula" }
+{ "c_custkey": 125i64, "c_name": "Customer#000000125", "revenue": 84808.068d, "c_acctbal": -234.12d, "n_name": "ROMANIA", "c_address": ",wSZXdVR xxIIfm9s8ITyLl3kgjT6UC07GY0Y", "c_phone": "29-261-996-3120", "c_comment": "x-ray finally after the packages? regular requests c" }
+{ "c_custkey": 59i64, "c_name": "Customer#000000059", "revenue": 84655.5711d, "c_acctbal": 3458.6d, "n_name": "ARGENTINA", "c_address": "zLOCP0wh92OtBihgspOGl4", "c_phone": "11-355-584-3112", "c_comment": "ously final packages haggle blithely after the express deposits. furiou" }
diff --git a/asterix-app/src/test/resources/runtimets/testsuite.xml b/asterix-app/src/test/resources/runtimets/testsuite.xml
index e57d491..f547aab 100644
--- a/asterix-app/src/test/resources/runtimets/testsuite.xml
+++ b/asterix-app/src/test/resources/runtimets/testsuite.xml
@@ -2399,6 +2399,11 @@
         <output-file compare="Text">query-issue208.adm</output-file>
       </compilation-unit>
     </test-case>
+    <test-case FilePath="open-closed">
+      <compilation-unit name="query-issue236">
+       <output-file compare="Text">query-issue236.adm</output-file>
+      </compilation-unit>
+    </test-case>
     <!--
     <test-case FilePath="open-closed">
       <compilation-unit name="open-closed-15">
@@ -3453,6 +3458,11 @@
       </compilation-unit>
     </test-case>
     <test-case FilePath="tpch">
+      <compilation-unit name="q10_returned_item_int64">
+	<output-file compare="Text">q10_returned_item_int64.adm</output-file>
+      </compilation-unit>
+    </test-case>
+    <test-case FilePath="tpch">
       <compilation-unit name="q11_important_stock">
         <output-file compare="Text">q11_important_stock.adm</output-file>
       </compilation-unit>
diff --git a/asterix-common/pom.xml b/asterix-common/pom.xml
index 048c037..ee81e75 100644
--- a/asterix-common/pom.xml
+++ b/asterix-common/pom.xml
@@ -25,13 +25,11 @@
 	<dependencies>
 		<dependency>
 			<groupId>edu.uci.ics.hyracks</groupId>
-			<artifactId>hyracks-algebricks-compiler</artifactId>
-			<version>0.2.2-SNAPSHOT</version>
+			<artifactId>algebricks-compiler</artifactId>
 		</dependency>
 		<dependency>
 			<groupId>edu.uci.ics.hyracks</groupId>
 			<artifactId>hyracks-dataflow-std</artifactId>
-			<version>0.2.2-SNAPSHOT</version>
 		</dependency>
 		<dependency>
 			<groupId>edu.uci.ics.asterix</groupId>
diff --git a/asterix-common/src/main/java/edu/uci/ics/asterix/common/context/AsterixAppRuntimeContext.java b/asterix-common/src/main/java/edu/uci/ics/asterix/common/context/AsterixAppRuntimeContext.java
index d676cb5..f84f294 100644
--- a/asterix-common/src/main/java/edu/uci/ics/asterix/common/context/AsterixAppRuntimeContext.java
+++ b/asterix-common/src/main/java/edu/uci/ics/asterix/common/context/AsterixAppRuntimeContext.java
@@ -12,9 +12,11 @@
 import edu.uci.ics.hyracks.storage.am.common.dataflow.IndexRegistry;
 import edu.uci.ics.hyracks.storage.common.buffercache.BufferCache;
 import edu.uci.ics.hyracks.storage.common.buffercache.ClockPageReplacementStrategy;
+import edu.uci.ics.hyracks.storage.common.buffercache.DelayPageCleanerPolicy;
 import edu.uci.ics.hyracks.storage.common.buffercache.HeapBufferAllocator;
 import edu.uci.ics.hyracks.storage.common.buffercache.IBufferCache;
 import edu.uci.ics.hyracks.storage.common.buffercache.ICacheMemoryAllocator;
+import edu.uci.ics.hyracks.storage.common.buffercache.IPageCleanerPolicy;
 import edu.uci.ics.hyracks.storage.common.buffercache.IPageReplacementStrategy;
 import edu.uci.ics.hyracks.storage.common.file.IFileMapManager;
 import edu.uci.ics.hyracks.storage.common.file.IFileMapProvider;
@@ -22,7 +24,7 @@
 public class AsterixAppRuntimeContext {
     private static final int DEFAULT_BUFFER_CACHE_PAGE_SIZE = 32768;
     private final INCApplicationContext ncApplicationContext;
-    
+
     private IndexRegistry<IIndex> indexRegistry;
     private IFileMapManager fileMapManager;
     private IBufferCache bufferCache;
@@ -43,7 +45,8 @@
         ICacheMemoryAllocator allocator = new HeapBufferAllocator();
         IPageReplacementStrategy prs = new ClockPageReplacementStrategy();
         IIOManager ioMgr = ncApplicationContext.getRootContext().getIOManager();
-        bufferCache = new BufferCache(ioMgr, allocator, prs, fileMapManager, pageSize, numPages, Integer.MAX_VALUE);
+        IPageCleanerPolicy pcp = new DelayPageCleanerPolicy(600000);
+        bufferCache = new BufferCache(ioMgr, allocator, prs, pcp, fileMapManager, pageSize, numPages, Integer.MAX_VALUE);
 
         // Initialize the index registry
         indexRegistry = new IndexRegistry<IIndex>();
diff --git a/asterix-dist/pom.xml b/asterix-dist/pom.xml
index 53168b4..654a11e 100644
--- a/asterix-dist/pom.xml
+++ b/asterix-dist/pom.xml
@@ -1,54 +1,55 @@
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-  <modelVersion>4.0.0</modelVersion>
-  <artifactId>asterix-dist</artifactId>
-  <parent>
-    <groupId>edu.uci.ics.asterix</groupId>
-    <artifactId>asterix</artifactId>
-    <version>0.0.4-SNAPSHOT</version>
-  </parent>
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+	<modelVersion>4.0.0</modelVersion>
+	<artifactId>asterix-dist</artifactId>
+	<parent>
+		<groupId>edu.uci.ics.asterix</groupId>
+		<artifactId>asterix</artifactId>
+		<version>0.0.4-SNAPSHOT</version>
+	</parent>
 
-  <build>
-    <plugins>
-      <plugin>
-        <artifactId>maven-assembly-plugin</artifactId>
-        <version>2.2-beta-5</version>
-        <executions>
-          <execution>
-            <configuration>
-              <descriptors>
-                <descriptor>src/main/assembly/binary-assembly.xml</descriptor>
-              </descriptors>
-            </configuration>
-            <phase>package</phase>
-            <goals>
-              <goal>attached</goal>
-            </goals>
-          </execution>
-        </executions>
-      </plugin>
-    </plugins>
-  </build>
-  <dependencies>
-    <dependency>
-	  <groupId>edu.uci.ics.hyracks</groupId>
-  	  <artifactId>hyracks-server</artifactId>
-  	  <version>0.2.2-SNAPSHOT</version>
-  	  <type>zip</type>
-      <classifier>binary-assembly</classifier>
-    </dependency>
-    <dependency>
-	  <groupId>edu.uci.ics.hyracks</groupId>
-  	  <artifactId>hyracks-cli</artifactId>
-  	  <version>0.2.2-SNAPSHOT</version>
-  	  <type>zip</type>
-      <classifier>binary-assembly</classifier>
-    </dependency>
-    <dependency>
-	  <groupId>edu.uci.ics.asterix</groupId>
-  	  <artifactId>asterix-app</artifactId>
-  	  <version>0.0.4-SNAPSHOT</version>
-  	  <type>zip</type>
-      <classifier>binary-assembly</classifier>
-    </dependency>
-  </dependencies>
+	<build>
+		<plugins>
+			<plugin>
+				<artifactId>maven-assembly-plugin</artifactId>
+				<version>2.2-beta-5</version>
+				<executions>
+					<execution>
+						<configuration>
+							<descriptors>
+								<descriptor>src/main/assembly/binary-assembly.xml</descriptor>
+							</descriptors>
+						</configuration>
+						<phase>package</phase>
+						<goals>
+							<goal>attached</goal>
+						</goals>
+					</execution>
+				</executions>
+			</plugin>
+		</plugins>
+	</build>
+	<dependencies>
+		<dependency>
+			<groupId>edu.uci.ics.hyracks</groupId>
+			<artifactId>hyracks-server</artifactId>
+			<version>0.2.3-SNAPSHOT</version>
+			<type>zip</type>
+			<classifier>binary-assembly</classifier>
+		</dependency>
+		<dependency>
+			<groupId>edu.uci.ics.hyracks</groupId>
+			<artifactId>hyracks-cli</artifactId>
+			<version>0.2.3-SNAPSHOT</version>
+			<type>zip</type>
+			<classifier>binary-assembly</classifier>
+		</dependency>
+		<dependency>
+			<groupId>edu.uci.ics.asterix</groupId>
+			<artifactId>asterix-app</artifactId>
+			<version>0.0.4-SNAPSHOT</version>
+			<type>zip</type>
+			<classifier>binary-assembly</classifier>
+		</dependency>
+	</dependencies>
 </project>
diff --git a/asterix-external-data/pom.xml b/asterix-external-data/pom.xml
index 7da6bd9..3076323 100644
--- a/asterix-external-data/pom.xml
+++ b/asterix-external-data/pom.xml
@@ -5,9 +5,7 @@
 		<groupId>edu.uci.ics.asterix</groupId>
 		<version>0.0.4-SNAPSHOT</version>
 	</parent>
-	<groupId>edu.uci.ics.asterix</groupId>
 	<artifactId>asterix-external-data</artifactId>
-	<version>0.0.4-SNAPSHOT</version>
 
 	<build>
 		<plugins>
@@ -131,7 +129,6 @@
 	        <dependency>
 		         <groupId>edu.uci.ics.hyracks</groupId>
 		         <artifactId>hyracks-dataflow-hadoop</artifactId>
-		         <version>0.2.2-SNAPSHOT</version>
 	        </dependency>
 <dependency>
             <groupId>jdom</groupId>
diff --git a/asterix-metadata/pom.xml b/asterix-metadata/pom.xml
index 67f16ff..58566f8 100644
--- a/asterix-metadata/pom.xml
+++ b/asterix-metadata/pom.xml
@@ -5,9 +5,7 @@
 		<groupId>edu.uci.ics.asterix</groupId>
 		<version>0.0.4-SNAPSHOT</version>
 	</parent>
-	<groupId>edu.uci.ics.asterix</groupId>
 	<artifactId>asterix-metadata</artifactId>
-	<version>0.0.4-SNAPSHOT</version>
 
 	<build>
 		<plugins>
@@ -45,12 +43,10 @@
 		<dependency>
 			<groupId>edu.uci.ics.hyracks</groupId>
 			<artifactId>hyracks-storage-am-invertedindex</artifactId>
-			<version>0.2.2-SNAPSHOT</version>
 		</dependency>
 		<dependency>
 			<groupId>edu.uci.ics.hyracks</groupId>
 			<artifactId>hyracks-storage-am-rtree</artifactId>
-			<version>0.2.2-SNAPSHOT</version>
 		</dependency>
 		<dependency>
 			<groupId>edu.uci.ics.asterix</groupId>
diff --git a/asterix-metadata/src/main/java/edu/uci/ics/asterix/metadata/entities/AsterixBuiltinTypeMap.java b/asterix-metadata/src/main/java/edu/uci/ics/asterix/metadata/entities/AsterixBuiltinTypeMap.java
index 734237e..27cf542 100644
--- a/asterix-metadata/src/main/java/edu/uci/ics/asterix/metadata/entities/AsterixBuiltinTypeMap.java
+++ b/asterix-metadata/src/main/java/edu/uci/ics/asterix/metadata/entities/AsterixBuiltinTypeMap.java
@@ -40,6 +40,7 @@
         _builtinTypeMap.put("time", BuiltinType.ATIME);
         _builtinTypeMap.put("datetime", BuiltinType.ADATETIME);
         _builtinTypeMap.put("duration", BuiltinType.ADURATION);
+        _builtinTypeMap.put("interval", BuiltinType.AINTERVAL);
         _builtinTypeMap.put("point", BuiltinType.APOINT);
         _builtinTypeMap.put("point3d", BuiltinType.APOINT3D);
         _builtinTypeMap.put("line", BuiltinType.ALINE);
diff --git a/asterix-metadata/src/main/java/edu/uci/ics/asterix/metadata/entities/Index.java b/asterix-metadata/src/main/java/edu/uci/ics/asterix/metadata/entities/Index.java
index 2aade27..4265630 100644
--- a/asterix-metadata/src/main/java/edu/uci/ics/asterix/metadata/entities/Index.java
+++ b/asterix-metadata/src/main/java/edu/uci/ics/asterix/metadata/entities/Index.java
@@ -123,27 +123,27 @@
         }
         throw new AlgebricksException("Could not find field " + expr + " in the schema.");
     }
-    
+
     @Override
     public int hashCode() {
-    	return indexName.hashCode() ^ datasetName.hashCode() ^ dataverseName.hashCode();
+        return indexName.hashCode() ^ datasetName.hashCode() ^ dataverseName.hashCode();
     }
-    
+
     @Override
     public boolean equals(Object other) {
-    	if (!(other instanceof Index)) {
-    		return false;
-    	}
-    	Index otherIndex = (Index) other;
-    	if (!indexName.equals(otherIndex.getIndexName())) {
-    		return false;
-    	}
-    	if (!datasetName.equals(otherIndex.getDatasetName())) {
-    		return false;
-    	}
-    	if (!dataverseName.equals(otherIndex.getDataverseName())) {
-    		return false;
-    	}
-    	return true;
+        if (!(other instanceof Index)) {
+            return false;
+        }
+        Index otherIndex = (Index) other;
+        if (!indexName.equals(otherIndex.getIndexName())) {
+            return false;
+        }
+        if (!datasetName.equals(otherIndex.getDatasetName())) {
+            return false;
+        }
+        if (!dataverseName.equals(otherIndex.getDataverseName())) {
+            return false;
+        }
+        return true;
     }
 }
diff --git a/asterix-om/pom.xml b/asterix-om/pom.xml
index a14f3c2..8cceaa0 100644
--- a/asterix-om/pom.xml
+++ b/asterix-om/pom.xml
@@ -5,9 +5,7 @@
 		<groupId>edu.uci.ics.asterix</groupId>
 		<version>0.0.4-SNAPSHOT</version>
 	</parent>
-	<groupId>edu.uci.ics.asterix</groupId>
 	<artifactId>asterix-om</artifactId>
-	<version>0.0.4-SNAPSHOT</version>
 
 	<build>
 		<plugins>
@@ -33,7 +31,6 @@
 		<dependency>
 			<groupId>edu.uci.ics.hyracks</groupId>
 			<artifactId>hyracks-storage-am-invertedindex</artifactId>
-			<version>0.2.2-SNAPSHOT</version>
 		</dependency>
 		<dependency>
 			<groupId>edu.uci.ics.asterix</groupId>
@@ -43,13 +40,11 @@
 		</dependency>
 		<dependency>
 			<groupId>edu.uci.ics.hyracks</groupId>
-			<artifactId>hyracks-algebricks-compiler</artifactId>
-			<version>0.2.2-SNAPSHOT</version>
+			<artifactId>algebricks-compiler</artifactId>
 		</dependency>
 		<dependency>
 			<groupId>edu.uci.ics.hyracks</groupId>
 			<artifactId>hyracks-storage-am-rtree</artifactId>
-			<version>0.2.2-SNAPSHOT</version>
 		</dependency>
 	</dependencies>
 </project>
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/comparators/ADateOrTimeAscBinaryComparatorFactory.java b/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/comparators/ADateOrTimeAscBinaryComparatorFactory.java
new file mode 100644
index 0000000..464a03c
--- /dev/null
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/comparators/ADateOrTimeAscBinaryComparatorFactory.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.dataflow.data.nontagged.comparators;
+
+import edu.uci.ics.hyracks.api.dataflow.value.IBinaryComparator;
+import edu.uci.ics.hyracks.api.dataflow.value.IBinaryComparatorFactory;
+
+public class ADateOrTimeAscBinaryComparatorFactory implements IBinaryComparatorFactory {
+
+    private static final long serialVersionUID = 1L;
+
+    public static final ADateOrTimeAscBinaryComparatorFactory INSTANCE = new ADateOrTimeAscBinaryComparatorFactory();
+
+    private ADateOrTimeAscBinaryComparatorFactory() {
+    }
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.hyracks.api.dataflow.value.IBinaryComparatorFactory#createBinaryComparator()
+     */
+    @Override
+    public IBinaryComparator createBinaryComparator() {
+        return new IBinaryComparator() {
+
+            @Override
+            public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) {
+                int chrononTime1 = getInt(b1, s1);
+                int chrononTime2 = getInt(b2, s2);
+
+                if (chrononTime1 > chrononTime2) {
+                    return 1;
+                } else if (chrononTime1 < chrononTime2) {
+                    return -1;
+                } else {
+                    return 0;
+                }
+            }
+
+            private int getInt(byte[] bytes, int start) {
+                return ((bytes[start] & 0xff) << 24) + ((bytes[start + 1] & 0xff) << 16)
+                        + ((bytes[start + 2] & 0xff) << 8) + ((bytes[start + 3] & 0xff) << 0);
+            }
+        };
+    }
+}
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/comparators/AObjectAscBinaryComparatorFactory.java b/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/comparators/AObjectAscBinaryComparatorFactory.java
index 881590d..0e486e7 100644
--- a/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/comparators/AObjectAscBinaryComparatorFactory.java
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/comparators/AObjectAscBinaryComparatorFactory.java
@@ -24,15 +24,21 @@
     public IBinaryComparator createBinaryComparator() {
         return new IBinaryComparator() {
             final IBinaryComparator ascBoolComp = BooleanBinaryComparatorFactory.INSTANCE.createBinaryComparator();
-            final IBinaryComparator ascIntComp = new PointableBinaryComparatorFactory(IntegerPointable.FACTORY).createBinaryComparator();
+            final IBinaryComparator ascIntComp = new PointableBinaryComparatorFactory(IntegerPointable.FACTORY)
+                    .createBinaryComparator();
             final IBinaryComparator ascLongComp = LongBinaryComparatorFactory.INSTANCE.createBinaryComparator();
-            final IBinaryComparator ascStrComp = new PointableBinaryComparatorFactory(UTF8StringPointable.FACTORY).createBinaryComparator();
-            final IBinaryComparator ascFloatComp = new PointableBinaryComparatorFactory(FloatPointable.FACTORY).createBinaryComparator();
-            final IBinaryComparator ascDoubleComp = new PointableBinaryComparatorFactory(DoublePointable.FACTORY).createBinaryComparator();
+            final IBinaryComparator ascStrComp = new PointableBinaryComparatorFactory(UTF8StringPointable.FACTORY)
+                    .createBinaryComparator();
+            final IBinaryComparator ascFloatComp = new PointableBinaryComparatorFactory(FloatPointable.FACTORY)
+                    .createBinaryComparator();
+            final IBinaryComparator ascDoubleComp = new PointableBinaryComparatorFactory(DoublePointable.FACTORY)
+                    .createBinaryComparator();
             final IBinaryComparator ascRectangleComp = RectangleBinaryComparatorFactory.INSTANCE
                     .createBinaryComparator();
             final IBinaryComparator ascDateTimeComp = ADateTimeAscBinaryComparatorFactory.INSTANCE
                     .createBinaryComparator();
+            final IBinaryComparator ascDateOrTimeComp = ADateOrTimeAscBinaryComparatorFactory.INSTANCE
+                    .createBinaryComparator();
 
             @Override
             public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) {
@@ -73,6 +79,10 @@
                     case DATETIME: {
                         return ascDateTimeComp.compare(b1, s1 + 1, l1 - 1, b2, s2 + 1, l2 - 1);
                     }
+                    case TIME:
+                    case DATE: {
+                        return ascDateOrTimeComp.compare(b1, s1 + 1, l1 - 1, b2, s2 + 1, l2 - 1);
+                    }
                     default: {
                         throw new NotImplementedException("Comparison for type " + tag + " is not implemented");
                     }
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/hash/MurmurHash3BinaryHashFunctionFamily.java b/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/hash/MurmurHash3BinaryHashFunctionFamily.java
new file mode 100644
index 0000000..83b165b
--- /dev/null
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/hash/MurmurHash3BinaryHashFunctionFamily.java
@@ -0,0 +1,86 @@
+/*
+ * Copyright 2009-2010 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.dataflow.data.nontagged.hash;
+
+import edu.uci.ics.hyracks.api.dataflow.value.IBinaryHashFunction;
+import edu.uci.ics.hyracks.api.dataflow.value.IBinaryHashFunctionFamily;
+
+/**
+ * An implementation of the Murmur3 hash family. The code is implemented based
+ * on the original <a
+ * href=http://code.google.com/p/guava-libraries/source/browse
+ * /guava/src/com/google/common/hash/Murmur3_32HashFunction.java>guava
+ * implementation</a> from Google Guava library.
+ */
+public class MurmurHash3BinaryHashFunctionFamily implements
+		IBinaryHashFunctionFamily {
+
+	public static final IBinaryHashFunctionFamily INSTANCE = new MurmurHash3BinaryHashFunctionFamily();
+
+	private static final long serialVersionUID = 1L;
+
+	private MurmurHash3BinaryHashFunctionFamily() {
+	}
+
+	private static final int C1 = 0xcc9e2d51;
+	private static final int C2 = 0x1b873593;
+	private static final int C3 = 5;
+	private static final int C4 = 0xe6546b64;
+	private static final int C5 = 0x85ebca6b;
+	private static final int C6 = 0xc2b2ae35;
+
+	@Override
+	public IBinaryHashFunction createBinaryHashFunction(final int seed) {
+		return new IBinaryHashFunction() {
+			@Override
+			public int hash(byte[] bytes, int offset, int length) {
+				int h = seed;
+				int p = offset;
+				int remain = length;
+				while (remain >= 4) {
+					int k = (bytes[p] & 0xff) | ((bytes[p + 1] & 0xff) << 8)
+							| ((bytes[p + 2] & 0xff) << 16)
+							| ((bytes[p + 3] & 0xff) << 24);
+					k *= C1;
+					k = Integer.rotateLeft(k, 15);
+					k *= C2;
+					h ^= k;
+					h = Integer.rotateLeft(h, 13);
+					h = h * C3 + C4;
+					p += 4;
+					remain -= 4;
+				}
+				if (remain > 0) {
+					int k = 0;
+					for (int i = 0; remain > 0; i += 8) {
+						k ^= (bytes[p++] & 0xff) << i;
+						remain--;
+					}
+					k *= C1;
+					k = Integer.rotateLeft(k, 15);
+					k *= C2;
+					h ^= k;
+				}
+				h ^= length;
+				h ^= (h >>> 16);
+				h *= C5;
+				h ^= (h >>> 13);
+				h *= C6;
+				h ^= (h >>> 16);
+				return h;
+			}
+		};
+	}
+}
\ No newline at end of file
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/keynormalizers/AInt32AscNormalizedKeyComputerFactory.java b/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/keynormalizers/AInt32AscNormalizedKeyComputerFactory.java
deleted file mode 100644
index 903ac3d..0000000
--- a/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/keynormalizers/AInt32AscNormalizedKeyComputerFactory.java
+++ /dev/null
@@ -1,30 +0,0 @@
-package edu.uci.ics.asterix.dataflow.data.nontagged.keynormalizers;
-
-import edu.uci.ics.hyracks.api.dataflow.value.INormalizedKeyComputer;
-import edu.uci.ics.hyracks.api.dataflow.value.INormalizedKeyComputerFactory;
-import edu.uci.ics.hyracks.dataflow.common.data.normalizers.IntegerNormalizedKeyComputerFactory;
-
-public class AInt32AscNormalizedKeyComputerFactory implements INormalizedKeyComputerFactory {
-
-    private static final long serialVersionUID = 1L;
-
-    public static final AInt32AscNormalizedKeyComputerFactory INSTANCE = new AInt32AscNormalizedKeyComputerFactory();
-
-    private IntegerNormalizedKeyComputerFactory inkcf = new IntegerNormalizedKeyComputerFactory();
-
-    private AInt32AscNormalizedKeyComputerFactory() {
-    }
-
-    @Override
-    public INormalizedKeyComputer createNormalizedKeyComputer() {
-        final INormalizedKeyComputer intNkc = inkcf.createNormalizedKeyComputer();
-        return new INormalizedKeyComputer() {
-
-            @Override
-            public int normalize(byte[] bytes, int start, int length) {
-                return intNkc.normalize(bytes, start + 1, length - 1);
-            }
-        };
-    }
-
-}
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/keynormalizers/AInt32DescNormalizedKeyComputerFactory.java b/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/keynormalizers/AInt32DescNormalizedKeyComputerFactory.java
deleted file mode 100644
index cec6a40..0000000
--- a/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/keynormalizers/AInt32DescNormalizedKeyComputerFactory.java
+++ /dev/null
@@ -1,30 +0,0 @@
-package edu.uci.ics.asterix.dataflow.data.nontagged.keynormalizers;
-
-import edu.uci.ics.hyracks.api.dataflow.value.INormalizedKeyComputer;
-import edu.uci.ics.hyracks.api.dataflow.value.INormalizedKeyComputerFactory;
-import edu.uci.ics.hyracks.dataflow.common.data.normalizers.IntegerNormalizedKeyComputerFactory;
-
-public class AInt32DescNormalizedKeyComputerFactory implements INormalizedKeyComputerFactory {
-
-    private static final long serialVersionUID = 1L;
-
-    public static final AInt32DescNormalizedKeyComputerFactory INSTANCE = new AInt32DescNormalizedKeyComputerFactory();
-
-    private IntegerNormalizedKeyComputerFactory inkcf = new IntegerNormalizedKeyComputerFactory();
-
-    private AInt32DescNormalizedKeyComputerFactory() {
-    }
-
-    @Override
-    public INormalizedKeyComputer createNormalizedKeyComputer() {
-        final INormalizedKeyComputer intNkc = inkcf.createNormalizedKeyComputer();
-        return new INormalizedKeyComputer() {
-
-            @Override
-            public int normalize(byte[] bytes, int start, int length) {
-                int nk = intNkc.normalize(bytes, start + 1, length - 1);
-                return (int) ((long) 0xffffffff - (long) nk);
-            }
-        };
-    }
-}
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/keynormalizers/AStringAscNormalizedKeyComputerFactory.java b/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/keynormalizers/AStringAscNormalizedKeyComputerFactory.java
deleted file mode 100644
index 0d1780f..0000000
--- a/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/keynormalizers/AStringAscNormalizedKeyComputerFactory.java
+++ /dev/null
@@ -1,30 +0,0 @@
-package edu.uci.ics.asterix.dataflow.data.nontagged.keynormalizers;
-
-import edu.uci.ics.hyracks.api.dataflow.value.INormalizedKeyComputer;
-import edu.uci.ics.hyracks.api.dataflow.value.INormalizedKeyComputerFactory;
-import edu.uci.ics.hyracks.dataflow.common.data.normalizers.UTF8StringNormalizedKeyComputerFactory;
-
-public class AStringAscNormalizedKeyComputerFactory implements INormalizedKeyComputerFactory {
-
-    private static final long serialVersionUID = 1L;
-
-    public static final AStringAscNormalizedKeyComputerFactory INSTANCE = new AStringAscNormalizedKeyComputerFactory();
-
-    private AStringAscNormalizedKeyComputerFactory() {
-    }
-
-    private UTF8StringNormalizedKeyComputerFactory strnkcf = new UTF8StringNormalizedKeyComputerFactory();
-
-    @Override
-    public INormalizedKeyComputer createNormalizedKeyComputer() {
-        final INormalizedKeyComputer strNkc = strnkcf.createNormalizedKeyComputer();
-        return new INormalizedKeyComputer() {
-
-            @Override
-            public int normalize(byte[] bytes, int start, int length) {
-                return strNkc.normalize(bytes, start + 1, length - 1);
-            }
-        };
-    }
-
-}
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/keynormalizers/AStringDescNormalizedKeyComputerFactory.java b/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/keynormalizers/AStringDescNormalizedKeyComputerFactory.java
deleted file mode 100644
index 0ff6acd..0000000
--- a/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/keynormalizers/AStringDescNormalizedKeyComputerFactory.java
+++ /dev/null
@@ -1,31 +0,0 @@
-package edu.uci.ics.asterix.dataflow.data.nontagged.keynormalizers;
-
-import edu.uci.ics.hyracks.api.dataflow.value.INormalizedKeyComputer;
-import edu.uci.ics.hyracks.api.dataflow.value.INormalizedKeyComputerFactory;
-import edu.uci.ics.hyracks.dataflow.common.data.normalizers.UTF8StringNormalizedKeyComputerFactory;
-
-public class AStringDescNormalizedKeyComputerFactory implements INormalizedKeyComputerFactory {
-
-    private static final long serialVersionUID = 1L;
-
-    public static final AStringDescNormalizedKeyComputerFactory INSTANCE = new AStringDescNormalizedKeyComputerFactory();
-
-    private AStringDescNormalizedKeyComputerFactory() {
-    }
-
-    private UTF8StringNormalizedKeyComputerFactory strnkcf = new UTF8StringNormalizedKeyComputerFactory();
-
-    @Override
-    public INormalizedKeyComputer createNormalizedKeyComputer() {
-        final INormalizedKeyComputer strNkc = strnkcf.createNormalizedKeyComputer();
-        return new INormalizedKeyComputer() {
-
-            @Override
-            public int normalize(byte[] bytes, int start, int length) {
-                int nk = strNkc.normalize(bytes, start + 1, length - 1);
-                return (int) ((long) 0xffffffff - (long) nk);
-            }
-        };
-    }
-
-}
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/keynormalizers/AWrappedAscNormalizedKeyComputerFactory.java b/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/keynormalizers/AWrappedAscNormalizedKeyComputerFactory.java
new file mode 100644
index 0000000..2efa593
--- /dev/null
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/keynormalizers/AWrappedAscNormalizedKeyComputerFactory.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright 2009-2010 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package edu.uci.ics.asterix.dataflow.data.nontagged.keynormalizers;
+
+import edu.uci.ics.hyracks.api.dataflow.value.INormalizedKeyComputer;
+import edu.uci.ics.hyracks.api.dataflow.value.INormalizedKeyComputerFactory;
+
+/**
+ * This class uses a decorator pattern to wrap an ASC ordered INomralizedKeyComputerFactory implementation to
+ * obtain the ASC order.
+ */
+public class AWrappedAscNormalizedKeyComputerFactory implements INormalizedKeyComputerFactory {
+
+    private static final long serialVersionUID = 1L;
+    private final INormalizedKeyComputerFactory nkcf;
+
+    public AWrappedAscNormalizedKeyComputerFactory(INormalizedKeyComputerFactory nkcf) {
+        this.nkcf = nkcf;
+    }
+
+    @Override
+    public INormalizedKeyComputer createNormalizedKeyComputer() {
+        final INormalizedKeyComputer nkc = nkcf.createNormalizedKeyComputer();
+        return new INormalizedKeyComputer() {
+
+            @Override
+            public int normalize(byte[] bytes, int start, int length) {
+                // start +1, length -1 is because in ASTERIX data format, there is always a type tag before the value 
+                return nkc.normalize(bytes, start + 1, length - 1);
+            }
+        };
+    }
+
+}
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/keynormalizers/AWrappedDescNormalizedKeyComputerFactory.java b/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/keynormalizers/AWrappedDescNormalizedKeyComputerFactory.java
new file mode 100644
index 0000000..a5653b9
--- /dev/null
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/keynormalizers/AWrappedDescNormalizedKeyComputerFactory.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright 2009-2010 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package edu.uci.ics.asterix.dataflow.data.nontagged.keynormalizers;
+
+import edu.uci.ics.hyracks.api.dataflow.value.INormalizedKeyComputer;
+import edu.uci.ics.hyracks.api.dataflow.value.INormalizedKeyComputerFactory;
+
+/**
+ * This class uses a decorator pattern to wrap an ASC ordered INomralizedKeyComputerFactory implementation
+ * to obtain the DESC order.
+ */
+public class AWrappedDescNormalizedKeyComputerFactory implements INormalizedKeyComputerFactory {
+
+    private static final long serialVersionUID = 1L;
+    private final INormalizedKeyComputerFactory nkcf;
+
+    public AWrappedDescNormalizedKeyComputerFactory(INormalizedKeyComputerFactory nkcf) {
+        this.nkcf = nkcf;
+    }
+
+    @Override
+    public INormalizedKeyComputer createNormalizedKeyComputer() {
+        final INormalizedKeyComputer nkc = nkcf.createNormalizedKeyComputer();
+        return new INormalizedKeyComputer() {
+
+            @Override
+            public int normalize(byte[] bytes, int start, int length) {
+                int key = nkc.normalize(bytes, start + 1, length - 1);
+                return (int) ((long) 0xffffffff - (long) key);
+            }
+        };
+    }
+
+}
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/printers/AIntervalPrinter.java b/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/printers/AIntervalPrinter.java
new file mode 100644
index 0000000..99c40b2
--- /dev/null
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/printers/AIntervalPrinter.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.dataflow.data.nontagged.printers;
+
+import java.io.PrintStream;
+
+import edu.uci.ics.asterix.dataflow.data.nontagged.serde.AInt8SerializerDeserializer;
+import edu.uci.ics.asterix.om.types.ATypeTag;
+import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
+import edu.uci.ics.hyracks.algebricks.data.IPrinter;
+
+public class AIntervalPrinter implements IPrinter {
+
+    private static final long serialVersionUID = 1L;
+
+    public static final AIntervalPrinter INSTANCE = new AIntervalPrinter();
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.hyracks.algebricks.data.IPrinter#init()
+     */
+    @Override
+    public void init() throws AlgebricksException {
+    }
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.hyracks.algebricks.data.IPrinter#print(byte[], int, int, java.io.PrintStream)
+     */
+    @Override
+    public void print(byte[] b, int s, int l, PrintStream ps) throws AlgebricksException {
+        ps.print("interval(\"");
+
+        short typetag = AInt8SerializerDeserializer.getByte(b, s + 1 + 8 * 2);
+
+        IPrinter timeInstancePrinter;
+
+        if (typetag == ATypeTag.DATE.serialize()) {
+            timeInstancePrinter = ADatePrinter.INSTANCE;
+        } else if (typetag == ATypeTag.TIME.serialize()) {
+            timeInstancePrinter = ATimePrinter.INSTANCE;
+        } else if (typetag == ATypeTag.DATETIME.serialize()) {
+            timeInstancePrinter = ADateTimePrinter.INSTANCE;
+        } else {
+            throw new AlgebricksException("Unsupport internal time types in interval: " + typetag);
+        }
+
+        if (typetag == ATypeTag.TIME.serialize() || typetag == ATypeTag.DATE.serialize()) {
+            timeInstancePrinter.print(b, s + 1 + 4 - 1, 8, ps);
+            ps.print(", ");
+            timeInstancePrinter.print(b, s + 1 + 8 + 4 - 1, 8, ps);
+        } else {
+            timeInstancePrinter.print(b, s, 8, ps);
+            ps.print(", ");
+            timeInstancePrinter.print(b, s + 1 + 8 - 1, 8, ps);
+        }
+
+        ps.print("\")");
+    }
+}
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/printers/AIntervalPrinterFactory.java b/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/printers/AIntervalPrinterFactory.java
new file mode 100644
index 0000000..5500091
--- /dev/null
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/printers/AIntervalPrinterFactory.java
@@ -0,0 +1,30 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.dataflow.data.nontagged.printers;
+
+import edu.uci.ics.hyracks.algebricks.data.IPrinter;
+import edu.uci.ics.hyracks.algebricks.data.IPrinterFactory;
+
+public class AIntervalPrinterFactory implements IPrinterFactory {
+
+    private static final long serialVersionUID = 1L;
+    public static final AIntervalPrinterFactory INSTANCE = new AIntervalPrinterFactory();
+
+    @Override
+    public IPrinter createPrinter() {
+        return AIntervalPrinter.INSTANCE;
+    }
+
+}
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/printers/AObjectPrinter.java b/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/printers/AObjectPrinter.java
index edcfc8a..478ad2c 100644
--- a/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/printers/AObjectPrinter.java
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/printers/AObjectPrinter.java
@@ -73,6 +73,10 @@
                 ADurationPrinter.INSTANCE.print(b, s, l, ps);
                 break;
             }
+            case INTERVAL: {
+                AIntervalPrinter.INSTANCE.print(b, s, l, ps);
+                break;
+            }
             case POINT: {
                 APointPrinter.INSTANCE.print(b, s, l, ps);
                 break;
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/serde/ADateSerializerDeserializer.java b/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/serde/ADateSerializerDeserializer.java
index 9bd25f4..86a9a8d 100644
--- a/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/serde/ADateSerializerDeserializer.java
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/serde/ADateSerializerDeserializer.java
@@ -21,7 +21,7 @@
 import edu.uci.ics.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
 import edu.uci.ics.asterix.om.base.ADate;
 import edu.uci.ics.asterix.om.base.AMutableDate;
-import edu.uci.ics.asterix.om.base.temporal.ADateAndTimeParser;
+import edu.uci.ics.asterix.om.base.temporal.ADateParserFactory;
 import edu.uci.ics.asterix.om.base.temporal.GregorianCalendarSystem;
 import edu.uci.ics.asterix.om.base.temporal.StringCharSequenceAccessor;
 import edu.uci.ics.asterix.om.types.BuiltinType;
@@ -64,8 +64,8 @@
         long chrononTimeInMs = 0;
         try {
             StringCharSequenceAccessor charAccessor = new StringCharSequenceAccessor();
-            charAccessor.reset(date, 0);
-            chrononTimeInMs = ADateAndTimeParser.parseDatePart(charAccessor, true);
+            charAccessor.reset(date, 0, date.length());
+            chrononTimeInMs = ADateParserFactory.parseDatePart(charAccessor, true);
         } catch (Exception e) {
             throw new HyracksDataException(e);
         }
@@ -78,4 +78,8 @@
 
         dateSerde.serialize(aDate, out);
     }
+
+    public static int getChronon(byte[] byteArray, int offset) {
+        return AInt32SerializerDeserializer.getInt(byteArray, offset);
+    }
 }
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/serde/ADateTimeSerializerDeserializer.java b/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/serde/ADateTimeSerializerDeserializer.java
index cb9e8e0..cedfc8d 100644
--- a/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/serde/ADateTimeSerializerDeserializer.java
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/serde/ADateTimeSerializerDeserializer.java
@@ -21,7 +21,8 @@
 import edu.uci.ics.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
 import edu.uci.ics.asterix.om.base.ADateTime;
 import edu.uci.ics.asterix.om.base.AMutableDateTime;
-import edu.uci.ics.asterix.om.base.temporal.ADateAndTimeParser;
+import edu.uci.ics.asterix.om.base.temporal.ADateParserFactory;
+import edu.uci.ics.asterix.om.base.temporal.ATimeParserFactory;
 import edu.uci.ics.asterix.om.base.temporal.StringCharSequenceAccessor;
 import edu.uci.ics.asterix.om.types.BuiltinType;
 import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
@@ -66,7 +67,7 @@
         long chrononTimeInMs = 0;
         try {
             StringCharSequenceAccessor charAccessor = new StringCharSequenceAccessor();
-            charAccessor.reset(datetime, 0);
+            charAccessor.reset(datetime, 0, datetime.length());
 
             // +1 if it is negative (-)
             short timeOffset = (short) ((charAccessor.getCharAt(0) == '-') ? 1 : 0);
@@ -78,11 +79,11 @@
             // if extended form 11, else 9
             timeOffset += (charAccessor.getCharAt(timeOffset + 13) == ':') ? (short) (11) : (short) (9);
 
-            chrononTimeInMs = ADateAndTimeParser.parseDatePart(charAccessor, false);
+            chrononTimeInMs = ADateParserFactory.parseDatePart(charAccessor, false);
 
-            charAccessor.reset(datetime, timeOffset);
+            charAccessor.reset(datetime, timeOffset, datetime.length() - timeOffset);
 
-            chrononTimeInMs += ADateAndTimeParser.parseTimePart(charAccessor);
+            chrononTimeInMs += ATimeParserFactory.parseTimePart(charAccessor);
         } catch (Exception e) {
             throw new HyracksDataException(e);
         }
@@ -90,4 +91,8 @@
 
         datetimeSerde.serialize(aDateTime, out);
     }
+
+    public static long getChronon(byte[] data, int offset) {
+        return AInt64SerializerDeserializer.getLong(data, offset);
+    }
 }
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/serde/ADurationSerializerDeserializer.java b/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/serde/ADurationSerializerDeserializer.java
index c3333f0..88e2ea5 100644
--- a/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/serde/ADurationSerializerDeserializer.java
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/serde/ADurationSerializerDeserializer.java
@@ -7,7 +7,7 @@
 import edu.uci.ics.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
 import edu.uci.ics.asterix.om.base.ADuration;
 import edu.uci.ics.asterix.om.base.AMutableDuration;
-import edu.uci.ics.asterix.om.base.temporal.ADurationParser;
+import edu.uci.ics.asterix.om.base.temporal.ADurationParserFactory;
 import edu.uci.ics.asterix.om.base.temporal.StringCharSequenceAccessor;
 import edu.uci.ics.asterix.om.types.BuiltinType;
 import edu.uci.ics.hyracks.api.dataflow.value.ISerializerDeserializer;
@@ -48,12 +48,34 @@
         try {
             AMutableDuration aDuration = new AMutableDuration(0, 0);
             StringCharSequenceAccessor charAccessor = new StringCharSequenceAccessor();
-            charAccessor.reset(duration, 0);
-            ADurationParser.parse(charAccessor, aDuration);
+            charAccessor.reset(duration, 0, duration.length());
+            ADurationParserFactory.parseDuration(charAccessor, aDuration);
 
             durationSerde.serialize(aDuration, out);
         } catch (Exception e) {
             throw new HyracksDataException(e);
         }
     }
+
+    /**
+     * Get the year-month field of the duration as an integer number of days.
+     * 
+     * @param data
+     * @param offset
+     * @return
+     */
+    public static int getYearMonth(byte[] data, int offset) {
+        return AInt32SerializerDeserializer.getInt(data, offset);
+    }
+
+    /**
+     * Get the day-time field of the duration as an long integer number of milliseconds.
+     * 
+     * @param data
+     * @param offset
+     * @return
+     */
+    public static long getDayTime(byte[] data, int offset) {
+        return AInt64SerializerDeserializer.getLong(data, offset + 4);
+    }
 }
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/serde/AIntervalSerializerDeserializer.java b/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/serde/AIntervalSerializerDeserializer.java
new file mode 100644
index 0000000..7c87dfa
--- /dev/null
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/serde/AIntervalSerializerDeserializer.java
@@ -0,0 +1,264 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.dataflow.data.nontagged.serde;
+
+import java.io.DataInput;
+import java.io.DataOutput;
+import java.io.IOException;
+
+import edu.uci.ics.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
+import edu.uci.ics.asterix.om.base.AInterval;
+import edu.uci.ics.asterix.om.base.AMutableInterval;
+import edu.uci.ics.asterix.om.base.temporal.ADateParserFactory;
+import edu.uci.ics.asterix.om.base.temporal.ATimeParserFactory;
+import edu.uci.ics.asterix.om.base.temporal.GregorianCalendarSystem;
+import edu.uci.ics.asterix.om.base.temporal.StringCharSequenceAccessor;
+import edu.uci.ics.asterix.om.types.ATypeTag;
+import edu.uci.ics.asterix.om.types.BuiltinType;
+import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
+import edu.uci.ics.hyracks.api.dataflow.value.ISerializerDeserializer;
+import edu.uci.ics.hyracks.api.exceptions.HyracksDataException;
+
+public class AIntervalSerializerDeserializer implements ISerializerDeserializer<AInterval> {
+
+    private static final long serialVersionUID = 1L;
+
+    public static final AIntervalSerializerDeserializer INSTANCE = new AIntervalSerializerDeserializer();
+    @SuppressWarnings("unchecked")
+    private static final ISerializerDeserializer<AInterval> intervalSerde = AqlSerializerDeserializerProvider.INSTANCE
+            .getSerializerDeserializer(BuiltinType.AINTERVAL);
+
+    private static final String errorMessage = "This can not be an instance of interval";
+
+    private AIntervalSerializerDeserializer() {
+    }
+
+    @Override
+    public AInterval deserialize(DataInput in) throws HyracksDataException {
+        try {
+            return new AInterval(in.readLong(), in.readLong(), in.readByte());
+        } catch (IOException e) {
+            throw new HyracksDataException(e);
+        }
+
+    }
+
+    @Override
+    public void serialize(AInterval instance, DataOutput out) throws HyracksDataException {
+        try {
+            out.writeLong(instance.getIntervalStart());
+            out.writeLong(instance.getIntervalEnd());
+            out.writeByte(instance.getIntervalType());
+        } catch (IOException e) {
+            throw new HyracksDataException(e);
+        }
+
+    }
+
+    public static long getIntervalStart(byte[] data, int offset) {
+        return AInt64SerializerDeserializer.getLong(data, offset);
+    }
+
+    public static long getIntervalEnd(byte[] data, int offset) {
+        return AInt64SerializerDeserializer.getLong(data, offset + 8);
+    }
+
+    public static byte getIntervalTimeType(byte[] data, int offset) {
+        return data[offset + 8 * 2];
+    }
+
+    /**
+     * create an interval value from two given datetime instance.
+     * 
+     * @param interval
+     * @param out
+     * @throws HyracksDataException
+     */
+    public static void parseDatetime(String interval, DataOutput out) throws HyracksDataException {
+        AMutableInterval aInterval = new AMutableInterval(0l, 0l, (byte) 0);
+
+        long chrononTimeInMsStart = 0;
+        long chrononTimeInMsEnd = 0;
+        try {
+
+            StringCharSequenceAccessor charAccessor = new StringCharSequenceAccessor();
+
+            // Get the index for the comma
+            int commaIndex = interval.indexOf(',');
+            if (commaIndex < 0) {
+                throw new AlgebricksException("comma is missing for a string of interval");
+            }
+
+            int nonSpaceIndex = commaIndex - 1;
+            while (interval.charAt(nonSpaceIndex) == ' ') {
+                nonSpaceIndex--;
+            }
+
+            // Interval Start
+            charAccessor.reset(interval, 0, nonSpaceIndex + 1);
+
+            // +1 if it is negative (-)
+            short timeOffset = (short) ((charAccessor.getCharAt(0) == '-') ? 1 : 0);
+
+            if (charAccessor.getCharAt(timeOffset + 10) != 'T' && charAccessor.getCharAt(timeOffset + 8) != 'T') {
+                throw new AlgebricksException(errorMessage + ": missing T");
+            }
+
+            // if extended form 11, else 9
+            timeOffset += (charAccessor.getCharAt(timeOffset + 13) == ':') ? (short) (11) : (short) (9);
+
+            chrononTimeInMsStart = ADateParserFactory.parseDatePart(charAccessor, false);
+
+            charAccessor.reset(interval, timeOffset, nonSpaceIndex - timeOffset + 1);
+
+            chrononTimeInMsStart += ATimeParserFactory.parseTimePart(charAccessor);
+
+            // Interval End
+            nonSpaceIndex = commaIndex + 1;
+            while (interval.charAt(nonSpaceIndex) == ' ') {
+                nonSpaceIndex++;
+            }
+
+            charAccessor.reset(interval, nonSpaceIndex, interval.length() - nonSpaceIndex);
+
+            // +1 if it is negative (-)
+            timeOffset = (short) ((charAccessor.getCharAt(0) == '-') ? 1 : 0);
+
+            if (charAccessor.getCharAt(timeOffset + 10) != 'T' && charAccessor.getCharAt(timeOffset + 8) != 'T') {
+                throw new AlgebricksException(errorMessage + ": missing T");
+            }
+
+            // if extended form 11, else 9
+            timeOffset += (charAccessor.getCharAt(timeOffset + 13) == ':') ? (short) (11) : (short) (9);
+
+            chrononTimeInMsEnd = ADateParserFactory.parseDatePart(charAccessor, false);
+
+            charAccessor.reset(interval, nonSpaceIndex + timeOffset, interval.length() - nonSpaceIndex - timeOffset);
+
+            chrononTimeInMsEnd += ATimeParserFactory.parseTimePart(charAccessor);
+
+        } catch (Exception e) {
+            throw new HyracksDataException(e);
+        }
+
+        aInterval.setValue(chrononTimeInMsStart, chrononTimeInMsEnd, ATypeTag.DATETIME.serialize());
+
+        intervalSerde.serialize(aInterval, out);
+    }
+
+    public static void parseTime(String interval, DataOutput out) throws HyracksDataException {
+        AMutableInterval aInterval = new AMutableInterval(0l, 0l, (byte) 0);
+
+        long chrononTimeInMsStart = 0;
+        long chrononTimeInMsEnd = 0;
+        try {
+
+            StringCharSequenceAccessor charAccessor = new StringCharSequenceAccessor();
+
+            // Get the index for the comma
+            int commaIndex = interval.indexOf(',');
+            if (commaIndex < 0) {
+                throw new AlgebricksException("comma is missing for a string of interval");
+            }
+
+            int nonSpaceIndex = commaIndex - 1;
+            while (interval.charAt(nonSpaceIndex) == ' ') {
+                nonSpaceIndex--;
+            }
+
+            // Interval Start
+            charAccessor.reset(interval, 0, nonSpaceIndex + 1);
+            chrononTimeInMsStart = ATimeParserFactory.parseTimePart(charAccessor);
+
+            if (chrononTimeInMsStart < 0) {
+                chrononTimeInMsStart += GregorianCalendarSystem.CHRONON_OF_DAY;
+            }
+
+            // Interval End
+            nonSpaceIndex = commaIndex + 1;
+            while (interval.charAt(nonSpaceIndex) == ' ') {
+                nonSpaceIndex++;
+            }
+
+            charAccessor.reset(interval, nonSpaceIndex, interval.length() - nonSpaceIndex);
+            chrononTimeInMsEnd = ATimeParserFactory.parseTimePart(charAccessor);
+
+            if (chrononTimeInMsEnd < 0) {
+                chrononTimeInMsEnd += GregorianCalendarSystem.CHRONON_OF_DAY;
+            }
+
+        } catch (Exception e) {
+            throw new HyracksDataException(e);
+        }
+
+        aInterval.setValue(chrononTimeInMsStart, chrononTimeInMsEnd, ATypeTag.TIME.serialize());
+        intervalSerde.serialize(aInterval, out);
+    }
+
+    public static void parseDate(String interval, DataOutput out) throws HyracksDataException {
+        AMutableInterval aInterval = new AMutableInterval(0l, 0l, (byte) 0);
+
+        long chrononTimeInMsStart = 0;
+        long chrononTimeInMsEnd = 0;
+        short tempStart = 0;
+        short tempEnd = 0;
+        try {
+            StringCharSequenceAccessor charAccessor = new StringCharSequenceAccessor();
+
+            // Get the index for the comma
+            int commaIndex = interval.indexOf(',');
+            if (commaIndex < 0) {
+                throw new AlgebricksException("comma is missing for a string of interval");
+            }
+
+            int nonSpaceIndex = commaIndex - 1;
+            while (interval.charAt(nonSpaceIndex) == ' ') {
+                nonSpaceIndex--;
+            }
+
+            // Interval Start
+            charAccessor.reset(interval, 0, nonSpaceIndex + 1);
+
+            chrononTimeInMsStart = ADateParserFactory.parseDatePart(charAccessor, true);
+
+            if (chrononTimeInMsStart < 0 && chrononTimeInMsStart % GregorianCalendarSystem.CHRONON_OF_DAY != 0) {
+                tempStart = 1;
+            }
+
+            // Interval End
+            nonSpaceIndex = commaIndex + 1;
+            while (interval.charAt(nonSpaceIndex) == ' ') {
+                nonSpaceIndex++;
+            }
+
+            charAccessor.reset(interval, nonSpaceIndex, interval.length() - nonSpaceIndex);
+
+            chrononTimeInMsEnd = ADateParserFactory.parseDatePart(charAccessor, true);
+
+            if (chrononTimeInMsEnd < 0 && chrononTimeInMsEnd % GregorianCalendarSystem.CHRONON_OF_DAY != 0) {
+                tempEnd = 1;
+            }
+
+        } catch (Exception e) {
+            throw new HyracksDataException(e);
+        }
+
+        aInterval.setValue((chrononTimeInMsStart / GregorianCalendarSystem.CHRONON_OF_DAY) - tempStart,
+                (chrononTimeInMsEnd / GregorianCalendarSystem.CHRONON_OF_DAY) - tempEnd, ATypeTag.DATE.serialize());
+
+        intervalSerde.serialize(aInterval, out);
+    }
+
+}
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/serde/AObjectSerializerDeserializer.java b/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/serde/AObjectSerializerDeserializer.java
index 311a6bc..b5b7303 100644
--- a/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/serde/AObjectSerializerDeserializer.java
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/serde/AObjectSerializerDeserializer.java
@@ -15,6 +15,7 @@
 import edu.uci.ics.asterix.om.base.AInt32;
 import edu.uci.ics.asterix.om.base.AInt64;
 import edu.uci.ics.asterix.om.base.AInt8;
+import edu.uci.ics.asterix.om.base.AInterval;
 import edu.uci.ics.asterix.om.base.ALine;
 import edu.uci.ics.asterix.om.base.ANull;
 import edu.uci.ics.asterix.om.base.AOrderedList;
@@ -84,6 +85,9 @@
             case DURATION: {
                 return ADurationSerializerDeserializer.INSTANCE.deserialize(in);
             }
+            case INTERVAL: {
+                return AIntervalSerializerDeserializer.INSTANCE.deserialize(in);
+            }
             case POINT: {
                 return APointSerializerDeserializer.INSTANCE.deserialize(in);
             }
@@ -108,9 +112,9 @@
             case UNORDEREDLIST: {
                 return AUnorderedListSerializerDeserializer.SCHEMALESS_INSTANCE.deserialize(in);
             }
-                // case TYPE: {
-                // return AUnorderedListBytesConverter.INSTANCE.deserialize(in);
-                // }
+            // case TYPE: {
+            // return AUnorderedListBytesConverter.INSTANCE.deserialize(in);
+            // }
             default: {
                 throw new NotImplementedException("No serializer/deserializer implemented for type " + typeTag + " .");
             }
@@ -179,6 +183,10 @@
                 ADurationSerializerDeserializer.INSTANCE.serialize((ADuration) instance, out);
                 break;
             }
+            case INTERVAL: {
+                AIntervalSerializerDeserializer.INSTANCE.serialize((AInterval) instance, out);
+                break;
+            }
             case POINT: {
                 APointSerializerDeserializer.INSTANCE.serialize((APoint) instance, out);
                 break;
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/serde/ATimeSerializerDeserializer.java b/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/serde/ATimeSerializerDeserializer.java
index 8860f2a..26e8d7a 100644
--- a/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/serde/ATimeSerializerDeserializer.java
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/serde/ATimeSerializerDeserializer.java
@@ -7,7 +7,7 @@
 import edu.uci.ics.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
 import edu.uci.ics.asterix.om.base.AMutableTime;
 import edu.uci.ics.asterix.om.base.ATime;
-import edu.uci.ics.asterix.om.base.temporal.ADateAndTimeParser;
+import edu.uci.ics.asterix.om.base.temporal.ATimeParserFactory;
 import edu.uci.ics.asterix.om.base.temporal.StringCharSequenceAccessor;
 import edu.uci.ics.asterix.om.types.BuiltinType;
 import edu.uci.ics.hyracks.api.dataflow.value.ISerializerDeserializer;
@@ -52,8 +52,8 @@
 
         try {
             StringCharSequenceAccessor charAccessor = new StringCharSequenceAccessor();
-            charAccessor.reset(time, 0);
-            chrononTimeInMs = ADateAndTimeParser.parseTimePart(charAccessor);
+            charAccessor.reset(time, 0, time.length());
+            chrononTimeInMs = ATimeParserFactory.parseTimePart(charAccessor);
         } catch (Exception e) {
             throw new HyracksDataException(e);
         }
@@ -63,4 +63,8 @@
         timeSerde.serialize(aTime, out);
     }
 
+    public static int getChronon(byte[] byteArray, int offset) {
+        return AInt32SerializerDeserializer.getInt(byteArray, offset);
+    }
+
 }
\ No newline at end of file
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/formats/base/IDataFormat.java b/asterix-om/src/main/java/edu/uci/ics/asterix/formats/base/IDataFormat.java
index c1df096..813c3a0 100644
--- a/asterix-om/src/main/java/edu/uci/ics/asterix/formats/base/IDataFormat.java
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/formats/base/IDataFormat.java
@@ -14,6 +14,7 @@
 import edu.uci.ics.hyracks.algebricks.data.IBinaryBooleanInspectorFactory;
 import edu.uci.ics.hyracks.algebricks.data.IBinaryComparatorFactoryProvider;
 import edu.uci.ics.hyracks.algebricks.data.IBinaryHashFunctionFactoryProvider;
+import edu.uci.ics.hyracks.algebricks.data.IBinaryHashFunctionFamilyProvider;
 import edu.uci.ics.hyracks.algebricks.data.IBinaryIntegerInspectorFactory;
 import edu.uci.ics.hyracks.algebricks.data.INormalizedKeyComputerFactoryProvider;
 import edu.uci.ics.hyracks.algebricks.data.IPrinterFactoryProvider;
@@ -63,4 +64,6 @@
     public IExpressionEvalSizeComputer getExpressionEvalSizeComputer();
 
     public INormalizedKeyComputerFactoryProvider getNormalizedKeyComputerFactoryProvider();
+
+    public IBinaryHashFunctionFamilyProvider getBinaryHashFunctionFamilyProvider();
 }
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/formats/nontagged/AqlBinaryComparatorFactoryProvider.java b/asterix-om/src/main/java/edu/uci/ics/asterix/formats/nontagged/AqlBinaryComparatorFactoryProvider.java
index e4db8da..02f0e47 100644
--- a/asterix-om/src/main/java/edu/uci/ics/asterix/formats/nontagged/AqlBinaryComparatorFactoryProvider.java
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/formats/nontagged/AqlBinaryComparatorFactoryProvider.java
@@ -2,6 +2,7 @@
 
 import java.io.Serializable;
 
+import edu.uci.ics.asterix.dataflow.data.nontagged.comparators.ADateOrTimeAscBinaryComparatorFactory;
 import edu.uci.ics.asterix.dataflow.data.nontagged.comparators.ADateTimeAscBinaryComparatorFactory;
 import edu.uci.ics.asterix.dataflow.data.nontagged.comparators.AObjectAscBinaryComparatorFactory;
 import edu.uci.ics.asterix.dataflow.data.nontagged.comparators.AObjectDescBinaryComparatorFactory;
@@ -19,8 +20,8 @@
 import edu.uci.ics.hyracks.data.std.primitive.FloatPointable;
 import edu.uci.ics.hyracks.data.std.primitive.IntegerPointable;
 import edu.uci.ics.hyracks.data.std.primitive.LongPointable;
+import edu.uci.ics.hyracks.data.std.primitive.RawUTF8StringPointable;
 import edu.uci.ics.hyracks.data.std.primitive.ShortPointable;
-import edu.uci.ics.hyracks.data.std.primitive.UTF8StringPointable;
 
 public class AqlBinaryComparatorFactoryProvider implements IBinaryComparatorFactoryProvider, Serializable {
 
@@ -39,7 +40,7 @@
     public static final PointableBinaryComparatorFactory DOUBLE_POINTABLE_INSTANCE = new PointableBinaryComparatorFactory(
             DoublePointable.FACTORY);
     public static final PointableBinaryComparatorFactory UTF8STRING_POINTABLE_INSTANCE = new PointableBinaryComparatorFactory(
-            UTF8StringPointable.FACTORY);
+            RawUTF8StringPointable.FACTORY);
     // Equivalent to UTF8STRING_POINTABLE_INSTANCE but all characters are considered lower case to implement case-insensitive comparisons.    
     public static final PointableBinaryComparatorFactory UTF8STRING_LOWERCASE_POINTABLE_INSTANCE = new PointableBinaryComparatorFactory(
             UTF8StringLowercasePointable.FACTORY);
@@ -64,11 +65,11 @@
     public IBinaryComparatorFactory getBinaryComparatorFactory(Object type, boolean ascending) {
         if (type == null) {
             return anyBinaryComparatorFactory(ascending);
-        }        
+        }
         IAType aqlType = (IAType) type;
         return getBinaryComparatorFactory(aqlType.getTypeTag(), ascending);
     }
-    
+
     public IBinaryComparatorFactory getBinaryComparatorFactory(ATypeTag type, boolean ascending) {
         switch (type) {
             case ANY:
@@ -120,13 +121,14 @@
                 return addOffset(RectangleBinaryComparatorFactory.INSTANCE, ascending);
             }
             case DATE:
-            case TIME:
+            case TIME: {
+                return addOffset(ADateOrTimeAscBinaryComparatorFactory.INSTANCE, ascending);
+            }
             case DATETIME: {
                 return addOffset(ADateTimeAscBinaryComparatorFactory.INSTANCE, ascending);
             }
             default: {
-                throw new NotImplementedException("No binary comparator factory implemented for type "
-                        + type + " .");
+                throw new NotImplementedException("No binary comparator factory implemented for type " + type + " .");
             }
         }
     }
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/formats/nontagged/AqlBinaryHashFunctionFactoryProvider.java b/asterix-om/src/main/java/edu/uci/ics/asterix/formats/nontagged/AqlBinaryHashFunctionFactoryProvider.java
index cab8ded..1afdbf8 100644
--- a/asterix-om/src/main/java/edu/uci/ics/asterix/formats/nontagged/AqlBinaryHashFunctionFactoryProvider.java
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/formats/nontagged/AqlBinaryHashFunctionFactoryProvider.java
@@ -16,20 +16,25 @@
 import edu.uci.ics.hyracks.data.std.primitive.DoublePointable;
 import edu.uci.ics.hyracks.data.std.primitive.FloatPointable;
 import edu.uci.ics.hyracks.data.std.primitive.IntegerPointable;
+import edu.uci.ics.hyracks.data.std.primitive.RawUTF8StringPointable;
 import edu.uci.ics.hyracks.data.std.primitive.UTF8StringPointable;
 
-
 public class AqlBinaryHashFunctionFactoryProvider implements IBinaryHashFunctionFactoryProvider, Serializable {
 
     private static final long serialVersionUID = 1L;
     public static final AqlBinaryHashFunctionFactoryProvider INSTANCE = new AqlBinaryHashFunctionFactoryProvider();
-    public static final PointableBinaryHashFunctionFactory INTEGER_POINTABLE_INSTANCE = new PointableBinaryHashFunctionFactory(IntegerPointable.FACTORY);
-    public static final PointableBinaryHashFunctionFactory FLOAT_POINTABLE_INSTANCE = new PointableBinaryHashFunctionFactory(FloatPointable.FACTORY);
-    public static final PointableBinaryHashFunctionFactory DOUBLE_POINTABLE_INSTANCE = new PointableBinaryHashFunctionFactory(DoublePointable.FACTORY);
-    public static final PointableBinaryHashFunctionFactory UTF8STRING_POINTABLE_INSTANCE = new PointableBinaryHashFunctionFactory(UTF8StringPointable.FACTORY);
+    public static final PointableBinaryHashFunctionFactory INTEGER_POINTABLE_INSTANCE = new PointableBinaryHashFunctionFactory(
+            IntegerPointable.FACTORY);
+    public static final PointableBinaryHashFunctionFactory FLOAT_POINTABLE_INSTANCE = new PointableBinaryHashFunctionFactory(
+            FloatPointable.FACTORY);
+    public static final PointableBinaryHashFunctionFactory DOUBLE_POINTABLE_INSTANCE = new PointableBinaryHashFunctionFactory(
+            DoublePointable.FACTORY);
+    public static final PointableBinaryHashFunctionFactory UTF8STRING_POINTABLE_INSTANCE = new PointableBinaryHashFunctionFactory(
+            RawUTF8StringPointable.FACTORY);
     // Equivalent to UTF8STRING_POINTABLE_INSTANCE but all characters are considered lower case to implement case-insensitive hashing.    
-    public static final PointableBinaryHashFunctionFactory UTF8STRING_LOWERCASE_POINTABLE_INSTANCE = new PointableBinaryHashFunctionFactory(UTF8StringLowercasePointable.FACTORY);
-    
+    public static final PointableBinaryHashFunctionFactory UTF8STRING_LOWERCASE_POINTABLE_INSTANCE = new PointableBinaryHashFunctionFactory(
+            UTF8StringLowercasePointable.FACTORY);
+
     private AqlBinaryHashFunctionFactoryProvider() {
     }
 
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/formats/nontagged/AqlBinaryHashFunctionFamilyProvider.java b/asterix-om/src/main/java/edu/uci/ics/asterix/formats/nontagged/AqlBinaryHashFunctionFamilyProvider.java
new file mode 100644
index 0000000..bc7ba26
--- /dev/null
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/formats/nontagged/AqlBinaryHashFunctionFamilyProvider.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright 2009-2010 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package edu.uci.ics.asterix.formats.nontagged;
+
+import java.io.Serializable;
+
+import edu.uci.ics.asterix.dataflow.data.nontagged.hash.MurmurHash3BinaryHashFunctionFamily;
+import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
+import edu.uci.ics.hyracks.algebricks.data.IBinaryHashFunctionFamilyProvider;
+import edu.uci.ics.hyracks.api.dataflow.value.IBinaryHashFunctionFamily;
+
+/**
+ * We use a type-independent binary hash function family from the hyracks
+ * codebase
+ */
+public class AqlBinaryHashFunctionFamilyProvider implements
+		IBinaryHashFunctionFamilyProvider, Serializable {
+
+	private static final long serialVersionUID = 1L;
+	public static final AqlBinaryHashFunctionFamilyProvider INSTANCE = new AqlBinaryHashFunctionFamilyProvider();
+
+	private AqlBinaryHashFunctionFamilyProvider() {
+
+	}
+
+	@Override
+	public IBinaryHashFunctionFamily getBinaryHashFunctionFamily(Object type)
+			throws AlgebricksException {
+		return MurmurHash3BinaryHashFunctionFamily.INSTANCE;
+	}
+
+}
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/formats/nontagged/AqlNormalizedKeyComputerFactoryProvider.java b/asterix-om/src/main/java/edu/uci/ics/asterix/formats/nontagged/AqlNormalizedKeyComputerFactoryProvider.java
index fe953dc..23306ed 100644
--- a/asterix-om/src/main/java/edu/uci/ics/asterix/formats/nontagged/AqlNormalizedKeyComputerFactoryProvider.java
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/formats/nontagged/AqlNormalizedKeyComputerFactoryProvider.java
@@ -1,12 +1,15 @@
 package edu.uci.ics.asterix.formats.nontagged;
 
-import edu.uci.ics.asterix.dataflow.data.nontagged.keynormalizers.AInt32AscNormalizedKeyComputerFactory;
-import edu.uci.ics.asterix.dataflow.data.nontagged.keynormalizers.AInt32DescNormalizedKeyComputerFactory;
-import edu.uci.ics.asterix.dataflow.data.nontagged.keynormalizers.AStringAscNormalizedKeyComputerFactory;
-import edu.uci.ics.asterix.dataflow.data.nontagged.keynormalizers.AStringDescNormalizedKeyComputerFactory;
+import edu.uci.ics.asterix.dataflow.data.nontagged.keynormalizers.AWrappedAscNormalizedKeyComputerFactory;
+import edu.uci.ics.asterix.dataflow.data.nontagged.keynormalizers.AWrappedDescNormalizedKeyComputerFactory;
 import edu.uci.ics.asterix.om.types.IAType;
 import edu.uci.ics.hyracks.algebricks.data.INormalizedKeyComputerFactoryProvider;
 import edu.uci.ics.hyracks.api.dataflow.value.INormalizedKeyComputerFactory;
+import edu.uci.ics.hyracks.dataflow.common.data.normalizers.DoubleNormalizedKeyComputerFactory;
+import edu.uci.ics.hyracks.dataflow.common.data.normalizers.FloatNormalizedKeyComputerFactory;
+import edu.uci.ics.hyracks.dataflow.common.data.normalizers.Integer64NormalizedKeyComputerFactory;
+import edu.uci.ics.hyracks.dataflow.common.data.normalizers.IntegerNormalizedKeyComputerFactory;
+import edu.uci.ics.hyracks.dataflow.common.data.normalizers.UTF8StringNormalizedKeyComputerFactory;
 
 public class AqlNormalizedKeyComputerFactoryProvider implements INormalizedKeyComputerFactoryProvider {
 
@@ -21,10 +24,19 @@
         if (ascending) {
             switch (aqlType.getTypeTag()) {
                 case INT32: {
-                    return AInt32AscNormalizedKeyComputerFactory.INSTANCE;
+                    return new AWrappedAscNormalizedKeyComputerFactory(new IntegerNormalizedKeyComputerFactory());
+                }
+                case INT64: {
+                    return new AWrappedAscNormalizedKeyComputerFactory(new Integer64NormalizedKeyComputerFactory());
+                }
+                case FLOAT: {
+                    return new AWrappedAscNormalizedKeyComputerFactory(new FloatNormalizedKeyComputerFactory());
+                }
+                case DOUBLE: {
+                    return new AWrappedAscNormalizedKeyComputerFactory(new DoubleNormalizedKeyComputerFactory());
                 }
                 case STRING: {
-                    return AStringAscNormalizedKeyComputerFactory.INSTANCE;
+                    return new AWrappedAscNormalizedKeyComputerFactory(new UTF8StringNormalizedKeyComputerFactory());
                 }
                 default: {
                     return null;
@@ -33,10 +45,19 @@
         } else {
             switch (aqlType.getTypeTag()) {
                 case INT32: {
-                    return AInt32DescNormalizedKeyComputerFactory.INSTANCE;
+                    return new AWrappedDescNormalizedKeyComputerFactory(new IntegerNormalizedKeyComputerFactory());
+                }
+                case INT64: {
+                    return new AWrappedDescNormalizedKeyComputerFactory(new Integer64NormalizedKeyComputerFactory());
+                }
+                case FLOAT: {
+                    return new AWrappedDescNormalizedKeyComputerFactory(new FloatNormalizedKeyComputerFactory());
+                }
+                case DOUBLE: {
+                    return new AWrappedDescNormalizedKeyComputerFactory(new DoubleNormalizedKeyComputerFactory());
                 }
                 case STRING: {
-                    return AStringDescNormalizedKeyComputerFactory.INSTANCE;
+                    return new AWrappedDescNormalizedKeyComputerFactory(new UTF8StringNormalizedKeyComputerFactory());
                 }
                 default: {
                     return null;
@@ -44,5 +65,4 @@
             }
         }
     }
-
 }
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/formats/nontagged/AqlPrinterFactoryProvider.java b/asterix-om/src/main/java/edu/uci/ics/asterix/formats/nontagged/AqlPrinterFactoryProvider.java
index b576ce0..fe8792f 100644
--- a/asterix-om/src/main/java/edu/uci/ics/asterix/formats/nontagged/AqlPrinterFactoryProvider.java
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/formats/nontagged/AqlPrinterFactoryProvider.java
@@ -1,6 +1,5 @@
 package edu.uci.ics.asterix.formats.nontagged;
 
-
 import edu.uci.ics.asterix.dataflow.data.nontagged.printers.ABooleanPrinterFactory;
 import edu.uci.ics.asterix.dataflow.data.nontagged.printers.ACirclePrinterFactory;
 import edu.uci.ics.asterix.dataflow.data.nontagged.printers.ADatePrinterFactory;
@@ -12,6 +11,7 @@
 import edu.uci.ics.asterix.dataflow.data.nontagged.printers.AInt32PrinterFactory;
 import edu.uci.ics.asterix.dataflow.data.nontagged.printers.AInt64PrinterFactory;
 import edu.uci.ics.asterix.dataflow.data.nontagged.printers.AInt8PrinterFactory;
+import edu.uci.ics.asterix.dataflow.data.nontagged.printers.AIntervalPrinterFactory;
 import edu.uci.ics.asterix.dataflow.data.nontagged.printers.ALinePrinterFactory;
 import edu.uci.ics.asterix.dataflow.data.nontagged.printers.ANullPrinterFactory;
 import edu.uci.ics.asterix.dataflow.data.nontagged.printers.ANullableFieldPrinterFactory;
@@ -49,8 +49,8 @@
 
         if (aqlType != null) {
             switch (aqlType.getTypeTag()) {
-                // case ANYTYPE:
-                // return AAnyTypePrinterFactory.INSTANCE;
+            // case ANYTYPE:
+            // return AAnyTypePrinterFactory.INSTANCE;
                 case INT8:
                     return AInt8PrinterFactory.INSTANCE;
                 case INT16:
@@ -75,6 +75,8 @@
                     return ADateTimePrinterFactory.INSTANCE;
                 case DURATION:
                     return ADurationPrinterFactory.INSTANCE;
+                case INTERVAL:
+                    return AIntervalPrinterFactory.INSTANCE;
                 case POINT:
                     return APointPrinterFactory.INSTANCE;
                 case POINT3D:
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/formats/nontagged/AqlSerializerDeserializerProvider.java b/asterix-om/src/main/java/edu/uci/ics/asterix/formats/nontagged/AqlSerializerDeserializerProvider.java
index 5492c5c..29e33fd 100644
--- a/asterix-om/src/main/java/edu/uci/ics/asterix/formats/nontagged/AqlSerializerDeserializerProvider.java
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/formats/nontagged/AqlSerializerDeserializerProvider.java
@@ -16,6 +16,7 @@
 import edu.uci.ics.asterix.dataflow.data.nontagged.serde.AInt32SerializerDeserializer;
 import edu.uci.ics.asterix.dataflow.data.nontagged.serde.AInt64SerializerDeserializer;
 import edu.uci.ics.asterix.dataflow.data.nontagged.serde.AInt8SerializerDeserializer;
+import edu.uci.ics.asterix.dataflow.data.nontagged.serde.AIntervalSerializerDeserializer;
 import edu.uci.ics.asterix.dataflow.data.nontagged.serde.ALineSerializerDeserializer;
 import edu.uci.ics.asterix.dataflow.data.nontagged.serde.ANullSerializerDeserializer;
 import edu.uci.ics.asterix.dataflow.data.nontagged.serde.AObjectSerializerDeserializer;
@@ -111,6 +112,9 @@
             case DURATION: {
                 return ADurationSerializerDeserializer.INSTANCE;
             }
+            case INTERVAL: {
+                return AIntervalSerializerDeserializer.INSTANCE;
+            }
             case ORDEREDLIST: {
                 return new AOrderedListSerializerDeserializer((AOrderedListType) aqlType);
             }
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/formats/nontagged/AqlTypeTraitProvider.java b/asterix-om/src/main/java/edu/uci/ics/asterix/formats/nontagged/AqlTypeTraitProvider.java
index eac6602..a7e8e83 100644
--- a/asterix-om/src/main/java/edu/uci/ics/asterix/formats/nontagged/AqlTypeTraitProvider.java
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/formats/nontagged/AqlTypeTraitProvider.java
@@ -14,6 +14,7 @@
     private static final ITypeTraits FOURBYTETYPETRAIT = new TypeTrait(4 + 1);
     private static final ITypeTraits EIGHTBYTETYPETRAIT = new TypeTrait(8 + 1);
     private static final ITypeTraits SIXTEENBYTETYPETRAIT = new TypeTrait(16 + 1);
+    private static final ITypeTraits SEVENTEENBYTETYPETRAIT = new TypeTrait(17 + 1);
     private static final ITypeTraits THIRTYTWOBYTETYPETRAIT = new TypeTrait(32 + 1);
     private static final ITypeTraits TWENTYFOURBYTETYPETRAIT = new TypeTrait(24 + 1);
 
@@ -42,6 +43,8 @@
                 return EIGHTBYTETYPETRAIT;
             case POINT:
                 return SIXTEENBYTETYPETRAIT;
+            case INTERVAL:
+                return SEVENTEENBYTETYPETRAIT;
             case POINT3D:
                 return TWENTYFOURBYTETYPETRAIT;
             case LINE:
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/ADate.java b/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/ADate.java
index ea4c33b..097b736 100644
--- a/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/ADate.java
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/ADate.java
@@ -30,7 +30,7 @@
      */
     protected int chrononTimeInDay;
 
-    private static long CHRONON_OF_DAY = 24 * 60 * 60 * 1000;
+    protected static long CHRONON_OF_DAY = 24 * 60 * 60 * 1000;
 
     public ADate(int chrononTimeInDay) {
         this.chrononTimeInDay = chrononTimeInDay;
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/AInterval.java b/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/AInterval.java
new file mode 100644
index 0000000..66a587a
--- /dev/null
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/AInterval.java
@@ -0,0 +1,144 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.om.base;
+
+import edu.uci.ics.asterix.common.exceptions.AsterixException;
+import edu.uci.ics.asterix.om.base.temporal.GregorianCalendarSystem;
+import edu.uci.ics.asterix.om.types.ATypeTag;
+import edu.uci.ics.asterix.om.types.BuiltinType;
+import edu.uci.ics.asterix.om.types.IAType;
+import edu.uci.ics.asterix.om.visitors.IOMVisitor;
+
+public class AInterval implements IAObject {
+
+    protected long intervalStart;
+    protected long intervalEnd;
+    protected byte typetag;
+
+    public AInterval(long intervalStart, long intervalEnd, byte typetag) {
+        this.intervalStart = intervalStart;
+        this.intervalEnd = intervalEnd;
+        this.typetag = typetag;
+    }
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.om.base.IAObject#getType()
+     */
+    @Override
+    public IAType getType() {
+        return BuiltinType.AINTERVAL;
+    }
+
+    public int compare(Object o) {
+        if (!(o instanceof AInterval)) {
+            return -1;
+        }
+        AInterval d = (AInterval) o;
+        if (d.intervalStart == this.intervalStart && d.intervalEnd == this.intervalEnd && d.typetag == this.typetag) {
+            return 0;
+        } else {
+            return -1;
+        }
+    }
+
+    public boolean equals(Object o) {
+        if (!(o instanceof AInterval)) {
+            return false;
+        } else {
+            AInterval t = (AInterval) o;
+            return (t.intervalStart == this.intervalStart || t.intervalEnd == this.intervalEnd
+                    && t.typetag == this.typetag);
+        }
+    }
+
+    @Override
+    public int hashCode() {
+        return (int) (((int) (this.intervalStart ^ (this.intervalStart >>> 32))) * 31 + (int) (this.intervalEnd ^ (this.intervalEnd >>> 32)))
+                * 31 + (int) this.typetag;
+    }
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.om.base.IAObject#accept(edu.uci.ics.asterix.om.visitors.IOMVisitor)
+     */
+    @Override
+    public void accept(IOMVisitor visitor) throws AsterixException {
+        visitor.visitAInterval(this);
+    }
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.om.base.IAObject#deepEqual(edu.uci.ics.asterix.om.base.IAObject)
+     */
+    @Override
+    public boolean deepEqual(IAObject obj) {
+        return equals(obj);
+    }
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.om.base.IAObject#hash()
+     */
+    @Override
+    public int hash() {
+        return hashCode();
+    }
+
+    @Override
+    public String toString() {
+        StringBuilder sbder = new StringBuilder();
+        sbder.append("AInterval: { ");
+        if (typetag == ATypeTag.DATE.serialize()) {
+            sbder.append("ADate: { ");
+            GregorianCalendarSystem.getInstance().getExtendStringRepWithTimezoneUntilField(
+                    intervalStart * ADate.CHRONON_OF_DAY, 0, sbder, GregorianCalendarSystem.Fields.YEAR,
+                    GregorianCalendarSystem.Fields.DAY);
+            sbder.append(" }, ADate: {");
+            GregorianCalendarSystem.getInstance().getExtendStringRepWithTimezoneUntilField(
+                    intervalEnd * ADate.CHRONON_OF_DAY, 0, sbder, GregorianCalendarSystem.Fields.YEAR,
+                    GregorianCalendarSystem.Fields.DAY);
+            sbder.append(" }");
+        } else if (typetag == ATypeTag.TIME.serialize()) {
+            sbder.append("ATime: { ");
+            GregorianCalendarSystem.getInstance().getExtendStringRepWithTimezoneUntilField(intervalStart, 0, sbder,
+                    GregorianCalendarSystem.Fields.HOUR, GregorianCalendarSystem.Fields.MILLISECOND);
+            sbder.append(" }, ATime: { ");
+
+            GregorianCalendarSystem.getInstance().getExtendStringRepWithTimezoneUntilField(intervalEnd, 0, sbder,
+                    GregorianCalendarSystem.Fields.HOUR, GregorianCalendarSystem.Fields.MILLISECOND);
+            sbder.append(" }");
+        } else if (typetag == ATypeTag.DATETIME.serialize()) {
+            sbder.append("ADateTime: { ");
+            GregorianCalendarSystem.getInstance().getExtendStringRepWithTimezoneUntilField(intervalStart, 0, sbder,
+                    GregorianCalendarSystem.Fields.YEAR, GregorianCalendarSystem.Fields.MILLISECOND);
+            sbder.append(" }, ADateTime: { ");
+            GregorianCalendarSystem.getInstance().getExtendStringRepWithTimezoneUntilField(intervalEnd, 0, sbder,
+                    GregorianCalendarSystem.Fields.YEAR, GregorianCalendarSystem.Fields.MILLISECOND);
+            sbder.append(" }");
+        }
+        sbder.append(" }");
+        return sbder.toString();
+    }
+
+    public long getIntervalStart() {
+        return intervalStart;
+    }
+
+    public long getIntervalEnd() {
+        return intervalEnd;
+    }
+
+    public short getIntervalType() {
+        return typetag;
+    }
+
+}
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/AMutableInterval.java b/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/AMutableInterval.java
new file mode 100644
index 0000000..055535f
--- /dev/null
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/AMutableInterval.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.om.base;
+
+public class AMutableInterval extends AInterval {
+
+    public AMutableInterval(long intervalStart, long intervalEnd, byte typetag) {
+        super(intervalStart, intervalEnd, typetag);
+    }
+
+    public void setValue(long intervalStart, long intervalEnd, byte typetag) {
+        this.intervalStart = intervalStart;
+        this.intervalEnd = intervalEnd;
+        this.typetag = typetag;
+    }
+
+}
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/ADateAndTimeParser.java b/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/ADateAndTimeParser.java
deleted file mode 100644
index 30ee525..0000000
--- a/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/ADateAndTimeParser.java
+++ /dev/null
@@ -1,264 +0,0 @@
-/*
- * Copyright 2009-2011 by The Regents of the University of California
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * you may obtain a copy of the License from
- * 
- *     http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package edu.uci.ics.asterix.om.base.temporal;
-
-public class ADateAndTimeParser {
-
-    private static final GregorianCalendarSystem gCalInstance = GregorianCalendarSystem.getInstance();
-
-    private static final String dateErrorMessage = "Wrong date format!";
-    private static final String timeErrorMessage = "Wrong time format!";
-
-    /**
-     * Parse the given char sequence as a date string, and return the milliseconds represented by the date.
-     * 
-     * @param charAccessor
-     *            accessor for the char sequence
-     * @param isDateOnly
-     *            indicating whether it is a single date string, or it is the date part of a datetime string
-     * @param errorMessage
-     * @return
-     * @throws Exception
-     */
-    public static <T> long parseDatePart(ICharSequenceAccessor<T> charAccessor, boolean isDateOnly) throws Exception {
-
-        int length = charAccessor.getLength();
-        int offset = 0;
-
-        int year = 0, month = 0, day = 0;
-        boolean positive = true;
-
-        boolean isExtendedForm = false;
-
-        if (charAccessor.getCharAt(offset) == '-') {
-            offset++;
-            positive = false;
-        }
-
-        if ((isDateOnly) && charAccessor.getCharAt(offset + 4) == '-' || (!isDateOnly)
-                && charAccessor.getCharAt(offset + 13) == ':') {
-            isExtendedForm = true;
-        }
-
-        if (isExtendedForm) {
-            if (charAccessor.getCharAt(offset + 4) != '-' || charAccessor.getCharAt(offset + 7) != '-') {
-                throw new Exception(dateErrorMessage);
-            }
-        }
-
-        // year
-        for (int i = 0; i < 4; i++) {
-            if (charAccessor.getCharAt(offset + i) >= '0' && charAccessor.getCharAt(offset + i) <= '9') {
-                year = year * 10 + charAccessor.getCharAt(offset + i) - '0';
-            } else {
-                throw new Exception(dateErrorMessage);
-            }
-        }
-
-        if (year < GregorianCalendarSystem.FIELD_MINS[GregorianCalendarSystem.Fields.YEAR.ordinal()]
-                || year > GregorianCalendarSystem.FIELD_MAXS[GregorianCalendarSystem.Fields.YEAR.ordinal()]) {
-            throw new Exception(dateErrorMessage + ": year " + year);
-        }
-
-        offset += (isExtendedForm) ? 5 : 4;
-
-        // month
-        for (int i = 0; i < 2; i++) {
-            if ((charAccessor.getCharAt(offset + i) >= '0' && charAccessor.getCharAt(offset + i) <= '9')) {
-                month = month * 10 + charAccessor.getCharAt(offset + i) - '0';
-            } else {
-                throw new Exception(dateErrorMessage);
-            }
-        }
-
-        if (month < GregorianCalendarSystem.FIELD_MINS[GregorianCalendarSystem.Fields.MONTH.ordinal()]
-                || month > GregorianCalendarSystem.FIELD_MAXS[GregorianCalendarSystem.Fields.MONTH.ordinal()]) {
-            throw new Exception(dateErrorMessage + ": month " + month);
-        }
-        offset += (isExtendedForm) ? 3 : 2;
-
-        // day
-        for (int i = 0; i < 2; i++) {
-            if ((charAccessor.getCharAt(offset + i) >= '0' && charAccessor.getCharAt(offset + i) <= '9')) {
-                day = day * 10 + charAccessor.getCharAt(offset + i) - '0';
-            } else {
-                throw new Exception(dateErrorMessage);
-            }
-        }
-
-        if (day < GregorianCalendarSystem.FIELD_MINS[GregorianCalendarSystem.Fields.DAY.ordinal()]
-                || day > GregorianCalendarSystem.FIELD_MAXS[GregorianCalendarSystem.Fields.DAY.ordinal()]) {
-            throw new Exception(dateErrorMessage + ": day " + day);
-        }
-
-        offset += 2;
-
-        if (!positive) {
-            year *= -1;
-        }
-
-        if (isDateOnly && length > offset) {
-            throw new Exception(dateErrorMessage);
-        }
-        return gCalInstance.getChronon(year, month, day, 0, 0, 0, 0, 0);
-    }
-
-    /**
-     * Parse the given char sequence as a time string, and return the milliseconds represented by the time.
-     * 
-     * @param charAccessor
-     * @return
-     * @throws Exception
-     */
-    public static <T> int parseTimePart(ICharSequenceAccessor<T> charAccessor) throws Exception {
-
-        int length = charAccessor.getLength();
-        int offset = 0;
-
-        int hour = 0, min = 0, sec = 0, millis = 0;
-        int timezone = 0;
-
-        boolean isExtendedForm = false;
-        if (charAccessor.getCharAt(offset + 2) == ':') {
-            isExtendedForm = true;
-        }
-
-        if (isExtendedForm && (charAccessor.getCharAt(offset + 2) != ':' || charAccessor.getCharAt(offset + 5) != ':')) {
-            throw new Exception(timeErrorMessage);
-        }
-        // hour
-        for (int i = 0; i < 2; i++) {
-            if ((charAccessor.getCharAt(offset + i) >= '0' && charAccessor.getCharAt(offset + i) <= '9')) {
-                hour = hour * 10 + charAccessor.getCharAt(offset + i) - '0';
-            } else {
-                throw new Exception(timeErrorMessage);
-            }
-        }
-
-        if (hour < GregorianCalendarSystem.FIELD_MINS[GregorianCalendarSystem.Fields.HOUR.ordinal()]
-                || hour > GregorianCalendarSystem.FIELD_MAXS[GregorianCalendarSystem.Fields.HOUR.ordinal()]) {
-            throw new Exception(timeErrorMessage + ": hour " + hour);
-        }
-
-        offset += (isExtendedForm) ? 3 : 2;
-
-        // minute
-        for (int i = 0; i < 2; i++) {
-            if ((charAccessor.getCharAt(offset + i) >= '0' && charAccessor.getCharAt(offset + i) <= '9')) {
-                min = min * 10 + charAccessor.getCharAt(offset + i) - '0';
-            } else {
-                throw new Exception(timeErrorMessage);
-            }
-        }
-
-        if (min < GregorianCalendarSystem.FIELD_MINS[GregorianCalendarSystem.Fields.MINUTE.ordinal()]
-                || min > GregorianCalendarSystem.FIELD_MAXS[GregorianCalendarSystem.Fields.MINUTE.ordinal()]) {
-            throw new Exception(timeErrorMessage + ": min " + min);
-        }
-
-        offset += (isExtendedForm) ? 3 : 2;
-
-        // second
-        for (int i = 0; i < 2; i++) {
-            if ((charAccessor.getCharAt(offset + i) >= '0' && charAccessor.getCharAt(offset + i) <= '9')) {
-                sec = sec * 10 + charAccessor.getCharAt(offset + i) - '0';
-            } else {
-                throw new Exception(timeErrorMessage);
-            }
-        }
-
-        if (sec < GregorianCalendarSystem.FIELD_MINS[GregorianCalendarSystem.Fields.SECOND.ordinal()]
-                || sec > GregorianCalendarSystem.FIELD_MAXS[GregorianCalendarSystem.Fields.SECOND.ordinal()]) {
-            throw new Exception(timeErrorMessage + ": sec " + sec);
-        }
-
-        offset += 2;
-
-        if ((isExtendedForm && length > offset && charAccessor.getCharAt(offset) == '.')
-                || (!isExtendedForm && length > offset)) {
-
-            offset += (isExtendedForm) ? 1 : 0;
-            int i = 0;
-            for (; i < 3 && offset + i < length; i++) {
-                if (charAccessor.getCharAt(offset + i) >= '0' && charAccessor.getCharAt(offset + i) <= '9') {
-                    millis = millis * 10 + charAccessor.getCharAt(offset + i) - '0';
-                } else {
-                    break;
-                }
-            }
-
-            offset += i;
-
-            for (; i < 3; i++) {
-                millis = millis * 10;
-            }
-
-            // error is thrown if more than three digits are seen for the millisecond part
-            if (charAccessor.getCharAt(offset) >= '0' && charAccessor.getCharAt(offset) <= '9') {
-                throw new Exception("Wrong format of time instance: too many fields for millisecond.");
-            }
-        }
-
-        if (length > offset) {
-            if (charAccessor.getCharAt(offset) != 'Z') {
-                if ((charAccessor.getCharAt(offset) != '+' && charAccessor.getCharAt(offset) != '-')
-                        || (isExtendedForm && charAccessor.getCharAt(offset + 3) != ':')) {
-                    throw new Exception(timeErrorMessage);
-                }
-
-                short timezoneHour = 0;
-                short timezoneMinute = 0;
-
-                for (int i = 0; i < 2; i++) {
-                    if ((charAccessor.getCharAt(offset + 1 + i) >= '0' && charAccessor.getCharAt(offset + 1 + i) <= '9')) {
-                        timezoneHour = (short) (timezoneHour * 10 + charAccessor.getCharAt(offset + 1 + i) - '0');
-                    } else {
-                        throw new Exception(timeErrorMessage);
-                    }
-                }
-
-                if (timezoneHour < GregorianCalendarSystem.TIMEZONE_HOUR_MIN
-                        || timezoneHour > GregorianCalendarSystem.TIMEZONE_HOUR_MAX) {
-                    throw new Exception(timeErrorMessage + ": time zone hour " + timezoneHour);
-                }
-
-                int temp_offset = (isExtendedForm) ? 1 : 0;
-
-                for (int i = 0; i < 2; i++) {
-                    if ((charAccessor.getCharAt(offset + temp_offset + 3 + i) >= '0' && charAccessor.getCharAt(offset
-                            + temp_offset + 3 + i) <= '9')) {
-                        timezoneMinute = (short) (timezoneMinute * 10
-                                + charAccessor.getCharAt(offset + temp_offset + 3 + i) - '0');
-                    } else {
-                        throw new Exception(timeErrorMessage);
-                    }
-                }
-
-                if (timezoneMinute < GregorianCalendarSystem.TIMEZONE_MIN_MIN
-                        || timezoneMinute > GregorianCalendarSystem.TIMEZONE_MIN_MAX) {
-                    throw new Exception(timeErrorMessage + ": time zone minute " + timezoneMinute);
-                }
-
-                if (charAccessor.getCharAt(offset) == '-') {
-                    timezone = (byte) -((timezoneHour * 4) + timezoneMinute / 15);
-                } else {
-                    timezone = (byte) ((timezoneHour * 4) + timezoneMinute / 15);
-                }
-            }
-        }
-
-        return gCalInstance.getChronon(hour, min, sec, millis, timezone);
-    }
-}
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/ADateParserFactory.java b/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/ADateParserFactory.java
new file mode 100644
index 0000000..8192919
--- /dev/null
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/ADateParserFactory.java
@@ -0,0 +1,150 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.om.base.temporal;
+
+import java.io.DataOutput;
+import java.io.IOException;
+
+import edu.uci.ics.hyracks.api.exceptions.HyracksDataException;
+import edu.uci.ics.hyracks.dataflow.common.data.parsers.IValueParser;
+import edu.uci.ics.hyracks.dataflow.common.data.parsers.IValueParserFactory;
+
+public class ADateParserFactory implements IValueParserFactory {
+
+    public static final IValueParserFactory INSTANCE = new ADateParserFactory();
+
+    private static final long serialVersionUID = 1L;
+
+    private static final String dateErrorMessage = "Wrong input format for a date value";
+
+    private ADateParserFactory() {
+
+    }
+
+    @Override
+    public IValueParser createValueParser() {
+
+        final CharArrayCharSequenceAccessor charArrayAccessor = new CharArrayCharSequenceAccessor();
+
+        return new IValueParser() {
+
+            @Override
+            public void parse(char[] buffer, int start, int length, DataOutput out) throws HyracksDataException {
+                charArrayAccessor.reset(buffer, start, length);
+                try {
+                    out.writeInt((int) (parseDatePart(charArrayAccessor, true) / GregorianCalendarSystem.CHRONON_OF_DAY));
+                } catch (IOException ex) {
+                    throw new HyracksDataException(ex);
+                }
+            }
+        };
+    }
+
+    /**
+     * Parse the given char sequence as a date string, and return the milliseconds represented by the date.
+     * 
+     * @param charAccessor
+     *            accessor for the char sequence
+     * @param isDateOnly
+     *            indicating whether it is a single date string, or it is the date part of a datetime string
+     * @param errorMessage
+     * @return
+     * @throws Exception
+     */
+    public static <T> long parseDatePart(ICharSequenceAccessor<T> charAccessor, boolean isDateOnly)
+            throws HyracksDataException {
+
+        int length = charAccessor.getLength();
+        int offset = 0;
+
+        int year = 0, month = 0, day = 0;
+        boolean positive = true;
+
+        boolean isExtendedForm = false;
+
+        if (charAccessor.getCharAt(offset) == '-') {
+            offset++;
+            positive = false;
+        }
+
+        if ((isDateOnly) && charAccessor.getCharAt(offset + 4) == '-' || (!isDateOnly)
+                && charAccessor.getCharAt(offset + 13) == ':') {
+            isExtendedForm = true;
+        }
+
+        if (isExtendedForm) {
+            if (charAccessor.getCharAt(offset + 4) != '-' || charAccessor.getCharAt(offset + 7) != '-') {
+                throw new HyracksDataException("Missing dash in the date string as an extended form");
+            }
+        }
+
+        // year
+        for (int i = 0; i < 4; i++) {
+            if (charAccessor.getCharAt(offset + i) >= '0' && charAccessor.getCharAt(offset + i) <= '9') {
+                year = year * 10 + charAccessor.getCharAt(offset + i) - '0';
+            } else {
+                throw new HyracksDataException("Non-numeric value in year field");
+            }
+        }
+
+        if (year < GregorianCalendarSystem.FIELD_MINS[GregorianCalendarSystem.Fields.YEAR.ordinal()]
+                || year > GregorianCalendarSystem.FIELD_MAXS[GregorianCalendarSystem.Fields.YEAR.ordinal()]) {
+            throw new HyracksDataException(dateErrorMessage + ": year " + year);
+        }
+
+        offset += (isExtendedForm) ? 5 : 4;
+
+        // month
+        for (int i = 0; i < 2; i++) {
+            if ((charAccessor.getCharAt(offset + i) >= '0' && charAccessor.getCharAt(offset + i) <= '9')) {
+                month = month * 10 + charAccessor.getCharAt(offset + i) - '0';
+            } else {
+                throw new HyracksDataException("Non-numeric value in month field");
+            }
+        }
+
+        if (month < GregorianCalendarSystem.FIELD_MINS[GregorianCalendarSystem.Fields.MONTH.ordinal()]
+                || month > GregorianCalendarSystem.FIELD_MAXS[GregorianCalendarSystem.Fields.MONTH.ordinal()]) {
+            throw new HyracksDataException(dateErrorMessage + ": month " + month);
+        }
+        offset += (isExtendedForm) ? 3 : 2;
+
+        // day
+        for (int i = 0; i < 2; i++) {
+            if ((charAccessor.getCharAt(offset + i) >= '0' && charAccessor.getCharAt(offset + i) <= '9')) {
+                day = day * 10 + charAccessor.getCharAt(offset + i) - '0';
+            } else {
+                throw new HyracksDataException("Non-numeric value in day field");
+            }
+        }
+
+        if (day < GregorianCalendarSystem.FIELD_MINS[GregorianCalendarSystem.Fields.DAY.ordinal()]
+                || day > GregorianCalendarSystem.FIELD_MAXS[GregorianCalendarSystem.Fields.DAY.ordinal()]) {
+            throw new HyracksDataException(dateErrorMessage + ": day " + day);
+        }
+
+        offset += 2;
+
+        if (!positive) {
+            year *= -1;
+        }
+
+        if (isDateOnly && length > offset) {
+            throw new HyracksDataException("Too many chars for a date only value");
+        }
+        return GregorianCalendarSystem.getInstance().getChronon(year, month, day, 0, 0, 0, 0, 0);
+    }
+
+}
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/ADateTimeParserFactory.java b/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/ADateTimeParserFactory.java
new file mode 100644
index 0000000..2df3c3b
--- /dev/null
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/ADateTimeParserFactory.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.om.base.temporal;
+
+import java.io.DataOutput;
+import java.io.IOException;
+
+import edu.uci.ics.hyracks.api.exceptions.HyracksDataException;
+import edu.uci.ics.hyracks.dataflow.common.data.parsers.IValueParser;
+import edu.uci.ics.hyracks.dataflow.common.data.parsers.IValueParserFactory;
+
+public class ADateTimeParserFactory implements IValueParserFactory {
+
+    public static final IValueParserFactory INSTANCE = new ADateTimeParserFactory();
+
+    private static final long serialVersionUID = 1L;
+
+    private static final String dateTimeErrorMessage = "Wrong Input Format for a DateTime Value";
+
+    private ADateTimeParserFactory() {
+
+    }
+
+    @Override
+    public IValueParser createValueParser() {
+
+        final CharArrayCharSequenceAccessor charArrayAccessor = new CharArrayCharSequenceAccessor();
+
+        return new IValueParser() {
+
+            @Override
+            public void parse(char[] buffer, int start, int length, DataOutput out) throws HyracksDataException {
+                long chrononTimeInMs = 0;
+
+                charArrayAccessor.reset(buffer, start, length);
+
+                short timeOffset = (short) ((charArrayAccessor.getCharAt(0) == '-') ? 1 : 0);
+
+                if (charArrayAccessor.getCharAt(timeOffset + 10) != 'T'
+                        && charArrayAccessor.getCharAt(timeOffset + 8) != 'T') {
+                    throw new HyracksDataException(dateTimeErrorMessage + ": missing T");
+                }
+
+                // if extended form 11, else 9
+                timeOffset += (charArrayAccessor.getCharAt(timeOffset + 13) == ':') ? (short) (11) : (short) (9);
+
+                chrononTimeInMs = ADateParserFactory.parseDatePart(charArrayAccessor, false);
+
+                charArrayAccessor.reset(buffer, start + timeOffset, length - timeOffset);
+
+                chrononTimeInMs += ATimeParserFactory.parseTimePart(charArrayAccessor);
+
+                try {
+                    out.writeLong(chrononTimeInMs);
+                } catch (IOException ex) {
+                    throw new HyracksDataException(ex);
+                }
+            }
+        };
+    }
+
+}
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/ADurationParser.java b/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/ADurationParserFactory.java
similarity index 62%
rename from asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/ADurationParser.java
rename to asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/ADurationParserFactory.java
index 5d43bba..b176061 100644
--- a/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/ADurationParser.java
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/ADurationParserFactory.java
@@ -14,9 +14,45 @@
  */
 package edu.uci.ics.asterix.om.base.temporal;
 
-import edu.uci.ics.asterix.om.base.AMutableDuration;
+import java.io.DataOutput;
+import java.io.IOException;
 
-public class ADurationParser {
+import edu.uci.ics.asterix.om.base.AMutableDuration;
+import edu.uci.ics.hyracks.api.exceptions.HyracksDataException;
+import edu.uci.ics.hyracks.dataflow.common.data.parsers.IValueParser;
+import edu.uci.ics.hyracks.dataflow.common.data.parsers.IValueParserFactory;
+
+public class ADurationParserFactory implements IValueParserFactory {
+
+    public static final IValueParserFactory INSTANCE = new ADurationParserFactory();
+
+    private static final long serialVersionUID = 1L;
+
+    private static final String durationErrorMessage = "Wrong Input Format for a Duration Value";
+
+    private ADurationParserFactory() {
+
+    }
+
+    @Override
+    public IValueParser createValueParser() {
+        final CharArrayCharSequenceAccessor charArrayAccessor = new CharArrayCharSequenceAccessor();
+        final AMutableDuration aMutableDuration = new AMutableDuration(0, 0);
+        return new IValueParser() {
+
+            @Override
+            public void parse(char[] buffer, int start, int length, DataOutput out) throws HyracksDataException {
+                charArrayAccessor.reset(buffer, start, length);
+                parseDuration(charArrayAccessor, aMutableDuration);
+                try {
+                    out.writeInt(aMutableDuration.getMonths());
+                    out.writeLong(aMutableDuration.getMilliseconds());
+                } catch (IOException ex) {
+                    throw new HyracksDataException(ex);
+                }
+            }
+        };
+    }
 
     private enum State {
         NOTHING_READ,
@@ -30,9 +66,8 @@
         SEC;
     };
 
-    private static final String errorMessage = "This can not be an instance of duration";
-
-    public static <T> void parse(ICharSequenceAccessor<T> charAccessor, AMutableDuration aDuration) throws Exception {
+    public static <T> void parseDuration(ICharSequenceAccessor<T> charAccessor, AMutableDuration aDuration)
+            throws HyracksDataException {
 
         boolean positive = true;
         int offset = 0;
@@ -45,7 +80,7 @@
         }
 
         if (charAccessor.getCharAt(offset++) != 'P') {
-            throw new Exception(errorMessage);
+            throw new HyracksDataException(durationErrorMessage + ": Missing leading 'P'.");
         }
 
         for (; offset < charAccessor.getLength(); offset++) {
@@ -59,7 +94,7 @@
                             year = value;
                             state = State.YEAR;
                         } else {
-                            throw new Exception(errorMessage);
+                            throw new HyracksDataException(durationErrorMessage + ": wrong YEAR feild.");
                         }
                         break;
                     case 'M':
@@ -68,13 +103,13 @@
                                 month = value;
                                 state = State.MONTH;
                             } else {
-                                throw new Exception(errorMessage);
+                                throw new HyracksDataException(durationErrorMessage + ": wrong MONTH field.");
                             }
                         } else if (state.compareTo(State.MIN) < 0) {
                             minute = value;
                             state = State.MIN;
                         } else {
-                            throw new Exception(errorMessage);
+                            throw new HyracksDataException(durationErrorMessage + ": wrong MIN field.");
                         }
                         break;
                     case 'D':
@@ -82,14 +117,14 @@
                             day = value;
                             state = State.DAY;
                         } else {
-                            throw new Exception(errorMessage);
+                            throw new HyracksDataException(durationErrorMessage + ": wrong DAY field");
                         }
                         break;
                     case 'T':
                         if (state.compareTo(State.TIME) < 0) {
                             state = State.TIME;
                         } else {
-                            throw new Exception(errorMessage);
+                            throw new HyracksDataException(durationErrorMessage + ": wrong TIME field.");
                         }
                         break;
 
@@ -98,7 +133,7 @@
                             hour = value;
                             state = State.HOUR;
                         } else {
-                            throw new Exception(errorMessage);
+                            throw new HyracksDataException(durationErrorMessage + ": wrong HOUR field.");
                         }
                         break;
                     case '.':
@@ -110,7 +145,8 @@
                                     if (i < 4) {
                                         millisecond = millisecond * 10 + (charAccessor.getCharAt(offset + i) - '0');
                                     } else {
-                                        throw new Exception(errorMessage);
+                                        throw new HyracksDataException(durationErrorMessage
+                                                + ": wrong MILLISECOND field.");
                                     }
                                 } else {
                                     break;
@@ -119,18 +155,18 @@
                             offset += i;
                             state = State.MILLISEC;
                         } else {
-                            throw new Exception(errorMessage);
+                            throw new HyracksDataException(durationErrorMessage + ": wrong MILLISECOND field.");
                         }
                     case 'S':
                         if (state.compareTo(State.SEC) < 0) {
                             second = value;
                             state = State.SEC;
                         } else {
-                            throw new Exception(errorMessage);
+                            throw new HyracksDataException(durationErrorMessage + ": wrong SECOND field.");
                         }
                         break;
                     default:
-                        throw new Exception(errorMessage);
+                        throw new HyracksDataException(durationErrorMessage + ": wrong format for duration.");
 
                 }
                 value = 0;
@@ -138,7 +174,7 @@
         }
 
         if (state.compareTo(State.TIME) == 0) {
-            throw new Exception(errorMessage);
+            throw new HyracksDataException(durationErrorMessage + ": no time fields after time separator.");
         }
 
         short temp = 1;
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/ATimeParserFactory.java b/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/ATimeParserFactory.java
new file mode 100644
index 0000000..d76f41d
--- /dev/null
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/ATimeParserFactory.java
@@ -0,0 +1,217 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.om.base.temporal;
+
+import java.io.DataOutput;
+import java.io.IOException;
+
+import edu.uci.ics.hyracks.api.exceptions.HyracksDataException;
+import edu.uci.ics.hyracks.dataflow.common.data.parsers.IValueParser;
+import edu.uci.ics.hyracks.dataflow.common.data.parsers.IValueParserFactory;
+
+public class ATimeParserFactory implements IValueParserFactory {
+
+    public static final IValueParserFactory INSTANCE = new ATimeParserFactory();
+
+    private static final long serialVersionUID = 1L;
+
+    private static final String timeErrorMessage = "Wrong Input Format for a Time Value";
+
+    private ATimeParserFactory() {
+
+    }
+
+    @Override
+    public IValueParser createValueParser() {
+
+        final CharArrayCharSequenceAccessor charArrayAccessor = new CharArrayCharSequenceAccessor();
+
+        return new IValueParser() {
+
+            @Override
+            public void parse(char[] buffer, int start, int length, DataOutput out) throws HyracksDataException {
+                charArrayAccessor.reset(buffer, start, length);
+                try {
+                    out.writeInt(parseTimePart(charArrayAccessor));
+                } catch (IOException ex) {
+                    throw new HyracksDataException(ex);
+                }
+            }
+        };
+    }
+
+    /**
+     * Parse the given char sequence as a time string, and return the milliseconds represented by the time.
+     * 
+     * @param charAccessor
+     * @return
+     * @throws Exception
+     */
+    public static <T> int parseTimePart(ICharSequenceAccessor<T> charAccessor) throws HyracksDataException {
+
+        int length = charAccessor.getLength();
+        int offset = 0;
+
+        int hour = 0, min = 0, sec = 0, millis = 0;
+        int timezone = 0;
+
+        boolean isExtendedForm = false;
+        if (charAccessor.getCharAt(offset + 2) == ':') {
+            isExtendedForm = true;
+        }
+
+        if (isExtendedForm && (charAccessor.getCharAt(offset + 2) != ':' || charAccessor.getCharAt(offset + 5) != ':')) {
+            throw new HyracksDataException(timeErrorMessage + ": Missing colon in an extended time format.");
+        }
+        // hour
+        for (int i = 0; i < 2; i++) {
+            if ((charAccessor.getCharAt(offset + i) >= '0' && charAccessor.getCharAt(offset + i) <= '9')) {
+                hour = hour * 10 + charAccessor.getCharAt(offset + i) - '0';
+            } else {
+                throw new HyracksDataException(timeErrorMessage + ": Non-numeric value in hour field");
+            }
+        }
+
+        if (hour < GregorianCalendarSystem.FIELD_MINS[GregorianCalendarSystem.Fields.HOUR.ordinal()]
+                || hour > GregorianCalendarSystem.FIELD_MAXS[GregorianCalendarSystem.Fields.HOUR.ordinal()]) {
+            throw new HyracksDataException(timeErrorMessage + ": hour " + hour);
+        }
+
+        offset += (isExtendedForm) ? 3 : 2;
+
+        // minute
+        for (int i = 0; i < 2; i++) {
+            if ((charAccessor.getCharAt(offset + i) >= '0' && charAccessor.getCharAt(offset + i) <= '9')) {
+                min = min * 10 + charAccessor.getCharAt(offset + i) - '0';
+            } else {
+                throw new HyracksDataException(timeErrorMessage + ": Non-numeric value in minute field");
+            }
+        }
+
+        if (min < GregorianCalendarSystem.FIELD_MINS[GregorianCalendarSystem.Fields.MINUTE.ordinal()]
+                || min > GregorianCalendarSystem.FIELD_MAXS[GregorianCalendarSystem.Fields.MINUTE.ordinal()]) {
+            throw new HyracksDataException(timeErrorMessage + ": min " + min);
+        }
+
+        offset += (isExtendedForm) ? 3 : 2;
+
+        // second
+        for (int i = 0; i < 2; i++) {
+            if ((charAccessor.getCharAt(offset + i) >= '0' && charAccessor.getCharAt(offset + i) <= '9')) {
+                sec = sec * 10 + charAccessor.getCharAt(offset + i) - '0';
+            } else {
+                throw new HyracksDataException(timeErrorMessage + ": Non-numeric value in second field");
+            }
+        }
+
+        if (sec < GregorianCalendarSystem.FIELD_MINS[GregorianCalendarSystem.Fields.SECOND.ordinal()]
+                || sec > GregorianCalendarSystem.FIELD_MAXS[GregorianCalendarSystem.Fields.SECOND.ordinal()]) {
+            throw new HyracksDataException(timeErrorMessage + ": sec " + sec);
+        }
+
+        offset += 2;
+
+        if ((isExtendedForm && length > offset && charAccessor.getCharAt(offset) == '.')
+                || (!isExtendedForm && length > offset)) {
+
+            offset += (isExtendedForm) ? 1 : 0;
+            int i = 0;
+            for (; i < 3 && offset + i < length; i++) {
+                if (charAccessor.getCharAt(offset + i) >= '0' && charAccessor.getCharAt(offset + i) <= '9') {
+                    millis = millis * 10 + charAccessor.getCharAt(offset + i) - '0';
+                } else {
+                    break;
+                }
+            }
+
+            offset += i;
+
+            for (; i < 3; i++) {
+                millis = millis * 10;
+            }
+
+            // error is thrown if more than three digits are seen for the millisecond part
+            if (charAccessor.getLength() > offset && charAccessor.getCharAt(offset) >= '0'
+                    && charAccessor.getCharAt(offset) <= '9') {
+                throw new HyracksDataException(timeErrorMessage + ": too many fields for millisecond.");
+            }
+        }
+
+        if (length > offset) {
+            timezone = parseTimezonePart(charAccessor, offset);
+        }
+
+        return GregorianCalendarSystem.getInstance().getChronon(hour, min, sec, millis, timezone);
+    }
+
+    /**
+     * Parse the given char sequence as a time string, and return the milliseconds represented by the time.
+     * 
+     * @param charAccessor
+     * @return
+     * @throws Exception
+     */
+    public static <T> int parseTimezonePart(ICharSequenceAccessor<T> charAccessor, int offset)
+            throws HyracksDataException {
+        int timezone = 0;
+
+        if (charAccessor.getCharAt(offset) != 'Z') {
+            if ((charAccessor.getCharAt(offset) != '+' && charAccessor.getCharAt(offset) != '-')) {
+                throw new HyracksDataException("Wrong timezone format: missing sign or missing colon for a time zone");
+            }
+
+            short timezoneHour = 0;
+            short timezoneMinute = 0;
+
+            for (int i = 0; i < 2; i++) {
+                if ((charAccessor.getCharAt(offset + 1 + i) >= '0' && charAccessor.getCharAt(offset + 1 + i) <= '9')) {
+                    timezoneHour = (short) (timezoneHour * 10 + charAccessor.getCharAt(offset + 1 + i) - '0');
+                } else {
+                    throw new HyracksDataException(timeErrorMessage + ": Non-numeric value in timezone hour field");
+                }
+            }
+
+            if (timezoneHour < GregorianCalendarSystem.TIMEZONE_HOUR_MIN
+                    || timezoneHour > GregorianCalendarSystem.TIMEZONE_HOUR_MAX) {
+                throw new HyracksDataException(timeErrorMessage + ": time zone hour " + timezoneHour);
+            }
+
+            int temp_offset = (charAccessor.getCharAt(offset + 3) == ':') ? 1 : 0;
+
+            for (int i = 0; i < 2; i++) {
+                if ((charAccessor.getCharAt(offset + temp_offset + 3 + i) >= '0' && charAccessor.getCharAt(offset
+                        + temp_offset + 3 + i) <= '9')) {
+                    timezoneMinute = (short) (timezoneMinute * 10
+                            + charAccessor.getCharAt(offset + temp_offset + 3 + i) - '0');
+                } else {
+                    throw new HyracksDataException(timeErrorMessage + ": Non-numeric value in timezone minute field");
+                }
+            }
+
+            if (timezoneMinute < GregorianCalendarSystem.TIMEZONE_MIN_MIN
+                    || timezoneMinute > GregorianCalendarSystem.TIMEZONE_MIN_MAX) {
+                throw new HyracksDataException(timeErrorMessage + ": time zone minute " + timezoneMinute);
+            }
+
+            if (charAccessor.getCharAt(offset) == '-') {
+                timezone = (byte) -((timezoneHour * 4) + timezoneMinute / 15);
+            } else {
+                timezone = (byte) ((timezoneHour * 4) + timezoneMinute / 15);
+            }
+        }
+        return timezone;
+    }
+
+}
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/ByteArrayCharSequenceAccessor.java b/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/ByteArrayCharSequenceAccessor.java
index e1a2135..453c86f 100644
--- a/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/ByteArrayCharSequenceAccessor.java
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/ByteArrayCharSequenceAccessor.java
@@ -14,27 +14,41 @@
  */
 package edu.uci.ics.asterix.om.base.temporal;
 
+import edu.uci.ics.asterix.common.exceptions.AsterixRuntimeException;
+
 public class ByteArrayCharSequenceAccessor implements ICharSequenceAccessor<Byte[]> {
 
-    private byte[] string;
+    private byte[] buf;
     private int offset;
-    private int beginOffset;
+    private int length;
 
     @Override
-    public char getCharAt(int index) {
-        return (char) (string[index + offset + beginOffset]);
+    public char getCharAt(int index) throws AsterixRuntimeException {
+        if (index < 0 || index >= length) {
+            throw new AsterixRuntimeException("Byte array char accessor is out of bound: " + index + ":" + length);
+        }
+        return (char) (buf[index + offset]);
     }
 
-    /* The offset is the position of the first letter in the byte array */
-    public void reset(byte[] obj, int beginOffset, int offset) {
-        string = obj;
+    /**
+     * Reset the wrapped byte array.
+     * 
+     * @param obj
+     *            The byte array to be wrapped
+     * @param beginOffset
+     *            The offset of the string stored in the byte array.
+     * @param offset
+     *            The offset of the substring of the string stored (offset from the beginOffset).
+     */
+    public void reset(byte[] obj, int offset, int length) {
+        this.buf = obj;
         this.offset = offset;
-        this.beginOffset = beginOffset;
+        this.length = length;
     }
 
     @Override
     public int getLength() {
-        return ((string[beginOffset - 2] & 0xff) << 8) + ((string[beginOffset - 1] & 0xff) << 0) - offset;
+        return length;
     }
 
 }
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/CharArrayCharSequenceAccessor.java b/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/CharArrayCharSequenceAccessor.java
new file mode 100644
index 0000000..404f0ee
--- /dev/null
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/CharArrayCharSequenceAccessor.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.om.base.temporal;
+
+import edu.uci.ics.asterix.common.exceptions.AsterixRuntimeException;
+
+public class CharArrayCharSequenceAccessor implements ICharSequenceAccessor<char[]> {
+
+    private char[] buf;
+    private int offset;
+    private int length;
+    
+    @Override
+    public char getCharAt(int index) throws AsterixRuntimeException {
+        if (index < 0 || index >= length) {
+            throw new AsterixRuntimeException("Byte array char accessor is out of bound: " + index + ":" + length);
+        }
+        return (char) (buf[index + offset]);
+    }
+
+    /**
+     * Reset the wrapped byte array.
+     * 
+     * @param obj
+     *            The byte array to be wrapped
+     * @param beginOffset
+     *            The offset of the string stored in the byte array.
+     * @param offset
+     *            The offset of the substring of the string stored (offset from the beginOffset).
+     */
+    public void reset(char[] obj, int offset, int length) {
+        this.buf = obj;
+        this.offset = offset;
+        this.length = length;
+    }
+
+    @Override
+    public int getLength() {
+        return length;
+ }
+
+}
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/DurationArithmeticOperations.java b/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/DurationArithmeticOperations.java
new file mode 100644
index 0000000..9d6bc2f
--- /dev/null
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/DurationArithmeticOperations.java
@@ -0,0 +1,87 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.om.base.temporal;
+
+/**
+ * Algorithms for duration related arithmetic operations.
+ */
+public class DurationArithmeticOperations {
+
+    private final static GregorianCalendarSystem calSystem = GregorianCalendarSystem.getInstance();
+
+    /**
+     * Add a duration (with yearMonth and dayTime) onto a time point. The algorithm works as described in
+     * <a
+     * href="http://www.w3.org/TR/xmlschema-2/#adding-durations-to-dateTimes">"XML: adding durations to dateTimes"</a>.
+     * <p/>
+     * The basic algorithm is like this: duration is applied to the time point as two separated fields: year-month field
+     * and day-time field. Year-month field is applied firstly by reserving the correct day within the month's range
+     * (for example add 1M to 03-31 will return 04-30). Then day-time field is applied.
+     * <p/>
+     * 
+     * @param pointChronon
+     * @param yearMonthDuration
+     * @param dayTimeDuration
+     * @return
+     */
+    public static long addDuration(long pointChronon, int yearMonthDuration, long dayTimeDuration) {
+
+        int year = calSystem.getYear(pointChronon);
+        int month = calSystem.getMonthOfYear(pointChronon, year);
+        int day = calSystem.getDayOfMonthYear(pointChronon, year, month);
+        int hour = calSystem.getHourOfDay(pointChronon);
+        int min = calSystem.getMinOfHour(pointChronon);
+        int sec = calSystem.getSecOfMin(pointChronon);
+        int ms = calSystem.getMillisOfSec(pointChronon);
+
+        // Apply the year-month duration
+        int carry = yearMonthDuration / 12;
+        month += (yearMonthDuration % 12);
+
+        if (month < 0) {
+            month += 12;
+            carry -= 1;
+        } else if (month > 12) {
+            month -= 12;
+            carry += 1;
+        }
+
+        year += carry;
+
+        boolean isLeapYear = calSystem.isLeapYear(year);
+
+        if (isLeapYear) {
+            if (day > GregorianCalendarSystem.DAYS_OF_MONTH_ORDI[month - 1]) {
+                day = GregorianCalendarSystem.DAYS_OF_MONTH_ORDI[month - 1];
+            }
+        } else {
+            if (day > GregorianCalendarSystem.DAYS_OF_MONTH_LEAP[month - 1]) {
+                day = GregorianCalendarSystem.DAYS_OF_MONTH_LEAP[month - 1];
+            }
+        }
+
+        return calSystem.getChronon(year, month, day, hour, min, sec, ms, 0) + dayTimeDuration;
+    }
+
+    public static int addDuration(int pointChronon, long dayTimeDuration) {
+        int rtnChronon = (int) ((pointChronon + dayTimeDuration) % GregorianCalendarSystem.CHRONON_OF_DAY);
+        if (rtnChronon < 0) {
+            rtnChronon += GregorianCalendarSystem.CHRONON_OF_DAY;
+        }
+
+        return rtnChronon;
+    }
+
+}
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/GregorianCalendarSystem.java b/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/GregorianCalendarSystem.java
index 149a1d2..d43f235 100644
--- a/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/GregorianCalendarSystem.java
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/GregorianCalendarSystem.java
@@ -57,6 +57,7 @@
     public static final int CHRONON_OF_MINUTE = 60 * CHRONON_OF_SECOND;
     public static final int CHRONON_OF_HOUR = 60 * CHRONON_OF_MINUTE;
     public static final long CHRONON_OF_DAY = 24 * CHRONON_OF_HOUR;
+    public static final int MONTHS_IN_A_YEAR = 12;
 
     /**
      * Minimum feasible value of each field
@@ -238,8 +239,25 @@
         return chrononTime;
     }
 
+    public long adjustChrononByTimezone(long chronon, int timezone) {
+        return chronon + timezone / 4 * CHRONON_OF_HOUR + (timezone % 4) * 15 * CHRONON_OF_MINUTE;
+    }
+
+    public static int getChrononInDays(long chronon) {
+        if (chronon >= 0) {
+            return (int) (chronon / CHRONON_OF_DAY);
+        } else {
+            if (chronon % CHRONON_OF_DAY != 0) {
+                return (int) (chronon / CHRONON_OF_DAY - 1);
+            } else {
+                return (int) (chronon / CHRONON_OF_DAY);
+            }
+        }
+    }
+
     /**
-     * Get the extended string representation of the given UTC chronon time under the given time zone. Only fields before
+     * Get the extended string representation of the given UTC chronon time under the given time zone. Only fields
+     * before
      * the given field index will be returned.
      * <p/>
      * The extended string representation is like:<br/>
@@ -258,6 +276,7 @@
 
         switch (startField) {
             case YEAR:
+            default:
                 sbder.append(String.format(year < 0 ? "%05d" : "%04d", year));
                 if (untilField == Fields.YEAR) {
                     return;
@@ -304,10 +323,13 @@
                 break;
         }
 
-        if (untilField.compareTo(Fields.DAY) > 0) {
+        if (timezone == 0) {
             sbder.append("Z");
         } else {
             short tzMin = (short) ((timezone % 4) * 15);
+            if (tzMin < 0) {
+                tzMin = (short) (-1 * tzMin);
+            }
             short tzHr = (short) (timezone / 4);
             sbder.append((tzHr >= 0 ? "+" : "-")).append(String.format("%02d", (tzHr < 0 ? -tzHr : tzHr))).append(":")
                     .append(String.format("%02d", tzMin));
@@ -328,6 +350,7 @@
 
         switch (startField) {
             case YEAR:
+            default:
                 sbder.append(String.format(year < 0 ? "%05d" : "%04d", year));
                 if (untilField == Fields.YEAR) {
                     return;
@@ -359,10 +382,13 @@
                 break;
         }
 
-        if (untilField.compareTo(Fields.DAY) > 0) {
+        if (timezone == 0) {
             sbder.append("Z");
         } else {
             short tzMin = (short) ((timezone % 4) * 15);
+            if (tzMin < 0) {
+                tzMin = (short) (-1 * tzMin);
+            }
             short tzHr = (short) (timezone / 4);
             sbder.append((tzHr >= 0 ? "+" : "-")).append(String.format("%02d", (tzHr < 0 ? -tzHr : tzHr)))
                     .append(String.format("%02d", tzMin));
@@ -422,7 +448,7 @@
      * @param year
      * @return
      */
-    protected boolean isLeapYear(int year) {
+    public boolean isLeapYear(int year) {
         return ((year & 3) == 0) && ((year % 100) != 0 || (year % 400) == 0);
     }
 
@@ -454,7 +480,8 @@
      * Get the year for the given chronon time.
      * <p/>
      * This code is directly from the Joda library BadicChronology.java.<br/>
-     * The original authers are Stephen Colebourne, Brain S O'Neill and Guy Allard, and modified by JArod Wen on May 7th, 2012.
+     * The original authers are Stephen Colebourne, Brain S O'Neill and Guy Allard, and modified by JArod Wen on May
+     * 7th, 2012.
      * 
      * @param chrononTime
      * @return
@@ -501,7 +528,8 @@
      * Get the month of the year for the given chronon time and the year.
      * <p/>
      * This code is directly from the Joda library BasicGJChronology.java.<br/>
-     * The original authers are Stephen Colebourne, Brain S O'Neill and Guy Allard, and modified by JArod Wen on May 7th, 2012.
+     * The original authers are Stephen Colebourne, Brain S O'Neill and Guy Allard, and modified by JArod Wen on May
+     * 7th, 2012 and commented by Theodoros Ioannou on July 2012.
      * <p/>
      * 
      * @param millis
@@ -565,7 +593,8 @@
      * Get the day of the given month and year for the input chronon time.
      * <p/>
      * This function is directly from Joda Library BasicChronology.java.<br/>
-     * The original authers are Stephen Colebourne, Brain S O'Neill and Guy Allard, and modified by JArod Wen on May 7th, 2012.
+     * The original authers are Stephen Colebourne, Brain S O'Neill and Guy Allard, and modified by JArod Wen on May
+     * 7th, 2012.
      * <p/>
      * 
      * @param millis
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/ICharSequenceAccessor.java b/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/ICharSequenceAccessor.java
index 6b4e898..d5a99a0 100644
--- a/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/ICharSequenceAccessor.java
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/ICharSequenceAccessor.java
@@ -14,10 +14,23 @@
  */
 package edu.uci.ics.asterix.om.base.temporal;
 
+import edu.uci.ics.asterix.common.exceptions.AsterixRuntimeException;
+
 public interface ICharSequenceAccessor<T> {
 
-    public char getCharAt(int index);
+    /**
+     * Return the character in the wrapped char sequence at the given index.
+     * 
+     * @param index
+     * @return
+     */
+    public char getCharAt(int index) throws AsterixRuntimeException;
 
+    /**
+     * Get the length of the wrapped char sequence.
+     * 
+     * @return
+     */
     public int getLength();
 
 }
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/StringCharSequenceAccessor.java b/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/StringCharSequenceAccessor.java
index 6c02340..17e483a 100644
--- a/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/StringCharSequenceAccessor.java
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/StringCharSequenceAccessor.java
@@ -14,24 +14,31 @@
  */
 package edu.uci.ics.asterix.om.base.temporal;
 
+import edu.uci.ics.asterix.common.exceptions.AsterixRuntimeException;
+
 public class StringCharSequenceAccessor implements ICharSequenceAccessor<String> {
 
     private String string;
     private int offset;
+    private int length;
 
     @Override
-    public char getCharAt(int index) {
+    public char getCharAt(int index) throws AsterixRuntimeException {
+        if (index >= length) {
+            throw new AsterixRuntimeException("String accessor is out of bound.");
+        }
         return string.charAt(index + offset);
     }
 
-    public void reset(String obj, int offset) {
-        string = obj;
+    public void reset(String obj, int offset, int len) {
+        this.string = obj;
         this.offset = offset;
+        this.length = len;
     }
 
     @Override
     public int getLength() {
-        return string.length() - offset;
+        return length;
     }
 
 }
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/om/functions/AsterixBuiltinFunctions.java b/asterix-om/src/main/java/edu/uci/ics/asterix/om/functions/AsterixBuiltinFunctions.java
index 42904fc..a547737 100644
--- a/asterix-om/src/main/java/edu/uci/ics/asterix/om/functions/AsterixBuiltinFunctions.java
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/om/functions/AsterixBuiltinFunctions.java
@@ -12,6 +12,8 @@
 import edu.uci.ics.asterix.om.typecomputer.base.IResultTypeComputer;
 import edu.uci.ics.asterix.om.typecomputer.impl.ABooleanTypeComputer;
 import edu.uci.ics.asterix.om.typecomputer.impl.ACircleTypeComputer;
+import edu.uci.ics.asterix.om.typecomputer.impl.ADateTimeTypeComputer;
+import edu.uci.ics.asterix.om.typecomputer.impl.ADateTypeComputer;
 import edu.uci.ics.asterix.om.typecomputer.impl.ADoubleTypeComputer;
 import edu.uci.ics.asterix.om.typecomputer.impl.AFloatTypeComputer;
 import edu.uci.ics.asterix.om.typecomputer.impl.AInt32TypeComputer;
@@ -21,6 +23,7 @@
 import edu.uci.ics.asterix.om.typecomputer.impl.APolygonTypeComputer;
 import edu.uci.ics.asterix.om.typecomputer.impl.ARectangleTypeComputer;
 import edu.uci.ics.asterix.om.typecomputer.impl.AStringTypeComputer;
+import edu.uci.ics.asterix.om.typecomputer.impl.ATimeTypeComputer;
 import edu.uci.ics.asterix.om.typecomputer.impl.BinaryBooleanOrNullFunctionTypeComputer;
 import edu.uci.ics.asterix.om.typecomputer.impl.BinaryStringBoolOrNullTypeComputer;
 import edu.uci.ics.asterix.om.typecomputer.impl.BinaryStringStringOrNullTypeComputer;
@@ -38,7 +41,9 @@
 import edu.uci.ics.asterix.om.typecomputer.impl.NonTaggedSumTypeComputer;
 import edu.uci.ics.asterix.om.typecomputer.impl.NonTaggedSwitchCaseComputer;
 import edu.uci.ics.asterix.om.typecomputer.impl.NonTaggedUnaryMinusTypeComputer;
+import edu.uci.ics.asterix.om.typecomputer.impl.NotNullTypeComputer;
 import edu.uci.ics.asterix.om.typecomputer.impl.OpenRecordConstructorResultType;
+import edu.uci.ics.asterix.om.typecomputer.impl.OptionalABooleanTypeComputer;
 import edu.uci.ics.asterix.om.typecomputer.impl.OptionalACircleTypeComputer;
 import edu.uci.ics.asterix.om.typecomputer.impl.OptionalADateTimeTypeComputer;
 import edu.uci.ics.asterix.om.typecomputer.impl.OptionalADateTypeComputer;
@@ -49,6 +54,7 @@
 import edu.uci.ics.asterix.om.typecomputer.impl.OptionalAInt32TypeComputer;
 import edu.uci.ics.asterix.om.typecomputer.impl.OptionalAInt64TypeComputer;
 import edu.uci.ics.asterix.om.typecomputer.impl.OptionalAInt8TypeComputer;
+import edu.uci.ics.asterix.om.typecomputer.impl.OptionalAIntervalTypeComputer;
 import edu.uci.ics.asterix.om.typecomputer.impl.OptionalALineTypeComputer;
 import edu.uci.ics.asterix.om.typecomputer.impl.OptionalAPoint3DTypeComputer;
 import edu.uci.ics.asterix.om.typecomputer.impl.OptionalAPointTypeComputer;
@@ -235,11 +241,14 @@
     public final static FunctionIdentifier AVG = new FunctionIdentifier(FunctionConstants.ASTERIX_NS, "agg-avg", 1);
     public final static FunctionIdentifier COUNT = new FunctionIdentifier(FunctionConstants.ASTERIX_NS, "agg-count", 1);
     public final static FunctionIdentifier SUM = new FunctionIdentifier(FunctionConstants.ASTERIX_NS, "agg-sum", 1);
-    public final static FunctionIdentifier LOCAL_SUM = new FunctionIdentifier(FunctionConstants.ASTERIX_NS, "agg-local-sum", 1);
+    public final static FunctionIdentifier LOCAL_SUM = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "agg-local-sum", 1);
     public final static FunctionIdentifier MAX = new FunctionIdentifier(FunctionConstants.ASTERIX_NS, "agg-max", 1);
-    public final static FunctionIdentifier LOCAL_MAX = new FunctionIdentifier(FunctionConstants.ASTERIX_NS, "agg-local-max", 1);
+    public final static FunctionIdentifier LOCAL_MAX = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "agg-local-max", 1);
     public final static FunctionIdentifier MIN = new FunctionIdentifier(FunctionConstants.ASTERIX_NS, "agg-min", 1);
-    public final static FunctionIdentifier LOCAL_MIN = new FunctionIdentifier(FunctionConstants.ASTERIX_NS, "agg-local-min", 1);
+    public final static FunctionIdentifier LOCAL_MIN = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "agg-local-min", 1);
     public final static FunctionIdentifier GLOBAL_AVG = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
             "agg-global-avg", 1);
     public final static FunctionIdentifier LOCAL_AVG = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
@@ -270,8 +279,6 @@
     public final static FunctionIdentifier SERIAL_LOCAL_AVG = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
             "local-avg-serial", 1);
 
-    public final static FunctionIdentifier YEAR = new FunctionIdentifier(FunctionConstants.ASTERIX_NS, "year", 1);
-
     public final static FunctionIdentifier SCAN_COLLECTION = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
             "scan-collection", 1);
     public final static FunctionIdentifier SUBSET_COLLECTION = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
@@ -363,6 +370,49 @@
             "datetime", 1);
     public final static FunctionIdentifier DURATION_CONSTRUCTOR = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
             "duration", 1);
+    public final static FunctionIdentifier INTERVAL_CONSTRUCTOR_DATE = new FunctionIdentifier(
+            FunctionConstants.ASTERIX_NS, "interval-from-date", 2);
+    public final static FunctionIdentifier INTERVAL_CONSTRUCTOR_TIME = new FunctionIdentifier(
+            FunctionConstants.ASTERIX_NS, "interval-from-time", 2);
+    public final static FunctionIdentifier INTERVAL_CONSTRUCTOR_DATETIME = new FunctionIdentifier(
+            FunctionConstants.ASTERIX_NS, "interval-from-datetime", 2);
+    public final static FunctionIdentifier INTERVAL_CONSTRUCTOR_START_FROM_DATE = new FunctionIdentifier(
+            FunctionConstants.ASTERIX_NS, "interval-start-from-date", 2);
+    public final static FunctionIdentifier INTERVAL_CONSTRUCTOR_START_FROM_TIME = new FunctionIdentifier(
+            FunctionConstants.ASTERIX_NS, "interval-start-from-time", 2);
+    public final static FunctionIdentifier INTERVAL_CONSTRUCTOR_START_FROM_DATETIME = new FunctionIdentifier(
+            FunctionConstants.ASTERIX_NS, "interval-start-from-datetime", 2);
+    public final static FunctionIdentifier INTERVAL_BEFORE = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "interval-before", 2);
+    public final static FunctionIdentifier INTERVAL_AFTER = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "interval-after", 2);
+    public final static FunctionIdentifier INTERVAL_MEETS = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "interval-meets", 2);
+    public final static FunctionIdentifier INTERVAL_MET_BY = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "interval-met-by", 2);
+    public final static FunctionIdentifier INTERVAL_OVERLAPS = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "interval-overlaps", 2);
+    public final static FunctionIdentifier INTERVAL_OVERLAPPED_BY = new FunctionIdentifier(
+            FunctionConstants.ASTERIX_NS, "interval-overlapped-by", 2);
+    public final static FunctionIdentifier OVERLAP = new FunctionIdentifier(FunctionConstants.ASTERIX_NS, "overlap", 2);
+    public final static FunctionIdentifier INTERVAL_STARTS = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "interval-starts", 2);
+    public final static FunctionIdentifier INTERVAL_STARTED_BY = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "interval-started-by", 2);
+    public final static FunctionIdentifier INTERVAL_COVERS = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "interval-covers", 2);
+    public final static FunctionIdentifier INTERVAL_COVERED_BY = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "interval-covered-by", 2);
+    public final static FunctionIdentifier INTERVAL_ENDS = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "interval-ends", 2);
+    public final static FunctionIdentifier INTERVAL_ENDED_BY = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "interval-ended-by", 2);
+    public final static FunctionIdentifier CURRENT_TIME = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "current-time", 0);
+    public final static FunctionIdentifier CURRENT_DATE = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "current-date", 0);
+    public final static FunctionIdentifier CURRENT_DATETIME = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "current-datetime", 0);
 
     // spatial
     public final static FunctionIdentifier CREATE_POINT = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
@@ -394,6 +444,56 @@
     public final static FunctionIdentifier CAST_RECORD = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
             "cast-record", 1);
 
+    // Spatial and temporal type accessors
+    public static final FunctionIdentifier ACCESSOR_TEMPORAL_YEAR = new FunctionIdentifier(
+            FunctionConstants.ASTERIX_NS, "year", 1);
+    public static final FunctionIdentifier ACCESSOR_TEMPORAL_MONTH = new FunctionIdentifier(
+            FunctionConstants.ASTERIX_NS, "month", 2);
+    public static final FunctionIdentifier ACCESSOR_TEMPORAL_DAY = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "day", 1);
+    public static final FunctionIdentifier ACCESSOR_TEMPORAL_HOUR = new FunctionIdentifier(
+            FunctionConstants.ASTERIX_NS, "hour", 1);
+    public static final FunctionIdentifier ACCESSOR_TEMPORAL_MIN = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "minute", 1);
+    public static final FunctionIdentifier ACCESSOR_TEMPORAL_SEC = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "second", 1);
+    public static final FunctionIdentifier ACCESSOR_TEMPORAL_MILLISEC = new FunctionIdentifier(
+            FunctionConstants.ASTERIX_NS, "millisecond", 1);
+
+    // Temporal functions
+    public static final FunctionIdentifier DATE_FROM_UNIX_TIME_IN_DAYS = new FunctionIdentifier(
+            FunctionConstants.ASTERIX_NS, "date-from-unix-time-in-days", 1);
+    public static final FunctionIdentifier DATE_FROM_DATETIME = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "date-from-datetime", 1);
+    public final static FunctionIdentifier ADD_DATE_DURATION = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "add-date-duration", 2);
+    public final static FunctionIdentifier SUBTRACT_DATE = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "subtract-date", 2);
+    public final static FunctionIdentifier TIME_FROM_UNIX_TIME_IN_MS = new FunctionIdentifier(
+            FunctionConstants.ASTERIX_NS, "time-from-unix-time-in-ms", 1);
+    public final static FunctionIdentifier TIME_FROM_DATETIME = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "time-from-datetime", 1);
+    public final static FunctionIdentifier SUBTRACT_TIME = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "subtract-time", 2);
+    public final static FunctionIdentifier ADD_TIME_DURATION = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "add-time-duration", 2);
+    public final static FunctionIdentifier DATETIME_FROM_UNIX_TIME_IN_MS = new FunctionIdentifier(
+            FunctionConstants.ASTERIX_NS, "datetime-from-unix-time-in-ms", 1);
+    public final static FunctionIdentifier DATETIME_FROM_DATE_TIME = new FunctionIdentifier(
+            FunctionConstants.ASTERIX_NS, "datetime-from-date-time", 2);
+    public final static FunctionIdentifier SUBTRACT_DATETIME = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "subtract-datetime", 2);
+    public final static FunctionIdentifier ADD_DATETIME_DURATION = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "add-datetime-duration", 2);
+    public final static FunctionIdentifier CALENDAR_DURATION_FROM_DATETIME = new FunctionIdentifier(
+            FunctionConstants.ASTERIX_NS, "calendar-duration-from-datetime", 2);
+    public final static FunctionIdentifier CALENDAR_DURATION_FROM_DATE = new FunctionIdentifier(
+            FunctionConstants.ASTERIX_NS, "calendar-duration-from-date", 2);
+    public final static FunctionIdentifier ADJUST_TIME_FOR_TIMEZONE = new FunctionIdentifier(
+            FunctionConstants.ASTERIX_NS, "adjust-time-for-timezone", 2);
+    public final static FunctionIdentifier ADJUST_DATETIME_FOR_TIMEZONE = new FunctionIdentifier(
+            FunctionConstants.ASTERIX_NS, "adjust-datetime-for-timezone", 2);
+
     public final static FunctionIdentifier GET_POINT_X_COORDINATE_ACCESSOR = new FunctionIdentifier(FunctionConstants.ASTERIX_NS, "get-x", 1);
     public final static FunctionIdentifier GET_POINT_Y_COORDINATE_ACCESSOR = new FunctionIdentifier(FunctionConstants.ASTERIX_NS, "get-y", 1);
     public final static FunctionIdentifier GET_CIRCLE_RADIUS_ACCESSOR = new FunctionIdentifier(FunctionConstants.ASTERIX_NS, "get-radius", 1);
@@ -412,6 +512,9 @@
     public static final FunctionIdentifier NUMERIC_ADD = AlgebricksBuiltinFunctions.NUMERIC_ADD;
     public static final FunctionIdentifier IS_NULL = AlgebricksBuiltinFunctions.IS_NULL;
 
+    public static final FunctionIdentifier NOT_NULL = new FunctionIdentifier(FunctionConstants.ASTERIX_NS, "not-null",
+            1);
+
     public static IFunctionInfo getAsterixFunctionInfo(FunctionIdentifier fid) {
         IFunctionInfo finfo = finfoRepo.get(fid);;
         if (finfo == null) {
@@ -440,6 +543,7 @@
         add(NUMERIC_ADD, NonTaggedNumericAddSubMulDivTypeComputer.INSTANCE);
 
         // and then, Asterix builtin functions
+        add(NOT_NULL, NotNullTypeComputer.INSTANCE);
         add(ANY_COLLECTION_MEMBER, NonTaggedCollectionMemberResultType.INSTANCE);
         addPrivateFunction(AVG, OptionalADoubleTypeComputer.INSTANCE);
         add(BOOLEAN_CONSTRUCTOR, UnaryBooleanOrNullFunctionTypeComputer.INSTANCE);
@@ -648,7 +752,6 @@
         add(TIME_CONSTRUCTOR, OptionalATimeTypeComputer.INSTANCE);
         add(TYPE_OF, null); // TODO
         add(UNORDERED_LIST_CONSTRUCTOR, UnorderedListConstructorResultType.INSTANCE);
-        add(YEAR, OptionalAInt32TypeComputer.INSTANCE);
         add(WORD_TOKENS, new IResultTypeComputer() {
 
             @Override
@@ -658,12 +761,64 @@
             }
         });
 
+        // temporal type accessors
+        add(ACCESSOR_TEMPORAL_YEAR, OptionalAInt32TypeComputer.INSTANCE);
+        add(ACCESSOR_TEMPORAL_MONTH, OptionalAInt32TypeComputer.INSTANCE);
+        add(ACCESSOR_TEMPORAL_DAY, OptionalAInt32TypeComputer.INSTANCE);
+        add(ACCESSOR_TEMPORAL_HOUR, OptionalAInt32TypeComputer.INSTANCE);
+        add(ACCESSOR_TEMPORAL_MIN, OptionalAInt32TypeComputer.INSTANCE);
+        add(ACCESSOR_TEMPORAL_SEC, OptionalAInt32TypeComputer.INSTANCE);
+        add(ACCESSOR_TEMPORAL_MILLISEC, OptionalAInt32TypeComputer.INSTANCE);
+
+        // temporal functions
+        add(DATE_FROM_UNIX_TIME_IN_DAYS, OptionalADateTypeComputer.INSTANCE);
+        add(DATE_FROM_DATETIME, OptionalADateTypeComputer.INSTANCE);
+        add(ADD_DATE_DURATION, OptionalADateTypeComputer.INSTANCE);
+        add(SUBTRACT_DATE, OptionalADurationTypeComputer.INSTANCE);
+        add(TIME_FROM_UNIX_TIME_IN_MS, OptionalATimeTypeComputer.INSTANCE);
+        add(TIME_FROM_DATETIME, OptionalATimeTypeComputer.INSTANCE);
+        add(SUBTRACT_TIME, OptionalADurationTypeComputer.INSTANCE);
+        add(ADD_TIME_DURATION, OptionalATimeTypeComputer.INSTANCE);
+        add(DATETIME_FROM_DATE_TIME, OptionalADateTimeTypeComputer.INSTANCE);
+        add(DATETIME_FROM_UNIX_TIME_IN_MS, OptionalADateTimeTypeComputer.INSTANCE);
+        add(SUBTRACT_DATETIME, OptionalADurationTypeComputer.INSTANCE);
+        add(ADD_DATETIME_DURATION, OptionalADateTimeTypeComputer.INSTANCE);
+        add(CALENDAR_DURATION_FROM_DATETIME, OptionalADurationTypeComputer.INSTANCE);
+        add(CALENDAR_DURATION_FROM_DATE, OptionalADurationTypeComputer.INSTANCE);
+        add(ADJUST_DATETIME_FOR_TIMEZONE, OptionalAStringTypeComputer.INSTANCE);
+        add(ADJUST_TIME_FOR_TIMEZONE, OptionalAStringTypeComputer.INSTANCE);
+        add(INTERVAL_BEFORE, OptionalABooleanTypeComputer.INSTANCE);
+        add(INTERVAL_AFTER, OptionalABooleanTypeComputer.INSTANCE);
+        add(INTERVAL_MEETS, OptionalABooleanTypeComputer.INSTANCE);
+        add(INTERVAL_MET_BY, OptionalABooleanTypeComputer.INSTANCE);
+        add(INTERVAL_OVERLAPS, OptionalABooleanTypeComputer.INSTANCE);
+        add(INTERVAL_OVERLAPPED_BY, OptionalABooleanTypeComputer.INSTANCE);
+        add(OVERLAP, OptionalABooleanTypeComputer.INSTANCE);
+        add(INTERVAL_STARTS, OptionalABooleanTypeComputer.INSTANCE);
+        add(INTERVAL_STARTED_BY, OptionalABooleanTypeComputer.INSTANCE);
+        add(INTERVAL_COVERS, OptionalABooleanTypeComputer.INSTANCE);
+        add(INTERVAL_COVERED_BY, OptionalABooleanTypeComputer.INSTANCE);
+        add(INTERVAL_ENDS, OptionalABooleanTypeComputer.INSTANCE);
+        add(INTERVAL_ENDED_BY, OptionalABooleanTypeComputer.INSTANCE);
+        add(CURRENT_DATE, ADateTypeComputer.INSTANCE);
+        add(CURRENT_TIME, ATimeTypeComputer.INSTANCE);
+        add(CURRENT_DATETIME, ADateTimeTypeComputer.INSTANCE);
+
+        // interval constructors
+        add(INTERVAL_CONSTRUCTOR_DATE, OptionalAIntervalTypeComputer.INSTANCE);
+        add(INTERVAL_CONSTRUCTOR_TIME, OptionalAIntervalTypeComputer.INSTANCE);
+        add(INTERVAL_CONSTRUCTOR_DATETIME, OptionalAIntervalTypeComputer.INSTANCE);
+        add(INTERVAL_CONSTRUCTOR_START_FROM_DATE, OptionalAIntervalTypeComputer.INSTANCE);
+        add(INTERVAL_CONSTRUCTOR_START_FROM_DATETIME, OptionalAIntervalTypeComputer.INSTANCE);
+        add(INTERVAL_CONSTRUCTOR_START_FROM_TIME, OptionalAIntervalTypeComputer.INSTANCE);
+
         String metadataFunctionLoaderClassName = "edu.uci.ics.asterix.metadata.functions.MetadataBuiltinFunctions";
         try {
             Class.forName(metadataFunctionLoaderClassName);
         } catch (ClassNotFoundException e) {
             throw new RuntimeException(e);
         }
+
     }
 
     static {
@@ -840,7 +995,7 @@
         funTypeComputer.put(functionInfo, typeComputer);
         finfoRepo.put(fi);
     }
-
+    
     private static IFunctionInfo addPrivateFunction(FunctionIdentifier fi, IResultTypeComputer typeComputer) {
         IFunctionInfo functionInfo = getAsterixFunctionInfo(fi);
         builtinFunctionsSet.put(functionInfo, functionInfo);
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/om/pointables/cast/ARecordCaster.java b/asterix-om/src/main/java/edu/uci/ics/asterix/om/pointables/cast/ARecordCaster.java
index fbad7a7..494ea6f 100644
--- a/asterix-om/src/main/java/edu/uci/ics/asterix/om/pointables/cast/ARecordCaster.java
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/om/pointables/cast/ARecordCaster.java
@@ -15,9 +15,11 @@
 
 package edu.uci.ics.asterix.om.pointables.cast;
 
+import java.io.ByteArrayOutputStream;
 import java.io.DataOutput;
 import java.io.DataOutputStream;
 import java.io.IOException;
+import java.io.PrintStream;
 import java.util.ArrayList;
 import java.util.List;
 
@@ -28,6 +30,7 @@
 import edu.uci.ics.asterix.om.pointables.PointableAllocator;
 import edu.uci.ics.asterix.om.pointables.base.DefaultOpenFieldType;
 import edu.uci.ics.asterix.om.pointables.base.IVisitablePointable;
+import edu.uci.ics.asterix.om.pointables.printer.APrintVisitor;
 import edu.uci.ics.asterix.om.types.ARecordType;
 import edu.uci.ics.asterix.om.types.ATypeTag;
 import edu.uci.ics.asterix.om.types.AUnionType;
@@ -35,6 +38,7 @@
 import edu.uci.ics.asterix.om.types.IAType;
 import edu.uci.ics.asterix.om.util.NonTaggedFormatUtil;
 import edu.uci.ics.asterix.om.util.ResettableByteArrayOutputStream;
+import edu.uci.ics.hyracks.algebricks.common.utils.Pair;
 import edu.uci.ics.hyracks.algebricks.common.utils.Triple;
 import edu.uci.ics.hyracks.api.dataflow.value.IBinaryComparator;
 import edu.uci.ics.hyracks.api.dataflow.value.INullWriter;
@@ -184,7 +188,7 @@
     }
 
     private void matchClosedPart(List<IVisitablePointable> fieldNames, List<IVisitablePointable> fieldTypeTags,
-            List<IVisitablePointable> fieldValues) {
+            List<IVisitablePointable> fieldValues) throws AsterixException {
         // sort-merge based match
         quickSort(fieldNamesSortedIndex, fieldNames, 0, numInputFields - 1);
         int fnStart = 0;
@@ -213,8 +217,30 @@
 
         // check unmatched fields in the input type
         for (int i = 0; i < openFields.length; i++) {
-            if (openFields[i] == true && !cachedReqType.isOpen())
-                throw new IllegalStateException("type mismatch: including extra closed fields");
+            if (openFields[i] == true && !cachedReqType.isOpen()) {
+                //print the field name
+                IVisitablePointable fieldName = fieldNames.get(i);
+                ByteArrayOutputStream bos = new ByteArrayOutputStream();
+                PrintStream ps = new PrintStream(bos);
+                APrintVisitor printVisitor = new APrintVisitor();
+                Pair<PrintStream, ATypeTag> visitorArg = new Pair<PrintStream, ATypeTag>(ps, ATypeTag.STRING);
+                fieldName.accept(printVisitor, visitorArg);
+
+                //print the colon
+                ps.print(":");
+
+                //print the field type
+                IVisitablePointable fieldType = fieldTypeTags.get(i);
+                ATypeTag typeTag = EnumDeserializer.ATYPETAGDESERIALIZER.deserialize(fieldType.getByteArray()[fieldType
+                        .getStartOffset()]);
+                ps.print(typeTag);
+
+                //collect the output message
+                byte[] output = bos.toByteArray();
+
+                //throw the exception
+                throw new IllegalStateException("type mismatch: including an extra field " + new String(output));
+            }
         }
 
         // check unmatched fields in the required type
@@ -223,7 +249,8 @@
                 IAType t = cachedReqType.getFieldTypes()[i];
                 if (!(t.getTypeTag() == ATypeTag.UNION && NonTaggedFormatUtil.isOptionalField((AUnionType) t))) {
                     // no matched field in the input for a required closed field
-                    throw new IllegalStateException("type mismatch: miss a required closed field");
+                    throw new IllegalStateException("type mismatch: miss a required closed field "
+                            + cachedReqType.getFieldNames()[i] + ":" + t.getTypeName());
                 }
             }
         }
@@ -288,8 +315,7 @@
         int j = right;
         while (true) {
             // grow from the left
-            while (compare(names.get(index[++i]), names.get(index[right])) < 0)
-                ;
+            while (compare(names.get(index[++i]), names.get(index[right])) < 0);
             // lower from the right
             while (compare(names.get(index[right]), names.get(index[--j])) < 0)
                 if (j == left)
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/om/typecomputer/impl/ADateTimeTypeComputer.java b/asterix-om/src/main/java/edu/uci/ics/asterix/om/typecomputer/impl/ADateTimeTypeComputer.java
new file mode 100644
index 0000000..c7a51da
--- /dev/null
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/om/typecomputer/impl/ADateTimeTypeComputer.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.om.typecomputer.impl;
+
+import edu.uci.ics.asterix.om.typecomputer.base.IResultTypeComputer;
+import edu.uci.ics.asterix.om.types.BuiltinType;
+import edu.uci.ics.asterix.om.types.IAType;
+import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
+import edu.uci.ics.hyracks.algebricks.core.algebra.base.ILogicalExpression;
+import edu.uci.ics.hyracks.algebricks.core.algebra.expressions.IVariableTypeEnvironment;
+import edu.uci.ics.hyracks.algebricks.core.algebra.metadata.IMetadataProvider;
+
+public class ADateTimeTypeComputer implements IResultTypeComputer {
+
+    public static final ADateTimeTypeComputer INSTANCE = new ADateTimeTypeComputer();
+
+    private ADateTimeTypeComputer() {
+    }
+
+    @Override
+    public IAType computeType(ILogicalExpression expression, IVariableTypeEnvironment env,
+            IMetadataProvider<?, ?> metadataProvider) throws AlgebricksException {
+        return BuiltinType.ADATETIME;
+    }
+
+}
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/om/typecomputer/impl/ATimeTypeComputer.java b/asterix-om/src/main/java/edu/uci/ics/asterix/om/typecomputer/impl/ATimeTypeComputer.java
new file mode 100644
index 0000000..55e1bc4
--- /dev/null
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/om/typecomputer/impl/ATimeTypeComputer.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.om.typecomputer.impl;
+
+import edu.uci.ics.asterix.om.typecomputer.base.IResultTypeComputer;
+import edu.uci.ics.asterix.om.types.BuiltinType;
+import edu.uci.ics.asterix.om.types.IAType;
+import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
+import edu.uci.ics.hyracks.algebricks.core.algebra.base.ILogicalExpression;
+import edu.uci.ics.hyracks.algebricks.core.algebra.expressions.IVariableTypeEnvironment;
+import edu.uci.ics.hyracks.algebricks.core.algebra.metadata.IMetadataProvider;
+
+public class ATimeTypeComputer implements IResultTypeComputer {
+
+    public static final ATimeTypeComputer INSTANCE = new ATimeTypeComputer();
+
+    private ATimeTypeComputer() {
+    }
+
+    @Override
+    public IAType computeType(ILogicalExpression expression, IVariableTypeEnvironment env,
+            IMetadataProvider<?, ?> metadataProvider) throws AlgebricksException {
+        return BuiltinType.ATIME;
+    }
+
+}
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/om/typecomputer/impl/NotNullTypeComputer.java b/asterix-om/src/main/java/edu/uci/ics/asterix/om/typecomputer/impl/NotNullTypeComputer.java
new file mode 100644
index 0000000..a9881c2
--- /dev/null
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/om/typecomputer/impl/NotNullTypeComputer.java
@@ -0,0 +1,72 @@
+/*
+ * Copyright 2009-2010 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package edu.uci.ics.asterix.om.typecomputer.impl;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import edu.uci.ics.asterix.om.typecomputer.base.IResultTypeComputer;
+import edu.uci.ics.asterix.om.types.ATypeTag;
+import edu.uci.ics.asterix.om.types.AUnionType;
+import edu.uci.ics.asterix.om.types.IAType;
+import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
+import edu.uci.ics.hyracks.algebricks.core.algebra.base.ILogicalExpression;
+import edu.uci.ics.hyracks.algebricks.core.algebra.expressions.AbstractFunctionCallExpression;
+import edu.uci.ics.hyracks.algebricks.core.algebra.expressions.IVariableTypeEnvironment;
+import edu.uci.ics.hyracks.algebricks.core.algebra.metadata.IMetadataProvider;
+
+/**
+ * This class is the type computer for not-null function.
+ * If the input type is not a union, we just return it.
+ * If the input type is a union,
+ * case 1: we return a new union without null if the new union still has more than one types;
+ * case 2: we return the non-null item type in the original union if there are only null and it in the original union.
+ */
+public class NotNullTypeComputer implements IResultTypeComputer {
+
+    public static final NotNullTypeComputer INSTANCE = new NotNullTypeComputer();
+
+    @Override
+    public IAType computeType(ILogicalExpression expression, IVariableTypeEnvironment env,
+            IMetadataProvider<?, ?> metadataProvider) throws AlgebricksException {
+        AbstractFunctionCallExpression f = (AbstractFunctionCallExpression) expression;
+        IAType type = (IAType) env.getType(f.getArguments().get(0).getValue());
+        if (type.getTypeTag() != ATypeTag.UNION) {
+            // directly return the input type if it is not a union
+            return type;
+        }
+
+        AUnionType unionType = (AUnionType) type;
+        List<IAType> items = new ArrayList<IAType>();
+        // copy the item types
+        items.addAll(unionType.getUnionList());
+
+        // remove null
+        for (int i = items.size() - 1; i >= 0; i--) {
+            IAType itemType = items.get(i);
+            if (itemType.getTypeTag() == ATypeTag.NULL) {
+                items.remove(i);
+            }
+        }
+        if (items.size() == 1) {
+            //only one type is left
+            return items.get(0);
+        } else {
+            //more than two types are left
+            return new AUnionType(items, unionType.getTypeName());
+        }
+    }
+}
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/om/typecomputer/impl/OptionalABooleanTypeComputer.java b/asterix-om/src/main/java/edu/uci/ics/asterix/om/typecomputer/impl/OptionalABooleanTypeComputer.java
new file mode 100644
index 0000000..abeea2a
--- /dev/null
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/om/typecomputer/impl/OptionalABooleanTypeComputer.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.om.typecomputer.impl;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import edu.uci.ics.asterix.om.typecomputer.base.IResultTypeComputer;
+import edu.uci.ics.asterix.om.types.AUnionType;
+import edu.uci.ics.asterix.om.types.BuiltinType;
+import edu.uci.ics.asterix.om.types.IAType;
+import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
+import edu.uci.ics.hyracks.algebricks.core.algebra.base.ILogicalExpression;
+import edu.uci.ics.hyracks.algebricks.core.algebra.expressions.IVariableTypeEnvironment;
+import edu.uci.ics.hyracks.algebricks.core.algebra.metadata.IMetadataProvider;
+
+public class OptionalABooleanTypeComputer implements IResultTypeComputer {
+
+    public static final OptionalABooleanTypeComputer INSTANCE = new OptionalABooleanTypeComputer();
+
+    private OptionalABooleanTypeComputer() {
+    }
+
+    @Override
+    public IAType computeType(ILogicalExpression expression, IVariableTypeEnvironment env,
+            IMetadataProvider<?, ?> metadataProvider) throws AlgebricksException {
+        List<IAType> unionList = new ArrayList<IAType>();
+        unionList.add(BuiltinType.ANULL);
+        unionList.add(BuiltinType.ABOOLEAN);
+        return new AUnionType(unionList, "OptionalBoolean");
+    }
+
+}
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/om/typecomputer/impl/OptionalAIntervalTypeComputer.java b/asterix-om/src/main/java/edu/uci/ics/asterix/om/typecomputer/impl/OptionalAIntervalTypeComputer.java
new file mode 100644
index 0000000..bb9f993
--- /dev/null
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/om/typecomputer/impl/OptionalAIntervalTypeComputer.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.om.typecomputer.impl;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import edu.uci.ics.asterix.om.typecomputer.base.IResultTypeComputer;
+import edu.uci.ics.asterix.om.types.AUnionType;
+import edu.uci.ics.asterix.om.types.BuiltinType;
+import edu.uci.ics.asterix.om.types.IAType;
+import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
+import edu.uci.ics.hyracks.algebricks.core.algebra.base.ILogicalExpression;
+import edu.uci.ics.hyracks.algebricks.core.algebra.expressions.IVariableTypeEnvironment;
+import edu.uci.ics.hyracks.algebricks.core.algebra.metadata.IMetadataProvider;
+
+public class OptionalAIntervalTypeComputer implements IResultTypeComputer {
+
+    public static final OptionalAIntervalTypeComputer INSTANCE = new OptionalAIntervalTypeComputer();
+
+    private OptionalAIntervalTypeComputer() {
+
+    }
+
+    public IAType computeType(ILogicalExpression expression, IVariableTypeEnvironment env,
+            IMetadataProvider<?, ?> metadataProvider) throws AlgebricksException {
+        List<IAType> unionList = new ArrayList<IAType>();
+        unionList.add(BuiltinType.ANULL);
+        unionList.add(BuiltinType.AINTERVAL);
+        return new AUnionType(unionList, "OptionalInterval");
+    }
+
+}
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/om/types/ATypeTag.java b/asterix-om/src/main/java/edu/uci/ics/asterix/om/types/ATypeTag.java
index b75c074..e69fbcd 100644
--- a/asterix-om/src/main/java/edu/uci/ics/asterix/om/types/ATypeTag.java
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/om/types/ATypeTag.java
@@ -42,6 +42,7 @@
     LINE(30),
     POLYGON(31),
     CIRCLE(32),
+    INTERVAL(34),
     RECTANGLE(33),
     SYSTEM_NULL(34);
 
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/om/types/BuiltinType.java b/asterix-om/src/main/java/edu/uci/ics/asterix/om/types/BuiltinType.java
index 0ec3b21..4d9cd7f 100644
--- a/asterix-om/src/main/java/edu/uci/ics/asterix/om/types/BuiltinType.java
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/om/types/BuiltinType.java
@@ -329,6 +329,27 @@
 
     };
 
+    public final static BuiltinType AINTERVAL = new LowerCaseConstructorType() {
+
+        private static final long serialVersionUID = 1L;
+
+        @Override
+        public String getDisplayName() {
+            return "AInterval";
+        }
+
+        @Override
+        public ATypeTag getTypeTag() {
+            return ATypeTag.INTERVAL;
+        }
+
+        @Override
+        public String getTypeName() {
+            return "interval";
+        }
+
+    };
+
     public final static BuiltinType APOINT = new LowerCaseConstructorType() {
 
         private static final long serialVersionUID = 1L;
@@ -515,25 +536,25 @@
         return getTypeTag().toString();
     }
 
-	@Override
-	public boolean deepEqual(IAObject obj) {
-		if (obj == this) {
-			return true;
-		}
-		if (!(obj instanceof BuiltinType)) {
-			return false;
-		}
-		return ((BuiltinType) obj).getTypeTag().equals(getTypeTag());
-	}
+    @Override
+    public boolean deepEqual(IAObject obj) {
+        if (obj == this) {
+            return true;
+        }
+        if (!(obj instanceof BuiltinType)) {
+            return false;
+        }
+        return ((BuiltinType) obj).getTypeTag().equals(getTypeTag());
+    }
 
     @Override
     public boolean equals(Object object) {
         return this.deepEqual((IAObject) object);
     }
-    
+
     @Override
     public int hashCode() {
-    	return getTypeTag().hashCode();
+        return getTypeTag().hashCode();
     }
 
     @Override
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/om/util/NonTaggedFormatUtil.java b/asterix-om/src/main/java/edu/uci/ics/asterix/om/util/NonTaggedFormatUtil.java
index 8832164..a8c0485 100644
--- a/asterix-om/src/main/java/edu/uci/ics/asterix/om/util/NonTaggedFormatUtil.java
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/om/util/NonTaggedFormatUtil.java
@@ -95,6 +95,8 @@
                 return 12;
             case POINT:
                 return 16;
+            case INTERVAL:
+                return 17;
             case POINT3D:
             case CIRCLE:
                 return 24;
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/om/visitors/IOMVisitor.java b/asterix-om/src/main/java/edu/uci/ics/asterix/om/visitors/IOMVisitor.java
index 2c82174..703b792 100644
--- a/asterix-om/src/main/java/edu/uci/ics/asterix/om/visitors/IOMVisitor.java
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/om/visitors/IOMVisitor.java
@@ -14,6 +14,7 @@
 import edu.uci.ics.asterix.om.base.AInt32;
 import edu.uci.ics.asterix.om.base.AInt64;
 import edu.uci.ics.asterix.om.base.AInt8;
+import edu.uci.ics.asterix.om.base.AInterval;
 import edu.uci.ics.asterix.om.base.ALine;
 import edu.uci.ics.asterix.om.base.ANull;
 import edu.uci.ics.asterix.om.base.AOrderedList;
@@ -46,6 +47,8 @@
 
     public void visitADuration(ADuration obj) throws AsterixException;
 
+    public void visitAInterval(AInterval obj) throws AsterixException;
+
     public void visitADate(ADate obj) throws AsterixException;
 
     public void visitATime(ATime obj) throws AsterixException;
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/om/visitors/OMPrintToStringVisitor.java b/asterix-om/src/main/java/edu/uci/ics/asterix/om/visitors/OMPrintToStringVisitor.java
index 1697c5c..e7856f0 100644
--- a/asterix-om/src/main/java/edu/uci/ics/asterix/om/visitors/OMPrintToStringVisitor.java
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/om/visitors/OMPrintToStringVisitor.java
@@ -15,6 +15,7 @@
 import edu.uci.ics.asterix.om.base.AInt32;
 import edu.uci.ics.asterix.om.base.AInt64;
 import edu.uci.ics.asterix.om.base.AInt8;
+import edu.uci.ics.asterix.om.base.AInterval;
 import edu.uci.ics.asterix.om.base.ALine;
 import edu.uci.ics.asterix.om.base.ANull;
 import edu.uci.ics.asterix.om.base.AOrderedList;
@@ -90,6 +91,12 @@
     }
 
     @Override
+    public void visitAInterval(AInterval obj) throws AsterixException {
+        // TODO Auto-generated method stub
+        throw new NotImplementedException();
+    }
+
+    @Override
     public void visitAFloat(AFloat obj) throws AsterixException {
         buffer.append(obj.getFloatValue() + "f");
     }
diff --git a/asterix-runtime/pom.xml b/asterix-runtime/pom.xml
index 77952a6..93b38df 100644
--- a/asterix-runtime/pom.xml
+++ b/asterix-runtime/pom.xml
@@ -1,13 +1,12 @@
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 	<modelVersion>4.0.0</modelVersion>
 	<parent>
 		<artifactId>asterix</artifactId>
 		<groupId>edu.uci.ics.asterix</groupId>
 		<version>0.0.4-SNAPSHOT</version>
 	</parent>
-	<groupId>edu.uci.ics.asterix</groupId>
 	<artifactId>asterix-runtime</artifactId>
-	<version>0.0.4-SNAPSHOT</version>
 
 
 	<build>
@@ -55,26 +54,25 @@
 		</dependency>
 		<dependency>
 			<groupId>edu.uci.ics.hyracks</groupId>
-		        <artifactId>hyracks-storage-am-btree</artifactId>
-			<version>0.2.2-SNAPSHOT</version>
+			<artifactId>hyracks-storage-am-btree</artifactId>
 		</dependency>
 		<dependency>
-		        <groupId>edu.uci.ics.asterix</groupId>
-		        <artifactId>asterix-transactions</artifactId>
+			<groupId>edu.uci.ics.asterix</groupId>
+			<artifactId>asterix-transactions</artifactId>
 			<version>0.0.4-SNAPSHOT</version>
 			<scope>compile</scope>
 		</dependency>
 		<dependency>
-		        <groupId>org.twitter4j</groupId>
-		        <artifactId>twitter4j-core</artifactId>
-		        <version>2.2.3</version>
+			<groupId>org.twitter4j</groupId>
+			<artifactId>twitter4j-core</artifactId>
+			<version>2.2.3</version>
 		</dependency>
 		<dependency>
-		        <groupId>org.apache.hadoop</groupId>
-		        <artifactId>hadoop-core</artifactId>
-		        <version>0.20.2</version>
-		        <type>jar</type>
-		        <scope>compile</scope>
+			<groupId>org.apache.hadoop</groupId>
+			<artifactId>hadoop-core</artifactId>
+			<version>0.20.2</version>
+			<type>jar</type>
+			<scope>compile</scope>
 		</dependency>
 	</dependencies>
 
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/comparisons/AbstractComparisonEvaluator.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/comparisons/AbstractComparisonEvaluator.java
index 18fc2d7..2b4ea3a 100644
--- a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/comparisons/AbstractComparisonEvaluator.java
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/comparisons/AbstractComparisonEvaluator.java
@@ -2,6 +2,7 @@
 
 import java.io.DataOutput;
 
+import edu.uci.ics.asterix.dataflow.data.nontagged.comparators.ADateOrTimeAscBinaryComparatorFactory;
 import edu.uci.ics.asterix.dataflow.data.nontagged.comparators.ADateTimeAscBinaryComparatorFactory;
 import edu.uci.ics.asterix.dataflow.data.nontagged.serde.ADoubleSerializerDeserializer;
 import edu.uci.ics.asterix.dataflow.data.nontagged.serde.AFloatSerializerDeserializer;
@@ -50,6 +51,8 @@
             .createBinaryComparator();
     protected IBinaryComparator dateTimeBinaryComp = ADateTimeAscBinaryComparatorFactory.INSTANCE
             .createBinaryComparator();
+    protected IBinaryComparator dateOrTimeBinaryComp = ADateOrTimeAscBinaryComparatorFactory.INSTANCE
+            .createBinaryComparator();
 
     public AbstractComparisonEvaluator(DataOutput out, ICopyEvaluatorFactory evalLeftFactory,
             ICopyEvaluatorFactory evalRightFactory) throws AlgebricksException {
@@ -119,6 +122,10 @@
             case DATETIME: {
                 return compareDateTimeWithArg(typeTag2);
             }
+            case DATE:
+            case TIME: {
+                return compareDateOrTimeWithArg(typeTag2);
+            }
             default: {
                 throw new AlgebricksException("Comparison is undefined between types " + typeTag1 + " and " + typeTag2
                         + " .");
@@ -126,6 +133,22 @@
         }
     }
 
+    private ComparisonResult compareDateOrTimeWithArg(ATypeTag typeTag2) throws AlgebricksException {
+        if (typeTag2 == ATypeTag.NULL) {
+            return ComparisonResult.GREATER_THAN;
+        } else if (typeTag2 == ATypeTag.DATETIME) {
+            int result = dateOrTimeBinaryComp.compare(outLeft.getByteArray(), 1, outLeft.getLength() - 1,
+                    outRight.getByteArray(), 1, outRight.getLength() - 1);
+            if (result == 0)
+                return ComparisonResult.EQUAL;
+            else if (result < 0)
+                return ComparisonResult.LESS_THAN;
+            else
+                return ComparisonResult.GREATER_THAN;
+        }
+        throw new AlgebricksException("Comparison is undefined between types ADateTime and " + typeTag2 + " .");
+    }
+
     private ComparisonResult compareDateTimeWithArg(ATypeTag typeTag2) throws AlgebricksException {
         if (typeTag2 == ATypeTag.NULL) {
             return ComparisonResult.GREATER_THAN;
@@ -153,8 +176,8 @@
 
     private ComparisonResult compareStringWithArg(ATypeTag typeTag2) throws AlgebricksException {
         if (typeTag2 == ATypeTag.STRING) {
-            int result = strBinaryComp.compare(outLeft.getByteArray(), 1, outLeft.getLength() - 1, outRight.getByteArray(), 1,
-                    outRight.getLength() - 1);
+            int result = strBinaryComp.compare(outLeft.getByteArray(), 1, outLeft.getLength() - 1,
+                    outRight.getByteArray(), 1, outRight.getLength() - 1);
             if (result == 0)
                 return ComparisonResult.EQUAL;
             else if (result < 0)
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/constructors/ADateConstructorDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/constructors/ADateConstructorDescriptor.java
index cfebf48..44fcf7c 100644
--- a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/constructors/ADateConstructorDescriptor.java
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/constructors/ADateConstructorDescriptor.java
@@ -21,7 +21,7 @@
 import edu.uci.ics.asterix.om.base.ADate;
 import edu.uci.ics.asterix.om.base.AMutableDate;
 import edu.uci.ics.asterix.om.base.ANull;
-import edu.uci.ics.asterix.om.base.temporal.ADateAndTimeParser;
+import edu.uci.ics.asterix.om.base.temporal.ADateParserFactory;
 import edu.uci.ics.asterix.om.base.temporal.ByteArrayCharSequenceAccessor;
 import edu.uci.ics.asterix.om.base.temporal.GregorianCalendarSystem;
 import edu.uci.ics.asterix.om.functions.AsterixBuiltinFunctions;
@@ -84,8 +84,10 @@
                             byte[] serString = outInput.getByteArray();
                             if (serString[0] == SER_STRING_TYPE_TAG) {
 
-                                charAccessor.reset(serString, 3, 0);
-                                long chrononTimeInMs = ADateAndTimeParser.parseDatePart(charAccessor, true);
+                                int stringLength = (serString[1] & 0xff << 8) + (serString[2] & 0xff << 0);
+
+                                charAccessor.reset(serString, 3, stringLength);
+                                long chrononTimeInMs = ADateParserFactory.parseDatePart(charAccessor, true);
 
                                 short temp = 0;
                                 if (chrononTimeInMs < 0
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/constructors/ADateTimeConstructorDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/constructors/ADateTimeConstructorDescriptor.java
index 19849aa..6a5783b 100644
--- a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/constructors/ADateTimeConstructorDescriptor.java
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/constructors/ADateTimeConstructorDescriptor.java
@@ -21,7 +21,8 @@
 import edu.uci.ics.asterix.om.base.ADateTime;
 import edu.uci.ics.asterix.om.base.AMutableDateTime;
 import edu.uci.ics.asterix.om.base.ANull;
-import edu.uci.ics.asterix.om.base.temporal.ADateAndTimeParser;
+import edu.uci.ics.asterix.om.base.temporal.ADateParserFactory;
+import edu.uci.ics.asterix.om.base.temporal.ATimeParserFactory;
 import edu.uci.ics.asterix.om.base.temporal.ByteArrayCharSequenceAccessor;
 import edu.uci.ics.asterix.om.functions.AsterixBuiltinFunctions;
 import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
@@ -71,7 +72,6 @@
                     @SuppressWarnings("unchecked")
                     private ISerializerDeserializer<ANull> nullSerde = AqlSerializerDeserializerProvider.INSTANCE
                             .getSerializerDeserializer(BuiltinType.ANULL);
-
                     private ByteArrayCharSequenceAccessor charAccessor = new ByteArrayCharSequenceAccessor();
 
                     @Override
@@ -82,7 +82,10 @@
                             eval.evaluate(tuple);
                             byte[] serString = outInput.getByteArray();
                             if (serString[0] == SER_STRING_TYPE_TAG) {
-                                charAccessor.reset(serString, 3, 0);
+
+                                int stringLength = (serString[1] & 0xff << 8) + (serString[2] & 0xff << 0);
+
+                                charAccessor.reset(serString, 3, stringLength);
 
                                 // +1 if it is negative (-)
                                 short timeOffset = (short) ((charAccessor.getCharAt(0) == '-') ? 1 : 0);
@@ -96,11 +99,11 @@
                                 timeOffset += (charAccessor.getCharAt(timeOffset + 13) == ':') ? (short) (11)
                                         : (short) (9);
 
-                                long chrononTimeInMs = ADateAndTimeParser.parseDatePart(charAccessor, false);
+                                long chrononTimeInMs = ADateParserFactory.parseDatePart(charAccessor, false);
 
-                                charAccessor.reset(serString, 3, timeOffset);
+                                charAccessor.reset(serString, 3 + timeOffset, stringLength - timeOffset);
 
-                                chrononTimeInMs += ADateAndTimeParser.parseTimePart(charAccessor);
+                                chrononTimeInMs += ATimeParserFactory.parseTimePart(charAccessor);
 
                                 aDateTime.setValue(chrononTimeInMs);
                                 datetimeSerde.serialize(aDateTime, out);
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/constructors/ADurationConstructorDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/constructors/ADurationConstructorDescriptor.java
index f0660f5..b2b3f4e 100644
--- a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/constructors/ADurationConstructorDescriptor.java
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/constructors/ADurationConstructorDescriptor.java
@@ -20,7 +20,7 @@
 import edu.uci.ics.asterix.om.base.ADuration;
 import edu.uci.ics.asterix.om.base.AMutableDuration;
 import edu.uci.ics.asterix.om.base.ANull;
-import edu.uci.ics.asterix.om.base.temporal.ADurationParser;
+import edu.uci.ics.asterix.om.base.temporal.ADurationParserFactory;
 import edu.uci.ics.asterix.om.base.temporal.ByteArrayCharSequenceAccessor;
 import edu.uci.ics.asterix.om.functions.AsterixBuiltinFunctions;
 import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
@@ -83,9 +83,11 @@
 
                             if (serString[0] == SER_STRING_TYPE_TAG) {
 
-                                charAccessor.reset(serString, 3, 0);
+                                int stringLength = (serString[1] & 0xff << 8) + (serString[2] & 0xff << 0);
 
-                                ADurationParser.parse(charAccessor, aDuration);
+                                charAccessor.reset(serString, 3, stringLength);
+
+                                ADurationParserFactory.parseDuration(charAccessor, aDuration);
 
                                 durationSerde.serialize(aDuration, out);
                             } else if (serString[0] == SER_NULL_TYPE_TAG) {
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/constructors/AInt64ConstructorDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/constructors/AInt64ConstructorDescriptor.java
index 15e3e72..6fa4925 100644
--- a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/constructors/AInt64ConstructorDescriptor.java
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/constructors/AInt64ConstructorDescriptor.java
@@ -98,8 +98,9 @@
                                     else
                                         throw new AlgebricksException(errorMessage);
                                 }
-                                if (value < 0)
+                                if (value < 0 && value != -9223372036854775808L) {
                                     throw new AlgebricksException(errorMessage);
+                                }
                                 if (value > 0 && !positive)
                                     value *= -1;
 
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/constructors/AIntervalFromDateConstructorDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/constructors/AIntervalFromDateConstructorDescriptor.java
new file mode 100644
index 0000000..e1a12f8
--- /dev/null
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/constructors/AIntervalFromDateConstructorDescriptor.java
@@ -0,0 +1,142 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.runtime.evaluators.constructors;
+
+import java.io.DataOutput;
+import java.io.IOException;
+
+import edu.uci.ics.asterix.common.functions.FunctionConstants;
+import edu.uci.ics.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
+import edu.uci.ics.asterix.om.base.AInterval;
+import edu.uci.ics.asterix.om.base.AMutableInterval;
+import edu.uci.ics.asterix.om.base.ANull;
+import edu.uci.ics.asterix.om.base.temporal.ADateParserFactory;
+import edu.uci.ics.asterix.om.base.temporal.ByteArrayCharSequenceAccessor;
+import edu.uci.ics.asterix.om.base.temporal.GregorianCalendarSystem;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
+import edu.uci.ics.asterix.om.types.ATypeTag;
+import edu.uci.ics.asterix.om.types.BuiltinType;
+import edu.uci.ics.asterix.runtime.evaluators.base.AbstractScalarFunctionDynamicDescriptor;
+import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
+import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluator;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory;
+import edu.uci.ics.hyracks.api.dataflow.value.ISerializerDeserializer;
+import edu.uci.ics.hyracks.data.std.api.IDataOutputProvider;
+import edu.uci.ics.hyracks.data.std.util.ArrayBackedValueStorage;
+import edu.uci.ics.hyracks.dataflow.common.data.accessors.IFrameTupleReference;
+
+public class AIntervalFromDateConstructorDescriptor extends AbstractScalarFunctionDynamicDescriptor {
+
+    private static final long serialVersionUID = 1L;
+    public final static FunctionIdentifier FID = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "interval-from-date", 2);
+    private final static byte SER_STRING_TYPE_TAG = ATypeTag.STRING.serialize();
+    private final static byte SER_NULL_TYPE_TAG = ATypeTag.NULL.serialize();
+
+    public static final IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
+        public IFunctionDescriptor createFunctionDescriptor() {
+            return new AIntervalFromDateConstructorDescriptor();
+        }
+    };
+
+    @Override
+    public ICopyEvaluatorFactory createEvaluatorFactory(final ICopyEvaluatorFactory[] args) {
+        return new ICopyEvaluatorFactory() {
+            private static final long serialVersionUID = 1L;
+
+            @Override
+            public ICopyEvaluator createEvaluator(final IDataOutputProvider output) throws AlgebricksException {
+                return new ICopyEvaluator() {
+
+                    private DataOutput out = output.getDataOutput();
+
+                    private ArrayBackedValueStorage argOut0 = new ArrayBackedValueStorage();
+                    private ArrayBackedValueStorage argOut1 = new ArrayBackedValueStorage();
+                    private ICopyEvaluator eval0 = args[0].createEvaluator(argOut0);
+                    private ICopyEvaluator eval1 = args[1].createEvaluator(argOut1);
+                    private String errorMessage = "This can not be an instance of interval (from Date)";
+                    //TODO: Where to move and fix these?
+                    private AMutableInterval aInterval = new AMutableInterval(0L, 0L, (byte) 0);
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<AInterval> intervalSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.AINTERVAL);
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<ANull> nullSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.ANULL);
+
+                    private ByteArrayCharSequenceAccessor charAccessor = new ByteArrayCharSequenceAccessor();
+
+                    @Override
+                    public void evaluate(IFrameTupleReference tuple) throws AlgebricksException {
+
+                        argOut0.reset();
+                        argOut1.reset();
+                        eval0.evaluate(tuple);
+                        eval1.evaluate(tuple);
+
+                        try {
+
+                            if (argOut0.getByteArray()[0] == SER_NULL_TYPE_TAG
+                                    || argOut1.getByteArray()[0] == SER_NULL_TYPE_TAG) {
+                                nullSerde.serialize(ANull.NULL, out);
+                            } else if (argOut0.getByteArray()[0] == SER_STRING_TYPE_TAG
+                                    && argOut1.getByteArray()[0] == SER_STRING_TYPE_TAG) {
+
+                                int stringLength = (argOut0.getByteArray()[1] & 0xff << 8)
+                                        + (argOut0.getByteArray()[2] & 0xff << 0);
+
+                                // start date
+                                charAccessor.reset(argOut0.getByteArray(), 3, stringLength);
+                                long intervalStart = ADateParserFactory.parseDatePart(charAccessor, true)
+                                        / GregorianCalendarSystem.CHRONON_OF_DAY;
+                                // end date
+
+                                stringLength = (argOut1.getByteArray()[1] & 0xff << 8)
+                                        + (argOut1.getByteArray()[2] & 0xff << 0);
+
+                                charAccessor.reset(argOut1.getByteArray(), 3, stringLength);
+                                long intervalEnd = ADateParserFactory.parseDatePart(charAccessor, true)
+                                        / GregorianCalendarSystem.CHRONON_OF_DAY;
+
+                                if (intervalEnd < intervalStart) {
+                                    throw new AlgebricksException(
+                                            "Interval end must not be less than the interval start.");
+                                }
+
+                                aInterval.setValue(intervalStart, intervalEnd, ATypeTag.DATE.serialize());
+                                intervalSerde.serialize(aInterval, out);
+                            } else {
+                                throw new AlgebricksException("Wrong format for interval constructor from dates.");
+                            }
+
+                        } catch (IOException e1) {
+                            throw new AlgebricksException(errorMessage);
+                        } catch (Exception e2) {
+                            throw new AlgebricksException(e2);
+                        }
+                    }
+                };
+            }
+        };
+    }
+
+    @Override
+    public FunctionIdentifier getIdentifier() {
+        return FID;
+    }
+
+}
\ No newline at end of file
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/constructors/AIntervalFromDateTimeConstructorDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/constructors/AIntervalFromDateTimeConstructorDescriptor.java
new file mode 100644
index 0000000..72a8e37
--- /dev/null
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/constructors/AIntervalFromDateTimeConstructorDescriptor.java
@@ -0,0 +1,167 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.runtime.evaluators.constructors;
+
+import java.io.DataOutput;
+import java.io.IOException;
+
+import edu.uci.ics.asterix.common.functions.FunctionConstants;
+import edu.uci.ics.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
+import edu.uci.ics.asterix.om.base.AInterval;
+import edu.uci.ics.asterix.om.base.AMutableInterval;
+import edu.uci.ics.asterix.om.base.ANull;
+import edu.uci.ics.asterix.om.base.temporal.ADateParserFactory;
+import edu.uci.ics.asterix.om.base.temporal.ATimeParserFactory;
+import edu.uci.ics.asterix.om.base.temporal.ByteArrayCharSequenceAccessor;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
+import edu.uci.ics.asterix.om.types.ATypeTag;
+import edu.uci.ics.asterix.om.types.BuiltinType;
+import edu.uci.ics.asterix.runtime.evaluators.base.AbstractScalarFunctionDynamicDescriptor;
+import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
+import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluator;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory;
+import edu.uci.ics.hyracks.api.dataflow.value.ISerializerDeserializer;
+import edu.uci.ics.hyracks.data.std.api.IDataOutputProvider;
+import edu.uci.ics.hyracks.data.std.util.ArrayBackedValueStorage;
+import edu.uci.ics.hyracks.dataflow.common.data.accessors.IFrameTupleReference;
+
+public class AIntervalFromDateTimeConstructorDescriptor extends AbstractScalarFunctionDynamicDescriptor {
+
+    private static final long serialVersionUID = 1L;
+    public final static FunctionIdentifier FID = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "interval-from-datetime", 2);
+    private final static byte SER_STRING_TYPE_TAG = ATypeTag.STRING.serialize();
+    private final static byte SER_NULL_TYPE_TAG = ATypeTag.NULL.serialize();
+
+    public static final IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
+        public IFunctionDescriptor createFunctionDescriptor() {
+            return new AIntervalFromDateTimeConstructorDescriptor();
+        }
+    };
+
+    @Override
+    public ICopyEvaluatorFactory createEvaluatorFactory(final ICopyEvaluatorFactory[] args) {
+        return new ICopyEvaluatorFactory() {
+            private static final long serialVersionUID = 1L;
+
+            @Override
+            public ICopyEvaluator createEvaluator(final IDataOutputProvider output) throws AlgebricksException {
+                return new ICopyEvaluator() {
+
+                    private DataOutput out = output.getDataOutput();
+
+                    private ArrayBackedValueStorage argOut0 = new ArrayBackedValueStorage();
+                    private ArrayBackedValueStorage argOut1 = new ArrayBackedValueStorage();
+                    private ICopyEvaluator eval0 = args[0].createEvaluator(argOut0);
+                    private ICopyEvaluator eval1 = args[1].createEvaluator(argOut1);
+                    private String errorMessage = "This can not be an instance of interval (from Date)";
+                    //TODO: Where to move and fix these?
+                    private AMutableInterval aInterval = new AMutableInterval(0L, 0L, (byte) 0);
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<AInterval> intervalSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.AINTERVAL);
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<ANull> nullSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.ANULL);
+
+                    private ByteArrayCharSequenceAccessor charAccessor = new ByteArrayCharSequenceAccessor();
+
+                    @Override
+                    public void evaluate(IFrameTupleReference tuple) throws AlgebricksException {
+
+                        argOut0.reset();
+                        argOut1.reset();
+                        eval0.evaluate(tuple);
+                        eval1.evaluate(tuple);
+
+                        try {
+
+                            if (argOut0.getByteArray()[0] == SER_NULL_TYPE_TAG
+                                    || argOut1.getByteArray()[0] == SER_NULL_TYPE_TAG) {
+                                nullSerde.serialize(ANull.NULL, out);
+                            } else if (argOut0.getByteArray()[0] == SER_STRING_TYPE_TAG
+                                    && argOut1.getByteArray()[0] == SER_STRING_TYPE_TAG) {
+                                // start date
+
+                                int stringLength = (argOut0.getByteArray()[1] & 0xff << 8)
+                                        + (argOut0.getByteArray()[2] & 0xff << 0);
+
+                                charAccessor.reset(argOut0.getByteArray(), 3, stringLength);
+                                // get offset for time part: +1 if it is negative (-)
+                                short timeOffset = (short) ((charAccessor.getCharAt(0) == '-') ? 1 : 0);
+
+                                if (charAccessor.getCharAt(timeOffset + 10) != 'T'
+                                        && charAccessor.getCharAt(timeOffset + 8) != 'T') {
+                                    throw new AlgebricksException(errorMessage + ": missing T");
+                                }
+
+                                // if extended form 11, else 9
+                                timeOffset += (charAccessor.getCharAt(timeOffset + 13) == ':') ? (short) (11)
+                                        : (short) (9);
+                                long intervalStart = ADateParserFactory.parseDatePart(charAccessor, false);
+                                charAccessor.reset(argOut0.getByteArray(), 3 + timeOffset, stringLength - timeOffset);
+                                intervalStart += ATimeParserFactory.parseTimePart(charAccessor);
+
+                                // end date
+
+                                stringLength = (argOut1.getByteArray()[1] & 0xff << 8)
+                                        + (argOut1.getByteArray()[2] & 0xff << 0);
+
+                                charAccessor.reset(argOut1.getByteArray(), 3, stringLength);
+                                // get offset for time part: +1 if it is negative (-)
+                                timeOffset = (short) ((charAccessor.getCharAt(0) == '-') ? 1 : 0);
+
+                                if (charAccessor.getCharAt(timeOffset + 10) != 'T'
+                                        && charAccessor.getCharAt(timeOffset + 8) != 'T') {
+                                    throw new AlgebricksException(errorMessage + ": missing T");
+                                }
+
+                                // if extended form 11, else 9
+                                timeOffset += (charAccessor.getCharAt(timeOffset + 13) == ':') ? (short) (11)
+                                        : (short) (9);
+                                long intervalEnd = ADateParserFactory.parseDatePart(charAccessor, false);
+                                charAccessor.reset(argOut1.getByteArray(), 3 + timeOffset, stringLength - timeOffset);
+                                intervalEnd += ATimeParserFactory.parseTimePart(charAccessor);
+
+                                if (intervalEnd < intervalStart) {
+                                    throw new AlgebricksException(
+                                            "Interval end must not be less than the interval start.");
+                                }
+
+                                aInterval.setValue(intervalStart, intervalEnd, ATypeTag.DATETIME.serialize());
+                                intervalSerde.serialize(aInterval, out);
+                            } else {
+                                throw new AlgebricksException("Wrong format for interval constructor from dates.");
+                            }
+
+                        } catch (IOException e1) {
+                            throw new AlgebricksException(errorMessage);
+                        } catch (Exception e2) {
+                            throw new AlgebricksException(e2);
+                        }
+                    }
+                };
+            }
+        };
+    }
+
+    @Override
+    public FunctionIdentifier getIdentifier() {
+        return FID;
+    }
+
+}
\ No newline at end of file
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/constructors/AIntervalFromTimeConstructorDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/constructors/AIntervalFromTimeConstructorDescriptor.java
new file mode 100644
index 0000000..3ce722a
--- /dev/null
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/constructors/AIntervalFromTimeConstructorDescriptor.java
@@ -0,0 +1,147 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.runtime.evaluators.constructors;
+
+import java.io.DataOutput;
+import java.io.IOException;
+
+import edu.uci.ics.asterix.common.functions.FunctionConstants;
+import edu.uci.ics.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
+import edu.uci.ics.asterix.om.base.AInterval;
+import edu.uci.ics.asterix.om.base.AMutableInterval;
+import edu.uci.ics.asterix.om.base.ANull;
+import edu.uci.ics.asterix.om.base.temporal.ATimeParserFactory;
+import edu.uci.ics.asterix.om.base.temporal.ByteArrayCharSequenceAccessor;
+import edu.uci.ics.asterix.om.base.temporal.GregorianCalendarSystem;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
+import edu.uci.ics.asterix.om.types.ATypeTag;
+import edu.uci.ics.asterix.om.types.BuiltinType;
+import edu.uci.ics.asterix.runtime.evaluators.base.AbstractScalarFunctionDynamicDescriptor;
+import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
+import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluator;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory;
+import edu.uci.ics.hyracks.api.dataflow.value.ISerializerDeserializer;
+import edu.uci.ics.hyracks.data.std.api.IDataOutputProvider;
+import edu.uci.ics.hyracks.data.std.util.ArrayBackedValueStorage;
+import edu.uci.ics.hyracks.dataflow.common.data.accessors.IFrameTupleReference;
+
+public class AIntervalFromTimeConstructorDescriptor extends AbstractScalarFunctionDynamicDescriptor {
+
+    private static final long serialVersionUID = 1L;
+    public final static FunctionIdentifier FID = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "interval-from-time", 2);
+    private final static byte SER_STRING_TYPE_TAG = ATypeTag.STRING.serialize();
+    private final static byte SER_NULL_TYPE_TAG = ATypeTag.NULL.serialize();
+
+    public static final IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
+        public IFunctionDescriptor createFunctionDescriptor() {
+            return new AIntervalFromTimeConstructorDescriptor();
+        }
+    };
+
+    @Override
+    public ICopyEvaluatorFactory createEvaluatorFactory(final ICopyEvaluatorFactory[] args) {
+        return new ICopyEvaluatorFactory() {
+            private static final long serialVersionUID = 1L;
+
+            @Override
+            public ICopyEvaluator createEvaluator(final IDataOutputProvider output) throws AlgebricksException {
+                return new ICopyEvaluator() {
+
+                    private DataOutput out = output.getDataOutput();
+
+                    private ArrayBackedValueStorage argOut0 = new ArrayBackedValueStorage();
+                    private ArrayBackedValueStorage argOut1 = new ArrayBackedValueStorage();
+                    private ICopyEvaluator eval0 = args[0].createEvaluator(argOut0);
+                    private ICopyEvaluator eval1 = args[1].createEvaluator(argOut1);
+                    private String errorMessage = "This can not be an instance of interval (from Date)";
+                    //TODO: Where to move and fix these?
+                    private AMutableInterval aInterval = new AMutableInterval(0L, 0L, (byte) 0);
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<AInterval> intervalSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.AINTERVAL);
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<ANull> nullSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.ANULL);
+
+                    private ByteArrayCharSequenceAccessor charAccessor = new ByteArrayCharSequenceAccessor();
+
+                    @Override
+                    public void evaluate(IFrameTupleReference tuple) throws AlgebricksException {
+
+                        argOut0.reset();
+                        argOut1.reset();
+                        eval0.evaluate(tuple);
+                        eval1.evaluate(tuple);
+
+                        try {
+
+                            if (argOut0.getByteArray()[0] == SER_NULL_TYPE_TAG
+                                    || argOut1.getByteArray()[0] == SER_NULL_TYPE_TAG) {
+                                nullSerde.serialize(ANull.NULL, out);
+                            } else if (argOut0.getByteArray()[0] == SER_STRING_TYPE_TAG
+                                    && argOut1.getByteArray()[0] == SER_STRING_TYPE_TAG) {
+                                // start date
+
+                                int stringLength = (argOut0.getByteArray()[1] & 0xff << 8)
+                                        + (argOut0.getByteArray()[2] & 0xff << 0);
+
+                                charAccessor.reset(argOut0.getByteArray(), 3, stringLength);
+                                long intervalStart = ATimeParserFactory.parseTimePart(charAccessor);
+                                if (intervalStart < 0) {
+                                    intervalStart += GregorianCalendarSystem.CHRONON_OF_DAY;
+                                }
+
+                                // end date
+
+                                stringLength = (argOut1.getByteArray()[1] & 0xff << 8)
+                                        + (argOut1.getByteArray()[2] & 0xff << 0);
+
+                                charAccessor.reset(argOut1.getByteArray(), 3, stringLength);
+                                long intervalEnd = ATimeParserFactory.parseTimePart(charAccessor);
+                                if (intervalEnd < 0) {
+                                    intervalEnd += GregorianCalendarSystem.CHRONON_OF_DAY;
+                                }
+
+                                if (intervalEnd < intervalStart) {
+                                    throw new AlgebricksException(
+                                            "Interval end must not be less than the interval start.");
+                                }
+
+                                aInterval.setValue(intervalStart, intervalEnd, ATypeTag.TIME.serialize());
+                                intervalSerde.serialize(aInterval, out);
+                            } else {
+                                throw new AlgebricksException("Wrong format for interval constructor from dates.");
+                            }
+
+                        } catch (IOException e1) {
+                            throw new AlgebricksException(errorMessage);
+                        } catch (Exception e2) {
+                            throw new AlgebricksException(e2);
+                        }
+                    }
+                };
+            }
+        };
+    }
+
+    @Override
+    public FunctionIdentifier getIdentifier() {
+        return FID;
+    }
+
+}
\ No newline at end of file
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/constructors/AIntervalStartFromDateConstructorDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/constructors/AIntervalStartFromDateConstructorDescriptor.java
new file mode 100644
index 0000000..23fdb07
--- /dev/null
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/constructors/AIntervalStartFromDateConstructorDescriptor.java
@@ -0,0 +1,150 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.runtime.evaluators.constructors;
+
+import java.io.DataOutput;
+import java.io.IOException;
+
+import edu.uci.ics.asterix.common.functions.FunctionConstants;
+import edu.uci.ics.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
+import edu.uci.ics.asterix.om.base.AInterval;
+import edu.uci.ics.asterix.om.base.AMutableDuration;
+import edu.uci.ics.asterix.om.base.AMutableInterval;
+import edu.uci.ics.asterix.om.base.ANull;
+import edu.uci.ics.asterix.om.base.temporal.ADateParserFactory;
+import edu.uci.ics.asterix.om.base.temporal.ADurationParserFactory;
+import edu.uci.ics.asterix.om.base.temporal.ByteArrayCharSequenceAccessor;
+import edu.uci.ics.asterix.om.base.temporal.DurationArithmeticOperations;
+import edu.uci.ics.asterix.om.base.temporal.GregorianCalendarSystem;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
+import edu.uci.ics.asterix.om.types.ATypeTag;
+import edu.uci.ics.asterix.om.types.BuiltinType;
+import edu.uci.ics.asterix.runtime.evaluators.base.AbstractScalarFunctionDynamicDescriptor;
+import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
+import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluator;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory;
+import edu.uci.ics.hyracks.api.dataflow.value.ISerializerDeserializer;
+import edu.uci.ics.hyracks.data.std.api.IDataOutputProvider;
+import edu.uci.ics.hyracks.data.std.util.ArrayBackedValueStorage;
+import edu.uci.ics.hyracks.dataflow.common.data.accessors.IFrameTupleReference;
+
+public class AIntervalStartFromDateConstructorDescriptor extends AbstractScalarFunctionDynamicDescriptor {
+
+    private static final long serialVersionUID = 1L;
+    public final static FunctionIdentifier FID = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "interval-start-from-date", 2);
+    private final static byte SER_STRING_TYPE_TAG = ATypeTag.STRING.serialize();
+    private final static byte SER_NULL_TYPE_TAG = ATypeTag.NULL.serialize();
+
+    public static final IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
+        public IFunctionDescriptor createFunctionDescriptor() {
+            return new AIntervalStartFromDateConstructorDescriptor();
+        }
+    };
+
+    @Override
+    public ICopyEvaluatorFactory createEvaluatorFactory(final ICopyEvaluatorFactory[] args) {
+        return new ICopyEvaluatorFactory() {
+            private static final long serialVersionUID = 1L;
+
+            @Override
+            public ICopyEvaluator createEvaluator(final IDataOutputProvider output) throws AlgebricksException {
+                return new ICopyEvaluator() {
+
+                    private DataOutput out = output.getDataOutput();
+
+                    private ArrayBackedValueStorage argOut0 = new ArrayBackedValueStorage();
+                    private ArrayBackedValueStorage argOut1 = new ArrayBackedValueStorage();
+                    private ICopyEvaluator eval0 = args[0].createEvaluator(argOut0);
+                    private ICopyEvaluator eval1 = args[1].createEvaluator(argOut1);
+                    private String errorMessage = "This can not be an instance of interval (from Date)";
+
+                    private AMutableInterval aInterval = new AMutableInterval(0L, 0L, (byte) 0);
+                    private AMutableDuration aDuration = new AMutableDuration(0, 0L);
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<AInterval> intervalSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.AINTERVAL);
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<ANull> nullSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.ANULL);
+
+                    private ByteArrayCharSequenceAccessor charAccessor = new ByteArrayCharSequenceAccessor();
+
+                    @Override
+                    public void evaluate(IFrameTupleReference tuple) throws AlgebricksException {
+
+                        argOut0.reset();
+                        argOut1.reset();
+                        eval0.evaluate(tuple);
+                        eval1.evaluate(tuple);
+
+                        try {
+
+                            if (argOut0.getByteArray()[0] == SER_NULL_TYPE_TAG
+                                    || argOut1.getByteArray()[0] == SER_NULL_TYPE_TAG) {
+                                nullSerde.serialize(ANull.NULL, out);
+                            } else if (argOut0.getByteArray()[0] == SER_STRING_TYPE_TAG
+                                    && argOut1.getByteArray()[0] == SER_STRING_TYPE_TAG) {
+                                // start date
+
+                                int stringLength = (argOut0.getByteArray()[1] & 0xff << 8)
+                                        + (argOut0.getByteArray()[2] & 0xff << 0);
+
+                                charAccessor.reset(argOut0.getByteArray(), 3, stringLength);
+                                long intervalStart = ADateParserFactory.parseDatePart(charAccessor, true);
+                                // duration
+
+                                stringLength = (argOut1.getByteArray()[1] & 0xff << 8)
+                                        + (argOut1.getByteArray()[2] & 0xff << 0);
+
+                                charAccessor.reset(argOut1.getByteArray(), 3, stringLength);
+                                ADurationParserFactory.parseDuration(charAccessor, aDuration);
+
+                                long intervalEnd = DurationArithmeticOperations.addDuration(intervalStart,
+                                        aDuration.getMonths(), aDuration.getMilliseconds());
+
+                                intervalStart = GregorianCalendarSystem.getChrononInDays(intervalStart);
+                                intervalEnd = GregorianCalendarSystem.getChrononInDays(intervalEnd);
+
+                                if (intervalEnd < intervalStart) {
+                                    throw new AlgebricksException(
+                                            "Interval end must not be less than the interval start.");
+                                }
+
+                                aInterval.setValue(intervalStart, intervalEnd, ATypeTag.DATE.serialize());
+                                intervalSerde.serialize(aInterval, out);
+                            } else {
+                                throw new AlgebricksException("Wrong format for interval constructor from dates.");
+                            }
+
+                        } catch (IOException e1) {
+                            throw new AlgebricksException(errorMessage);
+                        } catch (Exception e2) {
+                            throw new AlgebricksException(e2);
+                        }
+                    }
+                };
+            }
+        };
+    }
+
+    @Override
+    public FunctionIdentifier getIdentifier() {
+        return FID;
+    }
+
+}
\ No newline at end of file
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/constructors/AIntervalStartFromDateTimeConstructorDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/constructors/AIntervalStartFromDateTimeConstructorDescriptor.java
new file mode 100644
index 0000000..91c45df
--- /dev/null
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/constructors/AIntervalStartFromDateTimeConstructorDescriptor.java
@@ -0,0 +1,161 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.runtime.evaluators.constructors;
+
+import java.io.DataOutput;
+import java.io.IOException;
+
+import edu.uci.ics.asterix.common.functions.FunctionConstants;
+import edu.uci.ics.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
+import edu.uci.ics.asterix.om.base.AInterval;
+import edu.uci.ics.asterix.om.base.AMutableDuration;
+import edu.uci.ics.asterix.om.base.AMutableInterval;
+import edu.uci.ics.asterix.om.base.ANull;
+import edu.uci.ics.asterix.om.base.temporal.ADateParserFactory;
+import edu.uci.ics.asterix.om.base.temporal.ADurationParserFactory;
+import edu.uci.ics.asterix.om.base.temporal.ATimeParserFactory;
+import edu.uci.ics.asterix.om.base.temporal.ByteArrayCharSequenceAccessor;
+import edu.uci.ics.asterix.om.base.temporal.DurationArithmeticOperations;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
+import edu.uci.ics.asterix.om.types.ATypeTag;
+import edu.uci.ics.asterix.om.types.BuiltinType;
+import edu.uci.ics.asterix.runtime.evaluators.base.AbstractScalarFunctionDynamicDescriptor;
+import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
+import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluator;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory;
+import edu.uci.ics.hyracks.api.dataflow.value.ISerializerDeserializer;
+import edu.uci.ics.hyracks.data.std.api.IDataOutputProvider;
+import edu.uci.ics.hyracks.data.std.util.ArrayBackedValueStorage;
+import edu.uci.ics.hyracks.dataflow.common.data.accessors.IFrameTupleReference;
+
+public class AIntervalStartFromDateTimeConstructorDescriptor extends AbstractScalarFunctionDynamicDescriptor {
+
+    private static final long serialVersionUID = 1L;
+    public final static FunctionIdentifier FID = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "interval-start-from-datetime", 2);
+    private final static byte SER_STRING_TYPE_TAG = ATypeTag.STRING.serialize();
+    private final static byte SER_NULL_TYPE_TAG = ATypeTag.NULL.serialize();
+
+    public static final IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
+        public IFunctionDescriptor createFunctionDescriptor() {
+            return new AIntervalStartFromDateTimeConstructorDescriptor();
+        }
+    };
+
+    @Override
+    public ICopyEvaluatorFactory createEvaluatorFactory(final ICopyEvaluatorFactory[] args) {
+        return new ICopyEvaluatorFactory() {
+            private static final long serialVersionUID = 1L;
+
+            @Override
+            public ICopyEvaluator createEvaluator(final IDataOutputProvider output) throws AlgebricksException {
+                return new ICopyEvaluator() {
+
+                    private DataOutput out = output.getDataOutput();
+
+                    private ArrayBackedValueStorage argOut0 = new ArrayBackedValueStorage();
+                    private ArrayBackedValueStorage argOut1 = new ArrayBackedValueStorage();
+                    private ICopyEvaluator eval0 = args[0].createEvaluator(argOut0);
+                    private ICopyEvaluator eval1 = args[1].createEvaluator(argOut1);
+                    private String errorMessage = "This can not be an instance of interval (from Date)";
+
+                    private AMutableInterval aInterval = new AMutableInterval(0L, 0L, (byte) 0);
+                    private AMutableDuration aDuration = new AMutableDuration(0, 0L);
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<AInterval> intervalSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.AINTERVAL);
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<ANull> nullSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.ANULL);
+
+                    private ByteArrayCharSequenceAccessor charAccessor = new ByteArrayCharSequenceAccessor();
+
+                    @Override
+                    public void evaluate(IFrameTupleReference tuple) throws AlgebricksException {
+
+                        argOut0.reset();
+                        argOut1.reset();
+                        eval0.evaluate(tuple);
+                        eval1.evaluate(tuple);
+
+                        try {
+
+                            if (argOut0.getByteArray()[0] == SER_NULL_TYPE_TAG
+                                    || argOut1.getByteArray()[0] == SER_NULL_TYPE_TAG) {
+                                nullSerde.serialize(ANull.NULL, out);
+                            } else if (argOut0.getByteArray()[0] == SER_STRING_TYPE_TAG
+                                    && argOut1.getByteArray()[0] == SER_STRING_TYPE_TAG) {
+                                // start date
+
+                                int stringLength = (argOut0.getByteArray()[1] & 0xff << 8)
+                                        + (argOut0.getByteArray()[2] & 0xff << 0);
+
+                                charAccessor.reset(argOut0.getByteArray(), 3, stringLength);
+                                // get offset for time part: +1 if it is negative (-)
+                                short timeOffset = (short) ((charAccessor.getCharAt(0) == '-') ? 1 : 0);
+
+                                if (charAccessor.getCharAt(timeOffset + 10) != 'T'
+                                        && charAccessor.getCharAt(timeOffset + 8) != 'T') {
+                                    throw new AlgebricksException(errorMessage + ": missing T");
+                                }
+
+                                // if extended form 11, else 9
+                                timeOffset += (charAccessor.getCharAt(timeOffset + 13) == ':') ? (short) (11)
+                                        : (short) (9);
+                                long intervalStart = ADateParserFactory.parseDatePart(charAccessor, false);
+                                charAccessor.reset(argOut0.getByteArray(), 3 + timeOffset, stringLength - timeOffset);
+                                intervalStart += ATimeParserFactory.parseTimePart(charAccessor);
+
+                                // duration
+
+                                stringLength = (argOut1.getByteArray()[1] & 0xff << 8)
+                                        + (argOut1.getByteArray()[2] & 0xff << 0);
+
+                                charAccessor.reset(argOut1.getByteArray(), 3, stringLength);
+                                ADurationParserFactory.parseDuration(charAccessor, aDuration);
+
+                                long intervalEnd = DurationArithmeticOperations.addDuration(intervalStart,
+                                        aDuration.getMonths(), aDuration.getMilliseconds());
+
+                                if (intervalEnd < intervalStart) {
+                                    throw new AlgebricksException(
+                                            "Interval end must not be less than the interval start.");
+                                }
+
+                                aInterval.setValue(intervalStart, intervalEnd, ATypeTag.DATETIME.serialize());
+                                intervalSerde.serialize(aInterval, out);
+                            } else {
+                                throw new AlgebricksException("Wrong format for interval constructor from dates.");
+                            }
+
+                        } catch (IOException e1) {
+                            throw new AlgebricksException(errorMessage);
+                        } catch (Exception e2) {
+                            throw new AlgebricksException(e2);
+                        }
+                    }
+                };
+            }
+        };
+    }
+
+    @Override
+    public FunctionIdentifier getIdentifier() {
+        return FID;
+    }
+
+}
\ No newline at end of file
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/constructors/AIntervalStartFromTimeConstructorDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/constructors/AIntervalStartFromTimeConstructorDescriptor.java
new file mode 100644
index 0000000..e576fef
--- /dev/null
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/constructors/AIntervalStartFromTimeConstructorDescriptor.java
@@ -0,0 +1,161 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.runtime.evaluators.constructors;
+
+import java.io.DataOutput;
+import java.io.IOException;
+
+import edu.uci.ics.asterix.common.functions.FunctionConstants;
+import edu.uci.ics.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
+import edu.uci.ics.asterix.om.base.AInterval;
+import edu.uci.ics.asterix.om.base.AMutableDuration;
+import edu.uci.ics.asterix.om.base.AMutableInterval;
+import edu.uci.ics.asterix.om.base.ANull;
+import edu.uci.ics.asterix.om.base.temporal.ADurationParserFactory;
+import edu.uci.ics.asterix.om.base.temporal.ATimeParserFactory;
+import edu.uci.ics.asterix.om.base.temporal.ByteArrayCharSequenceAccessor;
+import edu.uci.ics.asterix.om.base.temporal.DurationArithmeticOperations;
+import edu.uci.ics.asterix.om.base.temporal.GregorianCalendarSystem;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
+import edu.uci.ics.asterix.om.types.ATypeTag;
+import edu.uci.ics.asterix.om.types.BuiltinType;
+import edu.uci.ics.asterix.runtime.evaluators.base.AbstractScalarFunctionDynamicDescriptor;
+import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
+import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluator;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory;
+import edu.uci.ics.hyracks.api.dataflow.value.ISerializerDeserializer;
+import edu.uci.ics.hyracks.data.std.api.IDataOutputProvider;
+import edu.uci.ics.hyracks.data.std.util.ArrayBackedValueStorage;
+import edu.uci.ics.hyracks.dataflow.common.data.accessors.IFrameTupleReference;
+
+public class AIntervalStartFromTimeConstructorDescriptor extends AbstractScalarFunctionDynamicDescriptor {
+
+    private static final long serialVersionUID = 1L;
+    public final static FunctionIdentifier FID = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "interval-start-from-time", 2);
+    private final static byte SER_STRING_TYPE_TAG = ATypeTag.STRING.serialize();
+    private final static byte SER_NULL_TYPE_TAG = ATypeTag.NULL.serialize();
+
+    public static final IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
+        public IFunctionDescriptor createFunctionDescriptor() {
+            return new AIntervalStartFromTimeConstructorDescriptor();
+        }
+    };
+
+    @Override
+    public ICopyEvaluatorFactory createEvaluatorFactory(final ICopyEvaluatorFactory[] args) {
+        return new ICopyEvaluatorFactory() {
+            private static final long serialVersionUID = 1L;
+
+            @Override
+            public ICopyEvaluator createEvaluator(final IDataOutputProvider output) throws AlgebricksException {
+                return new ICopyEvaluator() {
+
+                    private DataOutput out = output.getDataOutput();
+
+                    private ArrayBackedValueStorage argOut0 = new ArrayBackedValueStorage();
+                    private ArrayBackedValueStorage argOut1 = new ArrayBackedValueStorage();
+                    private ICopyEvaluator eval0 = args[0].createEvaluator(argOut0);
+                    private ICopyEvaluator eval1 = args[1].createEvaluator(argOut1);
+                    private String errorMessage = "This can not be an instance of interval (from Date)";
+
+                    private AMutableInterval aInterval = new AMutableInterval(0L, 0L, (byte) 0);
+                    private AMutableDuration aDuration = new AMutableDuration(0, 0L);
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<AInterval> intervalSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.AINTERVAL);
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<ANull> nullSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.ANULL);
+
+                    private ByteArrayCharSequenceAccessor charAccessor = new ByteArrayCharSequenceAccessor();
+
+                    @Override
+                    public void evaluate(IFrameTupleReference tuple) throws AlgebricksException {
+
+                        argOut0.reset();
+                        argOut1.reset();
+                        eval0.evaluate(tuple);
+                        eval1.evaluate(tuple);
+
+                        try {
+
+                            if (argOut0.getByteArray()[0] == SER_NULL_TYPE_TAG
+                                    || argOut1.getByteArray()[0] == SER_NULL_TYPE_TAG) {
+                                nullSerde.serialize(ANull.NULL, out);
+                            } else if (argOut0.getByteArray()[0] == SER_STRING_TYPE_TAG
+                                    && argOut1.getByteArray()[0] == SER_STRING_TYPE_TAG) {
+                                // start time
+
+                                int stringLength = (argOut0.getByteArray()[1] & 0xff << 8)
+                                        + (argOut0.getByteArray()[2] & 0xff << 0);
+
+                                charAccessor.reset(argOut0.getByteArray(), 3, stringLength);
+                                int intervalStart = ATimeParserFactory.parseTimePart(charAccessor);
+
+                                if (intervalStart < 0) {
+                                    intervalStart += GregorianCalendarSystem.CHRONON_OF_DAY;
+                                }
+
+                                // duration
+
+                                stringLength = (argOut1.getByteArray()[1] & 0xff << 8)
+                                        + (argOut1.getByteArray()[2] & 0xff << 0);
+
+                                charAccessor.reset(argOut1.getByteArray(), 3, stringLength);
+                                ADurationParserFactory.parseDuration(charAccessor, aDuration);
+
+                                if (aDuration.getMonths() != 0) {
+                                    throw new AlgebricksException("Cannot add a year-month duration to a time value.");
+                                }
+
+                                int intervalEnd = DurationArithmeticOperations.addDuration(intervalStart,
+                                        aDuration.getMilliseconds());
+
+                                if (intervalEnd > GregorianCalendarSystem.CHRONON_OF_DAY) {
+
+                                    intervalEnd = intervalEnd - (int) (GregorianCalendarSystem.CHRONON_OF_DAY);
+                                }
+
+                                if (intervalEnd < intervalStart) {
+                                    throw new AlgebricksException(
+                                            "Interval end must not be less than the interval start.");
+                                }
+
+                                aInterval.setValue(intervalStart, intervalEnd, ATypeTag.TIME.serialize());
+                                intervalSerde.serialize(aInterval, out);
+                            } else {
+                                throw new AlgebricksException("Wrong format for interval constructor from dates.");
+                            }
+
+                        } catch (IOException e1) {
+                            throw new AlgebricksException(errorMessage);
+                        } catch (Exception e2) {
+                            throw new AlgebricksException(e2);
+                        }
+                    }
+                };
+            }
+        };
+    }
+
+    @Override
+    public FunctionIdentifier getIdentifier() {
+        return FID;
+    }
+
+}
\ No newline at end of file
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/constructors/ATimeConstructorDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/constructors/ATimeConstructorDescriptor.java
index 1a7eb12..caff78b 100644
--- a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/constructors/ATimeConstructorDescriptor.java
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/constructors/ATimeConstructorDescriptor.java
@@ -21,8 +21,9 @@
 import edu.uci.ics.asterix.om.base.AMutableTime;
 import edu.uci.ics.asterix.om.base.ANull;
 import edu.uci.ics.asterix.om.base.ATime;
-import edu.uci.ics.asterix.om.base.temporal.ADateAndTimeParser;
+import edu.uci.ics.asterix.om.base.temporal.ATimeParserFactory;
 import edu.uci.ics.asterix.om.base.temporal.ByteArrayCharSequenceAccessor;
+import edu.uci.ics.asterix.om.base.temporal.GregorianCalendarSystem;
 import edu.uci.ics.asterix.om.functions.AsterixBuiltinFunctions;
 import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
 import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
@@ -82,8 +83,15 @@
                             eval.evaluate(tuple);
                             byte[] serString = outInput.getByteArray();
                             if (serString[0] == SER_STRING_TYPE_TAG) {
-                                charAccessor.reset(serString, 3, 0);
-                                int chrononTimeInMs = ADateAndTimeParser.parseTimePart(charAccessor);
+
+                                int stringLength = (serString[1] & 0xff << 8) + (serString[2] & 0xff << 0);
+
+                                charAccessor.reset(serString, 3, stringLength);
+                                int chrononTimeInMs = ATimeParserFactory.parseTimePart(charAccessor);
+
+                                if (chrononTimeInMs < 0) {
+                                    chrononTimeInMs += GregorianCalendarSystem.CHRONON_OF_DAY;
+                                }
 
                                 aTime.setValue(chrononTimeInMs);
                                 timeSerde.serialize(aTime, out);
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/NotNullDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/NotNullDescriptor.java
new file mode 100644
index 0000000..12e73f6
--- /dev/null
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/NotNullDescriptor.java
@@ -0,0 +1,87 @@
+/*
+ * Copyright 2009-2010 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package edu.uci.ics.asterix.runtime.evaluators.functions;
+
+import java.io.DataOutput;
+import java.io.IOException;
+
+import edu.uci.ics.asterix.om.functions.AsterixBuiltinFunctions;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
+import edu.uci.ics.asterix.om.types.ATypeTag;
+import edu.uci.ics.asterix.runtime.evaluators.base.AbstractScalarFunctionDynamicDescriptor;
+import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
+import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluator;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory;
+import edu.uci.ics.hyracks.data.std.api.IDataOutputProvider;
+import edu.uci.ics.hyracks.data.std.util.ArrayBackedValueStorage;
+import edu.uci.ics.hyracks.dataflow.common.data.accessors.IFrameTupleReference;
+
+/**
+ * This runtime function checks if the input is null.
+ * If the input is not null, just return it directly;
+ * Otherwise, throw a runtime exception.
+ */
+public class NotNullDescriptor extends AbstractScalarFunctionDynamicDescriptor {
+
+    private static final long serialVersionUID = 1L;
+    public static final IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
+        public IFunctionDescriptor createFunctionDescriptor() {
+            return new NotNullDescriptor();
+        }
+    };
+    private final static byte SER_NULL_TYPE_TAG = ATypeTag.NULL.serialize();
+
+    @Override
+    public ICopyEvaluatorFactory createEvaluatorFactory(final ICopyEvaluatorFactory[] args) {
+        return new ICopyEvaluatorFactory() {
+            private static final long serialVersionUID = 1L;
+
+            @Override
+            public ICopyEvaluator createEvaluator(final IDataOutputProvider output) throws AlgebricksException {
+                return new ICopyEvaluator() {
+                    private DataOutput out = output.getDataOutput();
+                    private ArrayBackedValueStorage outInput = new ArrayBackedValueStorage();
+                    private ICopyEvaluator eval = args[0].createEvaluator(outInput);
+                    private String errorMessage = "The input value cannot be null!";
+
+                    @Override
+                    public void evaluate(IFrameTupleReference tuple) throws AlgebricksException {
+
+                        try {
+                            outInput.reset();
+                            eval.evaluate(tuple);
+                            byte[] data = outInput.getByteArray();
+                            if (data[outInput.getStartOffset()] == SER_NULL_TYPE_TAG) {
+                                throw new AlgebricksException(errorMessage);
+                            }
+                            out.write(data, outInput.getStartOffset(), outInput.getLength());
+                        } catch (IOException e1) {
+                            throw new AlgebricksException(errorMessage);
+                        }
+                    }
+                };
+            }
+        };
+    }
+
+    @Override
+    public FunctionIdentifier getIdentifier() {
+        return AsterixBuiltinFunctions.NOT_NULL;
+    }
+
+}
\ No newline at end of file
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/YearDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/YearDescriptor.java
deleted file mode 100644
index 107f3cd..0000000
--- a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/YearDescriptor.java
+++ /dev/null
@@ -1,102 +0,0 @@
-package edu.uci.ics.asterix.runtime.evaluators.functions;
-
-import java.io.DataOutput;
-
-import edu.uci.ics.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
-import edu.uci.ics.asterix.om.base.AInt32;
-import edu.uci.ics.asterix.om.base.AMutableInt32;
-import edu.uci.ics.asterix.om.base.ANull;
-import edu.uci.ics.asterix.om.functions.AsterixBuiltinFunctions;
-import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
-import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
-import edu.uci.ics.asterix.om.types.ATypeTag;
-import edu.uci.ics.asterix.om.types.BuiltinType;
-import edu.uci.ics.asterix.om.types.EnumDeserializer;
-import edu.uci.ics.asterix.runtime.evaluators.base.AbstractScalarFunctionDynamicDescriptor;
-import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
-import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
-import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluator;
-import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory;
-import edu.uci.ics.hyracks.api.dataflow.value.ISerializerDeserializer;
-import edu.uci.ics.hyracks.api.exceptions.HyracksDataException;
-import edu.uci.ics.hyracks.data.std.api.IDataOutputProvider;
-import edu.uci.ics.hyracks.data.std.primitive.UTF8StringPointable;
-import edu.uci.ics.hyracks.data.std.util.ArrayBackedValueStorage;
-import edu.uci.ics.hyracks.dataflow.common.data.accessors.IFrameTupleReference;
-
-public class YearDescriptor extends AbstractScalarFunctionDynamicDescriptor {
-
-    private static final long serialVersionUID = 1L;
-    private final static byte SER_NULL_TYPE_TAG = ATypeTag.NULL.serialize();
-    private final static byte SER_STRING_TYPE_TAG = ATypeTag.STRING.serialize();
-    public static final IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
-        public IFunctionDescriptor createFunctionDescriptor() {
-            return new YearDescriptor();
-        }
-    };
-
-    @Override
-    public FunctionIdentifier getIdentifier() {
-        return AsterixBuiltinFunctions.YEAR;
-    }
-
-    /**
-     * Returns the 4-digit representation of a year from a string, as an int32.
-     * e.g. year('2010-10-24') = 2010
-     */
-
-    @Override
-    public ICopyEvaluatorFactory createEvaluatorFactory(final ICopyEvaluatorFactory[] args) {
-
-        return new ICopyEvaluatorFactory() {
-            private static final long serialVersionUID = 1L;
-
-            @Override
-            public ICopyEvaluator createEvaluator(IDataOutputProvider output) throws AlgebricksException {
-                final DataOutput out = output.getDataOutput();
-
-                return new ICopyEvaluator() {
-                    private ArrayBackedValueStorage out1 = new ArrayBackedValueStorage();
-                    private ICopyEvaluator eval1 = args[0].createEvaluator(out1);
-                    private AMutableInt32 m = new AMutableInt32(0);
-                    @SuppressWarnings("unchecked")
-                    private ISerializerDeserializer<AInt32> int32Serde = AqlSerializerDeserializerProvider.INSTANCE
-                            .getSerializerDeserializer(BuiltinType.AINT32);
-                    @SuppressWarnings("unchecked")
-                    private ISerializerDeserializer<ANull> nullSerde = AqlSerializerDeserializerProvider.INSTANCE
-                            .getSerializerDeserializer(BuiltinType.ANULL);
-
-                    @Override
-                    public void evaluate(IFrameTupleReference tuple) throws AlgebricksException {
-                        try {
-                            out1.reset();
-                            eval1.evaluate(tuple);
-                            byte[] dateArray = out1.getByteArray();
-
-                            if (dateArray[0] == SER_NULL_TYPE_TAG) {
-                                nullSerde.serialize(ANull.NULL, out);
-                                return;
-                            }
-
-                            if (dateArray[0] != SER_STRING_TYPE_TAG) {
-                                throw new AlgebricksException("year function can not be called on values of type"
-                                        + EnumDeserializer.ATYPETAGDESERIALIZER.deserialize(dateArray[0]));
-                            }
-
-                            int year = (UTF8StringPointable.charAt(dateArray, 3) - '0') * 1000
-                                    + (UTF8StringPointable.charAt(dateArray, 4) - '0') * 100
-                                    + (UTF8StringPointable.charAt(dateArray, 5) - '0') * 10
-                                    + (UTF8StringPointable.charAt(dateArray, 6) - '0');
-                            m.setValue(year);
-
-                            int32Serde.serialize(m, out);
-                        } catch (HyracksDataException e) {
-                            throw new AlgebricksException(e);
-                        }
-                    }
-                };
-            }
-        };
-    }
-
-}
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/AbstractIntervalLogicFuncDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/AbstractIntervalLogicFuncDescriptor.java
new file mode 100644
index 0000000..241e2e0
--- /dev/null
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/AbstractIntervalLogicFuncDescriptor.java
@@ -0,0 +1,117 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.runtime.evaluators.functions.temporal;
+
+import java.io.DataOutput;
+
+import edu.uci.ics.asterix.dataflow.data.nontagged.serde.AIntervalSerializerDeserializer;
+import edu.uci.ics.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
+import edu.uci.ics.asterix.om.base.ABoolean;
+import edu.uci.ics.asterix.om.base.ANull;
+import edu.uci.ics.asterix.om.types.ATypeTag;
+import edu.uci.ics.asterix.om.types.BuiltinType;
+import edu.uci.ics.asterix.runtime.evaluators.base.AbstractScalarFunctionDynamicDescriptor;
+import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluator;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory;
+import edu.uci.ics.hyracks.api.dataflow.value.ISerializerDeserializer;
+import edu.uci.ics.hyracks.api.exceptions.HyracksDataException;
+import edu.uci.ics.hyracks.data.std.api.IDataOutputProvider;
+import edu.uci.ics.hyracks.data.std.util.ArrayBackedValueStorage;
+import edu.uci.ics.hyracks.dataflow.common.data.accessors.IFrameTupleReference;
+
+public abstract class AbstractIntervalLogicFuncDescriptor extends AbstractScalarFunctionDynamicDescriptor {
+
+    private final static long serialVersionUID = 1L;
+
+    // allowed input types
+    private final static byte SER_INTERVAL_TYPE_TAG = ATypeTag.INTERVAL.serialize();
+    private final static byte SER_NULL_TYPE_TAG = ATypeTag.NULL.serialize();
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.runtime.base.IScalarFunctionDynamicDescriptor#createEvaluatorFactory(edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory[])
+     */
+    @Override
+    public ICopyEvaluatorFactory createEvaluatorFactory(final ICopyEvaluatorFactory[] args) throws AlgebricksException {
+        return new ICopyEvaluatorFactory() {
+
+            private static final long serialVersionUID = 1L;
+
+            @Override
+            public ICopyEvaluator createEvaluator(final IDataOutputProvider output) throws AlgebricksException {
+
+                return new ICopyEvaluator() {
+
+                    private DataOutput out = output.getDataOutput();
+                    private ArrayBackedValueStorage argOut0 = new ArrayBackedValueStorage();
+                    private ArrayBackedValueStorage argOut1 = new ArrayBackedValueStorage();
+                    private ICopyEvaluator eval0 = args[0].createEvaluator(argOut0);
+                    private ICopyEvaluator eval1 = args[1].createEvaluator(argOut1);
+
+                    // possible output types
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<ANull> nullSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.ANULL);
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<ABoolean> booleanSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.ABOOLEAN);
+
+                    @Override
+                    public void evaluate(IFrameTupleReference tuple) throws AlgebricksException {
+                        argOut0.reset();
+                        eval0.evaluate(tuple);
+                        argOut1.reset();
+                        eval1.evaluate(tuple);
+
+                        try {
+                            if (argOut0.getByteArray()[0] == SER_NULL_TYPE_TAG
+                                    || argOut1.getByteArray()[0] == SER_NULL_TYPE_TAG) {
+                                nullSerde.serialize(ANull.NULL, out);
+                                return;
+                            }
+
+                            if (argOut0.getByteArray()[0] != SER_INTERVAL_TYPE_TAG
+                                    || argOut1.getByteArray()[0] != SER_INTERVAL_TYPE_TAG) {
+                                throw new AlgebricksException("Inapplicable input type for parameters: ("
+                                        + argOut0.getByteArray()[0] + ", " + argOut1.getByteArray()[0] + ")");
+                            }
+
+                            if (AIntervalSerializerDeserializer.getIntervalTimeType(argOut0.getByteArray(), 1) != AIntervalSerializerDeserializer
+                                    .getIntervalTimeType(argOut1.getByteArray(), 1)) {
+                                throw new AlgebricksException(
+                                        "Failed to compare to intervals with different internal time type.");
+                            }
+
+                            ABoolean res = (compareIntervals(
+                                    AIntervalSerializerDeserializer.getIntervalStart(argOut0.getByteArray(), 1),
+                                    AIntervalSerializerDeserializer.getIntervalEnd(argOut0.getByteArray(), 1),
+                                    AIntervalSerializerDeserializer.getIntervalStart(argOut1.getByteArray(), 1),
+                                    AIntervalSerializerDeserializer.getIntervalEnd(argOut1.getByteArray(), 1))) ? ABoolean.TRUE
+                                    : ABoolean.FALSE;
+
+                            booleanSerde.serialize(res, out);
+
+                        } catch (HyracksDataException hex) {
+                            throw new AlgebricksException(hex);
+                        }
+                    }
+                };
+            }
+        };
+    }
+
+    protected abstract boolean compareIntervals(long s1, long e1, long s2, long e2);
+
+}
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/AddDateDurationDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/AddDateDurationDescriptor.java
new file mode 100644
index 0000000..7417f2b
--- /dev/null
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/AddDateDurationDescriptor.java
@@ -0,0 +1,150 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.runtime.evaluators.functions.temporal;
+
+import java.io.DataOutput;
+
+import edu.uci.ics.asterix.common.functions.FunctionConstants;
+import edu.uci.ics.asterix.dataflow.data.nontagged.serde.ADateSerializerDeserializer;
+import edu.uci.ics.asterix.dataflow.data.nontagged.serde.ADurationSerializerDeserializer;
+import edu.uci.ics.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
+import edu.uci.ics.asterix.om.base.ADate;
+import edu.uci.ics.asterix.om.base.AMutableDate;
+import edu.uci.ics.asterix.om.base.ANull;
+import edu.uci.ics.asterix.om.base.temporal.DurationArithmeticOperations;
+import edu.uci.ics.asterix.om.base.temporal.GregorianCalendarSystem;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
+import edu.uci.ics.asterix.om.types.ATypeTag;
+import edu.uci.ics.asterix.om.types.BuiltinType;
+import edu.uci.ics.asterix.runtime.evaluators.base.AbstractScalarFunctionDynamicDescriptor;
+import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
+import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluator;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory;
+import edu.uci.ics.hyracks.api.dataflow.value.ISerializerDeserializer;
+import edu.uci.ics.hyracks.api.exceptions.HyracksDataException;
+import edu.uci.ics.hyracks.data.std.api.IDataOutputProvider;
+import edu.uci.ics.hyracks.data.std.util.ArrayBackedValueStorage;
+import edu.uci.ics.hyracks.dataflow.common.data.accessors.IFrameTupleReference;
+
+public class AddDateDurationDescriptor extends AbstractScalarFunctionDynamicDescriptor {
+
+    private final static long serialVersionUID = 1L;
+    public final static FunctionIdentifier FID = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "add-date-duration", 2);
+
+    // allowed input types
+    private final static byte SER_NULL_TYPE_TAG = ATypeTag.NULL.serialize();
+    private final static byte SER_DATE_TYPE_TAG = ATypeTag.DATE.serialize();
+    private final static byte SER_DURATION_TYPE_TAG = ATypeTag.DURATION.serialize();
+
+    public final static IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
+
+        @Override
+        public IFunctionDescriptor createFunctionDescriptor() {
+            return new AddDateDurationDescriptor();
+        }
+    };
+
+    @Override
+    public ICopyEvaluatorFactory createEvaluatorFactory(final ICopyEvaluatorFactory[] args) throws AlgebricksException {
+        return new ICopyEvaluatorFactory() {
+
+            private static final long serialVersionUID = 1L;
+
+            @Override
+            public ICopyEvaluator createEvaluator(final IDataOutputProvider output) throws AlgebricksException {
+                return new ICopyEvaluator() {
+
+                    private DataOutput out = output.getDataOutput();
+                    private ArrayBackedValueStorage argOut0 = new ArrayBackedValueStorage();
+                    private ArrayBackedValueStorage argOut1 = new ArrayBackedValueStorage();
+                    private ICopyEvaluator eval0 = args[0].createEvaluator(argOut0);
+                    private ICopyEvaluator eval1 = args[1].createEvaluator(argOut1);
+
+                    // possible output types
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<ANull> nullSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.ANULL);
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<ADate> dateSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.ADATE);
+
+                    private AMutableDate aDate = new AMutableDate(0);
+
+                    @Override
+                    public void evaluate(IFrameTupleReference tuple) throws AlgebricksException {
+                        argOut0.reset();
+                        eval0.evaluate(tuple);
+                        argOut1.reset();
+                        eval1.evaluate(tuple);
+
+                        try {
+                            if (argOut0.getByteArray()[0] == SER_NULL_TYPE_TAG
+                                    || argOut1.getByteArray()[0] == SER_NULL_TYPE_TAG) {
+                                nullSerde.serialize(ANull.NULL, out);
+                                return;
+                            }
+
+                            if (argOut0.getByteArray()[0] != SER_DATE_TYPE_TAG) {
+                                throw new AlgebricksException(
+                                        "Inapplicable input type for parameter 0: expecting a Date ("
+                                                + SER_DATE_TYPE_TAG + ") or null (" + SER_NULL_TYPE_TAG
+                                                + "), but got: " + argOut0.getByteArray()[0]);
+                            }
+
+                            if (argOut1.getByteArray()[0] != SER_DURATION_TYPE_TAG) {
+                                throw new AlgebricksException(
+                                        "Inapplicable input type for parameter 1: expecting a Duration ("
+                                                + SER_DURATION_TYPE_TAG + ") or null (" + SER_NULL_TYPE_TAG
+                                                + "), but got: " + argOut1.getByteArray()[0]);
+                            }
+
+                            // get duration fields: yearMonth field and dayTime field
+                            int yearMonth = ADurationSerializerDeserializer.getYearMonth(argOut1.getByteArray(), 1);
+                            long dayTime = ADurationSerializerDeserializer.getDayTime(argOut1.getByteArray(), 1);
+
+                            // get date fields
+                            long datetimeChronon = ADateSerializerDeserializer.getChronon(argOut0.getByteArray(), 1)
+                                    * GregorianCalendarSystem.CHRONON_OF_DAY;
+
+                            datetimeChronon = DurationArithmeticOperations.addDuration(datetimeChronon, yearMonth,
+                                    dayTime);
+
+                            int dateChrononInDays = (int) (datetimeChronon / GregorianCalendarSystem.CHRONON_OF_DAY);
+                            if (dateChrononInDays < 0 && datetimeChronon % GregorianCalendarSystem.CHRONON_OF_DAY != 0) {
+                                dateChrononInDays -= 1;
+                            }
+
+                            aDate.setValue(dateChrononInDays);
+
+                            dateSerde.serialize(aDate, out);
+
+                        } catch (HyracksDataException hex) {
+                            throw new AlgebricksException(hex);
+                        }
+                    }
+                };
+            }
+        };
+    }
+
+    @Override
+    public FunctionIdentifier getIdentifier() {
+        return FID;
+    }
+
+}
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/AddDatetimeDurationDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/AddDatetimeDurationDescriptor.java
new file mode 100644
index 0000000..4f04da3
--- /dev/null
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/AddDatetimeDurationDescriptor.java
@@ -0,0 +1,150 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.runtime.evaluators.functions.temporal;
+
+import java.io.DataOutput;
+
+import edu.uci.ics.asterix.common.functions.FunctionConstants;
+import edu.uci.ics.asterix.dataflow.data.nontagged.serde.ADateTimeSerializerDeserializer;
+import edu.uci.ics.asterix.dataflow.data.nontagged.serde.ADurationSerializerDeserializer;
+import edu.uci.ics.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
+import edu.uci.ics.asterix.om.base.ADateTime;
+import edu.uci.ics.asterix.om.base.AMutableDateTime;
+import edu.uci.ics.asterix.om.base.ANull;
+import edu.uci.ics.asterix.om.base.temporal.DurationArithmeticOperations;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
+import edu.uci.ics.asterix.om.types.ATypeTag;
+import edu.uci.ics.asterix.om.types.BuiltinType;
+import edu.uci.ics.asterix.runtime.evaluators.base.AbstractScalarFunctionDynamicDescriptor;
+import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
+import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluator;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory;
+import edu.uci.ics.hyracks.api.dataflow.value.ISerializerDeserializer;
+import edu.uci.ics.hyracks.api.exceptions.HyracksDataException;
+import edu.uci.ics.hyracks.data.std.api.IDataOutputProvider;
+import edu.uci.ics.hyracks.data.std.util.ArrayBackedValueStorage;
+import edu.uci.ics.hyracks.dataflow.common.data.accessors.IFrameTupleReference;
+
+public class AddDatetimeDurationDescriptor extends AbstractScalarFunctionDynamicDescriptor {
+
+    private final static long serialVersionUID = 1L;
+    public final static FunctionIdentifier FID = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "add-datetime-duration", 2);
+
+    // allowed input types
+    private final static byte SER_NULL_TYPE_TAG = ATypeTag.NULL.serialize();
+    private final static byte SER_DATETIME_TYPE_TAG = ATypeTag.DATETIME.serialize();
+    private final static byte SER_DURATION_TYPE_TAG = ATypeTag.DURATION.serialize();
+
+    public final static IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
+
+        @Override
+        public IFunctionDescriptor createFunctionDescriptor() {
+            return new AddDatetimeDurationDescriptor();
+        }
+    };
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.runtime.base.IScalarFunctionDynamicDescriptor#createEvaluatorFactory(edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory[])
+     */
+    @Override
+    public ICopyEvaluatorFactory createEvaluatorFactory(final ICopyEvaluatorFactory[] args) throws AlgebricksException {
+        return new ICopyEvaluatorFactory() {
+
+            private static final long serialVersionUID = 1L;
+
+            @Override
+            public ICopyEvaluator createEvaluator(final IDataOutputProvider output) throws AlgebricksException {
+                return new ICopyEvaluator() {
+
+                    private DataOutput out = output.getDataOutput();
+                    private ArrayBackedValueStorage argOut0 = new ArrayBackedValueStorage();
+                    private ArrayBackedValueStorage argOut1 = new ArrayBackedValueStorage();
+                    private ICopyEvaluator eval0 = args[0].createEvaluator(argOut0);
+                    private ICopyEvaluator eval1 = args[1].createEvaluator(argOut1);
+
+                    // possible output types
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<ANull> nullSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.ANULL);
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<ADateTime> datetimeSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.ADATETIME);
+
+                    private AMutableDateTime aDatetime = new AMutableDateTime(0);
+
+                    @Override
+                    public void evaluate(IFrameTupleReference tuple) throws AlgebricksException {
+                        argOut0.reset();
+                        eval0.evaluate(tuple);
+                        argOut1.reset();
+                        eval1.evaluate(tuple);
+
+                        try {
+                            if (argOut0.getByteArray()[0] == SER_NULL_TYPE_TAG
+                                    || argOut1.getByteArray()[0] == SER_NULL_TYPE_TAG) {
+                                nullSerde.serialize(ANull.NULL, out);
+                                return;
+                            }
+
+                            if (argOut0.getByteArray()[0] != SER_DATETIME_TYPE_TAG) {
+                                throw new AlgebricksException(
+                                        "Inapplicable input type for parameter 0: expecting a DateTime ("
+                                                + SER_DATETIME_TYPE_TAG + ") or null (" + SER_NULL_TYPE_TAG
+                                                + "), but got: " + argOut0.getByteArray()[0]);
+                            }
+
+                            if (argOut1.getByteArray()[0] != SER_DURATION_TYPE_TAG) {
+                                throw new AlgebricksException(
+                                        "Inapplicable input type for parameter 1: expecting a Duration ("
+                                                + SER_DURATION_TYPE_TAG + ") or null (" + SER_NULL_TYPE_TAG
+                                                + "), but got: " + argOut1.getByteArray()[0]);
+                            }
+
+                            // get duration fields: yearMonth field and dayTime field
+                            int yearMonth = ADurationSerializerDeserializer.getYearMonth(argOut1.getByteArray(), 1);
+                            long dayTime = ADurationSerializerDeserializer.getDayTime(argOut1.getByteArray(), 1);
+
+                            // get date fields
+                            long datetimeChronon = ADateTimeSerializerDeserializer
+                                    .getChronon(argOut0.getByteArray(), 1);
+
+                            datetimeChronon = DurationArithmeticOperations.addDuration(datetimeChronon, yearMonth,
+                                    dayTime);
+
+                            aDatetime.setValue(datetimeChronon);
+
+                            datetimeSerde.serialize(aDatetime, out);
+
+                        } catch (HyracksDataException hex) {
+                            throw new AlgebricksException(hex);
+                        }
+                    }
+                };
+            }
+        };
+    }
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.om.functions.IFunctionDescriptor#getIdentifier()
+     */
+    @Override
+    public FunctionIdentifier getIdentifier() {
+        return FID;
+    }
+
+}
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/AddTimeDurationDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/AddTimeDurationDescriptor.java
new file mode 100644
index 0000000..e6b6ebd
--- /dev/null
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/AddTimeDurationDescriptor.java
@@ -0,0 +1,154 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.runtime.evaluators.functions.temporal;
+
+import java.io.DataOutput;
+
+import edu.uci.ics.asterix.common.functions.FunctionConstants;
+import edu.uci.ics.asterix.dataflow.data.nontagged.serde.ADurationSerializerDeserializer;
+import edu.uci.ics.asterix.dataflow.data.nontagged.serde.ATimeSerializerDeserializer;
+import edu.uci.ics.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
+import edu.uci.ics.asterix.om.base.AMutableTime;
+import edu.uci.ics.asterix.om.base.ANull;
+import edu.uci.ics.asterix.om.base.ATime;
+import edu.uci.ics.asterix.om.base.temporal.DurationArithmeticOperations;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
+import edu.uci.ics.asterix.om.types.ATypeTag;
+import edu.uci.ics.asterix.om.types.BuiltinType;
+import edu.uci.ics.asterix.runtime.evaluators.base.AbstractScalarFunctionDynamicDescriptor;
+import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
+import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluator;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory;
+import edu.uci.ics.hyracks.api.dataflow.value.ISerializerDeserializer;
+import edu.uci.ics.hyracks.api.exceptions.HyracksDataException;
+import edu.uci.ics.hyracks.data.std.api.IDataOutputProvider;
+import edu.uci.ics.hyracks.data.std.util.ArrayBackedValueStorage;
+import edu.uci.ics.hyracks.dataflow.common.data.accessors.IFrameTupleReference;
+
+public class AddTimeDurationDescriptor extends AbstractScalarFunctionDynamicDescriptor {
+
+    private final static long serialVersionUID = 1L;
+    public final static FunctionIdentifier FID = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "add-time-duration", 2);
+
+    // allowed input types
+    private final static byte SER_NULL_TYPE_TAG = ATypeTag.NULL.serialize();
+    private final static byte SER_TIME_TYPE_TAG = ATypeTag.TIME.serialize();
+    private final static byte SER_DURATION_TYPE_TAG = ATypeTag.DURATION.serialize();
+
+    public final static IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
+
+        @Override
+        public IFunctionDescriptor createFunctionDescriptor() {
+            return new AddTimeDurationDescriptor();
+        }
+    };
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.runtime.base.IScalarFunctionDynamicDescriptor#createEvaluatorFactory(edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory[])
+     */
+    @Override
+    public ICopyEvaluatorFactory createEvaluatorFactory(final ICopyEvaluatorFactory[] args) throws AlgebricksException {
+        return new ICopyEvaluatorFactory() {
+
+            private static final long serialVersionUID = 1L;
+
+            @Override
+            public ICopyEvaluator createEvaluator(final IDataOutputProvider output) throws AlgebricksException {
+                return new ICopyEvaluator() {
+
+                    private DataOutput out = output.getDataOutput();
+                    private ArrayBackedValueStorage argOut0 = new ArrayBackedValueStorage();
+                    private ArrayBackedValueStorage argOut1 = new ArrayBackedValueStorage();
+                    private ICopyEvaluator eval0 = args[0].createEvaluator(argOut0);
+                    private ICopyEvaluator eval1 = args[1].createEvaluator(argOut1);
+
+                    // possible output types
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<ANull> nullSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.ANULL);
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<ATime> timeSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.ATIME);
+
+                    private AMutableTime aTime = new AMutableTime(0);
+
+                    @Override
+                    public void evaluate(IFrameTupleReference tuple) throws AlgebricksException {
+                        argOut0.reset();
+                        eval0.evaluate(tuple);
+                        argOut1.reset();
+                        eval1.evaluate(tuple);
+
+                        try {
+                            if (argOut0.getByteArray()[0] == SER_NULL_TYPE_TAG
+                                    || argOut1.getByteArray()[0] == SER_NULL_TYPE_TAG) {
+                                nullSerde.serialize(ANull.NULL, out);
+                                return;
+                            }
+
+                            if (argOut0.getByteArray()[0] != SER_TIME_TYPE_TAG) {
+                                throw new AlgebricksException(
+                                        "Inapplicable input type for parameter 0: expecting a Time ("
+                                                + SER_TIME_TYPE_TAG + ") or null (" + SER_NULL_TYPE_TAG
+                                                + "), but got: " + argOut0.getByteArray()[0]);
+                            }
+
+                            if (argOut1.getByteArray()[0] != SER_DURATION_TYPE_TAG) {
+                                throw new AlgebricksException(
+                                        "Inapplicable input type for parameter 1: expecting a Duration ("
+                                                + SER_DURATION_TYPE_TAG + ") or null (" + SER_DURATION_TYPE_TAG
+                                                + "), but got: " + argOut1.getByteArray()[0]);
+                            }
+
+                            // get duration fields: yearMonth field and dayTime field
+                            int yearMonth = ADurationSerializerDeserializer.getYearMonth(argOut1.getByteArray(), 1);
+
+                            // cannot add a year-month duration to a time value
+                            if (yearMonth != 0) {
+                                throw new AlgebricksException("ATime cannot be added by a year-month duration.");
+                            }
+
+                            long dayTime = ADurationSerializerDeserializer.getDayTime(argOut1.getByteArray(), 1);
+
+                            // get time fields
+                            int timeChronon = ATimeSerializerDeserializer.getChronon(argOut0.getByteArray(), 1);
+
+                            timeChronon = DurationArithmeticOperations.addDuration(timeChronon, dayTime);
+
+                            aTime.setValue(timeChronon);
+
+                            timeSerde.serialize(aTime, out);
+
+                        } catch (HyracksDataException hex) {
+                            throw new AlgebricksException(hex);
+                        }
+                    }
+                };
+            }
+        };
+    }
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.om.functions.IFunctionDescriptor#getIdentifier()
+     */
+    @Override
+    public FunctionIdentifier getIdentifier() {
+        return FID;
+    }
+
+}
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/AdjustDateTimeForTimeZoneDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/AdjustDateTimeForTimeZoneDescriptor.java
new file mode 100644
index 0000000..fb01e97
--- /dev/null
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/AdjustDateTimeForTimeZoneDescriptor.java
@@ -0,0 +1,154 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.runtime.evaluators.functions.temporal;
+
+import java.io.DataOutput;
+
+import edu.uci.ics.asterix.common.functions.FunctionConstants;
+import edu.uci.ics.asterix.dataflow.data.nontagged.serde.ADateTimeSerializerDeserializer;
+import edu.uci.ics.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
+import edu.uci.ics.asterix.om.base.ANull;
+import edu.uci.ics.asterix.om.base.temporal.ATimeParserFactory;
+import edu.uci.ics.asterix.om.base.temporal.ByteArrayCharSequenceAccessor;
+import edu.uci.ics.asterix.om.base.temporal.GregorianCalendarSystem;
+import edu.uci.ics.asterix.om.base.temporal.GregorianCalendarSystem.Fields;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
+import edu.uci.ics.asterix.om.types.ATypeTag;
+import edu.uci.ics.asterix.om.types.BuiltinType;
+import edu.uci.ics.asterix.runtime.evaluators.base.AbstractScalarFunctionDynamicDescriptor;
+import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
+import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluator;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory;
+import edu.uci.ics.hyracks.api.dataflow.value.ISerializerDeserializer;
+import edu.uci.ics.hyracks.data.std.api.IDataOutputProvider;
+import edu.uci.ics.hyracks.data.std.util.ArrayBackedValueStorage;
+import edu.uci.ics.hyracks.dataflow.common.data.accessors.IFrameTupleReference;
+
+public class AdjustDateTimeForTimeZoneDescriptor extends AbstractScalarFunctionDynamicDescriptor {
+
+    private final static long serialVersionUID = 1L;
+    public final static FunctionIdentifier FID = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "adjust-datetime-for-timezone", 2);
+
+    // allowed input types
+    private final static byte SER_NULL_TYPE_TAG = ATypeTag.NULL.serialize();
+    private final static byte SER_DATETIME_TYPE_TAG = ATypeTag.DATETIME.serialize();
+    private final static byte SER_STRING_TYPE_TAG = ATypeTag.STRING.serialize();
+
+    public final static IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
+
+        @Override
+        public IFunctionDescriptor createFunctionDescriptor() {
+            return new AdjustDateTimeForTimeZoneDescriptor();
+        }
+    };
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.runtime.base.IScalarFunctionDynamicDescriptor#createEvaluatorFactory(edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory[])
+     */
+    @Override
+    public ICopyEvaluatorFactory createEvaluatorFactory(final ICopyEvaluatorFactory[] args) throws AlgebricksException {
+        return new ICopyEvaluatorFactory() {
+
+            private static final long serialVersionUID = 1L;
+
+            @Override
+            public ICopyEvaluator createEvaluator(final IDataOutputProvider output) throws AlgebricksException {
+                return new ICopyEvaluator() {
+
+                    private DataOutput out = output.getDataOutput();
+                    private ArrayBackedValueStorage argOut0 = new ArrayBackedValueStorage();
+                    private ArrayBackedValueStorage argOut1 = new ArrayBackedValueStorage();
+                    private ICopyEvaluator eval0 = args[0].createEvaluator(argOut0);
+                    private ICopyEvaluator eval1 = args[1].createEvaluator(argOut1);
+
+                    // possible output types
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<ANull> nullSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.ANULL);
+
+                    private ByteArrayCharSequenceAccessor charAccessor = new ByteArrayCharSequenceAccessor();
+
+                    private GregorianCalendarSystem calInstance = GregorianCalendarSystem.getInstance();
+
+                    @Override
+                    public void evaluate(IFrameTupleReference tuple) throws AlgebricksException {
+                        argOut0.reset();
+                        eval0.evaluate(tuple);
+                        argOut1.reset();
+                        eval1.evaluate(tuple);
+
+                        try {
+                            if (argOut0.getByteArray()[0] == SER_NULL_TYPE_TAG
+                                    || argOut1.getByteArray()[0] == SER_NULL_TYPE_TAG) {
+                                nullSerde.serialize(ANull.NULL, out);
+                                return;
+                            }
+
+                            if (argOut0.getByteArray()[0] != SER_DATETIME_TYPE_TAG) {
+                                throw new AlgebricksException(
+                                        "Inapplicable input type for parameter 0: expecting a Datetime, but got: "
+                                                + argOut0.getByteArray()[0]);
+                            }
+
+                            if (argOut1.getByteArray()[0] != SER_STRING_TYPE_TAG) {
+                                throw new AlgebricksException(
+                                        "Inapplicable input type for parameter 0: expecting a String, but got: "
+                                                + argOut1.getByteArray()[0]);
+                            }
+
+                            int stringLength = (argOut1.getByteArray()[1] & 0xff << 8)
+                                    + (argOut1.getByteArray()[2] & 0xff << 0);
+
+                            charAccessor.reset(argOut1.getByteArray(), 3, stringLength);
+
+                            int timezone = ATimeParserFactory.parseTimezonePart(charAccessor, 0);
+
+                            if (!calInstance.validateTimeZone(timezone)) {
+                                throw new AlgebricksException("Wrong format for a time zone string!");
+                            }
+
+                            long chronon = ADateTimeSerializerDeserializer.getChronon(argOut0.getByteArray(), 1);
+
+                            chronon = calInstance.adjustChrononByTimezone(chronon, timezone);
+
+                            StringBuilder sbder = new StringBuilder();
+
+                            calInstance.getExtendStringRepWithTimezoneUntilField(chronon, timezone, sbder, Fields.YEAR,
+                                    Fields.MILLISECOND);
+
+                            out.writeByte(SER_STRING_TYPE_TAG);
+                            out.writeUTF(sbder.toString());
+
+                        } catch (Exception e1) {
+                            throw new AlgebricksException(e1);
+                        }
+                    }
+                };
+            }
+        };
+    }
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.om.functions.IFunctionDescriptor#getIdentifier()
+     */
+    @Override
+    public FunctionIdentifier getIdentifier() {
+        return FID;
+    }
+
+}
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/AdjustTimeForTimeZoneDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/AdjustTimeForTimeZoneDescriptor.java
new file mode 100644
index 0000000..1323664
--- /dev/null
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/AdjustTimeForTimeZoneDescriptor.java
@@ -0,0 +1,154 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.runtime.evaluators.functions.temporal;
+
+import java.io.DataOutput;
+
+import edu.uci.ics.asterix.common.functions.FunctionConstants;
+import edu.uci.ics.asterix.dataflow.data.nontagged.serde.ATimeSerializerDeserializer;
+import edu.uci.ics.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
+import edu.uci.ics.asterix.om.base.ANull;
+import edu.uci.ics.asterix.om.base.temporal.ATimeParserFactory;
+import edu.uci.ics.asterix.om.base.temporal.ByteArrayCharSequenceAccessor;
+import edu.uci.ics.asterix.om.base.temporal.GregorianCalendarSystem;
+import edu.uci.ics.asterix.om.base.temporal.GregorianCalendarSystem.Fields;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
+import edu.uci.ics.asterix.om.types.ATypeTag;
+import edu.uci.ics.asterix.om.types.BuiltinType;
+import edu.uci.ics.asterix.runtime.evaluators.base.AbstractScalarFunctionDynamicDescriptor;
+import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
+import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluator;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory;
+import edu.uci.ics.hyracks.api.dataflow.value.ISerializerDeserializer;
+import edu.uci.ics.hyracks.data.std.api.IDataOutputProvider;
+import edu.uci.ics.hyracks.data.std.util.ArrayBackedValueStorage;
+import edu.uci.ics.hyracks.dataflow.common.data.accessors.IFrameTupleReference;
+
+public class AdjustTimeForTimeZoneDescriptor extends AbstractScalarFunctionDynamicDescriptor {
+
+    private final static long serialVersionUID = 1L;
+    public final static FunctionIdentifier FID = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "adjust-time-for-timezone", 2);
+
+    // allowed input types
+    private final static byte SER_NULL_TYPE_TAG = ATypeTag.NULL.serialize();
+    private final static byte SER_TIME_TYPE_TAG = ATypeTag.TIME.serialize();
+    private final static byte SER_STRING_TYPE_TAG = ATypeTag.STRING.serialize();
+
+    public final static IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
+
+        @Override
+        public IFunctionDescriptor createFunctionDescriptor() {
+            return new AdjustTimeForTimeZoneDescriptor();
+        }
+    };
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.runtime.base.IScalarFunctionDynamicDescriptor#createEvaluatorFactory(edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory[])
+     */
+    @Override
+    public ICopyEvaluatorFactory createEvaluatorFactory(final ICopyEvaluatorFactory[] args) throws AlgebricksException {
+        return new ICopyEvaluatorFactory() {
+
+            private static final long serialVersionUID = 1L;
+
+            @Override
+            public ICopyEvaluator createEvaluator(final IDataOutputProvider output) throws AlgebricksException {
+                return new ICopyEvaluator() {
+
+                    private DataOutput out = output.getDataOutput();
+                    private ArrayBackedValueStorage argOut0 = new ArrayBackedValueStorage();
+                    private ArrayBackedValueStorage argOut1 = new ArrayBackedValueStorage();
+                    private ICopyEvaluator eval0 = args[0].createEvaluator(argOut0);
+                    private ICopyEvaluator eval1 = args[1].createEvaluator(argOut1);
+
+                    // possible output types
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<ANull> nullSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.ANULL);
+
+                    private ByteArrayCharSequenceAccessor charAccessor = new ByteArrayCharSequenceAccessor();
+
+                    private GregorianCalendarSystem calInstance = GregorianCalendarSystem.getInstance();
+
+                    @Override
+                    public void evaluate(IFrameTupleReference tuple) throws AlgebricksException {
+                        argOut0.reset();
+                        eval0.evaluate(tuple);
+                        argOut1.reset();
+                        eval1.evaluate(tuple);
+
+                        try {
+                            if (argOut0.getByteArray()[0] == SER_NULL_TYPE_TAG
+                                    || argOut1.getByteArray()[0] == SER_NULL_TYPE_TAG) {
+                                nullSerde.serialize(ANull.NULL, out);
+                                return;
+                            }
+
+                            if (argOut0.getByteArray()[0] != SER_TIME_TYPE_TAG) {
+                                throw new AlgebricksException(
+                                        "Inapplicable input type for parameter 0: expecting a Time, but got: "
+                                                + argOut0.getByteArray()[0]);
+                            }
+
+                            if (argOut1.getByteArray()[0] != SER_STRING_TYPE_TAG) {
+                                throw new AlgebricksException(
+                                        "Inapplicable input type for parameter 0: expecting a String, but got: "
+                                                + argOut1.getByteArray()[0]);
+                            }
+
+                            int stringLength = (argOut0.getByteArray()[1] & 0xff << 8)
+                                    + (argOut0.getByteArray()[2] & 0xff << 0);
+
+                            charAccessor.reset(argOut1.getByteArray(), 3, stringLength);
+
+                            int timezone = ATimeParserFactory.parseTimezonePart(charAccessor, 0);
+
+                            if (!calInstance.validateTimeZone(timezone)) {
+                                throw new AlgebricksException("Wrong format for a time zone string!");
+                            }
+
+                            int chronon = ATimeSerializerDeserializer.getChronon(argOut0.getByteArray(), 1);
+
+                            chronon = (int) calInstance.adjustChrononByTimezone(chronon, timezone);
+
+                            StringBuilder sbder = new StringBuilder();
+
+                            calInstance.getExtendStringRepWithTimezoneUntilField(chronon, timezone, sbder, Fields.HOUR,
+                                    Fields.MILLISECOND);
+
+                            out.writeByte(SER_STRING_TYPE_TAG);
+                            out.writeUTF(sbder.toString());
+
+                        } catch (Exception e1) {
+                            throw new AlgebricksException(e1);
+                        }
+                    }
+                };
+            }
+        };
+    }
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.om.functions.IFunctionDescriptor#getIdentifier()
+     */
+    @Override
+    public FunctionIdentifier getIdentifier() {
+        return FID;
+    }
+
+}
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/CalendarDuartionFromDateDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/CalendarDuartionFromDateDescriptor.java
new file mode 100644
index 0000000..c6be030
--- /dev/null
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/CalendarDuartionFromDateDescriptor.java
@@ -0,0 +1,235 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.runtime.evaluators.functions.temporal;
+
+import java.io.DataOutput;
+
+import edu.uci.ics.asterix.common.functions.FunctionConstants;
+import edu.uci.ics.asterix.dataflow.data.nontagged.serde.ADateSerializerDeserializer;
+import edu.uci.ics.asterix.dataflow.data.nontagged.serde.ADurationSerializerDeserializer;
+import edu.uci.ics.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
+import edu.uci.ics.asterix.om.base.ADuration;
+import edu.uci.ics.asterix.om.base.AMutableDuration;
+import edu.uci.ics.asterix.om.base.ANull;
+import edu.uci.ics.asterix.om.base.temporal.DurationArithmeticOperations;
+import edu.uci.ics.asterix.om.base.temporal.GregorianCalendarSystem;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
+import edu.uci.ics.asterix.om.types.ATypeTag;
+import edu.uci.ics.asterix.om.types.BuiltinType;
+import edu.uci.ics.asterix.runtime.evaluators.base.AbstractScalarFunctionDynamicDescriptor;
+import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
+import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluator;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory;
+import edu.uci.ics.hyracks.api.dataflow.value.ISerializerDeserializer;
+import edu.uci.ics.hyracks.api.exceptions.HyracksDataException;
+import edu.uci.ics.hyracks.data.std.api.IDataOutputProvider;
+import edu.uci.ics.hyracks.data.std.util.ArrayBackedValueStorage;
+import edu.uci.ics.hyracks.dataflow.common.data.accessors.IFrameTupleReference;
+
+public class CalendarDuartionFromDateDescriptor extends AbstractScalarFunctionDynamicDescriptor {
+
+    private final static long serialVersionUID = 1L;
+    public final static FunctionIdentifier FID = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "calendar-duration-from-date", 2);
+
+    // allowed input types
+    private final static byte SER_NULL_TYPE_TAG = ATypeTag.NULL.serialize();
+    private final static byte SER_DATE_TYPE_TAG = ATypeTag.DATE.serialize();
+    private final static byte SER_DURATION_TYPE_TAG = ATypeTag.DURATION.serialize();
+
+    public final static IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
+
+        @Override
+        public IFunctionDescriptor createFunctionDescriptor() {
+            return new CalendarDuartionFromDateDescriptor();
+        }
+    };
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.runtime.base.IScalarFunctionDynamicDescriptor#createEvaluatorFactory(edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory[])
+     */
+    @Override
+    public ICopyEvaluatorFactory createEvaluatorFactory(final ICopyEvaluatorFactory[] args) throws AlgebricksException {
+        return new ICopyEvaluatorFactory() {
+
+            private static final long serialVersionUID = 1L;
+
+            @Override
+            public ICopyEvaluator createEvaluator(final IDataOutputProvider output) throws AlgebricksException {
+
+                return new ICopyEvaluator() {
+
+                    private DataOutput out = output.getDataOutput();
+                    private ArrayBackedValueStorage argOut0 = new ArrayBackedValueStorage();
+                    private ArrayBackedValueStorage argOut1 = new ArrayBackedValueStorage();
+                    private ICopyEvaluator eval0 = args[0].createEvaluator(argOut0);
+                    private ICopyEvaluator eval1 = args[1].createEvaluator(argOut1);
+
+                    // possible output types
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<ANull> nullSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.ANULL);
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<ADuration> durationSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.ADURATION);
+
+                    private AMutableDuration aDuration = new AMutableDuration(0, 0);
+
+                    private GregorianCalendarSystem calInstanct = GregorianCalendarSystem.getInstance();
+
+                    @Override
+                    public void evaluate(IFrameTupleReference tuple) throws AlgebricksException {
+
+                        argOut0.reset();
+                        eval0.evaluate(tuple);
+                        argOut1.reset();
+                        eval1.evaluate(tuple);
+
+                        try {
+                            if (argOut0.getByteArray()[0] == SER_NULL_TYPE_TAG
+                                    || argOut1.getByteArray()[0] == SER_NULL_TYPE_TAG) {
+                                nullSerde.serialize(ANull.NULL, out);
+                                return;
+                            }
+
+                            if (argOut0.getByteArray()[0] != SER_DATE_TYPE_TAG) {
+                                throw new AlgebricksException(
+                                        "Inapplicable input type for parameter 0: expecting a Date, but got: "
+                                                + argOut0.getByteArray()[0]);
+                            }
+
+                            if (argOut1.getByteArray()[0] != SER_DURATION_TYPE_TAG) {
+                                throw new AlgebricksException(
+                                        "Inapplicable input type for parameter 1: expecting a Date, but got: "
+                                                + argOut1.getByteArray()[0]);
+                            }
+
+                            int yearMonthDurationInMonths = ADurationSerializerDeserializer.getYearMonth(
+                                    argOut1.getByteArray(), 1);
+                            long dayTimeDurationInMs = ADurationSerializerDeserializer.getDayTime(
+                                    argOut1.getByteArray(), 1);
+
+                            long startingTimePoint = ADateSerializerDeserializer.getChronon(argOut0.getByteArray(), 1)
+                                    * GregorianCalendarSystem.CHRONON_OF_DAY;
+
+                            long endingTimePoint = DurationArithmeticOperations.addDuration(startingTimePoint,
+                                    yearMonthDurationInMonths, dayTimeDurationInMs);
+
+                            if (startingTimePoint == endingTimePoint) {
+                                aDuration.setValue(0, 0);
+                            } else {
+
+                                boolean negative = false;
+
+                                if (endingTimePoint < startingTimePoint) {
+                                    negative = true;
+                                    // swap the starting and ending time, so that ending time is always larger than the starting time.
+                                    long tmpTime = endingTimePoint;
+                                    endingTimePoint = startingTimePoint;
+                                    startingTimePoint = tmpTime;
+                                }
+
+                                int year0 = calInstanct.getYear(startingTimePoint);
+                                int month0 = calInstanct.getMonthOfYear(startingTimePoint, year0);
+
+                                int year1 = calInstanct.getYear(endingTimePoint);
+                                int month1 = calInstanct.getMonthOfYear(endingTimePoint, year1);
+
+                                int year = year1 - year0;
+                                int month = month1 - month0;
+                                int day = calInstanct.getDayOfMonthYear(endingTimePoint, year1, month1)
+                                        - calInstanct.getDayOfMonthYear(startingTimePoint, year0, month0);
+                                int hour = calInstanct.getHourOfDay(endingTimePoint)
+                                        - calInstanct.getHourOfDay(startingTimePoint);
+                                int min = calInstanct.getMinOfHour(endingTimePoint)
+                                        - calInstanct.getMinOfHour(startingTimePoint);
+                                int sec = calInstanct.getSecOfMin(endingTimePoint)
+                                        - calInstanct.getSecOfMin(startingTimePoint);
+                                int ms = calInstanct.getMillisOfSec(endingTimePoint)
+                                        - calInstanct.getMillisOfSec(startingTimePoint);
+
+                                if (ms < 0) {
+                                    ms += GregorianCalendarSystem.CHRONON_OF_SECOND;
+                                    sec -= 1;
+                                }
+
+                                if (sec < 0) {
+                                    sec += GregorianCalendarSystem.CHRONON_OF_MINUTE
+                                            / GregorianCalendarSystem.CHRONON_OF_SECOND;
+                                    min -= 1;
+                                }
+
+                                if (min < 0) {
+                                    min += GregorianCalendarSystem.CHRONON_OF_HOUR
+                                            / GregorianCalendarSystem.CHRONON_OF_MINUTE;
+                                    hour -= 1;
+                                }
+
+                                if (hour < 0) {
+                                    hour += GregorianCalendarSystem.CHRONON_OF_DAY
+                                            / GregorianCalendarSystem.CHRONON_OF_HOUR;
+                                    day -= 1;
+                                }
+
+                                if (day < 0) {
+                                    boolean isLeapYear = calInstanct.isLeapYear(year0);
+                                    day += (isLeapYear) ? (GregorianCalendarSystem.DAYS_OF_MONTH_LEAP[month0 - 1])
+                                            : (GregorianCalendarSystem.DAYS_OF_MONTH_ORDI[month0 - 1]);
+                                    month -= 1;
+                                }
+
+                                if (month < 0) {
+                                    month += GregorianCalendarSystem.MONTHS_IN_A_YEAR;
+                                    year -= 1;
+                                }
+
+                                if (negative) {
+                                    aDuration.setValue(-1 * (year * GregorianCalendarSystem.MONTHS_IN_A_YEAR + month),
+                                            -1
+                                                    * (day * GregorianCalendarSystem.CHRONON_OF_DAY + hour
+                                                            * GregorianCalendarSystem.CHRONON_OF_HOUR + min
+                                                            * GregorianCalendarSystem.CHRONON_OF_MINUTE + sec
+                                                            * GregorianCalendarSystem.CHRONON_OF_SECOND + ms));
+                                } else {
+                                    aDuration.setValue(year * GregorianCalendarSystem.MONTHS_IN_A_YEAR + month, day
+                                            * GregorianCalendarSystem.CHRONON_OF_DAY + hour
+                                            * GregorianCalendarSystem.CHRONON_OF_HOUR + min
+                                            * GregorianCalendarSystem.CHRONON_OF_MINUTE + sec
+                                            * GregorianCalendarSystem.CHRONON_OF_SECOND + ms);
+                                }
+                            }
+
+                            durationSerde.serialize(aDuration, out);
+
+                        } catch (HyracksDataException hex) {
+                            throw new AlgebricksException(hex);
+                        }
+                    }
+                };
+            }
+        };
+    }
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.om.functions.IFunctionDescriptor#getIdentifier()
+     */
+    @Override
+    public FunctionIdentifier getIdentifier() {
+        return FID;
+    }
+
+}
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/CalendarDurationFromDateTimeDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/CalendarDurationFromDateTimeDescriptor.java
new file mode 100644
index 0000000..2c7a9a7
--- /dev/null
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/CalendarDurationFromDateTimeDescriptor.java
@@ -0,0 +1,251 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.runtime.evaluators.functions.temporal;
+
+import java.io.DataOutput;
+
+import edu.uci.ics.asterix.common.functions.FunctionConstants;
+import edu.uci.ics.asterix.dataflow.data.nontagged.serde.ADateTimeSerializerDeserializer;
+import edu.uci.ics.asterix.dataflow.data.nontagged.serde.ADurationSerializerDeserializer;
+import edu.uci.ics.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
+import edu.uci.ics.asterix.om.base.ADuration;
+import edu.uci.ics.asterix.om.base.AMutableDuration;
+import edu.uci.ics.asterix.om.base.ANull;
+import edu.uci.ics.asterix.om.base.temporal.DurationArithmeticOperations;
+import edu.uci.ics.asterix.om.base.temporal.GregorianCalendarSystem;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
+import edu.uci.ics.asterix.om.types.ATypeTag;
+import edu.uci.ics.asterix.om.types.BuiltinType;
+import edu.uci.ics.asterix.runtime.evaluators.base.AbstractScalarFunctionDynamicDescriptor;
+import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
+import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluator;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory;
+import edu.uci.ics.hyracks.api.dataflow.value.ISerializerDeserializer;
+import edu.uci.ics.hyracks.api.exceptions.HyracksDataException;
+import edu.uci.ics.hyracks.data.std.api.IDataOutputProvider;
+import edu.uci.ics.hyracks.data.std.util.ArrayBackedValueStorage;
+import edu.uci.ics.hyracks.dataflow.common.data.accessors.IFrameTupleReference;
+
+/**
+ * This function converts a given duration into a "human-readable" duration containing both year-month and day-time
+ * duration parts, by re-organizing values between the duration fields from the given reference time point.
+ * <p/>
+ * The basic algorithm for this convert is simple: <br/>
+ * 1. Calculate the time point by adding the given duration to the given time point;<br/>
+ * 2. Calculate the differences by fields between two different time points;<br/>
+ * 3. Re-format the duration into a human-readable one.
+ * <p/>
+ * Here "human-readable" means the value of each field of the duration is within the value range of the field in the
+ * calendar system. For example, month would be in [0, 12), and hour would be in [0, 24).
+ * <p/>
+ * The result can be considered as a "field-based" difference between the two datetime value, but all negative values
+ * would be converted to be non-negative.
+ * <p/>
+ * In the implementation, we always do the subtraction from the later time point, resulting a positive duration always.
+ * <p/>
+ */
+public class CalendarDurationFromDateTimeDescriptor extends AbstractScalarFunctionDynamicDescriptor {
+
+    private final static long serialVersionUID = 1L;
+    public final static FunctionIdentifier FID = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "calendar-duration-from-datetime", 2);
+
+    // allowed input types
+    private final static byte SER_NULL_TYPE_TAG = ATypeTag.NULL.serialize();
+    private final static byte SER_DATETIME_TYPE_TAG = ATypeTag.DATETIME.serialize();
+    private final static byte SER_DURATION_TYPE_TAG = ATypeTag.DURATION.serialize();
+
+    public final static IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
+
+        @Override
+        public IFunctionDescriptor createFunctionDescriptor() {
+            return new CalendarDurationFromDateTimeDescriptor();
+        }
+    };
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.runtime.base.IScalarFunctionDynamicDescriptor#createEvaluatorFactory(edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory[])
+     */
+    @Override
+    public ICopyEvaluatorFactory createEvaluatorFactory(final ICopyEvaluatorFactory[] args) throws AlgebricksException {
+        return new ICopyEvaluatorFactory() {
+
+            private static final long serialVersionUID = 1L;
+
+            @Override
+            public ICopyEvaluator createEvaluator(final IDataOutputProvider output) throws AlgebricksException {
+                return new ICopyEvaluator() {
+
+                    private DataOutput out = output.getDataOutput();
+                    private ArrayBackedValueStorage argOut0 = new ArrayBackedValueStorage();
+                    private ArrayBackedValueStorage argOut1 = new ArrayBackedValueStorage();
+                    private ICopyEvaluator eval0 = args[0].createEvaluator(argOut0);
+                    private ICopyEvaluator eval1 = args[1].createEvaluator(argOut1);
+
+                    // possible output types
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<ANull> nullSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.ANULL);
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<ADuration> durationSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.ADURATION);
+
+                    private AMutableDuration aDuration = new AMutableDuration(0, 0);
+
+                    private GregorianCalendarSystem calInstanct = GregorianCalendarSystem.getInstance();
+
+                    @Override
+                    public void evaluate(IFrameTupleReference tuple) throws AlgebricksException {
+                        argOut0.reset();
+                        eval0.evaluate(tuple);
+                        argOut1.reset();
+                        eval1.evaluate(tuple);
+
+                        try {
+                            if (argOut0.getByteArray()[0] == SER_NULL_TYPE_TAG
+                                    || argOut1.getByteArray()[0] == SER_NULL_TYPE_TAG) {
+                                nullSerde.serialize(ANull.NULL, out);
+                                return;
+                            }
+
+                            if (argOut0.getByteArray()[0] != SER_DATETIME_TYPE_TAG) {
+                                throw new AlgebricksException(
+                                        "Inapplicable input type for parameter 0: expecting ADateTime, but got: "
+                                                + argOut0.getByteArray()[0]);
+                            }
+
+                            if (argOut1.getByteArray()[0] != SER_DURATION_TYPE_TAG) {
+                                throw new AlgebricksException(
+                                        "Inapplicable input type for parameter 1: expecting ADateTime, but got: "
+                                                + argOut1.getByteArray()[0]);
+                            }
+
+                            int yearMonthDurationInMonths = ADurationSerializerDeserializer.getYearMonth(
+                                    argOut1.getByteArray(), 1);
+                            long dayTimeDurationInMs = ADurationSerializerDeserializer.getDayTime(
+                                    argOut1.getByteArray(), 1);
+
+                            long startingTimePoint = ADateTimeSerializerDeserializer.getChronon(argOut0.getByteArray(),
+                                    1);
+
+                            long endingTimePoint = DurationArithmeticOperations.addDuration(startingTimePoint,
+                                    yearMonthDurationInMonths, dayTimeDurationInMs);
+
+                            if (startingTimePoint == endingTimePoint) {
+                                aDuration.setValue(0, 0);
+                            } else {
+
+                                boolean negative = false;
+
+                                if (endingTimePoint < startingTimePoint) {
+                                    negative = true;
+                                    // swap the starting and ending time, so that ending time is always larger than the starting time.
+                                    long tmpTime = endingTimePoint;
+                                    endingTimePoint = startingTimePoint;
+                                    startingTimePoint = tmpTime;
+                                }
+
+                                int year0 = calInstanct.getYear(startingTimePoint);
+                                int month0 = calInstanct.getMonthOfYear(startingTimePoint, year0);
+
+                                int year1 = calInstanct.getYear(endingTimePoint);
+                                int month1 = calInstanct.getMonthOfYear(endingTimePoint, year1);
+
+                                int year = year1 - year0;
+                                int month = month1 - month0;
+                                int day = calInstanct.getDayOfMonthYear(endingTimePoint, year1, month1)
+                                        - calInstanct.getDayOfMonthYear(startingTimePoint, year0, month0);
+                                int hour = calInstanct.getHourOfDay(endingTimePoint)
+                                        - calInstanct.getHourOfDay(startingTimePoint);
+                                int min = calInstanct.getMinOfHour(endingTimePoint)
+                                        - calInstanct.getMinOfHour(startingTimePoint);
+                                int sec = calInstanct.getSecOfMin(endingTimePoint)
+                                        - calInstanct.getSecOfMin(startingTimePoint);
+                                int ms = calInstanct.getMillisOfSec(endingTimePoint)
+                                        - calInstanct.getMillisOfSec(startingTimePoint);
+
+                                if (ms < 0) {
+                                    ms += GregorianCalendarSystem.CHRONON_OF_SECOND;
+                                    sec -= 1;
+                                }
+
+                                if (sec < 0) {
+                                    sec += GregorianCalendarSystem.CHRONON_OF_MINUTE
+                                            / GregorianCalendarSystem.CHRONON_OF_SECOND;
+                                    min -= 1;
+                                }
+
+                                if (min < 0) {
+                                    min += GregorianCalendarSystem.CHRONON_OF_HOUR
+                                            / GregorianCalendarSystem.CHRONON_OF_MINUTE;
+                                    hour -= 1;
+                                }
+
+                                if (hour < 0) {
+                                    hour += GregorianCalendarSystem.CHRONON_OF_DAY
+                                            / GregorianCalendarSystem.CHRONON_OF_HOUR;
+                                    day -= 1;
+                                }
+
+                                if (day < 0) {
+                                    boolean isLeapYear = calInstanct.isLeapYear(year0);
+                                    day += (isLeapYear) ? (GregorianCalendarSystem.DAYS_OF_MONTH_LEAP[month0 - 1])
+                                            : (GregorianCalendarSystem.DAYS_OF_MONTH_ORDI[month0 - 1]);
+                                    month -= 1;
+                                }
+
+                                if (month < 0) {
+                                    month += GregorianCalendarSystem.MONTHS_IN_A_YEAR;
+                                    year -= 1;
+                                }
+
+                                if (negative) {
+                                    aDuration.setValue(-1 * (year * GregorianCalendarSystem.MONTHS_IN_A_YEAR + month),
+                                            -1
+                                                    * (day * GregorianCalendarSystem.CHRONON_OF_DAY + hour
+                                                            * GregorianCalendarSystem.CHRONON_OF_HOUR + min
+                                                            * GregorianCalendarSystem.CHRONON_OF_MINUTE + sec
+                                                            * GregorianCalendarSystem.CHRONON_OF_SECOND + ms));
+                                } else {
+                                    aDuration.setValue(year * GregorianCalendarSystem.MONTHS_IN_A_YEAR + month, day
+                                            * GregorianCalendarSystem.CHRONON_OF_DAY + hour
+                                            * GregorianCalendarSystem.CHRONON_OF_HOUR + min
+                                            * GregorianCalendarSystem.CHRONON_OF_MINUTE + sec
+                                            * GregorianCalendarSystem.CHRONON_OF_SECOND + ms);
+                                }
+                            }
+
+                            durationSerde.serialize(aDuration, out);
+
+                        } catch (HyracksDataException hex) {
+                            throw new AlgebricksException(hex);
+                        }
+                    }
+                };
+            }
+        };
+    }
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.om.functions.IFunctionDescriptor#getIdentifier()
+     */
+    @Override
+    public FunctionIdentifier getIdentifier() {
+        return FID;
+    }
+
+}
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/CurrentDateDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/CurrentDateDescriptor.java
new file mode 100644
index 0000000..0cb47b5
--- /dev/null
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/CurrentDateDescriptor.java
@@ -0,0 +1,88 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.runtime.evaluators.functions.temporal;
+
+import java.io.DataOutput;
+
+import edu.uci.ics.asterix.common.functions.FunctionConstants;
+import edu.uci.ics.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
+import edu.uci.ics.asterix.om.base.ADate;
+import edu.uci.ics.asterix.om.base.AMutableDate;
+import edu.uci.ics.asterix.om.base.temporal.GregorianCalendarSystem;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
+import edu.uci.ics.asterix.om.types.BuiltinType;
+import edu.uci.ics.asterix.runtime.evaluators.base.AbstractScalarFunctionDynamicDescriptor;
+import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
+import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluator;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory;
+import edu.uci.ics.hyracks.api.dataflow.value.ISerializerDeserializer;
+import edu.uci.ics.hyracks.api.exceptions.HyracksDataException;
+import edu.uci.ics.hyracks.data.std.api.IDataOutputProvider;
+import edu.uci.ics.hyracks.dataflow.common.data.accessors.IFrameTupleReference;
+
+public class CurrentDateDescriptor extends AbstractScalarFunctionDynamicDescriptor {
+
+    private static final long serialVersionUID = 1L;
+    private final static FunctionIdentifier FID = new FunctionIdentifier(FunctionConstants.ASTERIX_NS, "current-date",
+            0);
+
+    public final static IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
+
+        @Override
+        public IFunctionDescriptor createFunctionDescriptor() {
+            return new CurrentDateDescriptor();
+        }
+    };
+
+    @Override
+    public ICopyEvaluatorFactory createEvaluatorFactory(ICopyEvaluatorFactory[] args) throws AlgebricksException {
+        return new ICopyEvaluatorFactory() {
+
+            private static final long serialVersionUID = 1L;
+
+            @Override
+            public ICopyEvaluator createEvaluator(final IDataOutputProvider output) throws AlgebricksException {
+                return new ICopyEvaluator() {
+
+                    private DataOutput out = output.getDataOutput();
+
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<ADate> dateSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.ADATE);
+                    private AMutableDate aDate = new AMutableDate(0);
+
+                    @Override
+                    public void evaluate(IFrameTupleReference tuple) throws AlgebricksException {
+                        try {
+                            int dateChronon = (int) (System.currentTimeMillis() / GregorianCalendarSystem.CHRONON_OF_DAY);
+                            aDate.setValue(dateChronon);
+                            dateSerde.serialize(aDate, out);
+                        } catch (HyracksDataException hex) {
+                            throw new AlgebricksException(hex);
+                        }
+                    }
+                };
+            }
+        };
+    }
+
+    @Override
+    public FunctionIdentifier getIdentifier() {
+        return FID;
+    }
+
+}
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/CurrentDateTimeDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/CurrentDateTimeDescriptor.java
new file mode 100644
index 0000000..9209cae
--- /dev/null
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/CurrentDateTimeDescriptor.java
@@ -0,0 +1,92 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.runtime.evaluators.functions.temporal;
+
+import java.io.DataOutput;
+
+import edu.uci.ics.asterix.common.functions.FunctionConstants;
+import edu.uci.ics.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
+import edu.uci.ics.asterix.om.base.ADateTime;
+import edu.uci.ics.asterix.om.base.AMutableDateTime;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
+import edu.uci.ics.asterix.om.types.BuiltinType;
+import edu.uci.ics.asterix.runtime.evaluators.base.AbstractScalarFunctionDynamicDescriptor;
+import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
+import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluator;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory;
+import edu.uci.ics.hyracks.api.dataflow.value.ISerializerDeserializer;
+import edu.uci.ics.hyracks.api.exceptions.HyracksDataException;
+import edu.uci.ics.hyracks.data.std.api.IDataOutputProvider;
+import edu.uci.ics.hyracks.dataflow.common.data.accessors.IFrameTupleReference;
+
+public class CurrentDateTimeDescriptor extends AbstractScalarFunctionDynamicDescriptor {
+
+    private static final long serialVersionUID = 1L;
+    private final static FunctionIdentifier FID = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "current-datetime", 0);
+
+    public final static IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
+
+        @Override
+        public IFunctionDescriptor createFunctionDescriptor() {
+            return new CurrentDateTimeDescriptor();
+        }
+    };
+
+    private CurrentDateTimeDescriptor() {
+    }
+
+    @Override
+    public ICopyEvaluatorFactory createEvaluatorFactory(ICopyEvaluatorFactory[] args) throws AlgebricksException {
+        return new ICopyEvaluatorFactory() {
+
+            private static final long serialVersionUID = 1L;
+
+            @Override
+            public ICopyEvaluator createEvaluator(final IDataOutputProvider output) throws AlgebricksException {
+                return new ICopyEvaluator() {
+
+                    private DataOutput out = output.getDataOutput();
+
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<ADateTime> datetimeSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.ADATETIME);
+                    private AMutableDateTime aDateTime = new AMutableDateTime(0);
+
+                    @Override
+                    public void evaluate(IFrameTupleReference tuple) throws AlgebricksException {
+                        try {
+                            aDateTime.setValue(System.currentTimeMillis());
+                            datetimeSerde.serialize(aDateTime, out);
+                        } catch (HyracksDataException hex) {
+                            throw new AlgebricksException(hex);
+                        }
+                    }
+                };
+            }
+        };
+    }
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.om.functions.IFunctionDescriptor#getIdentifier()
+     */
+    @Override
+    public FunctionIdentifier getIdentifier() {
+        return FID;
+    }
+
+}
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/CurrentTimeDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/CurrentTimeDescriptor.java
new file mode 100644
index 0000000..c7078b9
--- /dev/null
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/CurrentTimeDescriptor.java
@@ -0,0 +1,93 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.runtime.evaluators.functions.temporal;
+
+import java.io.DataOutput;
+
+import edu.uci.ics.asterix.common.functions.FunctionConstants;
+import edu.uci.ics.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
+import edu.uci.ics.asterix.om.base.AMutableTime;
+import edu.uci.ics.asterix.om.base.ATime;
+import edu.uci.ics.asterix.om.base.temporal.GregorianCalendarSystem;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
+import edu.uci.ics.asterix.om.types.BuiltinType;
+import edu.uci.ics.asterix.runtime.evaluators.base.AbstractScalarFunctionDynamicDescriptor;
+import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
+import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluator;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory;
+import edu.uci.ics.hyracks.api.dataflow.value.ISerializerDeserializer;
+import edu.uci.ics.hyracks.api.exceptions.HyracksDataException;
+import edu.uci.ics.hyracks.data.std.api.IDataOutputProvider;
+import edu.uci.ics.hyracks.dataflow.common.data.accessors.IFrameTupleReference;
+
+public class CurrentTimeDescriptor extends AbstractScalarFunctionDynamicDescriptor {
+
+    private static final long serialVersionUID = 1L;
+    public final static FunctionIdentifier FID = new FunctionIdentifier(FunctionConstants.ASTERIX_NS, "current-time", 0);
+
+    public final static IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
+
+        @Override
+        public IFunctionDescriptor createFunctionDescriptor() {
+            return new CurrentTimeDescriptor();
+        }
+    };
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.runtime.base.IScalarFunctionDynamicDescriptor#createEvaluatorFactory(edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory[])
+     */
+    @Override
+    public ICopyEvaluatorFactory createEvaluatorFactory(ICopyEvaluatorFactory[] args) throws AlgebricksException {
+        return new ICopyEvaluatorFactory() {
+
+            private static final long serialVersionUID = 1L;
+
+            @Override
+            public ICopyEvaluator createEvaluator(final IDataOutputProvider output) throws AlgebricksException {
+                return new ICopyEvaluator() {
+
+                    private DataOutput out = output.getDataOutput();
+
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<ATime> timeSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.ATIME);
+                    private AMutableTime aTime = new AMutableTime(0);
+
+                    @Override
+                    public void evaluate(IFrameTupleReference tuple) throws AlgebricksException {
+                        try {
+                            int timeChronon = (int) (System.currentTimeMillis() % GregorianCalendarSystem.CHRONON_OF_DAY);
+                            aTime.setValue(timeChronon);
+                            timeSerde.serialize(aTime, out);
+                        } catch (HyracksDataException hex) {
+                            throw new AlgebricksException(hex);
+                        }
+                    }
+                };
+            }
+        };
+    }
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.om.functions.IFunctionDescriptor#getIdentifier()
+     */
+    @Override
+    public FunctionIdentifier getIdentifier() {
+        return FID;
+    }
+
+}
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/DateFromDatetimeDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/DateFromDatetimeDescriptor.java
new file mode 100644
index 0000000..4ef52d9
--- /dev/null
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/DateFromDatetimeDescriptor.java
@@ -0,0 +1,108 @@
+package edu.uci.ics.asterix.runtime.evaluators.functions.temporal;
+
+import java.io.DataOutput;
+
+import edu.uci.ics.asterix.common.functions.FunctionConstants;
+import edu.uci.ics.asterix.dataflow.data.nontagged.serde.ADateTimeSerializerDeserializer;
+import edu.uci.ics.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
+import edu.uci.ics.asterix.om.base.ADate;
+import edu.uci.ics.asterix.om.base.AMutableDate;
+import edu.uci.ics.asterix.om.base.ANull;
+import edu.uci.ics.asterix.om.base.temporal.GregorianCalendarSystem;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
+import edu.uci.ics.asterix.om.types.ATypeTag;
+import edu.uci.ics.asterix.om.types.BuiltinType;
+import edu.uci.ics.asterix.runtime.evaluators.base.AbstractScalarFunctionDynamicDescriptor;
+import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
+import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluator;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory;
+import edu.uci.ics.hyracks.api.dataflow.value.ISerializerDeserializer;
+import edu.uci.ics.hyracks.api.exceptions.HyracksDataException;
+import edu.uci.ics.hyracks.data.std.api.IDataOutputProvider;
+import edu.uci.ics.hyracks.data.std.util.ArrayBackedValueStorage;
+import edu.uci.ics.hyracks.dataflow.common.data.accessors.IFrameTupleReference;
+
+public class DateFromDatetimeDescriptor extends AbstractScalarFunctionDynamicDescriptor {
+
+    private static final long serialVersionUID = 1L;
+    public final static FunctionIdentifier FID = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "date-from-datetime", 1);
+
+    // allowed input types
+    private final static byte SER_NULL_TYPE_TAG = ATypeTag.NULL.serialize();
+    private final static byte SER_DATETIME_TYPE_TAG = ATypeTag.DATETIME.serialize();
+
+    public final static IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
+
+        @Override
+        public IFunctionDescriptor createFunctionDescriptor() {
+            return new DateFromDatetimeDescriptor();
+        }
+
+    };
+
+    @Override
+    public ICopyEvaluatorFactory createEvaluatorFactory(final ICopyEvaluatorFactory[] args) throws AlgebricksException {
+        return new ICopyEvaluatorFactory() {
+
+            private static final long serialVersionUID = 1L;
+
+            @Override
+            public ICopyEvaluator createEvaluator(final IDataOutputProvider output) throws AlgebricksException {
+                return new ICopyEvaluator() {
+
+                    private DataOutput out = output.getDataOutput();
+                    private ArrayBackedValueStorage argOut = new ArrayBackedValueStorage();
+                    private ICopyEvaluator eval = args[0].createEvaluator(argOut);
+
+                    // possible returning types
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<ADate> dateSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.ADATE);
+                    private AMutableDate aDate = new AMutableDate(0);
+
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<ANull> nullSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.ANULL);
+
+                    @Override
+                    public void evaluate(IFrameTupleReference tuple) throws AlgebricksException {
+                        argOut.reset();
+                        eval.evaluate(tuple);
+                        try {
+                            if (argOut.getByteArray()[0] == SER_NULL_TYPE_TAG) {
+                                nullSerde.serialize(ANull.NULL, out);
+                            } else {
+                                if (argOut.getByteArray()[0] != SER_DATETIME_TYPE_TAG) {
+                                    throw new AlgebricksException(
+                                            "Inapplicable input type for function date_from_datetime: expecting ADateTime ("
+                                                    + SER_DATETIME_TYPE_TAG + ") or null (" + SER_NULL_TYPE_TAG
+                                                    + "), but got: " + argOut.getByteArray()[0]);
+                                }
+                                long datetimeChronon = ADateTimeSerializerDeserializer.getChronon(
+                                        argOut.getByteArray(), 1);
+                                int dateChrononInDays = (int) (datetimeChronon / GregorianCalendarSystem.CHRONON_OF_DAY);
+                                if (dateChrononInDays < 0
+                                        && datetimeChronon % GregorianCalendarSystem.CHRONON_OF_DAY != 0) {
+                                    dateChrononInDays -= 1;
+                                }
+                                aDate.setValue(dateChrononInDays);
+                                dateSerde.serialize(aDate, out);
+                            }
+                        } catch (HyracksDataException hex) {
+                            throw new AlgebricksException(hex);
+                        }
+                    }
+                };
+            }
+        };
+    }
+
+    @Override
+    public FunctionIdentifier getIdentifier() {
+        return FID;
+    }
+
+}
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/DateFromUnixTimeInDaysDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/DateFromUnixTimeInDaysDescriptor.java
new file mode 100644
index 0000000..6b78a35
--- /dev/null
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/DateFromUnixTimeInDaysDescriptor.java
@@ -0,0 +1,121 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.runtime.evaluators.functions.temporal;
+
+import java.io.DataOutput;
+
+import edu.uci.ics.asterix.common.functions.FunctionConstants;
+import edu.uci.ics.asterix.dataflow.data.nontagged.serde.AInt16SerializerDeserializer;
+import edu.uci.ics.asterix.dataflow.data.nontagged.serde.AInt32SerializerDeserializer;
+import edu.uci.ics.asterix.dataflow.data.nontagged.serde.AInt8SerializerDeserializer;
+import edu.uci.ics.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
+import edu.uci.ics.asterix.om.base.ADate;
+import edu.uci.ics.asterix.om.base.AMutableDate;
+import edu.uci.ics.asterix.om.base.ANull;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
+import edu.uci.ics.asterix.om.types.ATypeTag;
+import edu.uci.ics.asterix.om.types.BuiltinType;
+import edu.uci.ics.asterix.runtime.evaluators.base.AbstractScalarFunctionDynamicDescriptor;
+import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
+import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluator;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory;
+import edu.uci.ics.hyracks.api.dataflow.value.ISerializerDeserializer;
+import edu.uci.ics.hyracks.api.exceptions.HyracksDataException;
+import edu.uci.ics.hyracks.data.std.api.IDataOutputProvider;
+import edu.uci.ics.hyracks.data.std.util.ArrayBackedValueStorage;
+import edu.uci.ics.hyracks.dataflow.common.data.accessors.IFrameTupleReference;
+
+public class DateFromUnixTimeInDaysDescriptor extends AbstractScalarFunctionDynamicDescriptor {
+
+    private final static long serialVersionUID = 1L;
+    public final static FunctionIdentifier FID = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "date-from-unix-time-in-days", 1);
+
+    public final static IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
+
+        @Override
+        public IFunctionDescriptor createFunctionDescriptor() {
+            return new DateFromUnixTimeInDaysDescriptor();
+        }
+    };
+
+    @Override
+    public ICopyEvaluatorFactory createEvaluatorFactory(final ICopyEvaluatorFactory[] args) throws AlgebricksException {
+        return new ICopyEvaluatorFactory() {
+
+            private static final long serialVersionUID = 1L;
+
+            @Override
+            public ICopyEvaluator createEvaluator(final IDataOutputProvider output) throws AlgebricksException {
+                return new ICopyEvaluator() {
+
+                    private DataOutput out = output.getDataOutput();
+                    private ArrayBackedValueStorage argOut = new ArrayBackedValueStorage();
+                    private ICopyEvaluator eval = args[0].createEvaluator(argOut);
+
+                    // allowed input types
+                    private byte serNullTypeTag = ATypeTag.NULL.serialize();
+                    private byte serInt8TypeTag = ATypeTag.INT8.serialize();
+                    private byte serInt16TypeTag = ATypeTag.INT16.serialize();
+                    private byte serInt32TypeTag = ATypeTag.INT32.serialize();
+
+                    private AMutableDate aDate = new AMutableDate(0);
+
+                    // possible returning types
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<ADate> dateSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.ADATE);
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<ANull> nullSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.ANULL);
+
+                    @Override
+                    public void evaluate(IFrameTupleReference tuple) throws AlgebricksException {
+                        argOut.reset();
+                        eval.evaluate(tuple);
+                        try {
+                            if (argOut.getByteArray()[0] == serNullTypeTag) {
+                                nullSerde.serialize(ANull.NULL, out);
+                            } else {
+                                if (argOut.getByteArray()[0] == serInt8TypeTag) {
+                                    aDate.setValue(AInt8SerializerDeserializer.getByte(argOut.getByteArray(), 1));
+                                } else if (argOut.getByteArray()[0] == serInt16TypeTag) {
+                                    aDate.setValue(AInt16SerializerDeserializer.getShort(argOut.getByteArray(), 1));
+                                } else if (argOut.getByteArray()[0] == serInt32TypeTag) {
+                                    aDate.setValue(AInt32SerializerDeserializer.getInt(argOut.getByteArray(), 1));
+                                } else {
+                                    throw new AlgebricksException(
+                                            "Inapplicable input type for function date-from-unix-time-in-days: expecting integer or null type, but got "
+                                                    + argOut.getByteArray()[0]);
+                                }
+                                dateSerde.serialize(aDate, out);
+                            }
+                        } catch (HyracksDataException hex) {
+                            throw new AlgebricksException(hex);
+                        }
+                    }
+                };
+            }
+        };
+    }
+
+    @Override
+    public FunctionIdentifier getIdentifier() {
+        return FID;
+    }
+
+}
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/DatetimeFromDateAndTimeDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/DatetimeFromDateAndTimeDescriptor.java
new file mode 100644
index 0000000..2ade4b7
--- /dev/null
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/DatetimeFromDateAndTimeDescriptor.java
@@ -0,0 +1,144 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.runtime.evaluators.functions.temporal;
+
+import java.io.DataOutput;
+
+import edu.uci.ics.asterix.common.functions.FunctionConstants;
+import edu.uci.ics.asterix.dataflow.data.nontagged.serde.ADateSerializerDeserializer;
+import edu.uci.ics.asterix.dataflow.data.nontagged.serde.ATimeSerializerDeserializer;
+import edu.uci.ics.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
+import edu.uci.ics.asterix.om.base.ADateTime;
+import edu.uci.ics.asterix.om.base.AMutableDateTime;
+import edu.uci.ics.asterix.om.base.ANull;
+import edu.uci.ics.asterix.om.base.temporal.GregorianCalendarSystem;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
+import edu.uci.ics.asterix.om.types.ATypeTag;
+import edu.uci.ics.asterix.om.types.BuiltinType;
+import edu.uci.ics.asterix.runtime.evaluators.base.AbstractScalarFunctionDynamicDescriptor;
+import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
+import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluator;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory;
+import edu.uci.ics.hyracks.api.dataflow.value.ISerializerDeserializer;
+import edu.uci.ics.hyracks.api.exceptions.HyracksDataException;
+import edu.uci.ics.hyracks.data.std.api.IDataOutputProvider;
+import edu.uci.ics.hyracks.data.std.util.ArrayBackedValueStorage;
+import edu.uci.ics.hyracks.dataflow.common.data.accessors.IFrameTupleReference;
+
+public class DatetimeFromDateAndTimeDescriptor extends AbstractScalarFunctionDynamicDescriptor {
+
+    private static final long serialVersionUID = 1L;
+    public final static FunctionIdentifier FID = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "datetime-from-date-time", 2);
+
+    // allowed input types
+    private final static byte SER_NULL_TYPE_TAG = ATypeTag.NULL.serialize();
+    private final static byte SER_DATE_TYPE_TAG = ATypeTag.DATE.serialize();
+    private final static byte SER_TIME_TYPE_TAG = ATypeTag.TIME.serialize();
+
+    public final static IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
+
+        @Override
+        public IFunctionDescriptor createFunctionDescriptor() {
+            return new DatetimeFromDateAndTimeDescriptor();
+        }
+
+    };
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.runtime.base.IScalarFunctionDynamicDescriptor#createEvaluatorFactory(edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory[])
+     */
+    @Override
+    public ICopyEvaluatorFactory createEvaluatorFactory(final ICopyEvaluatorFactory[] args) throws AlgebricksException {
+        return new ICopyEvaluatorFactory() {
+
+            private static final long serialVersionUID = 1L;
+
+            @Override
+            public ICopyEvaluator createEvaluator(final IDataOutputProvider output) throws AlgebricksException {
+                return new ICopyEvaluator() {
+
+                    private DataOutput out = output.getDataOutput();
+                    private ArrayBackedValueStorage argOut0 = new ArrayBackedValueStorage();
+                    private ArrayBackedValueStorage argOut1 = new ArrayBackedValueStorage();
+                    private ICopyEvaluator eval0 = args[0].createEvaluator(argOut0);
+                    private ICopyEvaluator eval1 = args[1].createEvaluator(argOut1);
+
+                    // possible returning types
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<ADateTime> datetimeSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.ADATETIME);
+                    private AMutableDateTime aDateTime = new AMutableDateTime(0);
+
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<ANull> nullSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.ANULL);
+
+                    @Override
+                    public void evaluate(IFrameTupleReference tuple) throws AlgebricksException {
+                        argOut0.reset();
+                        eval0.evaluate(tuple);
+                        argOut1.reset();
+                        eval1.evaluate(tuple);
+
+                        try {
+                            if (argOut0.getByteArray()[0] == SER_NULL_TYPE_TAG
+                                    || argOut1.getByteArray()[0] == SER_NULL_TYPE_TAG) {
+                                nullSerde.serialize(ANull.NULL, out);
+                            } else {
+                                if (argOut0.getByteArray()[0] != SER_DATE_TYPE_TAG) {
+                                    throw new AlgebricksException(
+                                            "Inapplicable input type for function datetime-from-date-time: expecting a Date ("
+                                                    + SER_DATE_TYPE_TAG + ") or null (" + SER_NULL_TYPE_TAG
+                                                    + ") for the first parameter, but got: "
+                                                    + argOut0.getByteArray()[0]);
+                                }
+
+                                if (argOut1.getByteArray()[0] != SER_TIME_TYPE_TAG) {
+                                    throw new AlgebricksException(
+                                            "Inapplicable input type for function datetime-from-date-time: expecting a Time ("
+                                                    + SER_TIME_TYPE_TAG + ") or null (" + SER_NULL_TYPE_TAG
+                                                    + ") for the secon parameter, but got: "
+                                                    + argOut1.getByteArray()[0]);
+                                }
+
+                                long datetimeChronon = ADateSerializerDeserializer
+                                        .getChronon(argOut0.getByteArray(), 1)
+                                        * GregorianCalendarSystem.CHRONON_OF_DAY
+                                        + ATimeSerializerDeserializer.getChronon(argOut1.getByteArray(), 1);
+
+                                aDateTime.setValue(datetimeChronon);
+                                datetimeSerde.serialize(aDateTime, out);
+                            }
+                        } catch (HyracksDataException hex) {
+                            throw new AlgebricksException(hex);
+                        }
+                    }
+                };
+            }
+        };
+    }
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.om.functions.IFunctionDescriptor#getIdentifier()
+     */
+    @Override
+    public FunctionIdentifier getIdentifier() {
+        return FID;
+    }
+
+}
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/DatetimeFromUnixTimeInMsDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/DatetimeFromUnixTimeInMsDescriptor.java
new file mode 100644
index 0000000..dbd34f2
--- /dev/null
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/DatetimeFromUnixTimeInMsDescriptor.java
@@ -0,0 +1,131 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.runtime.evaluators.functions.temporal;
+
+import java.io.DataOutput;
+
+import edu.uci.ics.asterix.common.functions.FunctionConstants;
+import edu.uci.ics.asterix.dataflow.data.nontagged.serde.AInt16SerializerDeserializer;
+import edu.uci.ics.asterix.dataflow.data.nontagged.serde.AInt32SerializerDeserializer;
+import edu.uci.ics.asterix.dataflow.data.nontagged.serde.AInt64SerializerDeserializer;
+import edu.uci.ics.asterix.dataflow.data.nontagged.serde.AInt8SerializerDeserializer;
+import edu.uci.ics.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
+import edu.uci.ics.asterix.om.base.ADateTime;
+import edu.uci.ics.asterix.om.base.AMutableDateTime;
+import edu.uci.ics.asterix.om.base.ANull;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
+import edu.uci.ics.asterix.om.types.ATypeTag;
+import edu.uci.ics.asterix.om.types.BuiltinType;
+import edu.uci.ics.asterix.runtime.evaluators.base.AbstractScalarFunctionDynamicDescriptor;
+import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
+import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluator;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory;
+import edu.uci.ics.hyracks.api.dataflow.value.ISerializerDeserializer;
+import edu.uci.ics.hyracks.api.exceptions.HyracksDataException;
+import edu.uci.ics.hyracks.data.std.api.IDataOutputProvider;
+import edu.uci.ics.hyracks.data.std.util.ArrayBackedValueStorage;
+import edu.uci.ics.hyracks.dataflow.common.data.accessors.IFrameTupleReference;
+
+public class DatetimeFromUnixTimeInMsDescriptor extends AbstractScalarFunctionDynamicDescriptor {
+
+    private final static long serialVersionUID = 1L;
+    public final static FunctionIdentifier FID = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "datetime-from-unix-time-in-ms", 1);
+
+    // allowed input types
+    private final static byte SER_NULL_TYPE_TAG = ATypeTag.NULL.serialize();
+    private final static byte SER_INT8_TYPE_TAG = ATypeTag.INT8.serialize();
+    private final static byte SER_INT16_TYPE_TAG = ATypeTag.INT16.serialize();
+    private final static byte SER_INT32_TYPE_TAG = ATypeTag.INT32.serialize();
+    private final static byte SER_INT64_TYPE_TAG = ATypeTag.INT64.serialize();
+
+    public final static IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
+
+        @Override
+        public IFunctionDescriptor createFunctionDescriptor() {
+            return new DatetimeFromUnixTimeInMsDescriptor();
+        }
+    };
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.runtime.base.IScalarFunctionDynamicDescriptor#createEvaluatorFactory(edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory[])
+     */
+    @Override
+    public ICopyEvaluatorFactory createEvaluatorFactory(final ICopyEvaluatorFactory[] args) throws AlgebricksException {
+        return new ICopyEvaluatorFactory() {
+
+            private static final long serialVersionUID = 1L;
+
+            @Override
+            public ICopyEvaluator createEvaluator(final IDataOutputProvider output) throws AlgebricksException {
+                return new ICopyEvaluator() {
+
+                    private DataOutput out = output.getDataOutput();
+                    private ArrayBackedValueStorage argOut = new ArrayBackedValueStorage();
+                    private ICopyEvaluator eval = args[0].createEvaluator(argOut);
+
+                    // possible output types
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<ADateTime> datetimeSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.ADATETIME);
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<ANull> nullSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.ANULL);
+
+                    private AMutableDateTime aDatetime = new AMutableDateTime(0);
+
+                    @Override
+                    public void evaluate(IFrameTupleReference tuple) throws AlgebricksException {
+                        argOut.reset();
+                        eval.evaluate(tuple);
+                        try {
+                            if (argOut.getByteArray()[0] == SER_NULL_TYPE_TAG) {
+                                nullSerde.serialize(ANull.NULL, out);
+                            } else {
+                                if (argOut.getByteArray()[0] == SER_INT8_TYPE_TAG) {
+                                    aDatetime.setValue(AInt8SerializerDeserializer.getByte(argOut.getByteArray(), 1));
+                                } else if (argOut.getByteArray()[0] == SER_INT16_TYPE_TAG) {
+                                    aDatetime.setValue(AInt16SerializerDeserializer.getShort(argOut.getByteArray(), 1));
+                                } else if (argOut.getByteArray()[0] == SER_INT32_TYPE_TAG) {
+                                    aDatetime.setValue(AInt32SerializerDeserializer.getInt(argOut.getByteArray(), 1));
+                                } else if (argOut.getByteArray()[0] == SER_INT64_TYPE_TAG) {
+                                    aDatetime.setValue(AInt64SerializerDeserializer.getLong(argOut.getByteArray(), 1));
+                                } else {
+                                    throw new AlgebricksException(
+                                            "Inapplicable input type for function datetime-from-unix-time-in-ms: expecting integer or null type, but got "
+                                                    + argOut.getByteArray()[0]);
+                                }
+                                datetimeSerde.serialize(aDatetime, out);
+                            }
+                        } catch (HyracksDataException hex) {
+                            throw new AlgebricksException(hex);
+                        }
+                    }
+                };
+            }
+        };
+    }
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.om.functions.IFunctionDescriptor#getIdentifier()
+     */
+    @Override
+    public FunctionIdentifier getIdentifier() {
+        return FID;
+    }
+
+}
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/IntervalAfterDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/IntervalAfterDescriptor.java
new file mode 100644
index 0000000..85bb378
--- /dev/null
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/IntervalAfterDescriptor.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.runtime.evaluators.functions.temporal;
+
+import edu.uci.ics.asterix.common.functions.FunctionConstants;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
+import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
+
+public class IntervalAfterDescriptor extends AbstractIntervalLogicFuncDescriptor {
+
+    private final static long serialVersionUID = 1L;
+    public final static FunctionIdentifier FID = new FunctionIdentifier(FunctionConstants.ASTERIX_NS, "interval-after",
+            2);
+
+    public final static IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
+
+        @Override
+        public IFunctionDescriptor createFunctionDescriptor() {
+            return new IntervalAfterDescriptor();
+        }
+    };
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.om.functions.IFunctionDescriptor#getIdentifier()
+     */
+    @Override
+    public FunctionIdentifier getIdentifier() {
+        return FID;
+    }
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.runtime.evaluators.functions.temporal.AbstractIntervalLogicFuncDescriptor#compareIntervals(long, long, long, long)
+     */
+    @Override
+    protected boolean compareIntervals(long s1, long e1, long s2, long e2) {
+        return IntervalLogic.after(s1, e1, s2, e2);
+    }
+
+}
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/IntervalBeforeDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/IntervalBeforeDescriptor.java
new file mode 100644
index 0000000..2da48ee
--- /dev/null
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/IntervalBeforeDescriptor.java
@@ -0,0 +1,49 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.runtime.evaluators.functions.temporal;
+
+import edu.uci.ics.asterix.common.functions.FunctionConstants;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
+import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
+
+public class IntervalBeforeDescriptor extends AbstractIntervalLogicFuncDescriptor {
+
+    private final static long serialVersionUID = 1L;
+    public final static FunctionIdentifier FID = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "interval-before", 2);
+
+    public final static IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
+
+        @Override
+        public IFunctionDescriptor createFunctionDescriptor() {
+            return new IntervalBeforeDescriptor();
+        }
+    };
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.om.functions.IFunctionDescriptor#getIdentifier()
+     */
+    @Override
+    public FunctionIdentifier getIdentifier() {
+        return FID;
+    }
+
+    @Override
+    protected boolean compareIntervals(long s1, long e1, long s2, long e2) {
+        return IntervalLogic.before(s1, e1, s2, e2);
+    }
+
+}
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/IntervalCoveredByDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/IntervalCoveredByDescriptor.java
new file mode 100644
index 0000000..1064e59
--- /dev/null
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/IntervalCoveredByDescriptor.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.runtime.evaluators.functions.temporal;
+
+import edu.uci.ics.asterix.common.functions.FunctionConstants;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
+import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
+
+public class IntervalCoveredByDescriptor extends AbstractIntervalLogicFuncDescriptor {
+
+    private final static long serialVersionUID = 1L;
+    public final static FunctionIdentifier FID = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "interval-covered-by", 2);
+
+    public final static IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
+
+        @Override
+        public IFunctionDescriptor createFunctionDescriptor() {
+            return new IntervalCoveredByDescriptor();
+        }
+    };
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.om.functions.IFunctionDescriptor#getIdentifier()
+     */
+    @Override
+    public FunctionIdentifier getIdentifier() {
+        return FID;
+    }
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.runtime.evaluators.functions.temporal.AbstractIntervalLogicFuncDescriptor#compareIntervals(long, long, long, long)
+     */
+    @Override
+    protected boolean compareIntervals(long s1, long e1, long s2, long e2) {
+        return IntervalLogic.coveredBy(s1, e1, s2, e2);
+    }
+
+}
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/IntervalCoversDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/IntervalCoversDescriptor.java
new file mode 100644
index 0000000..5b1cfa5
--- /dev/null
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/IntervalCoversDescriptor.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.runtime.evaluators.functions.temporal;
+
+import edu.uci.ics.asterix.common.functions.FunctionConstants;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
+import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
+
+public class IntervalCoversDescriptor extends AbstractIntervalLogicFuncDescriptor {
+
+    private final static long serialVersionUID = 1L;
+    public final static FunctionIdentifier FID = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "interval-covers", 2);
+
+    public final static IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
+
+        @Override
+        public IFunctionDescriptor createFunctionDescriptor() {
+            return new IntervalCoversDescriptor();
+        }
+    };
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.om.functions.IFunctionDescriptor#getIdentifier()
+     */
+    @Override
+    public FunctionIdentifier getIdentifier() {
+        return FID;
+    }
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.runtime.evaluators.functions.temporal.AbstractIntervalLogicFuncDescriptor#compareIntervals(long, long, long, long)
+     */
+    @Override
+    protected boolean compareIntervals(long s1, long e1, long s2, long e2) {
+        return IntervalLogic.covers(s1, e1, s2, e2);
+    }
+
+}
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/IntervalEndedByDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/IntervalEndedByDescriptor.java
new file mode 100644
index 0000000..4610c89
--- /dev/null
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/IntervalEndedByDescriptor.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.runtime.evaluators.functions.temporal;
+
+import edu.uci.ics.asterix.common.functions.FunctionConstants;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
+import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
+
+public class IntervalEndedByDescriptor extends AbstractIntervalLogicFuncDescriptor {
+
+    private final static long serialVersionUID = 1L;
+    public final static FunctionIdentifier FID = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "interval-ended-by", 2);
+
+    public final static IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
+
+        @Override
+        public IFunctionDescriptor createFunctionDescriptor() {
+            return new IntervalEndedByDescriptor();
+        }
+    };
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.om.functions.IFunctionDescriptor#getIdentifier()
+     */
+    @Override
+    public FunctionIdentifier getIdentifier() {
+        return FID;
+    }
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.runtime.evaluators.functions.temporal.AbstractIntervalLogicFuncDescriptor#compareIntervals(long, long, long, long)
+     */
+    @Override
+    protected boolean compareIntervals(long s1, long e1, long s2, long e2) {
+        return IntervalLogic.endedBy(s1, e1, s2, e2);
+    }
+
+}
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/IntervalEndsDecriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/IntervalEndsDecriptor.java
new file mode 100644
index 0000000..9853c62
--- /dev/null
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/IntervalEndsDecriptor.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.runtime.evaluators.functions.temporal;
+
+import edu.uci.ics.asterix.common.functions.FunctionConstants;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
+import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
+
+public class IntervalEndsDecriptor extends AbstractIntervalLogicFuncDescriptor {
+
+    private final static long serialVersionUID = 1L;
+    public final static FunctionIdentifier FID = new FunctionIdentifier(FunctionConstants.ASTERIX_NS, "interval-ends",
+            2);
+
+    public final static IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
+
+        @Override
+        public IFunctionDescriptor createFunctionDescriptor() {
+            return new IntervalEndsDecriptor();
+        }
+    };
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.om.functions.IFunctionDescriptor#getIdentifier()
+     */
+    @Override
+    public FunctionIdentifier getIdentifier() {
+        return FID;
+    }
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.runtime.evaluators.functions.temporal.AbstractIntervalLogicFuncDescriptor#compareIntervals(long, long, long, long)
+     */
+    @Override
+    protected boolean compareIntervals(long s1, long e1, long s2, long e2) {
+        return IntervalLogic.ends(s1, e1, s2, e2);
+    }
+
+}
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/IntervalLogic.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/IntervalLogic.java
new file mode 100644
index 0000000..e8e814f
--- /dev/null
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/IntervalLogic.java
@@ -0,0 +1,161 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.runtime.evaluators.functions.temporal;
+
+public class IntervalLogic {
+
+    public static <T extends Comparable<T>> boolean validateInterval(T s, T e) {
+        return s.compareTo(e) <= 0;
+    }
+
+    /**
+     * Anything from interval 1 is less than anything from interval 2.
+     * <p/>
+     * |------|<br/>
+     * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|------|<br/>
+     * 
+     * @param s1
+     * @param e1
+     * @param s2
+     * @param e2
+     * @return
+     */
+    public static <T extends Comparable<T>> boolean before(T s1, T e1, T s2, T e2) {
+        return e1.compareTo(s2) < 0;
+    }
+
+    public static <T extends Comparable<T>> boolean after(T s1, T e1, T s2, T e2) {
+        return before(s2, e2, s1, e1);
+    }
+
+    /**
+     * The end of interval 1 is the same as the start of interval 2.
+     * <p/>
+     * |------|<br/>
+     * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|------|<br/>
+     * 
+     * @param s1
+     * @param e1
+     * @param s2
+     * @param e2
+     * @return
+     */
+    public static <T extends Comparable<T>> boolean meets(T s1, T e1, T s2, T e2) {
+        return e1.compareTo(s2) == 0;
+    }
+
+    public static <T extends Comparable<T>> boolean metBy(T s1, T e1, T s2, T e2) {
+        return meets(s2, e2, s1, e1);
+    }
+
+    /**
+     * Something at the end of interval 1 is contained as the beginning of interval 2.
+     * <p/>
+     * |------|<br/>
+     * &nbsp;&nbsp;&nbsp;&nbsp;|------|<br/>
+     * 
+     * @param s1
+     * @param e1
+     * @param s2
+     * @param e2
+     * @return
+     */
+    public static <T extends Comparable<T>> boolean overlaps(T s1, T e1, T s2, T e2) {
+        return s1.compareTo(s2) < 0 && e1.compareTo(s2) > 0 && e2.compareTo(e1) > 0;
+    }
+
+    public static <T extends Comparable<T>> boolean overlappedBy(T s1, T e1, T s2, T e2) {
+        return overlaps(s2, e2, s1, e1);
+    }
+
+    /**
+     * Something is shared by both interval 1 and interval 2.
+     * <p/>
+     * 
+     * @param s1
+     * @param e1
+     * @param s2
+     * @param e2
+     * @return
+     */
+    public static <T extends Comparable<T>> boolean overlap(T s1, T e1, T s2, T e2) {
+        return s1.compareTo(e2) < 0 && s2.compareTo(e1) < 0;
+    }
+
+    /**
+     * Anything from interval 1 is contained in the beginning of interval 2.
+     * <p/>
+     * |------|<br/>
+     * |-------|<br/>
+     * 
+     * @param s1
+     * @param e1
+     * @param s2
+     * @param e2
+     * @return
+     */
+    public static <T extends Comparable<T>> boolean starts(T s1, T e1, T s2, T e2) {
+        return s1.compareTo(s2) == 0 && e1.compareTo(e2) <= 0;
+    }
+
+    public static <T extends Comparable<T>> boolean startedBy(T s1, T e1, T s2, T e2) {
+        return starts(s2, e2, s1, e1);
+    }
+
+    /**
+     * Anything from interval 2 is in interval 1.
+     * <p/>
+     * |------|<br/>
+     * &nbsp;&nbsp;|----|<br/>
+     * 
+     * @param s1
+     * @param e1
+     * @param s2
+     * @param e2
+     * @return
+     */
+    public static <T extends Comparable<T>> boolean covers(T s1, T e1, T s2, T e2) {
+        return s1.compareTo(s2) <= 0 && e1.compareTo(e2) >= 0;
+    }
+
+    public static <T extends Comparable<T>> boolean coveredBy(T s1, T e1, T s2, T e2) {
+        return covers(s2, e2, s1, e1);
+    }
+
+    /**
+     * Anything from interval 1 is from the ending part of interval 2.
+     * <p/>
+     * &nbsp;&nbsp;|-----|<br/>
+     * |------|<br/>
+     * 
+     * @param s1
+     * @param e1
+     * @param s2
+     * @param e2
+     * @return
+     */
+    public static <T extends Comparable<T>> boolean ends(T s1, T e1, T s2, T e2) {
+        return s1.compareTo(s2) >= 0 && e1.compareTo(e2) == 0;
+    }
+
+    public static <T extends Comparable<T>> boolean endedBy(T s1, T e1, T s2, T e2) {
+        return ends(s2, e2, s1, e1);
+    }
+
+    public static <T extends Comparable<T>> boolean equals(T s1, T e1, T s2, T e2) {
+        return s1.compareTo(s1) == 0 && e1.compareTo(e2) == 0;
+    }
+
+}
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/IntervalMeetsDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/IntervalMeetsDescriptor.java
new file mode 100644
index 0000000..0263edb
--- /dev/null
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/IntervalMeetsDescriptor.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.runtime.evaluators.functions.temporal;
+
+import edu.uci.ics.asterix.common.functions.FunctionConstants;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
+import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
+
+public class IntervalMeetsDescriptor extends AbstractIntervalLogicFuncDescriptor {
+
+    private final static long serialVersionUID = 1L;
+    public final static FunctionIdentifier FID = new FunctionIdentifier(FunctionConstants.ASTERIX_NS, "interval-meets",
+            2);
+
+    public final static IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
+
+        @Override
+        public IFunctionDescriptor createFunctionDescriptor() {
+            return new IntervalMeetsDescriptor();
+        }
+    };
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.om.functions.IFunctionDescriptor#getIdentifier()
+     */
+    @Override
+    public FunctionIdentifier getIdentifier() {
+        return FID;
+    }
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.runtime.evaluators.functions.temporal.AbstractIntervalLogicFuncDescriptor#compareIntervals(long, long, long, long)
+     */
+    @Override
+    protected boolean compareIntervals(long s1, long e1, long s2, long e2) {
+        return IntervalLogic.meets(s1, e1, s2, e2);
+    }
+
+}
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/IntervalMetByDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/IntervalMetByDescriptor.java
new file mode 100644
index 0000000..4cab864
--- /dev/null
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/IntervalMetByDescriptor.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.runtime.evaluators.functions.temporal;
+
+import edu.uci.ics.asterix.common.functions.FunctionConstants;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
+import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
+
+public class IntervalMetByDescriptor extends AbstractIntervalLogicFuncDescriptor {
+
+    private final static long serialVersionUID = 1L;
+    public final static FunctionIdentifier FID = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "interval-met-by", 2);
+
+    public final static IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
+
+        @Override
+        public IFunctionDescriptor createFunctionDescriptor() {
+            return new IntervalMetByDescriptor();
+        }
+    };
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.om.functions.IFunctionDescriptor#getIdentifier()
+     */
+    @Override
+    public FunctionIdentifier getIdentifier() {
+        return FID;
+    }
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.runtime.evaluators.functions.temporal.AbstractIntervalLogicFuncDescriptor#compareIntervals(long, long, long, long)
+     */
+    @Override
+    protected boolean compareIntervals(long s1, long e1, long s2, long e2) {
+        return IntervalLogic.metBy(s1, e1, s2, e2);
+    }
+
+}
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/IntervalOverlappedByDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/IntervalOverlappedByDescriptor.java
new file mode 100644
index 0000000..17e7612
--- /dev/null
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/IntervalOverlappedByDescriptor.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.runtime.evaluators.functions.temporal;
+
+import edu.uci.ics.asterix.common.functions.FunctionConstants;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
+import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
+
+public class IntervalOverlappedByDescriptor extends AbstractIntervalLogicFuncDescriptor {
+
+    private final static long serialVersionUID = 1L;
+    public final static FunctionIdentifier FID = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "interval-overlapped-by", 2);
+
+    public final static IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
+
+        @Override
+        public IFunctionDescriptor createFunctionDescriptor() {
+            return new IntervalOverlappedByDescriptor();
+        }
+    };
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.om.functions.IFunctionDescriptor#getIdentifier()
+     */
+    @Override
+    public FunctionIdentifier getIdentifier() {
+        return FID;
+    }
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.runtime.evaluators.functions.temporal.AbstractIntervalLogicFuncDescriptor#compareIntervals(long, long, long, long)
+     */
+    @Override
+    protected boolean compareIntervals(long s1, long e1, long s2, long e2) {
+        return IntervalLogic.overlappedBy(s1, e1, s2, e2);
+    }
+
+}
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/IntervalOverlapsDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/IntervalOverlapsDescriptor.java
new file mode 100644
index 0000000..ee62711
--- /dev/null
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/IntervalOverlapsDescriptor.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.runtime.evaluators.functions.temporal;
+
+import edu.uci.ics.asterix.common.functions.FunctionConstants;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
+import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
+
+public class IntervalOverlapsDescriptor extends AbstractIntervalLogicFuncDescriptor {
+
+    private final static long serialVersionUID = 1L;
+    public final static FunctionIdentifier FID = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "interval-overlaps", 2);
+
+    public final static IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
+
+        @Override
+        public IFunctionDescriptor createFunctionDescriptor() {
+            return new IntervalOverlapsDescriptor();
+        }
+    };
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.om.functions.IFunctionDescriptor#getIdentifier()
+     */
+    @Override
+    public FunctionIdentifier getIdentifier() {
+        return FID;
+    }
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.runtime.evaluators.functions.temporal.AbstractIntervalLogicFuncDescriptor#compareIntervals(long, long, long, long)
+     */
+    @Override
+    protected boolean compareIntervals(long s1, long e1, long s2, long e2) {
+        return IntervalLogic.overlaps(s1, e1, s2, e2);
+    }
+
+}
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/IntervalStartedByDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/IntervalStartedByDescriptor.java
new file mode 100644
index 0000000..7e5e0fe
--- /dev/null
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/IntervalStartedByDescriptor.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.runtime.evaluators.functions.temporal;
+
+import edu.uci.ics.asterix.common.functions.FunctionConstants;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
+import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
+
+public class IntervalStartedByDescriptor extends AbstractIntervalLogicFuncDescriptor {
+
+    private final static long serialVersionUID = 1L;
+    public final static FunctionIdentifier FID = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "interval-started-by", 2);
+
+    public final static IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
+
+        @Override
+        public IFunctionDescriptor createFunctionDescriptor() {
+            return new IntervalStartedByDescriptor();
+        }
+    };
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.om.functions.IFunctionDescriptor#getIdentifier()
+     */
+    @Override
+    public FunctionIdentifier getIdentifier() {
+        return FID;
+    }
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.runtime.evaluators.functions.temporal.AbstractIntervalLogicFuncDescriptor#compareIntervals(long, long, long, long)
+     */
+    @Override
+    protected boolean compareIntervals(long s1, long e1, long s2, long e2) {
+        return IntervalLogic.startedBy(s1, e1, s2, e2);
+    }
+
+}
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/IntervalStartsDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/IntervalStartsDescriptor.java
new file mode 100644
index 0000000..c2ca32e
--- /dev/null
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/IntervalStartsDescriptor.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.runtime.evaluators.functions.temporal;
+
+import edu.uci.ics.asterix.common.functions.FunctionConstants;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
+import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
+
+public class IntervalStartsDescriptor extends AbstractIntervalLogicFuncDescriptor {
+
+    private final static long serialVersionUID = 1L;
+    public final static FunctionIdentifier FID = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "interval-starts", 2);
+
+    public final static IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
+
+        @Override
+        public IFunctionDescriptor createFunctionDescriptor() {
+            return new IntervalStartsDescriptor();
+        }
+    };
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.om.functions.IFunctionDescriptor#getIdentifier()
+     */
+    @Override
+    public FunctionIdentifier getIdentifier() {
+        return FID;
+    }
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.runtime.evaluators.functions.temporal.AbstractIntervalLogicFuncDescriptor#compareIntervals(long, long, long, long)
+     */
+    @Override
+    protected boolean compareIntervals(long s1, long e1, long s2, long e2) {
+        return IntervalLogic.starts(s1, e1, s2, e2);
+    }
+
+}
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/OverlapDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/OverlapDescriptor.java
new file mode 100644
index 0000000..80479cd
--- /dev/null
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/OverlapDescriptor.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.runtime.evaluators.functions.temporal;
+
+import edu.uci.ics.asterix.common.functions.FunctionConstants;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
+import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
+
+public class OverlapDescriptor extends AbstractIntervalLogicFuncDescriptor {
+
+    private final static long serialVersionUID = 1L;
+    public final static FunctionIdentifier FID = new FunctionIdentifier(FunctionConstants.ASTERIX_NS, "overlap", 2);
+
+    public final static IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
+
+        @Override
+        public IFunctionDescriptor createFunctionDescriptor() {
+            return new OverlapDescriptor();
+        }
+    };
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.om.functions.IFunctionDescriptor#getIdentifier()
+     */
+    @Override
+    public FunctionIdentifier getIdentifier() {
+        return FID;
+    }
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.runtime.evaluators.functions.temporal.AbstractIntervalLogicFuncDescriptor#compareIntervals(long, long, long, long)
+     */
+    @Override
+    protected boolean compareIntervals(long s1, long e1, long s2, long e2) {
+        return IntervalLogic.overlap(s1, e1, s2, e2);
+    }
+
+}
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/SubtractDateDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/SubtractDateDescriptor.java
new file mode 100644
index 0000000..67d8ef3
--- /dev/null
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/SubtractDateDescriptor.java
@@ -0,0 +1,134 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.runtime.evaluators.functions.temporal;
+
+import java.io.DataOutput;
+
+import edu.uci.ics.asterix.common.functions.FunctionConstants;
+import edu.uci.ics.asterix.dataflow.data.nontagged.serde.ADateSerializerDeserializer;
+import edu.uci.ics.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
+import edu.uci.ics.asterix.om.base.ADuration;
+import edu.uci.ics.asterix.om.base.AMutableDuration;
+import edu.uci.ics.asterix.om.base.ANull;
+import edu.uci.ics.asterix.om.base.temporal.GregorianCalendarSystem;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
+import edu.uci.ics.asterix.om.types.ATypeTag;
+import edu.uci.ics.asterix.om.types.BuiltinType;
+import edu.uci.ics.asterix.runtime.evaluators.base.AbstractScalarFunctionDynamicDescriptor;
+import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
+import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluator;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory;
+import edu.uci.ics.hyracks.api.dataflow.value.ISerializerDeserializer;
+import edu.uci.ics.hyracks.api.exceptions.HyracksDataException;
+import edu.uci.ics.hyracks.data.std.api.IDataOutputProvider;
+import edu.uci.ics.hyracks.data.std.util.ArrayBackedValueStorage;
+import edu.uci.ics.hyracks.dataflow.common.data.accessors.IFrameTupleReference;
+
+public class SubtractDateDescriptor extends AbstractScalarFunctionDynamicDescriptor {
+
+    private final static long serialVersionUID = 1L;
+    public final static FunctionIdentifier FID = new FunctionIdentifier(FunctionConstants.ASTERIX_NS, "subtract-date",
+            2);
+
+    // allowed input types
+    private final static byte SER_NULL_TYPE_TAG = ATypeTag.NULL.serialize();
+    private final static byte SER_DATE_TYPE_TAG = ATypeTag.DATE.serialize();
+
+    public final static IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
+
+        @Override
+        public IFunctionDescriptor createFunctionDescriptor() {
+            return new SubtractDateDescriptor();
+        }
+    };
+
+    @Override
+    public ICopyEvaluatorFactory createEvaluatorFactory(final ICopyEvaluatorFactory[] args) throws AlgebricksException {
+        return new ICopyEvaluatorFactory() {
+
+            private static final long serialVersionUID = 1L;
+
+            @Override
+            public ICopyEvaluator createEvaluator(final IDataOutputProvider output) throws AlgebricksException {
+                return new ICopyEvaluator() {
+
+                    private DataOutput out = output.getDataOutput();
+                    private ArrayBackedValueStorage argOut0 = new ArrayBackedValueStorage();
+                    private ArrayBackedValueStorage argOut1 = new ArrayBackedValueStorage();
+                    private ICopyEvaluator eval0 = args[0].createEvaluator(argOut0);
+                    private ICopyEvaluator eval1 = args[1].createEvaluator(argOut1);
+
+                    // possible output types
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<ANull> nullSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.ANULL);
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<ADuration> durationSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.ADURATION);
+
+                    private AMutableDuration aDuration = new AMutableDuration(0, 0);
+
+                    @Override
+                    public void evaluate(IFrameTupleReference tuple) throws AlgebricksException {
+                        argOut0.reset();
+                        eval0.evaluate(tuple);
+                        argOut1.reset();
+                        eval1.evaluate(tuple);
+
+                        try {
+                            if (argOut0.getByteArray()[0] == SER_NULL_TYPE_TAG
+                                    || argOut1.getByteArray()[0] == SER_NULL_TYPE_TAG) {
+                                nullSerde.serialize(ANull.NULL, out);
+                                return;
+                            }
+
+                            if (argOut0.getByteArray()[0] != SER_DATE_TYPE_TAG) {
+                                throw new AlgebricksException(
+                                        "Inapplicable input type for parameter 0: expecting a Date ("
+                                                + SER_DATE_TYPE_TAG + ") or null (" + SER_NULL_TYPE_TAG
+                                                + "), but got: " + argOut0.getByteArray()[0]);
+                            }
+
+                            if (argOut1.getByteArray()[0] != SER_DATE_TYPE_TAG) {
+                                throw new AlgebricksException(
+                                        "Inapplicable input type for parameter 1: expecting a Date ("
+                                                + SER_DATE_TYPE_TAG + ") or null (" + SER_NULL_TYPE_TAG
+                                                + "), but got: " + argOut1.getByteArray()[0]);
+                            }
+
+                            long durationChronon = (ADateSerializerDeserializer.getChronon(argOut0.getByteArray(), 1) - ADateSerializerDeserializer
+                                    .getChronon(argOut1.getByteArray(), 1)) * GregorianCalendarSystem.CHRONON_OF_DAY;
+
+                            aDuration.setValue(0, durationChronon);
+
+                            durationSerde.serialize(aDuration, out);
+
+                        } catch (HyracksDataException hex) {
+                            throw new AlgebricksException(hex);
+                        }
+                    }
+                };
+            }
+        };
+    }
+
+    @Override
+    public FunctionIdentifier getIdentifier() {
+        return FID;
+    }
+
+}
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/SubtractDatetimeDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/SubtractDatetimeDescriptor.java
new file mode 100644
index 0000000..5b77709
--- /dev/null
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/SubtractDatetimeDescriptor.java
@@ -0,0 +1,138 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.runtime.evaluators.functions.temporal;
+
+import java.io.DataOutput;
+
+import edu.uci.ics.asterix.common.functions.FunctionConstants;
+import edu.uci.ics.asterix.dataflow.data.nontagged.serde.ADateTimeSerializerDeserializer;
+import edu.uci.ics.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
+import edu.uci.ics.asterix.om.base.ADuration;
+import edu.uci.ics.asterix.om.base.AMutableDuration;
+import edu.uci.ics.asterix.om.base.ANull;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
+import edu.uci.ics.asterix.om.types.ATypeTag;
+import edu.uci.ics.asterix.om.types.BuiltinType;
+import edu.uci.ics.asterix.runtime.evaluators.base.AbstractScalarFunctionDynamicDescriptor;
+import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
+import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluator;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory;
+import edu.uci.ics.hyracks.api.dataflow.value.ISerializerDeserializer;
+import edu.uci.ics.hyracks.api.exceptions.HyracksDataException;
+import edu.uci.ics.hyracks.data.std.api.IDataOutputProvider;
+import edu.uci.ics.hyracks.data.std.util.ArrayBackedValueStorage;
+import edu.uci.ics.hyracks.dataflow.common.data.accessors.IFrameTupleReference;
+
+public class SubtractDatetimeDescriptor extends AbstractScalarFunctionDynamicDescriptor {
+
+    private final static long serialVersionUID = 1L;
+    public final static FunctionIdentifier FID = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "subtract-datetime", 2);
+
+    // allowed input types
+    private final static byte SER_NULL_TYPE_TAG = ATypeTag.NULL.serialize();
+    private final static byte SER_DATETIME_TYPE_TAG = ATypeTag.DATETIME.serialize();
+
+    public final static IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
+
+        @Override
+        public IFunctionDescriptor createFunctionDescriptor() {
+            return new SubtractDatetimeDescriptor();
+        }
+    };
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.runtime.base.IScalarFunctionDynamicDescriptor#createEvaluatorFactory(edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory[])
+     */
+    @Override
+    public ICopyEvaluatorFactory createEvaluatorFactory(final ICopyEvaluatorFactory[] args) throws AlgebricksException {
+        return new ICopyEvaluatorFactory() {
+
+            private static final long serialVersionUID = 1L;
+
+            @Override
+            public ICopyEvaluator createEvaluator(final IDataOutputProvider output) throws AlgebricksException {
+                return new ICopyEvaluator() {
+
+                    private DataOutput out = output.getDataOutput();
+                    private ArrayBackedValueStorage argOut0 = new ArrayBackedValueStorage();
+                    private ArrayBackedValueStorage argOut1 = new ArrayBackedValueStorage();
+                    private ICopyEvaluator eval0 = args[0].createEvaluator(argOut0);
+                    private ICopyEvaluator eval1 = args[1].createEvaluator(argOut1);
+
+                    // possible output types
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<ANull> nullSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.ANULL);
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<ADuration> durationSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.ADURATION);
+
+                    private AMutableDuration aDuration = new AMutableDuration(0, 0);
+
+                    @Override
+                    public void evaluate(IFrameTupleReference tuple) throws AlgebricksException {
+                        argOut0.reset();
+                        eval0.evaluate(tuple);
+                        argOut1.reset();
+                        eval1.evaluate(tuple);
+
+                        try {
+                            if (argOut0.getByteArray()[0] == SER_NULL_TYPE_TAG
+                                    || argOut1.getByteArray()[0] == SER_NULL_TYPE_TAG) {
+                                nullSerde.serialize(ANull.NULL, out);
+                                return;
+                            }
+
+                            if (argOut0.getByteArray()[0] != SER_DATETIME_TYPE_TAG) {
+                                throw new AlgebricksException(
+                                        "Inapplicable input type for parameter 0: expecting a DateTime, but got: "
+                                                + argOut0.getByteArray()[0]);
+                            }
+
+                            if (argOut1.getByteArray()[0] != SER_DATETIME_TYPE_TAG) {
+                                throw new AlgebricksException(
+                                        "Inapplicable input type for parameter 1: expecting a DateTime, but got: "
+                                                + argOut1.getByteArray()[0]);
+                            }
+
+                            long durationChronon = ADateTimeSerializerDeserializer
+                                    .getChronon(argOut0.getByteArray(), 1)
+                                    - ADateTimeSerializerDeserializer.getChronon(argOut1.getByteArray(), 1);
+
+                            aDuration.setValue(0, durationChronon);
+
+                            durationSerde.serialize(aDuration, out);
+
+                        } catch (HyracksDataException hex) {
+                            throw new AlgebricksException(hex);
+                        }
+                    }
+                };
+            }
+        };
+    }
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.om.functions.IFunctionDescriptor#getIdentifier()
+     */
+    @Override
+    public FunctionIdentifier getIdentifier() {
+        return FID;
+    }
+
+}
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/SubtractTimeDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/SubtractTimeDescriptor.java
new file mode 100644
index 0000000..323033e
--- /dev/null
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/SubtractTimeDescriptor.java
@@ -0,0 +1,139 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.runtime.evaluators.functions.temporal;
+
+import java.io.DataOutput;
+
+import edu.uci.ics.asterix.common.functions.FunctionConstants;
+import edu.uci.ics.asterix.dataflow.data.nontagged.serde.ATimeSerializerDeserializer;
+import edu.uci.ics.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
+import edu.uci.ics.asterix.om.base.ADuration;
+import edu.uci.ics.asterix.om.base.AMutableDuration;
+import edu.uci.ics.asterix.om.base.ANull;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
+import edu.uci.ics.asterix.om.types.ATypeTag;
+import edu.uci.ics.asterix.om.types.BuiltinType;
+import edu.uci.ics.asterix.runtime.evaluators.base.AbstractScalarFunctionDynamicDescriptor;
+import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
+import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluator;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory;
+import edu.uci.ics.hyracks.api.dataflow.value.ISerializerDeserializer;
+import edu.uci.ics.hyracks.api.exceptions.HyracksDataException;
+import edu.uci.ics.hyracks.data.std.api.IDataOutputProvider;
+import edu.uci.ics.hyracks.data.std.util.ArrayBackedValueStorage;
+import edu.uci.ics.hyracks.dataflow.common.data.accessors.IFrameTupleReference;
+
+public class SubtractTimeDescriptor extends AbstractScalarFunctionDynamicDescriptor {
+
+    private final static long serialVersionUID = 1L;
+    public final static FunctionIdentifier FID = new FunctionIdentifier(FunctionConstants.ASTERIX_NS, "subtract-time",
+            2);
+
+    // allowed input types
+    private final static byte SER_NULL_TYPE_TAG = ATypeTag.NULL.serialize();
+    private final static byte SER_TIME_TYPE_TAG = ATypeTag.TIME.serialize();
+
+    public final static IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
+
+        @Override
+        public IFunctionDescriptor createFunctionDescriptor() {
+            return new SubtractTimeDescriptor();
+        }
+    };
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.runtime.base.IScalarFunctionDynamicDescriptor#createEvaluatorFactory(edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory[])
+     */
+    @Override
+    public ICopyEvaluatorFactory createEvaluatorFactory(final ICopyEvaluatorFactory[] args) throws AlgebricksException {
+        return new ICopyEvaluatorFactory() {
+
+            private static final long serialVersionUID = 1L;
+
+            @Override
+            public ICopyEvaluator createEvaluator(final IDataOutputProvider output) throws AlgebricksException {
+                return new ICopyEvaluator() {
+
+                    private DataOutput out = output.getDataOutput();
+                    private ArrayBackedValueStorage argOut0 = new ArrayBackedValueStorage();
+                    private ArrayBackedValueStorage argOut1 = new ArrayBackedValueStorage();
+                    private ICopyEvaluator eval0 = args[0].createEvaluator(argOut0);
+                    private ICopyEvaluator eval1 = args[1].createEvaluator(argOut1);
+
+                    // possible output types
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<ANull> nullSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.ANULL);
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<ADuration> durationSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.ADURATION);
+
+                    private AMutableDuration aDuration = new AMutableDuration(0, 0);
+
+                    @Override
+                    public void evaluate(IFrameTupleReference tuple) throws AlgebricksException {
+                        argOut0.reset();
+                        eval0.evaluate(tuple);
+                        argOut1.reset();
+                        eval1.evaluate(tuple);
+
+                        try {
+                            if (argOut0.getByteArray()[0] == SER_NULL_TYPE_TAG
+                                    || argOut1.getByteArray()[0] == SER_NULL_TYPE_TAG) {
+                                nullSerde.serialize(ANull.NULL, out);
+                                return;
+                            }
+
+                            if (argOut0.getByteArray()[0] != SER_TIME_TYPE_TAG) {
+                                throw new AlgebricksException(
+                                        "Inapplicable input type for parameter 0: expecting a Time ("
+                                                + SER_TIME_TYPE_TAG + ") or null (" + SER_NULL_TYPE_TAG
+                                                + "), but got: " + argOut0.getByteArray()[0]);
+                            }
+
+                            if (argOut1.getByteArray()[0] != SER_TIME_TYPE_TAG) {
+                                throw new AlgebricksException(
+                                        "Inapplicable input type for parameter 1: expecting a Time ("
+                                                + SER_TIME_TYPE_TAG + ") or null (" + SER_NULL_TYPE_TAG
+                                                + "), but got: " + argOut1.getByteArray()[0]);
+                            }
+
+                            int durationChronon = ATimeSerializerDeserializer.getChronon(argOut0.getByteArray(), 1)
+                                    - ATimeSerializerDeserializer.getChronon(argOut1.getByteArray(), 1);
+
+                            aDuration.setValue(0, durationChronon);
+
+                            durationSerde.serialize(aDuration, out);
+
+                        } catch (HyracksDataException hex) {
+                            throw new AlgebricksException(hex);
+                        }
+                    }
+                };
+            }
+        };
+    }
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.om.functions.IFunctionDescriptor#getIdentifier()
+     */
+    @Override
+    public FunctionIdentifier getIdentifier() {
+        return FID;
+    }
+
+}
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/TimeFromDatetimeDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/TimeFromDatetimeDescriptor.java
new file mode 100644
index 0000000..b1053a4
--- /dev/null
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/TimeFromDatetimeDescriptor.java
@@ -0,0 +1,127 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.runtime.evaluators.functions.temporal;
+
+import java.io.DataOutput;
+
+import edu.uci.ics.asterix.common.functions.FunctionConstants;
+import edu.uci.ics.asterix.dataflow.data.nontagged.serde.ADateTimeSerializerDeserializer;
+import edu.uci.ics.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
+import edu.uci.ics.asterix.om.base.AMutableTime;
+import edu.uci.ics.asterix.om.base.ANull;
+import edu.uci.ics.asterix.om.base.ATime;
+import edu.uci.ics.asterix.om.base.temporal.GregorianCalendarSystem;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
+import edu.uci.ics.asterix.om.types.ATypeTag;
+import edu.uci.ics.asterix.om.types.BuiltinType;
+import edu.uci.ics.asterix.runtime.evaluators.base.AbstractScalarFunctionDynamicDescriptor;
+import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
+import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluator;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory;
+import edu.uci.ics.hyracks.api.dataflow.value.ISerializerDeserializer;
+import edu.uci.ics.hyracks.api.exceptions.HyracksDataException;
+import edu.uci.ics.hyracks.data.std.api.IDataOutputProvider;
+import edu.uci.ics.hyracks.data.std.util.ArrayBackedValueStorage;
+import edu.uci.ics.hyracks.dataflow.common.data.accessors.IFrameTupleReference;
+
+public class TimeFromDatetimeDescriptor extends AbstractScalarFunctionDynamicDescriptor {
+
+    private static final long serialVersionUID = 1L;
+    public final static FunctionIdentifier FID = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "time-from-datetime", 1);
+
+    // allowed input types
+    private final static byte SER_NULL_TYPE_TAG = ATypeTag.NULL.serialize();
+    private final static byte SER_DATETIME_TYPE_TAG = ATypeTag.DATETIME.serialize();
+
+    public final static IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
+
+        @Override
+        public IFunctionDescriptor createFunctionDescriptor() {
+            return new TimeFromDatetimeDescriptor();
+        }
+
+    };
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.runtime.base.IScalarFunctionDynamicDescriptor#createEvaluatorFactory(edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory[])
+     */
+    @Override
+    public ICopyEvaluatorFactory createEvaluatorFactory(final ICopyEvaluatorFactory[] args) throws AlgebricksException {
+        return new ICopyEvaluatorFactory() {
+
+            private static final long serialVersionUID = 1L;
+
+            @Override
+            public ICopyEvaluator createEvaluator(final IDataOutputProvider output) throws AlgebricksException {
+                return new ICopyEvaluator() {
+
+                    private DataOutput out = output.getDataOutput();
+                    private ArrayBackedValueStorage argOut = new ArrayBackedValueStorage();
+                    private ICopyEvaluator eval = args[0].createEvaluator(argOut);
+
+                    // possible returning types
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<ATime> timeSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.ATIME);
+                    private AMutableTime aTime = new AMutableTime(0);
+
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<ANull> nullSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.ANULL);
+
+                    @Override
+                    public void evaluate(IFrameTupleReference tuple) throws AlgebricksException {
+                        argOut.reset();
+                        eval.evaluate(tuple);
+                        try {
+                            if (argOut.getByteArray()[0] == SER_NULL_TYPE_TAG) {
+                                nullSerde.serialize(ANull.NULL, out);
+                            } else {
+                                if (argOut.getByteArray()[0] != SER_DATETIME_TYPE_TAG) {
+                                    throw new AlgebricksException(
+                                            "Inapplicable input type for function time-from-datetime: expecting a DataTime ("
+                                                    + SER_DATETIME_TYPE_TAG + ") or null (" + SER_NULL_TYPE_TAG
+                                                    + "), but got: " + argOut.getByteArray()[0]);
+                                }
+                                long datetimeChronon = ADateTimeSerializerDeserializer.getChronon(
+                                        argOut.getByteArray(), 1);
+                                int timeChronon = (int) (datetimeChronon % GregorianCalendarSystem.CHRONON_OF_DAY);
+                                if (timeChronon < 0) {
+                                    timeChronon += GregorianCalendarSystem.CHRONON_OF_DAY;
+                                }
+                                aTime.setValue(timeChronon);
+                                timeSerde.serialize(aTime, out);
+                            }
+                        } catch (HyracksDataException hex) {
+                            throw new AlgebricksException(hex);
+                        }
+                    }
+                };
+            }
+        };
+    }
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.om.functions.IFunctionDescriptor#getIdentifier()
+     */
+    @Override
+    public FunctionIdentifier getIdentifier() {
+        return FID;
+    }
+
+}
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/TimeFromUnixTimeInMsDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/TimeFromUnixTimeInMsDescriptor.java
new file mode 100644
index 0000000..b3fbc0e
--- /dev/null
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/temporal/TimeFromUnixTimeInMsDescriptor.java
@@ -0,0 +1,126 @@
+/*
+ * Copyright 2009-2011 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package edu.uci.ics.asterix.runtime.evaluators.functions.temporal;
+
+import java.io.DataOutput;
+
+import edu.uci.ics.asterix.common.functions.FunctionConstants;
+import edu.uci.ics.asterix.dataflow.data.nontagged.serde.AInt16SerializerDeserializer;
+import edu.uci.ics.asterix.dataflow.data.nontagged.serde.AInt32SerializerDeserializer;
+import edu.uci.ics.asterix.dataflow.data.nontagged.serde.AInt8SerializerDeserializer;
+import edu.uci.ics.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
+import edu.uci.ics.asterix.om.base.AMutableTime;
+import edu.uci.ics.asterix.om.base.ANull;
+import edu.uci.ics.asterix.om.base.ATime;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
+import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
+import edu.uci.ics.asterix.om.types.ATypeTag;
+import edu.uci.ics.asterix.om.types.BuiltinType;
+import edu.uci.ics.asterix.runtime.evaluators.base.AbstractScalarFunctionDynamicDescriptor;
+import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
+import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluator;
+import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory;
+import edu.uci.ics.hyracks.api.dataflow.value.ISerializerDeserializer;
+import edu.uci.ics.hyracks.api.exceptions.HyracksDataException;
+import edu.uci.ics.hyracks.data.std.api.IDataOutputProvider;
+import edu.uci.ics.hyracks.data.std.util.ArrayBackedValueStorage;
+import edu.uci.ics.hyracks.dataflow.common.data.accessors.IFrameTupleReference;
+
+public class TimeFromUnixTimeInMsDescriptor extends AbstractScalarFunctionDynamicDescriptor {
+
+    private final static long serialVersionUID = 1L;
+    public final static FunctionIdentifier FID = new FunctionIdentifier(FunctionConstants.ASTERIX_NS,
+            "time-from-unix-time-in-ms", 1);
+
+    // allowed input types
+    private final static byte SER_NULL_TYPE_TAG = ATypeTag.NULL.serialize();
+    private final static byte SER_INT8_TYPE_TAG = ATypeTag.INT8.serialize();
+    private final static byte SER_INT16_TYPE_TAG = ATypeTag.INT16.serialize();
+    private final static byte SER_INT32_TYPE_TAG = ATypeTag.INT32.serialize();
+
+    public final static IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
+
+        @Override
+        public IFunctionDescriptor createFunctionDescriptor() {
+            return new TimeFromUnixTimeInMsDescriptor();
+        }
+    };
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.runtime.base.IScalarFunctionDynamicDescriptor#createEvaluatorFactory(edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory[])
+     */
+    @Override
+    public ICopyEvaluatorFactory createEvaluatorFactory(final ICopyEvaluatorFactory[] args) throws AlgebricksException {
+        return new ICopyEvaluatorFactory() {
+
+            private static final long serialVersionUID = 1L;
+
+            @Override
+            public ICopyEvaluator createEvaluator(final IDataOutputProvider output) throws AlgebricksException {
+                return new ICopyEvaluator() {
+
+                    private DataOutput out = output.getDataOutput();
+                    private ArrayBackedValueStorage argOut = new ArrayBackedValueStorage();
+                    private ICopyEvaluator eval = args[0].createEvaluator(argOut);
+
+                    // possible output types
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<ATime> timeSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.ATIME);
+                    @SuppressWarnings("unchecked")
+                    private ISerializerDeserializer<ANull> nullSerde = AqlSerializerDeserializerProvider.INSTANCE
+                            .getSerializerDeserializer(BuiltinType.ANULL);
+
+                    private AMutableTime aTime = new AMutableTime(0);
+
+                    @Override
+                    public void evaluate(IFrameTupleReference tuple) throws AlgebricksException {
+                        argOut.reset();
+                        eval.evaluate(tuple);
+                        try {
+                            if (argOut.getByteArray()[0] == SER_NULL_TYPE_TAG) {
+                                nullSerde.serialize(ANull.NULL, out);
+                            } else {
+                                if (argOut.getByteArray()[0] == SER_INT8_TYPE_TAG) {
+                                    aTime.setValue(AInt8SerializerDeserializer.getByte(argOut.getByteArray(), 1));
+                                } else if (argOut.getByteArray()[0] == SER_INT16_TYPE_TAG) {
+                                    aTime.setValue(AInt16SerializerDeserializer.getShort(argOut.getByteArray(), 1));
+                                } else if (argOut.getByteArray()[0] == SER_INT32_TYPE_TAG) {
+                                    aTime.setValue(AInt32SerializerDeserializer.getInt(argOut.getByteArray(), 1));
+                                } else {
+                                    throw new AlgebricksException(
+                                            "Inapplicable input type for function time-from-unix-time-in-ms: expecting integer or null type, but got "
+                                                    + argOut.getByteArray()[0]);
+                                }
+                                timeSerde.serialize(aTime, out);
+                            }
+                        } catch (HyracksDataException hex) {
+                            throw new AlgebricksException(hex);
+                        }
+                    }
+                };
+            }
+        };
+    }
+
+    /* (non-Javadoc)
+     * @see edu.uci.ics.asterix.om.functions.IFunctionDescriptor#getIdentifier()
+     */
+    @Override
+    public FunctionIdentifier getIdentifier() {
+        return FID;
+    }
+}
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/formats/NonTaggedDataFormat.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/formats/NonTaggedDataFormat.java
index 92d4294..a334893 100644
--- a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/formats/NonTaggedDataFormat.java
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/formats/NonTaggedDataFormat.java
@@ -17,6 +17,7 @@
 import edu.uci.ics.asterix.formats.nontagged.AqlBinaryBooleanInspectorImpl;
 import edu.uci.ics.asterix.formats.nontagged.AqlBinaryComparatorFactoryProvider;
 import edu.uci.ics.asterix.formats.nontagged.AqlBinaryHashFunctionFactoryProvider;
+import edu.uci.ics.asterix.formats.nontagged.AqlBinaryHashFunctionFamilyProvider;
 import edu.uci.ics.asterix.formats.nontagged.AqlBinaryIntegerInspector;
 import edu.uci.ics.asterix.formats.nontagged.AqlNormalizedKeyComputerFactoryProvider;
 import edu.uci.ics.asterix.formats.nontagged.AqlPrinterFactoryProvider;
@@ -65,6 +66,13 @@
 import edu.uci.ics.asterix.runtime.aggregates.std.SumAggregateDescriptor;
 import edu.uci.ics.asterix.runtime.aggregates.stream.EmptyStreamAggregateDescriptor;
 import edu.uci.ics.asterix.runtime.aggregates.stream.NonEmptyStreamAggregateDescriptor;
+import edu.uci.ics.asterix.runtime.evaluators.accessors.TemporalDayAccessor;
+import edu.uci.ics.asterix.runtime.evaluators.accessors.TemporalHourAccessor;
+import edu.uci.ics.asterix.runtime.evaluators.accessors.TemporalMillisecondAccessor;
+import edu.uci.ics.asterix.runtime.evaluators.accessors.TemporalMinuteAccessor;
+import edu.uci.ics.asterix.runtime.evaluators.accessors.TemporalMonthAccessor;
+import edu.uci.ics.asterix.runtime.evaluators.accessors.TemporalSecondAccessor;
+import edu.uci.ics.asterix.runtime.evaluators.accessors.TemporalYearAccessor;
 import edu.uci.ics.asterix.runtime.evaluators.accessors.CircleCenterAccessor;
 import edu.uci.ics.asterix.runtime.evaluators.accessors.CircleRadiusAccessor;
 import edu.uci.ics.asterix.runtime.evaluators.accessors.LineRectanglePolygonAccessor;
@@ -84,6 +92,12 @@
 import edu.uci.ics.asterix.runtime.evaluators.constructors.AInt32ConstructorDescriptor;
 import edu.uci.ics.asterix.runtime.evaluators.constructors.AInt64ConstructorDescriptor;
 import edu.uci.ics.asterix.runtime.evaluators.constructors.AInt8ConstructorDescriptor;
+import edu.uci.ics.asterix.runtime.evaluators.constructors.AIntervalFromDateConstructorDescriptor;
+import edu.uci.ics.asterix.runtime.evaluators.constructors.AIntervalFromDateTimeConstructorDescriptor;
+import edu.uci.ics.asterix.runtime.evaluators.constructors.AIntervalFromTimeConstructorDescriptor;
+import edu.uci.ics.asterix.runtime.evaluators.constructors.AIntervalStartFromDateConstructorDescriptor;
+import edu.uci.ics.asterix.runtime.evaluators.constructors.AIntervalStartFromDateTimeConstructorDescriptor;
+import edu.uci.ics.asterix.runtime.evaluators.constructors.AIntervalStartFromTimeConstructorDescriptor;
 import edu.uci.ics.asterix.runtime.evaluators.constructors.ALineConstructorDescriptor;
 import edu.uci.ics.asterix.runtime.evaluators.constructors.ANullConstructorDescriptor;
 import edu.uci.ics.asterix.runtime.evaluators.constructors.APoint3DConstructorDescriptor;
@@ -124,6 +138,7 @@
 import edu.uci.ics.asterix.runtime.evaluators.functions.LenDescriptor;
 import edu.uci.ics.asterix.runtime.evaluators.functions.LikeDescriptor;
 import edu.uci.ics.asterix.runtime.evaluators.functions.NotDescriptor;
+import edu.uci.ics.asterix.runtime.evaluators.functions.NotNullDescriptor;
 import edu.uci.ics.asterix.runtime.evaluators.functions.NumericAbsDescriptor;
 import edu.uci.ics.asterix.runtime.evaluators.functions.NumericAddDescriptor;
 import edu.uci.ics.asterix.runtime.evaluators.functions.NumericCeilingDescriptor;
@@ -152,6 +167,10 @@
 import edu.uci.ics.asterix.runtime.evaluators.functions.SpatialDistanceDescriptor;
 import edu.uci.ics.asterix.runtime.evaluators.functions.SpatialIntersectDescriptor;
 import edu.uci.ics.asterix.runtime.evaluators.functions.StartsWithDescriptor;
+import edu.uci.ics.asterix.runtime.evaluators.functions.SubstringDescriptor;
+import edu.uci.ics.asterix.runtime.evaluators.functions.SwitchCaseDescriptor;
+import edu.uci.ics.asterix.runtime.evaluators.functions.UnorderedListConstructorDescriptor;
+import edu.uci.ics.asterix.runtime.evaluators.functions.WordTokensDescriptor;
 import edu.uci.ics.asterix.runtime.evaluators.functions.StringConcatDescriptor;
 import edu.uci.ics.asterix.runtime.evaluators.functions.StringEndWithDescrtiptor;
 import edu.uci.ics.asterix.runtime.evaluators.functions.StringEqualDescriptor;
@@ -167,11 +186,38 @@
 import edu.uci.ics.asterix.runtime.evaluators.functions.Substring2Descriptor;
 import edu.uci.ics.asterix.runtime.evaluators.functions.SubstringAfterDescriptor;
 import edu.uci.ics.asterix.runtime.evaluators.functions.SubstringBeforeDescriptor;
-import edu.uci.ics.asterix.runtime.evaluators.functions.SubstringDescriptor;
-import edu.uci.ics.asterix.runtime.evaluators.functions.SwitchCaseDescriptor;
-import edu.uci.ics.asterix.runtime.evaluators.functions.UnorderedListConstructorDescriptor;
-import edu.uci.ics.asterix.runtime.evaluators.functions.WordTokensDescriptor;
-import edu.uci.ics.asterix.runtime.evaluators.functions.YearDescriptor;
+import edu.uci.ics.asterix.runtime.evaluators.functions.temporal.AddDateDurationDescriptor;
+import edu.uci.ics.asterix.runtime.evaluators.functions.temporal.AddDatetimeDurationDescriptor;
+import edu.uci.ics.asterix.runtime.evaluators.functions.temporal.AddTimeDurationDescriptor;
+import edu.uci.ics.asterix.runtime.evaluators.functions.temporal.AdjustDateTimeForTimeZoneDescriptor;
+import edu.uci.ics.asterix.runtime.evaluators.functions.temporal.AdjustTimeForTimeZoneDescriptor;
+import edu.uci.ics.asterix.runtime.evaluators.functions.temporal.CalendarDuartionFromDateDescriptor;
+import edu.uci.ics.asterix.runtime.evaluators.functions.temporal.CalendarDurationFromDateTimeDescriptor;
+import edu.uci.ics.asterix.runtime.evaluators.functions.temporal.CurrentDateDescriptor;
+import edu.uci.ics.asterix.runtime.evaluators.functions.temporal.CurrentDateTimeDescriptor;
+import edu.uci.ics.asterix.runtime.evaluators.functions.temporal.CurrentTimeDescriptor;
+import edu.uci.ics.asterix.runtime.evaluators.functions.temporal.DateFromDatetimeDescriptor;
+import edu.uci.ics.asterix.runtime.evaluators.functions.temporal.DateFromUnixTimeInDaysDescriptor;
+import edu.uci.ics.asterix.runtime.evaluators.functions.temporal.DatetimeFromDateAndTimeDescriptor;
+import edu.uci.ics.asterix.runtime.evaluators.functions.temporal.DatetimeFromUnixTimeInMsDescriptor;
+import edu.uci.ics.asterix.runtime.evaluators.functions.temporal.IntervalAfterDescriptor;
+import edu.uci.ics.asterix.runtime.evaluators.functions.temporal.IntervalBeforeDescriptor;
+import edu.uci.ics.asterix.runtime.evaluators.functions.temporal.IntervalCoveredByDescriptor;
+import edu.uci.ics.asterix.runtime.evaluators.functions.temporal.IntervalCoversDescriptor;
+import edu.uci.ics.asterix.runtime.evaluators.functions.temporal.IntervalEndedByDescriptor;
+import edu.uci.ics.asterix.runtime.evaluators.functions.temporal.IntervalEndsDecriptor;
+import edu.uci.ics.asterix.runtime.evaluators.functions.temporal.IntervalMeetsDescriptor;
+import edu.uci.ics.asterix.runtime.evaluators.functions.temporal.IntervalMetByDescriptor;
+import edu.uci.ics.asterix.runtime.evaluators.functions.temporal.OverlapDescriptor;
+import edu.uci.ics.asterix.runtime.evaluators.functions.temporal.IntervalOverlappedByDescriptor;
+import edu.uci.ics.asterix.runtime.evaluators.functions.temporal.IntervalOverlapsDescriptor;
+import edu.uci.ics.asterix.runtime.evaluators.functions.temporal.IntervalStartedByDescriptor;
+import edu.uci.ics.asterix.runtime.evaluators.functions.temporal.IntervalStartsDescriptor;
+import edu.uci.ics.asterix.runtime.evaluators.functions.temporal.SubtractDateDescriptor;
+import edu.uci.ics.asterix.runtime.evaluators.functions.temporal.SubtractDatetimeDescriptor;
+import edu.uci.ics.asterix.runtime.evaluators.functions.temporal.SubtractTimeDescriptor;
+import edu.uci.ics.asterix.runtime.evaluators.functions.temporal.TimeFromDatetimeDescriptor;
+import edu.uci.ics.asterix.runtime.evaluators.functions.temporal.TimeFromUnixTimeInMsDescriptor;
 import edu.uci.ics.asterix.runtime.operators.file.AdmSchemafullRecordParserFactory;
 import edu.uci.ics.asterix.runtime.operators.file.NtDelimitedDataTupleParserFactory;
 import edu.uci.ics.asterix.runtime.runningaggregates.std.TidRunningAggregateDescriptor;
@@ -197,6 +243,7 @@
 import edu.uci.ics.hyracks.algebricks.data.IBinaryBooleanInspectorFactory;
 import edu.uci.ics.hyracks.algebricks.data.IBinaryComparatorFactoryProvider;
 import edu.uci.ics.hyracks.algebricks.data.IBinaryHashFunctionFactoryProvider;
+import edu.uci.ics.hyracks.algebricks.data.IBinaryHashFunctionFamilyProvider;
 import edu.uci.ics.hyracks.algebricks.data.IBinaryIntegerInspectorFactory;
 import edu.uci.ics.hyracks.algebricks.data.INormalizedKeyComputerFactoryProvider;
 import edu.uci.ics.hyracks.algebricks.data.IPrinterFactoryProvider;
@@ -218,52 +265,56 @@
 
 public class NonTaggedDataFormat implements IDataFormat {
 
-    private static boolean registered = false;
+	private static boolean registered = false;
 
-    public static final NonTaggedDataFormat INSTANCE = new NonTaggedDataFormat();
+	public static final NonTaggedDataFormat INSTANCE = new NonTaggedDataFormat();
 
-    private static LogicalVariable METADATA_DUMMY_VAR = new LogicalVariable(-1);
+	private static LogicalVariable METADATA_DUMMY_VAR = new LogicalVariable(-1);
 
-    private static final HashMap<ATypeTag, IValueParserFactory> typeToValueParserFactMap = new HashMap<ATypeTag, IValueParserFactory>();
+	private static final HashMap<ATypeTag, IValueParserFactory> typeToValueParserFactMap = new HashMap<ATypeTag, IValueParserFactory>();
 
-    public static final String NON_TAGGED_DATA_FORMAT = "edu.uci.ics.asterix.runtime.formats.NonTaggedDataFormat";
+	public static final String NON_TAGGED_DATA_FORMAT = "edu.uci.ics.asterix.runtime.formats.NonTaggedDataFormat";
 
-    static {
-        typeToValueParserFactMap.put(ATypeTag.INT32, IntegerParserFactory.INSTANCE);
-        typeToValueParserFactMap.put(ATypeTag.FLOAT, FloatParserFactory.INSTANCE);
-        typeToValueParserFactMap.put(ATypeTag.DOUBLE, DoubleParserFactory.INSTANCE);
-        typeToValueParserFactMap.put(ATypeTag.INT64, LongParserFactory.INSTANCE);
-        typeToValueParserFactMap.put(ATypeTag.STRING, UTF8StringParserFactory.INSTANCE);
-    }
+	static {
+		typeToValueParserFactMap.put(ATypeTag.INT32,
+				IntegerParserFactory.INSTANCE);
+		typeToValueParserFactMap.put(ATypeTag.FLOAT,
+				FloatParserFactory.INSTANCE);
+		typeToValueParserFactMap.put(ATypeTag.DOUBLE,
+				DoubleParserFactory.INSTANCE);
+		typeToValueParserFactMap
+				.put(ATypeTag.INT64, LongParserFactory.INSTANCE);
+		typeToValueParserFactMap.put(ATypeTag.STRING,
+				UTF8StringParserFactory.INSTANCE);
+	}
 
-    public NonTaggedDataFormat() {
-    }
+	public NonTaggedDataFormat() {
+	}
 
-    public void registerRuntimeFunctions() throws AlgebricksException {
+	public void registerRuntimeFunctions() throws AlgebricksException {
 
-        if (registered) {
-            return;
-        }
-        registered = true;
+		if (registered) {
+			return;
+		}
+		registered = true;
 
-        if (FunctionManagerHolder.getFunctionManager() != null) {
-            return;
-        }
+		if (FunctionManagerHolder.getFunctionManager() != null) {
+			return;
+		}
 
-        List<IFunctionDescriptorFactory> temp = new ArrayList<IFunctionDescriptorFactory>();
+		List<IFunctionDescriptorFactory> temp = new ArrayList<IFunctionDescriptorFactory>();
 
-        // format-independent
-        temp.add(ContainsDescriptor.FACTORY);
-        temp.add(EndsWithDescriptor.FACTORY);
-        temp.add(StartsWithDescriptor.FACTORY);
-        temp.add(SubstringDescriptor.FACTORY);
-        temp.add(TidRunningAggregateDescriptor.FACTORY);
+		// format-independent
+		temp.add(ContainsDescriptor.FACTORY);
+		temp.add(EndsWithDescriptor.FACTORY);
+		temp.add(StartsWithDescriptor.FACTORY);
+		temp.add(SubstringDescriptor.FACTORY);
+		temp.add(TidRunningAggregateDescriptor.FACTORY);
 
         // format-dependent
         temp.add(AndDescriptor.FACTORY);
         temp.add(OrDescriptor.FACTORY);
         temp.add(LikeDescriptor.FACTORY);
-        temp.add(YearDescriptor.FACTORY);
         temp.add(ScanCollectionDescriptor.FACTORY);
         temp.add(AnyCollectionMemberDescriptor.FACTORY);
         temp.add(ClosedRecordConstructorDescriptor.FACTORY);
@@ -276,137 +327,189 @@
         temp.add(UnorderedListConstructorDescriptor.FACTORY);
         temp.add(EmbedTypeDescriptor.FACTORY);
 
-        temp.add(NumericAddDescriptor.FACTORY);
-        temp.add(NumericDivideDescriptor.FACTORY);
-        temp.add(NumericMultiplyDescriptor.FACTORY);
-        temp.add(NumericSubtractDescriptor.FACTORY);
-        temp.add(NumericModuloDescriptor.FACTORY);
-        temp.add(IsNullDescriptor.FACTORY);
-        temp.add(NotDescriptor.FACTORY);
-        temp.add(LenDescriptor.FACTORY);
-        temp.add(EmptyStreamAggregateDescriptor.FACTORY);
-        temp.add(NonEmptyStreamAggregateDescriptor.FACTORY);
-        temp.add(RangeDescriptor.FACTORY);
+		temp.add(NumericAddDescriptor.FACTORY);
+		temp.add(NumericDivideDescriptor.FACTORY);
+		temp.add(NumericMultiplyDescriptor.FACTORY);
+		temp.add(NumericSubtractDescriptor.FACTORY);
+		temp.add(NumericModuloDescriptor.FACTORY);
+		temp.add(IsNullDescriptor.FACTORY);
+		temp.add(NotDescriptor.FACTORY);
+		temp.add(LenDescriptor.FACTORY);
+		temp.add(EmptyStreamAggregateDescriptor.FACTORY);
+		temp.add(NonEmptyStreamAggregateDescriptor.FACTORY);
+		temp.add(RangeDescriptor.FACTORY);
 
-        temp.add(NumericAbsDescriptor.FACTORY);
-        temp.add(NumericCeilingDescriptor.FACTORY);
-        temp.add(NumericFloorDescriptor.FACTORY);
-        temp.add(NumericRoundDescriptor.FACTORY);
-        temp.add(NumericRoundHalfToEvenDescriptor.FACTORY);
-        temp.add(NumericRoundHalfToEven2Descriptor.FACTORY);
-        // String functions
-        temp.add(StringEqualDescriptor.FACTORY);
-        temp.add(StringStartWithDescrtiptor.FACTORY);
-        temp.add(StringEndWithDescrtiptor.FACTORY);
-        temp.add(StringMatchesDescriptor.FACTORY);
-        temp.add(StringLowerCaseDescriptor.FACTORY);
-        temp.add(StringMatchesWithFlagDescriptor.FACTORY);
-        temp.add(StringReplaceDescriptor.FACTORY);
-        temp.add(StringReplaceWithFlagsDescriptor.FACTORY);
-        temp.add(StringLengthDescriptor.FACTORY);
-        temp.add(Substring2Descriptor.FACTORY);
-        temp.add(SubstringBeforeDescriptor.FACTORY);
-        temp.add(SubstringAfterDescriptor.FACTORY);
-        temp.add(StringToCodePointDescriptor.FACTORY);
-        temp.add(CodePointToStringDescriptor.FACTORY);
-        temp.add(StringConcatDescriptor.FACTORY);
-        temp.add(StringJoinDescriptor.FACTORY);
+		temp.add(NumericAbsDescriptor.FACTORY);
+		temp.add(NumericCeilingDescriptor.FACTORY);
+		temp.add(NumericFloorDescriptor.FACTORY);
+		temp.add(NumericRoundDescriptor.FACTORY);
+		temp.add(NumericRoundHalfToEvenDescriptor.FACTORY);
+		temp.add(NumericRoundHalfToEven2Descriptor.FACTORY);
+		// String functions
+		temp.add(StringEqualDescriptor.FACTORY);
+		temp.add(StringStartWithDescrtiptor.FACTORY);
+		temp.add(StringEndWithDescrtiptor.FACTORY);
+		temp.add(StringMatchesDescriptor.FACTORY);
+		temp.add(StringLowerCaseDescriptor.FACTORY);
+		temp.add(StringMatchesWithFlagDescriptor.FACTORY);
+		temp.add(StringReplaceDescriptor.FACTORY);
+		temp.add(StringReplaceWithFlagsDescriptor.FACTORY);
+		temp.add(StringLengthDescriptor.FACTORY);
+		temp.add(Substring2Descriptor.FACTORY);
+		temp.add(SubstringBeforeDescriptor.FACTORY);
+		temp.add(SubstringAfterDescriptor.FACTORY);
+		temp.add(StringToCodePointDescriptor.FACTORY);
+		temp.add(CodePointToStringDescriptor.FACTORY);
+		temp.add(StringConcatDescriptor.FACTORY);
+		temp.add(StringJoinDescriptor.FACTORY);
 
-        // aggregates
-        temp.add(ListifyAggregateDescriptor.FACTORY);
-        temp.add(CountAggregateDescriptor.FACTORY);
-        temp.add(AvgAggregateDescriptor.FACTORY);
-        temp.add(LocalAvgAggregateDescriptor.FACTORY);
-        temp.add(GlobalAvgAggregateDescriptor.FACTORY);
-        temp.add(SumAggregateDescriptor.FACTORY);
-        temp.add(LocalSumAggregateDescriptor.FACTORY);
-        temp.add(MaxAggregateDescriptor.FACTORY);
-        temp.add(LocalMaxAggregateDescriptor.FACTORY);
-        temp.add(MinAggregateDescriptor.FACTORY);
-        temp.add(LocalMinAggregateDescriptor.FACTORY);
+		// aggregates
+		temp.add(ListifyAggregateDescriptor.FACTORY);
+		temp.add(CountAggregateDescriptor.FACTORY);
+		temp.add(AvgAggregateDescriptor.FACTORY);
+		temp.add(LocalAvgAggregateDescriptor.FACTORY);
+		temp.add(GlobalAvgAggregateDescriptor.FACTORY);
+		temp.add(SumAggregateDescriptor.FACTORY);
+		temp.add(LocalSumAggregateDescriptor.FACTORY);
+		temp.add(MaxAggregateDescriptor.FACTORY);
+		temp.add(LocalMaxAggregateDescriptor.FACTORY);
+		temp.add(MinAggregateDescriptor.FACTORY);
+		temp.add(LocalMinAggregateDescriptor.FACTORY);
 
-        // serializable aggregates
-        temp.add(SerializableCountAggregateDescriptor.FACTORY);
-        temp.add(SerializableAvgAggregateDescriptor.FACTORY);
-        temp.add(SerializableLocalAvgAggregateDescriptor.FACTORY);
-        temp.add(SerializableGlobalAvgAggregateDescriptor.FACTORY);
-        temp.add(SerializableSumAggregateDescriptor.FACTORY);
-        temp.add(SerializableLocalSumAggregateDescriptor.FACTORY);
+		// serializable aggregates
+		temp.add(SerializableCountAggregateDescriptor.FACTORY);
+		temp.add(SerializableAvgAggregateDescriptor.FACTORY);
+		temp.add(SerializableLocalAvgAggregateDescriptor.FACTORY);
+		temp.add(SerializableGlobalAvgAggregateDescriptor.FACTORY);
+		temp.add(SerializableSumAggregateDescriptor.FACTORY);
+		temp.add(SerializableLocalSumAggregateDescriptor.FACTORY);
 
-        // scalar aggregates
-        temp.add(ScalarCountAggregateDescriptor.FACTORY);
-        temp.add(ScalarAvgAggregateDescriptor.FACTORY);
-        temp.add(ScalarSumAggregateDescriptor.FACTORY);
-        temp.add(ScalarMaxAggregateDescriptor.FACTORY);
-        temp.add(ScalarMinAggregateDescriptor.FACTORY);
+		// scalar aggregates
+		temp.add(ScalarCountAggregateDescriptor.FACTORY);
+		temp.add(ScalarAvgAggregateDescriptor.FACTORY);
+		temp.add(ScalarSumAggregateDescriptor.FACTORY);
+		temp.add(ScalarMaxAggregateDescriptor.FACTORY);
+		temp.add(ScalarMinAggregateDescriptor.FACTORY);
 
-        // new functions - constructors
-        temp.add(ABooleanConstructorDescriptor.FACTORY);
-        temp.add(ANullConstructorDescriptor.FACTORY);
-        temp.add(AStringConstructorDescriptor.FACTORY);
-        temp.add(AInt8ConstructorDescriptor.FACTORY);
-        temp.add(AInt16ConstructorDescriptor.FACTORY);
-        temp.add(AInt32ConstructorDescriptor.FACTORY);
-        temp.add(AInt64ConstructorDescriptor.FACTORY);
-        temp.add(AFloatConstructorDescriptor.FACTORY);
-        temp.add(ADoubleConstructorDescriptor.FACTORY);
-        temp.add(APointConstructorDescriptor.FACTORY);
-        temp.add(APoint3DConstructorDescriptor.FACTORY);
-        temp.add(ALineConstructorDescriptor.FACTORY);
-        temp.add(APolygonConstructorDescriptor.FACTORY);
-        temp.add(ACircleConstructorDescriptor.FACTORY);
-        temp.add(ARectangleConstructorDescriptor.FACTORY);
-        temp.add(ATimeConstructorDescriptor.FACTORY);
-        temp.add(ADateConstructorDescriptor.FACTORY);
-        temp.add(ADateTimeConstructorDescriptor.FACTORY);
-        temp.add(ADurationConstructorDescriptor.FACTORY);
+		// new functions - constructors
+		temp.add(ABooleanConstructorDescriptor.FACTORY);
+		temp.add(ANullConstructorDescriptor.FACTORY);
+		temp.add(AStringConstructorDescriptor.FACTORY);
+		temp.add(AInt8ConstructorDescriptor.FACTORY);
+		temp.add(AInt16ConstructorDescriptor.FACTORY);
+		temp.add(AInt32ConstructorDescriptor.FACTORY);
+		temp.add(AInt64ConstructorDescriptor.FACTORY);
+		temp.add(AFloatConstructorDescriptor.FACTORY);
+		temp.add(ADoubleConstructorDescriptor.FACTORY);
+		temp.add(APointConstructorDescriptor.FACTORY);
+		temp.add(APoint3DConstructorDescriptor.FACTORY);
+		temp.add(ALineConstructorDescriptor.FACTORY);
+		temp.add(APolygonConstructorDescriptor.FACTORY);
+		temp.add(ACircleConstructorDescriptor.FACTORY);
+		temp.add(ARectangleConstructorDescriptor.FACTORY);
+		temp.add(ATimeConstructorDescriptor.FACTORY);
+		temp.add(ADateConstructorDescriptor.FACTORY);
+		temp.add(ADateTimeConstructorDescriptor.FACTORY);
+		temp.add(ADurationConstructorDescriptor.FACTORY);
 
-        // Spatial
-        temp.add(CreatePointDescriptor.FACTORY);
-        temp.add(CreateLineDescriptor.FACTORY);
-        temp.add(CreatePolygonDescriptor.FACTORY);
-        temp.add(CreateCircleDescriptor.FACTORY);
-        temp.add(CreateRectangleDescriptor.FACTORY);
-        temp.add(SpatialAreaDescriptor.FACTORY);
-        temp.add(SpatialDistanceDescriptor.FACTORY);
-        temp.add(SpatialIntersectDescriptor.FACTORY);
-        temp.add(CreateMBRDescriptor.FACTORY);
-        temp.add(SpatialCellDescriptor.FACTORY);
-        temp.add(PointXCoordinateAccessor.FACTORY);
-        temp.add(PointYCoordinateAccessor.FACTORY);
-        temp.add(CircleRadiusAccessor.FACTORY);
-        temp.add(CircleCenterAccessor.FACTORY);
-        temp.add(LineRectanglePolygonAccessor.FACTORY);
+		// Spatial
+		temp.add(CreatePointDescriptor.FACTORY);
+		temp.add(CreateLineDescriptor.FACTORY);
+		temp.add(CreatePolygonDescriptor.FACTORY);
+		temp.add(CreateCircleDescriptor.FACTORY);
+		temp.add(CreateRectangleDescriptor.FACTORY);
+		temp.add(SpatialAreaDescriptor.FACTORY);
+		temp.add(SpatialDistanceDescriptor.FACTORY);
+		temp.add(SpatialIntersectDescriptor.FACTORY);
+		temp.add(CreateMBRDescriptor.FACTORY);
+		temp.add(SpatialCellDescriptor.FACTORY);
+		temp.add(PointXCoordinateAccessor.FACTORY);
+		temp.add(PointYCoordinateAccessor.FACTORY);
+		temp.add(CircleRadiusAccessor.FACTORY);
+		temp.add(CircleCenterAccessor.FACTORY);
+		temp.add(LineRectanglePolygonAccessor.FACTORY);
 
-        // fuzzyjoin function
-        temp.add(FuzzyEqDescriptor.FACTORY);
-        temp.add(SubsetCollectionDescriptor.FACTORY);
-        temp.add(PrefixLenJaccardDescriptor.FACTORY);
+		// fuzzyjoin function
+		temp.add(FuzzyEqDescriptor.FACTORY);
+		temp.add(SubsetCollectionDescriptor.FACTORY);
+		temp.add(PrefixLenJaccardDescriptor.FACTORY);
 
-        temp.add(WordTokensDescriptor.FACTORY);
-        temp.add(HashedWordTokensDescriptor.FACTORY);
-        temp.add(CountHashedWordTokensDescriptor.FACTORY);
+		temp.add(WordTokensDescriptor.FACTORY);
+		temp.add(HashedWordTokensDescriptor.FACTORY);
+		temp.add(CountHashedWordTokensDescriptor.FACTORY);
 
-        temp.add(GramTokensDescriptor.FACTORY);
-        temp.add(HashedGramTokensDescriptor.FACTORY);
-        temp.add(CountHashedGramTokensDescriptor.FACTORY);
+		temp.add(GramTokensDescriptor.FACTORY);
+		temp.add(HashedGramTokensDescriptor.FACTORY);
+		temp.add(CountHashedGramTokensDescriptor.FACTORY);
 
-        temp.add(EditDistanceDescriptor.FACTORY);
-        temp.add(EditDistanceCheckDescriptor.FACTORY);
-        temp.add(EditDistanceStringIsFilterable.FACTORY);
-        temp.add(EditDistanceListIsFilterable.FACTORY);
+		temp.add(EditDistanceDescriptor.FACTORY);
+		temp.add(EditDistanceCheckDescriptor.FACTORY);
+		temp.add(EditDistanceStringIsFilterable.FACTORY);
+		temp.add(EditDistanceListIsFilterable.FACTORY);
 
-        temp.add(SimilarityJaccardDescriptor.FACTORY);
-        temp.add(SimilarityJaccardCheckDescriptor.FACTORY);
-        temp.add(SimilarityJaccardSortedDescriptor.FACTORY);
-        temp.add(SimilarityJaccardSortedCheckDescriptor.FACTORY);
-        temp.add(SimilarityJaccardPrefixDescriptor.FACTORY);
-        temp.add(SimilarityJaccardPrefixCheckDescriptor.FACTORY);
+		temp.add(SimilarityJaccardDescriptor.FACTORY);
+		temp.add(SimilarityJaccardCheckDescriptor.FACTORY);
+		temp.add(SimilarityJaccardSortedDescriptor.FACTORY);
+		temp.add(SimilarityJaccardSortedCheckDescriptor.FACTORY);
+		temp.add(SimilarityJaccardPrefixDescriptor.FACTORY);
+		temp.add(SimilarityJaccardPrefixCheckDescriptor.FACTORY);
 
-        temp.add(SwitchCaseDescriptor.FACTORY);
-        temp.add(RegExpDescriptor.FACTORY);
-        temp.add(InjectFailureDescriptor.FACTORY);
-        temp.add(CastRecordDescriptor.FACTORY);
+		temp.add(SwitchCaseDescriptor.FACTORY);
+		temp.add(RegExpDescriptor.FACTORY);
+		temp.add(InjectFailureDescriptor.FACTORY);
+		temp.add(CastRecordDescriptor.FACTORY);
+		temp.add(NotNullDescriptor.FACTORY);
+
+        // Spatial and temporal type accessors
+        temp.add(TemporalYearAccessor.FACTORY);
+        temp.add(TemporalMonthAccessor.FACTORY);
+        temp.add(TemporalDayAccessor.FACTORY);
+        temp.add(TemporalHourAccessor.FACTORY);
+        temp.add(TemporalMinuteAccessor.FACTORY);
+        temp.add(TemporalSecondAccessor.FACTORY);
+        temp.add(TemporalMillisecondAccessor.FACTORY);
+
+        // Temporal functions
+        temp.add(DateFromUnixTimeInDaysDescriptor.FACTORY);
+        temp.add(DateFromDatetimeDescriptor.FACTORY);
+        temp.add(AddDateDurationDescriptor.FACTORY);
+        temp.add(SubtractDateDescriptor.FACTORY);
+        temp.add(TimeFromUnixTimeInMsDescriptor.FACTORY);
+        temp.add(TimeFromDatetimeDescriptor.FACTORY);
+        temp.add(SubtractTimeDescriptor.FACTORY);
+        temp.add(AddTimeDurationDescriptor.FACTORY);
+        temp.add(DatetimeFromUnixTimeInMsDescriptor.FACTORY);
+        temp.add(DatetimeFromDateAndTimeDescriptor.FACTORY);
+        temp.add(SubtractDatetimeDescriptor.FACTORY);
+        temp.add(AddDatetimeDurationDescriptor.FACTORY);
+        temp.add(CalendarDurationFromDateTimeDescriptor.FACTORY);
+        temp.add(CalendarDuartionFromDateDescriptor.FACTORY);
+        temp.add(AdjustDateTimeForTimeZoneDescriptor.FACTORY);
+        temp.add(AdjustTimeForTimeZoneDescriptor.FACTORY);
+        temp.add(IntervalBeforeDescriptor.FACTORY);
+        temp.add(IntervalAfterDescriptor.FACTORY);
+        temp.add(IntervalMeetsDescriptor.FACTORY);
+        temp.add(IntervalMetByDescriptor.FACTORY);
+        temp.add(IntervalOverlapsDescriptor.FACTORY);
+        temp.add(IntervalOverlappedByDescriptor.FACTORY);
+        temp.add(OverlapDescriptor.FACTORY);
+        temp.add(IntervalStartsDescriptor.FACTORY);
+        temp.add(IntervalStartedByDescriptor.FACTORY);
+        temp.add(IntervalCoversDescriptor.FACTORY);
+        temp.add(IntervalCoveredByDescriptor.FACTORY);
+        temp.add(IntervalEndsDecriptor.FACTORY);
+        temp.add(IntervalEndedByDescriptor.FACTORY);
+        temp.add(CurrentDateDescriptor.FACTORY);
+        temp.add(CurrentTimeDescriptor.FACTORY);
+        temp.add(CurrentDateTimeDescriptor.FACTORY);
+
+        // Interval constructor
+        temp.add(AIntervalFromDateConstructorDescriptor.FACTORY);
+        temp.add(AIntervalFromTimeConstructorDescriptor.FACTORY);
+        temp.add(AIntervalFromDateTimeConstructorDescriptor.FACTORY);
+        temp.add(AIntervalStartFromDateConstructorDescriptor.FACTORY);
+        temp.add(AIntervalStartFromDateTimeConstructorDescriptor.FACTORY);
+        temp.add(AIntervalStartFromTimeConstructorDescriptor.FACTORY);
 
         IFunctionManager mgr = new FunctionManagerImpl();
         for (IFunctionDescriptorFactory fdFactory : temp) {
@@ -415,367 +518,425 @@
         FunctionManagerHolder.setFunctionManager(mgr);
     }
 
-    @Override
-    public IBinaryBooleanInspectorFactory getBinaryBooleanInspectorFactory() {
-        return AqlBinaryBooleanInspectorImpl.FACTORY;
-    }
+	@Override
+	public IBinaryBooleanInspectorFactory getBinaryBooleanInspectorFactory() {
+		return AqlBinaryBooleanInspectorImpl.FACTORY;
+	}
 
-    @Override
-    public IBinaryComparatorFactoryProvider getBinaryComparatorFactoryProvider() {
-        return AqlBinaryComparatorFactoryProvider.INSTANCE;
-    }
+	@Override
+	public IBinaryComparatorFactoryProvider getBinaryComparatorFactoryProvider() {
+		return AqlBinaryComparatorFactoryProvider.INSTANCE;
+	}
 
-    @Override
-    public IBinaryHashFunctionFactoryProvider getBinaryHashFunctionFactoryProvider() {
-        return AqlBinaryHashFunctionFactoryProvider.INSTANCE;
-    }
+	@Override
+	public IBinaryHashFunctionFactoryProvider getBinaryHashFunctionFactoryProvider() {
+		return AqlBinaryHashFunctionFactoryProvider.INSTANCE;
+	}
 
-    @Override
-    public ISerializerDeserializerProvider getSerdeProvider() {
-        return AqlSerializerDeserializerProvider.INSTANCE; // done
-    }
+	@Override
+	public ISerializerDeserializerProvider getSerdeProvider() {
+		return AqlSerializerDeserializerProvider.INSTANCE; // done
+	}
 
-    @Override
-    public ITypeTraitProvider getTypeTraitProvider() {
-        return AqlTypeTraitProvider.INSTANCE;
-    }
+	@Override
+	public ITypeTraitProvider getTypeTraitProvider() {
+		return AqlTypeTraitProvider.INSTANCE;
+	}
 
-    @SuppressWarnings("unchecked")
-    @Override
-    public ICopyEvaluatorFactory getFieldAccessEvaluatorFactory(ARecordType recType, String fldName, int recordColumn)
-            throws AlgebricksException {
-        String[] names = recType.getFieldNames();
-        int n = names.length;
-        for (int i = 0; i < n; i++) {
-            if (names[i].equals(fldName)) {
-                ICopyEvaluatorFactory recordEvalFactory = new ColumnAccessEvalFactory(recordColumn);
-                ArrayBackedValueStorage abvs = new ArrayBackedValueStorage();
-                DataOutput dos = abvs.getDataOutput();
-                try {
-                    AInt32 ai = new AInt32(i);
-                    AqlSerializerDeserializerProvider.INSTANCE.getSerializerDeserializer(ai.getType()).serialize(ai,
-                            dos);
-                } catch (HyracksDataException e) {
-                    throw new AlgebricksException(e);
-                }
-                ICopyEvaluatorFactory fldIndexEvalFactory = new ConstantEvalFactory(Arrays.copyOf(abvs.getByteArray(),
-                        abvs.getLength()));
-                ICopyEvaluatorFactory evalFactory = new FieldAccessByIndexEvalFactory(recordEvalFactory,
-                        fldIndexEvalFactory, recType);
-                return evalFactory;
-            }
-        }
-        throw new AlgebricksException("Could not find field " + fldName + " in the schema.");
-    }
+	@SuppressWarnings("unchecked")
+	@Override
+	public ICopyEvaluatorFactory getFieldAccessEvaluatorFactory(
+			ARecordType recType, String fldName, int recordColumn)
+			throws AlgebricksException {
+		String[] names = recType.getFieldNames();
+		int n = names.length;
+		for (int i = 0; i < n; i++) {
+			if (names[i].equals(fldName)) {
+				ICopyEvaluatorFactory recordEvalFactory = new ColumnAccessEvalFactory(
+						recordColumn);
+				ArrayBackedValueStorage abvs = new ArrayBackedValueStorage();
+				DataOutput dos = abvs.getDataOutput();
+				try {
+					AInt32 ai = new AInt32(i);
+					AqlSerializerDeserializerProvider.INSTANCE
+							.getSerializerDeserializer(ai.getType()).serialize(
+									ai, dos);
+				} catch (HyracksDataException e) {
+					throw new AlgebricksException(e);
+				}
+				ICopyEvaluatorFactory fldIndexEvalFactory = new ConstantEvalFactory(
+						Arrays.copyOf(abvs.getByteArray(), abvs.getLength()));
+				ICopyEvaluatorFactory evalFactory = new FieldAccessByIndexEvalFactory(
+						recordEvalFactory, fldIndexEvalFactory, recType);
+				return evalFactory;
+			}
+		}
+		throw new AlgebricksException("Could not find field " + fldName
+				+ " in the schema.");
+	}
 
-    @SuppressWarnings("unchecked")
-    @Override
-    public ICopyEvaluatorFactory[] createMBRFactory(ARecordType recType, String fldName, int recordColumn, int dimension)
-            throws AlgebricksException {
-        ICopyEvaluatorFactory evalFactory = getFieldAccessEvaluatorFactory(recType, fldName, recordColumn);
-        int numOfFields = dimension * 2;
-        ICopyEvaluatorFactory[] evalFactories = new ICopyEvaluatorFactory[numOfFields];
+	@SuppressWarnings("unchecked")
+	@Override
+	public ICopyEvaluatorFactory[] createMBRFactory(ARecordType recType,
+			String fldName, int recordColumn, int dimension)
+			throws AlgebricksException {
+		ICopyEvaluatorFactory evalFactory = getFieldAccessEvaluatorFactory(
+				recType, fldName, recordColumn);
+		int numOfFields = dimension * 2;
+		ICopyEvaluatorFactory[] evalFactories = new ICopyEvaluatorFactory[numOfFields];
 
-        ArrayBackedValueStorage abvs1 = new ArrayBackedValueStorage();
-        DataOutput dos1 = abvs1.getDataOutput();
-        try {
-            AInt32 ai = new AInt32(dimension);
-            AqlSerializerDeserializerProvider.INSTANCE.getSerializerDeserializer(ai.getType()).serialize(ai, dos1);
-        } catch (HyracksDataException e) {
-            throw new AlgebricksException(e);
-        }
-        ICopyEvaluatorFactory dimensionEvalFactory = new ConstantEvalFactory(Arrays.copyOf(abvs1.getByteArray(),
-                abvs1.getLength()));
+		ArrayBackedValueStorage abvs1 = new ArrayBackedValueStorage();
+		DataOutput dos1 = abvs1.getDataOutput();
+		try {
+			AInt32 ai = new AInt32(dimension);
+			AqlSerializerDeserializerProvider.INSTANCE
+					.getSerializerDeserializer(ai.getType())
+					.serialize(ai, dos1);
+		} catch (HyracksDataException e) {
+			throw new AlgebricksException(e);
+		}
+		ICopyEvaluatorFactory dimensionEvalFactory = new ConstantEvalFactory(
+				Arrays.copyOf(abvs1.getByteArray(), abvs1.getLength()));
 
-        for (int i = 0; i < numOfFields; i++) {
-            ArrayBackedValueStorage abvs2 = new ArrayBackedValueStorage();
-            DataOutput dos2 = abvs2.getDataOutput();
-            try {
-                AInt32 ai = new AInt32(i);
-                AqlSerializerDeserializerProvider.INSTANCE.getSerializerDeserializer(ai.getType()).serialize(ai, dos2);
-            } catch (HyracksDataException e) {
-                throw new AlgebricksException(e);
-            }
-            ICopyEvaluatorFactory coordinateEvalFactory = new ConstantEvalFactory(Arrays.copyOf(abvs2.getByteArray(),
-                    abvs2.getLength()));
+		for (int i = 0; i < numOfFields; i++) {
+			ArrayBackedValueStorage abvs2 = new ArrayBackedValueStorage();
+			DataOutput dos2 = abvs2.getDataOutput();
+			try {
+				AInt32 ai = new AInt32(i);
+				AqlSerializerDeserializerProvider.INSTANCE
+						.getSerializerDeserializer(ai.getType()).serialize(ai,
+								dos2);
+			} catch (HyracksDataException e) {
+				throw new AlgebricksException(e);
+			}
+			ICopyEvaluatorFactory coordinateEvalFactory = new ConstantEvalFactory(
+					Arrays.copyOf(abvs2.getByteArray(), abvs2.getLength()));
 
-            evalFactories[i] = new CreateMBREvalFactory(evalFactory, dimensionEvalFactory, coordinateEvalFactory);
-        }
-        return evalFactories;
-    }
+			evalFactories[i] = new CreateMBREvalFactory(evalFactory,
+					dimensionEvalFactory, coordinateEvalFactory);
+		}
+		return evalFactories;
+	}
 
-    @SuppressWarnings("unchecked")
-    @Override
-    public Triple<ICopyEvaluatorFactory, ScalarFunctionCallExpression, IAType> partitioningEvaluatorFactory(
-            ARecordType recType, String fldName) throws AlgebricksException {
-        String[] names = recType.getFieldNames();
-        int n = names.length;
-        for (int i = 0; i < n; i++) {
-            if (names[i].equals(fldName)) {
-                ICopyEvaluatorFactory recordEvalFactory = new ColumnAccessEvalFactory(
-                        GlobalConfig.DEFAULT_INPUT_DATA_COLUMN);
-                ArrayBackedValueStorage abvs = new ArrayBackedValueStorage();
-                DataOutput dos = abvs.getDataOutput();
-                try {
-                    AInt32 ai = new AInt32(i);
-                    AqlSerializerDeserializerProvider.INSTANCE.getSerializerDeserializer(ai.getType()).serialize(ai,
-                            dos);
-                } catch (HyracksDataException e) {
-                    throw new AlgebricksException(e);
-                }
-                ICopyEvaluatorFactory fldIndexEvalFactory = new ConstantEvalFactory(Arrays.copyOf(abvs.getByteArray(),
-                        abvs.getLength()));
-                ICopyEvaluatorFactory evalFactory = new FieldAccessByIndexEvalFactory(recordEvalFactory,
-                        fldIndexEvalFactory, recType);
-                IFunctionInfo finfoAccess = AsterixBuiltinFunctions
-                        .getAsterixFunctionInfo(AsterixBuiltinFunctions.FIELD_ACCESS_BY_INDEX);
+	@SuppressWarnings("unchecked")
+	@Override
+	public Triple<ICopyEvaluatorFactory, ScalarFunctionCallExpression, IAType> partitioningEvaluatorFactory(
+			ARecordType recType, String fldName) throws AlgebricksException {
+		String[] names = recType.getFieldNames();
+		int n = names.length;
+		for (int i = 0; i < n; i++) {
+			if (names[i].equals(fldName)) {
+				ICopyEvaluatorFactory recordEvalFactory = new ColumnAccessEvalFactory(
+						GlobalConfig.DEFAULT_INPUT_DATA_COLUMN);
+				ArrayBackedValueStorage abvs = new ArrayBackedValueStorage();
+				DataOutput dos = abvs.getDataOutput();
+				try {
+					AInt32 ai = new AInt32(i);
+					AqlSerializerDeserializerProvider.INSTANCE
+							.getSerializerDeserializer(ai.getType()).serialize(
+									ai, dos);
+				} catch (HyracksDataException e) {
+					throw new AlgebricksException(e);
+				}
+				ICopyEvaluatorFactory fldIndexEvalFactory = new ConstantEvalFactory(
+						Arrays.copyOf(abvs.getByteArray(), abvs.getLength()));
+				ICopyEvaluatorFactory evalFactory = new FieldAccessByIndexEvalFactory(
+						recordEvalFactory, fldIndexEvalFactory, recType);
+				IFunctionInfo finfoAccess = AsterixBuiltinFunctions
+						.getAsterixFunctionInfo(AsterixBuiltinFunctions.FIELD_ACCESS_BY_INDEX);
 
-                ScalarFunctionCallExpression partitionFun = new ScalarFunctionCallExpression(finfoAccess,
-                        new MutableObject<ILogicalExpression>(new VariableReferenceExpression(METADATA_DUMMY_VAR)),
-                        new MutableObject<ILogicalExpression>(new ConstantExpression(new AsterixConstantValue(
-                                new AInt32(i)))));
-                return new Triple<ICopyEvaluatorFactory, ScalarFunctionCallExpression, IAType>(evalFactory,
-                        partitionFun, recType.getFieldTypes()[i]);
-            }
-        }
-        throw new AlgebricksException("Could not find field " + fldName + " in the schema.");
-    }
+				ScalarFunctionCallExpression partitionFun = new ScalarFunctionCallExpression(
+						finfoAccess,
+						new MutableObject<ILogicalExpression>(
+								new VariableReferenceExpression(
+										METADATA_DUMMY_VAR)),
+						new MutableObject<ILogicalExpression>(
+								new ConstantExpression(
+										new AsterixConstantValue(new AInt32(i)))));
+				return new Triple<ICopyEvaluatorFactory, ScalarFunctionCallExpression, IAType>(
+						evalFactory, partitionFun, recType.getFieldTypes()[i]);
+			}
+		}
+		throw new AlgebricksException("Could not find field " + fldName
+				+ " in the schema.");
+	}
 
-    @Override
-    public IFunctionDescriptor resolveFunction(ILogicalExpression expr, IVariableTypeEnvironment context)
-            throws AlgebricksException {
-        FunctionIdentifier fnId = ((AbstractFunctionCallExpression) expr).getFunctionIdentifier();
-        IFunctionManager mgr = FunctionManagerHolder.getFunctionManager();
-        IFunctionDescriptor fd = mgr.lookupFunction(fnId);
-        if (fd == null) {
-            throw new AsterixRuntimeException("Unresolved function " + fnId);
-        }
-        typeInference(expr, fd, context);
-        return fd;
-    }
+	@Override
+	public IFunctionDescriptor resolveFunction(ILogicalExpression expr,
+			IVariableTypeEnvironment context) throws AlgebricksException {
+		FunctionIdentifier fnId = ((AbstractFunctionCallExpression) expr)
+				.getFunctionIdentifier();
+		IFunctionManager mgr = FunctionManagerHolder.getFunctionManager();
+		IFunctionDescriptor fd = mgr.lookupFunction(fnId);
+		if (fd == null) {
+			throw new AsterixRuntimeException("Unresolved function " + fnId);
+		}
+		typeInference(expr, fd, context);
+		return fd;
+	}
 
-    private void typeInference(ILogicalExpression expr, IFunctionDescriptor fd, IVariableTypeEnvironment context)
-            throws AlgebricksException {
-        if (fd.getIdentifier().equals(AsterixBuiltinFunctions.LISTIFY)) {
-            AbstractFunctionCallExpression f = (AbstractFunctionCallExpression) expr;
-            if (f.getArguments().size() == 0) {
-                ((ListifyAggregateDescriptor) fd).reset(new AOrderedListType(null, null));
-            } else {
-                IAType itemType = (IAType) context.getType(f.getArguments().get(0).getValue());
-                // Convert UNION types into ANY.
-                if (itemType instanceof AUnionType) {
-                    itemType = BuiltinType.ANY;
-                }
-                ((ListifyAggregateDescriptor) fd).reset(new AOrderedListType(itemType, null));
-            }
-        }
-        if (fd.getIdentifier().equals(AsterixBuiltinFunctions.CAST_RECORD)) {
-            ARecordType rt = (ARecordType) TypeComputerUtilities.getRequiredType((AbstractFunctionCallExpression) expr);
-            ARecordType it = (ARecordType) TypeComputerUtilities.getInputType((AbstractFunctionCallExpression) expr);
-            ((CastRecordDescriptor) fd).reset(rt, it);
-        }
-        if (fd.getIdentifier().equals(AsterixBuiltinFunctions.OPEN_RECORD_CONSTRUCTOR)) {
-            ARecordType rt = (ARecordType) context.getType(expr);
-            ((OpenRecordConstructorDescriptor) fd).reset(rt,
-                    computeOpenFields((AbstractFunctionCallExpression) expr, rt));
-        }
-        if (fd.getIdentifier().equals(AsterixBuiltinFunctions.CLOSED_RECORD_CONSTRUCTOR)) {
-            ((ClosedRecordConstructorDescriptor) fd).reset((ARecordType) context.getType(expr));
-        }
-        if (fd.getIdentifier().equals(AsterixBuiltinFunctions.ORDERED_LIST_CONSTRUCTOR)) {
-            ((OrderedListConstructorDescriptor) fd).reset((AOrderedListType) context.getType(expr));
-        }
-        if (fd.getIdentifier().equals(AsterixBuiltinFunctions.UNORDERED_LIST_CONSTRUCTOR)) {
-            ((UnorderedListConstructorDescriptor) fd).reset((AUnorderedListType) context.getType(expr));
-        }
-        if (fd.getIdentifier().equals(AsterixBuiltinFunctions.FIELD_ACCESS_BY_INDEX)) {
-            AbstractFunctionCallExpression fce = (AbstractFunctionCallExpression) expr;
-            IAType t = (IAType) context.getType(fce.getArguments().get(0).getValue());
-            switch (t.getTypeTag()) {
-                case RECORD: {
-                    ARecordType recType = (ARecordType) t;
-                    ((FieldAccessByIndexDescriptor) fd).reset(recType);
-                    break;
-                }
-                case UNION: {
-                    AUnionType unionT = (AUnionType) t;
-                    if (unionT.isNullableType()) {
-                        IAType t2 = unionT.getUnionList().get(1);
-                        if (t2.getTypeTag() == ATypeTag.RECORD) {
-                            ARecordType recType = (ARecordType) t2;
-                            ((FieldAccessByIndexDescriptor) fd).reset(recType);
-                            break;
-                        }
-                    }
-                    throw new NotImplementedException("field-access-by-index for data of type " + t);
-                }
-                default: {
-                    throw new NotImplementedException("field-access-by-index for data of type " + t);
-                }
-            }
-        }
-    }
+	private void typeInference(ILogicalExpression expr, IFunctionDescriptor fd,
+			IVariableTypeEnvironment context) throws AlgebricksException {
+		if (fd.getIdentifier().equals(AsterixBuiltinFunctions.LISTIFY)) {
+			AbstractFunctionCallExpression f = (AbstractFunctionCallExpression) expr;
+			if (f.getArguments().size() == 0) {
+				((ListifyAggregateDescriptor) fd).reset(new AOrderedListType(
+						null, null));
+			} else {
+				IAType itemType = (IAType) context.getType(f.getArguments()
+						.get(0).getValue());
+				// Convert UNION types into ANY.
+				if (itemType instanceof AUnionType) {
+					itemType = BuiltinType.ANY;
+				}
+				((ListifyAggregateDescriptor) fd).reset(new AOrderedListType(
+						itemType, null));
+			}
+		}
+		if (fd.getIdentifier().equals(AsterixBuiltinFunctions.CAST_RECORD)) {
+			ARecordType rt = (ARecordType) TypeComputerUtilities
+					.getRequiredType((AbstractFunctionCallExpression) expr);
+			ARecordType it = (ARecordType) TypeComputerUtilities
+					.getInputType((AbstractFunctionCallExpression) expr);
+			((CastRecordDescriptor) fd).reset(rt, it);
+		}
+		if (fd.getIdentifier().equals(
+				AsterixBuiltinFunctions.OPEN_RECORD_CONSTRUCTOR)) {
+			ARecordType rt = (ARecordType) context.getType(expr);
+			((OpenRecordConstructorDescriptor) fd)
+					.reset(rt,
+							computeOpenFields(
+									(AbstractFunctionCallExpression) expr, rt));
+		}
+		if (fd.getIdentifier().equals(
+				AsterixBuiltinFunctions.CLOSED_RECORD_CONSTRUCTOR)) {
+			((ClosedRecordConstructorDescriptor) fd)
+					.reset((ARecordType) context.getType(expr));
+		}
+		if (fd.getIdentifier().equals(
+				AsterixBuiltinFunctions.ORDERED_LIST_CONSTRUCTOR)) {
+			((OrderedListConstructorDescriptor) fd)
+					.reset((AOrderedListType) context.getType(expr));
+		}
+		if (fd.getIdentifier().equals(
+				AsterixBuiltinFunctions.UNORDERED_LIST_CONSTRUCTOR)) {
+			((UnorderedListConstructorDescriptor) fd)
+					.reset((AUnorderedListType) context.getType(expr));
+		}
+		if (fd.getIdentifier().equals(
+				AsterixBuiltinFunctions.FIELD_ACCESS_BY_INDEX)) {
+			AbstractFunctionCallExpression fce = (AbstractFunctionCallExpression) expr;
+			IAType t = (IAType) context.getType(fce.getArguments().get(0)
+					.getValue());
+			switch (t.getTypeTag()) {
+			case RECORD: {
+				ARecordType recType = (ARecordType) t;
+				((FieldAccessByIndexDescriptor) fd).reset(recType);
+				break;
+			}
+			case UNION: {
+				AUnionType unionT = (AUnionType) t;
+				if (unionT.isNullableType()) {
+					IAType t2 = unionT.getUnionList().get(1);
+					if (t2.getTypeTag() == ATypeTag.RECORD) {
+						ARecordType recType = (ARecordType) t2;
+						((FieldAccessByIndexDescriptor) fd).reset(recType);
+						break;
+					}
+				}
+				throw new NotImplementedException(
+						"field-access-by-index for data of type " + t);
+			}
+			default: {
+				throw new NotImplementedException(
+						"field-access-by-index for data of type " + t);
+			}
+			}
+		}
+	}
 
-    private boolean[] computeOpenFields(AbstractFunctionCallExpression expr, ARecordType recType) {
-        int n = expr.getArguments().size() / 2;
-        boolean[] open = new boolean[n];
-        for (int i = 0; i < n; i++) {
-            Mutable<ILogicalExpression> argRef = expr.getArguments().get(2 * i);
-            ILogicalExpression arg = argRef.getValue();
-            if (arg.getExpressionTag() == LogicalExpressionTag.CONSTANT) {
-                String fn = ((AString) ((AsterixConstantValue) ((ConstantExpression) arg).getValue()).getObject())
-                        .getStringValue();
-                open[i] = true;
-                for (String s : recType.getFieldNames()) {
-                    if (s.equals(fn)) {
-                        open[i] = false;
-                        break;
-                    }
-                }
-            } else {
-                open[i] = true;
-            }
-        }
-        return open;
-    }
+	private boolean[] computeOpenFields(AbstractFunctionCallExpression expr,
+			ARecordType recType) {
+		int n = expr.getArguments().size() / 2;
+		boolean[] open = new boolean[n];
+		for (int i = 0; i < n; i++) {
+			Mutable<ILogicalExpression> argRef = expr.getArguments().get(2 * i);
+			ILogicalExpression arg = argRef.getValue();
+			if (arg.getExpressionTag() == LogicalExpressionTag.CONSTANT) {
+				String fn = ((AString) ((AsterixConstantValue) ((ConstantExpression) arg)
+						.getValue()).getObject()).getStringValue();
+				open[i] = true;
+				for (String s : recType.getFieldNames()) {
+					if (s.equals(fn)) {
+						open[i] = false;
+						break;
+					}
+				}
+			} else {
+				open[i] = true;
+			}
+		}
+		return open;
+	}
 
-    @Override
-    public IPrinterFactoryProvider getPrinterFactoryProvider() {
-        return AqlPrinterFactoryProvider.INSTANCE;
-    }
+	@Override
+	public IPrinterFactoryProvider getPrinterFactoryProvider() {
+		return AqlPrinterFactoryProvider.INSTANCE;
+	}
 
-    @SuppressWarnings("unchecked")
-    @Override
-    public ICopyEvaluatorFactory getConstantEvalFactory(IAlgebricksConstantValue value) throws AlgebricksException {
-        IAObject obj = null;
-        if (value.isNull()) {
-            obj = ANull.NULL;
-        } else if (value.isTrue()) {
-            obj = ABoolean.TRUE;
-        } else if (value.isFalse()) {
-            obj = ABoolean.FALSE;
-        } else {
-            AsterixConstantValue acv = (AsterixConstantValue) value;
-            obj = acv.getObject();
-        }
-        ArrayBackedValueStorage abvs = new ArrayBackedValueStorage();
-        DataOutput dos = abvs.getDataOutput();
-        try {
-            AqlSerializerDeserializerProvider.INSTANCE.getSerializerDeserializer(obj.getType()).serialize(obj, dos);
-        } catch (HyracksDataException e) {
-            throw new AlgebricksException(e);
-        }
-        return new ConstantEvalFactory(Arrays.copyOf(abvs.getByteArray(), abvs.getLength()));
-    }
+	@SuppressWarnings("unchecked")
+	@Override
+	public ICopyEvaluatorFactory getConstantEvalFactory(
+			IAlgebricksConstantValue value) throws AlgebricksException {
+		IAObject obj = null;
+		if (value.isNull()) {
+			obj = ANull.NULL;
+		} else if (value.isTrue()) {
+			obj = ABoolean.TRUE;
+		} else if (value.isFalse()) {
+			obj = ABoolean.FALSE;
+		} else {
+			AsterixConstantValue acv = (AsterixConstantValue) value;
+			obj = acv.getObject();
+		}
+		ArrayBackedValueStorage abvs = new ArrayBackedValueStorage();
+		DataOutput dos = abvs.getDataOutput();
+		try {
+			AqlSerializerDeserializerProvider.INSTANCE
+					.getSerializerDeserializer(obj.getType()).serialize(obj,
+							dos);
+		} catch (HyracksDataException e) {
+			throw new AlgebricksException(e);
+		}
+		return new ConstantEvalFactory(Arrays.copyOf(abvs.getByteArray(),
+				abvs.getLength()));
+	}
 
-    @Override
-    public IBinaryIntegerInspectorFactory getBinaryIntegerInspectorFactory() {
-        return AqlBinaryIntegerInspector.FACTORY;
-    }
+	@Override
+	public IBinaryIntegerInspectorFactory getBinaryIntegerInspectorFactory() {
+		return AqlBinaryIntegerInspector.FACTORY;
+	}
 
-    @Override
-    public ITupleParserFactory createTupleParser(ARecordType recType, IParseFileSplitsDecl decl) {
-        if (decl.isDelimitedFileFormat()) {
-            int n = recType.getFieldTypes().length;
-            IValueParserFactory[] fieldParserFactories = new IValueParserFactory[n];
-            for (int i = 0; i < n; i++) {
-                ATypeTag tag = recType.getFieldTypes()[i].getTypeTag();
-                IValueParserFactory vpf = typeToValueParserFactMap.get(tag);
-                if (vpf == null) {
-                    throw new NotImplementedException("No value parser factory for delimited fields of type " + tag);
-                }
-                fieldParserFactories[i] = vpf;
-            }
-            return new NtDelimitedDataTupleParserFactory(recType, fieldParserFactories, decl.getDelimChar());
-        } else {
-            return new AdmSchemafullRecordParserFactory(recType);
-        }
-    }
+	@Override
+	public ITupleParserFactory createTupleParser(ARecordType recType,
+			IParseFileSplitsDecl decl) {
+		if (decl.isDelimitedFileFormat()) {
+			int n = recType.getFieldTypes().length;
+			IValueParserFactory[] fieldParserFactories = new IValueParserFactory[n];
+			for (int i = 0; i < n; i++) {
+				ATypeTag tag = recType.getFieldTypes()[i].getTypeTag();
+				IValueParserFactory vpf = typeToValueParserFactMap.get(tag);
+				if (vpf == null) {
+					throw new NotImplementedException(
+							"No value parser factory for delimited fields of type "
+									+ tag);
+				}
+				fieldParserFactories[i] = vpf;
+			}
+			return new NtDelimitedDataTupleParserFactory(recType,
+					fieldParserFactories, decl.getDelimChar());
+		} else {
+			return new AdmSchemafullRecordParserFactory(recType);
+		}
+	}
 
-    @Override
-    public ITupleParserFactory createTupleParser(ARecordType recType, boolean delimitedFormat, Character delimiter) {
-        if (delimitedFormat) {
-            int n = recType.getFieldTypes().length;
-            IValueParserFactory[] fieldParserFactories = new IValueParserFactory[n];
-            for (int i = 0; i < n; i++) {
-                ATypeTag tag = recType.getFieldTypes()[i].getTypeTag();
-                IValueParserFactory vpf = typeToValueParserFactMap.get(tag);
-                if (vpf == null) {
-                    throw new NotImplementedException("No value parser factory for delimited fields of type " + tag);
-                }
-                fieldParserFactories[i] = vpf;
-            }
-            return new NtDelimitedDataTupleParserFactory(recType, fieldParserFactories, delimiter);
-        } else {
-            return new AdmSchemafullRecordParserFactory(recType);
-        }
-    }
+	@Override
+	public ITupleParserFactory createTupleParser(ARecordType recType,
+			boolean delimitedFormat, Character delimiter) {
+		if (delimitedFormat) {
+			int n = recType.getFieldTypes().length;
+			IValueParserFactory[] fieldParserFactories = new IValueParserFactory[n];
+			for (int i = 0; i < n; i++) {
+				ATypeTag tag = recType.getFieldTypes()[i].getTypeTag();
+				IValueParserFactory vpf = typeToValueParserFactMap.get(tag);
+				if (vpf == null) {
+					throw new NotImplementedException(
+							"No value parser factory for delimited fields of type "
+									+ tag);
+				}
+				fieldParserFactories[i] = vpf;
+			}
+			return new NtDelimitedDataTupleParserFactory(recType,
+					fieldParserFactories, delimiter);
+		} else {
+			return new AdmSchemafullRecordParserFactory(recType);
+		}
+	}
 
-    @Override
-    public INullWriterFactory getNullWriterFactory() {
-        return AqlNullWriterFactory.INSTANCE;
-    }
+	@Override
+	public INullWriterFactory getNullWriterFactory() {
+		return AqlNullWriterFactory.INSTANCE;
+	}
 
-    @Override
-    public IExpressionEvalSizeComputer getExpressionEvalSizeComputer() {
-        return new IExpressionEvalSizeComputer() {
-            @Override
-            public int getEvalSize(ILogicalExpression expr, IVariableEvalSizeEnvironment env)
-                    throws AlgebricksException {
-                switch (expr.getExpressionTag()) {
-                    case CONSTANT: {
-                        ConstantExpression c = (ConstantExpression) expr;
-                        if (c == ConstantExpression.NULL) {
-                            return 1;
-                        } else if (c == ConstantExpression.FALSE || c == ConstantExpression.TRUE) {
-                            return 2;
-                        } else {
-                            AsterixConstantValue acv = (AsterixConstantValue) c.getValue();
-                            IAObject o = acv.getObject();
-                            switch (o.getType().getTypeTag()) {
-                                case DOUBLE: {
-                                    return 9;
-                                }
-                                case BOOLEAN: {
-                                    return 2;
-                                }
-                                case NULL: {
-                                    return 1;
-                                }
-                                case INT32: {
-                                    return 5;
-                                }
-                                case INT64: {
-                                    return 9;
-                                }
-                                default: {
-                                    // TODO
-                                    return -1;
-                                }
-                            }
-                        }
-                    }
-                    case FUNCTION_CALL: {
-                        AbstractFunctionCallExpression f = (AbstractFunctionCallExpression) expr;
-                        if (f.getFunctionIdentifier().equals(AsterixBuiltinFunctions.TID)) {
-                            return 5;
-                        } else {
-                            // TODO
-                            return -1;
-                        }
-                    }
-                    default: {
-                        // TODO
-                        return -1;
-                    }
-                }
-            }
-        };
-    }
+	@Override
+	public IExpressionEvalSizeComputer getExpressionEvalSizeComputer() {
+		return new IExpressionEvalSizeComputer() {
+			@Override
+			public int getEvalSize(ILogicalExpression expr,
+					IVariableEvalSizeEnvironment env)
+					throws AlgebricksException {
+				switch (expr.getExpressionTag()) {
+				case CONSTANT: {
+					ConstantExpression c = (ConstantExpression) expr;
+					if (c == ConstantExpression.NULL) {
+						return 1;
+					} else if (c == ConstantExpression.FALSE
+							|| c == ConstantExpression.TRUE) {
+						return 2;
+					} else {
+						AsterixConstantValue acv = (AsterixConstantValue) c
+								.getValue();
+						IAObject o = acv.getObject();
+						switch (o.getType().getTypeTag()) {
+						case DOUBLE: {
+							return 9;
+						}
+						case BOOLEAN: {
+							return 2;
+						}
+						case NULL: {
+							return 1;
+						}
+						case INT32: {
+							return 5;
+						}
+						case INT64: {
+							return 9;
+						}
+						default: {
+							// TODO
+							return -1;
+						}
+						}
+					}
+				}
+				case FUNCTION_CALL: {
+					AbstractFunctionCallExpression f = (AbstractFunctionCallExpression) expr;
+					if (f.getFunctionIdentifier().equals(
+							AsterixBuiltinFunctions.TID)) {
+						return 5;
+					} else {
+						// TODO
+						return -1;
+					}
+				}
+				default: {
+					// TODO
+					return -1;
+				}
+				}
+			}
+		};
+	}
 
-    @Override
-    public INormalizedKeyComputerFactoryProvider getNormalizedKeyComputerFactoryProvider() {
-        return AqlNormalizedKeyComputerFactoryProvider.INSTANCE;
-    }
+	@Override
+	public INormalizedKeyComputerFactoryProvider getNormalizedKeyComputerFactoryProvider() {
+		return AqlNormalizedKeyComputerFactoryProvider.INSTANCE;
+	}
+
+	@Override
+	public IBinaryHashFunctionFamilyProvider getBinaryHashFunctionFamilyProvider() {
+		return AqlBinaryHashFunctionFamilyProvider.INSTANCE;
+	}
 
 }
diff --git a/asterix-runtime/src/main/javacc/nontagged/AdmLexer.jj b/asterix-runtime/src/main/javacc/nontagged/AdmLexer.jj
index f556d54..d94033d 100644
--- a/asterix-runtime/src/main/javacc/nontagged/AdmLexer.jj
+++ b/asterix-runtime/src/main/javacc/nontagged/AdmLexer.jj
@@ -144,13 +144,13 @@
 <DEFAULT>
 TOKEN :
 {
-	<TIMEZONE_LITERAL : (("+"|"-")<INTEGER>(":")<INTEGER>) | ("Z") >
+	<TIMEZONE_LITERAL : (("+"|"-")<DIGIT><DIGIT>(":")<DIGIT><DIGIT>) | (("+"|"-")<DIGIT><DIGIT><DIGIT><DIGIT>) | ("Z") >
 }
 
 <DEFAULT>
 TOKEN :
 {
-	<DATE_LITERAL : ("-")?<INTEGER>("-")<INTEGER>("-")<INTEGER> (<TIMEZONE_LITERAL>)? >
+	<DATE_LITERAL : (("-")?<DIGIT><DIGIT><DIGIT><DIGIT>("-")<DIGIT><DIGIT>("-")<DIGIT><DIGIT>) | (("-")?<DIGIT><DIGIT><DIGIT><DIGIT><DIGIT><DIGIT><DIGIT><DIGIT>) >
 }
 
 <DEFAULT>
@@ -162,7 +162,7 @@
 <DEFAULT>
 TOKEN :
 {
-	<TIME_LITERAL : <INTEGER>(":")<INTEGER>(":")<INTEGER> ( (":")<INTEGER>)? (<TIMEZONE_LITERAL>)? >
+	<TIME_LITERAL : (<DIGIT><DIGIT>(":")<DIGIT><DIGIT>(":")<DIGIT><DIGIT> ( (".")<DIGIT>(<DIGIT>((<DIGIT>)?))?)? ((("+"|"-")<DIGIT><DIGIT>(":")<DIGIT><DIGIT>) | ("Z"))?) | (<DIGIT><DIGIT><DIGIT><DIGIT><DIGIT><DIGIT> (<DIGIT>(<DIGIT>((<DIGIT>)?))?)? ((("+"|"-")<DIGIT><DIGIT><DIGIT><DIGIT>) | ("Z"))?) >
 }
 
 <DEFAULT>
@@ -174,7 +174,7 @@
 <DEFAULT>
 TOKEN :
 {
-	<DATETIME_LITERAL : ("-")? <INTEGER>("-")<INTEGER>("-")<INTEGER>("T")<INTEGER>(":")<INTEGER>(":")<INTEGER> ( (":")<INTEGER>)? (<TIMEZONE_LITERAL>)?>
+	<DATETIME_LITERAL : (("-")?<DIGIT><DIGIT><DIGIT><DIGIT>("-")<DIGIT><DIGIT>("-")<DIGIT><DIGIT>("T")<DIGIT><DIGIT>(":")<DIGIT><DIGIT>(":")<DIGIT><DIGIT> ( (".")<DIGIT>(<DIGIT>((<DIGIT>)?))?)? ((("+"|"-")<DIGIT><DIGIT>(":")<DIGIT><DIGIT>) | ("Z"))?) | (("-")?<DIGIT><DIGIT><DIGIT><DIGIT><DIGIT><DIGIT><DIGIT><DIGIT>("T")<DIGIT><DIGIT><DIGIT><DIGIT><DIGIT><DIGIT> (<DIGIT>(<DIGIT>((<DIGIT>)?))?)? ((("+"|"-")<DIGIT><DIGIT><DIGIT><DIGIT>) | ("Z"))?)>
 }
 
 <DEFAULT>
@@ -186,7 +186,7 @@
 <DEFAULT>
 TOKEN :
 {
-	<DURATION_LITERAL : ("-")? ("D")(<INTEGER>("Y"))?(<INTEGER>("M"))?(<INTEGER>("D"))?(("T")(<INTEGER>("H"))?(<INTEGER>("M"))?(<INTEGER>("S"))?)?>
+	<DURATION_LITERAL : ("-")? ("P")(<INTEGER>("Y"))?(<INTEGER>("M"))?(<INTEGER>("D"))?(("T")(((<INTEGER>("H"))(<INTEGER>("M"))?(<INTEGER>((".")<DIGIT>(<DIGIT>(<DIGIT>)?)?)?("S"))?) | ((<INTEGER>("M"))(<INTEGER>((".")<DIGIT>(<DIGIT>(<DIGIT>)?)?)?("S"))?) | ((<INTEGER>((".")<DIGIT>(<DIGIT>(<DIGIT>)?)?)?("S")))))?>
 }
 
 <DEFAULT>
@@ -197,6 +197,29 @@
 
 <DEFAULT>
 TOKEN :
+{
	<INTERVAL_CONS : ("interval")>
+}
+
+<DEFAULT>
+TOKEN :
+{
+	<TIME_INTERVAL_CONS : ("tinterval")>
+}
+
+<DEFAULT>
+TOKEN :
+{
+	<DATE_INTERVAL_CONS : ("dinterval")>
+}
+
+<DEFAULT>
+TOKEN :
+{
+	<DATETIME_INTERVAL_CONS : ("dtinterval")>
+}
+
+<DEFAULT>
+TOKEN :
 {
 	<#DIGIT : ["0" - "9"]>
 }
diff --git a/asterix-tools/pom.xml b/asterix-tools/pom.xml
index 5a8ea70..62176d9 100644
--- a/asterix-tools/pom.xml
+++ b/asterix-tools/pom.xml
@@ -1,13 +1,12 @@
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 	<modelVersion>4.0.0</modelVersion>
 	<parent>
 		<artifactId>asterix</artifactId>
 		<groupId>edu.uci.ics.asterix</groupId>
 		<version>0.0.4-SNAPSHOT</version>
 	</parent>
-	<groupId>edu.uci.ics.asterix</groupId>
 	<artifactId>asterix-tools</artifactId>
-	<version>0.0.4-SNAPSHOT</version>
 
 	<build>
 		<plugins>
@@ -21,6 +20,29 @@
 				</configuration>
 			</plugin>
 			<plugin>
+				<artifactId>maven-jar-plugin</artifactId>
+				<executions>
+					<execution>
+						<id>aqlclient</id>
+						<goals>
+							<goal>jar</goal>
+						</goals>
+						<phase>package</phase>
+						<configuration>
+							<classifier>aqlclient</classifier>
+							<archive>
+								<manifest>
+									<MainClass>edu.uci.ics.asterix.tools.aqlclient.AqlClient</MainClass>
+								</manifest>
+							</archive>
+							<includes>
+								<include>**/uci/ics/asterix/tools/aqlclient/*</include>
+							</includes>
+						</configuration>
+					</execution>
+				</executions>
+			</plugin>
+			<plugin>
 				<artifactId>maven-surefire-plugin</artifactId>
 				<version>2.7.2</version>
 				<executions>
@@ -112,6 +134,18 @@
 			<scope>compile</scope>
 		</dependency>
 		<dependency>
+			<groupId>org.apache.httpcomponents</groupId>
+			<artifactId>httpclient</artifactId>
+			<version>4.2.2</version>
+			<scope>compile</scope>
+		</dependency>
+		<dependency>
+			<groupId>org.apache.httpcomponents</groupId>
+			<artifactId>httpcore</artifactId>
+			<version>4.2.2</version>
+			<scope>compile</scope>
+		</dependency>
+		<dependency>
 			<groupId>junit</groupId>
 			<artifactId>junit</artifactId>
 			<version>4.8.1</version>
diff --git a/asterix-tools/src/main/java/edu/uci/ics/asterix/tools/aqlclient/AqlClient.java b/asterix-tools/src/main/java/edu/uci/ics/asterix/tools/aqlclient/AqlClient.java
new file mode 100644
index 0000000..911b68b
--- /dev/null
+++ b/asterix-tools/src/main/java/edu/uci/ics/asterix/tools/aqlclient/AqlClient.java
@@ -0,0 +1,176 @@
+/*
+ * Copyright 2009-2010 by The Regents of the University of California
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * you may obtain a copy of the License from
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package edu.uci.ics.asterix.tools.aqlclient;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.http.HttpEntity;
+import org.apache.http.HttpResponse;
+import org.apache.http.NameValuePair;
+import org.apache.http.client.entity.UrlEncodedFormEntity;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.impl.client.DefaultHttpClient;
+import org.apache.http.message.BasicNameValuePair;
+import org.apache.http.util.EntityUtils;
+
+/**
+ * This class is to automate AQL queries for benchmarking.
+ * The code is written by Pouria for the purpose of benchmarking ASTERIX.
+ */
+public class AqlClient {
+
+    static ArrayList<String> qFiles;
+    static ArrayList<String> qNames;
+
+    /*
+     * This code loads a set of AQL-Queries and runs them against Asterix. It
+     * runs the queries for a number of iterations, specified by the user. For
+     * each query it shows the Hyracks time, Asterix Time, and Client time on
+     * the screen, while it also dumps its stats into an output file, to make it
+     * persistent for future use/reference.
+     */
+    public static void main(String args[]) throws Exception {
+        /*
+         * Arguments: args0 - Path to the file, that contains list of query
+         * files. The assumption is that each AQL query, is saved in a file, and
+         * its path is mentioned in arg[0]. Each line of arg[0] file, denotes
+         * one query file. args1 - IP-Address of CC args2 - Path to the output
+         * file, for dumping stats args3 - Number of iterations, you want the
+         * simulation to be run args4 - Set it to true, so you stats, on the
+         * console, as queries are running.
+         */
+        if (args.length != 5) {
+            System.out
+                    .println("Usage: [0]=List-of-Query-Files, [1]=ccIPadr, [2]=outputFile, [3]=Iteration# , [4]=boolean-showOnConsole ");
+            return;
+        }
+        qFiles = new ArrayList<String>();
+        qNames = new ArrayList<String>();
+
+        loadQueriesPaths(args[0]);
+        String ccUrl = args[1];
+        String outputFile = args[2];
+        int iteration = Integer.parseInt(args[3]);
+        boolean showOnConsole = Boolean.parseBoolean(args[4]);
+
+        PrintWriter pw = new PrintWriter(new File(outputFile));
+        pw.println("Code\tStatus\tName\tHyracksTime\tAsterixTime\tClientTime\n");
+
+        DefaultHttpClient httpclient = new DefaultHttpClient();
+        HttpPost httpPost = new HttpPost("http://" + ccUrl + ":19001");
+        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
+        nvps.add(new BasicNameValuePair("hyracks-port", "1098"));
+        nvps.add(new BasicNameValuePair("hyracks-ip", ccUrl));
+        nvps.add(new BasicNameValuePair("display-result", "true"));
+        nvps.add(new BasicNameValuePair("query", null)); // it will get its
+                                                         // value in the loop
+                                                         // below
+
+        int ixToremove = nvps.size() - 1;
+        try {
+            for (int i = 0; i < iteration; i++) {
+                for (int x = 0; x < qFiles.size(); x++) {
+                    nvps.remove(ixToremove);
+                    String query = readQueryFromFile(qFiles.get(x));
+                    String qName = qNames.get(x);
+                    System.out.println("\n\nNow Running Query " + qName + " in iteration " + i);
+                    nvps.add(new BasicNameValuePair("query", query));
+
+                    httpPost.setEntity(new UrlEncodedFormEntity(nvps));
+                    long s = System.currentTimeMillis();
+                    HttpResponse response = httpclient.execute(httpPost);
+                    long e = System.currentTimeMillis();
+
+                    String status = response.getStatusLine().toString();
+                    HttpEntity entity = response.getEntity();
+                    String content = EntityUtils.toString(entity);
+                    EntityUtils.consume(entity);
+
+                    double[] times = extractStats(content);
+                    double endToend = ((double) (e - s)) / 1000.00; // This is
+                                                                    // the
+                                                                    // client-time
+                                                                    // (end to
+                                                                    // end delay
+                                                                    // from
+                                                                    // client's
+                                                                    // perspective)
+                    pw.print(status + "\t" + qName + "\t" + times[0] + "\t" + times[1] + "\t" + endToend + "\n");
+
+                    if (showOnConsole) {
+                        // System.out.println("Iteration "+i+"\n"+content+"\n");
+                        // //Uncomment this line, if you want to see the whole
+                        // content of the returned HTML page
+                        System.out.print(qName + "\t" + status + "\t" + times[0] + "\t" + times[1] + "\t" + endToend
+                                + " (iteration " + (i) + ")\n");
+                    }
+                }
+                pw.println();
+            }
+        } finally {
+            pw.close();
+            httpPost.releaseConnection();
+        }
+
+    }
+
+    // Assumption: It contains one query file path per line
+    private static void loadQueriesPaths(String qFilesPath) throws Exception {
+        BufferedReader in = new BufferedReader(new FileReader(qFilesPath));
+        String str;
+        while ((str = in.readLine()) != null) {
+            qFiles.add(str.trim());
+            int nameIx = str.lastIndexOf('/');
+            qNames.add(new String(str.substring(nameIx + 1)));
+        }
+        in.close();
+    }
+
+    private static String readQueryFromFile(String filePath) throws Exception {
+        BufferedReader in = new BufferedReader(new FileReader(filePath));
+        String query = "";
+        String str;
+        while ((str = in.readLine()) != null) {
+            query += str + "\n";
+        }
+        in.close();
+        return query;
+    }
+
+    private static double[] extractStats(String content) {
+        int hyracksTimeIx = content.indexOf("<PRE>Duration:");
+        if (hyracksTimeIx < 0) {
+            return new double[] { -1, -1 };
+        }
+        int endHyracksTimeIx = content.indexOf("</PRE>", hyracksTimeIx);
+        double hTime = Double.parseDouble(content.substring(hyracksTimeIx + 14, endHyracksTimeIx));
+
+        int totalTimeSIx = content.indexOf("Duration", endHyracksTimeIx);
+        if (totalTimeSIx < 0) {
+            return new double[] { hTime, -1 };
+        }
+        int totalTimeEIx = content.indexOf("\n", totalTimeSIx);
+        double tTime = Double.parseDouble(content.substring(totalTimeSIx + 10, totalTimeEIx));
+
+        return new double[] { hTime, tTime };
+    }
+
+}
\ No newline at end of file
diff --git a/asterix-transactions/pom.xml b/asterix-transactions/pom.xml
index c440c2a..7db5cd9 100644
--- a/asterix-transactions/pom.xml
+++ b/asterix-transactions/pom.xml
@@ -28,9 +28,6 @@
 	    <dependency>
   		<groupId>edu.uci.ics.hyracks</groupId>
   		<artifactId>hyracks-storage-am-common</artifactId>
-  		<version>0.2.2-SNAPSHOT</version>
-  		<type>jar</type>
-  		<scope>compile</scope>
   	</dependency>
 	</dependencies>
 </project>
diff --git a/pom.xml b/pom.xml
index 506d57d..fadaa0b 100644
--- a/pom.xml
+++ b/pom.xml
@@ -6,6 +6,11 @@
 	<version>0.0.4-SNAPSHOT</version>
 	<packaging>pom</packaging>
 
+    <properties>
+    	<algebricks.version>0.2.3-SNAPSHOT</algebricks.version>
+    	<hyracks.version>0.2.3-SNAPSHOT</hyracks.version>
+    </properties>
+
 	<build>
 		<plugins>
 			<plugin>
@@ -137,4 +142,65 @@
             <optional>true</optional>
         </dependency>
     </dependencies>
+        <dependencyManagement>
+    	<dependencies>
+    		<dependency>
+    			<groupId>edu.uci.ics.hyracks</groupId>
+    			<artifactId>algebricks-compiler</artifactId>
+    			<version>${algebricks.version}</version>
+    		</dependency>
+    		<dependency>
+    			<groupId>edu.uci.ics.hyracks</groupId>
+    			<artifactId>hyracks-dataflow-std</artifactId>
+    			<version>${hyracks.version}</version>
+    		</dependency>
+    		<dependency>
+    			<groupId>edu.uci.ics.hyracks</groupId>
+    			<artifactId>hyracks-control-cc</artifactId>
+    			<version>${hyracks.version}</version>
+    		</dependency>
+    		<dependency>
+    			<groupId>edu.uci.ics.hyracks</groupId>
+    			<artifactId>hyracks-control-nc</artifactId>
+    			<version>${hyracks.version}</version>
+    		</dependency>
+    		<dependency>
+    			<groupId>edu.uci.ics.hyracks</groupId>
+    			<artifactId>hyracks-server</artifactId>
+    			<version>${hyracks.version}</version>
+    		</dependency>
+    		<dependency>
+    			<groupId>edu.uci.ics.hyracks</groupId>
+    			<artifactId>hyracks-cli</artifactId>
+    			<version>${hyracks.version}</version>
+    		</dependency>
+    		<dependency>
+    			<groupId>edu.uci.ics.hyracks</groupId>
+    			<artifactId>hyracks-dataflow-hadoop</artifactId>
+    			<version>${hyracks.version}</version>
+    		</dependency>
+    		<dependency>
+    			<groupId>edu.uci.ics.hyracks</groupId>
+    			<artifactId>hyracks-storage-am-btree</artifactId>
+    			<version>${hyracks.version}</version>
+    		</dependency>
+    		<dependency>
+    			<groupId>edu.uci.ics.hyracks</groupId>
+    			<artifactId>hyracks-storage-am-rtree</artifactId>
+    			<version>${hyracks.version}</version>
+    		</dependency>
+    		<dependency>
+    			<groupId>edu.uci.ics.hyracks</groupId>
+    			<artifactId>
+    				hyracks-storage-am-invertedindex
+    			</artifactId>
+    			<version>${hyracks.version}</version>
+    		</dependency>
+    		<dependency>
+    			<groupId>edu.uci.ics.hyracks</groupId>
+    			<artifactId>hyracks-storage-am-common</artifactId>
+    			<version>${hyracks.version}</version>
+    		</dependency>
+    	</dependencies>
+    </dependencyManagement>
 </project>