making logic more robust and adding some comments