function [X_p, Mxcal, Sxcal]=pretX_miss_0(X, DimX, Pret, ordPret, indblk, Mxcal, Sxcal, reverse);

%% do data pretreatment for 3D array with missing data
%%
%% INPUT
%% X data array
%% DimX sizes of X
%% Pret (mnc = centering; aut= std scaling; blk=blockscaling; non= none; psc = pareto scaling).
%% Pret has as many row as Array modes
%% ordPret is a vector of ord dimension containing the order in which Pret
%% have to be applied with respect to the modes
%% indblk is needed only for blk option, is a structured array indicized
%% per mode
%% Mxcal, Sxcal are structured arrays indicized per mode that contain
%% Mx_cal and Sx_cal (user defined, or for rescaling )
%% reverse= [] scale ; reverse=1 apply given scale; reverse=-1 rescale
%%
%% OUTPUT
%% X_p processed array
%% Mxcal, Sxcal as above
%%
%% misstoolbox required
%% Marina Cocchi Feb 2013
%% [X_p, Mxcal, Sxcal]=pretX_miss_0(X, DimX, Pret, ordPret, indblk, Mxcal, Sxcal, reverse);



ord=length(DimX);
if ~exist('reverse')==1
    Mxcal(ord).Mx_cal=[];
    Sxcal(ord).Sx_cal=[];
    reverse=[];
end
if  isempty(reverse)==1 | reverse==1
    for i=1:ord       
        imode=ordPret(i);
        sc=Pret(imode,1:3);
        
        if sc~='non'
            Mx1=Mxcal(imode).Mx_cal;
            if sc=='mnc' | sc=='aut'| sc=='psc'
                Sx1=Sxcal(imode).Sx_cal;
                [X_p, Mx, Sx]=scal_piu(X, DimX, imode, ord, sc, Mx1, Sx1);
            elseif sc =='blk'  %% BLOCKSCALING
                ind_blk=indblk(imode).indblk;
                nblock=length(unique(ind_blk));
                if isempty(reverse)==1
                    XA=nshape(X,imode)';
                    M_XA=missmean(XA);
                    XM=(XA - ones(size(XA,1),1)*M_XA);
                    SStot=missss(XA);
                    for iblk=1:nblock
                        indb=find(ind_blk==iblk);
                        SSblock(iblk)=missss(XM(:,indb));
                        Sx1(1,indb)=1./(sqrt(SStot./(SSblock(iblk).*nblock)));
                    end                    
                else
                    Sx1=Sxcal(imode).Sx_cal;
                end
                [X_p, Mx, Sx]=scal_piu(X, DimX, imode, ord, sc, Mx1, Sx1);
            end
            X=X_p;
            if nnz(find(Sx==0)) > 0; fprintf('WARNING: some varibales has zero variance in MODE %i',i);end 
            if isempty(reverse)==1 & sc~='non'
                Mxcal(imode).Mx_cal=Mx;
                Sxcal(imode).Sx_cal=Sx;
            end
        else
            X_p=X;
        end
    end
    
elseif reverse==-1%% post processing
    for i=ord:-1:1
        imode=ordPret(i);
        sc=Pret(imode,1:3);
        if sc~='non'
            Mx1=Mxcal(imode).Mx_cal;
            Sx1=Sxcal(imode).Sx_cal;
            X_p=rescal_piu(X, DimX, imode, ord, sc, Mx1, Sx1);
            X=X_p;
        else
            X_p=X;
        end
    end
    
end
