Modified logic and moved code into separate functions.