Significantly cleaned up code