% plotCNzero.m
% 
% Plot the C/N_0 and Yield compared to Base Station of the standard
% Rover and the GIE receiver. Plot these individually for each SV and
% save all the plots as PNG files. 
% 
% Vivek Nadkarni
% Trimble
% June 11, 2004
function plotCNzero
%% Load files
close all; 
loadData;
pause on; 
printPlots = 1; % save to PNG format
plotFigS   = 1; % generate individual plots by SV
plotFigC   = 1; % generate composite plot of all SVs
printStats = 1; % print out statistics

% newSplitFigure; 
% return; 

% Create several figures - some for plotting everything together
% and some for plotting each SV separately.
labelFileNames = strrep(fileNames, '_', '\_');

% Time duration
hrs = floor(duration/3600);
mins = floor((duration - hrs*3600)/60);
xlimits = [startTime - duration*0.02, endTime + duration*0.02];
xText = xlimits(2)+duration*0.025;

if (plotFigS)
  % Separate figures by satellite
  [hTopSubplotS, hBottomSubplotS, hFigS] = newSplitFigure;
end
if (plotFigC)
  % Combined figure for all svs.
  [hTopSubplotC, hBottomSubplotC, hFigC] = newSplitFigure;
  %% Select and set up the top subplot
  subplot(hTopSubplotC);
  xlim([0,33]); % SVids go from 1 to 32
  ylim([0, 60]); % C/N0 should be between 10 and 60
  ylabel('C/N_0 dB-Hz');
  grid minor; 
  hold on;
end  
if (printStats)
  fid = fopen([directoryname 'CN0Stats.txt'],'w');
  fprintf(fid, '%% %s\r\n', [directoryname 'CN0Stats.txt']);
  fprintf(fid, '%% svid, epochsGie, epochsRover, epochsBase, gieYield, roverYield\r\n');
end

%% Cycle through receivers and make C/N0 plots
% Plot the base first, then the gie and then the rover.
rcvrOrder = [BASE, GIE, ROVER];

%% Loop through the satellites
for sv = 1:32

  skipSv = 0;

  for rcvridx = 1:3
    % Choose receiver to plot and analyze
    rcvr = rcvrOrder(rcvridx);

    % Select data and plotting parameters for the chosen receiver
    switch rcvr
      case BASE
        data = baseData;
        colorC = 'bs';
        colorS = 'bx';
      case ROVER
        data = roverData;
        colorC = 'r.';
        colorS = 'r.';
      case GIE
        data = gieData;
        colorC = 'g+';
        colorS = 'g+';
    end

    % Set up variables to be plotted
    time = data(:, dkey.TIME);
    svid = data(:, dkey.SVID);
    cn0 = data(:, dkey.L1CNZERO);
    valid = data(:, dkey.VALID);
    %     elev = data(:, dkey.ELV);

    if (plotFigC)
      % Set up time line for plotting each satellite
      adjTime = (0.5*(time - startTime)/duration) - 0.25;
    end

    seg = find((svid == sv) & (valid~=-1) );
    if ~(isempty(seg))
      if (plotFigS)
        %% Select and set up the top subplot
        figure(hFigS);
        subplot(hTopSubplotS);
        ylabel('C/N_0 dB-Hz');
        handleS(rcvr) = plot(time(seg), cn0(seg), colorS);
        % use same axes for all plots. Add a 2% margin on both sides.
        xlim(xlimits);
        ylim([0, 60]); % C/N0 should be between 10 and 60
        grid minor;
        hold on;
      end

      if (plotFigC)
        figure(hFigC);
        % Stagger the plots according to SV
        subplot(hTopSubplotC);
        handleC(rcvr) = plot(sv + adjTime(seg), cn0(seg), colorC);
      end
    else
      skipSv = 1;
    end

    % Compute number of epochs for yield
    numEpochs(rcvr, sv) = length(seg);

  end % (rcvr = 1:3)

  if (skipSv)

    roverYield = 0;
    gieYield = 0; 
    
    if (plotFigS)
      figure(hFigS);
      %% Set up the plots to be cleared
      subplot(hBottomSubplotS);
      hold off;
      plot(1,1);
      subplot(hTopSubplotS);
      hold off;
      plot(1,1);

      text(0.8,1,'No Data', 'FontSize', 16);

    end % plotFigS

    % do nothing for plotFigC

  else % (~skipSv)

    roverYield = 100*numEpochs(ROVER,sv)/numEpochs(BASE,sv);
    gieYield = 100*numEpochs(GIE,sv)/numEpochs(BASE,sv);

    if (plotFigS)

      figure(hFigS);

      subplot(hTopSubplotS);
      legend(handleS, rcvrLabels, -1);

      % Attach side labels of file names
      txtstr = sprintf('GIE:%s', labelFileNames{GIE});
      text(xText,35,txtstr);

      txtstr = sprintf('Rover:%s', labelFileNames{ROVER});
      text(xText,25,txtstr);

      txtstr = sprintf('Base:%s', labelFileNames{BASE});
      text(xText,15,txtstr);

      subplot(hBottomSubplotS);
      % Plot a bar chart
      if (version('-release') > 13)
        bar('v6', 1, roverYield, 'r');
        hold on;
        bar('v6', 2, gieYield, 'k');
      else
        bar(1, roverYield, 'r');
        hold on;
        bar(2, gieYield, 'k');
      end
      % Change the shading and colormap
      ylim([0,150]); % Yield can be higher than 100 %
      %       xlabel('time of week in seconds');
      xlabelstr = sprintf('Time[GPS Sec] %02dhrs:%02dmins', hrs, mins);
      xlabel(xlabelstr);
      ylabel('yield %');
      text(0.85,roverYield + 25, [num2str(roverYield) '%']);
      text(1.85,gieYield + 25, [num2str(gieYield) '%']);
      legend(rcvrLabels{2:3}, -1);
      set(hBottomSubplotS, 'XTick', [1 2], 'XTickLabel', {'rover', 'gie'});
      xlim([0.5,2.5]);

    end % plotFigS

    % do nothing for plotFigC

    if (printStats)
      fprintf(fid, '%2d % 8d % 8d % 8d    % 3.2f % 3.2f \r\n', ...
        sv, ...
        numEpochs(GIE, sv), numEpochs(ROVER,sv), numEpochs(BASE,sv), ...
        gieYield, roverYield);
    end

  end % skipSv

  if (plotFigS)
    figure(hFigS);
    %% Plot suptitle maintaining width
    pos = get(hTopSubplotS, 'Position');
    width = pos(3);

    titlestr = ['GIE vs. Standard Rover: SV ' num2str(sv)];
    suptitlebar(titlestr);

    % Reset figure width, which was changed by suptitlebar.
    pos = get(hTopSubplotS, 'Position');
    pos(3) = width;
    set(hTopSubplotS, 'Position', pos);

    pos = get(hBottomSubplotS, 'Position');
    pos(3) = width;
    set(hBottomSubplotS, 'Position', pos);


    %% Print the combined figure

    %% Print the png file
    % Append a leading '0' if the SV id is less than 10.
    if (sv < 10)
      pngFileName = [resultsdir 'CN0-SV0' num2str(sv)];
    else
      pngFileName = [resultsdir 'CN0-SV' num2str(sv)];
    end

    if (printPlots && ~skipSv)
      print( '-dpng', pngFileName);
    end

    %% Set up the plots to be cleared
    subplot(hBottomSubplotS);
    hold off;
    subplot(hTopSubplotS);
    hold off;

    if (~printPlots && ~skipSv)
      pause;
    end
  end % plotFigS

  % Do nothing for plotFigC
  
end % (sv = 1:32)

if (plotFigC || printStats)

  %% Compute Total Yield
  for rcvr = 1:3
    totalEpochs(rcvr) = sum(numEpochs(rcvr,:));
  end
  roverYieldTotal = 100*totalEpochs(ROVER)/totalEpochs(BASE);
  gieYieldTotal = 100*totalEpochs(GIE)/totalEpochs(BASE);

  %% Compute Yields by SV
  for rcvr = 1:3
    seg = find(numEpochs(rcvr,:) == 0);
    numEpochs(rcvr,seg) = NaN;
  end

  svYield(1,:) = 100*numEpochs(ROVER,:)./numEpochs(BASE,:); % rover yield ratio
  svYield(2,:) = 100*numEpochs(GIE,:)./numEpochs(BASE,:); % gie yield ratio

end


if (plotFigC)
  figure(hFigC);


  %% Plot titles and legends
  titlestr = sprintf( ...
    'Yield: Rover = %3.3f%% (%d epochs). GIE = %3.3f%% (%d epochs).', ...
    roverYieldTotal, ...
    totalEpochs(ROVER), ...
    gieYieldTotal, ...
    totalEpochs(GIE) );
  title(titlestr);

  % Plot suptitle
  titlestr = 'GIE vs. Standard Rover Performance';
  suptitlebar(titlestr);

  % Plot legend
  handleC = handleC(:);
  legend(handleC, rcvrLabels, -1 );

  % Attach side labels of file names
  txtstr = sprintf('GIE:%s', labelFileNames{GIE});
  text(34,35,txtstr);

  txtstr = sprintf('Rover:%s', labelFileNames{ROVER});
  text(34,25,txtstr);

  txtstr = sprintf('Base:%s', labelFileNames{BASE});
  text(34,15,txtstr);
  
  txtstr = sprintf('%02dhrs:%02dmins', hrs, mins); 
  text(34, 5,txtstr);


  %% Plot Yields
  % Select bottom subplot
  subplot(hBottomSubplotC);

  % Plot a bar chart
  bar(svYield', 'grouped' );
  % Change the shading and colormap
  shading flat;
  cmap = ...
    [ ...
    1, 0, 0; ... % red
    0, 0, 0; ... % black
    ];
  colormap(cmap);

  %% Tidy up the bottom subplot
  xlim([0,33]); % SVids go from 1 to 32
  ylim([0,125]); % Yield can be higher than 100 %
  xlabel('SV (with time based information)');
  ylabel('yield %');
  legend(rcvrLabels{2:3}, -1);

  if (printPlots)
    %% Print the png file
    print( '-dpng', [resultsdir 'CN0']);
  end

end % plotFigC

if (printStats)
  fprintf(fid, '%2d % 8d % 8d % 8d    % 3.2f % 3.2f \r\n', ...
    0, ...
    totalEpochs(GIE), totalEpochs(ROVER), totalEpochs(BASE), ...
    gieYieldTotal, roverYieldTotal);

  fclose(fid);
end


return;


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [hTopSubplot, hBottomSubplot, hFig] = newSplitFigure;
%% Initialize figure
hFig = newfigure;
%% Create subplots
% The next lines first create a figure with 4 subplots vertically. The
% first three subplots are then combined to form a single subplot.
for idx = 1:4
  h(idx) = subplot(4,1,idx);
  pos(idx,:) = get(h(idx), 'Position');
end
yheight = pos(1,2) + pos(1,4) - pos(3,2);
% xwidth = pos(1,3)*0.9;
% Recreate top subplot to overwrite the top three subplots.
hTopSubplot = subplot('Position', [pos(3,1), pos(3,2), pos(3,3), yheight]);
% hTopSubplot = subplot('Position', [pos(3,1), pos(3,2), xwidth, yheight]);
% Get the handle for the bottom subplot
hBottomSubplot = h(4);
% hBottomSubplot = subplot('Position', [pos(4,1), pos(4,2), xwidth, pos(4,4)]);

% clear yheight idx pos;
return;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
