function gplotpg(arg1);
%
% Usage: gplotpg(pgstruct)
% Where: pgstruct has the following required fields (with examples):
%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
%    pgstruct.printflag = 1;      % if 1, print to file.
%
% 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> <days_per_page>  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

% 2000/03/20 EF cleanup


if nargin ~= 1,
  help gplotpg
  error('must set single input argument, pgstruct')
end


%here 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
pgstruct.printflag = 1;      % if 1, print to file.


%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
   % Transfer input parameters, overriding defaults.
   fn = fieldnames(arg1);
   for ii = 1:length(fn)
      fname = fn{ii};
      pgstruct = setfield(pgstruct, fname, getfield(arg1, fname));
   end
end


% Following could be eliminated by using pgstruct.whatever instead.
start_dd = pgstruct.start_dd;
dbname = pgstruct.dbname;
dbpath = pgstruct.dbpath;
year_base = pgstruct.year_base;
cruiseid = pgstruct.comment;  %using the name "comment" in gplogadcp

nbins = pgstruct.nbins;
pg_range = [pgstruct.PGOOD_MIN pgstruct.PGOOD_MAX];
icolor = pgstruct.icolor;
reduce_res = pgstruct.reduce_res;
days_per_panel = pgstruct.days_per_panel;


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

% extract data with getmat; clean up workspace

time_specs = [' ',num2str(year_base),' ',num2str(start_dd),...
           ' ',num2str(days_per_page)];
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 ==================================================
plot_dates = [start_dd:days_per_panel:all_date(end-5)];
   % (Don't start a panel if there is nothing to plot.)

% set up the graphics
clf

% Ticks on colorbar every 10 units:
colorticks = (10*round(pg_range(1)/10)):10:(10*round(pg_range(2)/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);
xtick_str=['XTickLabel'];
ytick_str=['YTickLabel'];


ncmap=35;
if ( icolor == 1),
%
   hjet = jet(ncmap);
   index1=round(.2*ncmap);
   index2=round(.3*ncmap);  %light blue transition at 30pg
   index3=round(.8*ncmap);  %yellow at 80pg
   index4=round(.9*ncmap);
   allindex= [1 index1 index2 index3 index4 ncmap]';
   r=table1([allindex [0 0 0 1 1 .6]'],[1:ncmap]);
   g=table1([allindex [0 0 1 1 0 0]'],[1:ncmap]);
   b=table1([allindex [.6 1 1 0 0 0]'],[1:ncmap]);
   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:ncmap)'/ncmap);
   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)));

psfile = ['pgood', num2str(round(plot_dates(1))), '.ps'];  % start day

for panel_num=1:length(plot_dates)


   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  ------------------------------
   position_contour=[ c_left c_bot(panel_num) c_wid c_hgt ];
   axes('position', position_contour, 'Box', 'on', 'YDir', 'reverse');
   axis([today  today+days_per_panel 0 (nbins+1)])
   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)

   %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']);

      % 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, and print to file
   if (panel_num == length(plot_dates))
      xlabel([num2str(year_base),' decimal days']);

      orient('tall')
      date_it('UH ADCP');
      if (pgstruct.printflag == 0)
         disp('not saving figure to disk: do that manually if desired')
      else
         disp(['printing to ', psfile])
         if icolor == 1,
            pdev = '-dpsc';
         else
            pdev = '-dps';
         end
         print(pdev, psfile);
      end
   end
end

