Incorporating some changes from tobyweston