Fixed to work again, cleaned up code