revised after seeing solution