This method is very long and nested, could you split them up in some smaller methods. Would be easiery to read and also to write tests.