var getLastGlucose = function (data) {
    data = data.map(function prepGlucose (obj) {
        //Support the NS sgv field to avoid having to convert in a custom way
        obj.glucose = obj.glucose || obj.sgv;
        return obj;
    });

    var now = data[0];
    var last = data[1];
    var minutes;
    var change;
    var avg = 0;

    //console.error(data);
    //TODO: calculate average using system_time instead of assuming 1 data point every 5m
    if (typeof data[5] !== 'undefined' && data[5].glucose > 30) {
        then = data[5];
    } else if (typeof data[4] !== 'undefined' && data[4].glucose > 30) {
        then = data[4];
    } else if (typeof data[3] !== 'undefined' && data[3].glucose > 30) {
        then = data[3];
    } else if (typeof data[2] !== 'undefined' && data[2].glucose > 30) {
        then = data[2];
    } else if (typeof data[1] !== 'undefined' && data[1].glucose > 30) {
        then = data[1];
    } else {
        then = data[0];
    }
    change = now.glucose - then.glucose;
    if (typeof then.date !== 'undefined' && typeof now.date !== 'undefined') {
        minutes = Math.round( (now.date - then.date) / (1000 * 60) );
        console.error("Avgdelta lookback", minutes, "minutes");
        // multiply by 5 to get the same units as delta, i.e. mg/dL/5m
        avg = change/minutes * 5;
    } else { console.error("Error: date field not found: cannot calculate avgdelta"); }

    return {
        delta: now.glucose - last.glucose
        , glucose: now.glucose
        , avgdelta: Math.round( avg * 1000 ) / 1000
    };
};

module.exports = getLastGlucose;

@@ -1011,16 +1011,143 @@
 lucose;%0A
+%0A    var then_date = then.date %7C%7C Date.parse(then.display_time);%0A    var now_date = now.date %7C%7C Date.parse(now.display_time);%0A%0A
     if (
@@ -1153,25 +1153,25 @@
 (typeof then
-.
+_
 date !== 'un
@@ -1188,25 +1188,25 @@
 & typeof now
-.
+_
 date !== 'un
@@ -1251,17 +1251,17 @@
 nd( (now
-.
+_
 date - t
@@ -1259,25 +1259,25 @@
 _date - then
-.
+_
 date) / (100

Support display_time in getLastGlucose