function [fighandle,linehandles]=gdat_plot(gdat_data,varargin);
%
% choices from doplot in gdat_data.gdat_params.doplot:
%     doplot = 0: no plot
%            = 1: new figure created (default if not given)
%            = -1: add to current figure (with hold all)
%            > 1: create new figure with this number, adding clf
%            <-1: add to figure number abs(doplot) (with hold all)
%

fighandle = NaN;
linehandles = [];
gdat_plot_params.dummy=NaN;
if mod(nargin-1,2)==0
  for i=1:2:nargin-1
    if ischar(varargin{i})
      % enforce lower case for any character driven input
      gdat_plot_params.(lower(varargin{i})) = varargin{i+1};
    else
      warning(['input argument nb: ' num2str(i) ' is incorrect, expects a character string'])
      error_status=101;
      return
    end
  end
else
  warning('number of input arguments incorrect, cannot make pairs of parameters')
  error_status=102;
  return
end

doplot=1;
if isfield(gdat_plot_params,'doplot') && ~isempty(gdat_plot_params.doplot)
  doplot = gdat_plot_params.doplot;
elseif isfield(gdat_data(1),'gdat_params') && isfield(gdat_data(1).gdat_params,'doplot') && ~isempty(gdat_data(1).gdat_params.doplot)
  if gdat_data(1).gdat_params.doplot~=0 % assume one does not call gdat_plot not to plot
    doplot = gdat_data(1).gdat_params.doplot;
  end
end
if doplot==0; return; end
redo_legend_from_Tags = 0;
do_legend = 1;

nb_linehandles_current = numel(linehandles);
for ishot=1:numel(gdat_data)
  nb_linehandles_prev = nb_linehandles_current;
  if all(isfield(gdat_data(ishot),{'data','t'})) && ~isempty(gdat_data(ishot).data) && ~isempty(gdat_data(ishot).t)
    fighandle = get(0,'CurrentFigure');
    if ishot > 1 && gdat_data(1).gdat_params.doplot==1
      % assume that for a series of shot, need doplot=-1 after 1st plot if doplot was 1 in request
      doplot = -1;
    end
    if doplot == 1
      fighandle = figure;
    elseif doplot > 1
      fighandle = figure(doplot);
      clf;
    elseif doplot == -1
      hold all
    elseif doplot < -1
      fighandle = figure(abs(doplot));
      hold all
    end
    if isfield(gdat_data(ishot),'gdat_request') && ischar(gdat_data(ishot).gdat_request) ...
        && strcmp(gdat_data(ishot).gdat_request,'eqdsk')
      % special case, plot contours of first equil
      endstr = '';
      if iscell(gdat_data(ishot).eqdsk); endstr = '{1}'; end
      eval(['contour(gdat_data(ishot).eqdsk' endstr '.rmesh,gdat_data(ishot).eqdsk' endstr '.zmesh,gdat_data(ishot).eqdsk' endstr '.psi'',100);'])
      hold on
      eval(['linehandles{end+1} = plot(gdat_data(ishot).eqdsk' endstr '.rplas,gdat_data(ishot).eqdsk' endstr '.zplas,''k'');'])
      eval(['linehandles{end+1} = plot(gdat_data(ishot).eqdsk' endstr '.rlim,gdat_data(ishot).eqdsk' endstr '.zlim,''k'');'])
      axis equal;
      title(eval(['gdat_data(ishot).eqdsk' endstr '.stitle']));
      do_legend = 0;
    elseif any(find(size(gdat_data(ishot).data)==length(gdat_data(ishot).t)))
      try
        if length(size(gdat_data(ishot).data))<=2
          if isnumeric(gdat_data(ishot).t)
            linehandles{end+1} = plot(gdat_data(ishot).t,gdat_data(ishot).data);
          elseif iscell(gdat_data(ishot).t)
            linehandles{end+1} = plot(str2num(cell2mat(gdat_data(ishot).t)),gdat_data(ishot).data);
          end
        else
          disp('WARNING')
          disp(['size(gdat_data(ishot).data) = ' num2str(size(gdat_data(ishot).data)) ', >2D thus do not try to plot'])
          disp(' ')
          return
        end
      catch ME
        if exist('ME','var')
          disp('Problem in gdat_plot')
          rethrow(ME)
        end
        return
      end
      if ~isfield(gdat_data(ishot),'shot'); return; end % allows to plot if just .t and .data exist
      if doplot < 0
        title([gdat_data(ishot).gdat_params.machine]);
      else
        title([gdat_data(ishot).gdat_params.machine ' #' num2str(gdat_data(ishot).shot)]);
      end
      if isfield(gdat_data(ishot),'mapping_for')
        dimunits_x = gdat_data(ishot).dimunits{gdat_data(ishot).mapping_for.(gdat_data(ishot).gdat_params.machine).gdat_timedim};
        if ischar(dimunits_x)
          xlabel(['time [' dimunits_x ']']);
        else
          xlabel(['time']);
        end
      else
        xlabel(['time']);
      end
      ylabel_eff = gdat_data(ishot).label;
      if iscell(gdat_data(ishot).label) && length(gdat_data(ishot).label)>=2; ylabel_eff = gdat_data(ishot).label{end}; end
      if ~isempty(gdat_data(ishot).units)
        hylabel=ylabel([ylabel_eff '[' gdat_data(ishot).units ']'],'interpreter','none');
      else
        hylabel=ylabel(ylabel_eff,'interpreter','none');
      end
      ab=get(gca,'children');
      if iscell(gdat_data(ishot).label) && numel(gdat_data(ishot).label) > 1;
        if numel(ab)==numel(gdat_data(ishot).label) || mod(numel(ab),numel(gdat_data(ishot).label))==0
          % Assumes a single shot with several lines and labels, if mod==0 then this is a new shot, only Tag present lines
          for iab=1:numel(gdat_data(ishot).label)
            set(ab(iab),'Tag',[num2str(gdat_data(ishot).shot) ' ' gdat_data(ishot).label{end-iab+1}]);
          end
          if numel(ab)>numel(gdat_data(ishot).label), redo_legend_from_Tags = 1; end
        end
        if iscell(gdat_data(ishot).label) && length(ab) < length(gdat_data(ishot).label)
          if length(ab) == 1
            % assume combine label is best
            tempaaa = sprintf('%s/',gdat_data(ishot).label{:});
            hhhleg=legend(tempaaa(1:end-1));
            set(ab(1),'Tag',[num2str(gdat_data(ishot).shot) ' ' tempaaa(1:min(10,numel(tempaaa)-1))]);
          else
            % not sure why would get there
            hhhleg=legend(gdat_data(ishot).label{1:length(ab)});
          end
        elseif numel(ab)==numel(gdat_data(ishot).label)
          hhhleg=legend(gdat_data(ishot).label);
        end
        if exist('hhhleg','var'), set(hhhleg,'Interpreter','none'); end
      else
        % assume one line per call
        if isempty(gdat_data(ishot).label)
          set(ab(1),'Tag',[num2str(gdat_data(ishot).shot)]);
        elseif ischar(gdat_data(ishot).label)
          % assume one signal, take max 10 chars
          set(ab(1),'Tag',[num2str(gdat_data(ishot).shot) ' ' gdat_data(ishot).label(1:min(10,numel(gdat_data(ishot).label)))]);
        elseif iscell(gdat_data(ishot).label) && numel(gdat_data(ishot).label) == 1
          if isempty(gdat_data(ishot).label{1})
            set(ab(1),'Tag',[num2str(gdat_data(ishot).shot)]);
          else
            set(ab(1),'Tag',[num2str(gdat_data(ishot).shot) ' ' gdat_data(ishot).label{1}(1:min(10,numel(gdat_data(ishot).label{1})))]);
          end
        end
      end
      if redo_legend_from_Tags
        for iab=1:numel(ab)
          % Use Tag for DisplayName, when overlay plots of multiple data at this stage
          set(ab(iab),'DisplayName',strrep(get(ab(iab),'Tag'),'_','\_'));
        end
      end
      zoom on;
    end
    maxnblines = 1;
    nb_linehandles_current = numel(linehandles);
    if ~exist('ab','var'), ab=get(gca,'children'); end
    if do_legend==0 || redo_legend_from_Tags || any(strcmp(gdat_data(ishot).gdat_params.data_request,'powers'))  ...
          || (numel(ab)==numel(gdat_data(ishot).label) && numel(ab)>1)
      % keep legend as is
    else
      for i=nb_linehandles_prev+1:nb_linehandles_current
        maxnblines = max(maxnblines,numel(linehandles{i}));
        if numel(linehandles{i}) == 1
          set(linehandles{i},'DisplayName',[num2str(gdat_data(ishot).shot)]);
        else
          for j=1:numel(linehandles{i})
            set(linehandles{i}(j),'DisplayName',[num2str(gdat_data(ishot).shot) ',' num2str(j)]);
          end
        end
      end
    end
    if do_legend==1 && maxnblines==1; legend show; end
    if strcmp(gdat_data(ishot).gdat_request,'mhd')
      % special case, add legend instead of ylabel
      delete(hylabel);
      legend(gdat_data(ishot).label);
      % add spectrogram per signal
      mhd_sum_data = 0.;
      if isfield(gdat_data(ishot).gdat_params,'nfft') && ~isempty(gdat_data(ishot).gdat_params.nfft)
        nfft = gdat_data(ishot).gdat_params.nfft;
      else
        nfft=512;
      end
      tmhdm=mean(reshape(gdat_data(ishot).t(1:nfft*fix(length(gdat_data(ishot).t)/nfft)),nfft,fix(length(gdat_data(ishot).t)/nfft)));
      for i=1:size(gdat_data(ishot).data,2)
        [B,F,T]=specgram(gdat_data(ishot).data(:,i),nfft,1/mean(diff(gdat_data(ishot).t)),hanning(nfft),nfft/2);
        figure;
        imagesc(T+tmhdm(1),F/1e3,20*log10(abs(B)));axis xy;colormap jet;
        ylabel('freq [kHz]')
        xlabel(gdat_data(ishot).dimunits{1})
        ylabel_eff = gdat_data(ishot).label;
        if iscell(gdat_data(ishot).label) && length(gdat_data(ishot).label)>=i; ylabel_eff = gdat_data(ishot).label{i}; end
        title([upper(gdat_data(ishot).gdat_params.machine) '#' num2str(gdat_data(ishot).shot) ' ' ylabel_eff])
        mhd_sum_data = mhd_sum_data + gdat_data(ishot).data(:,i);
      end
      [B,F,T]=specgram(mhd_sum_data./size(gdat_data(ishot).data,2),nfft,1/mean(diff(gdat_data(ishot).t)),hanning(nfft),nfft/2);
      figure;
      imagesc(T+tmhdm(1),F/1e3,20*log10(abs(B)));axis xy;colormap jet;
      ylabel('freq [kHz]')
      xlabel(gdat_data(ishot).dimunits{1})
      ylabel_eff = gdat_data(ishot).label;
      if iscell(gdat_data(ishot).label); ylabel_eff = sprintf('%s ',gdat_data(ishot).label{:}); end
      title([upper(gdat_data(ishot).gdat_params.machine) '#' num2str(gdat_data(ishot).shot) ' sum of ' ylabel_eff])
    end
  else
    disp(['cannot plot gdat_data(' num2str(ishot) '), has empty data or t field'])
  end
end
