Rewrite algorithm to clean up logic and make internal logic synchronous.