Fixes ported from PHP

Signed-off-by: Nick Brook <nick.brook@ratemyplacement.co.uk>