function [Jstr,group,finDiffFlags,alpha] = spFinDiffSetup(Jstr,finDiffFlags,alpha)
%

%SPFINDIFFSETUP Prepare data for sparse finite differences
%
%   [Jstr,group,finDiffFlags,alpha] = spFinDiffSetup(Jstr,finDiffFlags,alpha)
%   prepares the Jacobian structure (Jstr), the column groups (group), the
%   needed flags (finDiffFlags), and column scales (alpha).
%

%   Copyright 2017 The MathWorks, Inc.

if finDiffFlags.sparseFinDiff
    % Determine coloring/grouping for sparse finite-differencing
    n = size(Jstr,2);
    p = colamd(Jstr)';
    p = (n+1)*ones(n,1)-p;
    group = color(Jstr,p);
    
    finDiffFlags.scalealpha = false;
    
    ncol = max(group);
    if isempty(alpha)
        finDiffFlags.scalealpha = true;
        alpha = repmat(sqrt(eps),ncol,1);
    end
    
    % Setup the structure for each iteration
    Jstr = spones(Jstr);
    
    % Override and use dense finite-differences if the group encompasses
    % all columns
    finDiffFlags.sparseFinDiff = ncol < n;
else
    group = [];
end