Nicked some more code from the old system (still needs to be updated).