Updated code to reduce function complexity.