function status = check_shot_preparation(shot,verbose)
% function status = check_shot_preparation(shot[,verbose])
% Checks whether shot preparation steps were done in the correct order
% For -1 shot, checks whether the PCS tree data is more recent than the previous shot
% Returns status=1 if everything is ok

if nargin<2, verbose = true; end

% Addresses of nodes to query
addresses = {'\pcs::mgams.data:*',...
             '',...
             '\pcs::mgams.mga:*',...
             '\pcs::top.physics.***'...
             '\pcs::top.loadables.***'};

% Labels referring to each node family
labels = {'MGAMS','FBTE','MGA','PHYSICS','LOADABLES'};

nitem   = numel(labels);
time    = cell(1,nitem);
timenum = NaN(1,nitem);

mdsopen('pcs',shot);
fbtver = upper(deblank(mdsvalue('get_fbte_version()')));
switch fbtver
  case 'FBTE',   addresses{2} = '\pcs::mgams.fbte:*';
  case 'FBTE.M', addresses{2} = '\pcs::mgams.equil:*';
  otherwise, error('FBTE version not recognized: %s', fbtver);
end
for ii = 1:nitem
  time{ii} = mdsvalue('TIMES(MAXVAL(getnci($1,"TIME_INSERTED")))',addresses{ii});
  timenum(ii) = Node.datenum_dum(time{ii});
end

status = issorted(timenum); % assumes ascending
if verbose 
  if ~status
    fprintf('\rWARNING: The age of the data in the PCS tree does not match the standard preparation procedure\n');
  end
  
  str = cell(1,nitem+1);
  
  format = ' %01d % 15s % 1s %s';
  str{1} = sprintf(format,0,'Standard order','','Time inserted');
  for ii = 1:nitem
    if ii < nitem && timenum(ii) >= timenum(ii+1)
      fprintf('\r===> %s data is posterior to %s data\n',labels{ii},labels{ii+1});
      s = 'X';
    else
      s = '';
    end
    str{ii+1} = sprintf(format,ii,labels{ii},s,time{ii});
  end
  if (shot>0 && shot<100000)
    str{ii+2} = sprintf(format,ii+1,'SHOT','',mdsvalue('tcv_shot_time($)',shot));
  end
  fprintf('\r%s\n',str{:});
  
end
  
if shot == -1
  shot_prev = mdsopen(0);
  prev_time = mdsvalue('tcv_shot_time($1)',shot_prev);
  [tmax,imax] = max(timenum);
  if tmax < Node.datenum_dum(prev_time) && verbose
    fprintf('\rWARNING: The data in the PCS tree seem to be older than the previous shot (#%05d)\n',shot_prev);
    format = '\r% 30s: %s\n';
    fprintf(format,'Last update of the PCS tree',time{imax});
    fprintf(format,'Time of last shot',prev_time);
  end
end

end

