function gplotpg(arg1);
%
% Usage: gplotpg(pgstruct)
% Where: pgstruct has the following fields (and defaults):
%pgstruct.start_dd=309;           % starting decimal day       (required)
%pgstruct.dbname = 'a9611';       % database name              (required)
%pgstruct.dbpath = '../adcpdb/';  % database path              (required)
%pgstruct.year_base = 1996;       % for getting decimal days   (required)
%pgstruct.comment = 'lg9611'      % title for plots            (required)
%%optional fields (these are the defaults)
%    pgstruct.nbins = 60;         % maximum number of bins
%    pgstruct.PGOOD_MIN=0;        % mininum  values for clipping data
%    pgstruct.PGOOD_MAX=100;      % maximum  values for clipping data
%    pgstruct.icolor=1;           % if 1, use color, otherwise gray scale
%    pgstruct.reduce_res=0;       % yes=1,no=0;50% resolution in time and depth
%    pgstruct.days_per_panel=1;   % number of days to plot/panel; default is 2
%                                 % there are 4 panels per page
%
%
% plots PERCENT_GOOD versus decimal days for each ensemble
% specified by the time range in 4 PANELS PER PAGE with a
% number of user set options (see below):
%
% It calls getmat -t <dbname> <year> <start_dd> <interval_dd>  to
% extract data from the database for the time range specified.
%
%
% Run one page at a time (as is done for ref.layer plots).
%

% Written on March 96 by EK
% changed to include correct number of profiles per bin and correct
%   decimal day - Jules 1997/03/05
% modified to use getmat with time option, JF 97/03/10
% further modifications by EF, conversion to function by JF 97/03/13
%

%99/08/28 Jules added the option of passing all the info in as a structure
% then it can be used with newday.prl
%2000/02/10 Jules - fixed a bug where it would try to use a vector of
%    5 starting days for the 4 panels (and then would be upset)
%2000/02/12 Jules - palettes are now set up to have 0-30pg, 30-80pg, and
%  80-100pg come up as clearly delimited regions, as opposed to just
%   using 'jet' which makes a single big transition at about 50pg.
% -- also require structure now for the argument.
%NOTE: If you change the way the structure (pgstruct) comes into the
%  function, please be aware that the following 3 programs use this program
%  and you may break them:
%  programs/codas3/adcp/demo/edit/plotpg.m
%  programs/codas3/adcp/demo/plotall.m
%  programs/matlab/utils/gplogadcp.m


if nargin==0
  help gplotpg
  error('must set pgstruct')
end


%here are the defaults
default_nbins = 60;         % maximum number of bins
default_PGOOD_MIN=0;        % mininum  values for clipping data
default_PGOOD_MAX=100;      % maximum  values for clipping data
default_icolor=1;           % if 1, use color, otherwise gray scale
default_reduce_res=0;       % yes=1,no=0;50% resolution in time and depth
default_days_per_panel=1;   % number of days to plot/panel; default is 2
%                                 % there are 4 panels per page


%check out the structure
if ~isstruct(arg1)
  help gplotpg
  sprintf('this must have a structure as its argument.  ')
  sprintf('see demo/edit/plotpg.m for an example of usage. ')
  sprintf('look at the top of this file (gplotpg) to see how to')
  sprintf('    make it matlab4 compatible')
  error('argument is not a structure')
else
  %for these values, if there isn't something set, we drop out with a message
  start_dd = arg1.start_dd;
  dbname = arg1.dbname;
  dbpath = arg1.dbpath;
  year_base = arg1.year_base;
  cruiseid = arg1.comment;  %using the name "comment" in gplogadcp

  %now set the ones with defaults
  %initialize first:
  pgstruct.nbins            = default_nbins;
  pgstruct.PGOOD_MIN        = default_PGOOD_MIN;
  pgstruct.PGOOD_MAX        = default_PGOOD_MAX;
  pgstruct.icolor           = default_icolor;
  pgstruct.reduce_res       = default_reduce_res;
  pgstruct.days_per_panel   = default_days_per_panel;

  %then override
  if (isfield(arg1,'nbins')),         nbins = arg1.nbins; end
  if (isfield(arg1,'PGOOD_MAX')),     PGOOD_MAX = arg1.PGOOD_MAX; end
  if (isfield(arg1,'PGOOD_MIN')),     PGOOD_MIN = arg1.PGOOD_MIN; end
  if (isfield(arg1,'icolor')),        icolor = arg1.icolor; end
  if (isfield(arg1,'reduce_res')),    reduce_res = arg1.reduce_res; end
  if (isfield(arg1,'days_per_panel')),days_per_panel = arg1.days_per_panel; end
end


% not a free parameter at present.
panels_per_page = 4;     % set as an integer >=1 (for number of panels/page)
interval_dd = panels_per_page * days_per_panel;

% extract data with getmat; clean up workspace

time_specs = [' ',num2str(year_base),' ',num2str(start_dd),...
           ' ',num2str(interval_dd)];
eval(['!getmat -t ',dbpath,dbname,time_specs]);
load other
load pg
all_date=DAYS;

if (NBINS<nbins)
  nbins=min(nbins,NBINS);  %nbins was set earlier, NBINS is from the data
  beep
  disp(sprintf('There are only %d bins available.\n',NBINS))
end
bins=[1:nbins]';
all_pgood = PGOOD(bins,:);

clear DAYS IBLKPRF LAT LGB LON NBINS NPRFS PGOOD TIME
delete amp.mat depth.mat e.mat other.mat
delete  pg.mat u.mat v.mat w.mat pf.mat


%now plot it ==================================================
ndates = length(all_date);
dt = mean(diff(all_date)); %subtract this little bit to make sure we don't
                           %end up on an integer and have one too many days
plot_dates = [start_dd:days_per_panel:all_date(ndates)-dt];  %here's the fudge
pg_range = [ PGOOD_MIN PGOOD_MAX];

% set up the graphics
clf

% Ticks on colorbar every 10 units:
colorticks = (10*round(PGOOD_MIN/10)):10:(10*round(PGOOD_MAX/10));

position_contour = [.2 .73 .65 .163 ];   % size same as ref.layer plots
c_left=position_contour(1);
c_bot=[position_contour(2) .53 .29 .09];    % panels' vertial positions
c_wid=position_contour(3);
c_hgt=position_contour(4);
%c_panel_hgt=c_hgt/(panels_per_page+1);
%c_dy = c_panel_hgt/(panels_per_page);

%if (v4);
%  xtick_str=['XTickLabels'];
%  ytick_str=['YTickLabels'];
%else;
  xtick_str=['XTickLabel'];
  ytick_str=['YTickLabel'];
%end



if ( icolor == 1),
%
        nbins=35;
        hjet = jet(nbins);
        index1=round(.2*nbins);
        index2=round(.3*nbins);  %light blue transition at 30pg
        index3=round(.8*nbins);  %yellow at 80pg
        index4=round(.9*nbins);
        allindex= [1 index1 index2 index3 index4 nbins]';
        r=table1([allindex [0 0 0 1 1 .6]'],[1:nbins]);
        g=table1([allindex [0 0 1 1 0 0]'],[1:nbins]);
        b=table1([allindex [.6 1 1 0 0 0]'],[1:nbins]);
        h = [r g b];
else
                hgray=  table1(...
                        [[0 .01 .15 .28 .3 .31 .78 .82 1]' ...
                        [0 .01 .35 .4 .52 .55 .6 .7 1]'],...
                        (1:nbins)'/nbins);
                h=[hgray hgray hgray];
end


% set up arrays for colorbar
x=0:1;
y = pg_range(1):(pg_range(2)+1);    % +1 because pcolor does not
               %   use last row, column
z = [y.' y.'];
z=z(:,ones(1,length(x)));

early_end=0;            % flag for page with < 4 panels
pagenum=round(plot_dates(1));      % start day in ps file name

% check for matlab version


for panel_num=1:length(plot_dates)      % (1:panels_per_page)

        [plot_dates(panel_num) panel_num ];
        position_contour=[ c_left c_bot(panel_num) c_wid c_hgt ];

        today=plot_dates(panel_num);
        ii=find((all_date>=today)&(all_date<=today+days_per_panel));

        if (reduce_res==1)
                ii=ii(1:2:length(ii)); jj=(1:2:nbins);
        else
                jj=1:nbins;
        end

        % make image for this panel  ------------------------------
        if (panel_num==1);   clf;  end

      axes('position',position_contour,'Box','on', 'YDir', 'reverse');
      hold on
      colormap(h)
      if (isempty(ii))
        fprintf('no data in time range %7.4f to %7.4f\n',...
           today,today+days_per_panel)
      else
        pcolor(all_date(ii),bins(jj),all_pgood(jj,ii));
        shading flat
      end
      caxis(pg_range)

      axis([today  today+days_per_panel 0 (nbins+1)])
      %changed to make xticklabels follow xtick being set (automatically)
      if (days_per_panel>=1)
        xticks = today:0.2:today+days_per_panel;
        set(gca,'xtick',xticks);
      end
      %now do the vertical
      yticks = 0:10:nbins;
      set(gca,'ytick',yticks);
      set(gca, 'TickDir', 'out');
      ylabel(['bin number'])

      % add title  and color bar to top of first plot
      if (panel_num==1);
        title([cruiseid,': Percent Good']);

        % add x-axis label if this panel is the only panel
        if  (panel_num == length(plot_dates))
         xlabel([num2str(year_base),' decimal days']);
         early_end=1;
        end

        % now colorbar
        h1 = axes('position',[.87 .730 .02 .163], ...
           'Box','on','YLim',pg_range );
        hold on
        colormap(h)
        pcolor(x,y,z)
        shading flat
        caxis(pg_range)
        set(h1, 'XTick', [], 'YTick', colorticks);
        set(h1, 'TickDir', 'out', 'TickLength', [0.02 0.02])
        set(h1,xtick_str,'')
        set(h1,ytick_str,'');
        top_label_pg = colorticks(length(colorticks));
        bottom_label_pg = colorticks(1);
        s1 = sprintf('%d', top_label_pg);      % reverse values
        s2 = sprintf('%d', bottom_label_pg);
        text(1.4,top_label_pg,s1, ...
           'HorizontalAlignment', 'left','FontSize',10);
        text(1.4,bottom_label_pg,s2, ...
           'HorizontalAlignment', 'left','FontSize',10);
        end

        % add x-axis label to bottom panel
        if (panel_num == length(plot_dates))

                if (early_end == 0)
                        xlabel([num2str(year_base),' decimal days']);
                end

                orient('tall')
                date_it('UH ADCP');
                if (isstruct(arg1))
                   disp('not saving figure to disk: do that manually if desired')
                else
                   disp(['printing to pgood',num2str(pagenum)])
                   if icolor == 1,
                     pdev = 'psc';
                   else
                     pdev = 'ps';
                   end
                   eval(['print -d' pdev ' pgood',num2str(pagenum)])
               end
        end
end

