
// Map zones via root keys. Zones are centered around root keys. 3 "alt" versions per root key.

sxt.sortZonesByRootKey();

zoneIdx = 0;
loop(numZones)
{
   zone <= sxt.getZoneByIdx(zoneIdx);
   zone.setAlt(true);
   zoneIdx++;
}

if(numZones >= 3)
{
   var zone1 <= sxt.getRootKeyOrderedZoneByIdx(0);
   zone1.setLoKey(1);
   var pzone1 <= zone1;

   var zone2 <= sxt.getRootKeyOrderedZoneByIdx(1);
   zone2.setLoKey(1);
   var pzone2 <= zone2;

   var zone3 <= sxt.getRootKeyOrderedZoneByIdx(2);
   zone3.setLoKey(1);
   var pzone3 <= zone3;

   zoneIdx = 3;

   if(numZones >= 6)
   {
      loop( (numZones - 3) / 3 )
      {
         zone1 <= sxt.getRootKeyOrderedZoneByIdx(zoneIdx);
         zone2 <= sxt.getRootKeyOrderedZoneByIdx(zoneIdx + 1);
         zone3 <= sxt.getRootKeyOrderedZoneByIdx(zoneIdx + 2);

         var root = zone1.getRootKey();
         var proot = pzone1.getRootKey();

         var center = int((root + proot) / 2);

         if((center != proot) && (center != root))
         {
            pzone1.setHiKey(center);
            pzone2.setHiKey(center);
            pzone3.setHiKey(center);
         }
         else
         {
            if(center == root)
            {
               pzone1.setHiKey(root);
               pzone2.setHiKey(root);
               pzone3.setHiKey(root);
            }
            else
            {
               pzone1.setHiKey(root - 1);
               pzone2.setHiKey(root - 1);
               pzone3.setHiKey(root - 1);
            }
         }

         center++;

         if(center < root)
         {
            zone1.setLoKey(center);
            zone2.setLoKey(center);
            zone3.setLoKey(center);
         }
         else
         {
            zone1.setLoKey(root);
            zone2.setLoKey(root);
            zone3.setLoKey(root);
         }

         pzone1 <= zone1;
         pzone2 <= zone2;
         pzone3 <= zone3;
         zoneIdx += 3;
      }

      pzone1.setHiKey(127);
      pzone2.setHiKey(127);
      pzone3.setHiKey(127);
   }
}
