Re-write of many ideas in the code. Some optimizations. Magic numbers removed.