function RMS = finitescarperror(x,z,thetadeg,a,ktvec,bdegreevec,offsetvec)

% Returns Root Mean Square (RMS) function for varying morphologic
%   age (kt), far-field slope (bdegreevec), and offset of profile
%   from center of scarp (offsetvec).  Each of the input parameters
%   are:
%
%   x --> distance along measured scarp profile [L].
%   z --> elevation at each point x of the measured profile [L].
%   thetadeg --> initial scarp slope angle [deg].
%   a --> fault scarp offset [L].
%   ktvec --> vector of morphologic ages at which RMS function is
%     computed [L^2].
%   bdegreevec --> vector of far-field slope at which RMS function is
%     computed [deg].
%   offsetvec --> offset of measured profile relative to center of
%     profile, defined by central scarp slope angle [L].
%  
% The output matrix RMS is a m x n x o matrix, with variations in ktvec,
%   bdegreevec, and offsetvec along the m, n, and o dimensions,
%   respectively.

ktveclength = length(ktvec);
bdegreeveclength = length(bdegreevec);
offsetveclength = length(offsetvec);

RMS = zeros(ktveclength,bdegreeveclength,offsetveclength);

total = ktveclength*bdegreeveclength*offsetveclength;
counter = 1;
percounter = 0;

[X,KT,BDEG,OFF] = ndgrid(x,ktvec,bdegreevec,offsetvec);
ZPRED = finitescarp(thetadeg,a,X+OFF,KT,BDEG);
Z = repmat(z',[1 ktveclength bdegreeveclength offsetveclength]);
RMS = sqrt(mean( (Z - ZPRED).^2, 1));
RMS = reshape(RMS,ktveclength,bdegreeveclength,offsetveclength);


%for(i=1:ktveclength)
%   for(j=1:bdegreeveclength)
%      for(k=1:offsetveclength)
%         
%         RMS(i,j,k) = computeRMS(x + offsetvec(k),z,thetadeg,a,ktvec(i),bdegreevec(j));
         
%         if(floor((counter/total)*100) > percounter)
%            percounter = percounter + 1;
%            
%            fprintf('%i  ',percounter);
%         end
         
%         counter = counter + 1;
%         
%      end
%   end
%end

%--
function RMS = computeRMS(x,z,thetadeg,a,kt,bdeg)

Zpred = finitescarp(thetadeg,a,x,kt,bdeg);

RMS = sqrt(mean((Zpred - z).^2));

