Seemingly working solution
More robust solution