previous code was just working out the logic. i've edited to make it a function