function s = gas_params_bd(k)
% GAS_PARAMS_BD Converts gas trace into lists of parameters
%
% Looks for times < 0.01s
% Looks if there are two separate time interval with x>0
% If yes, 1st -> valve unsticking bit
%         2nd -> prefill keeps level at t=0 and adjust duration to keep the
%         same amount of injected gas
% If there is a time between t=0 and t=0.01, this is the postfill
% else postfill=prefill
%
% See also: gas_trace_bd

if nargin < 1, k = 2; end

dt = 1e-3;

s.t_valve = NaN;
s.w_valve = NaN;
s.h_valve = NaN;
s.w_prefill = NaN;
s.h_prefill = NaN;
s.t_postfill = NaN;
s.h_postfill = NaN;

global MGgas

gas_ref = MGgas(k);

mask = gas_ref.t <= 0.01;
to   = gas_ref.t(mask);
xo   = gas_ref.x(mask);

if numel(to) < 2
  to = [-1,0];
  xo = [0,0];
end
t = unique([to(:);0]);
x = interp1(to,xo,t,'nearest','extrap');

% Look for separate gas puffs
istart = find(diff(x==0) == -1); % diff=-1 means the signal goes from 0 to not 0.
npuffs = numel(istart);

if npuffs > 2
  error('The gas trace has more than 2 puffs for t<0, aborting ...');
elseif npuffs == 0
  error('The gas trace has no puff for t<0, aborting ...');
elseif npuffs == 2
  iend = find(diff(x==0) == 1); % diff=1 means the signal goes from not 0 to 0.
  s.t_valve = t(istart(1));
  s.w_valve = t(iend(1)) - t(istart(1)) - dt; % Width of the valve unsticking
  % Height of the valve unsticking keeping integral constant
  mask_v = istart(1):iend(1)+1;
  s.h_valve = trapz(t(mask_v),x(mask_v))/(s.w_valve+dt);
end
% Here npuffs=1 or 2 and the last one is the prefill
iend = find(t==0,1);
s.w_prefill = 0-t(istart(end));
% Height of the prefill keeping integral constant
mask_p = istart(end):iend;
s.h_prefill = trapz(t(mask_p),x(mask_p))/(s.w_prefill-dt*0.5);

% Postfill
ipo = find(t>0,1,'first');
if ~isempty(ipo)
  s.t_postfill = t(ipo);
  s.h_postfill = x(ipo);
else
  s.t_postfill = 1e-3;
  s.h_postfill = s.h_prefill*(1+1e-2); % Minimum difference so that the points are different in MDS (may not work)
end

end