function id = preprocPGA(D,lim,stmax,maxmb)

if lim == 0 || stmax == 1
    id = 1:size(D,2);
else

    [k,n] = size(D);
    Do = D;

    % D = diag(1./max(D'))*D;
    mea = (1/k*ones(1,k)*D)';
    for i=1:n
        sig(i,1) = 1/(k-1)*sum((D(:,i)-mea(i,1)).^2);
    end

    % lim = 2.5E-3;
    % lim = 1E-2;

    str = ceil(lim./(sig/max(sig)));

    if stmax>1
        %     stmax = 30;
        id = 1;
        while id(end) < n-1
            cst = min(str(id(end)),stmax);
            cst = min(cst,n-id(end));
            sts = str(id(end)+1:id(end)+cst);
            st = min([stmax min(sts) n-id(end)]);
            id(end+1) = id(end)+st;
        end
    else
        stmax = 5;
        id = 1:size(D,2);
        length(id)*k*8;
        while length(id)*8*k > maxmb*1000000 && stmax<50
            id = 1;
            while id(end) < n-1
                cst = min(str(id(end)),stmax);
                cst = min(cst,n-id(end));
                sts = str(id(end)+1:id(end)+cst);
                st = min([stmax min(sts) n-id(end)]);
                id(end+1) = id(end)+st;
            end
            stmax = stmax+1;
            length(id)*k*8/1000000;
        end
        stmax;
    end
end