improved code and added explanation