Modified code according to comments