<?php
  function second($in, $string) {
      return strpos(substr($in, strpos($in, $string) + 1), $string) + strpos($in, $string) + 2;
  }
  //grab class
  include('Wikibot.php5');
  //get my password
  $fhpw = fopen("password2.txt", 'r') or die("can't open file");
  $password = fgets($fhpw);
  fclose($fhpw);
  //create bot
  $LivingBot = new Wikibot("LivingBot", $password, "en", "5", "5");
  
  $handle = fopen("livingbot_targets.txt", 'r') or die("can't open file");
  while (!feof($handle)) {
      $targets[] = trim(fgets($handle));
  }
  fclose($handle);
  $targets[0] = "User:Jarry1250/Achaen";
  $counter = 0;
  for ($i = 40; $i < count($targets); $i++) {
      if (stripos($LivingBot->get_page("User:LivingBot/shutoff"), "<!--Emergency shutoff-->") === false) {
          echo "Bot shut down.<br />";
          break;
      }
      echo "Editing page [[$targets[$i]]].<br />";
      $page = $LivingBot->get_page($targets[$i]);
      //echo $page;
      if (stripos(str_replace(" ", "", $page), "{{infobox") !== false || stripos($page, "Map not yet") === false) {
          //It's been updated in the mean time
          echo "Not found. <br />";
          continue;
      }
      preg_match("/'''[^']*'''/", $page, $temp);
      $name = substr($temp[0], 3, strlen($temp[0]) - 6);
      preg_match("/<br[ ]*>'''''[^']*'''''/", $page, $temp);
      $native = substr($temp[0], (strpos($temp[0], "'") + 5), strlen($temp[0]) - 14);
      $prefec = "[[Achaea]]";
      if (stripos(str_replace(" ", "", $page), "{{coord") !== false) {
          preg_match_all("/\{\{[ ]*coord[ ]*\|[ ]*([^ |]*)[ ]*\|[ ]*([^ |]*)[ ]*\|[ ]*([^ |]*)[ ]*\|[ ]*([^ |]*)[ ]*\|[ ]*([^ |]*)[ ]*\|[ ]*([^ |]*)[ ]*\|[ ]*([^ |]*)[ ]*\|[ ]*([^ |]*)[ ]*/i", $page, $temp);
          $map = "Greece";
          $latd = $temp[1][0];
          $latm = $temp[2][0];
          if (trim($temp[4][0]) == "N" || trim($temp[4][0]) == "S") {
              //Degs, mins and secs
              $lats = $temp[3][0];
              $latNS = $temp[4][0];
              $longd = $temp[5][0];
              $longm = $temp[6][0];
              $longs = $temp[7][0];
              $longEW = $temp[8][0];
          } elseif (trim($temp[3][0]) == "N" || trim($temp[3][0]) == "S") {
              //Just degs and mins
              $latNS = $temp[3][0];
              $longd = $temp[4][0];
              $longm = $temp[5][0];
              $longEW = $temp[6][0];
          }
      } elseif (preg_match("/[(][0-9][0-9][^0-9a-zA-Z%.]{2} [0-9]+['] [0-9]+[\"]\) [NS]/", $page) === true) {
          preg_match("/[(][0-9][0-9][^0-9a-zA-Z%.]{2} [0-9]+['] [0-9]+[\"]\) [NS]/", $page, $temp);
          $secspace = second($temp[0], " ");
          $latd = substr($temp[0], 1, 2);
          $latm = substr($temp[0], strpos($temp[0], " ") + 1, (strpos($temp[0], "'") - strpos($temp[0], " ") - 1));
          $lats = substr($temp[0], $secspace, (strpos($temp[0], '"') - $secspace));
          $latNS = substr($temp[0], strlen($temp[0]) - 1, 1);
          preg_match("/[(][0-9][0-9][^0-9a-zA-Z%.]{2} [0-9]+['] [0-9]+[\"]\) [EW]/", $page, $temp);
          $longd = substr($temp[0], 1, 2);
          $longm = substr($temp[0], strpos($temp[0], " ") + 1, (strpos($temp[0], "'") - strpos($temp[0], " ") - 1));
          $secspace = second($temp[0], " ");
          $longs = substr($temp[0], $secspace, (strpos($temp[0], '"') - $secspace));
          $longEW = substr($temp[0], strlen($temp[0]) - 1, 1);
          $map = "Greece";
      }
      preg_match("/ Municipality: \|\|(.*)\[\[(.*)\]\]/", $page, $temp);
      $munic = substr($temp[0], strpos($temp[0], "|") + 2);
      preg_match("/ \[\[Provinces of Greece\|Province\]\]: \|\|(.*)\[\[(.*)\]\]/", $page, $temp);
      $province = substr($temp[0], second($temp[0], "|") + 2);
      preg_match("/ Municipal district: \|\|[^|]*/", $page, $temp);
      $district = str_replace("'", "", substr($temp[0], strpos($temp[0], "|") + 2));
      preg_match("/ \[\[Area codes in Greece\|Area\/distance code\]\]: \|\|[ ]*[^]]*\]\]/", $page, $temp);
      $code = substr($temp[0], second($temp[0], "|") + 2, strlen($temp[0]) - second($temp[0], "|") + 4);
      preg_match("/ Population: \([0-9]{4}\)/", $page, $temp);
      $popyear = substr($temp[0], 14, 4);
      preg_match_all("/Population:[^|]*\|\|<br>([^< ]*)[ <]/", $page, $temp);
      $pop = $temp[1][0];
      preg_match("/GR-[0-9]{3} [0-9]{2}/", $page, $temp);
      $postal = $temp[0];
      preg_match("/ Website: \|\|(.*)\[\[(.*)\]\]/", $page, $temp);
      $website = substr($temp[0], strpos($temp[0], "|") + 2);
      preg_match_all("/\[\[Category:[ ]*([^ \]]*) in the ([^ ]*) prefecture/", $page, $temp);
      $type = $temp[1][0];
      $prefec = "[[" . $temp[2][0] . "]]";
      echo $type;
      switch ($type) {
          case "Municipalities":
              $type = "Municipality";
              break;
          case "Villages":
              $type = "Village";
              break;
          default:
              if (preg_match("/\[\[Category:[ ]*Achaea/", $page) == true) {
                  echo "Matched cat. ";
                  $prefec = "[[Achaea]]";
                  if (is_numeric(str_replace(",", "", $pop))) {
                      echo "Numeric. ";
                      if (str_replace(",", "", $pop) < 3000) {
                          $type = "Village";
                      } else {
                          
                          $type = "Municipality";
                      }
                  }
              } else {
                  
                  echo "Type not found (" . preg_match("/\[\[Category:[ ]*Achaea/", $page) . ".";
                  continue(2);
              }
              break;
      }
      echo "Continuing...";
      $new = "{{Infobox Settlement
<!--See Template:Infobox Settlement for additional fields that may be available-->
<!--See the Table at Infobox Settlement for all fields and descriptions of usage-->
<!-- Basic info  ---------------->
|name                   = $name
|official_name          =
|other_name             =
|native_name            = $native
|native_name_lang       = gr
|nickname               =
|settlement_type        = $type
|total_type             = <!-- to set a non-standard label for total area and population rows -->
|motto                  =
<!-- images and maps  ----------->
|image_skyline          =
|imagesize              =
|image_caption          =
|image_flag             =
|flag_size              =
|image_seal             =
|seal_size              =
|image_shield           =
|shield_size            =
|image_blank_emblem     =
|blank_emblem_type      =
|blank_emblem_size      =
|image_map              =
|mapsize                =
|map_caption            =
|image_map1             =
|mapsize1               =
|map_caption1           =
|image_dot_map          =
|dot_mapsize            =
|dot_map_caption        =
|dot_x =  |dot_y =
|pushpin_map            = $map
|pushpin_label_position = <!-- the position of the pushpin label: left, right, top, bottom, none -->
|pushpin_map_caption    =
|pushpin_mapsize        =
<!-- Location ------------------>
|subdivision_type       = Country
|subdivision_name       = Greece
|subdivision_type1      = [[Prefectures of Greece|Prefecture]]
|subdivision_name1      = $prefec
|subdivision_type2      = [[Provinces of Greece|Province]]
|subdivision_name2      = $province
|subdivision_type3      = Municipality
|subdivision_name3      = $munic
|subdivision_type4      = Municipal district
|subdivision_name4      = $district
<!-- Smaller parts (e.g. boroughs of a city) and seat of government -->
|seat_type              =
|seat                   =
|parts_type             =
|parts_style            = <!-- =list (for list), coll (for collapsed list), para (for paragraph format)
                               Default is list if up to 5 items, coll if more than 5-->
|parts                  = <!-- parts text, or header for parts list -->
|p1                     =
|p2                     = <!-- etc. up to p50: for separate parts to be listed-->
<!-- Politics ----------------->
|government_footnotes   =
|government_type        =
|leader_title           =
|leader_name            =  <!--add   (no-break space) to leader names to disable automatic links-->
|leader_title1          =
|leader_name1           =
|established_title      =  <!-- Settled -->
|established_date       =
<!-- Area    --------------------->
|area_magnitude         =
|unit_pref                = <!--Enter: Imperial, to display imperial  before metric-->
|area_footnotes           =
|area_total_km2           = <!-- ALL fields with measurements are subject to automatic unit conversion-->
|area_land_km2            = <!--See table @ Template:Infobox Settlement for details on unit conversion-->
|area_water_km2           =
|area_total_sq_mi         =
|area_land_sq_mi          =
|area_water_sq_mi         =
|area_water_percent       =
<!-- Elevation -------------------------->
|elevation_footnotes    =  <!--for references: use <ref> tags-->
|elevation_m            =
|elevation_ft           =
|elevation_max_m            =
|elevation_max_ft           =
|elevation_min_m            =
|elevation_min_ft           =
<!-- Population   ----------------------->
|population_as_of               = $popyear
|population_footnotes           =
|population_note                =
|population_total               = $pop
|population_density_km2         = <!--For automatic calculation, any density field may contain: auto -->
|population_density_sq_mi       =
<!-- General information  --------------->
|time_zone          = [[Eastern European Time|EET]]
|utc_offset         = +2
|time_zone_DST      = [[EEST]]
|utc_offset_DST     = +3
|coor_pinpoint         =<!-- can be used to specify exactly where/what the coordinates refer to -->
|coordinates_type       = type:city($pop)_region:GR
|coordinates_display    = display=inline,title
|latd= $latd |latm= $latm |lats= $lats |latNS= $latNS
|longd= $longd |longm= $longm |longs= $longs |longEW= $longEW
<!-- Area/postal codes & others -------->
|postal_code_type       =  [[List of postal codes in Greece|Postal code]]
|postal_code            =  $postal
|area_code              =  $code
|website                =  $website
|footnotes              =
}}";
      
      $newpage = preg_replace("/\{\| border=[\"]0[\"][^}]*\}/", $new, $page);
      $LivingBot->edit_page($targets[$i], $page, $newpage, "Bot replacing table with infobox (settlement). [[User_talk:LivingBot|Incorrect?]]");
      $counter++;
      if ($counter == 6) {
          break;
      }
  }
?>