/* ----------- Controll Loop ----------------*/
for ($i = 1; $i <= 80; $i++) {
    //if ($i>40) $Tout_stream = 0.0;
    //if ($i>40) $WaterInput = 0;
    list($erate, $elevel) = getLastErrors($Tdemand, $Level, $LastLevel);
    $x->SetRealInput('ERROR', $elevel);
    $x->SetRealInput('RATE', $erate);
    //$fuzzy_arr = $x->calcFuzzyAlt();
    //
    //$Fuzzy = $fuzzy_arr[0];
    $fuzzy_arr = $x->calcFuzzy();
    $Fuzzy = $fuzzy_arr['OUT'];
    //print_r($fuzzy_arr);
    $LastLevel = $Level;
    $Level = $Level - $Tout_stream + $WaterInput;
    list($Valve, $WaterInput) = getValve($Fuzzy, $Valve, $Vinp_max, 0, 1);
    $dotline = str_repeat('.', 100);
    $dotline[round($Level * 99)] = '#';
    echo $dotline, sprintf("L:%1.3f F:%1.3f V:%1.3f", $Level, $Fuzzy, $Valve), "\n";
}
print_r($x->StateOutput);
echo "</pre>\n";
/*---- required additional function ------------*/
function getValve($Fuzzy, $Valve, $inpMax, $lb, $ub)
{
    $xdot = $Valve + $Fuzzy;
    if ($xdot <= $lb) {
        $Valve = $lb;
    } elseif ($xdot >= $ub) {
        $Valve = $ub;
    } else {
$tankMaxLevel = array(1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0);
$tankInpDT = array(0.07000000000000001, 0.07000000000000001, 0.07000000000000001, 0.07000000000000001, 0.07000000000000001, 0.07000000000000001, 0.07000000000000001);
$tankOutDT = array(0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05);
$tankFuzzy = array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
/* ----------- Fuzzy Controll Loop ----------------*/
for ($tank = 0; $tank < 7; $tank++) {
    $name = $tankName[$tank];
    list($erate, $elevel) = getLastErrors($tankDemandLevel[$tank], $tankLevel[$tank], $tankLastLevel[$tank]);
    $x->SetRealInput('ERROR', $elevel);
    $x->SetRealInput('RATE', $erate);
    $fuzzy_arr = $x->calcFuzzy();
    $tankFuzzy[$tank] = $fuzzy_arr['OUT'];
    $tankLastLevel[$tank] = $tankLevel[$tank];
    $key_input_ref = $tankInputRefKey[$tank];
    if ($key_input_ref >= 0) {
        $Vinp_max = $tankInpMax[$tank] * $tankInpDT[$tank] * (int) ($tankLevel[$tank] <= $tankMaxWorkLevel[$tank] and $tankLevel[$key_input_ref] > $tankMinWorkLevel[$key_input_ref]);
    } else {
        $Vinp_max = $InputMaxValve * $Tinp_stream * (int) ($tankLevel[$tank] < $tankMaxWorkLevel[$tank]);
    }
    list($tankValve[$tank], $WaterInput) = getValve($tankFuzzy[$tank], $tankValve[$tank], $Vinp_max, 0, 1);
    $key_output_ref = $tankOutputRefKey[$tank];
    if ($key_output_ref >= 0) {
        $VOut_max = $tankOutMax[$tank] * $tankOutDT[$tank] * (int) ($tankLevel[$key_output_ref] > $tankMinWorkLevel[$key_output_ref]);
    } else {
        //-1
        $VOut_max = $OutputXMaxValve * $ToutX_stream * (int) ($tankLevel[$tank] > $tankMinWorkLevel[$tank]);
    }
    $tankLevel[$tank] = min($tankMaxLevel[$tank], $tankLevel[$tank] - $VOut_max + $WaterInput);
}
$out = array("currTanksLevel" => $tankLevel, "lastTanksLevel" => $tankLastLevel, "valveTanksInput" => $tankValve);
echo json_encode($out);