function [dataOut MaxVal MinVal] = DoEScaleData(dataIn,MaxVal,MinVal,direction)
% DOESCALEDATA normalizes data into the interval [MinVal,MaxVal]. Direction 'f' specifies the
% 'forward' normalization, 'b' specifies the 'backward' scaling of the data set 'dataIn'.
%
%
% [dataOut MaxVal MinVal] = DoEScaleData(dataIn,MaxVal,MinVal,direction)
%
%
% INPUT
%
%   dataIn:        N x p   Incoming data matrix.
%   MaxVal/MinVal  1 x p   Max/min values for normalization/scaling. If empty, normalization to interval [0,1].  
%   direction:     string  'f': forward normalization (default), 'b': backward scaling of dataIn.
%
%
% OUTPUT
%
%   dataOut:       N x p   Outgoing data matrix.
%   MaxVal/MinVal  1 x p   Max/min values for normalization/scaling.     
%
%
% HiLoMoTDoE - Nonlinear System Identification Toolbox for Design of Experiments
% Geritt Kampmann & Benjamin Hartmann, 05-April-2012
% Institute of Mechanics & Automatic Control, University of Siegen, Germany
% Copyright (c) 2012 by Prof. Dr.-Ing. Oliver Nelles


if nargin == 1
    MaxVal = max(dataIn,[],1);
    MinVal = min(dataIn,[],1);
    direction='f';
end
if nargin==3
    direction='f';
end

if isempty(dataIn)
    
    dataOut=[];

else
    
    [nRows,nCols]=size(dataIn);
    
    if nCols~=max(size(MaxVal)) || nCols~=max(size(MinVal)) || min(size(MaxVal))~=1 || min(size(MinVal))~=1
        error('hilomotDoE:DoEScaleData','Incorrect vector length for MaxVal or MinVal')
    end
    
    dataOut=zeros(nRows,nCols);
    
    if direction=='f'
        for count=1:nCols
            scaleFactor=1/(MaxVal(count)-MinVal(count));
            dataOut(:,count)=(dataIn(:,count)-MinVal(count))*scaleFactor;
        end
    elseif direction=='b'
        for count=1:nCols
            scaleFactor=1/(MaxVal(count)-MinVal(count));
            dataOut(:,count)=dataIn(:,count)/scaleFactor+MinVal(count);
        end
    else
        error('hilomotDoE:DoEScaleData','Unknown value for direction!')
    end
    
end
end