Code cleanup and some refactoring. It even seems to keep working as it used to