function [outData] = rpp_block_transform(inData)
% Transform RPP blocks to newer version to ensure backward compatibility
%
% This function is called automaticall after opening an old model.
% See "Make Backward-Compatible Changes to Libraries"
% http://www.mathworks.com/help/simulink/ug/creating-block-libraries.html#brkngxr-6

    fte = inData.ForwardingTableEntry;

    % Fields with underscore cannot be accessed by using '.' operator!
    oldName = getfield(fte, '__slOldName__');
    newName = getfield(fte, '__slNewName__');
    oldVersion = getfield(fte, '__slOldVersion__');
    newVersion = getfield(fte, '__slNewVersion__');

    instanceData = inData.InstanceData;

    if ismember(oldName, {'rpp_lib/General Purpose Digital Output' ...
                          'rpp_lib/General Purpose Digital Input' ...
                          'rpp_gio_out/General Purpose Digital Output' ...
                          'rpp_gio_in/General Purpose Digital Input' }),
        outData = update_gio_pin_name(instanceData);
    end
end


function [outData] = update_gio_pin_name(instanceData)
    outData.NewBlockPath = '';
    outData.NewInstanceData = [];

    % Get the field type 'Name' from instanceData
    [ParameterNames{1:length(instanceData)}] = instanceData.Name;
    port_type_idx = find(strcmp(ParameterNames, 'port_type'));
    pin_number_idx = find(strcmp(ParameterNames, 'pin_number'));

    if (~ismember('pin', ParameterNames))
        instanceData(end+1).Name = 'pin';
        instanceData(end).Value = '---';
    end

    if (~ismember('pin_name', ParameterNames) && ...
        ~isempty(port_type_idx) && ...
        ~isempty(pin_number_idx)),

        instanceData(end+1).Name = 'pin_name';
        instanceData(end).Value = sprintf('%s%s', ...
                                          instanceData(port_type_idx).Value, ...
                                          instanceData(pin_number_idx).Value);

        % Delete old parameters to avoid warnings
        instanceData(arrayfun(@(x) strcmp(x.Name, 'port_type'), instanceData)) = [];
        instanceData(arrayfun(@(x) strcmp(x.Name, 'pin_number'), instanceData)) = [];
    end

    outData.NewInstanceData = instanceData;
end
