improved code as advised