function [st,extraVent,heatRecovery,heaterElectric,ok]=advance_tank(st,dm,dt,k,FC_W,etaFC) % Rigid tank: dm<0 is never used; positive mass out carries specific enthalpy. f=k.fluid;extraVent=0;heatRecovery=0;heaterElectric=0;ok=true; old=st.s;m=st.m-dm; U=st.U+k.Qleak_W*dt-dm*old.h_out; if m<=0,error('Tank emptied');end s=r23.state_mu(m,U,k.V_m3,f,old.T_K); if s.p_Pa>k.Pmax_Pa h=s.h_out; hi=min(m*.02,max(m*(s.p_Pa-k.Pmax_Pa)/s.p_Pa,1e-8)); for j=1:20 try,v=vent_residual(hi);catch,v=-1;end if v<=0,break;end hi=min(hi*2,m*.5); end lo=0; for j=1:28 mid=(lo+hi)/2; try,v=vent_residual(mid);catch,v=-1;end if v>0,lo=mid;else,hi=mid;end end extraVent=(lo+hi)/2;m=m-extraVent;U=U-extraVent*h; s=r23.state_mu(m,U,k.V_m3,f,s.T_K); st.out_enthalpy_J=st.out_enthalpy_J+extraVent*h; end if s.p_Paf.pmax||s.T_K