From cc87e270481d69b2bb7d5bf02f131a505dc09fdd Mon Sep 17 00:00:00 2001
From: Vladimir Sitnikov <sitnikov.vladimir@gmail.com>
Date: Mon, 25 Feb 2013 00:43:35 +0400
Subject: [PATCH] Fixed computation of stacked series in case some series start
 in the middle of the range The bug is caused by stale value of last_x local
 across loop in gatherDatasets_. See
 https://code.google.com/p/dygraphs/issues/detail?id=438

---
 auto_tests/tests/stacked.js | 24 ++++++++++++++++++++++++
 dygraph.js                  |  6 ++++--
 2 files changed, 28 insertions(+), 2 deletions(-)

diff --git a/auto_tests/tests/stacked.js b/auto_tests/tests/stacked.js
index b0ad492..e365c58 100644
--- a/auto_tests/tests/stacked.js
+++ b/auto_tests/tests/stacked.js
@@ -155,3 +155,27 @@ stackedTestCase.prototype.testNullValues = function() {
   g.setSelection(4);
   assertEquals("4: Y1: 3 Y2: 2 Y3: 3", Util.getLegend());
 };
+
+// Regression test for http://code.google.com/p/dygraphs/issues/detail?id=438
+stackedTestCase.prototype.testMissingValueAtZero = function() {
+  var opts = {
+    stackedGraph: true
+  };
+  var data = "X,Y1,Y2\n" +
+      "0,,1\n" +
+      "1,1,2\n" +
+      "2,,3\n"
+  ;
+
+  var graph = document.getElementById("graph");
+  g = new Dygraph(graph, data, opts);
+
+  g.setSelection(0);
+  assertEquals("0: Y2: 1", Util.getLegend());
+
+  g.setSelection(1);
+  assertEquals("1: Y1: 1 Y2: 2", Util.getLegend());
+
+  g.setSelection(2);
+  assertEquals("2: Y2: 3", Util.getLegend());
+};
diff --git a/dygraph.js b/dygraph.js
index b2c9ba8..833c29c 100644
--- a/dygraph.js
+++ b/dygraph.js
@@ -2335,7 +2335,9 @@ Dygraph.prototype.gatherDatasets_ = function(rolledSeries, dateWindow) {
                      series[j][1][2]];
       }
     } else if (this.attr_("stackedGraph")) {
-      var actual_y, last_x;
+      // Need to clear last_x explicitly as javascript's locals are
+      // local to function, not to a block of statements
+      var actual_y, last_x = null;
       for (j = 0; j < series.length; j++) {
         // If one data set has a NaN, let all subsequent stacked
         // sets inherit the NaN -- only start at 0 for the first set.
@@ -2350,7 +2352,7 @@ Dygraph.prototype.gatherDatasets_ = function(rolledSeries, dateWindow) {
           continue;
         }
 
-        if (j === 0 || last_x != x) {
+        if (last_x != x) {
           cumulative_y[x] += actual_y;
           // If an x-value is repeated, we ignore the duplicates.
         }
-- 
2.7.4