This method is insanely long.  It should be broken into different methods.  Handling the different types (sets vs set) should absolutely be in it's own method and possibly use duck typing.  Given that you'll call multiple methods, I'd recommend that you make this an instance method and not a class method.