<?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
 **/

function generateDriverString($team)
{
    $driversInRace = array();
    $q = 0;
    foreach ($team['driver_lfs'] as $driver_lfs) {
        if ($team['driver_active'][$q])
            $driversInRace[] = $driver_lfs;
        $q++;
    }
    return "lfsworld='" . implode("' OR lfsworld='", $driversInRace) . "'";
}
function print_array($l)
{
    foreach ($l as $i => $lap)
        print $i . " " . $lap['lap'] . " " . $lap['laptime'] . "<br>";
}

function inTeam($string, $num)
{
    $pieces = explode(" - ", $string);
    $numberString = substr($string, 0, 3);
    $numberString2 = intval($numberString);
    if (empty($numberString2)) {
        if ($numberString == "00 " && $num == "00") {
            return true;
        }
    } elseif (!empty($numberString2))
        return ($numberString == addzeros($num) || intval($pieces[0]) == $num);
}
function filterLaps($laparray)
{
    $laparraynum = count($laparray);
    $j = 0;
    $lapblocks = array(); //print "<table><tr>";
    while ($j < $laparraynum) {
        if ($laparray[$j]['driverUserName'] == $laparray[$j + 1]['driverUserName'] && $laparray[$j]['laptime'] ==
            $laparray[$j + 1]['laptime'] && ($laparray[$j + 1]['logged'] - $laparray[$j]['logged']) <
            20) {
            $laparray = deleteFromArray($laparray, ($j + 1));
            $j = 0;
        } else
            $j++;
    }
    $j = 0;
    while ($j < $laparraynum) {
        //ob_start();
        if ($laparray[$j]['lap'] == 0 && is_array($laparray[$j + 1]))
            $laparray[$j]['lap'] = $laparray[$j + 1]['lap'] - 1;
        if ($laparray[$j]['lap'] == ($laparray[$j + 1]['lap'] - 1)) {
            $j++;
        } else {
            if ($laparray[$j]['lap'] == ($laparray[$j + 2]['lap'] - 1)) {
                //print $laparray[$j]['lap'] . " == " .  ($laparray[$j+2]['lap'] - 1) . "<br>";
                //print "deleting key " . ($j +1) . " from laparray." . "<br>";
                $laparray = deleteFromArray($laparray, ($j + 1));
                //print "</td><td width=150 valign=top>";
                //print_array ($laparray);
                //print "</td>";
                //die;
            } else
                if ($laparray[$j]['lap'] == ($laparray[$j + 1]['lap'] - 2)) {
                    //print $laparray[$j]['lap'] . " == " . ($laparray[$j+1]['lap'] - 2) . "<br>";
                    //print "adding value " . ($laparray[$j]['lap']+1) . " after key ". $j . " to laparray." . "<br>";
                    $laparray = addToArray($laparray, $j, $laparray[$j]['lap'] + 1);
                    //print "</td><td width=150 valign=top>";
                    //print_array ($laparray);
                    //print "</td>";
                    //die;
                } else
                    if ($laparray[$j]['lap'] == ($laparray[$j + 2]['lap'] - 2)) {
                        //print $laparray[$j]['lap'] . " == " . ($laparray[$j+2]['lap'] - 2) . "<br>";
                        //print "changing key " . ($j +1) . " into " . ($laparray[$j]['lap']+1) . "<br>";
                        $laparray = changeInArray($laparray, ($j + 1), $laparray[$j]['lap'] + 1);
                        //print "</td><td width=150 valign=top>";
                        //print_array ($laparray);
                        //print "</td>";
                        //die;
                    } else // close current block and start new one
                    {
                        //print "cutting after " . $j . "<br>";
                        $lapblocks[] = getFromArray($laparray, $j);
                        //print "</td><td width=150 valign=top>";
                        //print_array (getFromArray ($laparray, $j));
                        //print "</td>";
                        $laparray = deleteFromArrayUntil($laparray, $j);
                        //print "</td><td width=150 valign=top>";
                        //print_array ($laparray);
                        //print "</td>";
                        $j = 0; //die;
                    }
                    //print "</td>";
        }
        $laparraynum = count($laparray);
    }
    //ob_clean();
    $lapblocks[] = $laparray; //print "now here...";
    //die;
    $filteredLapArray = array(); //print_r ($lapblocks);
    $lap = 0;
    $r = 1;
    foreach ($lapblocks as $lapblock) {
        for ($i = 0; $i < count($lapblock); $i++) {
            $filteredLapArray[$lap] = $lapblock[$i];
            $lap++;
        }
    }
    return $filteredLapArray;
}
function deleteFromArray($a, $d) // delete key $d from array $a
{
    $r = array();
    for ($i = 0; $i < $d; $i++) {
        $r[$i]['lap'] = $a[$i]['lap'];
        $r[$i]['laptime'] = $a[$i]['laptime'];
        $r[$i]['driverUserName'] = $a[$i]['driverUserName'];
        $r[$i]['logged'] = $a[$i]['logged'];
        $r[$i]['sessiontime'] = $a[$i]['sessiontime'];
        $r[$i]['mysqlid'] = $a[$i]['mysqlid'];
    }
    for ($i = ($d + 1); $i < count($a); $i++) {
        $r[$i - 1]['lap'] = $a[$i]['lap'];
        $r[$i - 1]['laptime'] = $a[$i]['laptime'];
        $r[$i - 1]['driverUserName'] = $a[$i]['driverUserName'];
        $r[$i - 1]['logged'] = $a[$i]['logged'];
        $r[$i - 1]['sessiontime'] = $a[$i]['sessiontime'];
        $r[$i - 1]['mysqlid'] = $a[$i]['mysqlid'];
    }
    return $r;
}
function changeInArray($a, $c, $v)
{
    $a[$c]['lap'] = $v;
    return $a;
}
function addToArray($a, $d, $v)
    // $a = array, $d = place value $v AT key $d, and move down from $d+1
{
    $r = array();
    for ($i = 0; $i <= $d; $i++) {
        $r[$i]['lap'] = $a[$i]['lap'];
        $r[$i]['laptime'] = $a[$i]['laptime'];
        $r[$i]['driverUserName'] = $a[$i]['driverUserName'];
        $r[$i]['logged'] = $a[$i]['logged'];
        $r[$i]['sessiontime'] = $a[$i]['sessiontime'];
        $r[$i]['mysqlid'] = $a[$i]['mysqlid'];
    }
    $r[$i]['lap'] = $v;
    $r[$i]['laptime'] = 0;
    if ($r[$i - 1]['driverUserName'] != "") {
        $r[$i]['laptime'] = $r[$i - 1]['laptime'];
        $r[$i]['driverUserName'] = $r[$i - 1]['driverUserName'];
        $r[$i]['logged'] = $r[$i - 1]['logged'];
        $r[$i]['sessiontime'] = $r[$i - 1]['sessiontime'];
        $r[$i]['mysqlid'] = $r[$i - 1]['mysqlid'] + 1;
    } else {
        $r[$i]['driverUserName'] = "";
        $r[$i]['logged'] = -1;
    }
    for ($i; $i < count($a); $i++) {
        $r[$i + 1]['lap'] = $a[$i]['lap'];
        $r[$i + 1]['laptime'] = $a[$i]['laptime'];
        $r[$i + 1]['driverUserName'] = $a[$i]['driverUserName'];
        $r[$i + 1]['logged'] = $a[$i]['logged'];
        $r[$i + 1]['sessiontime'] = $a[$i]['sessiontime'];
        $r[$i + 1]['mysqlid'] = $a[$i]['mysqlid'];
    }
    return $r;
}
function getFromArray($a, $u)
    // get the part of array $a until and including key $u
{
    $r = array();
    for ($i = 0; $i <= $u; $i++) {
        $r[$i]['lap'] = $a[$i]['lap'];
        $r[$i]['laptime'] = $a[$i]['laptime'];
        $r[$i]['driverUserName'] = $a[$i]['driverUserName'];
        $r[$i]['logged'] = $a[$i]['logged'];
        $r[$i]['sessiontime'] = $a[$i]['sessiontime'];
        $r[$i]['mysqlid'] = $a[$i]['mysqlid'];
    }
    return $r;
}
function deleteFromArrayUntil($a, $u)
    //delete the first part of an array until and including the key $u
{
    $r = array();
    for ($i = ($u + 1); $i < count($a); $i++) {
        $r[$i - ($u + 1)]['lap'] = $a[$i]['lap'];
        $r[$i - ($u + 1)]['laptime'] = $a[$i]['laptime'];
        $r[$i - ($u + 1)]['driverUserName'] = $a[$i]['driverUserName'];
        $r[$i - ($u + 1)]['logged'] = $a[$i]['logged'];
        $r[$i - ($u + 1)]['sessiontime'] = $a[$i]['sessiontime'];
        $r[$i - ($u + 1)]['mysqlid'] = $a[$i]['mysqlid'];
    }
    return $r;
}
function print_html_r($aData)
{
    echo nl2br(eregi_replace(" ", " ", print_r($data, true)));
}
function addzeros($i)
{
    if (strlen($i) == 1)
        return "0" . $i;
    else
        return $i;
}
function removeszeros($i)
{
    return ltrim($i, '0');
}
function totalTime($laps, $rs, $untilLap = 99999)
{
    $alt = ($laps[min((count($laps) - 1), $untilLap)]['logged'] - $rs) * 100;
    return $alt;
}
function countLaps($laps)
{
    $return = 0;
    $last = 0;
    foreach ($laps as $lap) {
        if ($last <= $lap['lap']) {
            $last = $lap['lap'];
        } else {
            $return += $last;
            $last = $lap['lap'];
        }
    }
    return $return + $last; //return count ($laps);
}
function getTeam($name, $prefix = true)
{
    $best_match = "";
    if ($prefix == true) {
        $bits = explode(" - ", $name);
        $bats = explode("-", $bits[0]);
        $number = trim($bats[0], "\0");
        foreach ($TEAMS as $k => $team) {
            if ($team['number'] == $number) {
                $best_match = $TEAMS[$k]['team_name'];
                $h = 100;
            }
        }
    }
    if ($prefix == false || $best_match == "") {
        $strpercent = 0;
        $h = -1;
        $match = array();
        global $TEAMS;
        foreach ($TEAMS as $k => $team) {
            foreach ($team['driver_real'] as $l => $array_name) {
                similar_text(trim($name), trim($array_name), $strpercent);
                if ($strpercent > $h) {
                    $best_match = $TEAMS[$k]['team_name'];
                    $h = $strpercent;
                }
            }
            foreach ($team['driver_lfs'] as $l => $array_name) {
                similar_text(trim($name), trim($array_name), $strpercent);
                if ($strpercent > $h) {
                    $best_match = $TEAMS[$k]['team_name'];
                    $h = $strpercent;
                }
            }
        }
    }
    $return['match'] = $best_match;
    $return['prc'] = $h;
    return $return;
}
function getInfo($string)
{
    $b = explode(" ", $string);
    $match = 0;
    for ($i = 0; $i < count($b); $i++) {
        if ($b[$i] == "antwortet" || $b[$i] == "nimmt" || $b[$i] == "verlässt" || $b[$i] ==
            "geht") {
            $match = $i;
        }
    }
    $tname = "";
    $error = $b[$match];
    while ($match > 0) {
        $tname = $b[$match - 1] . " " . $tname;
        $match--;
    }
    $return['error'] = $error;
    $return['name'] = $tname;
    return $return;
}
function format_name($n, $spaces)
{
    $bits = explode(" ", $n);
    $l = count($bits);
    $initials = "";
    for ($g = 0; $g < ($l - 1); $g++) {
        $initials .= mb_substr($bits[$g], 0, 1, 'UTF-8') . ".$spaces";
    }
    return $initials . $bits[$l - 1];
}

/**
 * Sorting standings for IGTC - RUN, RET, DQ, DNS initially, then as below in sort_standings
 **/
function sort_standings_status($a, $b)
{
    if ($a['team_data']['team_status_num'] < $b['team_data']['team_status_num']) {
        return - 1;
    } elseif ($a['team_data']['team_status_num'] > $b['team_data']['team_status_num']) {
        return 1;
    } else {
        if (($a['race_data']['laps'] + $a['race_data']['penalty_laps']
            /**+$a['race_data']['correction_laps']**/ ) == ($b['race_data']['laps'] + $b['race_data']['penalty_laps']
            /**+$b['race_data']['correction_laps']**/ )) {
            if ($a['race_data']['total_sessiontime'] < $b['race_data']['total_sessiontime'])
                return - 1;
            elseif (($a['race_data']['laps'] + $a['race_data']['penalty_laps']) == 0 && ($a['race_data']['total_time'] ==
                $b['race_data']['total_time']) && ($a['team_data']['grid'] < $b['team_data']['grid'])) {
                return - 1;
            } elseif (($a['race_data']['laps'] + $a['race_data']['penalty_laps']) == 0 && ($a['race_data']['total_time'] ==
            $b['race_data']['total_time']) && ($a['team_data']['grid'] == $b['team_data']['grid']) &&
                ($a['team_data']['number'] < $b['team_data']['number'])) {
                return - 1;
            } elseif ($a['race_data']['total_sessiontime'] == $b['race_data']['total_sessiontime'] &&
            $a['raw_laps'][($a['race_data']['laps'] - 1)]['mysqlid'] < $b['raw_laps'][($b['race_data']['laps'] -
                1)]['mysqlid']) {
                return - 1;
            } else
                return 1;
        } else {
            if (($a['race_data']['laps'] + $a['race_data']['penalty_laps']
                /**+$a['race_data']['correction_laps']**/ ) > ($b['race_data']['laps'] + $b['race_data']['penalty_laps']
                /**+$b['race_data']['correction_laps']**/ )) {
                return - 1;
            } else {
                return 1;
            }
        }
    }
}
/**
 * Sorting standings
 *      check for same laps
 *      SORT BY TOTAL RACE TIME
 *      check for 0 laps, same total race time - SORT BY GRID
 *      check for 0 laps, same total race time, same grid - SORT BY NUMBER
 *      check for same total race time - SORT BY FINAL LAP'S MYSQLID
 **/
function sort_standings($a, $b)
{
    if ($a['team_data']['team_status_num'] > 3 && $b['team_data']['team_status_num'] <
        4) {
        return 1;
    } elseif ($a['team_data']['team_status_num'] < 4 && $b['team_data']['team_status_num'] >
    3) {
        return - 1;
    } else {
        if ($a['race_data']['corrected_laps'] == $b['race_data']['corrected_laps']) {
            if ($a['race_data']['total_sessiontime'] < $b['race_data']['total_sessiontime'])
                return - 1;
            elseif (($a['race_data']['laps'] + $a['race_data']['penalty_laps']) == 0 && ($a['race_data']['total_time'] ==
                $b['race_data']['total_time']) && ($a['team_data']['grid'] < $b['team_data']['grid'])) {
                return - 1;
            } elseif (($a['race_data']['laps'] + $a['race_data']['penalty_laps']) == 0 && ($a['race_data']['total_time'] ==
            $b['race_data']['total_time']) && ($a['team_data']['grid'] == $b['team_data']['grid']) &&
                ($a['team_data']['number'] < $b['team_data']['number'])) {
                return - 1;
            } elseif ($a['race_data']['total_sessiontime'] == $b['race_data']['total_sessiontime'] &&
            $a['raw_laps'][($a['race_data']['laps'] - 1)]['mysqlid'] < $b['raw_laps'][($b['race_data']['laps'] -
                1)]['mysqlid']) {
                return - 1;
            } else
                return 1;
        } else {
            if (($a['race_data']['laps'] + $a['race_data']['penalty_laps']
                /**+$a['race_data']['correction_laps']**/ ) > ($b['race_data']['laps'] + $b['race_data']['penalty_laps']
                /**+$b['race_data']['correction_laps']**/ )) {
                return - 1;
            } else {
                return 1;
            }
        }
    }
}
/**
 * Sorting standings for qualifying / practice
 *      SORT BY lap time
 *      SORT BY earlier logged time
 *          CHECK FOR no laptime, SORT BY number of laps 
 *      SORT BY fastest lap set on
 *      SORT BY number of laps 
 *      SORT BY number
 **/
function sort_standingsq($a, $b)
{
    if ($a['race_data']['laps'] == 0 && $b['race_data']['laps'] == 0) {
        if ($a['team_data']['number'] < $b['team_data']['number']) {
            return - 1;
        } else {
            return 1;
        }
    } else {
        if ($a['race_data']['fastest_lap'] == $b['race_data']['fastest_lap']) {
            if ($a['raw_laps'][($a['race_data']['fastest_lap_on'] - 2)]['sessiontime'] == $b['raw_laps'][($b['race_data']['fastest_lap_on'] -
                2)]['sessiontime']) {
                if ($a['race_data']['fastest_lap_on'] == $b['race_data']['fastest_lap_on']) {
                    if ($a['race_data']['fastest_lap'] == 99999999999 && $b['race_data']['fastest_lap'] ==
                        99999999999) {
                        if ($a['race_data']['laps'] > $b['race_data']['laps']) {
                            return - 1;
                        } else {
                            return 1;
                        }
                    } elseif ($a['race_data']['laps'] == $b['race_data']['laps']) {
                        if ($a['team_data']['number'] < $b['team_data']['number']) {
                            return - 1;
                        } else {
                            return 1;
                        }
                    } elseif ($a['race_data']['laps'] < $b['race_data']['laps']) {
                        return - 1;
                    } else {
                        return 1;
                    }
                } elseif ($a['race_data']['fastest_lap_on'] < $b['race_data']['fastest_lap_on']) {
                    return - 1;
                } else {
                    return 1;
                }
            } elseif ($a['raw_laps'][($a['race_data']['fastest_lap_on'] - 2)]['sessiontime'] < $b['raw_laps'][($b['race_data']['fastest_lap_on'] -
            2)]['sessiontime']) {
                return - 1;
            } else {
                return 1;
            }
        } elseif ($a['race_data']['fastest_lap'] < $b['race_data']['fastest_lap']) {
            return - 1;
        } else {
            return 1;
        }
    }
}

/**
 * Sorting standings (where $qualElimation = true) for qualifying / practice
 *      IF $qualElimation = true, SORT BY grid
 *      SORT BY lap time
 *      SORT BY earlier logged time
 *          CHECK FOR no laptime, SORT BY number of laps 
 *      SORT BY fastest lap set on
 *      SORT BY number of laps 
 *      SORT BY number
 **/
function sort_standingsq2($a, $b)
{
    if ($a['race_data']['maxraceid'] < $b['race_data']['maxraceid']) {
        return 1;
    } elseif ($a['race_data']['maxraceid'] > $b['race_data']['maxraceid']) {
        return - 1;
    } else {
        if ($a['race_data']['laps'] == 0 && $b['race_data']['laps'] == 0) {
            if ($a['team_data']['number'] < $b['team_data']['number']) {
                return - 1;
            } else {
                return 1;
            }
        } else {
            if ($a['race_data']['fastest_lap'] == $b['race_data']['fastest_lap']) {
                if ($a['raw_laps'][($a['race_data']['fastest_lap_on'] - 2)]['sessiontime'] == $b['raw_laps'][($b['race_data']['fastest_lap_on'] -
                    2)]['sessiontime']) {
                    if ($a['race_data']['fastest_lap_on'] == $b['race_data']['fastest_lap_on']) {
                        if ($a['race_data']['fastest_lap'] == 99999999999 && $b['race_data']['fastest_lap'] ==
                            99999999999) {
                            if ($a['race_data']['laps'] > $b['race_data']['laps']) {
                                return - 1;
                            } else {
                                return 1;
                            }

                        } elseif ($a['race_data']['laps'] == $b['race_data']['laps']) {
                            if ($a['team_data']['number'] < $b['team_data']['number']) {
                                return - 1;
                            } else {
                                return 1;
                            }
                        } elseif ($a['race_data']['laps'] < $b['race_data']['laps']) {
                            return - 1;
                        } else {
                            return 1;
                        }


                    } elseif ($a['race_data']['fastest_lap_on'] < $b['race_data']['fastest_lap_on']) {
                        return - 1;
                    } else {
                        return 1;
                    }
                } elseif ($a['raw_laps'][($a['race_data']['fastest_lap_on'] - 2)]['sessiontime'] < $b['raw_laps'][($b['race_data']['fastest_lap_on'] -
                2)]['sessiontime']) {
                    return - 1;
                } else {
                    return 1;
                }
            } elseif ($a['race_data']['fastest_lap'] < $b['race_data']['fastest_lap']) {
                return - 1;
            } else {
                return 1;
            }
        }
    }
}

function normalTime($time, $h = true, $teamstats = false, $Mzero = false, $Mshow = false,
    $Szero = true, $Shide = false, $Hhide = true, $Sspan = false)
    // produces 1h 10:00.00 by default - expects milliseconds, options to remove hundreths, show +/- and remove minutes, remove leading zero from minutes, remove minutes entirely, remove leading zero from seconds
{
    $negative = false;
    if ($time < 0) {
        $negative = true;
    }
    $time = abs($time);
    if ((!$time or $time == 99999999999) && !$teamstats && $time !== 0) {
        $string = "";
    } elseif ($time == 0) {
        $string = "0:00";
        if ($h) {
            $string = "0.00";
        }
    } else {
        $hour = floor($time / (60 * 60 * 1000));
        $remain = $time % (60 * 60 * 1000);
        $min = floor($remain / (60 * 1000));
        $remain = $time % (60 * 1000);
        $sec = floor($remain / 1000);
        $hun = $remain % 1000;
        if (strlen($hun) == 2) {
            $hun = "0" . $hun;
        } elseif (strlen($hun) == 1) {
            $hun = "00" . $hun;
        } elseif (strlen($hun) == 0) {
            $hun = "000";
        }
        if (strlen($sec) == 1 && $Szero == false && $min != 0) {
            $sec = "0" . $sec;
        } elseif (strlen($sec) == 1 && $Szero == false && $Shide == true && $min == 0 &&
        $hour == 0 && $Sspan == true) {
            $sec = "<span class ='invisible'>0</span>" . $sec;
        } elseif (strlen($sec) == 1 && $Szero == false) {
            $sec = "" . $sec;
        } elseif (strlen($sec) == 1) {
            $sec = "0" . $sec;
        } elseif (strlen($sec) == 0) {
            $sec = "00";
        }
        if (strlen($min) == 1 && $Mzero == false && $hour != 0) {
            $min = "0" . $min;
        } elseif (strlen($min) == 1 && $Mzero == false) {
            $min = "" . $min;
        } elseif (strlen($min) == 1) {
            $min = "0" . $min;
        } elseif (strlen($min) == 0) {
            $min = "00";
        }
        $string = "";
        if ($hour > 0 && $Hhide == false)
            $string = $hour . "h ";
        elseif ($hour > 0 && $Hhide == true)
            $string = $hour . ":";
        if ($h && $teamstats && $min == 0)
            $string = substr_replace($sec . "." . $hun, "", -1);
        elseif ($h && $hour == 0 && $min == 0 && !$Mshow)
            $string = substr_replace($sec . "." . $hun, "", -1);
        elseif ($h)
            $string = $string = substr_replace($string . $min . ":" . $sec . "." . $hun, "",
                -1);
        else
            $string = $string . $min . ":" . $sec;
    }
    if ($teamstats && $negative) {
        $string = "-" . $string;
    } elseif ($teamstats) {
        $string = "+" . $string;
    }
    return $string;
}

function html_print_r($object, $returnValue = false)
{
    $output = print_r($object, true);
    $output = htmlentities($output);
    $output = str_replace(" ", "&nbsp;", $output);
    $output = nl2br($output);
    if ($returnValue) {
        return $output;
    } else {
        //echo $output;
        return true;
    }
}
function writeToFile($filename, $content)
{
    if (!file_exists($filename)) {
        if (!$handle = fopen($filename, 'w')) {
            echo "Cannot open file ($filename)";
            exit;
        } else {
            fclose($handle);
            chmod($filename, 06666);
        }
    }
    if (!$handle = fopen($filename, 'w')) {
        echo "Cannot open file ($filename)";
        exit;
    }
    if (is_writable($filename)) {
        if (fwrite($handle, $content) === false) {
            echo "Cannot write to file ($filename)";
            exit;
        }
        //print "File written : " . $filename . "<br>";
        flush();
        fclose($handle);
    } else {
        if (chmod($filename, 0666))
            writeToFile($filename, $content);
    }
}
/**
 *
 * @return number with ordinal suffix
 *
 * @param int $number
 *
 * @param int $ss Turn super script on/off
 *
 * @return string
 *
 */
function ordinalSuffix($number, $ss = 0)
{
    /*** check for 11, 12, 13 ***/
    if ($number % 100 > 10 && $number % 100 < 14) {
        $os = 'th';
    }
    /*** check if number is zero ***/  elseif ($number == 0) {
        $os = '';
    } else {
        /*** get the last digit ***/
        $last = substr($number, -1, 1);
        switch ($last) {
            case "1":
                $os = 'st';
                break;
            case "2":
                $os = 'nd';
                break;
            case "3":
                $os = 'rd';
                break;
            default:
                $os = 'th';
        }
    }
    /*** add super script ***/
    $os = $ss == 0 ? $os : '<sup>' . $os . '</sup>';
    /*** return ***/
    return $number . $os;
}
// L = Latin 1
// G = Greek
// C = Cyrillic
// E = Central Europe
// T = Turkish
// B = Baltic
// J = Japanese
// S = Simplified Chinese
// K = Korean
// H = Traditional Chinese
function codepage_convert($str, $conv_to = 'UTF-8')
{
    $sets = array(
        'L' => 'CP1252',
        'G' => 'ISO-8859-7',
        'C' => 'CP1251',
        'E' => 'ISO-8859-2',
        'T' => 'ISO-8859-9',
        'B' => 'ISO-8859-13',
        'J' => 'SJIS-win',
        'S' => 'CP936',
        'K' => 'CP949',
        'H' => 'CP950');

    $tr_ptrn = array(
        "/\^d/",
        "/\^s/",
        "/\^c/",
        "/\^a/",
        "/\^q/",
        "/\^t/",
        "/\^l/",
        "/\^r/",
        "/\^v/");
    $tr_ptrn_r = array(
        "\\",
        "/",
        ":",
        "*",
        "?",
        "\"",
        "<",
        ">",
        "|");
    $str = preg_replace($tr_ptrn, $tr_ptrn_r, $str);

    $newstr = $tmp = '';
    $current_cp = 'L';
    $len = strlen($str);
    for ($i = 0; $i < $len; $i++) {
        if ($str{$i} == '^' && isset($sets[$str{$i + 1}]) && $str{$i - 1} != "^") {
            if ($tmp != '') {
                $newstr .= mb_convert_encoding($tmp, $conv_to, $sets[$current_cp]);
                $tmp = '';
            }
            $current_cp = $str{++$i};
        }
        // Filter out every character below 0x20
        else
            if (ord($str{$i}) > 31)
                $tmp .= $str{$i};
    }
    if ($tmp != '')
        $newstr .= mb_convert_encoding($tmp, $conv_to, $sets[$current_cp]);

    // Final special char to convert - could not do that before codepage conversion
    return str_replace('^^', '^', $newstr);
}

?>