function [m,d]=combineDMC(varargin)
%function [m,d]=combineDMC(FileName1,FileName2,[OutputfileName])
%
%Combines the data in two Monte Carlo result files
%first checks to see if the files used the same model!

if or(length(varargin)<2,length(varargin)>3)
   error('Need at least two parameters with an optional third one for output file')
else
   FileName1 = varargin{1};
   FileName2 = varargin{2};
   if length(varargin)==3
      OutputfileName = varargin{3};
   else
      OutputfileName = '';
   end
end

disp(['Loading ',FileName1,'...']);
[m1,d1] = examineDMC(FileName1);
disp(['Loading ', FileName2, '...']);
[m2,d2] = examineDMC(FileName2);

disp('Combining... ');

names1 = fieldnames(m1);
names2 = fieldnames(m2);
namesd1 = fieldnames(d1);
namesd2 = fieldnames(d2);

if strcmp(char(names1),char(names2)) & strcmp(char(namesd1),char(namesd2))
   for i = 1:size(names1,1)
      if ~(eval(['m1.'names1{i}])==eval(['m2.'names1{i}]))
         error('Models not the same parameters')
      end
      %models must be the same so combine the data.
      d = d1;
      for i = 1:size(namesd1,1)
         if or(strcmp(namesd1(i),'Field'),or(strcmp(namesd1(i),'SurfaceR'),strcmp(namesd1(i),'SurfaceO')))
            eval(['d.',namesd1{i},'=[d.',namesd1{i},',d2.',namesd1{i},'];'])
         else
            eval(['d.',namesd1{i},'= d.',namesd1{i},'+d2.'namesd1{i},';'])
         end
      end
   end
else
   error('Models or data fields not the same')
end

if ~isempty(OutputfileName)
   %save resulting combination
   ProgressP= round((d.NumPhotonsSoFar/m1.NumPhotons)*100);
   OutputfileName = [OutputfileName, ' ',num2str(ProgressP),'%.dmc'];
   fwriteid = fopen(OutputfileName,'w');
   if (fwriteid == -1) 
      error('Error trying to open file for binary writing');
   else
      %*****************************************************************************
      [outcount,expectedcount] = WriteDMCFile(fwriteid,m1,d);
      %*****************************************************************************
      status = fclose(fwriteid);
      if outcount < expectedcount
         error(['Error writing file ',num2str(count),' writen of ',expectedcount,' expected']);
      else
         disp(['Output file ',OutputfileName, ' ',num2str(ProgressP),'%.dmc writen']);
      end
   end
end


