re factor the matching algo