Hopefully stamped all bugs. May be able to optimise further though