Added error checking for copy and refectored code into a function