updated code as per comments