Working code for 3 levels