Restructures and cleans up code