Mainly patch from James Teh