cleaned up spaghetti code