<?php

/*
    Created by Leif Madsen for IT360. April 8, 2009.

    Copyright LeifMadsen Enterprises, Inc. (c)2009 except for the magic_csv
    function and ArraySearchRecursive function, copyright their respective
    creators.

    This file can be used freely in your system, but there is no warranty,
    or guarentees that this file will do anything. If you use it, please
    give credit where it's due. Thanks!
    
*/

// from http://www.defproc.co.uk/php/magic_csv_load_a_CSV_file_into_an_associative_array
function magic_csv($filename){
 
$f = @fopen($filename,'r');
 if (!
$f) return false;
 
$headers fgetcsv($f,8090);
 
$all = array();
 while (!
feof($f)){
  
$values fgetcsv($f,8098);
  
$row = array();
  
$i=0;
  if (
is_array($values)){
     foreach(
$values as $v){
        if (
$i count($headers)) $row[$headers[$i]] = $v;
      
$i++;
     }
     
$all[] = $row;
    }
 }
 return 
$all;



// from http://www.php.net/manual/en/function.array-search.php#69232
function ArraySearchRecursive($Needle,$Haystack,$NeedleKey="",
                              
$Strict=false,$Path=array()) {
  if(!
is_array($Haystack))
    return 
false;
  foreach(
$Haystack as $Key => $Val) {
    if(
is_array($Val)&&
       
$SubPath=ArraySearchRecursive($Needle,$Val,$NeedleKey,
                                     
$Strict,$Path)) {
      
$Path=array_merge($Path,Array($Key),$SubPath);
      return 
$Path;
    }
    elseif((!
$Strict&&$Val==$Needle&&
            
$Key==(strlen($NeedleKey)>0?$NeedleKey:$Key))||
            (
$Strict&&$Val===$Needle&&
             
$Key==(strlen($NeedleKey)>0?$NeedleKey:$Key))) {
      
$Path[]=$Key;
      return 
$Path;
    }
  }
  return 
false;
}

$time_start microtime(true);
// from unlimitel.ca
$haystack magic_csv('wholesale-rate-sheet.csv');
$time_end microtime(true);
$haystack_time $time_end $time_start;

$number $_GET["number"];

$len strlen($number);

$offset 0;

$time_start microtime(true);
while(
$offset != $len) {
    if (
$offset == 0) {
        
$needle $number;
    } else {
        
$needle substr($number0, -$offset);
    }

    
$res ArraySearchRecursive("'$needle",$haystack);
    if (
$res == FALSE) {
        
$offset++;
    } else {
        
$location $res[0];
        
$rate $haystack[$location]['rate'];
        
$rate trim($rate);
        
$country $haystack[$location]['country'];
        break;
    }
}
$time_end microtime(true);
$search_time $time_end $time_start;


if (
$rate == FALSE) {
    echo 
"No rate found.";
} else {
    echo 
"$country,$needle,$rate,$haystack_time,$search_time";
}

?>