function state = addFluxDensityToState(state)
% addFluxDensityToState Internal helper to compute curl of state and add as
% NormFluxDensity to state struct. For nonlinear magnetostatics

% Copyright 2022 The MathWorks, Inc.

if isempty(state) || isempty(fieldnames(state))
    % state may be empty, or may be a struct with no fields if
    % there is no state
    return
end
if size(state.u,1) == 2
    % magnetization uses system size of 2, so reset state to
    % pass scalars into function handles
    state.u = state.u(1,:);
    state.ux = state.ux(1,:);
    state.uy = state.uy(1,:);
end
if size(state.u,1) == 1
    state.NormFluxDensity = sqrt(state.ux.^2 + state.uy.^2);
else
    state.NormFluxDensity = sqrt((state.uz(2,:) - state.uy(3,:)).^2 + ...
                                 (state.uz(1,:) - state.ux(3,:)).^2 + ...
                                 (state.ux(2,:) - state.uy(1,:)).^2);
end
end
