Merged James's code