Finalized Charles' intensive code with bug fixes.