close all;

% Now read all data files and plot the results
dataDirectory = '../../5-problems/swift/';
triggerListDirectory = '../../5-problems/';
triggerList = fileread([triggerListDirectory,'triggers.txt']);
triggerList = strsplit(triggerList,'\n');
missingFileCounter = 0;

% first read data from files and put them all in a single Cell array:

if exist('MyDataCell','var')
    warning('data cell array already exists in MATLAB environment. Using the available data...');
else
    MyDataCell = cell(1,length(triggerList));
    for i = 1:length(triggerList)
        disp(['reading data from file number ', num2str(i)]);
        filePath = [dataDirectory,'GRB',triggerList{i}(1:end-1),'_ep_flu.txt'];
        if exist(filePath,'file')
            %MyDataCell{i} = importdata(filePath); %,'headerlinesIn',1);
            MyDataCell{i} = readtable(filePath);
            MyDataCell{i} = table2array(MyDataCell{i});
            if isfield(MyDataCell{i},'data')
                MyDataCell{i} = MyDataCell{i}.data;
            end
        else
            missingFileCounter = missingFileCounter + 1;
            disp(['missing file detected: #', num2str(missingFileCounter)]);
        end
    end
end

% now plot the data:

figure(); hold on; box on;
eventCounter = 0;
for i = 1:length(triggerList)
    disp(['plotting data from file number ', num2str(i)]);
	if ~isempty(MyDataCell{i}) && all(MyDataCell{i}(:,2)<0)
        eventCounter = eventCounter + 1;
        scatter( exp(MyDataCell{i}(:,2)) ...
                , MyDataCell{i}(:,1) ...
                , 1 ...
                , 'MarkerFaceColor', 'red' ...
                , 'MarkerEdgeColor', 'red' ...
                , 'MarkerFaceAlpha', .01 ...
                , 'MarkerEdgeAlpha', .01 ...
                );
	end
end
set( gca ...
   , 'xscale','log' ...
   , 'yscale','log' ...
   , 'xlim', [1e-8 1e-1] ...
   );
xlabel( 'Fluence [ ergs/cm^2 ]' ...
      , 'interpreter', 'tex' ...
      , 'fontsize', 12 ...
      );
ylabel( 'E_{peak}' ...
      , 'interpreter', 'tex' ...
      , 'fontsize', 12 ...
      );
title( ['Plot of E_{peak} vs. Fluence for ', num2str(eventCounter), ' Swift GRB events' ] ...
     , 'interpreter', 'tex' ...
     , 'fontsize', 12 ...
     );
saveas( gcf ...
      , 'SwiftDataPlot.png' ...
      );