Code refactored, most of it rewritten in Swift