function mout=tmpcummax(mat,dim);
  if nargin<2;
    dim=1;
  endif

  
  ## Index logic.
  sz=szrem=size(mat);
  nsz=length(sz);
  ndim=sz(dim);
  szrem(dim)=[];
  nrest=prod(szrem);
  n=prod(sz);
  fullindices=indices1= ((1:ndim)'*ones(1,nrest))(:);
  indicesrest=natrixindexdecomposemy((ones(ndim,1)*(1:nrest))(:),szrem);
  if (dim>1);
    fullindices=[indicesrest(:,1:(dim-1)) fullindices];
  endif
  if dim<nsz;
    fullindices=[fullindices indicesrest(:,dim:end)];
  endif
  fullindices=reshape(natrixindexcomposemy(fullindices,sz),[ndim nrest]);

  ## Now, we have the indices, now we just need to do our simple loop.
  
  mout=mat;
  for ii=2:rows(fullindices);
    mout(fullindices(ii,:))=max(mout(fullindices(ii,:)),mout(fullindices(ii-1,:)));
  endfor

endfunction

