function [m_CV,ord_valid] = oe_with_CV(Data,MaxOrder)
% [m_CV,ord_valid] = oe_with_CV(Data,MaxOrder)
%    Estimate oe model of several orders and choose the order by
%    Cross-Validation
%    Data: The input-output data
%    MaxOrder: All orders up to MaxOrder are tested
%    m_CV: the chosen model
%    ord_valid: the chosen model order
%
%    The model calculations are done under the information that we start from
%         zero initial conditions



[N,ny,nu]=size(Data);
Nhalf = ceil(N/2);
% Estimation Data and Validation Data:

Est = Data(1:Nhalf);
Val = Data(Nhalf:end);

%first estimate oe models of many orders

%MaxOrder = 30;
for Order=1:MaxOrder
    try
    m{Order} = oe(Est,[Order*ones(1,2*nu),ones(1,nu)],'ini','z');
    catch % Order was too big
        m{Order} = m{1};
    end
end

% Validate their average prediction performance on Validation Data:
for k=1:MaxOrder
    for ph = 1:20
        [~,fitt]=compare(Val,m{k},ph,'ini','z');
        fit(ph,k)=max(fitt,-inf);
    end
    validfit(k) = mean(fit(:,k));
end

[~,ord_valid] = max(validfit);

m_CV = oe(Data,[ord_valid*ones(1,2*nu),ones(1,nu)],'ini','z');
