Index: trunk/Measure.php
===================================================================
--- trunk/Measure.php	(revision 64)
+++ trunk/Measure.php	(revision 65)
@@ -13,4 +13,5 @@
   var $Differential;
   var $DivisionCount;
+  var $PeriodTolerance;
 
   function __construct(Database $Database)
@@ -24,4 +25,5 @@
     $this->Differential = 0;
     $this->DivisionCount = 500;
+    $this->PeriodTolerance = 0.25; // 25%
   }
 
@@ -60,28 +62,45 @@
     $Result = $this->Database->select($this->Data['DataTable'], '*', '(`measure`='.$this->Data['Id'].') AND '.
       '(`level`=0) ORDER BY `time` DESC LIMIT 2');
-    if($Result->num_rows == 0) $this->Database->insert($this->Data['DataTable'],
+    if($Result->num_rows == 0) {
+      // No measure value found. Simply insert new first value.
+      $this->Database->insert($this->Data['DataTable'],
       array('min' => $Value, 'avg' => $Value, 'max' => $Value, 'level' => 0,
-      'measure' => $this->Data['Id'], 'time' => TimeToMysqlDateTime($Time), 'continuity' => 0));
-    else if($Result->num_rows == 1) $this->Database->insert($this->Data['DataTable'],
+      'measure' => $this->Data['Id'], 'time' => TimeToMysqlDateTime($Time),
+      'continuity' => 0));
+    } else if($Result->num_rows == 1) {
+      // One value exists. Add second value.
+      $this->Database->insert($this->Data['DataTable'],
       array('min' => $Value, 'avg' => $Value, 'max' => $Value, 'level' => 0,
       'measure' => $this->Data['Id'], 'time' => TimeToMysqlDateTime($Time),
       'continuity' => 1));
-    else {
+    } else {
+      // Two values already exist in measure table
       $LastValue = $Result->fetch_array();
       $NextToLastValue = $Result->fetch_array();
-      if(($Time - MysqlDateTimeToTime($LastValue['time'])) < 0.75 * $this->Data['Period'])
-      {
+      if(($Time - MysqlDateTimeToTime($LastValue['time'])) < (1 - $this->PeriodTolerance) * $this->Data['Period'])
+      {
+        // New value added too quickly. Need to wait for next measure period.
       }
       else
       {
-        if(($Time - MysqlDateTimeToTime($LastValue['time'])) < 1.25 * $this->Data['Period']) $Continuity = 1;
-          else $Continuity = 0;
+        // We are near defined period and can add new value.
+        if(($Time - MysqlDateTimeToTime($LastValue['time'])) < (1 + $this->PeriodTolerance) * $this->Data['Period']) {
+          // New value added near defined measure period inside tolerance. Keep continuity.
+          $Continuity = 1;
+        } else {
+          // New value added too late after defined measure period. Stop
+          // continuity and let gap to be added.
+          $Continuity = 0;
+        }
         if(($LastValue['avg'] == $NextToLastValue['avg']) and ($LastValue['avg'] == $Value) and
           ($LastValue['continuity'] == 1) and ($Continuity == 1))
         {
-          $this->Database->update($this->Data['DataTable'], '(time="'.$LastValue['time'].'") AND '.
-          '(level=0) AND (measure='.$this->Data['Id'].')', array('time' => TimeToMysqlDateTime($Time)));
+          // New value is same as last value and continuity mode is enabled and
+          // continuity flag is present. Just shift forward time for last value.
+          $this->Database->update($this->Data['DataTable'], '(`time`="'.$LastValue['time'].'") AND '.
+          '(`level`=0) AND (`measure`='.$this->Data['Id'].')', array('time' => TimeToMysqlDateTime($Time)));
         } else
         {
+          // Last value is different or not with continuity flag. Need to add new value.
           $this->Database->insert($this->Data['DataTable'], array('min' => $Value,
             'avg' => $Value, 'max' => $Value, 'level' => 0, 'measure' => $this->Data['Id'], 'time' => TimeToMysqlDateTime($Time),
@@ -91,5 +110,5 @@
     }
 
-    // Update levels
+    // Update higher levels
     for($Level = 1; $Level <= $this->MaxLevel; $Level++)
     {
@@ -101,5 +120,6 @@
       // Load values in time range
       $Values = array();
-      $Result = $this->Database->select($this->Data['DataTable'], '*', '(`time` > "'.TimeToMysqlDateTime($StartTime).'") AND '.
+      $Result = $this->Database->select($this->Data['DataTable'], '*', '(`time` > "'.
+        TimeToMysqlDateTime($StartTime).'") AND '.
         '(`time` < "'.TimeToMysqlDateTime($EndTime).'") AND '.
         '(`measure`='.$this->Data['Id'].') AND (`level`='.($Level - 1).') ORDER BY `time`');
@@ -115,15 +135,17 @@
         $this->LoadLeftSideValue($Level - 1, $StartTime),
         $Values,
-        $this->LoadRightSideValue($Level - 1, $EndTime));
+        $this->LoadRightSideValue($Level - 1, $EndTime)
+      );
 
       $Point = $this->ComputeOneValue($StartTime, $EndTime, $Values, $Level);
 
-      $this->Database->delete($this->Data['DataTable'], '(time > "'.TimeToMysqlDateTime($StartTime).'") AND
-        (time < "'.TimeToMysqlDateTime($EndTime).'") AND measure='.$this->Data['Id'].' AND level='.$Level);
+      $this->Database->delete($this->Data['DataTable'], '(`time` > "'.TimeToMysqlDateTime($StartTime).'") AND
+        (`time` < "'.TimeToMysqlDateTime($EndTime).'") AND (`measure`='.$this->Data['Id'].') '.
+        'AND (`level`='.$Level.')');
       $Continuity = $Values[1]['continuity'];
-      $this->Database->insert($this->Data['DataTable'], array('level' => $Level, 'measure' => $this->Data['Id'], 'min' => $Point['min'],
+      $this->Database->insert($this->Data['DataTable'], array('level' => $Level,
+        'measure' => $this->Data['Id'], 'min' => $Point['min'],
         'avg' => $Point['avg'], 'max' => $Point['max'], 'continuity' => $Continuity,
         'time' => TimeToMysqlDateTime($StartTime + ($EndTime - $StartTime) / 2)));
-
     }
   }
@@ -137,5 +159,6 @@
     foreach($this->ValueTypes as $ValueType)
     {
-      $Values[0][$ValueType] = Interpolation(NewPoint($Values[0]['time'], $Values[0][$ValueType]),
+      $Values[0][$ValueType] = Interpolation(
+        NewPoint($Values[0]['time'], $Values[0][$ValueType]),
         NewPoint($Values[1]['time'], $Values[1][$ValueType]), $LeftTime);
     }
@@ -143,6 +166,6 @@
     foreach($this->ValueTypes as $ValueType)
     {
-      $Values[count($Values) - 1][$ValueType] = Interpolation(NewPoint($Values[count($Values) - 2]['time'],
-        $Values[count($Values) - 2][$ValueType]),
+      $Values[count($Values) - 1][$ValueType] = Interpolation(
+        NewPoint($Values[count($Values) - 2]['time'], $Values[count($Values) - 2][$ValueType]),
         NewPoint($Values[count($Values) - 1]['time'], $Values[count($Values) - 1][$ValueType]),
         $RightTime);
@@ -233,17 +256,21 @@
   }
 
+  // Load one nearest value newer then given time
   function LoadRightSideValue($Level, $Time)
   {
     $Result = array();
-    $DbResult = $this->Database->select($this->Data['DataTable'], '*', '(time > "'.TimeToMysqlDateTime($Time).'") AND (measure='.$this->Data['Id'].') AND (level='.$Level.') ORDER BY time ASC LIMIT 1');
+    $DbResult = $this->Database->select($this->Data['DataTable'], '*',
+      '(`time` > "'.TimeToMysqlDateTime($Time).'") AND (`measure`='.
+      $this->Data['Id'].') AND (`level`='.$Level.') ORDER BY `time` ASC LIMIT 1');
     if($DbResult->num_rows > 0)
     {
+      // Found one value, simply return it
       $Row = $DbResult->fetch_array();
       $Row['time'] = MysqlDateTimeToTime($Row['time']);
       return(array($Row));
-    }
-    else
-    {
-      //$Time = $Values[count($Values)-1]['time'] + 60;
+    } else
+    {
+      // Not found any value. Calculate it
+      //$Time = $Values[count($Values) - 1]['time'] + 60;
       //array_push($Values, array('time' => $Time, 'min' => 0, 'avg' => 0, 'max' => 0, 'continuity' => 0));
       $Result[] = array('time' => ($Time + $this->TimeSegment($Level)), 'min' => 0,
@@ -262,4 +289,5 @@
   }
 
+  // Load one nearest value older then given time
   function LoadLeftSideValue($Level, $Time)
   {
@@ -270,8 +298,10 @@
     if($DbResult->num_rows > 0)
     {
+      // Found one value, simply return it
       $Row = $DbResult->fetch_array();
       $Row['time'] = MysqlDateTimeToTime($Row['time']);
       return(array($Row));
     } else {
+      // Not found any value. Calculate it
       //$Time = $Values[0]['time'] - 60;
       //array_unshift($Values, array('time' => $Time, 'min' => 0, 'avg' => 0, 'max' => 0, 'continuity' => 0));
@@ -301,5 +331,6 @@
 
     // Load values in time range
-    $Result = $this->Database->select($this->Data['DataTable'], '`time`, `min`, `avg`, `max`, `continuity`',
+    $Result = $this->Database->select($this->Data['DataTable'], '`time`, `min`, '.
+      '`avg`, `max`, `continuity`',
       '(`time` > "'.TimeToMysqlDateTime($TimeFrom).'") AND '.
       '(`time` < "'.TimeToMysqlDateTime($TimeTo).'") AND '.
@@ -308,5 +339,7 @@
     while($Row = $Result->fetch_array())
     {
-      $Values[] = array('time' => MysqlDateTimeToTime($Row['time']), 'min' => $Row['min'], 'avg' => $Row['avg'], 'max' => $Row['max'], 'continuity' => $Row['continuity']);
+      $Values[] = array('time' => MysqlDateTimeToTime($Row['time']),
+        'min' => $Row['min'], 'avg' => $Row['avg'], 'max' => $Row['max'],
+        'continuity' => $Row['continuity']);
     }
    // array_pop($Values);
@@ -325,5 +358,5 @@
       {
         $TimeStart = $TimeFrom + (($TimeTo - $TimeFrom) / $this->DivisionCount) * $I;
-        $TimeEnd = $TimeFrom + (($TimeTo - $TimeFrom) / $this->DivisionCount) * ($I+1);
+        $TimeEnd = $TimeFrom + (($TimeTo - $TimeFrom) / $this->DivisionCount) * ($I + 1);
 
         $EndIndex = $StartIndex;
Index: trunk/Version.php
===================================================================
--- trunk/Version.php	(revision 64)
+++ trunk/Version.php	(revision 65)
@@ -1,4 +1,4 @@
 <?php
 
-$Revision = 64;
+$Revision = 65;
 $ReleaseTime = strtotime('2016-01-01');
