<?php
// worldbank_population_data.php
// RJM Programming
// February, 2017

$mopt="";
$lri=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
$dri=["U+1F1E6","U+1F1E7","U+1F1E8","U+1F1E9","U+1F1EA","U+1F1EB","U+1F1EC","U+1F1ED","U+1F1EE","U+1F1EF","U+1F1F0","U+1F1F1","U+1F1F2","U+1F1F3","U+1F1F4","U+1F1F5","U+1F1F6","U+1F1F7","U+1F1F8","U+1F1F9","U+1F1FA","U+1F1FB","U+1F1FC","U+1F1FD","U+1F1FE","U+1F1FF"];
$flagentity="";	
$iso_country_codes=['AF','Afghanistan',
'AX','Aland Islands',
'AL','Albania',
'DZ','Algeria',
'AS','American Samoa',
'AD','Andorra',
'AO','Angola',
'AI','Anguilla',
'AQ','Antarctica',
'AG','Antigua and Barbuda',
'AR','Argentina',
'AM','Armenia',
'AW','Aruba',
'AU','Australia',
'AT','Austria',
'AZ','Azerbaijan',
'bs','Bahamas',
'BS','Bahamas the',
'BH','Bahrain',
'BD','Bangladesh',
'BB','Barbados',
'BY','Belarus',
'BE','Belgium',
'BZ','Belize',
'BJ','Benin',
'BM','Bermuda',
'BT','Bhutan',
'BO','Bolivia',
'BA','Bosnia and Herzegovina',
'BW','Botswana',
'BV','Bouvet Island (Bouvetoya)',
'BR','Brazil',
'IO','British Indian Ocean Territory (Chagos Archipelago)',
'VG','British Virgin Islands',
'BN','Brunei Darussalam',
'BG','Bulgaria',
'BF','Burkina Faso',
'BI','Burundi',
'KH','Cambodia',
'CM','Cameroon',
'CA','Canada',
'cv','Cabo Verde',
'CV','Cape Verde',
'KY','Cayman Islands',
'CF','Central African Republic',
'TD','Chad',
'CL','Chile',
'CN','China',
'CX','Christmas Island',
'CC','Cocos (Keeling) Islands',
'CO','Colombia',
'KM','Comoros the',
'Cd','Congo Dem Rep',
'Cg','Congo Rep',
'cd','Congo, Dem. Rep.',
'cg','Congo, Rep.',
'CD','Congo, Dem Rep',
'CG','Congo, Rep',
'CK','Cook Islands',
'CR','Costa Rica',
'Ci',"Cote d'Ivoire",
'ci','Cote dIvoire',
'CI','Cote d`Ivoire',
'HR','Croatia',
'CU','Cuba',
'CY','Cyprus',
'CZ','Czech Republic',
'DK','Denmark',
'DJ','Djibouti',
'DM','Dominica',
'DO','Dominican Republic',
'EC','Ecuador',
'Eg','Egypt Arab Rep',
'eg','Egypt, Arab Rep',
'EG','Egypt',
'SV','El Salvador',
'GQ','Equatorial Guinea',
'ER','Eritrea',
'EE','Estonia',
'ET','Ethiopia',
'FO','Faroe Islands',
'FK','Falkland Islands (Malvinas)',
'FJ','Fiji the Fiji Islands',
'FI','Finland',
'FR','France, French Republic',
'GF','French Guiana',
'PF','French Polynesia',
'TF','French Southern Territories',
'GA','Gabon',
'gm','Gambia',
'GM','Gambia the',
'GE','Georgia',
'DE','Germany',
'GH','Ghana',
'GI','Gibraltar',
'GR','Greece',
'GL','Greenland',
'GD','Grenada',
'GP','Guadeloupe',
'GU','Guam',
'GT','Guatemala',
'GG','Guernsey',
'GN','Guinea',
'GW','Guinea-Bissau',
'GY','Guyana',
'HT','Haiti',
'HM','Heard Island and McDonald Islands',
'VA','Holy See (Vatican City State)',
'HN','Honduras',
'hk','Hong Kong SAR',
'HK','Hong Kong',
'HU','Hungary',
'IS','Iceland',
'IN','India',
'ID','Indonesia',
'Ir','Iran Islamic Rep',
'ir','Iran, Islamic Rep',
'IR','Iran',
'IQ','Iraq',
'IE','Ireland',
'IM','Isle of Man',
'IL','Israel',
'IT','Italy',
'JM','Jamaica',
'JP','Japan',
'je','Channel Islands',
'JE','Jersey',
'JO','Jordan',
'KZ','Kazakhstan',
'KE','Kenya',
'KI','Kiribati',
'Kp','Korea Rep',
'Kr',"Korea Dem People’s Rep", 
'kp','Korea, Rep',
'kr',"Korea, Dem People’s Rep", 
'KP','Korea, Rep.',
'KR',"Korea, Dem. People’s Rep.", 
'KW','Kuwait',
'KG','Kyrgyz Republic',
'lA','Lao PDR',
'la','Laos',
'LA','Lao',
'LV','Latvia',
'LB','Lebanon',
'LS','Lesotho',
'LR','Liberia',
'LY','Libyan Arab Jamahiriya',
'LI','Liechtenstein',
'LT','Lithuania',
'LU','Luxembourg',
'Mo','Macao SAR, China',
'mo','Macao SAR',
'MO','Macao',
'MK','Macedonia',
'MG','Madagascar',
'MW','Malawi',
'MY','Malaysia',
'MV','Maldives',
'ML','Mali',
'MT','Malta',
'MH','Marshall Islands',
'MQ','Martinique',
'MR','Mauritania',
'MU','Mauritius',
'YT','Mayotte',
'MX','Mexico',
'FM','Micronesia',
'MD','Moldova',
'MC','Monaco',
'MN','Mongolia',
'ME','Montenegro',
'MS','Montserrat',
'MA','Morocco',
'MZ','Mozambique',
'MM','Myanmar',
'NA','Namibia',
'NR','Nauru',
'NP','Nepal',
'nl','Netherlands',
'AN','Netherlands Antilles',
'NL','Netherlands the',
'NC','New Caledonia',
'NZ','New Zealand',
'NI','Nicaragua',
'NE','Niger',
'NG','Nigeria',
'NU','Niue',
'NF','Norfolk Island',
'MK','North Macedonia',
'MP','Northern Mariana Islands',
'NO','Norway',
'OM','Oman',
'PK','Pakistan',
'PW','Palau',
'ps','West Bank and Gaza',
'PS','Palestinian Territory',
'PA','Panama',
'PG','Papua New Guinea',
'PY','Paraguay',
'PE','Peru',
'PH','Philippines',
'PN','Pitcairn Islands',
'PL','Poland',
'PT','Portugal, Portuguese Republic',
'PR','Puerto Rico',
'QA','Qatar',
'RE','Reunion',
'RO','Romania',
'RU','Russian Federation',
'RW','Rwanda',
'bl','St. Barthelemy',
'sh','St. Helena',
'kn','St. Kitts and Nevis',
'lc','St. Lucia',
'mF','Sint Maarten',
'mf','St. Martin',
'pm','St. Pierre and Miquelon',
'vc','St. Vincent and the Grenadines',
'BL','Saint Barthelemy',
'SH','Saint Helena',
'KN','Saint Kitts and Nevis',
'LC','Saint Lucia',
'MF','Saint Martin',
'PM','Saint Pierre and Miquelon',
'VC','Saint Vincent and the Grenadines',
'WS','Samoa',
'SM','San Marino',
'ST','Sao Tome and Principe',
'SA','Saudi Arabia',
'SN','Senegal',
'RS','Serbia',
'SC','Seychelles',
'SL','Sierra Leone',
'SG','Singapore',
'SK','Slovakia (Slovak Republic)',
'SI','Slovenia',
'SB','Solomon Islands',
'SO','Somalia, Somali Republic',
'ZA','South Africa',
'GS','South Georgia and the South Sandwich Islands',
'SS','South Sudan',
'ES','Spain',
'LK','Sri Lanka',
'SD','Sudan',
'SR','Suriname',
'SJ','Svalbard & Jan Mayen Islands',
'SZ','Swaziland',
'SE','Sweden',
'CH','Switzerland, Swiss Confederation',
'SY','Syrian Arab Republic',
'TW','Taiwan',
'TJ','Tajikistan',
'TZ','Tanzania',
'TH','Thailand',
'TL','Timor-Leste',
'TG','Togo',
'TK','Tokelau',
'TO','Tonga',
'TT','Trinidad and Tobago',
'TN','Tunisia',
'TR','Turkey',
'TM','Turkmenistan',
'TC','Turks and Caicos Islands',
'TV','Tuvalu',
'UG','Uganda',
'UA','Ukraine',
'AE','United Arab Emirates',
'GB','United Kingdom',
'US','United States of America',
'UM','United States Minor Outlying Islands',
'vi','Virgin Islands (U.S.)',
'VI','United States Virgin Islands',
'uy','Uruguay',
'UY','Uruguay, Eastern Republic of',
'UZ','Uzbekistan',
'VU','Vanuatu',
'VE','Venezuela',
'VN','Vietnam',
'WF','Wallis and Futuna',
'EH','Western Sahara',
'Ye','Yemen Rep',
'ye','Yemen, Rep',
'YE','Yemen',
'ZM','Zambia',
'ZW','Zimbabwe'];


function uvaltosfcp($string) { // thanks to https://stackoverflow.com/questions/1805802/php-convert-unicode-codepoint-to-utf-8
  return html_entity_decode(preg_replace("/U\+([0-9A-F]{5})/", "&#x\\1;", $string), ENT_NOQUOTES, 'UTF-8');
}

function retflagflag($inctryname) {
  global $flagentity, $iso_country_codes, $lri, $dri, $preudiff;
  // if (strpos($inctryname, "Ecuador") === false) {  echo $inctryname . 'z'; exit; } 
  if (strpos($inctryname, "\t") !== false || strpos($preudiff, 'pie_chart') === false) { return $inctryname; }
  $uretv="";
  $flagentity="";
  if ($inctryname != "") {
  $matchfound=false;
  for ($im=1; $im<sizeof($iso_country_codes); $im+=2) {
    if (strpos(strtolower($iso_country_codes[$im]), strtolower(str_replace("%20"," ",str_replace("%E2%80%99","",str_replace("%2C",",",$inctryname))))) !== false) {
      for ($jm=0; $jm<sizeof($lri); $jm++) {
       if (strtoupper(substr($iso_country_codes[-1 + $im],0,1)) == $lri[$jm]) {
         $uretv.=$dri[$jm]; //uvaltosfcp($dri[$jm]);
         $matchfound=true;
       }
      }
      for ($jm=0; $jm<sizeof($lri); $jm++) {
       if (strtoupper(substr($iso_country_codes[-1 + $im],1,1)) == $lri[$jm]) {
         $uretv.=$dri[$jm]; //uvaltosfcp($dri[$jm]);
       }
      }
      $flagentity=uvaltosfcp($uretv); //$uretv;
   //   if (strpos($inctryname, "Macao") != false) {  echo $inctryname . '%20' . $flagentity; exit; }
   //  if (strpos($inctryname, "Korea%2C%20Dem") !== false) {  echo $inctryname . 'xxxxx'; exit; }
      return str_replace("%E2%80%99","",str_replace("%2C","",$inctryname)) . '%09' . $flagentity;
    }
  }
  if ($uretv == "" && !$matchfound) {
  for ($im=1; $im<sizeof($iso_country_codes); $im+=2) {
    if (strpos(explode(",",strtolower($iso_country_codes[$im]))[0], explode(",",strtolower(str_replace("%20"," ",str_replace("%E2%80%99","",str_replace("%2C",",",$inctryname)))))[0]) !== false) {
      for ($jm=0; $jm<sizeof($lri); $jm++) {
       if (strtoupper(substr($iso_country_codes[-1 + $im],0,1)) == $lri[$jm]) {
         $uretv.=$dri[$jm]; //uvaltosfcp($dri[$jm]);
         $matchfound=true;
       }
      }
      for ($jm=0; $jm<sizeof($lri); $jm++) {
       if (strtoupper(substr($iso_country_codes[-1 + $im],1,1)) == $lri[$jm]) {
         $uretv.=$dri[$jm]; //uvaltosfcp($dri[$jm]);
       }
      }
      $flagentity=uvaltosfcp($uretv); //$uretv;
   //  if (strpos($inctryname, "Macao") != false) {  echo $inctryname . 'xx%20' . $flagentity; exit; }
   //  if (strpos($inctryname, "Korea%2C%20Dem") !== false) {  echo $inctryname . 'xxxx'; exit; }
      return str_replace("%E2%80%99","",str_replace("%2C","",$inctryname)) . '%09' . $flagentity;
    }
  }
  }

  if ($uretv == "" && !$matchfound) {
  for ($im=1; $im<sizeof($iso_country_codes); $im+=2) {
    if (strpos(explode(" (",strtolower($iso_country_codes[$im]))[0], explode(" (",strtolower(str_replace("%20"," ",str_replace("%E2%80%99","",str_replace("%2C",",",$inctryname)))))[0]) !== false) {
      for ($jm=0; $jm<sizeof($lri); $jm++) {
       if (strtoupper(substr($iso_country_codes[-1 + $im],0,1)) == $lri[$jm]) {
         $uretv.=$dri[$jm]; //uvaltosfcp($dri[$jm]);
         $matchfound=true;
       }
      }
      for ($jm=0; $jm<sizeof($lri); $jm++) {
       if (strtoupper(substr($iso_country_codes[-1 + $im],1,1)) == $lri[$jm]) {
         $uretv.=$dri[$jm]; //uvaltosfcp($dri[$jm]);
       }
      }
      $flagentity=uvaltosfcp($uretv); //$uretv;
   //  if (strpos($inctryname, "Macao") != false) {  echo $inctryname . 'xxx%20' . $flagentity; exit; }
   //  if (strpos($inctryname, "Korea%2C%20Dem") !== false) {  echo $inctryname . 'x'; exit; }
      return str_replace("%E2%80%99","",str_replace("%2C","",$inctryname)) . '%09' . $flagentity;
    }
  }
  }


  }
    // if (strpos($inctryname, "Macao") != false) {  echo $inctryname . 'xxx'; exit; }
  //  if (strpos($inctryname, "Korea%2C%20Dem") !== false) {  echo $inctryname . 'xxx'; exit; }
  return str_replace("%E2%80%99","",str_replace("%2C","",$inctryname));
}


function ourfilter($pl) {
  global $popdelim;
  $opl="";
  $apl=explode($popdelim, $pl);
  for ($i=0; $i<sizeof($apl); $i++) {
   if ($apl[$i] != "") {
    if (strpos($apl[$i], "~,0]") === false || strpos($apl[$i], "~,0.0]") === false) {
      $opl.=$popdelim . $apl[$i];
    }
   }
  }
  return $opl;
}

function our_str_replace($from, $to, $stris) {
  global $minval, $maxval, $xrange, $reportmode, $othercnt, $valuelist, $okvaluelist, $firstyear, $thisc, $oneyear, $thisyear;
  $outs=str_replace($from, $to, $stris); 
  if ($outs > 0.0) {
    if ($minval == 0.0 || $minval > $outs) $minval=$outs;
    if ($maxval == 0.0 || $maxval < $outs) $maxval=$outs;
  }
  if ($xrange == "") {
    if (isset($_GET['min']) && isset($_GET['max'])) {
      $xrange=" (" . $_GET['min'] . " <= " . $reportmode . " <= " . $_GET['max'] . ")";
    } else if (isset($_GET['min'])) {
      $xrange=" (" . $_GET['min'] . " <= " . $reportmode . ")";
    } else if (isset($_GET['max'])) {
      $xrange=" (" . $reportmode . " <= " . $_GET['max'] . ")";
    }
  }
  if (isset($_GET['min']) && isset($_GET['max'])) {
    if ($thisyear != $oneyear) { //$firstyear <= 0) {
      if (str_replace("," . $thisc . ",","","," . $okvaluelist . ",") != "," . $okvaluelist . ",") {
        return $outs;
      } else {
      $othercnt+=$outs;
      return "0";
      }
    }
    if ($outs < $_GET['min'] || $outs > $_GET['max']) {
      $othercnt+=$outs;
      return "0";
    } else if ($thisyear == $oneyear && $valuelist != "") {
      $vls=explode(",",$valuelist);
      if (str_replace("," . $vls[0] . ",","","," . $okvaluelist . ",") == "," . $okvaluelist . ",") {
        if ($okvaluelist == "") {
          $okvaluelist=$vls[0];
        } else {
          $prevok=$okvaluelist;
          $okvaluelist=$vls[0] . "," . $prevok;
        }
      }
    }
  } else if (isset($_GET['min'])) {
    if ($thisyear != $oneyear) { //$firstyear <= 0) {
      if (str_replace("," . $thisc . ",","","," . $okvaluelist . ",") != "," . $okvaluelist . ",") {
        return $outs;
      } else {
      $othercnt+=$outs;
      return "0";
      }
    }
    if ($outs < $_GET['min']) {
      $othercnt+=$outs;
      return "0";
    } else if ($thisyear == $oneyear && $valuelist != "") {
      $vls=explode(",",$valuelist);
      if (str_replace("," . $vls[0] . ",","","," . $okvaluelist . ",") == "," . $okvaluelist . ",") {
        if ($okvaluelist == "") {
          $okvaluelist=$vls[0];
        } else {
          $prevok=$okvaluelist;
          $okvaluelist=$vls[0] . "," . $prevok;
        }
      }
    }
  } else if (isset($_GET['max'])) {
    if ($thisyear != $oneyear) { //$firstyear <= 0) {
      if (str_replace("," . $thisc . ",","","," . $okvaluelist . ",") != "," . $okvaluelist . ",") {
        return $outs;
      } else {
      $othercnt+=$outs;
 //     if ($thisc != "China") {
 // echo "<!doctype html><html><body><textarea cols=80 rows=200 style=width:100%;>oneyear/thisyear=" . $oneyear ."/" . $thisyear . " "  . $thisc . "\n$" . "okvaluelist=" . $okvaluelist . "\n$" . "valuelist=" . $valuelist . "\n$" . "poplist=" . $poplist . "\n$" . "urlextra=" . $urlextra . "\n$" . "url=" . $url . "</textarea></body></html>";
 // exit;
 //     }
      return "0";
      }
    }
    if ($outs > $_GET['max']) {
      $othercnt+=$outs;
      return "0";
    } else if ($thisyear == $oneyear && $valuelist != "") {
      $vls=explode(",",$valuelist);
      if (str_replace("," . $vls[0] . ",","","," . $okvaluelist . ",") == "," . $okvaluelist . ",") {
        if ($okvaluelist == "") {
          $okvaluelist=$vls[0];
        } else {
          $prevok=$okvaluelist;
          $okvaluelist=$vls[0] . "," . $prevok;
        }
      }
    }
  }
  return $outs;
}

function rangeget($basis) {
  global $reportmode;
  $cookie_name = "Worldbank_" . str_replace(" ","_",$reportmode) . "_" . $basis;
  if (isset($_COOKIE[$cookie_name])) {
    return $_COOKIE[$cookie_name];
  }
  return 0.0;
}


function rangeset($basis, $val) {
  global $reportmode, $startswith;
  if ($startswith == "") {
   $cookie_name = "Worldbank_" . str_replace(" ","_",$reportmode) . "_" . $basis;
   $cookie_value = $val;
   setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/PHP/"); // 86400 = 1 day
   return $val;
  }
  return rangeget($basis);
}

function noe($inn) {
  $zeroes="";
  $neg="";
  $zinn=$inn;
  if (substr($inn,0,1) == '-') {
    $neg="-";
    $zinn=substr($inn,1);
  } 
  $ninn=explode("E",$zinn);
  if (sizeof($ninn) == 2) {
     $qd=explode(".",$ninn[0]);
     $hm=str_replace("+","",$ninn[1]);
     if (sizeof($qd) == 1) {
      for ($ii=1; $ii<=abs($hm); $ii++) {
       $zeroes.="0";
      }
      if ($hm >= 0) {
        return $neg . $qd[0] . $zeroes;
      } else {
        return $neg . "0." . $zeroes . $qd[0];
      }
     } else {
      if ($hm >= 0) {
        for ($ii=1; $ii<=(abs($hm) - strlen($qd[1])); $ii++) {
         $zeroes.="0";
        }
        return $neg . $qd[0] . $qd[1] . $zeroes;
      } else {
        for ($ii=1; $ii<=(abs($hm) - strlen($qd[0])); $ii++) {
         $zeroes.="0";
        }
        return $neg . "0." . $zeroes . $qd[0] . $qd[1];
      }
     }
  } 
  return $inn;
}

function thesmallest($y1, $y2) {
  if (strpos($y2, "-") !== false) {
    return min($y1, -$y2);
  } else if ($y2 != "") {
    return $y1; //min($y1, $y2);
  }
  return $y1;
}

function thebiggest($y1, $y2) {
  if (strpos($y2, "-") !== false) {
    return max($y1, -$y2);
  } else if ($y2 != "") {
    return $y1; //max($y1, $y2);
  }
  return $y1;
}

function andto($y1, $y2, $otheridea) {
  global $xrange;
  if (thebiggest($y1, $y2) != thesmallest($y1, $y2)) {
    if (strpos($y2, "-") !== false) {
      return thesmallest($y1, $y2) . " to " . thebiggest($y1, $y2) . $xrange;
    } else {
      return $y2 . " and " . $y1 . $xrange;
    }
  }
  return str_replace("%2d","",str_replace("%2D","",str_replace("-","",str_replace($y1 . " and " . $y2,$y2 . " and " . $y1,str_replace($y1 . "%20and%20" . $y2,$y2 . "%20and%20" . $y1,$otheridea)))));
}

$minval=0.0;
$maxval=0.0;

$thisc="";
$xrange="";
$lookforis="Population, tot";
$reportmode="Population";
$reportmode2="Population";
$indicator="SP.POP.TOTL";
$cn="Pie Chart";
$idata2="";
$udiff="";
$ddiff="";
$page=1;
$valuelist="";
$okvaluelist="";
$firstyear=-1;
$oneyear=0;
$thisyear=0;
$valuedelim="";
$othercnt=0;
$pagecontent="<wb:indicator";
$year="2015";
$xyearvs="";
$yearvs="";
$onclick="<input type='hidden' name='onclick' id='onclick' value='y'></input>";
$poplist="";
$popdelim=",%20";
$idelim="<wb:indicator";
$jdelim='<wb:country id="';
$lookingfor='"Afghanistan<';
$zero=0;
$one=1;
$eight=8;
$cdelim="<";
$prevc="";
$ddelim='<wb:value>';
$wf="600px";
$regexpok=1;
if (isset($_GET['indicator'])) {
  $indicator=$_GET['indicator'];
if ($indicator != "") {
  $reportmode=str_replace("NY.GDP.MKTP.CD","Gross Domestic Product",$indicator);
  $reportmode2=str_replace("NY.GDP.MKTP.CD","Gross Domestic Product (US$)",$indicator);
  $lookforis=str_replace("NY.GDP.MKTP.CD","GDP (current US",$indicator);
}
}
if (isset($_POST['indicator'])) {
  $indicator=$_POST['indicator'];
if ($indicator != "") {
  $reportmode=str_replace("NY.GDP.MKTP.CD","Gross Domestic Product",$indicator);
  $reportmode2=str_replace("NY.GDP.MKTP.CD","Gross Domestic Product (US$)",$indicator);
  $lookforis=str_replace("NY.GDP.MKTP.CD","GDP (current US",$indicator);
}
}
if (isset($_GET['year'])) $year=$_GET['year'];
if (isset($_POST['year'])) $year=$_POST['year'];
if (isset($_GET['yearvs'])) $yearvs=str_replace("%2d","-",str_replace("%2D","-",$_GET['yearvs']));
if (isset($_POST['yearvs'])) $yearvs=str_replace("%2d","-",str_replace("%2D","-",$_POST['yearvs']));
if (isset($_GET['yearvs'])) $xyearvs=" and " . str_replace("%2d","",str_replace("%2D","",str_replace("-","",$_GET['yearvs'])));
if (isset($_POST['yearvs'])) $xyearvs=" and " . str_replace("%2d","",str_replace("%2D","",str_replace("-","",$_POST['yearvs'])));
$zrange=our_str_replace("decimal","0","decimal0");
$tbit=andto($year, $yearvs, $year . $xyearvs . $xrange);
$preudiff="//www.rjmprogramming.com.au/PHP/PieChart/pie_chart";
if (strpos($yearvs, "-") !== false) {
  $mopt="";
  $preudiff="//www.rjmprogramming.com.au/PHP/LineChart/line_chart";
  $cn="Line Chart";
  if (isset($_GET['chart'])) {
    if (strpos(strtolower($_GET['chart']), "column") !== false) {
      $preudiff="//www.rjmprogramming.com.au/PHP/ColumnChart/column_chart";
      $cn="Column Chart";
    } else if (strpos(strtolower($_GET['chart']), "bar") !== false) {
      $preudiff="//www.rjmprogramming.com.au/PHP/BarChart/bar_chart";
      $cn="Bar Chart";
    } else if (strpos(strtolower($_GET['chart']), "area") !== false) {
      $preudiff="//www.rjmprogramming.com.au/PHP/AreaChart/area_chart";
      $cn="Area Chart";
    }
  }
  if (isset($_POST['chart'])) {
    if (strpos(strtolower($_POST['chart']), "column") !== false) {
      $preudiff="//www.rjmprogramming.com.au/PHP/ColumnChart/column_chart";
      $cn="Column Chart";
    } else if (strpos(strtolower($_POST['chart']), "bar") !== false) {
      $preudiff="//www.rjmprogramming.com.au/PHP/BarChart/bar_chart";
      $cn="Bar Chart";
    } else if (strpos(strtolower($_POST['chart']), "area") !== false) {
      $preudiff="//www.rjmprogramming.com.au/PHP/AreaChart/area_chart";
      $cn="Area Chart";
    }
  }
} else if ($yearvs != "") {
  $onclick="";
  $wf="900px";
  $udiff="_diff";
  $mopt="&moreopt=" . urlencode(' width: 620, height: 1200, chartArea: {  width: "46%", height: "70%" },  legend: { position: "right" }, ');
  $ddiff="&data0=";
  $idata2="<input type='hidden' name='data0' id='data0' value=''></input>";
}
$startswith='';
if (isset($_GET['startswith'])) $startswith=urldecode($_GET['startswith']);
if (isset($_POST['startswith'])) $startswith=urldecode($_POST['startswith']);
$url=$preudiff . $udiff . ".php?title=" . str_replace("+","%20",urlencode($reportmode2)) . "%20by%20World%20Country%20" . $startswith . "%20for%20Year%20" . urldecode(andto($year, $yearvs, $year . $xyearvs . $xrange)) . $mopt . "&onclick=y&label=Year&value=&task=" . str_replace("+","%20",urlencode($reportmode)) . "&desc=" . str_replace("+","%20",urlencode($reportmode)) . "&data=";
$urlextra="";
$tso=thesmallest($year, $yearvs);
$tbo=thebiggest($year, $yearvs);

while (strpos($pagecontent, "<wb:indicator") !== false) {
  $pagecontent=@file_get_contents("http://api.worldbank.org/countries/all/indicators/" . $indicator . "?format=json&date=" . $tso . ":" . $tbo . "&page=" . $page);
  if (strpos($pagecontent, $idelim) === false) {
     $idelim=$lookforis; //"Population, tot";
     $jdelim=$lookforis; //"Population, tot";
     $ddelim='"';
     $lookingfor='"Afghanistan"';
     $cdelim=',"value":"';
     $zero=10;
     $one=14;
     $eight=22;
     $pagecontent=str_replace(':null',':"0"',$pagecontent);
  }
  if (strpos($pagecontent, $idelim) !== false) {
     $entries=explode($jdelim, $pagecontent);
     for ($i=1; $i<sizeof($entries); $i++) {
       if ($lookingfor != "") {
         if (str_replace($lookingfor, '', $entries[$i]) != $entries[$i]) $lookingfor="";
       }
       if ($lookingfor == "" && strpos($entries[$i], $ddelim) !== false) {
        $pentries=explode($ddelim, $entries[$i]);
        $regexpok=1;
        
        if (isset($_GET['regex'])) {
          $thisc=str_replace("%27","",str_replace(".","",str_replace("+","%20",urlencode($pentries[$zero]))));
          $regexp="/" . urldecode($_GET['regex']) . "/i";
          //echo $regexp . " " . $thisc . " " . preg_match($regexp,$thisc) . " " . preg_match($regexp,urldecode($thisc));
          //$regexpok=1;
          //if ($regexpok != 0) echo " xxxx";
          //exit;
          $regexpok=preg_match($regexp,$thisc); 
        } else if (isset($_POST['regex'])) {
          $thisc=str_replace("%27","",str_replace(".","",str_replace("+","%20",urlencode($pentries[$zero]))));
          $regexp="/" . urldecode($_POST['regex']) . "/i";
          $regexpok=preg_match($regexp,$thisc); 
        }        

        if ($regexpok != 0 && (strpos('*' . explode("<", str_replace('">', '', $entries[$i]))[0], '*' . $startswith) !== false || strpos('*' . $pentries[$zero], '*' . $startswith) !== false)) { 
          if ($idelim == $lookforis) {
  if (strpos($yearvs, "-") !== false) {
          $prevc="," . $valuelist . ",";
          $thisc=retflagflag(str_replace("%27","",str_replace(".","",str_replace("+","%20",urlencode($pentries[$zero])))));
          if (strpos($prevc, "," . str_replace("%27","",str_replace(".","",str_replace("+","%20",urlencode($pentries[$zero])))) . ",") === false) {
            $prevc=$valuelist;
            $valuelist=retflagflag(str_replace("%27","",str_replace(".","",str_replace("+","%20",urlencode($pentries[$zero]))))) . $valuedelim . $prevc;
            $valuedelim=",";
            //echo $valuelist;
          } //else {
            //echo str_replace("%27","",str_replace(".","",str_replace("+","%20",urlencode($pentries[$zero])))) . " vs " . $prevc;
          //}
          if ($pentries[$one] == "decimal") {
            $thisyear=$pentries[6 + $one];
          } else {
            $thisyear=$pentries[$eight];
          }
          if ($firstyear < 0) {
            $firstyear=$thisyear;
            $oneyear=$thisyear;
          } else if ($thisyear != $oneyear) {
            $firstyear=0;
          }
          if ($poplist == "") {
            for ($jy=$tso; $jy<=$tbo; $jy++) {
              $poplist.=$popdelim . "[~" . $jy . "~]";
            }
          }
          if (strpos($poplist, "~" . $thisyear . "~") !== false) {
          if ($regexpok != 0) $poplist=str_replace("[~" . $thisyear . "~", "[~" . $thisyear . "~," . our_str_replace("decimal","0",explode($cdelim, $pentries[$one])[0]), $poplist);
          } else {
          $prevc=$poplist;
          if ($regexpok != 0) $poplist=$popdelim . "[~" . $thisyear . "~," . our_str_replace("decimal","0",explode($cdelim, $pentries[$one])[0]) . "]" . $prevc;
          }
  } else {
          if ($regexpok != 0) {
            //echo "2 " . $regexpok . " ... " . $regexp . " " . $thisc . " " . str_replace("%27","",str_replace(".","",str_replace("+","%20",urlencode($pentries[$zero]))));
            //exit;
            $poplist.=$popdelim . "[~" . retflagflag(str_replace("%27","",str_replace(".","",str_replace("+","%20",urlencode($pentries[$zero]))))) . "~," . our_str_replace("decimal","0",$pentries[$one]) . "]";
          }
  }
          } else {
  if (strpos($yearvs, "-") !== false) {
          $prevc="," . $valuelist . ",";
          $thisc=retflagflag(str_replace("%27","",str_replace(".","",str_replace("+","%20",explode('"', explode($cdelim, str_replace('">', '', urlencode($entries[$i])))[$zero])[0]))));
        $regexpok=1;
        
        if (isset($_GET['regex'])) {
          $regexp="/" . urldecode($_GET['regex']) . "/i";
          //echo $regexp . " " . $thisc . " " . preg_match($regexp,$thisc) . " " . preg_match($regexp,urldecode($thisc));
          //exit;
          $regexpok=preg_match($regexp,$thisc); 
        } else if (isset($_POST['regex'])) {
          $regexp="/" . urldecode($_POST['regex']) . "/i";
          $regexpok=preg_match($regexp,$thisc); 
        }        

        if (strpos($prevc, "," . retflagflag(str_replace("%27","",str_replace(".","",str_replace("+","%20",explode('"', explode($cdelim, str_replace('">', '', urlencode($entries[$i])))[$zero])[0])))) . ",") === false) {
            $prevc=$valuelist;
            $valuelist=retflagflag(str_replace("%27","",str_replace(".","",str_replace("+","%20",explode('"', explode($cdelim, str_replace('">', '', urlencode($entries[$i])))[$zero])[0])))) . $valuedelim . $prevc;
            $valuedelim=",";
            //echo $valuelist;
          } //else {
            //echo str_replace("%27","",str_replace(".","",str_replace("+","%20",explode('"', explode($cdelim, str_replace('">', '', urlencode($entries[$i])))[$zero])[0]))) . " vs " . $prevc;
          //}
          if ($pentries[$one] == "decimal") {
            $thisyear=$pentries[6 + $one];
          } else {
            $thisyear=$pentries[$eight];
          }
          if ($firstyear < 0) {
            $firstyear=$thisyear;
            $oneyear=$thisyear;
          } else if ($thisyear != $oneyear) {
            $firstyear=0;
          }
          if ($poplist == "") {
            for ($jy=$tso; $jy<=$tbo; $jy++) {
              $poplist.=$popdelim . "[~" . $jy . "~]";
            }
          }
          if (strpos($poplist, "~" . $thisyear . "~") !== false) {
          if ($regexpok != 0) $poplist=str_replace("[~" . $thisyear . "~", "[~" . $thisyear . "~," . our_str_replace("decimal","0",explode($cdelim, $pentries[$one])[0]), $poplist);
          } else {
          $prevc=$poplist;
          if ($regexpok != 0) $poplist=$popdelim . "[~" . $thisyear . "~," . our_str_replace("decimal","0",explode($cdelim, $pentries[$one])[0]) . "]" . $prevc;
          }
  } else {
           if ($regexpok != 0) {
            //echo "1 " . $thisc;
            //exit;
            $poplist.=$popdelim . "[~" . retflagflag(str_replace("%27","",str_replace(".","",str_replace("+","%20",explode('"', explode($cdelim, str_replace('">', '', urlencode($entries[$i])))[$zero])[0])))) . "~," . our_str_replace("decimal","0",explode($cdelim, $pentries[$one])[0]) . "]";
           }
  }
          }
          $popdelim=",%20";
        } else if (strpos($yearvs, "-") === false) {
          if ($idelim == $lookforis) {
          $othercnt+=str_replace("decimal","0",$pentries[$one]);
          } else {
          $othercnt+=str_replace("decimal","0",explode($cdelim, $pentries[$one])[0]);
          }
        }
       }       
     }
     $pagecontent="<wb:indicator";
  }
  $page++;
}

if (strpos($yearvs, "-") !== false) {
            for ($jy=$tso; $jy<=$tbo; $jy++) {
              $poplist=str_replace($popdelim . "[~" . $jy . "~]", "", $poplist);
            }
} 

if ($othercnt > 0 && !isset($_GET['justletters']) && !isset($_POST['justletters'])) {
  $url.=ourfilter($poplist) . $popdelim . "[~Non-" . $startswith . "~," . noe($othercnt) . "]";
} else {
  $url.=ourfilter($poplist);
}
if (strpos($yearvs, "-") !== false) $yearvs="";

$page=1;
$pagecontent="<wb:indicator";
$othercnt=0;
$zero=0;
$one=1;
$cdelim="<";
$ddelim='<wb:value>';
$poplist="";
$popdelim=",%20";
$idelim="<wb:indicator";
$jdelim='<wb:country id="';
$lookingfor='"Afghanistan<';
if ($yearvs != "") {
$urlextra="&data0=";
while (strpos($pagecontent, "<wb:indicator") !== false) {
  $pagecontent=@file_get_contents("http://api.worldbank.org/countries/all/indicators/" . $indicator . "?format=json&date=" . $yearvs . ":" . $yearvs . "&page=" . $page);
  if (strpos($pagecontent, $idelim) === false) {
     $idelim=$lookforis; //"Population, tot";
     $jdelim=$lookforis; //"Population, tot";
     $ddelim='"';
     $lookingfor='"Afghanistan"';
     $cdelim=',"value":"';
     $zero=10;
     $one=14;
     $eight=22;
     $pagecontent=str_replace(':null',':"0"',$pagecontent);
  }
  if (strpos($pagecontent, $idelim) !== false) {
     $entries=explode($jdelim, $pagecontent);
     for ($i=1; $i<sizeof($entries); $i++) {
       if ($lookingfor != "") {
         if (str_replace($lookingfor, '', $entries[$i]) != $entries[$i]) $lookingfor="";
       }
       if ($lookingfor == "" && strpos($entries[$i], $ddelim) !== false) {
        $pentries=explode($ddelim, $entries[$i]);
        $regexpok=1;
        
        if (isset($_GET['regex'])) {
          $thisc=str_replace("%27","",str_replace(".","",str_replace("+","%20",urlencode($pentries[$zero]))));
          $regexp="/" . urldecode($_GET['regex']) . "/i";
          //echo $regexp . " " . $thisc . " " . preg_match($regexp,$thisc) . " " . preg_match($regexp,urldecode($thisc));
          //$regexpok=1;
          //if ($regexpok != 0) echo " xxxx";
          //exit;
          if (preg_match($regexp,$thisc)) $regexpok=preg_match($regexp,$thisc); 
        } else if (isset($_POST['regex'])) {
          $thisc=str_replace("%27","",str_replace(".","",str_replace("+","%20",urlencode($pentries[$zero]))));
          $regexp="/" . urldecode($_POST['regex']) . "/i";
          if (preg_match($regexp,$thisc)) $regexpok=preg_match($regexp,$thisc); 
        }        

        if ($regexpok != 0 && (strpos('*' . explode("<", str_replace('">', '', $entries[$i]))[0], '*' . $startswith) !== false || strpos('*' . $pentries[$zero], '*' . $startswith) !== false)) { 
          if ($idelim == $lookforis) {
          if ($regexpok != 0) $poplist.=$popdelim . "[~" . retflagflag(str_replace("%27","",str_replace(".","",str_replace("+","%20",urlencode($pentries[$zero]))))) . "~," . our_str_replace("decimal","0",$pentries[$one]) . "]";
          } else {
          if ($regexpok != 0) $poplist.=$popdelim . "[~" . retflagflag(str_replace("%27","",str_replace(".","",str_replace("+","%20",explode('"', explode($cdelim, str_replace('">', '', urlencode($entries[$i])))[$zero])[0])))) . "~," . our_str_replace("decimal","0",explode($cdelim, $pentries[$one])[0]) . "]";
          }
          $popdelim=",%20";
        } else {
          if ($idelim == $lookforis) {
          $othercnt+=str_replace("decimal","0",$pentries[$one]);
          } else {
          $othercnt+=str_replace("decimal","0",explode($cdelim, $pentries[$one])[0]);
          }
        }
       }       
     }
     $pagecontent="<wb:indicator";
  }
  $page++;
}
}

if ($okvaluelist != "" && $okvaluelist != $valuelist) {
 // echo "<!doctype html><html><body><textarea cols=80 rows=200 style=width:100%;>$" . "okvaluelist=" . $okvaluelist . "\n$" . "valuelist=" . $valuelist . "\n$" . "poplist=" . $poplist . "\n$" . "urlextra=" . $urlextra . "\n$" . "url=" . $url . "</textarea></body></html>";
 // exit;
  $valuelist=$okvaluelist;
  $poplist=str_replace(",0","",$poplist);
  $urlextra=str_replace(",0","",$urlextra);
  $url=str_replace(",0","",$url);
}

if ($othercnt > 0 && !isset($_GET['justletters']) && !isset($_POST['justletters'])) {
  $urlextra.=$poplist . $popdelim . "[~Non-" . $startswith . "~," . $othercnt . "]";
  $idata2="<input type='hidden' name='data0' id='data0' value='" . explode("&data0=",$urlextra)[1] . "'></input>";
} else if ($poplist != "") {
  $urlextra.=$poplist;
  $idata2="<input type='hidden' name='data0' id='data0' value='" . explode("&data0=",$urlextra)[1] . "'></input>";
}

echo "<!doctype html><html><head><title>World Bank API " . $reportmode . " Data Google Chart " . $cn . " - RJM Programming - February, 2016</title><scr" . "ipt type='text/javascript'> 
  var url='" . explode("&data=",$url)[1] . "'; 
  var urlextra=\"" . str_replace('"','" + String.fromCharCode(34) + "',$urlextra) . "\"; 
  function preiframeviaurl() {
    if (document.getElementById('data').value != '') url=document.getElementById('data').value;
    return true;
  }
  function iframeviaurl() {
    if (parent.document.getElementById('maxrange')) {
       parent.document.getElementById('maxrange').value='" . rangeset('max',$maxval) . "'; 
    }
    if (parent.document.getElementById('minrange')) {
       parent.document.getElementById('minrange').value='" . rangeset('min',$minval) . "'; 
    }
    if (parent.document.getElementById('childiframe')) {
       document.body.style.backgroundColor='lightblue';
    }
    if (('" . str_replace('&value=&','&value=' . str_replace('%2c','',str_replace('%2C','',$valuelist)) . '&',explode("&data=",$url)[0]) . "&data=' + url + '" . $urlextra . "').length > 750) {
       document.getElementById('myiframe').style.display='block';
       document.getElementById('data').value=decodeURIComponent(url);
       document.getElementById('mysubmit').click();
    } else if (url != '') {
       document.getElementById('myiframe').style.display='block';
       document.getElementById('myiframe').src='" . str_replace('&value=&','&value=' . str_replace('%2c','',str_replace('%2C','',$valuelist)) . '&',explode("&data=",$url)[0]) . "&data=' + url + '" . $urlextra . "';
    }
    return true;
  }

function shareviaemail() {
  var prefix=document.getElementById('aemail').href.split('body=');
  document.getElementById('aemail').href=prefix[0] + 'body=' + encodeURIComponent(document.URL); 
  document.getElementById('aemail').click();
}
</scr" . "ipt>
</head>
<body onload='iframeviaurl();' style='height:900px;'>
<h1>World Bank API " . $reportmode . " Data Google Chart " . $cn . " <a id='eemail' onclick='shareviaemail();' title='Share via Email a link to this Current Pie Chart you are Viewing'>&#128231;</a></h1>
<h3>RJM Programming - February, 2016</h3>
<h4>Thanks to <a target=_blank title='World Bank API documentation' href='https://datahelpdesk.worldbank.org/knowledgebase/articles/898581-api-basic-call-structure'>World Bank API</a></h4>
<iframe style='width:100%;height:" . $wf . ";display:none;' name='myiframe' id='myiframe' src='about:blank'></iframe>
<form onsubmit='return preiframeviaurl();' target='myiframe' id='myform' style='display:none;' method='POST' action='" . $preudiff . $udiff . ".php'>
<input type='hidden' name='title' id='title' value='" . $reportmode2 . " by World Country " . $startswith . " for Year " . $tbit . "'></input>
" . $onclick . "
<input type='hidden' name='task' id='task' value='" . $reportmode . "'></input>
<input type='hidden' name='desc' id='desc' value='" . $reportmode . "'></input>
<input type='hidden' name='label' id='label' value='Year'></input>
<input type='hidden' name='value' id='value' value='" . str_replace('%2c','',str_replace('%2C','',$valuelist)) . "'></input>
<input type='hidden' name='onclick' value='y'></input>
<input type='hidden' name='moreopt' value=' width: 620, height: 1200, chartArea: {  width: \"46%\", height: \"70%\" }, legend: { position: \"right\" }, '></input>
<input type='hidden' name='wouldlikeyoutoseekpermission' value='y'></input>
<input type='hidden' name='data' id='data' value='" . explode("&data=",$url)[1] . "'></input>" . "\n" . $idata2 . "\n" . "
<input id='mysubmit' type='submit' value='Draw Pie Chart'></input>
</form>
<a target='_top' style='display:none;' href='mailto:fillin@email.to?subject=World%20Bank%20" . str_replace("+","%20",urlencode($reportmode)) . "%20Data%20" . urlencode($cn) . "&body=' id='aemail'>Share via Email</a>
</body>
</html>";

?>