Merge branch 'master' into jarodwen/hotfix/function-issues
diff --git a/asterix-app/data/temporal/simpletemp_30.json b/asterix-app/data/temporal/simpletemp_30.json
new file mode 100644
index 0000000..f0a4582
--- /dev/null
+++ b/asterix-app/data/temporal/simpletemp_30.json
@@ -0,0 +1,3 @@
+{ "date": date("4619-11-23"), "time": time("14:29:36.786Z"), "datetime": datetime("2749-01-27T17:27:30.020Z"), "duration": duration("-P474133Y7M854630DT4H40M6.45S"), "year-month-duration": year-month-duration("P193989Y3M"), "day-time-duration": day-time-duration("P4477686DT4H49M31.87S"), "date-interval": interval-date("-9537-08-04, 9656-06-03"), "time-interval": interval-time("12:04:45.689Z, 12:41:59.002Z"), "datetime-interval": interval-datetime("-2640-10-11T17:32:15.675Z, 4104-02-01T05:59:11.902Z") }
+{ "date": date("-9971-09-24"), "time": time("11:38:17.154Z"), "datetime": datetime("1259-11-13T09:49:11.852Z"), "duration": duration("P473653Y9M4566143DT10H20M53.61S"), "year-month-duration": year-month-duration("P148233Y10M"), "day-time-duration": day-time-duration("-P7236357DT2H56M56.164S"), "date-interval": interval-date("-0255-09-06, 4925-05-03"), "time-interval": interval-time("23:10:45.169Z, 01:37:48.736Z"), "datetime-interval": interval-datetime("0534-12-08T08:20:31.487Z, 6778-02-16T22:40:21.653Z") }
+{ "date": date("7986-11-25"), "time": time("12:49:39.736Z"), "datetime": datetime("-8337-01-30T15:23:07.598Z"), "duration": duration("-P184484Y7M2241423DT10H42M49.500S"), "year-month-duration": year-month-duration("-P546031Y3M"), "day-time-duration": day-time-duration("P2623386DT10H32M31.983S"), "date-interval": interval-date("-4514-05-24, 3337-08-26"), "time-interval": interval-time("04:16:42.321Z, 02:22:56.816Z"), "datetime-interval": interval-datetime("2129-12-12T13:18:35.758Z, 8647-07-01T13:10:19.691Z") }
diff --git a/asterix-app/src/test/resources/runtimets/queries/string/substr04/substr04.1.ddl.aql b/asterix-app/src/test/resources/runtimets/queries/string/substr04/substr04.1.ddl.aql
index 280e52c..d595848 100644
--- a/asterix-app/src/test/resources/runtimets/queries/string/substr04/substr04.1.ddl.aql
+++ b/asterix-app/src/test/resources/runtimets/queries/string/substr04/substr04.1.ddl.aql
@@ -1,6 +1,6 @@
 /*
  * Testcase Name  : substr04.aql
- * Description    : Test substring2(string,position,position) built in function.
+ * Description    : Test substring(string,position,position) built in function.
  * Success        : Yes
  * Date           : 18th April 2012
  */
diff --git a/asterix-app/src/test/resources/runtimets/queries/string/substr04/substr04.2.update.aql b/asterix-app/src/test/resources/runtimets/queries/string/substr04/substr04.2.update.aql
index 280e52c..d595848 100644
--- a/asterix-app/src/test/resources/runtimets/queries/string/substr04/substr04.2.update.aql
+++ b/asterix-app/src/test/resources/runtimets/queries/string/substr04/substr04.2.update.aql
@@ -1,6 +1,6 @@
 /*
  * Testcase Name  : substr04.aql
- * Description    : Test substring2(string,position,position) built in function.
+ * Description    : Test substring(string,position,position) built in function.
  * Success        : Yes
  * Date           : 18th April 2012
  */
diff --git a/asterix-app/src/test/resources/runtimets/queries/string/substr04/substr04.3.query.aql b/asterix-app/src/test/resources/runtimets/queries/string/substr04/substr04.3.query.aql
index 0f5b1ff..69ff8ab 100644
--- a/asterix-app/src/test/resources/runtimets/queries/string/substr04/substr04.3.query.aql
+++ b/asterix-app/src/test/resources/runtimets/queries/string/substr04/substr04.3.query.aql
@@ -1,19 +1,17 @@
 /*
  * Testcase Name  : substr04.aql
- * Description    : Test substring2(string,position,position) built in function.
+ * Description    : Test substring(string, position, length) built in function.
  * Success        : Yes
  * Date           : 18th April 2012
  */
 
-for $a in [ substring2("hello world",7,11),
-substring("hello world",1,11),
-substring("hello world",3,7),
-substring("ABCD",3,6),
-substring("ABCD",0,4),
-substring("UC Irvine",4,string-length("UC Irvine")),
-substring("UC Irvine",0,string-length("UC Irvine")),
-substring("UC Irvine",1,string-length("UC Irvine")),
-substring(substring("UC Irvine",4),0,string-length("Irvine")),
-substring(substring("UC Irvine",4),0,(string-length("Irvine")/2))
+for $a in [ substring("hello world", 7, 5),
+substring("hello world", 1, 11),
+substring("hello world", 3, 9),
+substring("ABCD", 3, 2),
+substring("ABCD", 1, 4),
+substring("UC Irvine", 4, string-length("UC Irvine") - 3),
+substring("UC Irvine", 1, string-length("UC Irvine")),
+substring(substring("UC Irvine", 4), 1, string-length("Irvine"))
 ]
 return $a
diff --git a/asterix-app/src/test/resources/runtimets/queries/string/substr05/substr05.1.ddl.aql b/asterix-app/src/test/resources/runtimets/queries/string/substr05/substr05.1.ddl.aql
index cd3bee1..6a77034 100644
--- a/asterix-app/src/test/resources/runtimets/queries/string/substr05/substr05.1.ddl.aql
+++ b/asterix-app/src/test/resources/runtimets/queries/string/substr05/substr05.1.ddl.aql
@@ -1,6 +1,6 @@
 /*
  * Testcase Name  : substr05.aql
- * Description    : Test substring2(string,position,position) built in function.
+ * Description    : Test substring(string,position,position) built in function.
  * Success        : Yes
  * Date           : 19th April 2012
  */
diff --git a/asterix-app/src/test/resources/runtimets/queries/string/substr05/substr05.2.update.aql b/asterix-app/src/test/resources/runtimets/queries/string/substr05/substr05.2.update.aql
index da796c7..680f0db 100644
--- a/asterix-app/src/test/resources/runtimets/queries/string/substr05/substr05.2.update.aql
+++ b/asterix-app/src/test/resources/runtimets/queries/string/substr05/substr05.2.update.aql
@@ -1,6 +1,6 @@
 /*
  * Testcase Name  : substr05.aql
- * Description    : Test substring2(string,position,position) built in function.
+ * Description    : Test substring(string,position,position) built in function.
  * Success        : Yes
  * Date           : 19th April 2012
  */
diff --git a/asterix-app/src/test/resources/runtimets/queries/string/substr05/substr05.3.query.aql b/asterix-app/src/test/resources/runtimets/queries/string/substr05/substr05.3.query.aql
index 1b2cfe5..5c0fa4f 100644
--- a/asterix-app/src/test/resources/runtimets/queries/string/substr05/substr05.3.query.aql
+++ b/asterix-app/src/test/resources/runtimets/queries/string/substr05/substr05.3.query.aql
@@ -1,14 +1,14 @@
 /*
  * Testcase Name  : substr05.aql
- * Description    : Test substring2(string,position,position) built in function.
+ * Description    : Test substring(string,position,position) built in function.
  * Success        : Yes
  * Date           : 19th April 2012
  */
 
-// To test substring2 function with string data stored in an internal dataset.
+// To test substring function with string data stored in an internal dataset.
 
 use dataverse test;
 
 for $a in dataset('testdst')
 order by $a.name
-return substring($a.name,4,string-length($a.name));
+return substring($a.name, 4, string-length($a.name) - 3);
diff --git a/asterix-app/src/test/resources/runtimets/queries/temporal/insert_from_ext_ds_2/insert_from_ext_ds_2.1.ddl.aql b/asterix-app/src/test/resources/runtimets/queries/temporal/insert_from_ext_ds_2/insert_from_ext_ds_2.1.ddl.aql
new file mode 100644
index 0000000..66d955c
--- /dev/null
+++ b/asterix-app/src/test/resources/runtimets/queries/temporal/insert_from_ext_ds_2/insert_from_ext_ds_2.1.ddl.aql
@@ -0,0 +1,25 @@
+/*
+ * Test case name: insert_from_ext_ds_2
+ * Description: verify external data loading on temporal types
+ * Expected result: success
+ */
+ 
+drop dataverse timeTest if exists;
+create dataverse timeTest;
+use dataverse timeTest;
+
+create type timesType as open {
+    date: date,
+    time: time,
+    datetime: datetime,
+    duration: duration,
+    year-month-duration: year-month-duration,
+    day-time-duration: day-time-duration,
+	date-interval: interval,
+	time-interval: interval,
+	datetime-interval: interval
+}
+
+create dataset timeData(timesType)
+primary key date;
+
diff --git a/asterix-app/src/test/resources/runtimets/queries/temporal/insert_from_ext_ds_2/insert_from_ext_ds_2.2.update.aql b/asterix-app/src/test/resources/runtimets/queries/temporal/insert_from_ext_ds_2/insert_from_ext_ds_2.2.update.aql
new file mode 100644
index 0000000..daff7c6
--- /dev/null
+++ b/asterix-app/src/test/resources/runtimets/queries/temporal/insert_from_ext_ds_2/insert_from_ext_ds_2.2.update.aql
@@ -0,0 +1,4 @@
+use dataverse timeTest;
+
+load dataset timeData using localfs
+(("path"="nc1://data/temporal/simpletemp_30.json"),("format"="adm"));
\ No newline at end of file
diff --git a/asterix-app/src/test/resources/runtimets/queries/temporal/insert_from_ext_ds_2/insert_from_ext_ds_2.3.query.aql b/asterix-app/src/test/resources/runtimets/queries/temporal/insert_from_ext_ds_2/insert_from_ext_ds_2.3.query.aql
new file mode 100644
index 0000000..28549c8
--- /dev/null
+++ b/asterix-app/src/test/resources/runtimets/queries/temporal/insert_from_ext_ds_2/insert_from_ext_ds_2.3.query.aql
@@ -0,0 +1,5 @@
+use dataverse timeTest;
+
+for $r in dataset timeData
+order by $r.date
+return $r
\ No newline at end of file
diff --git a/asterix-app/src/test/resources/runtimets/results/string/substr04/substr04.1.adm b/asterix-app/src/test/resources/runtimets/results/string/substr04/substr04.1.adm
index fcd3396..74bd0d6 100644
--- a/asterix-app/src/test/resources/runtimets/results/string/substr04/substr04.1.adm
+++ b/asterix-app/src/test/resources/runtimets/results/string/substr04/substr04.1.adm
@@ -5,6 +5,4 @@
 "ABCD"
 "Irvine"
 "UC Irvine"
-"UC Irvine"
-"Irvine"
 "Irvine"
diff --git a/asterix-app/src/test/resources/runtimets/results/temporal/insert_from_ext_ds_2/insert_from_ext_ds_2.1.adm b/asterix-app/src/test/resources/runtimets/results/temporal/insert_from_ext_ds_2/insert_from_ext_ds_2.1.adm
new file mode 100644
index 0000000..4d1cf59
--- /dev/null
+++ b/asterix-app/src/test/resources/runtimets/results/temporal/insert_from_ext_ds_2/insert_from_ext_ds_2.1.adm
@@ -0,0 +1,3 @@
+{ "date": date("-9971-09-24"), "time": time("11:38:17.154Z"), "datetime": datetime("1259-11-13T09:49:11.852Z"), "duration": duration("P473653Y9M4566143DT10H20M53.61S"), "year-month-duration": year-month-duration("P148233Y10M"), "day-time-duration": day-time-duration("-P7236357DT2H56M56.164S"), "date-interval": interval-date("-0255-09-06, 4925-05-03"), "time-interval": interval-time("23:10:45.169Z, 01:37:48.736Z"), "datetime-interval": interval-datetime("0534-12-08T08:20:31.487Z, 6778-02-16T22:40:21.653Z") }
+{ "date": date("4619-11-23"), "time": time("14:29:36.786Z"), "datetime": datetime("2749-01-27T17:27:30.020Z"), "duration": duration("-P474133Y7M854630DT4H40M6.45S"), "year-month-duration": year-month-duration("P193989Y3M"), "day-time-duration": day-time-duration("P4477686DT4H49M31.87S"), "date-interval": interval-date("-9537-08-04, 9656-06-03"), "time-interval": interval-time("12:04:45.689Z, 12:41:59.002Z"), "datetime-interval": interval-datetime("-2640-10-11T17:32:15.675Z, 4104-02-01T05:59:11.902Z") }
+{ "date": date("7986-11-25"), "time": time("12:49:39.736Z"), "datetime": datetime("-8337-01-30T15:23:07.598Z"), "duration": duration("-P184484Y7M2241423DT10H42M49.500S"), "year-month-duration": year-month-duration("-P546031Y3M"), "day-time-duration": day-time-duration("P2623386DT10H32M31.983S"), "date-interval": interval-date("-4514-05-24, 3337-08-26"), "time-interval": interval-time("04:16:42.321Z, 02:22:56.816Z"), "datetime-interval": interval-datetime("2129-12-12T13:18:35.758Z, 8647-07-01T13:10:19.691Z") }
\ No newline at end of file
diff --git a/asterix-app/src/test/resources/runtimets/testsuite.xml b/asterix-app/src/test/resources/runtimets/testsuite.xml
index f609bf4..50a3b5c 100644
--- a/asterix-app/src/test/resources/runtimets/testsuite.xml
+++ b/asterix-app/src/test/resources/runtimets/testsuite.xml
@@ -3523,7 +3523,6 @@
         <output-dir compare="Text">substr01</output-dir>
       </compilation-unit>
     </test-case>
-    <!-- Issue no 219
     <test-case FilePath="string">
       <compilation-unit name="substr04">
         <output-dir compare="Text">substr04</output-dir>
@@ -3534,7 +3533,6 @@
         <output-dir compare="Text">substr05</output-dir>
       </compilation-unit>
     </test-case>
-    -->
     <test-case FilePath="string">
       <compilation-unit name="substr06">
         <output-dir compare="Text">substr06</output-dir>
@@ -4264,6 +4262,11 @@
         <output-dir compare="Text">insert_from_ext_ds</output-dir>
       </compilation-unit>
   	</test-case>
+   <test-case FilePath="temporal">
+    <compilation-unit name="insert_from_ext_ds_2">
+        <output-dir compare="Text">insert_from_ext_ds_2</output-dir>
+      </compilation-unit>
+   </test-case>
   	<test-case FilePath="temporal">
   		<compilation-unit name="interval_functions">
         <output-dir compare="Text">interval_functions</output-dir>
diff --git a/asterix-aql/.gitignore b/asterix-aql/.gitignore
new file mode 100644
index 0000000..ea8c4bf
--- /dev/null
+++ b/asterix-aql/.gitignore
@@ -0,0 +1 @@
+/target
diff --git a/asterix-common/.gitignore b/asterix-common/.gitignore
index ea8c4bf..19f2e00 100644
--- a/asterix-common/.gitignore
+++ b/asterix-common/.gitignore
@@ -1 +1,2 @@
 /target
+/target
diff --git a/asterix-events/.gitignore b/asterix-events/.gitignore
new file mode 100644
index 0000000..ea8c4bf
--- /dev/null
+++ b/asterix-events/.gitignore
@@ -0,0 +1 @@
+/target
diff --git a/asterix-installer/.gitignore b/asterix-installer/.gitignore
new file mode 100644
index 0000000..19f2e00
--- /dev/null
+++ b/asterix-installer/.gitignore
@@ -0,0 +1,2 @@
+/target
+/target
diff --git a/asterix-om/.gitignore b/asterix-om/.gitignore
new file mode 100644
index 0000000..ea8c4bf
--- /dev/null
+++ b/asterix-om/.gitignore
@@ -0,0 +1 @@
+/target
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/printers/ADatePrinter.java b/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/printers/ADatePrinter.java
index 327faf1..b7df6ff 100644
--- a/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/printers/ADatePrinter.java
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/printers/ADatePrinter.java
@@ -1,9 +1,11 @@
 package edu.uci.ics.asterix.dataflow.data.nontagged.printers;
 
+import java.io.IOException;
 import java.io.PrintStream;
 
 import edu.uci.ics.asterix.dataflow.data.nontagged.serde.AInt32SerializerDeserializer;
 import edu.uci.ics.asterix.om.base.temporal.GregorianCalendarSystem;
+import edu.uci.ics.asterix.om.base.temporal.GregorianCalendarSystem.Fields;
 import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
 import edu.uci.ics.hyracks.algebricks.data.IPrinter;
 
@@ -22,22 +24,22 @@
     public void print(byte[] b, int s, int l, PrintStream ps) throws AlgebricksException {
         long chrononTime = AInt32SerializerDeserializer.getInt(b, s + 1) * CHRONON_OF_DAY;
 
-        int year = gCalInstance.getYear(chrononTime);
-        int month = gCalInstance.getMonthOfYear(chrononTime, year);
-
         ps.print("date(\"");
-        ps.append(String.format(year < 0 ? "%05d" : "%04d", year)).append("-").append(String.format("%02d", month))
-                .append("-").append(String.format("%02d", gCalInstance.getDayOfMonthYear(chrononTime, year, month)));
+        try {
+            gCalInstance.getExtendStringRepUntilField(chrononTime, 0, ps, Fields.YEAR, Fields.DAY, false);
+        } catch (IOException e) {
+            throw new AlgebricksException(e);
+        }
         ps.print("\")");
     }
 
     public void printString(byte[] b, int s, int l, PrintStream ps) throws AlgebricksException {
         long chrononTime = AInt32SerializerDeserializer.getInt(b, s + 1) * CHRONON_OF_DAY;
 
-        int year = gCalInstance.getYear(chrononTime);
-        int month = gCalInstance.getMonthOfYear(chrononTime, year);
-
-        ps.append(String.format(year < 0 ? "%05d" : "%04d", year)).append("-").append(String.format("%02d", month))
-                .append("-").append(String.format("%02d", gCalInstance.getDayOfMonthYear(chrononTime, year, month)));
+        try {
+            gCalInstance.getExtendStringRepUntilField(chrononTime, 0, ps, Fields.YEAR, Fields.DAY, false);
+        } catch (IOException e) {
+            throw new AlgebricksException(e);
+        }
     }
 }
\ No newline at end of file
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/printers/ADateTimePrinter.java b/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/printers/ADateTimePrinter.java
index 7cf1478..a412cb1 100644
--- a/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/printers/ADateTimePrinter.java
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/printers/ADateTimePrinter.java
@@ -1,9 +1,11 @@
 package edu.uci.ics.asterix.dataflow.data.nontagged.printers;
 
+import java.io.IOException;
 import java.io.PrintStream;
 
 import edu.uci.ics.asterix.dataflow.data.nontagged.serde.AInt64SerializerDeserializer;
 import edu.uci.ics.asterix.om.base.temporal.GregorianCalendarSystem;
+import edu.uci.ics.asterix.om.base.temporal.GregorianCalendarSystem.Fields;
 import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
 import edu.uci.ics.hyracks.algebricks.data.IPrinter;
 
@@ -21,30 +23,25 @@
     public void print(byte[] b, int s, int l, PrintStream ps) throws AlgebricksException {
         long chrononTime = AInt64SerializerDeserializer.getLong(b, s + 1);
 
-        int year = gCalInstance.getYear(chrononTime);
-        int month = gCalInstance.getMonthOfYear(chrononTime, year);
-
         ps.print("datetime(\"");
-        ps.append(String.format(year < 0 ? "%05d" : "%04d", year)).append("-").append(String.format("%02d", month))
-                .append("-").append(String.format("%02d", gCalInstance.getDayOfMonthYear(chrononTime, year, month)))
-                .append("T").append(String.format("%02d", gCalInstance.getHourOfDay(chrononTime))).append(":")
-                .append(String.format("%02d", gCalInstance.getMinOfHour(chrononTime))).append(":")
-                .append(String.format("%02d", gCalInstance.getSecOfMin(chrononTime))).append(".")
-                .append(String.format("%03d", gCalInstance.getMillisOfSec(chrononTime))).append("Z");
+
+        try {
+            gCalInstance.getExtendStringRepUntilField(chrononTime, 0, ps, Fields.YEAR, Fields.MILLISECOND, true);
+        } catch (IOException e) {
+            throw new AlgebricksException(e);
+        }
+
         ps.print("\")");
     }
 
     public void printString(byte[] b, int s, int l, PrintStream ps) throws AlgebricksException {
         long chrononTime = AInt64SerializerDeserializer.getLong(b, s + 1);
 
-        int year = gCalInstance.getYear(chrononTime);
-        int month = gCalInstance.getMonthOfYear(chrononTime, year);
-
-        ps.append(String.format(year < 0 ? "%05d" : "%04d", year)).append("-").append(String.format("%02d", month))
-                .append("-").append(String.format("%02d", gCalInstance.getDayOfMonthYear(chrononTime, year, month)))
-                .append("T").append(String.format("%02d", gCalInstance.getHourOfDay(chrononTime))).append(":")
-                .append(String.format("%02d", gCalInstance.getMinOfHour(chrononTime))).append(":")
-                .append(String.format("%02d", gCalInstance.getSecOfMin(chrononTime))).append(".")
-                .append(String.format("%03d", gCalInstance.getMillisOfSec(chrononTime))).append("Z");
+        try {
+            gCalInstance.getExtendStringRepUntilField(chrononTime, 0, ps, Fields.YEAR, Fields.MILLISECOND, true);
+        } catch (IOException e) {
+            throw new AlgebricksException(e);
+        }
+        
     }
 }
\ No newline at end of file
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/printers/ATimePrinter.java b/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/printers/ATimePrinter.java
index aba6a4b..6550906 100644
--- a/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/printers/ATimePrinter.java
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/dataflow/data/nontagged/printers/ATimePrinter.java
@@ -1,9 +1,11 @@
 package edu.uci.ics.asterix.dataflow.data.nontagged.printers;
 
+import java.io.IOException;
 import java.io.PrintStream;
 
 import edu.uci.ics.asterix.dataflow.data.nontagged.serde.AInt32SerializerDeserializer;
 import edu.uci.ics.asterix.om.base.temporal.GregorianCalendarSystem;
+import edu.uci.ics.asterix.om.base.temporal.GregorianCalendarSystem.Fields;
 import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
 import edu.uci.ics.hyracks.algebricks.data.IPrinter;
 
@@ -22,21 +24,24 @@
         int time = AInt32SerializerDeserializer.getInt(b, s + 1);
 
         ps.print("time(\"");
-        ps.append(String.format("%02d", gCalInstance.getHourOfDay(time))).append(":")
-                .append(String.format("%02d", gCalInstance.getMinOfHour(time))).append(":")
-                .append(String.format("%02d", gCalInstance.getSecOfMin(time))).append(".")
-                .append(String.format("%03d", gCalInstance.getMillisOfSec(time))).append("Z");
+
+        try {
+            gCalInstance.getExtendStringRepUntilField(time, 0, ps, Fields.HOUR, Fields.MILLISECOND, true);
+        } catch (IOException e) {
+            throw new AlgebricksException(e);
+        }
 
         ps.print("\")");
     }
-    
+
     public void printString(byte[] b, int s, int l, PrintStream ps) throws AlgebricksException {
         int time = AInt32SerializerDeserializer.getInt(b, s + 1);
 
-        ps.append(String.format("%02d", gCalInstance.getHourOfDay(time))).append(":")
-                .append(String.format("%02d", gCalInstance.getMinOfHour(time))).append(":")
-                .append(String.format("%02d", gCalInstance.getSecOfMin(time))).append(".")
-                .append(String.format("%03d", gCalInstance.getMillisOfSec(time))).append("Z");
+        try {
+            gCalInstance.getExtendStringRepUntilField(time, 0, ps, Fields.HOUR, Fields.MILLISECOND, true);
+        } catch (IOException e) {
+            throw new AlgebricksException(e);
+        }
     }
 
 }
\ No newline at end of file
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 0ef170e..28008b2 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
@@ -14,6 +14,8 @@
  */
 package edu.uci.ics.asterix.om.base;
 
+import java.io.IOException;
+
 import org.json.JSONException;
 import org.json.JSONObject;
 
@@ -75,9 +77,12 @@
     public String toString() {
         StringBuilder sbder = new StringBuilder();
         sbder.append("ADate: { ");
-        GregorianCalendarSystem.getInstance().getExtendStringRepWithTimezoneUntilField(
-                chrononTimeInDay * CHRONON_OF_DAY, 0, sbder, GregorianCalendarSystem.Fields.YEAR,
-                GregorianCalendarSystem.Fields.DAY);
+        try {
+            GregorianCalendarSystem.getInstance().getExtendStringRepUntilField(chrononTimeInDay * CHRONON_OF_DAY, 0,
+                    sbder, GregorianCalendarSystem.Fields.YEAR, GregorianCalendarSystem.Fields.DAY, false);
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
         sbder.append(" }");
         return sbder.toString();
     }
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/ADateTime.java b/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/ADateTime.java
index 081fa63..10d49aa 100644
--- a/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/ADateTime.java
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/ADateTime.java
@@ -14,6 +14,8 @@
  */
 package edu.uci.ics.asterix.om.base;
 
+import java.io.IOException;
+
 import org.json.JSONException;
 import org.json.JSONObject;
 
@@ -106,8 +108,12 @@
     public String toString() {
         StringBuilder sbder = new StringBuilder();
         sbder.append("ADateTime: { ");
-        GregorianCalendarSystem.getInstance().getExtendStringRepWithTimezoneUntilField(chrononTime, 0, sbder,
-                GregorianCalendarSystem.Fields.YEAR, GregorianCalendarSystem.Fields.MILLISECOND);
+        try {
+            GregorianCalendarSystem.getInstance().getExtendStringRepUntilField(chrononTime, 0, sbder,
+                    GregorianCalendarSystem.Fields.YEAR, GregorianCalendarSystem.Fields.MILLISECOND, true);
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
         sbder.append(" }");
         return sbder.toString();
     }
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
index f1352f1..e3c5213 100644
--- 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
@@ -14,6 +14,8 @@
  */
 package edu.uci.ics.asterix.om.base;
 
+import java.io.IOException;
+
 import org.json.JSONException;
 import org.json.JSONObject;
 
@@ -100,33 +102,38 @@
     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: { ");
+        try {
+            if (typetag == ATypeTag.DATE.serialize()) {
+                sbder.append("ADate: { ");
 
-            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(" }");
+                GregorianCalendarSystem.getInstance().getExtendStringRepUntilField(
+                        intervalStart * ADate.CHRONON_OF_DAY, 0, sbder, GregorianCalendarSystem.Fields.YEAR,
+                        GregorianCalendarSystem.Fields.DAY, false);
+
+                sbder.append(" }, ADate: {");
+                GregorianCalendarSystem.getInstance().getExtendStringRepUntilField(intervalEnd * ADate.CHRONON_OF_DAY,
+                        0, sbder, GregorianCalendarSystem.Fields.YEAR, GregorianCalendarSystem.Fields.DAY, false);
+                sbder.append(" }");
+            } else if (typetag == ATypeTag.TIME.serialize()) {
+                sbder.append("ATime: { ");
+                GregorianCalendarSystem.getInstance().getExtendStringRepUntilField(intervalStart, 0, sbder,
+                        GregorianCalendarSystem.Fields.HOUR, GregorianCalendarSystem.Fields.MILLISECOND, true);
+                sbder.append(" }, ATime: { ");
+
+                GregorianCalendarSystem.getInstance().getExtendStringRepUntilField(intervalEnd, 0, sbder,
+                        GregorianCalendarSystem.Fields.HOUR, GregorianCalendarSystem.Fields.MILLISECOND, true);
+                sbder.append(" }");
+            } else if (typetag == ATypeTag.DATETIME.serialize()) {
+                sbder.append("ADateTime: { ");
+                GregorianCalendarSystem.getInstance().getExtendStringRepUntilField(intervalStart, 0, sbder,
+                        GregorianCalendarSystem.Fields.YEAR, GregorianCalendarSystem.Fields.MILLISECOND, true);
+                sbder.append(" }, ADateTime: { ");
+                GregorianCalendarSystem.getInstance().getExtendStringRepUntilField(intervalEnd, 0, sbder,
+                        GregorianCalendarSystem.Fields.YEAR, GregorianCalendarSystem.Fields.MILLISECOND, true);
+                sbder.append(" }");
+            }
+        } catch (IOException e) {
+            throw new RuntimeException(e);
         }
         sbder.append(" }");
         return sbder.toString();
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/ATime.java b/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/ATime.java
index b97ed51..edbf007 100644
--- a/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/ATime.java
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/ATime.java
@@ -14,6 +14,8 @@
  */
 package edu.uci.ics.asterix.om.base;
 
+import java.io.IOException;
+
 import org.json.JSONException;
 import org.json.JSONObject;
 
@@ -90,8 +92,12 @@
     public String toString() {
         StringBuilder sbder = new StringBuilder();
         sbder.append("ATime: { ");
-        GregorianCalendarSystem.getInstance().getExtendStringRepWithTimezoneUntilField(chrononTime, 0, sbder,
-                GregorianCalendarSystem.Fields.HOUR, GregorianCalendarSystem.Fields.MILLISECOND);
+        try {
+            GregorianCalendarSystem.getInstance().getExtendStringRepUntilField(chrononTime, 0, sbder,
+                    GregorianCalendarSystem.Fields.HOUR, GregorianCalendarSystem.Fields.MILLISECOND, true);
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
         sbder.append(" }");
         return sbder.toString();
 
diff --git a/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/ADurationParserFactory.java b/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/ADurationParserFactory.java
index 84e2386..a651716 100644
--- a/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/ADurationParserFactory.java
+++ b/asterix-om/src/main/java/edu/uci/ics/asterix/om/base/temporal/ADurationParserFactory.java
@@ -248,18 +248,30 @@
             throw new HyracksDataException(durationErrorMessage + ": no time fields after time separator.");
         }
 
+        int totalMonths = sign * (year * 12 + month);
+        long totalMilliseconds = sign
+                * (day * GregorianCalendarSystem.CHRONON_OF_DAY + hour * GregorianCalendarSystem.CHRONON_OF_HOUR
+                        + minute * GregorianCalendarSystem.CHRONON_OF_MINUTE + second
+                        * GregorianCalendarSystem.CHRONON_OF_SECOND + millisecond);
+
+        if (sign > 0) {
+            if (totalMonths < 0) {
+                throw new HyracksDataException(durationErrorMessage
+                        + ": total number of months is beyond its max value (-2147483647 to 2147483647).");
+            }
+            if (totalMilliseconds < 0) {
+                throw new HyracksDataException(
+                        durationErrorMessage
+                                + ": total number of milliseconds is beyond its max value (-9223372036854775808 to 9223372036854775807).");
+            }
+        }
+
         if (mutableObject instanceof AMutableDuration) {
-            ((AMutableDuration) mutableObject)
-                    .setValue(sign * (year * 12 + month),
-                            sign
-                                    * (day * 24 * 3600 * 1000L + 3600 * 1000L * hour + 60 * minute * 1000L + second
-                                            * 1000L + millisecond));
+            ((AMutableDuration) mutableObject).setValue(totalMonths, totalMilliseconds);
         } else if (mutableObject instanceof AMutableYearMonthDuration) {
-            ((AMutableYearMonthDuration) mutableObject).setMonths(sign * (year * 12 + month));
+            ((AMutableYearMonthDuration) mutableObject).setMonths(totalMonths);
         } else if (mutableObject instanceof AMutableDayTimeDuration) {
-            ((AMutableDayTimeDuration) mutableObject)
-                    .setMilliseconds(sign
-                            * (day * 24 * 3600 * 1000L + 3600 * 1000L * hour + 60 * minute * 1000L + second * 1000L + millisecond));
+            ((AMutableDayTimeDuration) mutableObject).setMilliseconds(totalMilliseconds);
         }
     }
 }
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 f74af9b..8c21bad 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
@@ -30,6 +30,8 @@
  */
 package edu.uci.ics.asterix.om.base.temporal;
 
+import java.io.IOException;
+
 /**
  * A simple implementation of the Gregorian calendar system.
  * <p/>
@@ -53,9 +55,9 @@
 
     public static final int[] DAYS_SINCE_MONTH_BEGIN_ORDI = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
 
-    public static final int CHRONON_OF_SECOND = 1000;
-    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_SECOND = 1000;
+    public static final long CHRONON_OF_MINUTE = 60 * CHRONON_OF_SECOND;
+    public static final long 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;
 
@@ -234,9 +236,9 @@
      */
     public int getChronon(int hour, int min, int sec, int millis, int timezone) {
         // Added milliseconds for all fields but month and day
-        int chrononTime = (hour - timezone / 4) * CHRONON_OF_HOUR + (min - (timezone % 4) * 15) * CHRONON_OF_MINUTE
+        long chrononTime = (hour - timezone / 4) * CHRONON_OF_HOUR + (min - (timezone % 4) * 15) * CHRONON_OF_MINUTE
                 + sec * CHRONON_OF_SECOND + millis;
-        return chrononTime;
+        return (int)chrononTime;
     }
 
     public long adjustChrononByTimezone(long chronon, int timezone) {
@@ -268,8 +270,8 @@
      * @param sbder
      * @param untilField
      */
-    public void getExtendStringRepWithTimezoneUntilField(long chrononTime, int timezone, StringBuilder sbder,
-            Fields startField, Fields untilField) {
+    public void getExtendStringRepUntilField(long chrononTime, int timezone, Appendable sbder, Fields startField,
+            Fields untilField, boolean withTimezone) throws IOException {
 
         int year = getYear(chrononTime);
         int month = getMonthOfYear(chrononTime, year);
@@ -323,16 +325,18 @@
                 break;
         }
 
-        if (timezone == 0) {
-            sbder.append("Z");
-        } else {
-            short tzMin = (short) ((timezone % 4) * 15);
-            if (tzMin < 0) {
-                tzMin = (short) (-1 * tzMin);
+        if (withTimezone) {
+            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));
             }
-            short tzHr = (short) (timezone / 4);
-            sbder.append((tzHr >= 0 ? "+" : "-")).append(String.format("%02d", (tzHr < 0 ? -tzHr : tzHr))).append(":")
-                    .append(String.format("%02d", tzMin));
         }
     }
 
@@ -343,8 +347,8 @@
      * @param timezone
      * @param sbder
      */
-    public void getBasicStringRepWithTimezoneUntilField(long chrononTime, int timezone, StringBuilder sbder,
-            Fields startField, Fields untilField) {
+    public void getBasicStringRepUntilField(long chrononTime, int timezone, Appendable sbder, Fields startField,
+            Fields untilField, boolean withTimezone) throws IOException {
         int year = getYear(chrononTime);
         int month = getMonthOfYear(chrononTime, year);
 
@@ -382,16 +386,18 @@
                 break;
         }
 
-        if (timezone == 0) {
-            sbder.append("Z");
-        } else {
-            short tzMin = (short) ((timezone % 4) * 15);
-            if (tzMin < 0) {
-                tzMin = (short) (-1 * tzMin);
+        if (withTimezone) {
+            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));
             }
-            short tzHr = (short) (timezone / 4);
-            sbder.append((tzHr >= 0 ? "+" : "-")).append(String.format("%02d", (tzHr < 0 ? -tzHr : tzHr)))
-                    .append(String.format("%02d", tzMin));
         }
     }
 
@@ -480,8 +486,7 @@
      * 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
@@ -528,8 +533,7 @@
      * 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 and commented by Theodoros Ioannou on July 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
@@ -593,8 +597,7 @@
      * 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-runtime/.gitignore b/asterix-runtime/.gitignore
new file mode 100644
index 0000000..ea8c4bf
--- /dev/null
+++ b/asterix-runtime/.gitignore
@@ -0,0 +1 @@
+/target
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/AbstractQuadStringStringEval.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/AbstractQuadStringStringEval.java
index ce9ecd2..2bd874f 100644
--- a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/AbstractQuadStringStringEval.java
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/AbstractQuadStringStringEval.java
@@ -6,7 +6,6 @@
 
 import java.io.DataOutput;
 import java.util.Arrays;
-import java.util.regex.Pattern;
 
 import edu.uci.ics.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
 import edu.uci.ics.asterix.om.base.AMutableString;
@@ -24,9 +23,6 @@
 import edu.uci.ics.hyracks.data.std.util.ArrayBackedValueStorage;
 import edu.uci.ics.hyracks.dataflow.common.data.accessors.IFrameTupleReference;
 
-/**
- * @author ilovesoup
- */
 public abstract class AbstractQuadStringStringEval implements ICopyEvaluator {
 
     private DataOutput dout;
@@ -138,7 +134,7 @@
             } else if (c == '_') {
                 sb.append(".");
             } else {
-                if (Arrays.binarySearch(reservedRegexChars, c) >= 0) {
+                if (Arrays.binarySearch(StringEvaluatorUtils.reservedRegexChars, c) >= 0) {
                     sb.append('\\');
                 }
                 sb.append(c);
@@ -147,33 +143,4 @@
         return sb.toString();
     }
 
-    protected int toFlag(AString pattern) {
-        String str = pattern.getStringValue();
-        int flag = 0;
-        for (int i = 0; i < str.length(); i++) {
-            char c = str.charAt(i);
-            switch (c) {
-                case 's':
-                    flag |= Pattern.DOTALL;
-                    break;
-                case 'm':
-                    flag |= Pattern.MULTILINE;
-                    break;
-                case 'i':
-                    flag |= Pattern.CASE_INSENSITIVE;
-                    break;
-                case 'x':
-                    flag |= Pattern.COMMENTS;
-                    break;
-            }
-        }
-        return flag;
-    }
-
-    private final static char[] reservedRegexChars = new char[] { '\\', '(', ')', '[', ']', '{', '}', '.', '^', '$',
-            '*', '|' };
-
-    static {
-        Arrays.sort(reservedRegexChars);
-    }
 }
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/AbstractTripleStringBoolEval.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/AbstractTripleStringBoolEval.java
index a3be797..7d0a01f 100644
--- a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/AbstractTripleStringBoolEval.java
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/AbstractTripleStringBoolEval.java
@@ -2,7 +2,6 @@
 
 import java.io.DataOutput;
 import java.util.Arrays;
-import java.util.regex.Pattern;
 
 import edu.uci.ics.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
 import edu.uci.ics.asterix.om.base.ABoolean;
@@ -19,9 +18,6 @@
 import edu.uci.ics.hyracks.data.std.util.ArrayBackedValueStorage;
 import edu.uci.ics.hyracks.dataflow.common.data.accessors.IFrameTupleReference;
 
-/**
- * @author Xiaoyu Ma
- */
 public abstract class AbstractTripleStringBoolEval implements ICopyEvaluator {
 
     private DataOutput dout;
@@ -118,7 +114,7 @@
             } else if (c == '_') {
                 sb.append(".");
             } else {
-                if (Arrays.binarySearch(reservedRegexChars, c) >= 0) {
+                if (Arrays.binarySearch(StringEvaluatorUtils.reservedRegexChars, c) >= 0) {
                     sb.append('\\');
                 }
                 sb.append(c);
@@ -126,34 +122,4 @@
         }
         return sb.toString();
     }
-
-    protected int toFlag(AString pattern) {
-        String str = pattern.getStringValue();
-        int flag = 0;
-        for (int i = 0; i < str.length(); i++) {
-            char c = str.charAt(i);
-            switch (c) {
-                case 's':
-                    flag |= Pattern.DOTALL;
-                    break;
-                case 'm':
-                    flag |= Pattern.MULTILINE;
-                    break;
-                case 'i':
-                    flag |= Pattern.CASE_INSENSITIVE;
-                    break;
-                case 'x':
-                    flag |= Pattern.COMMENTS;
-                    break;
-            }
-        }
-        return flag;
-    }
-
-    private final static char[] reservedRegexChars = new char[] { '\\', '(', ')', '[', ']', '{', '}', '.', '^', '$',
-            '*', '|' };
-
-    static {
-        Arrays.sort(reservedRegexChars);
-    }
 }
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/AbstractTripleStringStringEval.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/AbstractTripleStringStringEval.java
index 41d0b3d..4833f16 100644
--- a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/AbstractTripleStringStringEval.java
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/AbstractTripleStringStringEval.java
@@ -20,9 +20,6 @@
 import edu.uci.ics.hyracks.data.std.util.ArrayBackedValueStorage;
 import edu.uci.ics.hyracks.dataflow.common.data.accessors.IFrameTupleReference;
 
-/**
- * @author Xiaoyu Ma
- */
 public abstract class AbstractTripleStringStringEval implements ICopyEvaluator {
 
     private DataOutput dout;
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/CodePointToStringDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/CodePointToStringDescriptor.java
index 1a3e1b8..14651fe 100644
--- a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/CodePointToStringDescriptor.java
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/CodePointToStringDescriptor.java
@@ -21,9 +21,6 @@
 import edu.uci.ics.hyracks.dataflow.common.data.accessors.IFrameTupleReference;
 import edu.uci.ics.hyracks.dataflow.common.data.util.StringUtils;
 
-/**
- * @author Xiaoyu Ma
- */
 public class CodePointToStringDescriptor extends AbstractScalarFunctionDynamicDescriptor {
 
     private static final long serialVersionUID = 1L;
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/CodepointIterator.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/CodepointIterator.java
index f103e0f..1365277 100644
--- a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/CodepointIterator.java
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/CodepointIterator.java
@@ -2,10 +2,6 @@
 
 import edu.uci.ics.hyracks.data.std.primitive.UTF8StringPointable;
 
-/**
- *
- * @author Xiaoyu Ma
- */
 public class CodepointIterator {
     public void reset(byte [] buf, int startPos) {
         this.buf = buf;
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/NumericAddDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/NumericAddDescriptor.java
index 0181698..10aea29 100644
--- a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/NumericAddDescriptor.java
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/NumericAddDescriptor.java
@@ -27,7 +27,7 @@
             if (y > 0 && z < 0)
                 throw new ArithmeticException("Overflow adding " + x + " + " + y);
         } else if (y < 0 && z > 0)
-            throw new ArithmeticException("Overflow adding " + x + " + " + y);
+            throw new ArithmeticException("Underflow adding " + x + " + " + y);
         return z;
     }
 
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringConcatDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringConcatDescriptor.java
index bcd199c..5ffcb29 100644
--- a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringConcatDescriptor.java
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringConcatDescriptor.java
@@ -25,9 +25,6 @@
 import edu.uci.ics.hyracks.dataflow.common.data.accessors.IFrameTupleReference;
 import edu.uci.ics.hyracks.dataflow.common.data.util.StringUtils;
 
-/**
- * @author Xiaoyu Ma
- */
 public class StringConcatDescriptor extends AbstractScalarFunctionDynamicDescriptor {
 
     private static final long serialVersionUID = 1L;
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringEndWithDescrtiptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringEndWithDescrtiptor.java
index 6d0eaad..3e08fa3 100644
--- a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringEndWithDescrtiptor.java
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringEndWithDescrtiptor.java
@@ -18,9 +18,6 @@
 import edu.uci.ics.hyracks.data.std.primitive.UTF8StringPointable;
 import edu.uci.ics.hyracks.data.std.util.ArrayBackedValueStorage;
 
-/**
- * @author Xiaoyu Ma
- */
 public class StringEndWithDescrtiptor extends AbstractScalarFunctionDynamicDescriptor {
     private static final long serialVersionUID = 1L;
 
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringEqualDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringEqualDescriptor.java
index e921e45..e778f3e 100644
--- a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringEqualDescriptor.java
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringEqualDescriptor.java
@@ -14,9 +14,6 @@
 import edu.uci.ics.hyracks.data.std.primitive.UTF8StringPointable;
 import edu.uci.ics.hyracks.data.std.util.ArrayBackedValueStorage;
 
-/**
- * @author Xiaoyu Ma
- */
 public class StringEqualDescriptor extends AbstractScalarFunctionDynamicDescriptor {
     private static final long serialVersionUID = 1L;
 
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringEvaluatorUtils.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringEvaluatorUtils.java
new file mode 100644
index 0000000..98a70b4
--- /dev/null
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringEvaluatorUtils.java
@@ -0,0 +1,49 @@
+/*
+ * Copyright 2009-2013 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.util.regex.Pattern;
+
+import edu.uci.ics.asterix.om.base.AString;
+
+public class StringEvaluatorUtils {
+
+    public static int toFlag(AString pattern) {
+        String str = pattern.getStringValue();
+        int flag = 0;
+        for (int i = 0; i < str.length(); i++) {
+            char c = str.charAt(i);
+            switch (c) {
+                case 's':
+                    flag |= Pattern.DOTALL;
+                    break;
+                case 'm':
+                    flag |= Pattern.MULTILINE;
+                    break;
+                case 'i':
+                    flag |= Pattern.CASE_INSENSITIVE;
+                    break;
+                case 'x':
+                    flag |= Pattern.COMMENTS;
+                    break;
+            }
+        }
+        return flag;
+    }
+
+    public final static char[] reservedRegexChars = new char[] { '$', '(', ')', '*', '.', '[', '\\', ']', '^', '{',
+            '|', '}' };
+    
+}
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringJoinDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringJoinDescriptor.java
index 9c2f960..7742ccc 100644
--- a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringJoinDescriptor.java
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringJoinDescriptor.java
@@ -21,9 +21,6 @@
 import edu.uci.ics.hyracks.dataflow.common.data.accessors.IFrameTupleReference;
 import edu.uci.ics.hyracks.dataflow.common.data.util.StringUtils;
 
-/**
- * @author Xiaoyu Ma
- */
 public class StringJoinDescriptor extends AbstractScalarFunctionDynamicDescriptor {
 
     private static final long serialVersionUID = 1L;
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringLowerCaseDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringLowerCaseDescriptor.java
index 5e188d3..d8d0b55 100644
--- a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringLowerCaseDescriptor.java
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringLowerCaseDescriptor.java
@@ -23,9 +23,6 @@
 import edu.uci.ics.hyracks.dataflow.common.data.accessors.IFrameTupleReference;
 import edu.uci.ics.hyracks.dataflow.common.data.util.StringUtils;
 
-/**
- * @author Xiaoyu Ma
- */
 public class StringLowerCaseDescriptor extends AbstractScalarFunctionDynamicDescriptor {
     private static final long serialVersionUID = 1L;
 
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringMatchesDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringMatchesDescriptor.java
index 03a3545..e26a0c6 100644
--- a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringMatchesDescriptor.java
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringMatchesDescriptor.java
@@ -26,9 +26,6 @@
 import edu.uci.ics.hyracks.data.std.util.ArrayBackedValueStorage;
 import edu.uci.ics.hyracks.data.std.util.ByteArrayAccessibleOutputStream;
 
-/**
- * @author Xiaoyu Ma
- */
 public class StringMatchesDescriptor extends AbstractScalarFunctionDynamicDescriptor {
     private static final long serialVersionUID = 1L;
 
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringMatchesWithFlagDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringMatchesWithFlagDescriptor.java
index 93dc342..6da320b 100644
--- a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringMatchesWithFlagDescriptor.java
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringMatchesWithFlagDescriptor.java
@@ -30,9 +30,6 @@
 import edu.uci.ics.hyracks.data.std.util.ArrayBackedValueStorage;
 import edu.uci.ics.hyracks.data.std.util.ByteArrayAccessibleOutputStream;
 
-/**
- * @author Xiaoyu Ma
- */
 public class StringMatchesWithFlagDescriptor extends AbstractScalarFunctionDynamicDescriptor {
 
     private static final long serialVersionUID = 1L;
@@ -112,7 +109,7 @@
                                 DataInputStream di = new DataInputStream(new ByteArrayInputStream(
                                         lastFlags.getByteArray()));
                                 astrFlags = (AString) stringSerde.deserialize(di);
-                                flags = toFlag(astrFlags);
+                                flags = StringEvaluatorUtils.toFlag(astrFlags);
                             }
 
                             pattern = Pattern.compile(strPattern, flags);
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringReplaceDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringReplaceDescriptor.java
index 230eb34..c8917dc 100644
--- a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringReplaceDescriptor.java
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringReplaceDescriptor.java
@@ -26,9 +26,6 @@
 import edu.uci.ics.hyracks.data.std.util.ArrayBackedValueStorage;
 import edu.uci.ics.hyracks.data.std.util.ByteArrayAccessibleOutputStream;
 
-/**
- * @author Xiaoyu Ma
- */
 public class StringReplaceDescriptor extends AbstractScalarFunctionDynamicDescriptor {
 
     private static final long serialVersionUID = 1L;
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringReplaceWithFlagsDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringReplaceWithFlagsDescriptor.java
index 4f18863..74c30e7 100644
--- a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringReplaceWithFlagsDescriptor.java
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringReplaceWithFlagsDescriptor.java
@@ -26,9 +26,6 @@
 import edu.uci.ics.hyracks.data.std.util.ArrayBackedValueStorage;
 import edu.uci.ics.hyracks.data.std.util.ByteArrayAccessibleOutputStream;
 
-/**
- * @author Xiaoyu Ma
- */
 public class StringReplaceWithFlagsDescriptor extends AbstractScalarFunctionDynamicDescriptor {
 
     private static final long serialVersionUID = 1L;
@@ -130,7 +127,7 @@
                                 DataInputStream di = new DataInputStream(new ByteArrayInputStream(
                                         lastFlags.getByteArray()));
                                 astrFlags = (AString) stringSerde.deserialize(di);
-                                flags = toFlag(astrFlags);
+                                flags = StringEvaluatorUtils.toFlag(astrFlags);
                             }
 
                             if (newPattern || newFlags)
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringStartWithDescrtiptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringStartWithDescrtiptor.java
index 601c3d0..c852fbc 100644
--- a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringStartWithDescrtiptor.java
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringStartWithDescrtiptor.java
@@ -14,9 +14,6 @@
 import edu.uci.ics.hyracks.data.std.primitive.UTF8StringPointable;
 import edu.uci.ics.hyracks.data.std.util.ArrayBackedValueStorage;
 
-/**
- * @author Xiaoyu Ma
- */
 public class StringStartWithDescrtiptor extends AbstractScalarFunctionDynamicDescriptor {
     private static final long serialVersionUID = 1L;
 
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringToCodePointDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringToCodePointDescriptor.java
index e001d9e..d34280e 100644
--- a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringToCodePointDescriptor.java
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/StringToCodePointDescriptor.java
@@ -25,18 +25,10 @@
 import edu.uci.ics.hyracks.data.std.util.ArrayBackedValueStorage;
 import edu.uci.ics.hyracks.dataflow.common.data.accessors.IFrameTupleReference;
 
-/**
- * @author Xiaoyu Ma
- */
 public class StringToCodePointDescriptor extends AbstractScalarFunctionDynamicDescriptor {
 
     private static final long serialVersionUID = 1L;
 
-    public static final IFunctionDescriptorFactory FACTORY1 = new IFunctionDescriptorFactory() {
-        public IFunctionDescriptor createFunctionDescriptor() {
-            return new StringToCodePointDescriptor();
-        }
-    };
     public static final IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
         public IFunctionDescriptor createFunctionDescriptor() {
             return new StringToCodePointDescriptor();
diff --git a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/SubstringBeforeDescriptor.java b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/SubstringBeforeDescriptor.java
index 77911af..61d5d72 100644
--- a/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/SubstringBeforeDescriptor.java
+++ b/asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/functions/SubstringBeforeDescriptor.java
@@ -72,8 +72,7 @@
                         int posPattern = 3;
 
                         int offset = 0;
-                        while (posSrc - 3 < srcLen - patternLen) {
-                            // offset = 0;                        
+                        while (posSrc - 3 < srcLen - patternLen) {                       
                             while (posPattern + offset - 3 < patternLen && posSrc + offset - 3 < srcLen) {
                                 char c1 = UTF8StringPointable.charAt(src, posSrc + offset);
                                 char c2 = UTF8StringPointable.charAt(pattern, posPattern + offset);
@@ -82,7 +81,6 @@
                                 offset++;
                             }
                             if (offset == patternLen) {
-                                // found = true;
                                 break;
                             }
                             posSrc += UTF8StringPointable.charSize(src, posSrc);
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
index 441d20a..55b9663 100644
--- 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
@@ -120,8 +120,8 @@
 
                             StringBuilder sbder = new StringBuilder();
 
-                            calInstance.getExtendStringRepWithTimezoneUntilField(chronon, timezone, sbder, Fields.YEAR,
-                                    Fields.MILLISECOND);
+                            calInstance.getExtendStringRepUntilField(chronon, timezone, sbder, Fields.YEAR,
+                                    Fields.MILLISECOND, true);
 
                             out.writeByte(SER_STRING_TYPE_TAG);
                             out.writeUTF(sbder.toString());
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
index 1ca64c6..340545d 100644
--- 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
@@ -120,8 +120,8 @@
 
                             StringBuilder sbder = new StringBuilder();
 
-                            calInstance.getExtendStringRepWithTimezoneUntilField(chronon, timezone, sbder, Fields.HOUR,
-                                    Fields.MILLISECOND);
+                            calInstance.getExtendStringRepUntilField(chronon, timezone, sbder, Fields.HOUR,
+                                    Fields.MILLISECOND, true);
 
                             out.writeByte(SER_STRING_TYPE_TAG);
                             out.writeUTF(sbder.toString());
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
index c6da17e..b343f63 100644
--- 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
@@ -187,8 +187,9 @@
 
                                 if (day < 0) {
                                     boolean isLeapYear = calInstanct.isLeapYear(year1);
-                                    day += (isLeapYear) ? (GregorianCalendarSystem.DAYS_OF_MONTH_LEAP[month1 - 2])
-                                            : (GregorianCalendarSystem.DAYS_OF_MONTH_ORDI[month1 - 2]);
+                                    // need to "borrow" the days in previous month to make the day positive; when month is 1 (Jan), Dec will be borrowed
+                                    day += (isLeapYear) ? (GregorianCalendarSystem.DAYS_OF_MONTH_LEAP[(12 + month1 - 2) % 12])
+                                            : (GregorianCalendarSystem.DAYS_OF_MONTH_ORDI[(12 + month1 - 2) % 12]);
                                     month -= 1;
                                 }
 
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
index e09f1da..a934473 100644
--- 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
@@ -201,8 +201,9 @@
 
                                 if (day < 0) {
                                     boolean isLeapYear = calInstanct.isLeapYear(year1);
-                                    day += (isLeapYear) ? (GregorianCalendarSystem.DAYS_OF_MONTH_LEAP[month1 - 2])
-                                            : (GregorianCalendarSystem.DAYS_OF_MONTH_ORDI[month1 - 2]);
+                                    // need to "borrow" the days in previous month to make the day positive; when month is 1 (Jan), Dec will be borrowed
+                                    day += (isLeapYear) ? (GregorianCalendarSystem.DAYS_OF_MONTH_LEAP[(12 + month1 - 2) % 12])
+                                            : (GregorianCalendarSystem.DAYS_OF_MONTH_ORDI[(12 + month1 - 2) % 12]);
                                     month -= 1;
                                 }