Completely rewritten PHP OOP version