Fix crash and further refine code

Authored by akhilkgangadharan on Mar 19 2019, 1:27 PM.