%The farmfiles written here are going to be huge. So, a change needs to be made for saving these...
%in util/farmit.m change the statements with savetest to saveandtest(T.fname, '-v7.3', '-struct', 'T')
%The farmfile writing is going to be extremely slow, so I would advise to 'split' into a smaller subset of files rather than a larger subset.
sernum  = '5901real'
daughter = 'g'

tags1 = get_tags('cmb2017'); 
coaddopt.sernum = sernum;coaddopt.daughter = daughter; 
coaddopt.jacktype=0; coaddopt.coaddtype=2; coaddopt.deproj =[1 1 0 0];
coaddopt.chflags = get_default_chflags('bicep3',2017);

% Reasonable default deprojection
coaddopt.deproj = [1,1,0,0];
% The real data comes along with large cut structures. Don't save these
% over and over again for noise realizations.
coaddopt.save_cuts = false;
% Flip scanset-by-scanset
coaddopt.sign_flip_type = 'by_scanset';

% Figure out the name of the real file to take signal subtraction from.
% See
%   http://bicep.rc.fas.harvard.edu/bkcmb/analysis_logbook/analysis/20140709_SignFlip_SignalSub/
% for more information.
coaddopt0 = coaddopt;
% Always use dp0000 for the subtraction (even subtraction of 1100 doesn't make any difference, see the 
%posting above)
coaddopt0.deproj = [0,0,0,0];
coaddopt0.jacktype = '0';
sigsubfname = 'maps/5901/real_g_filtp3_weight3_gs_dp0000_jack02.mat';%get_map_filename(coaddopt0);
fprintf(1, 'Loading signal-subtraction map from %s...\n', sigsubfname);
sigsubmap = load(sigsubfname, 'ac', 'm');
%Pass along as part of coaddopt, which triggers the signal subtraction
% code path.
coaddopt.ac = sigsubmap.ac;
coaddopt.m  = sigsubmap.m;
clear sigsubmap coaddopt0
%There is an issue with the naming of this file, it is for 2017 data but I had saved it as daughter='h' by mistake.
jack2map = load('maps/5901/real_h_filtp3_weight3_gs_dp1100_jack25.mat', 'coaddopt');

for rlz=1:100
  % Required to have get_map_filename return a map name of '0016_...'
  % instead of 'real_...' given that we still need sernum=='....real'
  % to have the correct pairmaps load.
  coaddopt.sign_flip_rlz = rlz;

  % Setup the random number generator for repeatability
  stream0 = RandStream('mlfg6331_64', 'Seed', rlz);
  RandStream.setDefaultStream(stream0);
  % Then get the sign-flip sequence
  coaddopt.sign_flip_seq = get_sign_flip_seq(jack2map.coaddopt);
  coaddopt = get_default_coaddopt(coaddopt)
%  clear jack2map
%  whos
%  reduc_coaddpairmaps(tags1, coaddopt)
  farm_coaddpairmaps(tags1, coaddopt, ...
      'OnlyMissing', true, ...
      'FarmJacksSeparately', false, ...
      'SplitSubmission', 10, ...
      'UseCompiled', false, ...
      'Realizations', [], ...
      'FarmJobs', true, ...
      'Queue', 'serial_requeue,kovac', ...
      'MemRequire', 50000, ...
      'maxtime', 12*60, ...
      'nice', 10, ...
      'Submit', false);
end
