Moved much of the logic to a pm for testability