Phasing

I've rewritten phasing and updated it to merge with the current code.