% Common function to check the format of sldvData and report errors.
function sldvdata = loadAndCheckSldvData(data)
%

%   Copyright 2013-2021 The MathWorks, Inc.

    if ischar(data) || isstring(data)
        if (exist(data, 'file') == 2)
            try
                data = load(data);
                if(isfield(data, 'sldvData'))
                    sldvdata = data.sldvData;
                else
                    error(message('Sldv:RptGen:InvalidSldvData', data));
                end
            catch MEx
                error(message('Sldv:RptGen:CannotLoadFile', data));
            end
        else
            error(message('Sldv:RptGen:DataNotFound', data));
        end
    else 
        sldvdata = data;
    end
   
    if ~isstruct(sldvdata)
        error(message('Sldv:RptGen:StructExpected'));
    end
    
    isLoggedSldvData = isfield(sldvdata,'LoggedTestUnitInfo');
    if isLoggedSldvData
        error(message('Sldv:RptGen:InvalidSldvDataLogged'));
    end
    
    isDerivedSldvData = isfield(sldvdata,'DerivedDataInfo'); 
    if isDerivedSldvData
        error(message('Sldv:RptGen:InvalidSldvDataMerged'));
    end
        
     if ~isfield(sldvdata,'AnalysisInformation')
        error(message('Sldv:RptGen:Missingfield', 'AnalysisInformation'));
    end

    if ~isfield(sldvdata,'ModelObjects')
        error(message('Sldv:RptGen:Missingfield', 'ModelObjects'));
    end

    if ~isfield(sldvdata,'Objectives')
        error(message('Sldv:RptGen:Missingfield', 'Objectives'));
    end  
    
    if ~isfield(sldvdata,'Version') || ...
            Sldv.DataUtils.dataVersionLessThan(sldvdata,'1.3')  
        error(message('Sldv:RptGen:InvalidSldvDataLoggedBeforeR2008b'));
    elseif Sldv.DataUtils.dataVersionLessThan(sldvdata,'1.7')  
        sldvdata.Constraints = [];
    end
    
    sldvdata = Sldv.DataUtils.updateObjectiveStatuses(sldvdata);    
    
end
