<?php

class CalculateChallengedSpeed
{

  static public function run($measuredSpeed, $percentageTolerance, $fixedTolerance, $toleranceTable)
  {
  	if(isset($toleranceTable) && count($toleranceTable) > 0)
  	{
  		foreach($toleranceTable as $interval)
  		{
  			if($measuredSpeed > $interval['minSpeed'] && $measuredSpeed <= $interval['maxSpeed'])
  			{
  				$challengedSpeed = $measuredSpeed - $interval['tolerance'];
  				
  				if($challengedSpeed < 0)
  					$challengedSpeed = 0;
  				
  				return $challengedSpeed;
  			}
  		
  		}

  		return null;
  	}
  	
    $measuredSpeedPerc = $measuredSpeed * $percentageTolerance;

    if($measuredSpeedPerc < $fixedTolerance)
      $measuredSpeedPerc = $fixedTolerance;

    $challengedSpeed = $measuredSpeed - $measuredSpeedPerc;

    $challengedSpeed = round($challengedSpeed, 2);

    return $challengedSpeed;
  }

}
