Partially refactored to functional programming paradigm, work in progress.