function [trn_img,tst_img] = load_blflagged_data(parms, trn_orig, tst_orig,keep_nans)
%
% Add 'flag' features that note the existance of a missing feature
% flag is added for each block of data, where blocks are found
% automatically from teh data
% 
% (C) Gal Chechik 2005
  
  % Init
  if exist('keep_nans','var')==0, keep_nans=0;end;
  [parms,do_force]   = take_from_struct(parms,'do_force', 0);
  n_trn = size(trn_orig); 
  [n_tst,n_features] = size(tst_orig); 
  
  % Try to load from file 
  filename = set_filenames('fild',parms);
  vars = {'trn_img','tst_img'};
  [do_calc, trn_img, tst_img] = cond_load(filename, do_force, vars{1:end});
  if do_calc<1, return; end
  
  data = [trn_orig;tst_orig];
  miss = isnan(data);  
  
  flagged = zeros(n_trn+n_tst,n_features+4);
  flagged(:,1:n_features) = data;

  ncols = size(data,2);
  different  = zeros(1,ncols);
  for col=2:ncols
     if(any(miss(:,col) ~= miss(:,col-1)))
       different(col)=1;
     else
       different(col)=0;
     end
  end    
  fff = find(different)-1;
  
  blocks{1} = 1:fff(1);
  for i=1:length(fff)-1
    blocks{i+1} = (fff(i)+1:fff(i+1));%#ok
  end
  
  for i=1:size(data,1)
    for i_block=1:length(blocks)
      isn = miss(i,blocks{i_block});
      if 0
      elseif(all(isn==1))
	flagged(i,n_features+i_block)=1;
      elseif(all(isn==0))
	flagged(i,n_features+i_block)=0;
      else
	error('Error in blocked flagged data i=%d, i_block=%d\n',i,i_block);
      end    
    end
  end
  if keep_nans
    fprintf('skip filling NaNs with zeros\n');
  else
    flagged(isnan(flagged))=0;
  end

  trn_img = flagged(1:n_trn,:);
  tst_img = flagged(n_trn+1:end,:);

  % Check if useful to sparsify
  sparse_ratio = nnz(flagged) / numel(flagged);
  if(sparse_ratio<0.7)
    trn_img = sparse(trn_img);
    tst_img = sparse(tst_img);    
  end

  % Check if can be translated to uint
  %tmp = uint8(trn_img);
  %if (all(all(double(tmp))) == trn_img)
  %   trn_img = uint(trn_img);
  %   tst_img = uint(tst_img);
  %end

  % Save to disk  
  fprintf('Save file "%s".\n',filename);
  save(filename,'trn_img','tst_img');
  return
end