function exitflag = check_state_validity(x,g,v,model)
% #codegen

% -1: all ok
% 3: NaNs
% 5: negative temperature
% 6: negative dpsi/drho
% 7: negative ne or ni
% 8: negative q on axis

te = [eval_te(x,g,v,model,false);eval_te(x,g,v,model,true)];
ti = [eval_ti(x,g,v,model,false);eval_ti(x,g,v,model,true)];
psip = [eval_psip(x,g,v,model,false);eval_psip(x,g,v,model,true)];
ne = [eval_ne(x,g,v,model,false);eval_ne(x,g,v,model,true)];
ni = [eval_ni(x,g,v,model,false);eval_ni(x,g,v,model,true)];
q  = [eval_q(x,g,v,model,false);eval_q(x,g,v,model,true)];

if any(isnan(x))
  exitflag = 3; % invalid due to nans
elseif any(te<0) || any(ti<0)
  exitflag = 5; % negative electron or ion temperature
elseif any(psip<0)
  exitflag = 6; % negative dpsi/drho
elseif any(ne<0) || any(ni<0)
  exitflag = 7; % negative electron or ion density
elseif q(1)<0
  exitflag = 8; % negative q on axis
else
  exitflag = -1; % stay in newton iterations
end
return