The code in this method is rather complex. It should be refactored into smaller methods in order to keep it maintainable.