Make code more robust and cleaner with minor changes