function saveAndCheckArgs(fileName, varargin)
% Author: saurabh.me@gmail.com (Saurabh Singh)

names = cell(1, length(varargin));
for i = 1 : length(varargin)
  names{i} = inputname(1 + i);
end

maxIter = 5;
pauseInterval = 10;
done = false;
for i = 1 : maxIter
  saveToFile(fileName, names, varargin);
  for j = 1 : maxIter
    try
      load(fileName);
      done = true;
      break;
    catch exp
      % Try again.
      pause(pauseInterval);
    end
  end
  if done
    break;
  end
end
end

function saveToFile(fileName, names, args)
for i = 1 : length(names)
  eval(sprintf('%s=args{%d};', names{i}, i));
  if i == 1
    save(fileName, names{i});
  else
    save(fileName, '-append', names{i});
  end
end
end