function [aOutData] = transformLogicBitwiseOperatorBlock(aInData)
%

%  Copyright 2020 The MathWorks, Inc.

% Transformation function for legacy Logic and Bit-operator blocks

    aOutData.NewInstanceData = [];
    aOutData.NewBlockPath = '';

    if ~isfield(aInData, 'InstanceData')
        return;
    end

    aOldInstanceData = aInData.InstanceData;
    aNewInstanceData = aOldInstanceData;

    [iOperatorIdx, iOperandIdx] = getLogicalOperator(aOldInstanceData);
    if isequal(iOperatorIdx, -1) || isequal(iOperandIdx, -1)
        return;
    end

    aOperatorValue = aOldInstanceData(iOperatorIdx).Value;
    aOperandValue = aOldInstanceData(iOperandIdx).Value;
    if (strcmp(aOperatorValue, 'SHIFT_RIGHT') || strcmp(aOperatorValue, 'SHIFT_LEFT'))
        aNewInstanceData(iOperatorIdx).Name = 'BitShiftNumber';
        
        % If the value is something like 'FF'
        if strcmp(aOperandValue(1), '''')
            aOperandValue = num2str(hex2dec(strrep(aOperandValue, '''', '')));
        end
        
        if strcmp(aOperatorValue, 'SHIFT_LEFT')
            aNewInstanceData(iOperatorIdx).Value = ['-(' aOperandValue ')'];
        else
            aNewInstanceData(iOperatorIdx).Value = aOperandValue;
        end
        
        aNewInstanceData(iOperandIdx).Name = 'BinPtShiftNumber';               
        aNewInstanceData(iOperandIdx).Value = '0';
        
        aOutData.NewBlockPath = 'simulink/Logic and Bit Operations/Shift Arithmetic';
    else
        aOutData.NewBlockPath = 'simulink/Logic and Bit Operations/Bitwise Operator';
    end

    aOutData.NewInstanceData = aNewInstanceData;
end

function [iOperatorIdx, iOperandIdx] = getLogicalOperator(aOldInstanceData)
    iOperatorIdx = -1;
    iOperandIdx = -1;
    
    for i = 1:length(aOldInstanceData)
        if (strcmp(aOldInstanceData(i).Name, 'Operator'))
            iOperatorIdx = i;
        elseif (strcmp(aOldInstanceData(i).Name, 'Operand2'))
            iOperandIdx = i;
        end                
    end
end