+# Loop over the mappings, trying to assign each country to the
+# nearest server, but subject to the bandwidth limits;
+foreach my $mapping (sort { $b->{priority} <=> $a->{priority} || $a->{distance} <=> $b->{distance} } @mappings)
+{
+ my $country = $mapping->{country};
+ my $server = $mapping->{server};
+
+ if ($country->{bandwidth} <= $server->{bandwidth} && !exists($country->{server}))
+ {
+ $country->{server} = $server;
+ $server->{bandwidth} = $server->{bandwidth} - $country->{bandwidth};
+ }
+}
+
+# Loop over the mappings again, assigning anything that is left
+# as best we can, and allowing bandwidth limits to be exeeded
+foreach my $mapping (sort { $b->{priority} <=> $a->{priority} || $a->{distance} <=> $b->{distance} } @mappings)
+{
+ my $country = $mapping->{country};
+ my $server = $mapping->{server};
+
+ $country->{server} = $server unless exists($country->{server});
+}
+
+# Open output files