function [nl,ns,ri] = runlength(x,R)
%function [l,s] = runlength(x,R)
%
% Parses the vector x into "runs" of constant value.
% 
% x   - row or column vector
% R   - maximum run length, lengths greater than this get split evenly
%
% l   - length of run
% s   - value of run
%
% Nathan Steiger, LDEO, Nov 2018


sx = size(x);
x = x(:)';                      % force x to be row vector

%---------------------
% FIGURE OUT THE RUNS
%---------------------

% mx marks with 1 all the places where a run begins in x
mx = [1;diff(x(:))]~=0;
% l are the run lengths
l = diff([find(mx);length(x)+1])';
% s are the values at the beginning of each run
s = x(mx);

% Get indices of runs and add end point
r0=[find(mx);length(x)];

% Find how to break up long lengths
dvsr=ceil(l/R)+1;

nr0=[];
for i=1:length(l)
   nr0=cat(2,nr0,round(linspace(r0(i),r0(i+1),dvsr(i))));
end

% New indices
nr=unique(nr0); % take away linspace end points
ri=nr(1:end-1); % remove end point

% Get the new length of runs
nmx=zeros(sx);
nmx(ri)=1;
nl = diff([find(nmx);length(x)+1])';

% Get the new values of runs
ns=x(ri);



