Working code (with incomplete commenting)