Extracted more logic out into functions