improved code according to comments