% Preprocessing für den Partitionsschätzer. Hier werden die Daten
% dimensionsweise auf das Intervall [0,1] gelegt. Nur die Extrema an beiden
% Rändern (in 1/100) werden aus dem Intervall gefiltert.

function [result] = regression_tree(X_l, Y_l, X_t, Y_t, X_eval, Y_eval , minleaf_list)
  
    number_minleaf=length(minleaf_list);
    % und uebferfluessige Variablen loeschen
    
      
    trees=cell(number_minleaf,1);
    errors=zeros(number_minleaf,1);
    levels=zeros(number_minleaf,1);

    parfor ml=1:number_minleaf

        trees{ml}=classregtree(X_l,Y_l,'MinLeaf',minleaf_list(ml));
        
        nsub = 1 + max(trees{ml}.prunelist);
        yfit = treeval(trees{ml},X_t,(0:nsub-1));
        error=sum((yfit-repmat(Y_t,1,nsub)).^2,1);
        [errors(ml) id]=min(error);
        levels(ml)=id-1;
      
    end
    
    [~, best_ml]=min(errors);
    Y_calc=treeval(trees{best_ml},X_eval,levels(best_ml));
%     error=sum((Y_calc-Y_eval).^2);  
%     best_ms=minleaf_list(best_ms);
    best_tree = prune(trees{best_ml},'level',levels(best_ml));
    number_terminal_nodes=sum(sum(children(best_tree),2)==0);
    result.mse=mean((Y_calc-Y_eval).^2);
    result.res=Y_calc-Y_eval;
    result.param=[minleaf_list(best_ml) number_terminal_nodes];
    
    
end

