<?php
/**
 ********************************************
 * Masters of Endurance tracker / LFS-Tracker 
 ********************************************
 * 
 * Copyright © 2007 Wolfgang Tom (WolleT)
 * v1.0 originally written by Wolfgang Tom
 * 
 * Copyright © 2009-2011 Michael Booth (Boothy)
 * v2.0 tracker modified by Michael Booth
 * 
 * Thanks also to Casper Roescher (Kaspur).  
 * 
 * Latest tracker version available from the LFS forum thread - http://www.lfsforum.net/showthread.php?t=73414
 * Any code changes/improvements can be submitted for inclusion in the public tracker version. 
 * E-mail me at web@michaelbooth.me.uk or PM me via http://www.lfsforum.net/private.php?do=newpm&u=202039
 * 
 ********************************************
 * 
 * DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
 * Version 2, December 2004

 * Copyright © 2004 Sam Hocevar <sam@hocevar.net>

 * Everyone is permitted to copy and distribute verbatim or modified
 * copies of this license document, and changing it is allowed as long
 * as the name is changed.

 * DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
 * TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

 * 0. You just DO WHAT THE FUCK YOU WANT TO. 
 * 
 ******************************************** 
 * See http://sam.zoy.org/wtfpl/ for more information
 **/
// REQUIRED FILES
require 'config.php';
require 'functions.php';
require 'variables.php';
require 'sql.php';
// CONNECT TO DB
$link = mysql_connect(SQL_HOST, SQL_USER, SQL_PASS);
if (!$link) {
    die('Could not connect: ' . mysql_error());
} else {
    mysql_select_db(SQL_DB);
    mysql_set_charset('utf8');
    // NUMBER OF SERVERS
    $rid_string = 'AND ( ';
    for ($s = 1; $s < ($numServers + 1); ++$s) {
        $name = 'manualIdServer' . $s;
        if (${$name}) {
            $race_id = ${$name};
        } else {
            $r_res = mysql_query("SELECT max(id) AS id FROM " . SQL_RACE . " where server='$s' AND type='race'") or
                die(mysql_error());
            $race_id = mysql_result($r_res, 0, 'id');
        }
        if ($s > 1) {
            $rid_string .= " OR race_id='" . $race_id . "' ";
        } elseif ($numServers == 1 && $serverCrash) {
            $rid_string = "AND ( race_id>='" . $race_id . "'";
        } elseif ($numServers == 1 && $allRaceids) {
            $rid_string = "AND ( race_id<='" . $race_id . "'";
        } else {
            $rid_string = "AND ( race_id='" . $race_id . "'";
        }

    }
    $rid_string .= " ) ";
}
// GET TIMESTAMP OF WHEN RACE WAS STARTED
$race_res = mysql_query("SELECT created_on FROM " . SQL_LAP .
    " WHERE type='RACE_START' " . $rid_string . " ORDER BY race_id asc") or die(mysql_error
    ());
if (mysql_num_rows($race_res) > 0)
    $race_start = mysql_result($race_res, 0);
// SET UP $XMLRACE ARRAY
$XMLRACE['race_start'] = $race_start;
$XMLRACE['num_sectors'] = $raceNumSectors;
$XMLRACE['raceTrackLengthKm'] = $raceTrackLengthKm;
if (!isset($raceHours) and !isset($raceMins) and !isset($raceLaps)) {
    print 'No race time specified.';
    die;
}
$XMLRACE['timeHours'] = $raceHours;
$XMLRACE['timeMins'] = $raceMins;
$XMLRACE['timeLaps'] = $raceLaps;
$trackstatusfilename = "trackstatus.txt";
$fh = fopen($trackstatusfilename, "r") or print ('Could not open track status file!');
if (filesize($trackstatusfilename) == 0) {
    $trackstatus = "";
} else {
    $trackstatus = fread($fh, filesize($trackstatusfilename)) or print ('Could not read track status file!');
    fclose($fh);
}
$XMLRACE['session_status'] = $trackstatus;
$XMLRACE['fastest_lap'] = 99999999999;
$XMLRACE['numClasses'] = $raceClasses;
for ($o = 1; $o <= count($raceClassName); ++$o) {
    $p = $raceClassName[$o];
    $XMLRACE['classes'][$p]['name'] = $raceClassName[$o];
    $XMLRACE['classes'][$p]['position'] = 1;
    $XMLRACE['classes'][$p]['fastest_lap'] = 99999999999;
}
$XMLRACE['first-i_on_same_lap'] = 0;
global $XMLRACE;
$XMLTEAM = array();
//FIND PIT STOPS
$pitstop_search = mysql_query("SELECT value, created_on FROM " . SQL_LAP .
    " WHERE type='MSG' AND value LIKE '% pit stop'" . $rid_string .
    " ORDER BY race_id asc");
//FIND DRIVE-THROUGH PENALTIES
$dt_search = mysql_query("SELECT value FROM " . SQL_LAP .
    " WHERE type='MSG' AND (value LIKE '% : completed DRIVE-THROUGH PENALTY' OR value LIKE '% completed ___ DRIVE-THROUGH PENALTY')" .
    $rid_string . " ORDER BY race_id asc");
//FIND STOP-GO PENALTIES
$sg_search = mysql_query("SELECT value FROM " . SQL_LAP .
    " WHERE type='MSG' AND (value LIKE '% : completed STOP-GO PENALTY' OR value LIKE '% completed ___ STOP-GO PENALTY')" .
    $rid_string . " ORDER BY race_id asc");
//FIND FINISHED TEAMS
mysql_set_charset('latin1');
$finished = mysql_query("SELECT value,created_on FROM " . SQL_LAP .
    " WHERE type='MSG' AND (value LIKE '%^L finished %' OR value LIKE '%^L won the race')" .
    $rid_string . " ORDER BY race_id asc");
$finishedDrivers = array();
while ($r = mysql_fetch_array($finished))
    $finishedDrivers[] = $r;
mysql_set_charset('utf8');
//FIND PIT IN AND PIT OUT
$pitinout_search = mysql_query("SELECT id,lfsworld,type,race_id,created_on FROM " .
    SQL_LAP . " WHERE (type='PITIN' OR type='PITOUT') AND (lfsworld != '') " . $rid_string .
    " ORDER BY race_id asc, id asc");
while ($r = mysql_fetch_array($pitstop_search))
    $pitstop_array[] = $r;
while ($r = mysql_fetch_array($dt_search))
    $dt_array[] = $r;
while ($r = mysql_fetch_array($sg_search))
    $sg_array[] = $r;
while ($r = mysql_fetch_array($pitinout_search))
    $pitinout_array[] = $r;
//GO THROUGH EACH TEAM FROM THE TEAMS.YAML ARRAY
$time2 = microtime(true);
foreach ($TEAMS as $key => $team) {
    $XMLTEAM[$key]['team_data'] = array();
    $XMLTEAM[$key]['team_data']['name'] = $TEAMS[$key]['team_name'];
    $XMLTEAM[$key]['team_data']['class'] = $TEAMS[$key]['class'];
    $XMLTEAM[$key]['team_data']['car'] = $TEAMS[$key]['car'];
    $XMLTEAM[$key]['team_data']['number'] = $TEAMS[$key]['number'];
    if ($showServer) {
        $XMLTEAM[$key]['team_data']['server'] = $TEAMS[$key]['server'];
    }
    $XMLTEAM[$key]['team_data']['grid'] = $TEAMS[$key]['grid'];
    $XMLTEAM[$key]['race_data']['penalty_laps'] = $TEAMS[$key]['penalty_laps'];
    if ($XMLTEAM[$key]['race_data']['penalty_laps'] < 0) {
        $XMLTEAM[$key]['race_data']['penalty_laps_teamstats'] = 0;
    } else {
        $XMLTEAM[$key]['race_data']['penalty_laps_teamstats'] = $XMLTEAM[$key]['race_data']['penalty_laps'];
    }
    $XMLTEAM[$key]['race_data']['penalty_time'] = $TEAMS[$key]['penalty_time'];
    $XMLTEAM[$key]['team_data']['team_status'] = $TEAMS[$key]['team_status'];
    $XMLTEAM[$key]['team_data']['team_status_num'] = 1;
    switch (strtoupper($XMLTEAM[$key]['team_data']['team_status'])) {
        case "NC":
            $XMLTEAM[$key]['team_data']['team_status_num'] = 2;
            break;
        case "RET":
            $XMLTEAM[$key]['team_data']['team_status_num'] = 3;
            break;
        case "DQ":
            $XMLTEAM[$key]['team_data']['team_status_num'] = 4;
            break;
        case "DNS":
            $XMLTEAM[$key]['team_data']['team_status_num'] = 5;
            break;
    }
    //$XMLTEAM[$key]['team_data']['class_position'] = 0;
    $XMLTEAM[$key]['team_data']['finished'] = false;
    $i = 0;
    foreach ($TEAMS[$key]['driver_active'] as $k => $active) {
        if ($active) // ALWAYS TRUE!
            {
            $XMLTEAM[$key]['team_data']['drivers'][$i]['driver_lfs'] = mb_strtolower($TEAMS[$key]['driver_lfs'][$k],
                'UTF-8');
            $XMLTEAM[$key]['team_data']['drivers'][$i]['driver_full'] = $TEAMS[$key]['driver_real'][$k];
            $XMLTEAM[$key]['team_data']['drivers'][$i]['driver_real'] = format_name($TEAMS[$key]['driver_real'][$k],
                " ");
            $XMLTEAM[$key]['team_data']['drivers'][$i]['driver_country'] = $TEAMS[$key]['driver_country'][$k];
            // check if team has finished after time has elapsed
            if (((($XMLRACE['race_start'] + ($XMLRACE['timeHours'] * 60 * 60) + ($raceFinishOffset *
                60)) - time()) <= 0) || strtoupper($XMLRACE['session_status']) ==
                "CHEQUERED FLAG" && $trimFinished) {
                foreach ($finishedDrivers as $msg) {
                    $hayStack = codepage_convert($msg['value']);
                    $needle = format_name($TEAMS[$key]['driver_real'][$k], "");
                    $hayStack = str_replace(' ', '', $hayStack);
                    $teamFinished = (strpos($hayStack, $needle) === false) ? false : true;
                    if ($teamFinished) {
                        $output = "Driver " . $TEAMS[$key]['driver_real'][$k] .
                            " finished the race for team " . $XMLTEAM[$key]['team_data']['name'];
                        $team['finished_on'] = $msg['created_on'];
                        $XMLTEAM[$key]['team_data']['finished'] = true;
                        $XMLTEAM[$key]['team_data']['finished_time'] = $team['finished_on'];
                    }
                }
            }
            ++$i;
        }
    }
    $XMLTEAM[$key]['team_data']['num_drivers'] = $i;
    //<!-- Group the drivers together and get all the LAPs they drove from the database -->
    $timeLimit = null;
    // cut off finished teams
    if (isset($team['finished_on']) && $team['finished_on'] != "") {
        $finishTime = $team['finished_on'];
        $timeLimit = " AND `created_on` <= '" . $finishTime . "' ";
    }
    $drivers = generateDriverString($team);
    $sql = "SELECT id, lfsworld, value, lap, created_on, time FROM " . SQL_LAP .
        " WHERE type='LAP' $timeLimit AND (" . $drivers . ") " . $rid_string .
        " ORDER BY race_id ASC, created_on ASC";
    $sql_res = mysql_query($sql);
    $sql_dummy = $sql_res;
    //<!-- Put the laps into an array -->
    $i = 0;
    while ($res = mysql_fetch_object($sql_res)) {
        $XMLTEAM[$key]['raw_laps'][$i]['lap'] = $res->lap;
        $XMLTEAM[$key]['raw_laps'][$i]['laptime'] = $res->value;
        $XMLTEAM[$key]['raw_laps'][$i]['driverUserName'] = mb_strtolower($res->lfsworld,
            'UTF-8');
        $XMLTEAM[$key]['raw_laps'][$i]['logged'] = $res->created_on;
        $XMLTEAM[$key]['raw_laps'][$i]['sessiontime'] = $res->time;
        $XMLTEAM[$key]['raw_laps'][$i]['mysqlid'] = $res->id;
        ++$i;
    }
    /*
    for ($j=0 ; $j<$XMLTEAM[$key]['raw_laps'][0]['lap'] ; $j++, $i++) {
    $XMLTEAM[$key]['raw_laps'][$i]['lap'] = $XMLTEAM[$key]['raw_laps'][0]['lap'];
    $XMLTEAM[$key]['raw_laps'][$i]['laptime'] = $XMLTEAM[$key]['raw_laps'][0]['laptime'];
    $XMLTEAM[$key]['raw_laps'][$i]['driverUserName'] = $XMLTEAM[$key]['raw_laps'][0]['driverUserName'];
    $XMLTEAM[$key]['raw_laps'][$i]['logged'] = $XMLTEAM[$key]['raw_laps'][0]['logged'];
    $XMLTEAM[$key]['raw_laps'][$i]['mysqlid'] = $XMLTEAM[$key]['raw_laps'][0]['mysqlid'];
    }
    */
    $XMLTEAM[$key]['filter_laps'] = filterLaps($XMLTEAM[$key]['raw_laps']);
    if ($XMLTEAM[$key]['filter_laps'] === $XMLTEAM[$key]['raw_laps']) {
        unset($XMLTEAM[$key]['raw_laps']);
    }
    $XMLTEAM[$key]['race_data']['laps'] = countLaps($XMLTEAM[$key]['filter_laps']);
    $XMLTEAM[$key]['race_data']['corrected_laps'] = $XMLTEAM[$key]['race_data']['laps'] +
        $TEAMS[$key]['penalty_laps'];
    $XMLTEAM[$key]['race_data']['total_time'] = totalTime($XMLTEAM[$key]['filter_laps'],
        $race_start) - ($XMLTEAM[$key]['race_data']['penalty_time'] * 100);
    $XMLTEAM[$key]['race_data']['total_sessiontime'] = $XMLTEAM[$key]['filter_laps'][($XMLTEAM[$key]['race_data']['laps'] -
        1)]['sessiontime'] - ($XMLTEAM[$key]['race_data']['penalty_time'] * 1000);

    // COUNT NUMBER OF PITSTOPS
    $pitted = 0;
    if (isset($pitstop_array)) {
        foreach ($pitstop_array as $pitstop_value) {
            if (inTeam($pitstop_value['value'], $team['number'])) {
                //$XMLTEAM[$key]['race_data']['last_pit'] = $pitstop_value['created_on'];
                if ((!$trimFinished or $pitstop_value['created_on'] <= $XMLTEAM[$key]['team_data']['finished_time'] or
                    !$XMLTEAM[$key]['team_data']['finished']) or $XMLTEAM[$key]['team_data']['team_status_num'] >
                    1) {
                    ++$pitted;
                }
            }
        }
    }
    $XMLTEAM[$key]['race_data']['num_pits'] = $pitted;
    // SAVE RECORD OF PITIN AND PITOUT MESSAGES
    $l = 0;
    if (count($pitinout_array) > 0) {
        foreach ($pitinout_array as $pitio_value) {
            for ($k = 0; $k < $XMLTEAM[$key]['team_data']['num_drivers']; ++$k) {
                if ((!$trimFinished or $pitio_value['created_on'] <= $XMLTEAM[$key]['team_data']['finished_time'] or
                    !$XMLTEAM[$key]['team_data']['finished']) or $XMLTEAM[$key]['team_data']['team_status_num'] >
                    1) {
                    if (mb_strtolower($pitio_value['lfsworld'], 'UTF-8') == $XMLTEAM[$key]['team_data']['drivers'][$k]['driver_lfs']) {
                        $XMLTEAM[$key]['race_data']['pitstops'][$l]['type'] = $pitio_value['type'];
                        $XMLTEAM[$key]['race_data']['pitstops'][$l]['time'] = $pitio_value['created_on'];
                        //$XMLTEAM[$key]['race_data']['pitstops'][$l]['lap'] = $pitio_value['lap'];
                        $XMLTEAM[$key]['race_data']['pitstops'][$l]['mysqlid'] = $pitio_value['id'];
                        ++$l;
                    }
                }
            }
        }
    }
    $XMLTEAM[$key]['race_data']['last_pit_index'] = $l;
    // COUNT NUMBER OF DRIVE THROUGHS
    if (isset($dt_array)) {
        $dt = 0;
        if (count($dt_array) > 0) {
            foreach ($dt_array as $dt_value) {
                if (inTeam($dt_value['value'], $team['number']))
                    ++$dt;
            }
            $XMLTEAM[$key]['race_data']['num_dt'] = $dt;
        } else
            $XMLTEAM[$key]['race_data']['num_dt'] = 0;
    } else
        $XMLTEAM[$key]['race_data']['num_dt'] = 0;
    // COUNT NUMBER OF STOP-GOs
    if (isset($sg_array)) {
        $sg = 0;
        if (count($sg_array) > 0) {
            foreach ($sg_array as $sg_value) {
                if (inTeam($sg_value['value'], $team['number']))
                    ++$sg;
            }
            $XMLTEAM[$key]['race_data']['num_sg'] = $sg;
        } else
            $XMLTEAM[$key]['race_data']['num_sg'] = 0;
    } else
        $XMLTEAM[$key]['race_data']['num_sg'] = 0;
    // COUNT NUMBER OF DRIVER SWAPS
    $swap = 0;
    for ($i = 1; $i < $XMLTEAM[$key]['race_data']['laps']; ++$i) {
        if ($XMLTEAM[$key]['filter_laps'][$i]['driverUserName'] != $XMLTEAM[$key]['filter_laps'][$i -
            1]['driverUserName'])
            ++$swap;
    }
    $XMLTEAM[$key]['race_data']['num_swap'] = $swap;
    // DETERMINE THE CURRENT POSITION OF THE CAR
    // DETERMINE THE DRIVER CURRENTLY IN THE CAR
    $sql_res2 = mysql_query("SELECT type, lfsworld FROM " . SQL_LAP .
        " WHERE (type='LAP' OR type='SP1' OR type='SP2' OR type='SP3') $timeLimit AND (" .
        $drivers . ") " . $rid_string . " ORDER BY race_id DESC, id DESC LIMIT 0, 1");
    $XMLTEAM[$key]['race_data']['current_driver'] = "";
    if ($XMLTEAM[$key]['race_data']['laps'] > 0) {
        if (mysql_result($sql_res2, 0, 'type') == "LAP")
            $XMLTEAM[$key]['race_data']['current_sector'] = 0;
        if (mysql_result($sql_res2, 0, 'type') == "SP1")
            $XMLTEAM[$key]['race_data']['current_sector'] = 1;
        if (mysql_result($sql_res2, 0, 'type') == "SP2")
            $XMLTEAM[$key]['race_data']['current_sector'] = 2;
        if (mysql_result($sql_res2, 0, 'type') == "SP3")
            $XMLTEAM[$key]['race_data']['current_sector'] = 3;
        $XMLTEAM[$key]['race_data']['current_driver'] = mb_strtolower(mysql_result($sql_res2,
            0, 'lfsworld'), 'UTF-8');
    } else {
        $XMLTEAM[$key]['race_data']['current_sector'] = 0;
    }
}
// SORT STANDINGS
if ($sortStatus) {
    usort($XMLTEAM, "sort_standings_status");
} else
    usort($XMLTEAM, "sort_standings");
$amountTeams = count($XMLTEAM);
for ($i = 0; $i < $amountTeams; ++$i) {
    $XMLTEAM[$i]['race_data']['position'] = ($i + 1);
    // TO DIFF TO CAR AHEAD
    if ($i > 0) {
        if ($XMLTEAM[$i]['race_data']['laps'] > 0)
            if (($XMLTEAM[$i - 1]['race_data']['corrected_laps'] - $XMLTEAM[$i]['race_data']['corrected_laps']) >
                1)
                $XMLTEAM[$i]['race_data']['dist_to_car_in_front'] = "" . ($XMLTEAM[$i - 1]['race_data']['corrected_laps'] -
                    $XMLTEAM[$i]['race_data']['corrected_laps']) . " laps";
            elseif (($XMLTEAM[$i - 1]['race_data']['corrected_laps'] - $XMLTEAM[$i]['race_data']['corrected_laps']) >
                0)
                $XMLTEAM[$i]['race_data']['dist_to_car_in_front'] = "" . ($XMLTEAM[$i - 1]['race_data']['corrected_laps'] -
                    $XMLTEAM[$i]['race_data']['corrected_laps']) . " lap";
            else
                $XMLTEAM[$i]['race_data']['dist_to_car_in_front'] = normalTime($XMLTEAM[$i]['race_data']['total_sessiontime'] -
                    $XMLTEAM[$i - 1]['race_data']['total_sessiontime'], true, false, false, false, false, true);
        else
            $XMLTEAM[$i]['race_data']['dist_to_car_in_front'] = "";
    } else
        $XMLTEAM[$i]['race_data']['dist_to_car_in_front'] = "";
    // GAP TO LEADER
    if ($i > 0) {
        if ($XMLTEAM[$i]['race_data']['laps'] > 0) {
            if (($XMLTEAM[0]['race_data']['corrected_laps'] - $XMLTEAM[$i]['race_data']['corrected_laps']) >
                1) {
                $XMLTEAM[$i]['race_data']['dist_to_lead_car'] = "" . ($XMLTEAM[0]['race_data']['corrected_laps'] -
                    $XMLTEAM[$i]['race_data']['corrected_laps']) . " laps";
            } elseif (($XMLTEAM[0]['race_data']['corrected_laps'] - $XMLTEAM[$i]['race_data']['corrected_laps']) >
            0) {
                $XMLTEAM[$i]['race_data']['dist_to_lead_car'] = "" . ($XMLTEAM[0]['race_data']['corrected_laps'] -
                    $XMLTEAM[$i]['race_data']['corrected_laps']) . " lap";
            } else {
                $XMLTEAM[$i]['race_data']['dist_to_lead_car'] = normalTime($XMLTEAM[$i]['race_data']['total_sessiontime'] -
                    $XMLTEAM[0]['race_data']['total_sessiontime'], true, false, false, false, false, true, false, false);
            }
            if ($XMLTEAM[$i]['race_data']['corrected_laps'] != $XMLTEAM[$i - 1]['race_data']['corrected_laps']) {
                $XMLRACE['first-i_on_same_lap'] = $i;
            } else {
                $XMLTEAM[$i]['race_data']['indexgap'] = "" . normalTime($XMLTEAM[$i]['race_data']['total_sessiontime'] -
                    $XMLTEAM[$XMLRACE['first-i_on_same_lap']]['race_data']['total_sessiontime'], true, false, false, false, false, true, false, false);
            }
        } else
            $XMLTEAM[$i]['race_data']['dist_to_lead_car'] = "";
    } else
        $XMLTEAM[$i]['race_data']['dist_to_lead_car'] = $XMLTEAM[$i]['race_data']['corrected_laps'] .
            " laps";
    // DRIVER LAP COUNT, FASTEST LAP AND DRIVING TIME
    for ($k = 0; $k < $XMLTEAM[$i]['race_data']['laps']; ++$k) {
        for ($l = 0; $l < $XMLTEAM[$i]['team_data']['num_drivers']; ++$l) {
            if (mb_strtolower($XMLTEAM[$i]['filter_laps'][$k]['driverUserName'], 'UTF-8') ==
                $XMLTEAM[$i]['team_data']['drivers'][$l]['driver_lfs']) {
                if ($XMLTEAM[$i]['filter_laps'][$k]['laptime'] != 0 && $XMLTEAM[$i]['team_data']['drivers'][$l]['fastest_lap']) {
                    $XMLTEAM[$i]['team_data']['drivers'][$l]['fastest_lap'] = min($XMLTEAM[$i]['team_data']['drivers'][$l]['fastest_lap'],
                        $XMLTEAM[$i]['filter_laps'][$k]['laptime']);
                } else {
                    $XMLTEAM[$i]['team_data']['drivers'][$l]['fastest_lap'] = $XMLTEAM[$i]['filter_laps'][$k]['laptime'];
                }
                if (is_numeric($standingStart) && $k >= $standingStart) {
                    $standingStartOffset = $standingStart;
                    ++$XMLTEAM[$i]['team_data']['drivers'][$l]['laps'];
                    $XMLTEAM[$i]['team_data']['drivers'][$l]['driving_time'] += $XMLTEAM[$i]['filter_laps'][$k]['laptime'];
                } elseif (($standingStart == false || $standingStart == "formation") && ($k > 0)) {
                    $standingStartOffset = 1;
                    ++$XMLTEAM[$i]['team_data']['drivers'][$l]['laps'];
                    $XMLTEAM[$i]['team_data']['drivers'][$l]['driving_time'] += $XMLTEAM[$i]['filter_laps'][$k]['laptime'];
                } elseif ($standingStart === true) {
                    $standingStartOffset = 0;
                    ++$XMLTEAM[$i]['team_data']['drivers'][$l]['laps'];
                    $XMLTEAM[$i]['team_data']['drivers'][$l]['driving_time'] += $XMLTEAM[$i]['filter_laps'][$k]['laptime'];
                }
            }
        }
    }
    // DRIVER AVERAGE LAPS
    if ($averagelap !== false) {
        for ($k = 0; $k < $XMLTEAM[$i]['race_data']['laps']; ++$k) {
            for ($l = 0; $l < $XMLTEAM[$i]['team_data']['num_drivers']; ++$l) {
                if (mb_strtolower($XMLTEAM[$i]['filter_laps'][$k]['driverUserName'], 'UTF-8') ==
                    $XMLTEAM[$i]['team_data']['drivers'][$l]['driver_lfs']) {
                    if ($averagelap > 100) {
                        if ($XMLTEAM[$i]['filter_laps'][$k]['laptime'] < ($XMLTEAM[$i]['team_data']['drivers'][$l]['fastest_lap'] *
                            $averagelap / 100)) {
                            $XMLTEAM[$i]['team_data']['drivers'][$l]['average_time'] += $XMLTEAM[$i]['filter_laps'][$k]['laptime'];
                            $XMLTEAM[$i]['team_data']['drivers'][$l]['average_laps']++;
                        }
                    } else {
                        $XMLTEAM[$i]['team_data']['drivers'][$l]['average_time'] += $XMLTEAM[$i]['filter_laps'][$k]['laptime'];
                        $XMLTEAM[$i]['team_data']['drivers'][$l]['average_laps']++;
                    }
                }
            }
        }
    }
    // DRIVER PERCENTAGES, TEAM FASTEST LAP AND AVERAGE TIME
    for ($l = 0; $l < $XMLTEAM[$i]['team_data']['num_drivers']; ++$l) {
        if ($XMLTEAM[$i]['team_data']['drivers'][$l]['fastest_lap'] > 0) {
            if ($XMLTEAM[$i]['team_data']['drivers'][$l]['laps'] > 0) {
                $XMLTEAM[$i]['team_data']['drivers'][$l]['percent'] = round((($XMLTEAM[$i]['team_data']['drivers'][$l]['laps'] /
                    ($XMLTEAM[$i]['race_data']['laps'] - $standingStartOffset)) * 100), 2) . "%";
            }
            if ($XMLTEAM[$i]['race_data']['fastest_lap']) {
                $XMLTEAM[$i]['race_data']['fastest_lap'] = min($XMLTEAM[$i]['team_data']['drivers'][$l]['fastest_lap'],
                    $XMLTEAM[$i]['race_data']['fastest_lap']);
            } else {
                $XMLTEAM[$i]['race_data']['fastest_lap'] = $XMLTEAM[$i]['team_data']['drivers'][$l]['fastest_lap'];
            }
        }
        if ($averagelap !== false && $XMLTEAM[$i]['team_data']['drivers'][$l]['average_laps']) {
            $XMLTEAM[$i]['team_data']['drivers'][$l]['average_time'] = ($XMLTEAM[$i]['team_data']['drivers'][$l]['average_time'] /
                $XMLTEAM[$i]['team_data']['drivers'][$l]['average_laps']);
        }
        if ($XMLTEAM[$i]['race_data']['current_driver'] == $XMLTEAM[$i]['team_data']['drivers'][$l]['driver_lfs']) {
            $XMLTEAM[$i]['race_data']['current_driver_num'] = $l;
        }
    }
    // RACE FASTEST LAP AND CLASS FASTEST LAP
    if (($XMLTEAM[$i]['race_data']['fastest_lap'] < $XMLRACE['fastest_lap']) && $XMLTEAM[$i]['race_data']['fastest_lap'] >
        0) {
        $XMLRACE['fastest_lap'] = $XMLTEAM[$i]['race_data']['fastest_lap'];
    }
    if (($XMLTEAM[$i]['race_data']['fastest_lap'] < $XMLRACE['classes'][($XMLTEAM[$i]['team_data']['class'])]['fastest_lap']) &&
        $XMLTEAM[$i]['race_data']['fastest_lap'] > 0) {
        $XMLRACE['classes'][($XMLTEAM[$i]['team_data']['class'])]['fastest_lap'] = $XMLTEAM[$i]['race_data']['fastest_lap'];
    }
}
$totalloop += (microtime(true) - $time2);
if ($raceControl) {
    mysql_set_charset('latin1');
    $chat_search = mysql_query("SELECT lfsworld, type, value, created_on FROM " .
        SQL_LAP . " WHERE (type='MSG' OR type='JOIN' OR type='SHIFTS' OR type='RACE_START' OR type='LEAVE')" .
        $rid_string . " ORDER BY race_id asc, created_on asc");
    while ($r = mysql_fetch_array($chat_search))
        $chat_array[] = $r;
    $XMLCHAT = array();
    $k = 0;
    // if (!empty($chat)) {
    if (($futureRaceStart - time() <= 0) or (strtoupper($XMLRACE['session_status'])
        !== "PRE-RACE")) {
        foreach ($chat_array as $chat) {
            $XMLCHAT[$k]['lfsworld'] = $chat['lfsworld'];
            $XMLCHAT[$k]['type'] = $chat['type'];
            $XMLCHAT[$k]['value'] = $chat['value'];
            $XMLCHAT[$k]['logged'] = $chat['created_on'];
            ++$k;
        }
    }
    /* MAIN STATS OUTPUT */
    //ob_clean();
    ob_start();
    include ('racecontrol.php');
    $statsphp = ob_get_contents();
    ob_clean();
    writeToFile('racecontrol.html', $statsphp);
    unset($statsphp);
    ob_clean();
}
ob_start();
include ('stats.php');
$statsphp = ob_get_contents();
ob_clean();
writeToFile('index.html', $statsphp);
unset($statsphp);
ob_clean();
/*
ob_start();
include ('mobile.php');
$mobilephp = ob_get_contents();
ob_clean();
writeToFile('mobile.html', $mobilephp);
unset($mobilephp);*/
foreach ($XMLTEAM as $i => $team) {
    ob_start();
    include ('teamstats.php');
    $teamstats = ob_get_contents();
    ob_clean();
    writeToFile('team_' . $team['team_data']['number'] . '.html', $teamstats);
    //sleep(1);
}
reset($XMLTEAM);
foreach ($XMLTEAM as $j => $team) {
    ob_start();
    include ('unfiltered.php');
    $teamstats = ob_get_contents();
    ob_clean();
    writeToFile('race_' . $team['team_data']['number'] . '.html', $teamstats);
    //sleep(1);
}

if (strtoupper($XMLRACE['session_status']) !== "PRE-RACE" || strtoupper($XMLRACE['session_status'])
    !== "CHEQUERED FLAG" || strtoupper($XMLRACE['session_status']) !== "FINISHED") {
    $hour2 = 0;
    $diff2 = (time() - $XMLRACE['race_start']);
    $hour2 = floor($diff2 / (60 * 60));
    $hour2 = intval($hour2);
    $filename = 'hour_' . $hour2 . '.html';
    if (!is_readable($filename) && $hour2 >= 0 && $hour2 <= $raceHours) {
        $file = 'index.html';
        $newfile = $filename;
        if (!copy($file, $newfile)) {
            echo "<p>failed to copy $file...</p>";
        }
        if ($twitterPositions && $hour2 > 0) {
            $gt1tweet = "Hour $hour2 positions - ";
            $gt2tweet = "Hour $hour2 GT2 positions - ";
            for ($i = 0; $i < 3; $i++) {
                if ($XMLTEAM[$i]['team_data']['position'] <= 3) {
                    //  if ($XMLTEAM[$i]['team_data']['class'] == "GT1") {
                    if ($i == 0) {
                        $gt1tweet .= $XMLTEAM[$i]['team_data']['name'] . " " . $XMLTEAM[$i]['race_data']['corrected_laps'] .
                            " laps";
                    } elseif (isset($XMLTEAM[$i]['race_data']['indexgap'])) {
                        $gt1tweet .= $XMLTEAM[$i]['team_data']['name'] . " +" . $XMLTEAM[$i]['race_data']['indexgap'];
                    } else {
                        $gt1tweet .= $XMLTEAM[$i]['team_data']['name'] . " +" . $XMLTEAM[$i]['race_data']['dist_to_lead_car'];
                    }
                    // if ($XMLTEAM[$i]['team_data']['class_position'] < 3) {
                    $gt1tweet .= ", ";
                    //}
                    /*} else {
                    if ($XMLTEAM[$i]['team_data']['class'] == "GT2") {
                    if ($XMLTEAM[$i]['team_data']['class_position'] == 1) {
                    $gt2tweet .= $XMLTEAM[$i]['team_data']['name'] . " " . $XMLTEAM[$i]['race_data']['corrected_laps'] .
                    " laps";
                    } elseif (isset($XMLTEAM[$i]['race_data']['indexgap'])) {
                    $gt2tweet .= $XMLTEAM[$i]['team_data']['name'] . " +" . $XMLTEAM[$i]['race_data']['indexgap'];
                    } else {
                    $gt2tweet .= $XMLTEAM[$i]['team_data']['name'];
                    $gt2tweet .= " +" . ($XMLRACE['classes']['GT2']['leaderslaps'] - $XMLTEAM[$i]['race_data']['corrected_laps']);
                    $gt2tweet .= ($XMLRACE['classes']['GT2']['leaderslaps'] - $XMLTEAM[$i]['race_data']['corrected_laps'] >
                    1) ? " laps" : " lap";
                    }
                    if ($XMLTEAM[$i]['team_data']['class_position'] < 3) {
                    $gt2tweet .= ", ";
                    }

                    }
                    }*/
                }
            }
            $gt1tweet .= " #gt2ws";
            $gt2tweet .= " #gt2ws";
            //echo $gt2tweet . "<br>";
            echo $gt1tweet;
            $consumerKey = '';
            $consumerSecret = '';
            $oAuthToken = '';
            $oAuthSecret = '';
            require_once ('twitteroauth.php');
            $tweet = new TwitterOAuth($consumerKey, $consumerSecret, $oAuthToken, $oAuthSecret);
            $tweet->post('statuses/update', array('status' => $gt1tweet));
            //$tweet->post('statuses/update', array('status' => $gt2tweet));

        }
    }

}
if ($debugArrays) {
    print_r($XMLRACE);
    print_r($XMLTEAM);
}

?>