partially rewritten in Swift!