Massive code-cleanup and re-write!