function showCompetitionResultsByPerson($resultsTable = 'Results')
{
    #----------------------------------------------------------------------
    global $chosenByPerson, $chosenAllResults, $chosenTop3, $chosenWinners;
    global $chosenCompetitionId;
    #--- Get the results.
    $competitionResults = getCompetitionResults($resultsTable);
    startTimer();
    tableBegin('results', 8);
    foreach ($competitionResults as $result) {
        extract($result);
        $isNewPerson = !isset($previousPersonId) || $personId != $previousPersonId;
        $isNewEvent = !isset($previousEventId) || $eventId != $previousEventId || $isNewPerson;
        #--- Welcome new persons.
        if ($isNewPerson) {
            if (isset($previousPersonId)) {
                tableRowBlank();
            }
            $bo3_as_mo3 = $formatId == '3' && ($eventId == '333bf' || $eventId == '333fm' || $eventId == '333ft');
            $headerAverage = $formatId == 'a' || $formatId == 'm' || $bo3_as_mo3 ? 'Average' : '';
            $headerAllResults = $formatId != '1' ? 'Result Details' : '';
            tableCaptionNew(false, $personId, spaced(array(personLink($personId, $personName), $countryName)));
            tableHeader(explode('|', "Event|Round|Place|Best||{$headerAverage}||{$headerAllResults}"), array(2 => 'class="r"', 3 => 'class="R"', 5 => 'class="R"', 7 => 'class="f"'));
        }
        #--- One result row.
        tableRowStyled($isNewEvent ? '' : 'color:#AAA', array($isNewEvent ? eventLink($eventId, $eventCellName) : '', $roundCellName, $isNewEvent ? "<b>{$pos}</b>" : $pos, formatValue($best, $valueFormat), $regionalSingleRecord, formatValue($average, $valueFormat), $regionalAverageRecord, formatAverageSources($formatId != '1', $result, $valueFormat)));
        $previousPersonId = $personId;
        $previousEventId = $eventId;
    }
    tableEnd();
    stopTimer("printing the huge table");
}
function showRegionalRecordsHistory()
{
    #----------------------------------------------------------------------
    global $chosenRegionId, $chosenHistory, $chosenMixHist;
    #--- Compute the region condition and the normal record name.
    if (preg_match('/^(world)?$/i', $chosenRegionId)) {
        $regionCondition = "AND recordName = 'WR'";
        $normalRecordName = '';
    } elseif (preg_match('/^_/', $chosenRegionId)) {
        $tmp = dbQuery("SELECT recordName FROM Continents WHERE id = '{$chosenRegionId}'");
        $normalRecordName = $tmp[0][0];
        $regionCondition = "AND recordName in ('WR', '{$normalRecordName}' ) AND continentId = '{$chosenRegionId}'";
    } else {
        $regionCondition = "AND (recordName <> '') AND (result.countryId = '{$chosenRegionId}')";
        $normalRecordName = 'NR';
    }
    #--- Order: normal history or mixed?
    $order = $chosenHistory ? 'event.rank, type, value, year desc, month desc, day desc, roundId desc' : 'year desc, month desc, day desc, roundId desc, event.rank, type, value';
    #--- Get the results.
    $results = dbQuery("\n    SELECT\n      year, month, day,\n\n      event.id         eventId,\n      event.name       eventName,\n      event.cellName   eventCellName,\n\n      result.type      type,\n      result.value     value,\n      event.format     valueFormat,\n                       recordName,\n\n      result.personId   personId,\n      result.personName personName,\n\n      country.name     countryName,\n\n      competition.id   competitionId,\n      competition.cellName competitionName,\n\n      value1, value2, value3, value4, value5\n    FROM\n      (SELECT Results.*, 1 type, best    value, regionalSingleRecord  recordName FROM Results WHERE regionalSingleRecord<>'' UNION\n       SELECT Results.*, 2 type, average value, regionalAverageRecord recordName FROM Results WHERE regionalAverageRecord<>'') result,\n      Events event,\n      Competitions competition,\n      Countries country\n    WHERE " . randomDebug() . "\n      AND event.id = eventId\n      AND event.rank < 1000\n      AND competition.id = competitionId\n      AND country.id = result.countryId\n      {$regionCondition}\n      " . eventCondition() . yearCondition() . "\n    ORDER BY\n      {$order}\n  ");
    #--- Start the table
    if ($chosenHistory) {
        tableBegin('results', 7);
    } else {
        tableBegin('results', 9);
        tableHeader(explode('|', 'Date circa|Event|What|Single|Average|Person|Citizen of|Competition|Result Details'), array(3 => 'class="R2"', 4 => 'class="R2"', 8 => 'class="f"'));
    }
    #--- Process the results.
    $currentEventId = false;
    foreach ($results as $result) {
        extract($result);
        #--- Announce the event (only for normal history, not mixed)
        if ($chosenHistory && $eventId != $currentEventId) {
            $currentEventId = $eventId;
            tableCaptionNew(false, $eventId, eventLink($eventId, $eventName));
            tableHeader(explode('|', '|Single|Average|Person|Citizen of|Competition|Result Details'), array(1 => 'class="R2"', 2 => 'class="R2"', 6 => 'class="f"'));
        }
        #--- Determine how to display the record name.
        if ($recordName != $normalRecordName) {
            $recordName = "<span style='color:#f93;font-weight:bold'>{$recordName}</span>";
        }
        #--- Prepare the table row.
        $data = array($recordName, $type == 1 ? formatValue($value, $valueFormat) : '', $type == 2 ? formatValue($value, $valueFormat) : '', personLink($personId, $personName), $countryName, competitionLink($competitionId, $competitionName), formatAverageSources($type == 2, $result, $valueFormat));
        if ($chosenMixHist) {
            array_unshift($data, sprintf('%4d-%02d-%02d', $year, $month, $day), eventLink($eventId, $eventCellName));
        }
        #--- Show the table row.
        tableRow($data);
    }
    tableEnd();
}
function showResultsByEvents()
{
    #----------------------------------------------------------------------
    global $chosenPersonId;
    $results = dbQuery("\n    SELECT\n                           result.*,\n      event.name           eventName,\n      competition.cellName competitionCellName,\n      event.format         valueFormat,\n      round.cellName       roundCellName\n    FROM\n      Results result,\n      Events  event,\n      Competitions competition,\n      Rounds round\n    WHERE " . randomDebug() . "\n      AND personId = '{$chosenPersonId}'\n      AND event.id = eventId\n      AND event.rank < 1000\n      AND competition.id = competitionId\n      AND round.id = roundId\n    ORDER BY\n      event.rank, year DESC, month DESC, day DESC, competitionCellName, round.rank DESC\n  ");
    tableBegin('results', 8);
    tableCaption(false, "History (<a href='person_map.php?i={$chosenPersonId}'>Map</a>)");
    #--- Process results by event.
    foreach (structureBy($results, 'eventId') as $eventResults) {
        extract($eventResults[0]);
        #--- Announce the event.
        tableCaptionNew(false, $eventId, eventLink($eventId, $eventName));
        tableHeader(explode('|', 'Competition|Round|Place|Best||Average||Result Details'), array(2 => 'class="r"', 3 => 'class="R"', 5 => 'class="R"', 7 => 'class="f"'));
        #--- Initialize.
        $currentCompetitionId = '';
        #--- Compute PB Markers
        //$pbMarkers = [];
        $bestBest = 9999999999;
        $bestAverage = 9999999999;
        foreach (array_reverse($eventResults) as $result) {
            extract($result);
            $pbMarkers[$competitionId][$roundCellName] = 0;
            if ($best > 0 && $best <= $bestBest) {
                $bestBest = $best;
                $pbMarkers[$competitionId][$roundCellName] += 1;
            }
            if ($average > 0 && $average <= $bestAverage) {
                $bestAverage = $average;
                $pbMarkers[$competitionId][$roundCellName] += 2;
            }
        }
        #--- Show the results.
        foreach ($eventResults as $result) {
            extract($result);
            $isNewCompetition = $competitionId != $currentCompetitionId;
            $currentCompetitionId = $competitionId;
            $formatBest = formatValue($best, $valueFormat);
            if ($pbMarkers[$competitionId][$roundCellName] % 2) {
                $formatBest = "<span style='color:#F60;font-weight:bold'>{$formatBest}</span>";
            }
            $formatAverage = formatValue($average, $valueFormat);
            if ($pbMarkers[$competitionId][$roundCellName] > 1) {
                $formatAverage = "<span style='color:#F60;font-weight:bold'>{$formatAverage}</span>";
            }
            tableRowStyled($isNewCompetition ? '' : 'color:#AAA', array($isNewCompetition ? competitionLink($competitionId, $competitionCellName) : '', $roundCellName, $isNewCompetition ? "<b>{$pos}</b>" : $pos, $formatBest, $regionalSingleRecord, $formatAverage, $regionalAverageRecord, formatAverageSources(true, $result, $valueFormat)));
        }
    }
    tableEnd();
}
function showCompetitionResults($competitionId, $eventId, $roundId)
{
    #----------------------------------------------------------------------
    # NOTE: This is mostly a copy of the same function in competition_results.php
    #--- Get the results.
    $competitionResults = getCompetitionResults($competitionId, $eventId, $roundId);
    tableBegin('results', 8);
    $prevEventId = $prevRoundId = '';
    foreach ($competitionResults as $result) {
        extract($result);
        $isNewEvent = $eventId != $prevEventId;
        $isNewRound = $roundId != $prevRoundId;
        #--- Welcome new rounds.
        if ($isNewEvent || $isNewRound) {
            $anchors = ($isNewEvent ? "{$eventId} " : "") . "{$eventId}_{$roundId}";
            $eventHtml = eventLink($eventId, $eventName);
            $caption = spaced(array($eventHtml, $roundName, $formatName));
            tableCaptionNew(false, $anchors, $caption);
            $bo3_as_mo3 = $formatId == '3' && ($eventId == '333bf' || $eventId == '333fm' || $eventId == '333ft');
            $headerAverage = $formatId == 'a' || $formatId == 'm' || $bo3_as_mo3 ? 'Average' : '';
            $headerAllResults = $formatId != '1' ? 'Result Details' : '';
            tableHeader(explode('|', "Place|Person|Best||{$headerAverage}||Citizen of|{$headerAllResults}"), array(0 => 'class="r"', 2 => 'class="R"', 4 => 'class="R"', 7 => 'class="f"'));
        }
        #--- One result row.
        tableRow(array($pos, personLink($personId, $personName), formatValue($best, $valueFormat), $regionalSingleRecord, formatValue($average, $valueFormat), $regionalAverageRecord, $countryName, formatAverageSources($formatId != '1', $result, $valueFormat)));
        $prevEventId = $eventId;
        $prevRoundId = $roundId;
    }
    tableEnd();
}
function showQualifications($competitionId, $eventId, $roundId1, $roundId2)
{
    #----------------------------------------------------------------------
    global $competitionResults1, $competitionResults2, $personsBothRounds;
    getQualifications($competitionId, $eventId, $roundId1, $roundId2);
    tableBegin('results', 8);
    #--- Display competitors only in round 2
    foreach ($competitionResults2 as $key => $result) {
        if (in_array($result['personId'], $personsBothRounds)) {
            continue;
        }
        extract($result);
        #--- Header
        if (!$captionShowed) {
            $anchors = "{$eventId} " . "{$eventId}_{$roundId}";
            $eventHtml = eventLink($eventId, $eventName);
            $caption = spaced(array($eventHtml, $roundName, $formatName));
            tableCaptionNew(false, $anchors, $caption);
            $headerAverage = $formatId == 'a' || $formatId == 'm' ? 'Average' : '';
            $headerAllResults = $formatId != '1' ? 'Result Details' : '';
            tableHeader(explode('|', "Person|Place|Best|{$headerAverage}|Place|Best|{$headerAverage}|"), array(1 => 'class="r"', 2 => 'class="R"', 3 => 'class="R"', 4 => 'class="r"', 5 => 'class="R"', 6 => 'class="R"', 7 => 'class="f"'));
            $captionShowed = true;
        }
        #--- One result row.
        tableRow(array(personLink($personId, $personName), '', '', '', $pos, formatValue($best, $valueFormat), formatValue($average, $valueFormat), ''));
        unset($competitionResults2[$key]);
        // Little speed-up for the second part
    }
    #--- Display the rest
    foreach ($competitionResults1 as $result) {
        extract($result);
        $inRound2 = false;
        foreach ($competitionResults2 as $key => $result2) {
            if ($result2['personId'] == $personId) {
                extract($result2, EXTR_PREFIX_ALL, 'r2');
                unset($competitionResults2[$key]);
                $inRound2 = true;
                $nbQuals += 1;
                break;
            }
        }
        #--- Header
        if (!$captionShowed) {
            $anchors = "{$eventId} " . "{$eventId}_{$roundId}";
            $eventHtml = eventLink($eventId, $eventName);
            $caption = spaced(array($eventHtml, $roundName, $formatName));
            tableCaptionNew(false, $anchors, $caption);
            $headerAverage = $formatId == 'a' || $formatId == 'm' ? 'Average' : '';
            $headerAllResults = $formatId != '1' ? 'Result Details' : '';
            tableHeader(explode('|', "Person|Place|Best|{$headerAverage}|Place|Best|{$headerAverage}|"), array(1 => 'class="r"', 2 => 'class="R"', 3 => 'class="R"', 4 => 'class="r"', 5 => 'class="R"', 6 => 'class="R"', 7 => 'class="f"'));
            $captionShowed = true;
        }
        $offerToDelete = $inRound2 && 4 * $nbQuals > 3 * count($competitionResults1);
        #--- One result row.
        tableRow(array(personLink($personId, $personName), $pos, formatValue($best, $valueFormat), formatValue($average, $valueFormat), $inRound2 ? $r2_pos : "", $inRound2 ? formatValue($r2_best, $r2_valueFormat) : "", $inRound2 ? formatValue($r2_average, $r2_valueFormat) : "", $offerToDelete ? "<input type='checkbox' name='deleteres{$r2_id}' value='1' /> Delete" : ""));
    }
    tableEnd();
}
function tableCaption($separate, $value)
{
    #----------------------------------------------------------------------
    tableCaptionNew($separate, '', $value);
}