Fix for PHP<5.3 and minor refactoring