Performance enhancements by Sergey Kudinov ($sortbegin/$sortend).