Code optimisation: created a function for repeated tasks