Major cleanup of code [Final merge fix]