function unexplode_complexSignals_in_portInfo(testcomp)
% Copyright 2019 The MathWorks, Inc.

   mdlFlatIOInfo = testcomp.mdlFlatIOInfo;
   Inport        = mdlFlatIOInfo.Inport;
   Outport       = mdlFlatIOInfo.Outport;
   
   for i=1:length(Inport)
       if portHasComplexSignals(Inport(i).compiledInfo)
           unExplodedCompiledInfo = unexplodeComplexSignalsInCompiledInfo(Inport(i).compiledInfo);
           Inport(i).compiledInfo = unExplodedCompiledInfo;
       end
   end
   
   for i=1:length(Outport)
       if portHasComplexSignals(Outport(i).compiledInfo)
           unExplodedCompiledInfo  = unexplodeComplexSignalsInCompiledInfo(Outport(i).compiledInfo);
           Outport(i).compiledInfo = unExplodedCompiledInfo;
       end
   end
   
   testcomp.mdlFlatIOInfo.Inport  = Inport;
   testcomp.mdlFlatIOInfo.Outport = Outport;
end


function out = portHasComplexSignals(compiledInfo)
    out = false;
    for i=1:length(compiledInfo)
        if strcmp(compiledInfo(i).Complexity, 'complex')
            out = true;
            return;
        end
    end
end

function unExplodedCompiledInfo = unexplodeComplexSignalsInCompiledInfo(compiledInfo)
    unexplodedIndex = 1;

    explodedIndex = 1;
    
    while explodedIndex <= length(compiledInfo)
        isComplexSignal = false;
        if strcmp(compiledInfo(explodedIndex).Complexity, 'complex')
            isComplexSignal = true;
        end
        
        unExplodedCompiledInfo(unexplodedIndex) = compiledInfo(explodedIndex); %#ok<AGROW>
        
        if isComplexSignal
            unExplodedCompiledInfo(unexplodedIndex).Used = ...
                unExplodedCompiledInfo(unexplodedIndex).Used ||...
                compiledInfo(explodedIndex+1).Used; %#ok<AGROW>
                
            explodedIndex = explodedIndex + 2;
        else
            explodedIndex = explodedIndex + 1;
        end
        unexplodedIndex = unexplodedIndex + 1;
    end
end
