Updated code logic for much more robustness