Functional version of SA, need refactoring.