significantly cleaned up code