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

if sc=='mnc'
    %%% sum offset across one mode
    %% ND - 2D
    [Xf, dimXf]=nshape(X,imod);
    for i=1:DimX(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' | 'blk'| sc=='psc'
   %%%%% rescaling within a mode
   %% ND - 2D
   [Xf, dimXf]=nshape(X,imod);
   Xs=Xf';
   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
%%%%%%            
%%%%%%
