updated code as per dan's comment