Update library with latest Google internal changes.

Change-Id: I9ce02d7b1da0b7532bbe992f05effeb562cb444e
diff --git a/README.android b/README.android
index 2816674..c38a6c3 100644
--- a/README.android
+++ b/README.android
@@ -1,4 +1,4 @@
 URL: http://code.google.com/p/libphonenumber/
-Version: r37
+Version: r39
 License: Apache 2
 Description: Google Phone Number Library.
diff --git a/java/resources/com/google/i18n/phonenumbers/BuildMetadataProtoFromXml.java b/java/resources/com/google/i18n/phonenumbers/BuildMetadataProtoFromXml.java
index 272ba29..2d2a50d 100644
--- a/java/resources/com/google/i18n/phonenumbers/BuildMetadataProtoFromXml.java
+++ b/java/resources/com/google/i18n/phonenumbers/BuildMetadataProtoFromXml.java
@@ -98,6 +98,9 @@
     PhoneMetadata metadata = new PhoneMetadata();
     metadata.setId(regionCode);
     metadata.setCountryCode(Integer.parseInt(element.getAttribute("countryCode")));
+    if (element.hasAttribute("leadingDigits")) {
+      metadata.setLeadingDigits(validateRE(element.getAttribute("leadingDigits")));
+    }
     metadata.setInternationalPrefix(validateRE(element.getAttribute("internationalPrefix")));
     if (element.hasAttribute("preferredInternationalPrefix")) {
       String preferredInternationalPrefix = element.getAttribute("preferredInternationalPrefix");
@@ -105,6 +108,7 @@
     }
     String nationalPrefix = "";
     String nationalPrefixFormattingRule = "";
+    String carrierCodeFormattingRule = "";
     if (element.hasAttribute("nationalPrefix")) {
       nationalPrefix = element.getAttribute("nationalPrefix");
       metadata.setNationalPrefix(nationalPrefix);
@@ -126,6 +130,10 @@
       metadata.setPreferredExtnPrefix(element.getAttribute("preferredExtnPrefix"));
     }
 
+    if (element.hasAttribute("mainCountryForCode")) {
+      metadata.setMainCountryForCode(true);
+    }
+
     // Extract availableFormats
     NodeList numberFormatElements = element.getElementsByTagName("numberFormat");
     int numOfFormatElements = numberFormatElements.getLength();
@@ -139,6 +147,13 @@
         } else {
           format.setNationalPrefixFormattingRule(nationalPrefixFormattingRule);
         }
+        if (numberFormatElement.hasAttribute("carrierCodeFormattingRule")) {
+          format.setDomesticCarrierCodeFormattingRule(validateRE(
+              getDomesticCarrierCodeFormattingRuleFromElement(numberFormatElement,
+                                                              nationalPrefix)));
+        } else {
+          format.setDomesticCarrierCodeFormattingRule(carrierCodeFormattingRule);
+        }
         if (numberFormatElement.hasAttribute("leadingDigits")) {
           format.setLeadingDigits(validateRE(numberFormatElement.getAttribute("leadingDigits")));
         }
@@ -159,6 +174,13 @@
         }
         format.setPattern(validateRE(numberFormatElement.getAttribute("pattern")));
         format.setFormat(validateRE(numberFormatElement.getFirstChild().getNodeValue()));
+        if (numberFormatElement.hasAttribute("carrierCodeFormattingRule")) {
+          format.setDomesticCarrierCodeFormattingRule(validateRE(
+              getDomesticCarrierCodeFormattingRuleFromElement(numberFormatElement,
+                                                              nationalPrefix)));
+        } else {
+          format.setDomesticCarrierCodeFormattingRule(carrierCodeFormattingRule);
+        }
         metadata.addIntlNumberFormat(format);
       }
     }
@@ -192,6 +214,15 @@
     return nationalPrefixFormattingRule;
   }
 
+  private static String getDomesticCarrierCodeFormattingRuleFromElement(Element element,
+                                                                        String nationalPrefix) {
+    String carrierCodeFormattingRule = element.getAttribute("carrierCodeFormattingRule");
+    // Replace $FG with the first group ($1) and $NP with the national prefix.
+    carrierCodeFormattingRule = carrierCodeFormattingRule.replaceFirst("\\$FG", "\\$1")
+        .replaceFirst("\\$NP", nationalPrefix);
+    return carrierCodeFormattingRule;
+  }
+
   /**
    * Processes a phone number description element from the XML file and returns it as a
    * PhoneNumberDesc. If the description element is a fixed line or mobile number, the general
diff --git a/java/resources/com/google/i18n/phonenumbers/proto/phonemetadata.proto b/java/resources/com/google/i18n/phonenumbers/proto/phonemetadata.proto
index 44f9764..6c30e14 100644
--- a/java/resources/com/google/i18n/phonenumbers/proto/phonemetadata.proto
+++ b/java/resources/com/google/i18n/phonenumbers/proto/phonemetadata.proto
@@ -64,6 +64,12 @@
   // prefix in NATIONAL format. This field does not affect how a number
   // is formatted in other formats, such as INTERNATIONAL.
   optional string national_prefix_formatting_rule = 4;
+
+  // This field specifies how any carrier code ($CC) together with the first
+  // group ($FG) in the national significant number should be formatted
+  // when formatWithCarrierCode is called, if carrier codes are used for a
+  // certain country.
+  optional string domestic_carrier_code_formatting_rule = 5;
 }
 
 message PhoneNumberDesc {
@@ -193,8 +199,21 @@
   // 15 (inserted after the area code of 343) is used.
   repeated NumberFormat intl_number_format = 20;
 
-  // Deprecated.
-  optional string national_prefix_formatting_rule = 21;
+  // This field is set when this country is considered to be the main country
+  // for a calling code. It may not be set by more than one country with the
+  // same calling code, and it should not be set by countries with a unique
+  // calling code. This can be used to indicate that "GB" is the main country
+  // for the calling code "44" for example, rather than Jersey or the Isle of
+  // Man.
+  optional bool main_country_for_code = 22 [default=false];
+
+  // This field is populated only for countries or regions that share a country
+  // calling code. If a number matches this pattern, it could belong to this
+  // region. This is not intended as a replacement for IsValidForRegion, and
+  // does not mean the number must come from this region (for example, 800
+  // numbers are valid for all NANPA countries.) This field should be a regular
+  // expression of the expected prefix match.
+  optional string leading_digits = 23;
 }
 
 message PhoneMetadataCollection {
diff --git a/java/resources/com/google/i18n/phonenumbers/src/PhoneNumberMetaData.xml b/java/resources/com/google/i18n/phonenumbers/src/PhoneNumberMetaData.xml
index a463f49..1958cea 100644
--- a/java/resources/com/google/i18n/phonenumbers/src/PhoneNumberMetaData.xml
+++ b/java/resources/com/google/i18n/phonenumbers/src/PhoneNumberMetaData.xml
@@ -53,6 +53,7 @@
 
     <!ATTLIST territory id CDATA #REQUIRED>
     <!ATTLIST territory countryCode CDATA #REQUIRED>
+    <!ATTLIST territory leadingDigits CDATA #IMPLIED>
     <!ATTLIST territory preferredInternationalPrefix CDATA #IMPLIED>
     <!ATTLIST territory internationalPrefix CDATA #REQUIRED>
     <!ATTLIST territory nationalPrefix CDATA #IMPLIED>
@@ -60,11 +61,15 @@
     <!ATTLIST territory nationalPrefixTransformRule CDATA #IMPLIED>
     <!ATTLIST territory preferredExtnPrefix CDATA #IMPLIED>
     <!ATTLIST territory nationalPrefixFormattingRule CDATA #IMPLIED>
+    <!ATTLIST territory mainCountryForCode (true) #IMPLIED>
+    <!ATTLIST territory carrierCodeFormattingRule CDATA #IMPLIED>
     <!ATTLIST numberFormat nationalPrefixFormattingRule CDATA #IMPLIED>
+    <!ATTLIST numberFormat carrierCodeFormattingRule CDATA #IMPLIED>
     <!ATTLIST numberFormat leadingDigits CDATA #IMPLIED>
     <!ATTLIST numberFormat pattern CDATA #REQUIRED>
     <!ATTLIST intlNumberFormat leadingDigits CDATA #IMPLIED>
     <!ATTLIST intlNumberFormat pattern CDATA #REQUIRED>
+    <!ATTLIST intlNumberFormat carrierCodeFormattingRule CDATA #IMPLIED>
     ]>
 
 <phoneNumberMetadata>
@@ -174,7 +179,8 @@
 
     <!-- Antigua and Barbuda -->
     <!-- http://www.itu.int/oth/T0202000008/en -->
-    <territory id="AG" countryCode="1" internationalPrefix="011">
+    <territory id="AG" countryCode="1" leadingDigits="268"
+      internationalPrefix="011">
       <generalDesc>
         <!-- NANPA country - uses US formatting rules -->
         <nationalNumberPattern>[289]\d{9}</nationalNumberPattern>
@@ -209,7 +215,8 @@
 
     <!-- Anguilla -->
     <!-- http://www.itu.int/oth/T0202000007/en -->
-    <territory id="AI" countryCode="1" internationalPrefix="011">
+    <territory id="AI" countryCode="1" leadingDigits="264"
+      internationalPrefix="011">
       <generalDesc>
         <!-- NANPA country - uses US formatting rules -->
         <nationalNumberPattern>[289]\d{9}</nationalNumberPattern>
@@ -391,7 +398,8 @@
 
     <!-- American Samoa -->
     <!-- http://www.itu.int/oth/T0202000004/en -->
-    <territory id="AS" countryCode="1" internationalPrefix="011">
+    <territory id="AS" countryCode="1" leadingDigits="684"
+      internationalPrefix="011">
       <generalDesc>
         <!-- NANPA country - uses US formatting rules -->
         <nationalNumberPattern>[689]\d{9}</nationalNumberPattern>
@@ -605,13 +613,50 @@
     </territory>
 
     <!-- Bosnia and Herzegovina -->
+    <!-- http://www.cra.ba/en/telecom/numbering/ -->
+    <!-- http://en.wikipedia.org/wiki/+387 -->
     <territory id="BA" countryCode="387" internationalPrefix="00"
-               nationalPrefix="0">
+               nationalPrefix="0" nationalPrefixFormattingRule="$NP$FG">
+      <availableFormats>
+        <numberFormat pattern="([3-689]\d)(\d{3})(\d{3})">$1 $2-$3</numberFormat>
+      </availableFormats>
+      <generalDesc>
+        <nationalNumberPattern>[3-689]\d{7}</nationalNumberPattern>
+        <possibleNumberPattern>\d{6,8}</possibleNumberPattern>
+      </generalDesc>
+      <fixedLine>
+        <!-- Including local tariff numbers here. -->
+        <nationalNumberPattern>(?:[35]\d|49|81)\d{6}</nationalNumberPattern>
+        <exampleNumber>30123456</exampleNumber>
+      </fixedLine>
+      <mobile>
+        <nationalNumberPattern>6[1-356]\d{6}</nationalNumberPattern>
+        <possibleNumberPattern>\d{8}</possibleNumberPattern>
+        <exampleNumber>61123456</exampleNumber>
+      </mobile>
+      <tollFree>
+        <nationalNumberPattern>8[08]\d{6}</nationalNumberPattern>
+        <possibleNumberPattern>\d{8}</possibleNumberPattern>
+        <exampleNumber>80123456</exampleNumber>
+      </tollFree>
+      <premiumRate>
+        <nationalNumberPattern>9[0246]\d{6}</nationalNumberPattern>
+        <possibleNumberPattern>\d{8}</possibleNumberPattern>
+        <exampleNumber>90123456</exampleNumber>
+      </premiumRate>
+      <sharedCost>
+        <!-- Using this category to model national tariff numbers - these are
+        under Shared Cost in the plan. -->
+        <nationalNumberPattern>82\d{6}</nationalNumberPattern>
+        <possibleNumberPattern>\d{8}</possibleNumberPattern>
+        <exampleNumber>82123456</exampleNumber>
+      </sharedCost>
     </territory>
 
     <!-- Barbados -->
     <!-- http://www.itu.int/oth/T0202000013/en -->
-    <territory id="BB" countryCode="1" internationalPrefix="011">
+    <territory id="BB" countryCode="1" leadingDigits="246"
+      internationalPrefix="011">
       <generalDesc>
         <!-- NANPA country - uses US formatting rules -->
         <nationalNumberPattern>[289]\d{9}</nationalNumberPattern>
@@ -639,8 +684,51 @@
     </territory>
 
     <!-- Bangladesh -->
-    <territory id="BD" countryCode="880" internationalPrefix="00"
-               nationalPrefix="0">
+    <!-- http://www.itu.int/oth/T0202000012/en -->
+    <!-- http://en.wikipedia.org/wiki/Telephone_numbers_in_Bangladesh -->
+    <!-- http://www.btrc.gov.bd/engineering/national_numbering_plan_2005.pdf -->
+    <territory id="BD" countryCode="880" internationalPrefix="00[12]?"
+               preferredInternationalPrefix="00"
+               nationalPrefix="0" nationalPrefixFormattingRule="$NP$FG">
+      <availableFormats>
+        <numberFormat leadingDigits="2" pattern="(2)(\d{7})">$1 $2</numberFormat>
+        <numberFormat leadingDigits="[3-79]1" pattern="(\d{2})(\d{4,6})">$1 $2</numberFormat>
+        <numberFormat leadingDigits="[3-79][2-9]|8" pattern="(\d{3})(\d{3,7})">$1 $2</numberFormat>
+        <numberFormat leadingDigits="1" pattern="(\d{4})(\d{6})">$1 $2</numberFormat>
+      </availableFormats>
+      <generalDesc>
+      <!-- This is quite complex so we can define that numbers beginning with
+             88 are not part of the plan, so the country code can be accurately stripped
+             off. -->
+        <nationalNumberPattern>[2-79]\d{5,9}|1\d{9}|8[0-7]\d{4,8}</nationalNumberPattern>
+        <possibleNumberPattern>\d{6,10}</possibleNumberPattern>
+      </generalDesc>
+      <fixedLine>
+        <!-- There was a plan to move to 10 digit fixed-line numbers, but this does not seem to
+             have been realised, judging by online numbers and wikipedia. These
+             patterns are grouped first by leading digit, then within by number
+             of digits. Several Dhaka prefixes (02 731, 751 etc) are included
+             despite not being mentioned on the wikipedia page due to online
+             evidence. Another oddity is Chittagong - some numbers have a
+             leading 2, others do not - both are allowed for now. -->
+             <nationalNumberPattern>2(?:7\d1|8(?:[026]1|[1379][1-5]|8[1-8])|9(?:0[0-2]|1[1-4]|3[3-5]|5[56]|6[67]|71|8[078]))\d{4}|3(?:[6-8]1|(?:0[23]|[25][12]|82|416)\d|(?:31|12?[5-7])\d{2})\d{3}|4(?:(?:02|[49]6|[68]1)|(?:0[13]|21\d?|[23]2|[457][12]|6[28])\d|(?:23|[39]1)\d{2}|1\d{3})\d{3}|5(?:(?:[457-9]1|62)|(?:1\d?|2[12]|3[1-3]|52)\d|61{2})|6(?:[45]1|(?:11|2[15]|[39]1)\d|(?:[06-8]1|62)\d{2})|7(?:(?:32|91)|(?:02|31|[67][12])\d|[458]1\d{2}|21\d{3})\d{3}|8(?:(?:4[12]|[5-7]2|1\d?)|(?:0|3[12]|[5-7]1|217)\d)\d{4}|9(?:[35]1|(?:[024]2|81)\d|(?:1|[24]1)\d{2})\d{3}</nationalNumberPattern>
+        <possibleNumberPattern>\d{6,9}</possibleNumberPattern>
+        <exampleNumber>27111234</exampleNumber>
+      </fixedLine>
+      <mobile>
+        <!-- Presuming that mobile numbers with the prefixes 66, 37, 44 and 38 must be followed by
+             numbers [02-9] or they would clash with fixed-line codes. According
+             to the plan, mobile numbers should be moving to 1[13-9] anyway. -->
+        <nationalNumberPattern>(?:1[13-9]\d|(?:3[78]|44)[02-9]|6(?:44|6[02-9]))\d{7}</nationalNumberPattern>
+        <possibleNumberPattern>\d{10}</possibleNumberPattern>
+        <exampleNumber>1812345678</exampleNumber>
+      </mobile>
+      <tollFree>
+        <!-- Note: Including Tele-voting numbers here as they are free of charge. -->
+        <nationalNumberPattern>80[03]\d{7}</nationalNumberPattern>
+        <possibleNumberPattern>\d{10}</possibleNumberPattern>
+        <exampleNumber>8001234567</exampleNumber>
+      </tollFree>
     </territory>
 
     <!-- Belgium -->
@@ -711,7 +799,7 @@
       <mobile>
         <!-- Adding 75 for Zain, Burkina Faso. This is actually used in the
         help-line number for them. -->
-        <nationalNumberPattern>7(?:[01568]\d|2[0-4]|4[01]|5[01346-9])\d{5}</nationalNumberPattern>
+        <nationalNumberPattern>7(?:[04-6]\d|1[0-489]|2[0-8]|8[013-9]|90)\d{5}</nationalNumberPattern>
         <exampleNumber>70123456</exampleNumber>
       </mobile>
     </territory>
@@ -830,13 +918,36 @@
       </voip>
     </territory>
 
-    <!-- French Dept. of Guadeloupe -->
-    <territory id="BL" countryCode="590" internationalPrefix="00">
+    <!-- Saint Barthélemy, French Antilles -->
+    <!-- There seems to be some overlap with phone numbers from Saint Martin and
+    Guadeloupe. The national numbering plan does not specify any St
+    Barthélemy-specific numbering prefixes, but it appears from searches in
+    online white and yellow pages that a subset of the prefixes available in
+    Guadeloupe are used. In these cases, if getRegionCodeForNumber is used, one
+    of these region codes will be returned, although numbers will be valid for
+    both regions. -->
+    <!-- http://www.itu.int/oth/T0202000058/en -->
+    <territory id="BL" countryCode="590" internationalPrefix="00"
+      nationalPrefix="0">
+      <!-- Formatting rules borrowed from Guadeloupe. -->
+      <generalDesc>
+        <nationalNumberPattern>[56]\d{8}</nationalNumberPattern>
+        <possibleNumberPattern>\d{9}</possibleNumberPattern>
+      </generalDesc>
+      <fixedLine>
+        <nationalNumberPattern>590(?:2[7-9]|5[12]|87)\d{4}</nationalNumberPattern>
+        <exampleNumber>590271234</exampleNumber>
+      </fixedLine>
+      <mobile>
+        <nationalNumberPattern>690(?:10|2[27]|66|77|8[78])\d{4}</nationalNumberPattern>
+        <exampleNumber>690221234</exampleNumber>
+      </mobile>
     </territory>
 
     <!-- Bermuda -->
     <!-- http://www.itu.int/oth/T0202000018/en -->
-    <territory id="BM" countryCode="1" internationalPrefix="011">
+    <territory id="BM" countryCode="1" leadingDigits="441"
+      internationalPrefix="011">
       <generalDesc>
         <!-- NANPA country - uses US formatting rules -->
         <nationalNumberPattern>[489]\d{9}</nationalNumberPattern>
@@ -904,7 +1015,9 @@
       code.-->
       <availableFormats>
         <numberFormat leadingDigits="[1-9][1-9]"
-                      pattern="(\d{2})(\d{4})(\d{4})">($1) $2-$3</numberFormat>
+                      pattern="(\d{2})(\d{4})(\d{4})"
+                      nationalPrefixFormattingRule="($FG)"
+                      carrierCodeFormattingRule="$NP $CC $FG">$1 $2-$3</numberFormat>
         <numberFormat leadingDigits="400|3003" pattern="([34]00\d)(\d{4})">$1-$2</numberFormat>
         <numberFormat leadingDigits="[3589]00" nationalPrefixFormattingRule="$NP$FG"
                       pattern="([3589]00)(\d{2,3})(\d{4})">$1 $2 $3</numberFormat>
@@ -938,7 +1051,8 @@
 
     <!-- Bahamas -->
     <!-- http://www.itu.int/dms_pub/itu-t/oth/02/02/T02020000100001MSWE.pdf -->
-    <territory id="BS" countryCode="1" internationalPrefix="011">
+    <territory id="BS" countryCode="1" leadingDigits="242"
+      internationalPrefix="011">
       <generalDesc>
         <!-- NANPA country - uses US formatting rules -->
         <nationalNumberPattern>[289]\d{9}</nationalNumberPattern>
@@ -1029,8 +1143,46 @@
     </territory>
 
     <!-- Belarus -->
+    <!-- http://eng.beltelecom.by/info/numbering/ -->
+    <!-- Information on national prefix provided by mahaniok -->
     <territory id="BY" countryCode="375" internationalPrefix="8~10"
-               nationalPrefix="8">
+               nationalPrefixForParsing="80?" nationalPrefix="8">
+      <availableFormats>
+        <numberFormat leadingDigits="[1-4]"
+          nationalPrefixFormattingRule="$NP 0$FG"
+          pattern="([1-4]\d)(\d{3})(\d{4})">$1 $2 $3</numberFormat>
+        <numberFormat leadingDigits="[89]"
+          nationalPrefixFormattingRule="$NP $FG"
+          pattern="([89]\d{2})(\d{3})(\d{4})">$1 $2 $3</numberFormat>
+      </availableFormats>
+      <generalDesc>
+        <nationalNumberPattern>[12-4]\d{8}|[89]\d{9}</nationalNumberPattern>
+        <!-- Numbers are often written without the city code. -->
+        <possibleNumberPattern>\d{7,10}</possibleNumberPattern>
+      </generalDesc>
+      <fixedLine>
+        <nationalNumberPattern>(?:1(?:5(?:1[1-5]|2\d|6[1-4]|9[1-7])|6(?:[235]\d|4[1-7])|7\d{2})|2(?:1(?:[246]\d|3[0-35-9]|5[1-9])|2(?:[235]\d|4[0-8])|3(?:2\d|3[02-79]|4[024-7]|5[0-7])))\d{5}</nationalNumberPattern>
+        <possibleNumberPattern>\d{7,9}</possibleNumberPattern>
+        <!-- Using test number for Grodno from the plan. -->
+        <exampleNumber>152450911</exampleNumber>
+      </fixedLine>
+      <mobile>
+        <nationalNumberPattern>(?:2(?:5[679]|9[1-9])|33\d|44\d)\d{6}</nationalNumberPattern>
+        <possibleNumberPattern>\d{9}</possibleNumberPattern>
+        <!-- Using test number for BelCel from the plan. -->
+        <exampleNumber>294911911</exampleNumber>
+      </mobile>
+      <tollFree>
+        <!-- Putting Interactive Polling Service (free) here too. -->
+        <nationalNumberPattern>80[13]\d{7}</nationalNumberPattern>
+        <possibleNumberPattern>\d{10}</possibleNumberPattern>
+        <exampleNumber>8011234567</exampleNumber>
+      </tollFree>
+      <premiumRate>
+        <nationalNumberPattern>902\d{7}</nationalNumberPattern>
+        <possibleNumberPattern>\d{10}</possibleNumberPattern>
+        <exampleNumber>9021234567</exampleNumber>
+      </premiumRate>
     </territory>
 
     <!-- Belize -->
@@ -1377,7 +1529,23 @@
     </territory>
 
     <!-- Costa Rica -->
+    <!-- http://www.itu.int/oth/T0202000030/en -->
     <territory id="CR" countryCode="506" internationalPrefix="00">
+      <availableFormats>
+        <numberFormat pattern="([28]\d{3})(\d{4})">$1 $2</numberFormat>
+      </availableFormats>
+      <generalDesc>
+        <nationalNumberPattern>[28]\d{7}</nationalNumberPattern>
+        <possibleNumberPattern>\d{8}</possibleNumberPattern>
+      </generalDesc>
+      <fixedLine>
+        <nationalNumberPattern>2[24-7]\d{6}</nationalNumberPattern>
+        <exampleNumber>22123456</exampleNumber>
+      </fixedLine>
+      <mobile>
+        <nationalNumberPattern>8[38]\d{6}</nationalNumberPattern>
+        <exampleNumber>83123456</exampleNumber>
+      </mobile>
     </territory>
 
     <!-- Cuba -->
@@ -1503,8 +1671,9 @@
         <numberFormat leadingDigits="1[5-7]" pattern="(1[5-7]\d)(\d{7,8})">$1 $2</numberFormat>
         <numberFormat leadingDigits="180" pattern="(180)(\d)(\d{4,10})">$1 $2 $3</numberFormat>
         <numberFormat leadingDigits="700" pattern="(700)(\d{4})(\d{4})">$1 $2 $3</numberFormat>
-        <numberFormat leadingDigits="800|900[135]"
-                      pattern="([89]00)(\d)(\d{6})">$1 $2 $3</numberFormat>
+        <numberFormat leadingDigits="800" pattern="(800)(\d{7,9})">$1 $2</numberFormat>
+        <numberFormat leadingDigits="900[135]"
+                      pattern="(900)(\d)(\d{6})">$1 $2 $3</numberFormat>
         <numberFormat leadingDigits="9009" pattern="(900)(9)(\d{7})">$1 $2 $3</numberFormat>
       </availableFormats>
       <generalDesc>
@@ -1529,8 +1698,8 @@
         <exampleNumber>15123456789</exampleNumber>
       </mobile>
       <tollFree>
-        <nationalNumberPattern>800\d{7}</nationalNumberPattern>
-        <possibleNumberPattern>\d{10}</possibleNumberPattern>
+        <nationalNumberPattern>800\d{7,9}</nationalNumberPattern>
+        <possibleNumberPattern>\d{10,12}</possibleNumberPattern>
         <exampleNumber>8001234567</exampleNumber>
       </tollFree>
       <premiumRate>
@@ -1609,7 +1778,8 @@
 
     <!-- Dominica -->
     <!-- http://www.itu.int/oth/T020200003B/en -->
-    <territory id="DM" countryCode="1" internationalPrefix="011">
+    <territory id="DM" countryCode="1" leadingDigits="767"
+      internationalPrefix="011">
       <generalDesc>
         <!-- NANPA country - uses US formatting rules -->
         <nationalNumberPattern>[7-9]\d{9}</nationalNumberPattern>
@@ -1637,18 +1807,24 @@
     </territory>
 
     <!-- Dominican Rep. -->
-    <territory id="DO" countryCode="1" internationalPrefix="011">
+    <!-- http://www.itu.int/oth/T020200003C/en -->
+    <territory id="DO" countryCode="1" leadingDigits="8[024]9"
+      internationalPrefix="011">
       <generalDesc>
         <!-- NANPA country - uses US formatting rules -->
         <nationalNumberPattern>[89]\d{9}</nationalNumberPattern>
         <possibleNumberPattern>\d{7,10}</possibleNumberPattern>
       </generalDesc>
       <fixedLine>
-        <nationalNumberPattern>8[02]9[2-9]\d{6}</nationalNumberPattern>
+        <!-- We could be more detailed here, as the metadata contains
+        information about some of the mobile/fixed-line prefixes, but the data
+        is incomplete, so we restrict ourselves to a more generic rule for
+        now.-->
+        <nationalNumberPattern>8[024]9[2-9]\d{6}</nationalNumberPattern>
         <exampleNumber>8092345678</exampleNumber>
       </fixedLine>
       <mobile>
-        <nationalNumberPattern>8[02]9[2-9]\d{6}</nationalNumberPattern>
+        <nationalNumberPattern>8[024]9[2-9]\d{6}</nationalNumberPattern>
         <exampleNumber>8092345678</exampleNumber>
       </mobile>
       <tollFree>
@@ -1771,6 +1947,9 @@
     <territory id="EG" countryCode="20" internationalPrefix="00"
                nationalPrefix="0" nationalPrefixFormattingRule="$NP$FG">
        <availableFormats>
+         <!-- Note that no explicit formatting rule is here for 5-digit numbers
+         starting with a 16 or 19. These are formatted without national prefix,
+         as a block, so do not need to be listed here. -->
          <numberFormat leadingDigits="2" pattern="(2)(\d{8})">$1 $2</numberFormat>
          <numberFormat leadingDigits="3" pattern="(3)(\d{7})">$1 $2</numberFormat>
          <numberFormat leadingDigits="[14-6]|[89][2-9]"
@@ -1779,12 +1958,14 @@
                        pattern="([89]00)(\d{3})(\d{4})">$1 $2 $3</numberFormat>
        </availableFormats>
       <generalDesc>
-        <nationalNumberPattern>[1-689]\d{7,9}</nationalNumberPattern>
-        <possibleNumberPattern>\d{7,10}</possibleNumberPattern>
+        <nationalNumberPattern>1\d{4,9}|[2-689]\d{7,9}</nationalNumberPattern>
+        <possibleNumberPattern>\d{5,10}</possibleNumberPattern>
       </generalDesc>
       <fixedLine>
-        <nationalNumberPattern>(?:1[35][23]|2[23]\d|3\d|4(?:0[2-4]|[578][23]|64)|5(?:0[234]|[57][23])|6[24-689]3|8(?:[28][2-4]|42|6[23])|9(?:[25]2|3[24]|6[23]|7[2-4]))\d{6}</nationalNumberPattern>
-        <possibleNumberPattern>\d{7,9}</possibleNumberPattern>
+        <!-- Short numbers used for businesses (starting with 16 or 19) are
+        covered here. -->
+        <nationalNumberPattern>(?:1[35][23]|2[23]\d|3\d|4(?:0[2-4]|[578][23]|64)|5(?:0[234]|[57][23])|6[24-689]3|8(?:[28][2-4]|42|6[23])|9(?:[25]2|3[24]|6[23]|7[2-4]))\d{6}|1[69]\d{3}</nationalNumberPattern>
+        <possibleNumberPattern>\d{5,9}</possibleNumberPattern>
         <exampleNumber>234567890</exampleNumber>
       </fixedLine>
       <mobile>
@@ -1950,13 +2131,13 @@
     <territory id="FR" countryCode="33" internationalPrefix="[04579]0"
                nationalPrefix="0" nationalPrefixFormattingRule="$NP$FG">
       <availableFormats>
-        <numberFormat leadingDigits="[1-69]"
-                      pattern="([1-69])(\d{2})(\d{2})(\d{2})(\d{2})">$1 $2 $3 $4 $5</numberFormat>
+        <numberFormat leadingDigits="[1-79]"
+                      pattern="([1-79])(\d{2})(\d{2})(\d{2})(\d{2})">$1 $2 $3 $4 $5</numberFormat>
         <numberFormat leadingDigits="8" nationalPrefixFormattingRule="$NP $FG"
                       pattern="(8\d{2})(\d{2})(\d{2})(\d{2})">$1 $2 $3 $4</numberFormat>
       </availableFormats>
       <generalDesc>
-        <nationalNumberPattern>[1-689]\d{8}</nationalNumberPattern>
+        <nationalNumberPattern>[1-9]\d{8}</nationalNumberPattern>
         <possibleNumberPattern>\d{9}</possibleNumberPattern>
       </generalDesc>
       <fixedLine>
@@ -2018,7 +2199,8 @@
     <!-- Note that this excludes Isle of Man, Jersey and Guernsey prefixes for
     the purposes of validation, although the formatting rules are shared. -->
     <territory id="GB" countryCode="44" internationalPrefix="00"
-               nationalPrefix="0" preferredExtnPrefix=" x" nationalPrefixFormattingRule="$NP$FG">
+               nationalPrefix="0" preferredExtnPrefix=" x" nationalPrefixFormattingRule="$NP$FG"
+               mainCountryForCode="true" >
       <availableFormats>
         <numberFormat leadingDigits="[23]|55"
                       pattern="([235]\d)(\d{4})(\d{4})">$1 $2 $3</numberFormat>
@@ -2096,7 +2278,8 @@
 
     <!-- Grenada -->
     <!-- http://www.itu.int/oth/T0202000057/en -->
-    <territory id="GD" countryCode="1" internationalPrefix="011">
+    <territory id="GD" countryCode="1" leadingDigits="473"
+      internationalPrefix="011">
       <generalDesc>
         <!-- NANPA country - uses US formatting rules -->
         <nationalNumberPattern>[489]\d{9}</nationalNumberPattern>
@@ -2302,29 +2485,61 @@
     </territory>
 
     <!-- Guadeloupe -->
-    <territory id="GP" countryCode="590" internationalPrefix="00">
+    <!-- http://www.itu.int/oth/T0202000058/en -->
+    <territory id="GP" countryCode="590" internationalPrefix="00"
+               mainCountryForCode="true" nationalPrefix="0"
+               nationalPrefixFormattingRule="$NP$FG">
+      <availableFormats>
+        <numberFormat pattern="([56]90)(\d{2})(\d{4})">$1 $2-$3</numberFormat>
+      </availableFormats>
+      <generalDesc>
+        <nationalNumberPattern>[56]\d{8}</nationalNumberPattern>
+        <possibleNumberPattern>\d{9}</possibleNumberPattern>
+      </generalDesc>
+      <fixedLine>
+        <!-- The plan says 59011 and 59012 are not implemented yet, but is from
+        2006 and online examples can be found. -->
+        <nationalNumberPattern>590(?:1[12]|2[0-68]|3[28]|4[126-8]|5[067]|6[018]|[89]\d)\d{4}</nationalNumberPattern>
+        <exampleNumber>590201234</exampleNumber>
+      </fixedLine>
+      <mobile>
+        <nationalNumberPattern>690(?:00|[3-5]\d|6[0-57-9]|7[1-6]|8[0-6]|9[09])\d{4}</nationalNumberPattern>
+        <exampleNumber>690301234</exampleNumber>
+      </mobile>
     </territory>
 
     <!-- Equatorial Guinea -->
     <!-- http://www.itu.int/oth/T0202000041/en -->
     <territory id="GQ" countryCode="240" internationalPrefix="00">
       <availableFormats>
-        <!-- Follows yellow page format from
-             http://malabophonebook.com/en/area/bata/ -->
-        <numberFormat pattern="(\d{2})(\d{2})(\d{2})">$1 $2 $3</numberFormat>
+        <numberFormat leadingDigits="[235]" pattern="(\d{2})(\d{3})(\d{4})">$1 $2 $3</numberFormat>
+        <numberFormat leadingDigits="[899]" pattern="(\d{3})(\d{6})">$1 $2</numberFormat>
       </availableFormats>
       <generalDesc>
-        <nationalNumberPattern>[0256]\d{5}</nationalNumberPattern>
-        <possibleNumberPattern>\d{6}</possibleNumberPattern>
+        <nationalNumberPattern>[23589]\d{8}</nationalNumberPattern>
+        <!-- The 6 here refers to the old number pattern - numbers written down
+        may still be this length although they can no longer be dialled. -->
+        <possibleNumberPattern>\d{6,9}</possibleNumberPattern>
       </generalDesc>
       <fixedLine>
-        <nationalNumberPattern>0[46-9]\d{4}</nationalNumberPattern>
-        <exampleNumber>041234</exampleNumber>
+        <nationalNumberPattern>3(?:3(?:3\d[7-9]|[0-24-9]\d[46])|5\d{2}[7-9])\d{4}</nationalNumberPattern>
+        <exampleNumber>333091234</exampleNumber>
       </fixedLine>
       <mobile>
-        <nationalNumberPattern>[256]\d{5}</nationalNumberPattern>
-        <exampleNumber>212345</exampleNumber>
+        <nationalNumberPattern>(?:222|551)\d{6}</nationalNumberPattern>
+        <exampleNumber>222123456</exampleNumber>
       </mobile>
+      <!-- Note that personal and sharedCost numbers are said to go under here
+      too - hopefully when they start allocating them there will be a
+      differentiation of prefixes, but this is not clear now. -->
+      <tollFree>
+        <nationalNumberPattern>80\d[1-9]\d{5}</nationalNumberPattern>
+        <exampleNumber>800123456</exampleNumber>
+      </tollFree>
+      <premiumRate>
+        <nationalNumberPattern>90\d[1-9]\d{5}</nationalNumberPattern>
+        <exampleNumber>900123456</exampleNumber>
+      </premiumRate>
     </territory>
 
     <!-- Greece -->
@@ -2377,7 +2592,8 @@
 
     <!-- Guam -->
     <!-- http://en.wikipedia.org/wiki/%2B1_671 -->
-    <territory id="GU" countryCode="1" internationalPrefix="011">
+    <territory id="GU" countryCode="1" leadingDigits="671"
+      internationalPrefix="011">
       <generalDesc>
         <!-- NANPA country - uses US formatting rules -->
         <nationalNumberPattern>[689]\d{9}</nationalNumberPattern>
@@ -2476,6 +2692,7 @@
 
     <!-- Croatia -->
     <!-- http://www.itu.int/oth/T0202000032/en -->
+    <!-- http://en.wikipedia.org/wiki/%2B385 -->
     <territory id="HR" countryCode="385" internationalPrefix="00"
                nationalPrefix="0" nationalPrefixFormattingRule="$NP$FG">
       <availableFormats>
@@ -2483,25 +2700,26 @@
              websites are formatted 1 XXXX XXX, so we prefer that formatting
              here. These same sources prefer XXX XXX to XX XXXX as well. -->
         <numberFormat leadingDigits="1" pattern="(1)(\d{4})(\d{3})">$1 $2 $3</numberFormat>
-        <numberFormat leadingDigits="62" pattern="(62)(\d{4})(\d{3})">$1 $2 $3</numberFormat>
+        <numberFormat leadingDigits="6[029]" pattern="(6[029])(\d{4})(\d{3})">$1 $2 $3</numberFormat>
         <numberFormat leadingDigits="[2-5]"
                       pattern="([2-5]\d)(\d{3})(\d{3})">$1 $2 $3</numberFormat>
         <numberFormat leadingDigits="9"
                       pattern="(9[12589])(\d{3,4})(\d{3,4})">$1 $2 $3</numberFormat>
         <numberFormat leadingDigits="9"
                       pattern="(9[12589])(\d{3,4})(\d{3})(\d{3})">$1 $2 $3 $4</numberFormat>
-        <numberFormat leadingDigits="60" pattern="(60)(\d{4})(\d{3})">$1 $2 $3</numberFormat>
-        <numberFormat leadingDigits="61" pattern="(61)(\d{4})">$1 $2</numberFormat>
-        <numberFormat leadingDigits="8" pattern="(800)(\d{2})(\d{2,3})">$1 $2 $3</numberFormat>
-        <numberFormat leadingDigits="8" pattern="(800)(\d{3,4})(\d{3})">$1 $2 $3</numberFormat>
+        <numberFormat leadingDigits="6[145]|7" pattern="(\d{2})(\d{2})(\d{2,3})">$1 $2 $3</numberFormat>
+        <numberFormat leadingDigits="6[145]|7" pattern="(\d{2})(\d{3,4})(\d{3})">$1 $2 $3</numberFormat>
+        <numberFormat leadingDigits="8" pattern="(80[01])(\d{2})(\d{2,3})">$1 $2 $3</numberFormat>
+        <numberFormat leadingDigits="8" pattern="(80[01])(\d{3,4})(\d{3})">$1 $2 $3</numberFormat>
       </availableFormats>
       <generalDesc>
         <nationalNumberPattern>[1-7]\d{5,8}|[89]\d{6,11}</nationalNumberPattern>
         <possibleNumberPattern>\d{6,12}</possibleNumberPattern>
       </generalDesc>
       <fixedLine>
-        <!-- Supporting 062 (universal access) numbers here too. -->
-        <nationalNumberPattern>(?:1|62)\d{7}|(?:2[0-3]|3[1-5]|4[02-47-9]|5[1-3])\d{6}</nationalNumberPattern>
+        <!-- Supporting 060 (general service), 062 (universal access), 069 (children service)
+             numbers here too. -->
+        <nationalNumberPattern>(?:1|6[029])\d{7}|(?:2[0-3]|3[1-5]|4[02-47-9]|5[1-3])\d{6}</nationalNumberPattern>
         <possibleNumberPattern>\d{6,9}</possibleNumberPattern>
         <exampleNumber>12345678</exampleNumber>
       </fixedLine>
@@ -2511,19 +2729,22 @@
         <exampleNumber>912345678</exampleNumber>
       </mobile>
       <tollFree>
-        <!-- The plan says it shall be 0800 followed by 7 digits, but online
-             examples vary between 4 and 7.-->
-        <nationalNumberPattern>800\d{4,7}</nationalNumberPattern>
+        <nationalNumberPattern>80[01]\d{4,7}</nationalNumberPattern>
         <possibleNumberPattern>\d{7,10}</possibleNumberPattern>
         <exampleNumber>8001234567</exampleNumber>
       </tollFree>
       <premiumRate>
         <!-- 061 is for TeleVoting numbers - but these are charged at similar
-             rates to premium rate so we include them here.-->
-        <nationalNumberPattern>6(?:0\d{3}|1)\d{4}</nationalNumberPattern>
+             rates to premium rate so we include them here. -->
+        <nationalNumberPattern>6[145]\d{4,7}</nationalNumberPattern>
         <possibleNumberPattern>\d{6,9}</possibleNumberPattern>
-        <exampleNumber>601234567</exampleNumber>
+        <exampleNumber>611234</exampleNumber>
       </premiumRate>
+      <personalNumber>
+        <nationalNumberPattern>7[45]\d{4,7}</nationalNumberPattern>
+        <possibleNumberPattern>\d{6,9}</possibleNumberPattern>
+        <exampleNumber>741234567</exampleNumber>
+      </personalNumber>
     </territory>
 
     <!-- Haiti -->
@@ -3080,7 +3301,8 @@
 
     <!-- Jamaica -->
     <!-- http://www.itu.int/oth/T020200006C/en -->
-    <territory id="JM" countryCode="1" internationalPrefix="011">
+    <territory id="JM" countryCode="1" leadingDigits="876"
+      internationalPrefix="011">
       <generalDesc>
         <!-- NANPA country - uses US formatting rules -->
         <nationalNumberPattern>[89]\d{9}</nationalNumberPattern>
@@ -3162,36 +3384,56 @@
     </territory>
 
     <!-- Japan -->
-    <!-- http://www.itu.int/dms_pub/itu-t/oth/02/02/T020200006D0001MSWE.doc -->
-    <!-- http://en.wikipedia.org/wiki/Telephone_numbers_in_Japan -->
-    <!-- http://www.japanvisitor.com/index.php?cID=374&pID=754&pName=travel-dialing-codes -->
+    <!-- http://www.soumu.go.jp/main_sosiki/joho_tsusin/top/tel_number/fixed.html -->
     <territory id="JP" countryCode="81" internationalPrefix="010"
                nationalPrefix="0" nationalPrefixFormattingRule="$NP$FG">
       <availableFormats>
-        <numberFormat leadingDigits="[36][1-9]"
-                      pattern="(\d)(\d{4})(\d{4})">$1 $2 $3</numberFormat>
-        <numberFormat leadingDigits="[57-9]0"
-                      pattern="(\d{2})(\d{4})(\d{4})">$1 $2 $3</numberFormat>
-        <!-- 4 digit area code -->
-        <numberFormat leadingDigits="124|4992"
-                      pattern="(\d{4})(\d)(\d{4})">$1 $2 $3</numberFormat>
-        <!-- 3 digit area codes that clash with the prefixes of 2 digit area
-        codes and hence are tested for first-->
-        <numberFormat
-            leadingDigits="1(?:38|66)|5(?:32|6[458]|86)|7(?:42|76|98)|852|9(?:42|5[26]|85)"
-            pattern="(\d{3})(\d{2})(\d{4})">$1 $2 $3</numberFormat>
-        <!-- 2 digit area codes -->
-        <numberFormat leadingDigits="(?:1[17-9]|[24][2-9]|5[2-589]|60|[79][235-9]|8[26-8])[1-9]"
-                      pattern="(\d{2})(\d{3})(\d{4})">$1 $2 $3</numberFormat>
+        <!-- Toll-free numbers -->
         <numberFormat leadingDigits="(?:12|99)0"
                       pattern="(\d{3})(\d{3})(\d{3})">$1 $2 $3</numberFormat>
+        <!-- Some leading digits are explicitly reserved for a particular purpose.
+             We handle them first in this rule, and let the following rules ignore those exceptions.
+             Note: The rule here is not in the files we rely on when creating the other rules.
+                   We would need to manually modify it if the Japanese goverment
+                   decided to change the rule.
+
+             (prefix): purpose
+             "50": IP phone
+             "90" and "80": Mobile phone
+             "70": PHS (Personal Handy-phone System, which has been used in Japan
+                   with Non-3G, Japanese-specific protocol).
+                   See also http://ja.wikipedia.org/wiki/PHS (Japanese)
+          -->
+        <numberFormat leadingDigits="[57-9]0"
+                      pattern="(\d{2})(\d{4})(\d{4})">$1 $2 $3</numberFormat>
+        <!-- The order of the reg-exps are important.
+             Examples (not all):
+             - "15": 15420 -> 154-20, 15472 -> 1547-2, 15410 -> 15-410,
+             - "22": 22200 -> 22-200, 22300 -> 22-300, 22320 -> 223-20, 22350 -> 22-350
+             - "42": 42000 -> 4-2000, 42901 -> 4-2901, 42910 -> 42-910
+             - "82": 82200 -> 82-200, 82020 -> 820-20, 82400 -> 82-400
+             - "99": 99400 -> 99-400, 99430 -> 994-30, 99692 -> 9969-2, 99750 -> 997-50
+             - "993": 99330 -> 993-30, 99331 -> 99-331, 99332 -> 993-32
+          -->
+        <numberFormat leadingDigits="1(?:267|3(?:7[247]|9[278])|4(?:5[67]|66)|5(?:47|58|64|8[67])|6(?:3[245]|48|5[4-68]))|5(?:769|979[2-69])|499[2468]|7468|8(?:3(?:8[78]|96[2457-9])|636[2-57-9]|477|51[24])|9(?:496|802|91[23]|969)"
+                      pattern="(\d{4})(\d)(\d{4})">$1 $2 $3</numberFormat>
+        <numberFormat leadingDigits="1(?:2[3-6]|3[3-9]|4[2-6]|5(?:[236-8]|[45][2-69])|6[2-7]|7[2-689]|8[2-7]|9[1-578])|2(?:2[04-9]|3[3-58]|4[0-468]|6[0135-8]|7[0679]|8[024578]|23[23]|5(?:5[78]|7[2-4]|[0468][2-9])|6(?:17|4[2-5])|78[2-7]|8(?:3[25-9]|9[6-9])|9(?:11|3[2-4]))|4(?:2(?:2[2-9]|8[237-9])|7[059][2-8]|3[689]|6[035-7]|7[68]|80|9[3-5])|5(?:3[1-36-9]|9(?:7[49]|[89][2-8])|4[4578]|5[013-8]|6[1-9]|7[2-8]|8[14-7]|9[4-7])|7(?:2[15]|3[5-9]|4[02-9]|6[135-8]|7[0-4689]|9[017-9]|618|797|9(?:4[6-8]|5[2-478]|6[2-589]))|8(?:29(?:20|4[04-9]|65[25]|[36]60)|376[0-59]|6(?:366|55[014-9]|69[02-69]|99[23])|24[4-8]|29[3578]|3(?:[3-6][2-9]|[78][2-5])|6(?:5[467]|9[236-8]|[68][2-8])|4[5-8]|5[2-9]|6[37]|7[579]|8[03-579]|9[2-8])|9(?:[23]0|4[0246-9]|5[025-79]|6[4-9]|7[27-9]|8[02-7]|[47]3|[57]4|9(?:4[2-69]|3(?:3[02-9]|4[0-24689])|[5-7]))"
+                      pattern="(\d{3})(\d{2})(\d{4})">$1 $2 $3</numberFormat>
+        <numberFormat leadingDigits="1|2(?:23|5(?:[57]|[68]0|917|999)|64|78|8[39]|917)|4(?:2(?:[68]|20|9[178])|64|7[347])|5(?:[2-589]|39[67])|8(?:[46-9]|3[279]|2(?:[124589]|9[24])|3[79]6|6(?:69|99))|9(?:[235-8]|9331|934)|15[45]"
+                      pattern="(\d{2})(\d{3})(\d{4})">$1 $2 $3</numberFormat>
+        <numberFormat leadingDigits="2(?:9[14-79]|74|[34]7|[56]9)|82|993"
+                      pattern="(\d{3})(\d{2})(\d{4})">$1 $2 $3</numberFormat>
+        <numberFormat leadingDigits="[36]|4(?:2[09]|7[01])"
+                      pattern="(\d)(\d{4})(\d{4})">$1 $2 $3</numberFormat>
+        <numberFormat leadingDigits="[2479]"
+                      pattern="(\d{2})(\d{3})(\d{4})">$1 $2 $3</numberFormat>
       </availableFormats>
       <generalDesc>
         <nationalNumberPattern>\d{9,10}</nationalNumberPattern>
         <possibleNumberPattern>\d{9,10}</possibleNumberPattern>
       </generalDesc>
       <fixedLine>
-        <nationalNumberPattern>(?:(?:1[1-9]|9[2-9])[1-9]|(?:[36][1-9]|[24578][2-9])\d)\d{6}</nationalNumberPattern>
+        <nationalNumberPattern>(?:1[1-9][1-9]|9(?:[3-9][1-9]|2\d)|(?:[36][1-9]|[24578][2-9])\d)\d{6}</nationalNumberPattern>
         <possibleNumberPattern>\d{9}</possibleNumberPattern>
         <exampleNumber>312345678</exampleNumber>
       </fixedLine>
@@ -3365,7 +3607,8 @@
 
     <!-- Saint Kitts and Nevis -->
     <!-- http://www.itu.int/oth/T02020000B0/en -->
-    <territory id="KN" countryCode="1" internationalPrefix="011">
+    <territory id="KN" countryCode="1" leadingDigits="869"
+      internationalPrefix="011">
       <generalDesc>
         <!-- NANPA country - uses US formatting rules -->
         <nationalNumberPattern>[89]\d{9}</nationalNumberPattern>
@@ -3503,7 +3746,8 @@
 
     <!-- Cayman Islands -->
     <!-- http://www.itu.int/oth/T0202000027/en -->
-    <territory id="KY" countryCode="1" internationalPrefix="011">
+    <territory id="KY" countryCode="1" leadingDigits="345"
+      internationalPrefix="011">
       <generalDesc>
         <!-- NANPA country - uses US formatting rules -->
         <nationalNumberPattern>[389]\d{9}</nationalNumberPattern>
@@ -3534,10 +3778,7 @@
     <!-- http://en.wikipedia.org/wiki/Telephone_numbers_in_Kazakhstan -->
     <territory id="KZ" countryCode="7" internationalPrefix="8~10"
                nationalPrefix="8" nationalPrefixFormattingRule="$NP$FG">
-        <availableFormats>
-          <numberFormat leadingDigits="[6-8]"
-                        pattern="([6-8]\d{2})(\d{3})(\d{4})">$1 $2 $3</numberFormat>
-        </availableFormats>
+       <!-- Formatting rules obtained from Russia. -->
       <generalDesc>
         <nationalNumberPattern>(?:[67]\d{2}|80[09])\d{7}</nationalNumberPattern>
         <possibleNumberPattern>\d{10}</possibleNumberPattern>
@@ -3634,7 +3875,8 @@
 
     <!-- Saint Lucia -->
     <!-- http://www.itu.int/oth/T02020000B1/en -->
-    <territory id="LC" countryCode="1" internationalPrefix="011">
+    <territory id="LC" countryCode="1" leadingDigits="758"
+      internationalPrefix="011">
       <generalDesc>
         <!-- NANPA country - uses US formatting rules -->
         <nationalNumberPattern>[789]\d{9}</nationalNumberPattern>
@@ -3845,7 +4087,41 @@
     </territory>
 
     <!-- Morocco -->
-    <territory id="MA" countryCode="212" internationalPrefix="00">
+    <!-- http://www.itu.int/oth/T0202000090/en -->
+    <!-- http://en.wikipedia.org/wiki/+212 -->
+    <territory id="MA" countryCode="212" internationalPrefix="00"
+      nationalPrefix="0" nationalPrefixFormattingRule="$NP$FG">
+      <availableFormats>
+        <numberFormat leadingDigits="5(?:2[015-7]|3[0-4])|6"
+          pattern="([56]\d{2})(\d{6})">$1-$2</numberFormat>
+        <numberFormat leadingDigits="5(?:2(?:[2-48]|90)|3(?:[5-79]|80))|892"
+          pattern="([58]\d{3})(\d{5})">$1-$2</numberFormat>
+        <numberFormat leadingDigits="5(?:29[89]|38[89])"
+          pattern="(5\d{4})(\d{4})">$1-$2</numberFormat>
+        <numberFormat leadingDigits="8(?:0|9[013-9])"
+          pattern="(8[09])(\d{7})">$1-$2</numberFormat>
+      </availableFormats>
+      <generalDesc>
+        <nationalNumberPattern>[5689]\d{8}</nationalNumberPattern>
+        <!-- Closed numbering plan. -->
+        <possibleNumberPattern>\d{9}</possibleNumberPattern>
+      </generalDesc>
+      <fixedLine>
+        <nationalNumberPattern>5(?:2(?:[015-7]\d{2}|(?:[28][2-9]|3[2-7]|4[2-8])\d|9(?:0\d|[89]0))|3(?:[0-4]\d{2}|(?:[57][2-9]|6[2-8]|9[3-9])\d|8(?:0\d|[89]0)))\d{4}</nationalNumberPattern>
+        <exampleNumber>520123456</exampleNumber>
+      </fixedLine>
+      <mobile>
+        <nationalNumberPattern>6(?:00|33|[15-7]\d|4[0-8]|99)\d{6}</nationalNumberPattern>
+        <exampleNumber>650123456</exampleNumber>
+      </mobile>
+      <tollFree>
+        <nationalNumberPattern>80\d{7}</nationalNumberPattern>
+        <exampleNumber>801234567</exampleNumber>
+      </tollFree>
+      <premiumRate>
+        <nationalNumberPattern>89\d{7}</nationalNumberPattern>
+        <exampleNumber>891234567</exampleNumber>
+      </premiumRate>
     </territory>
 
     <!-- Monaco -->
@@ -3921,6 +4197,25 @@
       </mobile>
     </territory>
 
+    <!-- Saint-Martin, French Antilles -->
+    <!-- http://www.itu.int/oth/T0202000058/en -->
+    <territory id="MF" countryCode="590" internationalPrefix="00"
+      nationalPrefix="0">
+      <!-- Formatting rules borrowed from Guadeloupe. -->
+      <generalDesc>
+        <nationalNumberPattern>[56]\d{8}</nationalNumberPattern>
+        <possibleNumberPattern>\d{9}</possibleNumberPattern>
+      </generalDesc>
+      <fixedLine>
+        <nationalNumberPattern>590(?:10|2[79]|5[128]|[78]7)\d{4}</nationalNumberPattern>
+        <exampleNumber>590271234</exampleNumber>
+      </fixedLine>
+      <mobile>
+        <nationalNumberPattern>690(?:10|2[27]|66|77|8[78])\d{4}</nationalNumberPattern>
+        <exampleNumber>690221234</exampleNumber>
+      </mobile>
+    </territory>
+
     <!-- Marshall Islands -->
     <territory id="MH" countryCode="692" internationalPrefix="011"
                nationalPrefix="1">
@@ -3979,13 +4274,12 @@
         <possibleNumberPattern>\d{8}</possibleNumberPattern>
       </generalDesc>
       <fixedLine>
-        <!-- 20 70 seems a common pattern, in addition to 20 79. 21 25 seems
-        also to exist. -->
+        <!-- 20 70 seems a common pattern, in addition to 21 25. -->
         <nationalNumberPattern>(?:2(?:0(?:2[0-589]|7[027-9])|1(?:2[5-7]|[3-689]\d))|442\d)\d{4}</nationalNumberPattern>
         <exampleNumber>20212345</exampleNumber>
       </fixedLine>
       <mobile>
-        <nationalNumberPattern>(?:6(?:[569]\d)|7(?:[3579][0-4]|4[014-7]|6\d|8[1-9]))\d{5}</nationalNumberPattern>
+        <nationalNumberPattern>(?:6(?:[569]\d)|7(?:[08][1-9]|[3579][0-4]|4[014-7]|6\d))\d{5}</nationalNumberPattern>
         <exampleNumber>65012345</exampleNumber>
       </mobile>
       <tollFree>
@@ -4088,7 +4382,8 @@
     <!--  Northern Mariana Islands -->
     <!-- http://www.itu.int/oth/T02020000EE/en -->
     <!-- www.cnmiphonebook.com/ -->
-    <territory id="MP" countryCode="1" internationalPrefix="011">
+    <territory id="MP" countryCode="1" leadingDigits="670"
+      internationalPrefix="011">
       <generalDesc>
         <!-- NANPA country - uses US formatting rules -->
         <nationalNumberPattern>[689]\d{9}</nationalNumberPattern>
@@ -4142,7 +4437,8 @@
 
     <!-- Montserrat -->
     <!-- http://www.itu.int/oth/T020200008F/en -->
-    <territory id="MS" countryCode="1" internationalPrefix="011">
+    <territory id="MS" countryCode="1" leadingDigits="664"
+      internationalPrefix="011">
       <generalDesc>
         <!-- NANPA country - uses US formatting rules -->
         <nationalNumberPattern>[689]\d{9}</nationalNumberPattern>
@@ -4759,7 +5055,7 @@
         <numberFormat leadingDigits="5" pattern="(500)(\d{4})">$1 $2</numberFormat>
       </availableFormats>
       <generalDesc>
-        <nationalNumberPattern>(?:2[3-6]|5|9[235-9])\d{6}|800\d{5,6}</nationalNumberPattern>
+        <nationalNumberPattern>(?:2[3-6]|5|9[2-9])\d{6}|800\d{5,6}</nationalNumberPattern>
         <possibleNumberPattern>\d{7,9}</possibleNumberPattern>
       </generalDesc>
       <fixedLine>
@@ -4768,9 +5064,7 @@
         <exampleNumber>23123456</exampleNumber>
       </fixedLine>
       <mobile>
-        <!-- Adding 93 as it seems numbers starting from 930 have started to be
-        issued. We successfully delivered numbers to this range. -->
-        <nationalNumberPattern>9[235-9]\d{6}</nationalNumberPattern>
+        <nationalNumberPattern>9[2-9]\d{6}</nationalNumberPattern>
         <possibleNumberPattern>\d{8}</possibleNumberPattern>
         <exampleNumber>92123456</exampleNumber>
       </mobile>
@@ -4795,8 +5089,35 @@
     </territory>
 
     <!-- Peru -->
+    <!-- http://www.itu.int/oth/T02020000A6/en -->
+    <!-- http://en.wikipedia.org/wiki/+51 -->
     <territory id="PE" countryCode="51" internationalPrefix="00"
-               nationalPrefix="0">
+               nationalPrefix="0" nationalPrefixFormattingRule="($FG)"
+               preferredExtnPrefix=" Anexo ">
+      <availableFormats>
+        <numberFormat leadingDigits="19" pattern="(1)(9\d{2})(\d{6})">$1 $2 $3</numberFormat>
+        <numberFormat leadingDigits="1[0-8]" pattern="(1)(\d{8})">$1 $2</numberFormat>
+        <numberFormat leadingDigits="[4-8]\d[0-8]" pattern="([4-8]\d)(\d{6})">$1 $2</numberFormat>
+        <numberFormat leadingDigits="[4-8]\d9"
+          pattern="([4-8]\d)(9\d{2})(\d{6})">$1 $2 $3</numberFormat>
+      </availableFormats>
+      <generalDesc>
+        <!-- The explicit requirements for numbers beginning with 5 are because
+        of the existence of a region code 51, not to be confused with the
+        country code 51. -->
+        <nationalNumberPattern>[146-8]\d{7,10}|5\d{7}(?:\d{3})?</nationalNumberPattern>
+        <possibleNumberPattern>\d{7,11}</possibleNumberPattern>
+      </generalDesc>
+      <fixedLine>
+        <nationalNumberPattern>(?:1\d{2}|4[1-4]|5[1-46]|6[1-7]|7[2-46]|8[2-4])\d{6}</nationalNumberPattern>
+        <possibleNumberPattern>\d{7,9}</possibleNumberPattern>
+        <exampleNumber>112345678</exampleNumber>
+      </fixedLine>
+      <mobile>
+        <nationalNumberPattern>(?:1|4[1-4]|5[1-46]|6[1-7]|7[2-46]|8[2-4])9\d{8}</nationalNumberPattern>
+        <possibleNumberPattern>\d{10,11}</possibleNumberPattern>
+        <exampleNumber>54951234567</exampleNumber>
+      </mobile>
     </territory>
 
     <!-- French Polynesia (Tahiti) (Territoire français d'outre-mer) -->
@@ -4981,7 +5302,8 @@
 
     <!-- Puerto Rico -->
     <!-- http://www.itu.int/oth/T02020000AA/en -->
-    <territory id="PR" countryCode="1" internationalPrefix="011">
+    <territory id="PR" countryCode="1" leadingDigits="787|939"
+      internationalPrefix="011">
       <generalDesc>
         <!-- NANPA country - uses US formatting rules -->
         <nationalNumberPattern>[789]\d{9}</nationalNumberPattern>
@@ -5085,7 +5407,8 @@
     them. -->
     <!-- http://www.itu.int/oth/T020200004B/en -->
     <territory id="RE" countryCode="262" internationalPrefix="00"
-               nationalPrefix="0" nationalPrefixFormattingRule="$NP$FG">
+               nationalPrefix="0" nationalPrefixFormattingRule="$NP$FG"
+               leadingDigits="262|6[49]|8" mainCountryForCode="true" >
       <availableFormats>
         <numberFormat pattern="([268]\d{2})(\d{2})(\d{2})(\d{2})">$1 $2 $3 $4</numberFormat>
       </availableFormats>
@@ -5206,11 +5529,16 @@
     <!-- http://www.itu.int/oth/T02020000AD/en -->
     <!-- http://en.wikipedia.org/wiki/%2B7 -->
     <territory id="RU" countryCode="7" internationalPrefix="8~10"
-               nationalPrefix="8" nationalPrefixFormattingRule="$NP ($FG)">
+               nationalPrefix="8" nationalPrefixFormattingRule="$NP ($FG)"
+               mainCountryForCode="true" >
       <availableFormats>
         <!-- Formatting from wikipedia, confirmed on Goverment websites such
-        as http://www.minjust.ru/ru/structure/contact/ -->
-        <numberFormat pattern="([3489]\d{2})(\d{3})(\d{2})(\d{2})">$1 $2-$3-$4</numberFormat>
+        as http://www.minjust.ru/ru/structure/contact/. Contains formatting
+        instructions for Kazakhstan as well. -->
+        <numberFormat leadingDigits="[34689]"
+          pattern="([34689]\d{2})(\d{3})(\d{2})(\d{2})">$1 $2-$3-$4</numberFormat>
+        <numberFormat leadingDigits="7"
+          pattern="([7]\d{2})(\d{3})(\d{4})">$1 $2 $3</numberFormat>
       </availableFormats>
       <generalDesc>
         <nationalNumberPattern>[3489]\d{9}</nationalNumberPattern>
@@ -5714,7 +6042,8 @@
 
     <!-- Turks and Caicos Islands -->
     <!-- http://www.itu.int/oth/T02020000D8/en -->
-    <territory id="TC" countryCode="1" internationalPrefix="011">
+    <territory id="TC" countryCode="1" leadingDigits="649"
+      internationalPrefix="011">
       <generalDesc>
         <!-- NANPA country - uses US formatting rules -->
         <nationalNumberPattern>[689]\d{9}</nationalNumberPattern>
@@ -5916,8 +6245,29 @@
     </territory>
 
     <!-- Tunisia -->
-    <territory id="TN" countryCode="216" internationalPrefix="00"
-               nationalPrefix="0">
+    <!-- http://www.itu.int/oth/T02020000D5/en -->
+    <territory id="TN" countryCode="216" internationalPrefix="00">
+      <availableFormats>
+        <numberFormat pattern="([247-9]\d)(\d{3})(\d{3})">$1 $2 $3</numberFormat>
+      </availableFormats>
+      <generalDesc>
+        <nationalNumberPattern>[247-9]\d{7}</nationalNumberPattern>
+        <possibleNumberPattern>\d{8}</possibleNumberPattern>
+      </generalDesc>
+      <fixedLine>
+        <nationalNumberPattern>7\d{7}</nationalNumberPattern>
+        <exampleNumber>71234567</exampleNumber>
+      </fixedLine>
+      <mobile>
+        <nationalNumberPattern>(?:2[0-7]|40|9\d)\d{6}</nationalNumberPattern>
+        <exampleNumber>20123456</exampleNumber>
+      </mobile>
+      <!-- These are listed as 'value added services' - pending further
+      information, we add them here for now. -->
+      <premiumRate>
+        <nationalNumberPattern>8[028]\d{6}</nationalNumberPattern>
+        <exampleNumber>80123456</exampleNumber>
+      </premiumRate>
     </territory>
 
     <!-- Tonga -->
@@ -5956,7 +6306,8 @@
 
     <!-- Trinidad and Tobago -->
     <!-- http://www.itu.int/oth/T02020000D4/en -->
-    <territory id="TT" countryCode="1" internationalPrefix="011">
+    <territory id="TT" countryCode="1" leadingDigits="868"
+      internationalPrefix="011">
       <generalDesc>
         <!-- NANPA country - uses US formatting rules -->
         <nationalNumberPattern>[89]\d{9}</nationalNumberPattern>
@@ -6163,7 +6514,8 @@
          numbers in the national format, it is not included. Therefore, we omit it here to make
          formatting consistent with the rest of the world. The same applies to all the
          countries/regions under NANPA -->
-    <territory id="US" countryCode="1" internationalPrefix="011">
+    <territory id="US" countryCode="1" internationalPrefix="011"
+               mainCountryForCode="true" >
       <availableFormats>
         <numberFormat pattern="(\d{3})(\d{3})(\d{4})">($1) $2-$3</numberFormat>
         <numberFormat pattern="(\d{3})(\d{4})">$1-$2</numberFormat>
@@ -6254,7 +6606,8 @@
 
     <!-- Saint Vincent and the Grenadines -->
     <!-- http://www.itu.int/oth/T02020000B3/en -->
-    <territory id="VC" countryCode="1" internationalPrefix="011">
+    <territory id="VC" countryCode="1" leadingDigits="784"
+      internationalPrefix="011">
       <generalDesc>
         <!-- NANPA country - uses US formatting rules -->
         <nationalNumberPattern>(?:784|8(?:00|66|77|88)|900)[2-9]\d{6}</nationalNumberPattern>
@@ -6282,13 +6635,48 @@
     </territory>
 
     <!-- Venezuela -->
+    <!-- http://www.itu.int/oth/T02020000E3/en -->
+    <!-- http://en.wikipedia.org/wiki/+58 -->
+    <!-- 1XX specifies a particular carrier to route a call to. -->
     <territory id="VE" countryCode="58" internationalPrefix="00"
-               nationalPrefix="0">
+      nationalPrefix="0" nationalPrefixForParsing="1\d{2}|0"
+      nationalPrefixFormattingRule="$NP$FG">
+      <availableFormats>
+        <numberFormat pattern="(\d{3})(\d{7})">$1-$2</numberFormat>
+      </availableFormats>
+      <generalDesc>
+        <nationalNumberPattern>[24589]\d{9}</nationalNumberPattern>
+        <!-- Open numbering plan. -->
+        <possibleNumberPattern>\d{7,10}</possibleNumberPattern>
+      </generalDesc>
+      <fixedLine>
+        <!-- Including region-free 500 calls here, since these are treated as
+        local calls. Wikipedia mentions these as 5XX, but online examples that
+        can be found are seemingly restricted to 50[01]. -->
+        <nationalNumberPattern>(?:2(?:12|3[457-9]|[58][1-9]|[467]\d|9[1-6])|50[01])\d{7}</nationalNumberPattern>
+        <exampleNumber>2121234567</exampleNumber>
+      </fixedLine>
+      <mobile>
+        <nationalNumberPattern>4(?:1[24-8]|2[46])\d{7}</nationalNumberPattern>
+        <possibleNumberPattern>\d{10}</possibleNumberPattern>
+        <exampleNumber>4121234567</exampleNumber>
+      </mobile>
+      <tollFree>
+        <nationalNumberPattern>800\d{7}</nationalNumberPattern>
+        <possibleNumberPattern>\d{10}</possibleNumberPattern>
+        <exampleNumber>8001234567</exampleNumber>
+      </tollFree>
+      <premiumRate>
+        <nationalNumberPattern>900\d{7}</nationalNumberPattern>
+        <possibleNumberPattern>\d{10}</possibleNumberPattern>
+        <exampleNumber>9001234567</exampleNumber>
+      </premiumRate>
     </territory>
 
     <!-- Virgin Islands, British -->
     <!-- http://www.itu.int/oth/T020200001E/en -->
-    <territory id="VG" countryCode="1" internationalPrefix="011">
+    <territory id="VG" countryCode="1" leadingDigits="284"
+      internationalPrefix="011">
       <generalDesc>
         <!-- NANPA country - uses US formatting rules -->
         <nationalNumberPattern>(?:284|8(?:00|66|77|88)|900)[2-9]\d{6}</nationalNumberPattern>
@@ -6317,7 +6705,8 @@
 
     <!-- Virgin Islands, United States -->
     <!-- http://www.itu.int/oth/T02020000DF/en -->
-    <territory id="VI" countryCode="1" internationalPrefix="011">
+    <territory id="VI" countryCode="1" leadingDigits="340"
+      internationalPrefix="011">
       <generalDesc>
         <!-- NANPA country - uses US formatting rules -->
         <nationalNumberPattern>340(?:6[49]2|7[17]\d)\d{4}|(?:8(?:00|66|77|88)|900)[2-9]\d{6}</nationalNumberPattern>
@@ -6475,7 +6864,8 @@
     fixed-line prefixes, but the mobile prefixes listed here seem out of date.
     -->
     <territory id="YT" countryCode="262" internationalPrefix="00"
-               nationalPrefix="0" nationalPrefixFormattingRule="$NP$FG">
+      nationalPrefix="0" nationalPrefixFormattingRule="$NP$FG"
+      leadingDigits="269|63">
       <!-- Formatting as per La Réunion. -->
       <generalDesc>
         <nationalNumberPattern>[268]\d{8}</nationalNumberPattern>
diff --git a/java/resources/com/google/i18n/phonenumbers/test/PhoneNumberMetaDataForTesting.xml b/java/resources/com/google/i18n/phonenumbers/test/PhoneNumberMetaDataForTesting.xml
index 524507b..e6d11cb 100644
--- a/java/resources/com/google/i18n/phonenumbers/test/PhoneNumberMetaDataForTesting.xml
+++ b/java/resources/com/google/i18n/phonenumbers/test/PhoneNumberMetaDataForTesting.xml
@@ -38,7 +38,7 @@
         <numberFormat leadingDigits="11" pattern="(\d{2})(\d{4})(\d{4})">$1 $2-$3</numberFormat>
         <numberFormat leadingDigits="1[02-9]|[23]" pattern="(\d{4})(\d{2})(\d{4})">$1 $2-$3</numberFormat>
         <numberFormat leadingDigits="911" pattern="9(11)(\d{4})(\d{4})">$1 15 $2-$3</numberFormat>
-        <numberFormat leadingDigits="9(?:1[02-9]|[23])" pattern="9(\d{4})(\d{2})(\d{4})">$1 15 $2-$3</numberFormat>
+        <numberFormat leadingDigits="9(?:1[02-9]|[23])" pattern="9(\d{4})(\d{2})(\d{4})" carrierCodeFormattingRule="$FG $CC">$1 $2-$3</numberFormat>
         <numberFormat leadingDigits="[68]" pattern="(\d{3})(\d{3})(\d{4})">$1-$2-$3</numberFormat>
         <intlNumberFormat leadingDigits="11" pattern="(\d{2})(\d{4})(\d{4})">$1 $2-$3</intlNumberFormat>
         <intlNumberFormat leadingDigits="1[02-9]|[23]" pattern="(\d{4})(\d{2})(\d{4})">$1 $2-$3</intlNumberFormat>
@@ -370,6 +370,41 @@
       </premiumRate>
     </territory>
 
+    <!-- Réunion (French Departments and Territories in the Indian Ocean) -->
+    <!-- Note this shares the same country code as La Mayotte and French
+    Southern Territories, and the formatting patterns here are used by all of
+    them. This is present to test leadingDigits. -->
+    <territory id="RE" countryCode="262" leadingDigits="262|6(?:9[23]|47)|8"
+               internationalPrefix="00" nationalPrefix="0" nationalPrefixFormattingRule="$NP$FG">
+      <availableFormats>
+        <numberFormat pattern="([268]\d{2})(\d{2})(\d{2})(\d{2})">$1 $2 $3 $4</numberFormat>
+      </availableFormats>
+      <generalDesc>
+        <nationalNumberPattern>[268]\d{8}</nationalNumberPattern>
+        <possibleNumberPattern>\d{9}</possibleNumberPattern>
+      </generalDesc>
+      <fixedLine>
+        <!-- 0876 numbers are mentioned in the plan, but none in use can be
+        found. -->
+        <nationalNumberPattern>262\d{6}</nationalNumberPattern>
+        <exampleNumber>262161234</exampleNumber>
+      </fixedLine>
+      <mobile>
+        <nationalNumberPattern>6(?:9[23]|47)\d{6}</nationalNumberPattern>
+        <possibleNumberPattern>\d{9}</possibleNumberPattern>
+        <exampleNumber>692123456</exampleNumber>
+      </mobile>
+      <!-- 08* Numbers in Réunion are the same as those valid in France. -->
+      <tollFree>
+        <nationalNumberPattern>80\d{7}</nationalNumberPattern>
+        <exampleNumber>801234567</exampleNumber>
+      </tollFree>
+      <premiumRate>
+        <nationalNumberPattern>8(?:1[01]|2[0156]|84|9[0-37-9])\d{6}</nationalNumberPattern>
+        <exampleNumber>810123456</exampleNumber>
+      </premiumRate>
+    </territory>
+
     <!-- Singapore -->
     <!-- http://www.ida.gov.sg/policies%20and%20regulation/20060508120124.aspx -->
     <territory id="SG" countryCode="65" internationalPrefix="0[0-3][0-9]">
@@ -405,7 +440,8 @@
     <!-- For testing purposes, numbers starting with 24 are not considered US
     numbers.-->
     <territory id="US" countryCode="1" internationalPrefix="011"
-               preferredExtnPrefix=" extn. ">
+               preferredExtnPrefix=" extn. "
+               mainCountryForCode="true">
       <availableFormats>
         <numberFormat pattern="(\d{3})(\d{3})(\d{4})">$1 $2 $3</numberFormat>
         <numberFormat pattern="(\d{3})(\d{4})">$1 $2</numberFormat>
@@ -424,5 +460,28 @@
         <possibleNumberPattern>\d{10}</possibleNumberPattern>
       </premiumRate>
     </territory>
+
+    <!-- Mayotte -->
+    <territory id="YT" countryCode="262" leadingDigits="269|639"
+               internationalPrefix="00" nationalPrefix="0" nationalPrefixFormattingRule="$NP$FG">
+      <!-- Formatting as per La Réunion. -->
+      <generalDesc>
+        <nationalNumberPattern>[268]\d{8}</nationalNumberPattern>
+        <possibleNumberPattern>\d{9}</possibleNumberPattern>
+      </generalDesc>
+      <fixedLine>
+        <nationalNumberPattern>2696[0-4]\d{4}</nationalNumberPattern>
+        <exampleNumber>269601234</exampleNumber>
+      </fixedLine>
+      <mobile>
+        <nationalNumberPattern>639\d{6}</nationalNumberPattern>
+        <exampleNumber>639123456</exampleNumber>
+      </mobile>
+      <!-- Same as in France. -->
+      <tollFree>
+        <nationalNumberPattern>80\d{7}</nationalNumberPattern>
+        <exampleNumber>801234567</exampleNumber>
+      </tollFree>
+    </territory>
   </territories>
 </phoneNumberMetadata>
diff --git a/java/src/com/google/i18n/phonenumbers/AsYouTypeFormatter.java b/java/src/com/google/i18n/phonenumbers/AsYouTypeFormatter.java
index 8936d5b..303a474 100644
--- a/java/src/com/google/i18n/phonenumbers/AsYouTypeFormatter.java
+++ b/java/src/com/google/i18n/phonenumbers/AsYouTypeFormatter.java
@@ -49,23 +49,31 @@
   private Phonemetadata.PhoneMetadata defaultMetaData;
   private PhoneMetadata currentMetaData;
 
+  // A pattern that is used to match character classes in regular expressions. An example of a
+  // character class is [1-4].
+  private final Pattern CHARACTER_CLASS_PATTERN = Pattern.compile("\\[([^\\[\\]])*\\]");
+  // Any digit in a regular expression that actually denotes a digit. For example, in the regular
+  // expression 80[0-2]\d{6,10}, the first 2 digits (8 and 0) are standalone digits, but the rest
+  // are not.
+  // Two look-aheads are needed because the number following \\d could be a two-digit number, since
+  // the phone number can be as long as 15 digits.
+  private static final Pattern STANDALONE_DIGIT_PATTERN = Pattern.compile("\\d(?=[^,}][^,}])");
+
   // The digits that have not been entered yet will be represented by a \u2008, the punctuation
   // space.
   private String digitPlaceholder = "\u2008";
   private Pattern digitPattern = Pattern.compile(digitPlaceholder);
   private int lastMatchPosition = 0;
-  private boolean rememberPosition = false;
+  // The position of a digit upon which inputDigitAndRememberPosition is most recently invoked, as
+  // found in the current output.
   private int positionRemembered = 0;
+  // The position of a digit upon which inputDigitAndRememberPosition is most recently invoked, as
+  // found in the original sequence of characters the user entered.
   private int originalPosition = 0;
   private Pattern nationalPrefixForParsing;
   private Pattern internationalPrefix;
   private StringBuffer prefixBeforeNationalNumber;
   private StringBuffer nationalNumber;
-  // No formatting will be applied when any of the character in the following character class is
-  // entered by users.
-  private final Pattern UNSUPPORTED_SYNTAX = Pattern.compile("[- *#;,.()/a-zA-Z]");
-  private final Pattern CHARACTER_CLASS_PATTERN = Pattern.compile("\\[([^\\[\\]])*\\]");
-  private final Pattern STANDALONE_DIGIT_PATTERN = Pattern.compile("\\d(?=[^,}][^,}])");
 
   /**
    * Constructs a light-weight formatter which does no formatting, but outputs exactly what is
@@ -182,25 +190,32 @@
     }
   }
 
-  /**
-   * Formats a phone number on-the-fly as each digit is entered.
-   *
-   * @param nextChar  the most recently entered digit of a phone number. Formatting characters are
-   *     allowed, but they are removed from the result. Full width digits and Arabic-indic digits
-   *     are allowed, and will be shown as they are.
-   * @return  the partially formatted phone number.
-   */
   public String inputDigit(char nextChar) {
+    return inputDigitWithOptionToRememberPosition(nextChar, false);
+  }
+
+  /**
+   * Same as inputDigit, but remembers the position where nextChar is inserted, so that it could be
+   * retrieved later by using getRememberedPosition(). The remembered position will be automatically
+   * adjusted if additional formatting characters are later inserted/removed in front of nextChar.
+   */
+  public String inputDigitAndRememberPosition(char nextChar) {
+    return inputDigitWithOptionToRememberPosition(nextChar, true);
+  }
+
+  private String inputDigitWithOptionToRememberPosition(char nextChar, boolean rememberPosition) {
     accruedInput.append(nextChar);
-    rememberPosition();
-    if (UNSUPPORTED_SYNTAX.matcher(Character.toString(nextChar)).matches()) {
+    if (rememberPosition) {
+      positionRemembered = accruedInput.length();
+      originalPosition = positionRemembered;
+    }
+    // We do formatting on-the-fly only when each character entered is either a plus sign or a
+    // digit.
+    if (!PhoneNumberUtil.VALID_START_CHAR_PATTERN.matcher(Character.toString(nextChar)).matches()) {
       ableToFormat = false;
     }
     if (!ableToFormat) {
-      if (positionRemembered > 0 && currentOutput.length() > 0) {
-        positionRemembered = originalPosition;
-        currentOutput.setLength(0);
-      }
+      resetPositionOnFailureToFormat();
       return accruedInput.toString();
     }
 
@@ -222,39 +237,27 @@
           return accruedInput.toString();
         }
         removeNationalPrefixFromNationalNumber();
-        return attemptToChooseFormattingPattern();
+        return attemptToChooseFormattingPattern(rememberPosition);
       default:
         if (nationalNumber.length() > 4) {  // The formatting pattern is already chosen.
-          String temp = inputDigitHelper(nextChar);
+          String temp = inputDigitHelper(nextChar, rememberPosition);
           return ableToFormat
               ? prefixBeforeNationalNumber + temp
               : temp;
         } else {
-          return attemptToChooseFormattingPattern();
+          return attemptToChooseFormattingPattern(rememberPosition);
         }
     }
   }
 
-  private void rememberPosition() {
-    if (rememberPosition) {
-      positionRemembered = accruedInput.length();
-      originalPosition = positionRemembered;
+  private void resetPositionOnFailureToFormat() {
+    if (positionRemembered > 0) {
+      positionRemembered = originalPosition;
+      currentOutput.setLength(0);
     }
   }
 
   /**
-   * Same as inputDigit, but remembers the position where nextChar is inserted, so that it could be
-   * retrieved later by using getRememberedPosition(). The remembered position will be automatically
-   * adjusted if additional formatting characters are later inserted/removed in front of nextChar.
-   */
-  public String inputDigitAndRememberPosition(char nextChar) {
-    rememberPosition = true;
-    String result = inputDigit(nextChar);
-    rememberPosition = false;
-    return result;
-  }
-
-  /**
    * Returns the current position in the partially formatted phone number of the character which was
    * previously passed in as the parameter of inputDigitAndRememberPosition().
    */
@@ -264,12 +267,12 @@
 
   // Attempts to set the formatting template and returns a string which contains the formatted
   // version of the digits entered so far.
-  private String attemptToChooseFormattingPattern() {
+  private String attemptToChooseFormattingPattern(boolean rememberPosition) {
     // We start to attempt to format only when as least 4 digits of national number (excluding
     // national prefix) have been entered.
     if (nationalNumber.length() >= 4) {
       chooseFormatAndCreateTemplate(nationalNumber.substring(0, 4));
-      return inputAccruedNationalNumber();
+      return inputAccruedNationalNumber(rememberPosition);
     } else {
       if (rememberPosition) {
         positionRemembered = prefixBeforeNationalNumber.length() + nationalNumber.length();
@@ -280,23 +283,23 @@
 
   // Invokes inputDigitHelper on each digit of the national number accrued, and returns a formatted
   // string in the end.
-  private String inputAccruedNationalNumber() {
+  private String inputAccruedNationalNumber(boolean rememberPosition) {
     int lengthOfNationalNumber = nationalNumber.length();
     if (lengthOfNationalNumber > 0) {
       // The positionRemembered should be only adjusted once in the loop that follows.
-      Boolean positionAlreadyAdjusted = false;
-      for (int i = 0; i < lengthOfNationalNumber - 1; i++) {
-        String temp = inputDigitHelper(nationalNumber.charAt(i));
+      boolean positionAlreadyAdjusted = false;
+      String tempNationalNumber = "";
+      for (int i = 0; i < lengthOfNationalNumber; i++) {
+        tempNationalNumber = inputDigitHelper(nationalNumber.charAt(i), rememberPosition);
         if (!positionAlreadyAdjusted &&
             positionRemembered - prefixBeforeNationalNumber.length() == i + 1) {
-          positionRemembered = prefixBeforeNationalNumber.length() + temp.length();
+          positionRemembered = prefixBeforeNationalNumber.length() + tempNationalNumber.length();
           positionAlreadyAdjusted = true;
         }
       }
-      String temp = inputDigitHelper(nationalNumber.charAt(lengthOfNationalNumber - 1));
       return ableToFormat
-          ? prefixBeforeNationalNumber + temp
-          : temp;
+          ? prefixBeforeNationalNumber + tempNationalNumber
+          : tempNationalNumber;
     } else {
       if (rememberPosition) {
         positionRemembered = prefixBeforeNationalNumber.length();
@@ -309,13 +312,12 @@
     int startOfNationalNumber = 0;
     if (currentMetaData.getCountryCode() == 1 && nationalNumber.charAt(0) == '1') {
       startOfNationalNumber = 1;
-      prefixBeforeNationalNumber.append("1");
-      // Since a space will be inserted after the national prefix in this case, we increase the
+      prefixBeforeNationalNumber.append("1 ");
+      // Since a space is inserted after the national prefix in this case, we increase the
       // remembered position by 1 for anything that is after the national prefix.
-      if (positionRemembered > prefixBeforeNationalNumber.length()) {
+      if (positionRemembered > prefixBeforeNationalNumber.length() - 1) {
         positionRemembered++;
       }
-      prefixBeforeNationalNumber.append(" ");
     } else if (currentMetaData.hasNationalPrefix()) {
       Matcher m = nationalPrefixForParsing.matcher(nationalNumber);
       if (m.lookingAt()) {
@@ -392,7 +394,7 @@
     return nextChar;
   }
 
-  private String inputDigitHelper(char nextChar) {
+  private String inputDigitHelper(char nextChar, boolean rememberPosition) {
     if (!PhoneNumberUtil.DIGIT_MAPPINGS.containsKey(nextChar)) {
       return currentOutput.toString();
     }
@@ -408,10 +410,7 @@
     } else {  // More digits are entered than we could handle.
       currentOutput.append(nextChar);
       ableToFormat = false;
-      if (positionRemembered > 0) {
-        positionRemembered = originalPosition;
-        currentOutput.setLength(0);
-      }
+      resetPositionOnFailureToFormat();
       return accruedInput.toString();
     }
   }
diff --git a/java/src/com/google/i18n/phonenumbers/PhoneNumberMetadataProto b/java/src/com/google/i18n/phonenumbers/PhoneNumberMetadataProto
index 31a15e5..c2906bc 100644
--- a/java/src/com/google/i18n/phonenumbers/PhoneNumberMetadataProto
+++ b/java/src/com/google/i18n/phonenumbers/PhoneNumberMetadataProto
Binary files differ
diff --git a/java/src/com/google/i18n/phonenumbers/PhoneNumberUtil.java b/java/src/com/google/i18n/phonenumbers/PhoneNumberUtil.java
index d0aa5c1..080a65a 100644
--- a/java/src/com/google/i18n/phonenumbers/PhoneNumberUtil.java
+++ b/java/src/com/google/i18n/phonenumbers/PhoneNumberUtil.java
@@ -26,6 +26,7 @@
 import java.io.InputStream;
 import java.io.IOException;
 import java.io.ObjectInputStream;
+import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.HashMap;
@@ -53,33 +54,19 @@
       "/com/google/i18n/phonenumbers/PhoneNumberMetadataProto";
   private static final Logger LOGGER = Logger.getLogger(PhoneNumberUtil.class.getName());
 
-  // A mapping from a country code to a region code which denotes the country/region
-  // represented by that country code. Note countries under NANPA share the country code 1,
-  // Russia and Kazakhstan share the country code 7, and many French territories in the Indian
-  // Ocean share the country code 262. Under this map, 1 is mapped to US, 7 is mapped to RU,
-  // and 262 is mapped to RE. The initial capacity is set to 300 as there are roughly 200 different
+  // A mapping from a country code to the region codes which denote the country/region
+  // represented by that country code. In the case of multiple countries sharing a calling code,
+  // such as the NANPA countries, the one indicated with "isMainCountryForCode" in the metadata
+  // should be first. The initial capacity is set to 300 as there are roughly 200 different
   // country codes, and this offers a load factor of roughly 0.75.
-  private final HashMap<Integer, String> countryCodeToRegionCodeMap =
-      new HashMap<Integer, String>(310);
+  private final Map<Integer, List<String> > countryCodeToRegionCodeMap =
+      new HashMap<Integer, List<String> >(310);
 
   // The set of countries that share country code 1. There are roughly 26 countries of them and we
   // set the initial capacity of the HashSet to 35 to offer a load factor of roughly 0.75.
   private final HashSet<String> nanpaCountries = new HashSet<String>(35);
   private static final int NANPA_COUNTRY_CODE = 1;
 
-  // The set of countries that share country code 7.
-  private final HashSet<String> russiaFederationCountries = new HashSet<String>(3);
-  private static final int RUSSIAN_FED_COUNTRY_CODE = 7;
-
-  // The set of countries that share country code 44.
-  private final HashSet<String> greatBritainAndDependencies = new HashSet<String>(7);
-  private static final int GREAT_BRITAIN_COUNTRY_CODE = 44;
-
-  // The set of countries that share country code 262.
-  private final HashSet<String> frenchIndianOceanTerritories = new HashSet<String>(6);
-
-  private static final int FRENCH_INDIAN_OCEAN_COUNTRY_CODE = 262;
-
   // The PLUS_SIGN signifies the international prefix.
   static final char PLUS_SIGN = '+';
 
@@ -173,7 +160,6 @@
     aSet.add(225);  // Cote d'Ivoire
     aSet.add(227);  // Niger
     aSet.add(228);  // Togo
-    aSet.add(240);  // Equatorial Guinea
     aSet.add(241);  // Gabon
     aSet.add(379);  // Vatican City
     LEADING_ZERO_COUNTRIES = Collections.unmodifiableSet(aSet);
@@ -214,7 +200,7 @@
   // not include other punctuation, as this will be stripped later during parsing and is of no
   // information value when parsing a number.
   private static final String VALID_START_CHAR = "[" + PLUS_CHARS + VALID_DIGITS + "]";
-  private static final Pattern VALID_START_CHAR_PATTERN = Pattern.compile(VALID_START_CHAR);
+  static final Pattern VALID_START_CHAR_PATTERN = Pattern.compile(VALID_START_CHAR);
 
   // Regular expression of characters typically used to start a second phone number for the purposes
   // of parsing. This allows us to strip off parts of the number that are actually the start of
@@ -260,8 +246,8 @@
   // Note that the only capturing groups should be around the digits that you want to capture as
   // part of the extension, or else parsing will fail!
   private static final String KNOWN_EXTN_PATTERNS = "[ \u00A0\\t,]*(?:ext(?:ensio)?n?|" +
-      "\uFF45\uFF58\uFF54\uFF4E?|[,x\uFF58#\uFF03~\uFF5E]|int|\uFF49\uFF4E\uFF54)" +
-      "[:\\.\uFF0E]?[ \u00A0\\t,]*([" + VALID_DIGITS + "]{1,7})|[- ]+([" + VALID_DIGITS +
+      "\uFF45\uFF58\uFF54\uFF4E?|[,x\uFF58#\uFF03~\uFF5E]|int|anexo|\uFF49\uFF4E\uFF54)" +
+      "[:\\.\uFF0E]?[ \u00A0\\t,-]*([" + VALID_DIGITS + "]{1,7})|[- ]+([" + VALID_DIGITS +
       "]{1,5})#";
 
   // Regexp of all known extension prefixes used by different countries followed by 1 or more valid
@@ -276,10 +262,12 @@
       Pattern.compile(VALID_PHONE_NUMBER + "(?:" + KNOWN_EXTN_PATTERNS + ")?",
                       Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);
 
-  private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("(\\D+)");
+  private static final Pattern NON_DIGITS_PATTERN = Pattern.compile("(\\D+)");
   private static final Pattern FIRST_GROUP_PATTERN = Pattern.compile("(\\$1)");
   private static final Pattern NP_PATTERN = Pattern.compile("\\$NP");
   private static final Pattern FG_PATTERN = Pattern.compile("\\$FG");
+  private static final Pattern CC_PATTERN = Pattern.compile("\\$CC");
+  private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("\\D");
 
   private static PhoneNumberUtil instance = null;
 
@@ -287,10 +275,10 @@
   private HashMap<String, PhoneMetadata> countryToMetadataMap =
       new HashMap<String, PhoneMetadata>();
 
-  // A cache for frequently used regular expressions. As most people use phone numbers primarily
-  // from one country, and there are roughly 30 regular expressions needed, the initial capacity of
-  // 50 offers a rough load factor of 0.75.
-  private RegexCache regexCache = new RegexCache(50);
+  // A cache for frequently used country-specific regular expressions. As most people use phone
+  // numbers primarily from one to two countries, and there are roughly 60 regular expressions
+  // needed, the initial capacity of 100 offers a rough load factor of 0.75.
+  private RegexCache regexCache = new RegexCache(100);
 
   /**
    * INTERNATIONAL and NATIONAL formats are consistent with the definition in ITU-T Recommendation
@@ -371,34 +359,23 @@
         countryToMetadataMap.put(regionCode, metadata);
         countryToMetadataMap.put(regionCode.toLowerCase(), metadata);
         int countryCode = metadata.getCountryCode();
-        switch (countryCode) {
-          case NANPA_COUNTRY_CODE:
-            nanpaCountries.add(regionCode);
-            nanpaCountries.add(regionCode.toLowerCase());
-            break;
-          case RUSSIAN_FED_COUNTRY_CODE:
-            russiaFederationCountries.add(regionCode);
-            russiaFederationCountries.add(regionCode.toLowerCase());
-            break;
-          case FRENCH_INDIAN_OCEAN_COUNTRY_CODE:
-            frenchIndianOceanTerritories.add(regionCode);
-            frenchIndianOceanTerritories.add(regionCode.toLowerCase());
-            break;
-          case GREAT_BRITAIN_COUNTRY_CODE:
-            greatBritainAndDependencies.add(regionCode);
-            break;
-          default:
-            countryCodeToRegionCodeMap.put(countryCode, regionCode);
-            break;
+        if (countryCodeToRegionCodeMap.containsKey(countryCode)) {
+          if (metadata.getMainCountryForCode()) {
+            countryCodeToRegionCodeMap.get(countryCode).add(0, regionCode);
+          } else {
+            countryCodeToRegionCodeMap.get(countryCode).add(regionCode);
+          }
+        } else {
+          // For most countries, there will be only one region code for the country dialing code.
+          List<String> listWithRegionCode = new ArrayList<String>(1);
+          listWithRegionCode.add(regionCode);
+          countryCodeToRegionCodeMap.put(countryCode, listWithRegionCode);
+        }
+        if (countryCode == NANPA_COUNTRY_CODE) {
+          nanpaCountries.add(regionCode);
+          nanpaCountries.add(regionCode.toLowerCase());
         }
       }
-
-      // Override the value, so that 1 is always mapped to US, 7 is always mapped to RU, 44 to GB
-      // and 262 to RE.
-      countryCodeToRegionCodeMap.put(NANPA_COUNTRY_CODE, "US");
-      countryCodeToRegionCodeMap.put(RUSSIAN_FED_COUNTRY_CODE, "RU");
-      countryCodeToRegionCodeMap.put(FRENCH_INDIAN_OCEAN_COUNTRY_CODE, "RE");
-      countryCodeToRegionCodeMap.put(GREAT_BRITAIN_COUNTRY_CODE, "GB");
     } catch (IOException e) {
       LOGGER.log(Level.WARNING, e.toString());
     } catch (ClassNotFoundException e) {
@@ -422,14 +399,14 @@
    *                found in the number
    */
   static String extractPossibleNumber(String number) {
-    // Remove trailing non-alpha non-numerical characters.
-    Matcher trailingCharsMatcher = UNWANTED_END_CHAR_PATTERN.matcher(number);
-    if (trailingCharsMatcher.find()) {
-      number = number.substring(0, trailingCharsMatcher.start());
-    }
     Matcher m = VALID_START_CHAR_PATTERN.matcher(number);
     if (m.find()) {
       number = number.substring(m.start());
+      // Remove trailing non-alpha non-numerical characters.
+      Matcher trailingCharsMatcher = UNWANTED_END_CHAR_PATTERN.matcher(number);
+      if (trailingCharsMatcher.find()) {
+        number = number.substring(0, trailingCharsMatcher.start());
+      }
       // Check for extra numbers at the end.
       Matcher secondNumber = SECOND_NUMBER_START_PATTERN.matcher(number);
       if (secondNumber.find()) {
@@ -710,9 +687,9 @@
       formatNumberByFormat(countryCode, PhoneNumberFormat.E164, formattedNumber);
       return;
     }
-    // Note here that all NANPA formatting rules are contained by US, so we use that to format NANPA
-    // numbers. The same applies to Russian Fed countries - rules are contained by Russia. French
-    // Indian Ocean country rules are contained by Reunion.
+    // Note getRegionCodeForCountryCode() is used because formatting information for countries which
+    // share a country code is contained by only one country for performance reasons. For example,
+    // for NANPA countries it will be contained in the metadata for US.
     String regionCode = getRegionCodeForCountryCode(countryCode);
     if (!isValidRegionCode(regionCode)) {
       formattedNumber.append(nationalSignificantNumber);
@@ -740,11 +717,11 @@
                                 PhoneNumberFormat numberFormat,
                                 List<NumberFormat> userDefinedFormats) {
     int countryCode = number.getCountryCode();
+    String nationalSignificantNumber = getNationalSignificantNumber(number);
     // Note getRegionCodeForCountryCode() is used because formatting information for countries which
     // share a country code is contained by only one country for performance reasons. For example,
     // for NANPA countries it will be contained in the metadata for US.
     String regionCode = getRegionCodeForCountryCode(countryCode);
-    String nationalSignificantNumber = getNationalSignificantNumber(number);
     if (!isValidRegionCode(regionCode)) {
       return nationalSignificantNumber;
     }
@@ -772,6 +749,27 @@
     return formattedNumber.toString();
   }
 
+  public String formatNationalNumberWithCarrierCode(PhoneNumber number, String carrierCode) {
+    int countryCode = number.getCountryCode();
+    String nationalSignificantNumber = getNationalSignificantNumber(number);
+    // Note getRegionCodeForCountryCode() is used because formatting information for countries which
+    // share a country code is contained by only one country for performance reasons. For example,
+    // for NANPA countries it will be contained in the metadata for US.
+    String regionCode = getRegionCodeForCountryCode(countryCode);
+    if (!isValidRegionCode(regionCode)) {
+      return nationalSignificantNumber;
+    }
+
+    StringBuffer formattedNumber = new StringBuffer(20);
+    formattedNumber.append(formatNationalNumber(nationalSignificantNumber,
+                                                regionCode,
+                                                PhoneNumberFormat.NATIONAL,
+                                                carrierCode));
+    maybeGetFormattedExtension(number, regionCode, formattedNumber);
+    formatNumberByFormat(countryCode, PhoneNumberFormat.NATIONAL, formattedNumber);
+    return formattedNumber.toString();
+  }
+
   /**
    * Formats a phone number for out-of-country dialing purpose. If no countryCallingFrom
    * is supplied, we format the number in its INTERNATIONAL format. If the countryCallingFrom is
@@ -796,55 +794,24 @@
       return format(number, PhoneNumberFormat.INTERNATIONAL);
     }
     int countryCode = number.getCountryCode();
-    if (countryCode == NANPA_COUNTRY_CODE && isNANPACountry(countryCallingFrom)) {
-      // For NANPA countries, return the national format for these countries but prefix it with the
-      // country code.
-      return countryCode + " " + format(number, PhoneNumberFormat.NATIONAL);
-    }
-    if (countryCode == FRENCH_INDIAN_OCEAN_COUNTRY_CODE &&
-        frenchIndianOceanTerritories.contains(countryCallingFrom)) {
-      // For dialling between FRENCH_INDIAN_OCEAN countries, the 10 digit number is all we need.
-      // Technically this is the case for dialling from la Reunion to other overseas departments of
-      // France (French Guiana, Martinique, Guadeloupe), but not vice versa - so we don't cover this
-      // edge case for now and for those cases return the version including country code.
-      // Details here: http://www.petitfute.com/voyage/225-info-pratiques-reunion
-      return format(number, PhoneNumberFormat.NATIONAL);
-    }
-    if (countryCode == GREAT_BRITAIN_COUNTRY_CODE &&
-        greatBritainAndDependencies.contains(countryCallingFrom)) {
-      // It seems that numbers can be dialled in national format between Great Britain and the crown
-      // dependencies with the same country code.
-      return format(number, PhoneNumberFormat.NATIONAL);
-    }
-    // If the country code is the Russian Fed country code, we check the number itself to determine
-    // which region code it is for. We don't do this for NANPA countries because of performance
-    // reasons, and instead use US rules for all NANPA numbers. Also, NANPA countries share the
-    // same national and international prefixes, which is not the case for Russian Fed countries.
-    // There is also a special case for toll-free and premium rate numbers dialled within Russian
-    // Fed countries.
-    String regionCode;
-    if (countryCode == RUSSIAN_FED_COUNTRY_CODE) {
-      if (russiaFederationCountries.contains(countryCallingFrom)) {
-        // For toll-free numbers and premium rate numbers dialled from within Russian Fed countries,
-        // we should format them as if they are local numbers.
-        // A toll-free number would be dialled from KZ as 8-800-080-7777 but from Russia as
-        // 0-800-080-7777. (Confirmation on government websites such as e.gov.kz).
-        PhoneNumberType numberType = getNumberType(number);
-        if (numberType == PhoneNumberType.TOLL_FREE || numberType == PhoneNumberType.PREMIUM_RATE) {
-          return format(number, PhoneNumberFormat.NATIONAL);
-        }
-      }
-      // Otherwise, we should find out what region the number really belongs to before continuing,
-      // since they have different formatting rules.
-      regionCode = getRegionCodeForNumber(number);
-    } else {
-      regionCode = getRegionCodeForCountryCode(countryCode);
-    }
+    String regionCode = getRegionCodeForCountryCode(countryCode);
     String nationalSignificantNumber = getNationalSignificantNumber(number);
     if (!isValidRegionCode(regionCode)) {
       return nationalSignificantNumber;
     }
-    if (regionCode.equalsIgnoreCase(countryCallingFrom)) {
+    if (countryCode == NANPA_COUNTRY_CODE) {
+      if (isNANPACountry(countryCallingFrom)) {
+        // For NANPA countries, return the national format for these countries but prefix it with
+        // the country code.
+        return countryCode + " " + format(number, PhoneNumberFormat.NATIONAL);
+      }
+    } else if (countryCode == getCountryCodeForRegion(countryCallingFrom)) {
+    // For countries that share a country calling code, the country code need not be dialled. This
+    // also applies when dialling within a country, so this if clause covers both these cases.
+    // Technically this is the case for dialling from la RŽunion to other overseas departments of
+    // France (French Guiana, Martinique, Guadeloupe), but not vice versa - so we don't cover this
+    // edge case for now and for those cases return the version including country code.
+    // Details here: http://www.petitfute.com/voyage/225-info-pratiques-reunion
       return format(number, PhoneNumberFormat.NATIONAL);
     }
     String formattedNationalNumber =
@@ -881,26 +848,25 @@
    * passed in. If such information is missing, the number will be formatted into the NATIONAL
    * format by default.
    *
-   * @param number  The PhoneNumber that needs to be formatted in its original number format
-   * @param defaultCountry  the country whose IDD needs to be appended if the original number has
-   *                        one
-   * @return  The formatted phone number in its original number format
+   * @param number  the PhoneNumber that needs to be formatted in its original number format
+   * @param countryCallingFrom  the country whose IDD needs to be prefixed if the original number
+   *     has one
+   * @return  the formatted phone number in its original number format
    */
-  public String formatUsingOriginalNumberFormat(PhoneNumber number, String defaultCountry) {
-    if (!number.hasRawInput()) {
+  public String formatInOriginalFormat(PhoneNumber number, String countryCallingFrom) {
+    if (!number.hasCountryCodeSource()) {
       return format(number, PhoneNumberFormat.NATIONAL);
     }
     switch (number.getCountryCodeSource()) {
-      case FROM_DEFAULT_COUNTRY:
-        return format(number, PhoneNumberFormat.NATIONAL);
       case FROM_NUMBER_WITH_PLUS_SIGN:
         return format(number, PhoneNumberFormat.INTERNATIONAL);
       case FROM_NUMBER_WITH_IDD:
-        return formatOutOfCountryCallingNumber(number, defaultCountry);
+        return formatOutOfCountryCallingNumber(number, countryCallingFrom);
       case FROM_NUMBER_WITHOUT_PLUS_SIGN:
         return format(number, PhoneNumberFormat.INTERNATIONAL).substring(1);
+      case FROM_DEFAULT_COUNTRY:
       default:
-        return number.getRawInput();
+        return format(number, PhoneNumberFormat.NATIONAL);      
     }
   }
 
@@ -947,12 +913,21 @@
     }
   }
 
-  // Note in some countries, the national number can be written in two completely different ways
-  // depending on whether it forms part of the NATIONAL format or INTERNATIONAL format. The
-  // numberFormat parameter here is used to specify which format to use for those cases.
+  // Simple wrapper of formatNationalNumber for the common case of no carrier code.
   private String formatNationalNumber(String number,
                                       String regionCode,
                                       PhoneNumberFormat numberFormat) {
+    return formatNationalNumber(number, regionCode, numberFormat, null);
+  }  
+
+  // Note in some countries, the national number can be written in two completely different ways
+  // depending on whether it forms part of the NATIONAL format or INTERNATIONAL format. The
+  // numberFormat parameter here is used to specify which format to use for those cases. If a
+  // carrierCode is specified, this will be inserted into the formatted string to replace $CC.
+  private String formatNationalNumber(String number,
+                                      String regionCode,
+                                      PhoneNumberFormat numberFormat,
+                                      String carrierCode) {
     PhoneMetadata metadata = getMetadataForRegion(regionCode);
     List<NumberFormat> intlNumberFormats = metadata.getIntlNumberFormatList();
     // When the intlNumberFormats exists, we use that to format national number for the
@@ -961,27 +936,48 @@
         (intlNumberFormats.size() == 0 || numberFormat == PhoneNumberFormat.NATIONAL)
         ? metadata.getNumberFormatList()
         : metadata.getIntlNumberFormatList();
-    return formatAccordingToFormats(number, availableFormats, numberFormat);
+    return formatAccordingToFormats(number, availableFormats, numberFormat, carrierCode);
   }
 
+  // Simple wrapper of formatAccordingToFormats for the common case of no carrier code.
   private String formatAccordingToFormats(String nationalNumber,
                                           List<NumberFormat> availableFormats,
                                           PhoneNumberFormat numberFormat) {
+    return formatAccordingToFormats(nationalNumber, availableFormats, numberFormat, null);
+  }
+
+  // Note that carrierCode is optional - if NULL or an empty string, no carrier code replacement
+  // will take place. Carrier code replacement occurs before national prefix replacement.
+  private String formatAccordingToFormats(String nationalNumber,
+                                          List<NumberFormat> availableFormats,
+                                          PhoneNumberFormat numberFormat,
+                                          String carrierCode) {
     for (NumberFormat numFormat : availableFormats) {
       if (!numFormat.hasLeadingDigits() ||
           regexCache.getPatternForRegex(numFormat.getLeadingDigits()).matcher(nationalNumber)
               .lookingAt()) {
-        Pattern patternToMatch = regexCache.getPatternForRegex(numFormat.getPattern());
-        Matcher m = patternToMatch.matcher(nationalNumber);
+        Matcher m = regexCache.getPatternForRegex(numFormat.getPattern()).matcher(nationalNumber);
+        String numberFormatRule = numFormat.getFormat();
         if (m.matches()) {
+          if (carrierCode != null && carrierCode.length() > 0 &&
+              numFormat.getDomesticCarrierCodeFormattingRule().length() > 0) {
+            // Replace the $CC in the formatting rule with the desired carrier code.
+            String carrierCodeFormattingRule = numFormat.getDomesticCarrierCodeFormattingRule();
+            carrierCodeFormattingRule =
+                CC_PATTERN.matcher(carrierCodeFormattingRule).replaceFirst(carrierCode);
+            // Now replace the $FG in the formatting rule with the first group and the carrier code
+            // combined in the appropriate way.
+            numberFormatRule = FIRST_GROUP_PATTERN.matcher(numberFormatRule)
+                .replaceFirst(carrierCodeFormattingRule);
+          }
           String nationalPrefixFormattingRule = numFormat.getNationalPrefixFormattingRule();
-          if (nationalPrefixFormattingRule != null && nationalPrefixFormattingRule.length() > 0 &&
-              numberFormat == PhoneNumberFormat.NATIONAL) {
-              Matcher firstGroupMatcher =
-                  FIRST_GROUP_PATTERN.matcher(numFormat.getFormat());
+          if (numberFormat == PhoneNumberFormat.NATIONAL &&
+              nationalPrefixFormattingRule != null &&
+              nationalPrefixFormattingRule.length() > 0) {
+            Matcher firstGroupMatcher = FIRST_GROUP_PATTERN.matcher(numberFormatRule);
             return m.replaceAll(firstGroupMatcher.replaceFirst(nationalPrefixFormattingRule));
           } else {
-            return m.replaceAll(numFormat.getFormat());
+            return m.replaceAll(numberFormatRule);
           }
         }
       }
@@ -1150,7 +1146,6 @@
     Matcher nationalNumberPatternMatcher =
         regexCache.getPatternForRegex(numberDesc.getNationalNumberPattern())
             .matcher(nationalNumber);
-
     return possibleNumberPatternMatcher.matches() && nationalNumberPatternMatcher.matches();
   }
 
@@ -1203,39 +1198,34 @@
    * the country/region level.
    *
    * @param number  the phone number whose origin we want to know
-   * @return  the country/region where the phone number is from
+   * @return  the country/region where the phone number is from, or null if no country matches this
+   *     calling code.
    */
   public String getRegionCodeForNumber(PhoneNumber number) {
     int countryCode = number.getCountryCode();
-    switch (countryCode) {
-      case NANPA_COUNTRY_CODE:
-        // Override this and try the US case first, since it is more likely than other countries,
-        // for performance reasons.
-        String nationalNumber = getNationalSignificantNumber(number);
-        if (getNumberTypeHelper(nationalNumber,
-                                getMetadataForRegion("US")) != PhoneNumberType.UNKNOWN) {
-          return "US";
-        }
-        HashSet<String> nanpaExceptUS = new HashSet<String>(nanpaCountries);
-        nanpaExceptUS.remove("US");
-        return getRegionCodeForNumberFromRegionList(number, nanpaExceptUS);
-      case RUSSIAN_FED_COUNTRY_CODE:
-        return getRegionCodeForNumberFromRegionList(number, russiaFederationCountries);
-      case FRENCH_INDIAN_OCEAN_COUNTRY_CODE:
-        return getRegionCodeForNumberFromRegionList(number, frenchIndianOceanTerritories);
-      case GREAT_BRITAIN_COUNTRY_CODE:
-        return getRegionCodeForNumberFromRegionList(number, greatBritainAndDependencies);
-      default:
-        return getRegionCodeForCountryCode(countryCode);
+    List<String> regions = countryCodeToRegionCodeMap.get(countryCode);
+    if (regions == null) {
+      return null;
+    }
+    if (regions.size() == 1) {
+      return regions.get(0);
+    } else {
+      return getRegionCodeForNumberFromRegionList(number, regions);
     }
   }
 
   private String getRegionCodeForNumberFromRegionList(PhoneNumber number,
-                                                      HashSet<String> regionCodes) {
+                                                      List<String> regionCodes) {
     String nationalNumber = String.valueOf(number.getNationalNumber());
     for (String regionCode : regionCodes) {
-      if (getNumberTypeHelper(nationalNumber, getMetadataForRegion(regionCode)) !=
-          PhoneNumberType.UNKNOWN) {
+      // If leadingDigits is present, use this. Otherwise, do full validation.
+      PhoneMetadata metadata = getMetadataForRegion(regionCode);
+      if (metadata.hasLeadingDigits()) {
+        if (regexCache.getPatternForRegex(metadata.getLeadingDigits())
+                .matcher(nationalNumber).lookingAt()) {
+          return regionCode;
+        }
+      } else if (getNumberTypeHelper(nationalNumber, metadata) != PhoneNumberType.UNKNOWN) {
         return regionCode;
       }
     }
@@ -1244,11 +1234,12 @@
 
   /**
    * Returns the region code that matches the specific country code. In the case of no region code
-   * being found, ZZ will be returned.
+   * being found, ZZ will be returned. In the case of multiple regions, the one designated in the
+   * metadata as the "main" country for this calling code will be returned.
    */
-  String getRegionCodeForCountryCode(int countryCode) {
-    String regionCode = countryCodeToRegionCodeMap.get(countryCode);
-    return regionCode == null ? "ZZ" : regionCode;
+  public String getRegionCodeForCountryCode(int countryCode) {
+    List<String> regionCodes = countryCodeToRegionCodeMap.get(countryCode);
+    return regionCodes == null ? "ZZ" : regionCodes.get(0);
   }
 
   /**
@@ -1330,6 +1321,18 @@
     }
     String nationalNumber = getNationalSignificantNumber(number);
     PhoneNumberDesc generalNumDesc = getMetadataForRegion(regionCode).getGeneralDesc();
+    // Handling case of numbers with no metadata.
+    if (!generalNumDesc.hasNationalNumberPattern()) {
+      LOGGER.log(Level.FINER, "Checking if number is possible with incomplete metadata.");
+      int numberLength = nationalNumber.length();
+      if (numberLength < MIN_LENGTH_FOR_NSN) {
+        return ValidationResult.TOO_SHORT;
+      } else if (numberLength > MAX_LENGTH_FOR_NSN) {
+        return ValidationResult.TOO_LONG;
+      } else {
+        return ValidationResult.IS_POSSIBLE;
+      }
+    }
     String possibleNumberPattern = generalNumDesc.getPossibleNumberPattern();
     Matcher m = regexCache.getPatternForRegex(possibleNumberPattern).matcher(nationalNumber);
     if (m.lookingAt()) {
@@ -1622,8 +1625,7 @@
     // it is an extension.
     if (m.find() && isViablePhoneNumber(number.substring(0, m.start()))) {
       // The numbers are captured into groups in the regular expression.
-      int length = m.groupCount();
-      for (int i = 1; i <= length; i++) {
+      for (int i = 1, length = m.groupCount(); i <= length; i++) {
         if (m.group(i) != null) {
           // We go through the capturing groups until we find one that captured some digits. If none
           // did, then we will return the empty string.
@@ -1665,8 +1667,10 @@
   public void parse(String numberToParse, String defaultCountry, PhoneNumber phoneNumber)
       throws NumberParseException {
     if (!isValidRegionCode(defaultCountry)) {
-      throw new NumberParseException(NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
-                                     "No default country was supplied.");
+      if (numberToParse.charAt(0) != PLUS_SIGN) {
+        throw new NumberParseException(NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
+                                       "Missing or invalid default country.");
+      }
     }
     parseHelper(numberToParse, defaultCountry, false, phoneNumber);
   }
@@ -1700,8 +1704,10 @@
                                    PhoneNumber phoneNumber)
       throws NumberParseException {
     if (!isValidRegionCode(defaultCountry)) {
-      throw new NumberParseException(NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
-                                     "No default country was supplied.");
+      if (numberToParse.charAt(0) != PLUS_SIGN) {
+        throw new NumberParseException(NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
+                                       "Missing or invalid default country.");
+      }
     }
     parseHelper(numberToParse, defaultCountry, true, phoneNumber);
   }
diff --git a/java/src/com/google/i18n/phonenumbers/Phonemetadata.java b/java/src/com/google/i18n/phonenumbers/Phonemetadata.java
index f7715c1..09022bb 100644
--- a/java/src/com/google/i18n/phonenumbers/Phonemetadata.java
+++ b/java/src/com/google/i18n/phonenumbers/Phonemetadata.java
@@ -77,6 +77,19 @@
       return this;
     }
 
+    // optional string domestic_carrier_code_formatting_rule = 5;
+    private boolean hasDomesticCarrierCodeFormattingRule;
+    private String domesticCarrierCodeFormattingRule_ = "";
+    public boolean hasDomesticCarrierCodeFormattingRule() {
+      return hasDomesticCarrierCodeFormattingRule; }
+    public String getDomesticCarrierCodeFormattingRule() {
+      return domesticCarrierCodeFormattingRule_; }
+    public NumberFormat setDomesticCarrierCodeFormattingRule(String value) {
+      hasDomesticCarrierCodeFormattingRule = true;
+      domesticCarrierCodeFormattingRule_ = value;
+      return this;
+    }
+
     public void writeExternal(ObjectOutput objectOutput) throws IOException {
       objectOutput.writeUTF(pattern_);
       objectOutput.writeUTF(format_);
@@ -88,6 +101,10 @@
       if (hasNationalPrefixFormattingRule) {
         objectOutput.writeUTF(nationalPrefixFormattingRule_);
       }
+      objectOutput.writeBoolean(hasDomesticCarrierCodeFormattingRule);
+      if (hasDomesticCarrierCodeFormattingRule) {
+        objectOutput.writeUTF(domesticCarrierCodeFormattingRule_);
+      }
     }
 
     public void readExternal(ObjectInput objectInput) throws IOException, ClassNotFoundException {
@@ -99,6 +116,9 @@
       if (objectInput.readBoolean()) {
         setNationalPrefixFormattingRule(objectInput.readUTF());
       }
+      if (objectInput.readBoolean()) {
+        setDomesticCarrierCodeFormattingRule(objectInput.readUTF());
+      }
     }
   }
 
@@ -441,6 +461,28 @@
       return this;
     }
 
+    // optional bool main_country_for_code = 22 [default = false];
+    private boolean hasMainCountryForCode;
+    private boolean mainCountryForCode_ = false;
+    public boolean hasMainCountryForCode() { return hasMainCountryForCode; }
+    public boolean getMainCountryForCode() { return mainCountryForCode_; }
+    public PhoneMetadata setMainCountryForCode(boolean value) {
+      hasMainCountryForCode = true;
+      mainCountryForCode_ = value;
+      return this;
+    }
+
+    // optional string leading_digits = 23;
+    private boolean hasLeadingDigits;
+    private String leadingDigits_ = "";
+    public boolean hasLeadingDigits() { return hasLeadingDigits; }
+    public String getLeadingDigits() { return leadingDigits_; }
+    public PhoneMetadata setLeadingDigits(String value) {
+      hasLeadingDigits = true;
+      leadingDigits_ = value;
+      return this;
+    }
+
     public void writeExternal(ObjectOutput objectOutput) throws IOException {
       objectOutput.writeBoolean(hasGeneralDesc);
       if (hasGeneralDesc) {
@@ -517,6 +559,13 @@
       for (int i = 0; i < intlNumberFormatSize; i++) {
         intlNumberFormat_.get(i).writeExternal(objectOutput);
       }
+
+      objectOutput.writeBoolean(mainCountryForCode_);
+
+      objectOutput.writeBoolean(hasLeadingDigits);
+      if (hasLeadingDigits) {
+        objectOutput.writeUTF(leadingDigits_);
+      }
     }
 
     public void readExternal(ObjectInput objectInput) throws IOException, ClassNotFoundException {
@@ -613,6 +662,13 @@
         numFormat.readExternal(objectInput);
         intlNumberFormat_.add(numFormat);
       }
+
+      setMainCountryForCode(objectInput.readBoolean());
+
+      hasString = objectInput.readBoolean();
+      if (hasString) {
+        setLeadingDigits(objectInput.readUTF());
+      }
     }
   }
 
diff --git a/java/test/com/google/i18n/phonenumbers/AsYouTypeFormatterTest.java b/java/test/com/google/i18n/phonenumbers/AsYouTypeFormatterTest.java
index 087e52e..9b29407 100644
--- a/java/test/com/google/i18n/phonenumbers/AsYouTypeFormatterTest.java
+++ b/java/test/com/google/i18n/phonenumbers/AsYouTypeFormatterTest.java
@@ -67,6 +67,97 @@
     assertEquals("1 650 253 2222", formatter.inputDigit('2'));
 
     formatter.clear();
+    assertEquals("0", formatter.inputDigit('0'));
+    assertEquals("01", formatter.inputDigit('1'));
+    assertEquals("011", formatter.inputDigit('1'));
+    assertEquals("0114", formatter.inputDigit('4'));
+    assertEquals("01144", formatter.inputDigit('4'));
+    assertEquals("011 44 6", formatter.inputDigit('6'));
+    assertEquals("011 44 61", formatter.inputDigit('1'));
+    assertEquals("011 44 612", formatter.inputDigit('2'));
+    assertEquals("011 44 6 123", formatter.inputDigit('3'));
+    assertEquals("011 44 6 123 1", formatter.inputDigit('1'));
+    assertEquals("011 44 6 123 12", formatter.inputDigit('2'));
+    assertEquals("011 44 6 123 123", formatter.inputDigit('3'));
+    assertEquals("011 44 6 123 123 1", formatter.inputDigit('1'));
+    assertEquals("011 44 6 123 123 12", formatter.inputDigit('2'));
+    assertEquals("011 44 6 123 123 123", formatter.inputDigit('3'));
+
+    formatter.clear();
+    assertEquals("0", formatter.inputDigit('0'));
+    assertEquals("01", formatter.inputDigit('1'));
+    assertEquals("011", formatter.inputDigit('1'));
+    assertEquals("0115", formatter.inputDigit('5'));
+    assertEquals("01154", formatter.inputDigit('4'));
+    assertEquals("011 54 9", formatter.inputDigit('9'));
+    assertEquals("011 54 91", formatter.inputDigit('1'));
+    assertEquals("011 54 911", formatter.inputDigit('1'));
+    assertEquals("011 54 9 11 2",
+                 formatter.inputDigit('2'));
+    assertEquals("011 54 9 11 23", formatter.inputDigit('3'));
+    assertEquals("011 54 9 11 231", formatter.inputDigit('1'));
+    assertEquals("011 54 9 11 2312", formatter.inputDigit('2'));
+    assertEquals("011 54 9 11 2312 1", formatter.inputDigit('1'));
+    assertEquals("011 54 9 11 2312 12", formatter.inputDigit('2'));
+    assertEquals("011 54 9 11 2312 123", formatter.inputDigit('3'));
+    assertEquals("011 54 9 11 2312 1234", formatter.inputDigit('4'));
+
+    formatter.clear();
+    assertEquals("+", formatter.inputDigit('+'));
+    assertEquals("+4", formatter.inputDigit('4'));
+    assertEquals("+48", formatter.inputDigit('8'));
+    assertEquals("+488", formatter.inputDigit('8'));
+    assertEquals("+4888", formatter.inputDigit('8'));
+    assertEquals("+48 881", formatter.inputDigit('1'));
+    assertEquals("+48 88 12", formatter.inputDigit('2'));
+    assertEquals("+48 88 123", formatter.inputDigit('3'));
+    assertEquals("+48 88 123 1", formatter.inputDigit('1'));
+    assertEquals("+48 88 123 12", formatter.inputDigit('2'));
+    assertEquals("+48 88 123 12 1", formatter.inputDigit('1'));
+    assertEquals("+48 88 123 12 12", formatter.inputDigit('2'));
+  }
+
+  public void testAsYouTypeFormatterUSFullWidthCharacters() {
+    AsYouTypeFormatter formatter = phoneUtil.getAsYouTypeFormatter("US");
+    assertEquals("\uFF16", formatter.inputDigit('\uFF16'));
+    assertEquals("\uFF16\uFF15", formatter.inputDigit('\uFF15'));
+    assertEquals("\uFF16\uFF15\uFF10", formatter.inputDigit('\uFF10'));
+    assertEquals("\uFF16\uFF15\uFF10\uFF12", formatter.inputDigit('\uFF12'));
+    assertEquals("\uFF16\uFF15\uFF10\uFF12\uFF15", formatter.inputDigit('\uFF15'));
+    assertEquals("650 253", formatter.inputDigit('\uFF13'));
+    assertEquals("650 253 2", formatter.inputDigit('\uFF12'));
+    assertEquals("650 253 22", formatter.inputDigit('\uFF12'));
+    assertEquals("650 253 222", formatter.inputDigit('\uFF12'));
+    assertEquals("650 253 2222", formatter.inputDigit('\uFF12'));
+  }
+
+  public void testAsYouTypeFormatterUSMobileShortCode() {
+    AsYouTypeFormatter formatter = phoneUtil.getAsYouTypeFormatter("US");
+    assertEquals("*", formatter.inputDigit('*'));
+    assertEquals("*1", formatter.inputDigit('1'));
+    assertEquals("*12", formatter.inputDigit('2'));
+    assertEquals("*121", formatter.inputDigit('1'));
+    assertEquals("*121#", formatter.inputDigit('#'));
+  }
+
+  public void testAsYouTypeFormatterUSVanityNumber() {
+    AsYouTypeFormatter formatter = phoneUtil.getAsYouTypeFormatter("US");
+    assertEquals("8", formatter.inputDigit('8'));
+    assertEquals("80", formatter.inputDigit('0'));
+    assertEquals("800", formatter.inputDigit('0'));
+    assertEquals("800 ", formatter.inputDigit(' '));
+    assertEquals("800 M", formatter.inputDigit('M'));
+    assertEquals("800 MY", formatter.inputDigit('Y'));
+    assertEquals("800 MY ", formatter.inputDigit(' '));
+    assertEquals("800 MY A", formatter.inputDigit('A'));
+    assertEquals("800 MY AP", formatter.inputDigit('P'));
+    assertEquals("800 MY APP", formatter.inputDigit('P'));
+    assertEquals("800 MY APPL", formatter.inputDigit('L'));
+    assertEquals("800 MY APPLE", formatter.inputDigit('E'));
+  }
+
+  public void testAsYouTypeFormatterAndRememberPositionUS() {
+    AsYouTypeFormatter formatter = phoneUtil.getAsYouTypeFormatter("US");
     assertEquals("1", formatter.inputDigitAndRememberPosition('1'));
     assertEquals(1, formatter.getRememberedPosition());
     assertEquals("16", formatter.inputDigit('6'));
@@ -76,6 +167,8 @@
     assertEquals(4, formatter.getRememberedPosition());
     assertEquals("16502", formatter.inputDigit('2'));
     assertEquals("1 650 25", formatter.inputDigit('5'));
+    // Note the remembered position for digit "0" changes from 4 to 5, because a space is now
+    // inserted in the front.
     assertEquals(5, formatter.getRememberedPosition());
     assertEquals("1 650 253", formatter.inputDigit('3'));
     assertEquals("1 650 253 2", formatter.inputDigit('2'));
@@ -93,26 +186,6 @@
     formatter.clear();
     assertEquals("1", formatter.inputDigit('1'));
     assertEquals("16", formatter.inputDigit('6'));
-    assertEquals("165", formatter.inputDigit('5'));
-    assertEquals("1650", formatter.inputDigitAndRememberPosition('0'));
-    assertEquals(4, formatter.getRememberedPosition());
-    assertEquals("16502", formatter.inputDigit('2'));
-    assertEquals("1 650 25", formatter.inputDigit('5'));
-    assertEquals(5, formatter.getRememberedPosition());
-    assertEquals("1 650 253", formatter.inputDigit('3'));
-    assertEquals("1 650 253 2", formatter.inputDigit('2'));
-    assertEquals("1 650 253 22", formatter.inputDigit('2'));
-    assertEquals(5, formatter.getRememberedPosition());
-    assertEquals("1 650 253 222", formatter.inputDigit('2'));
-    assertEquals("1 650 253 2222", formatter.inputDigit('2'));
-    assertEquals("165025322222", formatter.inputDigit('2'));
-    assertEquals(4, formatter.getRememberedPosition());
-    assertEquals("1650253222222", formatter.inputDigit('2'));
-    assertEquals(4, formatter.getRememberedPosition());    
-
-    formatter.clear();
-    assertEquals("1", formatter.inputDigit('1'));
-    assertEquals("16", formatter.inputDigit('6'));
     assertEquals("165", formatter.inputDigitAndRememberPosition('5'));
     assertEquals("1650", formatter.inputDigit('0'));
     assertEquals(3, formatter.getRememberedPosition());
@@ -185,41 +258,6 @@
     assertEquals("011 48 88 123 12 12", formatter.inputDigit('2'));
 
     formatter.clear();
-    assertEquals("0", formatter.inputDigit('0'));
-    assertEquals("01", formatter.inputDigit('1'));
-    assertEquals("011", formatter.inputDigit('1'));
-    assertEquals("0114", formatter.inputDigit('4'));
-    assertEquals("01144", formatter.inputDigit('4'));
-    assertEquals("011 44 6", formatter.inputDigit('6'));
-    assertEquals("011 44 61", formatter.inputDigit('1'));
-    assertEquals("011 44 612", formatter.inputDigit('2'));
-    assertEquals("011 44 6 123", formatter.inputDigit('3'));
-    assertEquals("011 44 6 123 1", formatter.inputDigit('1'));
-    assertEquals("011 44 6 123 12", formatter.inputDigit('2'));
-    assertEquals("011 44 6 123 123", formatter.inputDigit('3'));
-    assertEquals("011 44 6 123 123 1", formatter.inputDigit('1'));
-    assertEquals("011 44 6 123 123 12", formatter.inputDigit('2'));
-    assertEquals("011 44 6 123 123 123", formatter.inputDigit('3'));
-
-    formatter.clear();
-    assertEquals("0", formatter.inputDigit('0'));
-    assertEquals("01", formatter.inputDigit('1'));
-    assertEquals("011", formatter.inputDigit('1'));
-    assertEquals("0115", formatter.inputDigit('5'));
-    assertEquals("01154", formatter.inputDigit('4'));
-    assertEquals("011 54 9", formatter.inputDigit('9'));
-    assertEquals("011 54 91", formatter.inputDigit('1'));
-    assertEquals("011 54 911", formatter.inputDigit('1'));
-    assertEquals("011 54 9 11 2", formatter.inputDigit('2'));
-    assertEquals("011 54 9 11 23", formatter.inputDigit('3'));
-    assertEquals("011 54 9 11 231", formatter.inputDigit('1'));
-    assertEquals("011 54 9 11 2312", formatter.inputDigit('2'));
-    assertEquals("011 54 9 11 2312 1", formatter.inputDigit('1'));
-    assertEquals("011 54 9 11 2312 12", formatter.inputDigit('2'));
-    assertEquals("011 54 9 11 2312 123", formatter.inputDigit('3'));
-    assertEquals("011 54 9 11 2312 1234", formatter.inputDigit('4'));
-
-    formatter.clear();
     assertEquals("+", formatter.inputDigit('+'));
     assertEquals("+1", formatter.inputDigit('1'));
     assertEquals("+16", formatter.inputDigitAndRememberPosition('6'));
@@ -251,56 +289,6 @@
     assertEquals("+1 650 253 222", formatter.inputDigit('2'));
     assertEquals("+1650253222;", formatter.inputDigit(';'));
     assertEquals(3, formatter.getRememberedPosition());
-
-    formatter.clear();
-    assertEquals("+", formatter.inputDigit('+'));
-    assertEquals("+4", formatter.inputDigit('4'));
-    assertEquals("+48", formatter.inputDigit('8'));
-    assertEquals("+488", formatter.inputDigit('8'));
-    assertEquals("+4888", formatter.inputDigit('8'));
-    assertEquals("+48 881", formatter.inputDigit('1'));
-    assertEquals("+48 88 12", formatter.inputDigit('2'));
-    assertEquals("+48 88 123", formatter.inputDigit('3'));
-    assertEquals("+48 88 123 1", formatter.inputDigit('1'));
-    assertEquals("+48 88 123 12", formatter.inputDigit('2'));
-    assertEquals("+48 88 123 12 1", formatter.inputDigit('1'));
-    assertEquals("+48 88 123 12 12", formatter.inputDigit('2'));
-
-    // Test US number with full-width characters.
-    formatter.clear();
-    assertEquals("\uFF16", formatter.inputDigit('\uFF16'));
-    assertEquals("\uFF16\uFF15", formatter.inputDigit('\uFF15'));
-    assertEquals("\uFF16\uFF15\uFF10", formatter.inputDigit('\uFF10'));
-    assertEquals("\uFF16\uFF15\uFF10\uFF12", formatter.inputDigit('\uFF12'));
-    assertEquals("\uFF16\uFF15\uFF10\uFF12\uFF15", formatter.inputDigit('\uFF15'));
-    assertEquals("650 253", formatter.inputDigit('\uFF13'));
-    assertEquals("650 253 2", formatter.inputDigit('\uFF12'));
-    assertEquals("650 253 22", formatter.inputDigit('\uFF12'));
-    assertEquals("650 253 222", formatter.inputDigit('\uFF12'));
-    assertEquals("650 253 2222", formatter.inputDigit('\uFF12'));
-
-    // Mobile short code.
-    formatter.clear();
-    assertEquals("*", formatter.inputDigit('*'));
-    assertEquals("*1", formatter.inputDigit('1'));
-    assertEquals("*12", formatter.inputDigit('2'));
-    assertEquals("*121", formatter.inputDigit('1'));
-    assertEquals("*121#", formatter.inputDigit('#'));
-
-    // Test vanity numbers.
-    formatter.clear();
-    assertEquals("8", formatter.inputDigit('8'));
-    assertEquals("80", formatter.inputDigit('0'));
-    assertEquals("800", formatter.inputDigit('0'));
-    assertEquals("800 ", formatter.inputDigit(' '));
-    assertEquals("800 M", formatter.inputDigit('M'));
-    assertEquals("800 MY", formatter.inputDigit('Y'));
-    assertEquals("800 MY ", formatter.inputDigit(' '));
-    assertEquals("800 MY A", formatter.inputDigit('A'));
-    assertEquals("800 MY AP", formatter.inputDigit('P'));
-    assertEquals("800 MY APP", formatter.inputDigit('P'));
-    assertEquals("800 MY APPL", formatter.inputDigit('L'));
-    assertEquals("800 MY APPLE", formatter.inputDigit('E'));
   }
 
   public void testAsYouTypeFormatterGBFixedLine() {
@@ -321,7 +309,7 @@
   }
 
   public void testAsYouTypeFormatterGBTollFree() {
-    AsYouTypeFormatter formatter = phoneUtil.getAsYouTypeFormatter("gb");
+     AsYouTypeFormatter formatter = phoneUtil.getAsYouTypeFormatter("gb");
     assertEquals("0", formatter.inputDigit('0'));
     assertEquals("08", formatter.inputDigit('8'));
     assertEquals("080", formatter.inputDigit('0'));
@@ -357,6 +345,7 @@
     assertEquals("021", formatter.inputDigit('1'));
     assertEquals("0211", formatter.inputDigit('1'));
     assertEquals("02112", formatter.inputDigit('2'));
+    // Note the unittest is using fake metadata which might produce non-ideal results.
     assertEquals("02-112 3", formatter.inputDigit('3'));
     assertEquals("02-112 34", formatter.inputDigit('4'));
     assertEquals("02-112 345", formatter.inputDigit('5'));
diff --git a/java/test/com/google/i18n/phonenumbers/PhoneNumberMetadataProtoForTesting b/java/test/com/google/i18n/phonenumbers/PhoneNumberMetadataProtoForTesting
index 5418da9..8b72ac9 100644
--- a/java/test/com/google/i18n/phonenumbers/PhoneNumberMetadataProtoForTesting
+++ b/java/test/com/google/i18n/phonenumbers/PhoneNumberMetadataProtoForTesting
Binary files differ
diff --git a/java/test/com/google/i18n/phonenumbers/PhoneNumberUtilTest.java b/java/test/com/google/i18n/phonenumbers/PhoneNumberUtilTest.java
index 9499fbe..cab8140 100644
--- a/java/test/com/google/i18n/phonenumbers/PhoneNumberUtilTest.java
+++ b/java/test/com/google/i18n/phonenumbers/PhoneNumberUtilTest.java
@@ -117,9 +117,9 @@
     assertEquals("0", metadata.getNationalPrefix());
     assertEquals("0(?:(11|343|3715)15)?", metadata.getNationalPrefixForParsing());
     assertEquals("9$1", metadata.getNationalPrefixTransformRule());
+    assertEquals("$1 15 $2-$3", metadata.getNumberFormat(2).getFormat());
     assertEquals("9(\\d{4})(\\d{2})(\\d{4})",
                  metadata.getNumberFormat(3).getPattern());
-    assertEquals("$1 15 $2-$3", metadata.getNumberFormat(3).getFormat());
     assertEquals("(9)(\\d{4})(\\d{2})(\\d{4})",
                  metadata.getIntlNumberFormat(3).getPattern());
     assertEquals("$1 $2 $3 $4", metadata.getIntlNumberFormat(3).getFormat());
@@ -479,6 +479,25 @@
                  phoneUtil.formatOutOfCountryCallingNumber(itNumber, "AU"));
   }
 
+  public void testFormatWithCarrierCode() {
+    // We only support this for AR in our test metadata.
+    PhoneNumber arNumber = new PhoneNumber();
+    arNumber.setCountryCode(54).setNationalNumber(91234125678L);
+    assertEquals("01234 12-5678", phoneUtil.format(arNumber,
+                                                   PhoneNumberUtil.PhoneNumberFormat.NATIONAL));
+    // Test formatting with a carrier code.
+    assertEquals("01234 15 12-5678", phoneUtil.formatNationalNumberWithCarrierCode(arNumber, "15"));
+    // Here the international rule is used, so no carrier code should be present.
+    assertEquals("+5491234125678", phoneUtil.format(arNumber,
+                                                    PhoneNumberUtil.PhoneNumberFormat.E164));
+    // We don't support this for the US so there should be no change.
+    PhoneNumber usNumber = new PhoneNumber();
+    usNumber.setCountryCode(1).setNationalNumber(4241231234L);
+    assertEquals("424 123 1234", phoneUtil.format(usNumber,
+                                                  PhoneNumberUtil.PhoneNumberFormat.NATIONAL));
+    assertEquals("424 123 1234", phoneUtil.formatNationalNumberWithCarrierCode(usNumber, "15"));
+  }
+
   public void testFormatByPattern() {
     PhoneNumber usNumber = new PhoneNumber();
     usNumber.setCountryCode(1).setNationalNumber(6502530000L);
@@ -575,19 +594,19 @@
 
   public void testFormatUsingOriginalNumberFormat() throws Exception {
     PhoneNumber number1 = phoneUtil.parseAndKeepRawInput("+442087654321", "GB");
-    assertEquals("+44 20 8765 4321", phoneUtil.formatUsingOriginalNumberFormat(number1, "GB"));
+    assertEquals("+44 20 8765 4321", phoneUtil.formatInOriginalFormat(number1, "GB"));
 
     PhoneNumber number2 = phoneUtil.parseAndKeepRawInput("02087654321", "GB");
-    assertEquals("(020) 8765 4321", phoneUtil.formatUsingOriginalNumberFormat(number2, "GB"));
+    assertEquals("(020) 8765 4321", phoneUtil.formatInOriginalFormat(number2, "GB"));
 
     PhoneNumber number3 = phoneUtil.parseAndKeepRawInput("011442087654321", "US");
-    assertEquals("011 44 20 8765 4321", phoneUtil.formatUsingOriginalNumberFormat(number3, "US"));
+    assertEquals("011 44 20 8765 4321", phoneUtil.formatInOriginalFormat(number3, "US"));
 
     PhoneNumber number4 = phoneUtil.parseAndKeepRawInput("442087654321", "GB");
-    assertEquals("44 20 8765 4321", phoneUtil.formatUsingOriginalNumberFormat(number4, "GB"));
+    assertEquals("44 20 8765 4321", phoneUtil.formatInOriginalFormat(number4, "GB"));
 
     PhoneNumber number5 = phoneUtil.parse("+442087654321", "GB");
-    assertEquals("(020) 8765 4321", phoneUtil.formatUsingOriginalNumberFormat(number5, "GB"));
+    assertEquals("(020) 8765 4321", phoneUtil.formatInOriginalFormat(number5, "GB"));
   }
 
   public void testIsPremiumRate() {
@@ -763,6 +782,28 @@
     bsNumber.setNationalNumber(2421232345L);
     // This number is no longer valid.
     assertFalse(phoneUtil.isValidNumber(bsNumber));
+
+    // La Mayotte and RŽunion use 'leadingDigits' to differentiate them.
+    PhoneNumber reNumber = new PhoneNumber();
+    reNumber.setCountryCode(262).setNationalNumber(262123456L);
+    assertTrue(phoneUtil.isValidNumber(reNumber));
+    assertTrue(phoneUtil.isValidNumberForRegion(reNumber, "RE"));
+    assertFalse(phoneUtil.isValidNumberForRegion(reNumber, "YT"));
+    // Now change the number to be a number for La Mayotte.
+    reNumber.setNationalNumber(269601234L);
+    assertTrue(phoneUtil.isValidNumberForRegion(reNumber, "YT"));
+    assertFalse(phoneUtil.isValidNumberForRegion(reNumber, "RE"));
+    // This number is no longer valid for La RŽunion.
+    reNumber.setNationalNumber(269123456L);
+    assertFalse(phoneUtil.isValidNumberForRegion(reNumber, "YT"));
+    assertFalse(phoneUtil.isValidNumberForRegion(reNumber, "RE"));
+    assertFalse(phoneUtil.isValidNumber(reNumber));
+    // However, it should be recognised as from La Mayotte, since it is valid for this region.
+    assertEquals("YT", phoneUtil.getRegionCodeForNumber(reNumber));
+    // This number is valid in both places.
+    reNumber.setNationalNumber(800123456L);
+    assertTrue(phoneUtil.isValidNumberForRegion(reNumber, "YT"));
+    assertTrue(phoneUtil.isValidNumberForRegion(reNumber, "RE"));
   }
 
   public void testIsNotValidNumber() {
@@ -874,6 +915,18 @@
     number.setCountryCode(1).setNationalNumber(65025300000L);
     assertEquals(PhoneNumberUtil.ValidationResult.TOO_LONG,
                  phoneUtil.isPossibleNumberWithReason(number));
+
+    // Try with number that we don't have metadata for.
+    PhoneNumber adNumber = new PhoneNumber();
+    adNumber.setCountryCode(376).setNationalNumber(12345L);
+    assertEquals(PhoneNumberUtil.ValidationResult.IS_POSSIBLE,
+                 phoneUtil.isPossibleNumberWithReason(adNumber));
+    adNumber.setCountryCode(376).setNationalNumber(13L);
+    assertEquals(PhoneNumberUtil.ValidationResult.TOO_SHORT,
+                 phoneUtil.isPossibleNumberWithReason(adNumber));
+    adNumber.setCountryCode(376).setNationalNumber(1234567890123456L);
+    assertEquals(PhoneNumberUtil.ValidationResult.TOO_LONG,
+                 phoneUtil.isPossibleNumberWithReason(adNumber));
   }
 
   public void testIsNotPossibleNumber() {
@@ -1308,6 +1361,16 @@
                    e.getErrorType());
     }
     try {
+      String plusMinusPhoneNumber = "+---";
+      phoneUtil.parse(plusMinusPhoneNumber, "DE");
+      fail("This should not parse without throwing an exception " + plusMinusPhoneNumber);
+    } catch (NumberParseException e) {
+      // Expected this exception.
+      assertEquals("Wrong error type stored in exception.",
+                   NumberParseException.ErrorType.NOT_A_NUMBER,
+                   e.getErrorType());
+    }
+    try {
       String tooShortPhoneNumber = "+49 0";
       phoneUtil.parse(tooShortPhoneNumber, "DE");
       fail("This should not parse without throwing an exception " + tooShortPhoneNumber);
@@ -1339,6 +1402,16 @@
     }
     try {
       String someNumber = "123 456 7890";
+      phoneUtil.parse(someNumber, "CS");
+      fail("Deprecated country code not allowed: should fail.");
+    } catch (NumberParseException e) {
+      // Expected this exception.
+      assertEquals("Wrong error type stored in exception.",
+                   NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
+                   e.getErrorType());
+    }
+    try {
+      String someNumber = "123 456 7890";
       phoneUtil.parse(someNumber, null);
       fail("Null country code not allowed: should fail.");
     } catch (NumberParseException e) {
@@ -1389,6 +1462,20 @@
     }
   }
 
+  public void testParseNumbersWithPlusWithNoRegion() throws Exception {
+    PhoneNumber nzNumber = new PhoneNumber();
+    nzNumber.setCountryCode(64).setNationalNumber(33316005L);
+    // "ZZ" is allowed only if the number starts with a '+' - then the country code can be
+    // calculated.
+    assertEquals(nzNumber, phoneUtil.parse("+64 3 331 6005", "ZZ"));
+    assertEquals(nzNumber, phoneUtil.parse("+64 3 331 6005", null));
+    nzNumber.setRawInput("+64 3 331 6005").
+        setCountryCodeSource(CountryCodeSource.FROM_NUMBER_WITH_PLUS_SIGN);
+    assertEquals(nzNumber, phoneUtil.parseAndKeepRawInput("+64 3 331 6005", "ZZ"));
+    // Null is also allowed for the region code in these cases.
+    assertEquals(nzNumber, phoneUtil.parseAndKeepRawInput("+64 3 331 6005", null));
+  }
+
   public void testParseExtensions() throws Exception {
     PhoneNumber nzNumber = new PhoneNumber();
     nzNumber.setCountryCode(64).setNationalNumber(33316005L).setExtension("3456");
@@ -1472,6 +1559,17 @@
         setCountryCodeSource(CountryCodeSource.FROM_NUMBER_WITH_IDD);
     assertEquals(alphaNumericNumber,
                  phoneUtil.parseAndKeepRawInput("001800 six-flag", "NZ"));
+
+    // Invalid region code supplied.
+    try {
+      phoneUtil.parseAndKeepRawInput("123 456 7890", "CS");
+      fail("Deprecated country code not allowed: should fail.");
+    } catch (NumberParseException e) {
+      // Expected this exception.
+      assertEquals("Wrong error type stored in exception.",
+                   NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
+                   e.getErrorType());
+    }
   }
 
   public void testCountryWithNoNumberDesc() {