function [t_new, x_new, time, cancelFlag] = makemonotone(depth,age,ageerror,...
    interp_scale,M,interp_method)
% MAKEMONOTONE emulates monotonous MC age-depth relationships for the
% dating table (depth age ageerror) and the given interpolation
% preferences.

% output variables:
% t_new - M realisations of the ages in the age model  
% x_new - M realisations of the depths in the age model
% time  - M realisations of interpolated time axis for the proxy record

    N = length(ageerror);
    varnce = 1;
    i = varnce*randn(N, M);
    
    if size(age,2) == 1
        t_new = repmat(age, 1, M) + repmat(ageerror, 1, M) .* i; 
        x_new = repmat(depth, 1, M) + .1 * randn(N, M)/2;              
    elseif size(age,2) == 2        
        ncolsa = 2;
        idx = find(diff(age,1,2));
        if ~isempty(idx)
            n = 2^(size(idx,1));
            mu_ = repmat(age,1,n/ncolsa);
            sd_ = repmat(ageerror,1,n/ncolsa);
            for m = 1:numel(idx)
                k = 2^m;
                k_ = size(mu_,2)/k;
                for j = 1:k
                    colstart = 1 + (j-1)*k_;
                    colend = colstart + k_ -1;
                    mu_(idx(m),colstart:colend) = age(idx(m),mod(j,ncolsa)+1);
                    sd_(idx(m),colstart:colend) = ageerror(idx(m),mod(j,ncolsa)+1);
                end
            end
            alpha = linspace(0,1,n+1)';
            sel = rand(1,M);
            t_new = zeros(N,M);
            for m = 1:n
                t_tmp = repmat(mu_(:,m), 1, M) + repmat(sd_(:,m), 1, M) .* i;
                t_new(:,alpha(m)<sel&sel<alpha(m+1)) = t_tmp(:,alpha(m)<sel&sel<alpha(m+1));
            end
            clear t_tmp
        else
            age = age(:,1);ageerror = ageerror(:,1);
            t_new = repmat(age, 1, M) + repmat(ageerror, 1, M) .* i;
        end
        x_new = repmat(depth, 1, M) + .1 * randn(N, M)/2;        
    else
        error('The age data has to be one- or two-column matrix')
    end
    
    time = interp1(depth, t_new, interp_scale,interp_method,'extrap');
	
        
    k=1; % no of non-reversed trajectories for MC simulation
    agerev=0; % no of simulated agedepth trajectories that were reversed
    
%    if ~isoctave
%        h = waitbar(0,'MonteCarlo Simulation running ... please wait.','CreateCancelBtn',...
%            'setappdata(gcbf,''canceling'',1)');      
%    else
%        h = waitbar(0,'MonteCarlo Simulation running ... please wait.');
%    end
    
%    cancelFlag = 0;
%    setappdata(h,'canceling',0);
    
    
    while k < M+1
%        % cancel computation
%        if getappdata(h, 'canceling');
%            cancelFlag = 1;
%            break
%        end 
%        
%        waitbar(k/(M+1))      
               
        monoton=false;
        while ~monoton,
            time(:,k) = interp1(depth, t_new(:,k), interp_scale,interp_method,'extrap');      %cubic interpolation of MC simulated depth error
            
            % check monotonicity
            if all(diff(time(:,k))>=0)
                monoton=true; % OK
                k = k+1;
            else 
                agerev = agerev+1; %number of reversed MC ages
                if size(age,2) == 1 || isempty(idx)
                    t_new(:,k) = age + ageerror .* randn(N,1) .*varnce;
                elseif size(age,2) == 2  && ~isempty(idx)
                    sel = rand();
                    t_tmp = zeros(N,n);
                    for m = 1:n
                        t_tmp(:,m) = mu_(:,m) + sd_(:,m) .*randn(N,1).*varnce;
                    end
                    idx_ = find(alpha>sel,1,'first');
                    t_new(:,k) = t_tmp(:,idx_-1);
                end
                x_new(:,k) = depth + .1 * randn(N, 1)/2; 
                monoton=false; % try again
%                 if agerev > 10000, monoton=true;k = M+1;end
                if agerev==100000, 
                    k,
                    warning('difficult to ensure monotonicity of the agemodel: reversal or bottleneck?');end
                if agerev > 100000000, 
                    k,
                    error('100 Mio tries, monotonous age-depth relationship for dating data difficult to ensure. Reverse age-depth relationship.');end
            end

        end
        
    end
%    delete(h)
%    if cancelFlag
%        disp('Simulation canceled')
%    else
%        disp('No of reversed tries:')
%        disp(agerev)        
%    In total: agerev 'reversals'
%    end
%    In total: agerev 'reversals'
end
