Significant re-write of the code