<?php

function StopLoc($stp){
    $dom = new DOMDocument();
    @$dom->loadHtml(DownloadStopInfo($stp));
    $xpath = new DomXPath($dom);
    $loc = $xpath->query('//div[@class="loc"]')[0]->nodeValue;
    $loc = explode(',',$loc);
    return $loc;
}

function ExtractStopIDs(){
    global $routes;
    $genStops = array();
    foreach ($routes as $route){
        foreach ($route['stops'] as $dir){
            foreach ($dir as $stp){
                array_push($genStops,$stp);
            }
        }
    }
    return uniqueStops($genStops);
}

function GetStops(){
        $GenStops = array();
        $GenStops_keys = array('id', 'name', 'lat', 'lon');

        foreach (ExtractStopIDs() as $stp){
            $GenStops_values = array();

            $loc = StopLoc($stp);
            $GenStops_values = array($stp, DownloadStopName($stp), $loc[0], $loc[1]);

            array_push($GenStops, array_combine($GenStops_keys, $GenStops_values));
        }

        usort($GenStops, function($a,$b){
            return strcmp($a['name'], $b['name']);
        });
        return $GenStops;
}

function uniqueStops($list){
    $unique = array();
    foreach ($list as $stop){
        if (foundStop($unique,$stop) == false){
            array_push($unique, $stop);
        }
    }
    sort($unique);
    return $unique;
}

function foundStop($haystack,$needle){
    foreach ($haystack as $l){
        if ($l == $needle){
            return true;
        }
    }
    return false;
}

?>
