%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [X_p, Mx_cal, Sx_cal]=scal(X,DimX,imod,ord,sc,Mx_cal,Sx_cal)

if sc=='mnc'
    %%% centering across one mode
    %% ND - 2D
    [Xf, dimXf]=nshape(X,imod);
    if isempty(Mx_cal)==1
        Mx_cal = missmean(Xf);
    end
    for i=1:dimXf(1)
        XM(i,:)=Xf(i,:)-Mx_cal;
    end
    %%% 2D - ND
    Xback=reshape(XM,dimXf);
    for i=1:ord;
       try
           ind(i)=find(DimX(i)==dimXf);
       catch
           ind(i)=i;
       end
    end
    X_p=permute(Xback,ind);
elseif sc=='aut' |sc== 'blk'|sc=='psc'
   %%%%% scaling within a mode
   %% ND - 2D
   [Xf, dimXf]=nshape(X,imod);
   Xs=Xf';
   if isempty(Sx_cal)==1
       Sx_cal=missstd(Xs);
   end
   if sc=='aut'| sc=='blk'
       XA=Xs./(ones(size(Xs,1),1)*Sx_cal);
   elseif sc=='psc'
       XA=Xs./(ones(size(Xs,1),1)*sqrt(Sx_cal));
   end
   %% 2D - ND
   Xback=reshape(XA',dimXf);
   for i=1:ord;
       ind(i)=find(DimX(i)==dimXf);
   end
   X_p=permute(Xback,ind);
end
%%%%%%            
%%%%%%
