In-progress commit.
Emergency commit as I don't want to lose the results of hours of hacking through Moodle core libs.