Updated solution, after undoing small changes