% routine to make "horizontal" sections
%
%function [blanker]=hsec(x,y,z,blanker,cruise)
nargin=0;
% 
% cruise = 6 digit cruise code
% blanker= matrix with blanking coordinates
%
% function [blanker]=hsec(x,y,z,blanker,cruise)
%
% (note: See "versec.m" for vertical sections)

% prompt user for questions before the section loop starts
% but note that most of these are hardcoded



cp=computer;

%nsec=input('Enter number of sections on this page: ');
nsec=1;

if nsec>1;
  sp=menu('What form of plot?','subplots','overlay');
  disp(['Hardcoded to ',csp(sp,:),' ',num2str(nsec)]);
  sblk=menu('Use same blanking in loop?','y','n','none');

  stim=menu('Use same time in loop?','y','n');
else;

   sp=1;

   stim=1;
   sblk=3;
   disp(' ');
   disp('Assumes no contour blanking.');
end;


csp=['subplots';'overlays'];


eblk=exist('blanker');
if eblk==0;
  blanker=1;
end;


batch=1; % set to 1 for batch mode (used with i2m_batch.m)

wvar=1; % set default variable
cf=['   temp';'   salt';' sigmat';'station'];
cfield=cf(wvar,:);

gd=5; % set default gridding method 4= for objmap by saga 
cgd=['griddata';'mincurvi';' kriging';'  objmap';'    none'];

incr=3; % 1- min to max w/5 increments set default contour interval method
        % 2- prompt user
        % 3- set in code

dep=30; % set default depthzero for bottom value

dtype='done'; % set default datafile type

pts=' no'; % set default to plotting original stations locations

wbth=2; %default bathy option 2 = isobaths
cbth=['    none     ';'     isobaths';' Dicks shades';'Julios shades'];


bounds=1; %default geographic box
cbnd=[' min/max';'hardcode';'  ginput'];


%define colormap
colormap(jet)



% adjust fontsize to the number of sections
if sp==1;fs=8+6/nsec;
else; fs=14;
end;

for ksec=1:nsec;

  if batch~=1;
% Add some buttons to figure one to allow user options
  bfield=uicontrol('style','checkbox','string',['variable=',cfield],'Position', [300 20 250 20]);
  bmeth=uicontrol('style','checkbox','string',['gridmethod=',cgd(gd,:)],'Position',[300 50 200 20]);
  bincr=uicontrol('style','checkbox','string',['cont. incr=',num2str(incr)],'Position',[300 80 250 20]);
  bdep=uicontrol('style','checkbox','string',['depth=',num2str(dep)],'Position',[300 110 250 20]);
  btype=uicontrol('style','checkbox','string',['datafile= ',dtype],'Position',[300 140 250 20]);
  bpts=uicontrol('style','checkbox','string',['plot pts=',pts],'Position',[300 170 250 20]);
  bbty=uicontrol('style','checkbox','string',['bathy option=',cbth(wbth,:)],'Position',[300 200 250 20]);
  bbnd=uicontrol('style','checkbox','string',['bounds=',cbnd(bounds,:)],'Position',[300 230 250 20]);
  bsp=uicontrol('style','checkbox','string',['plotform=',csp(sp,:)],'Position',[300 230 300 20]);

%
  disp(' ')
  disp('')
  disp(' ***************************************************')
  disp('     Click  the variables you want to work with. ')
  disp(' ')
  disp('     Then click and press return in this window  when done. ')
  disp(' ***************************************************')
  disp(' ')
  disp('')
  pause;

  set(bfield,'Visible','off');
  set(bmeth,'Visible','off');
  set(bincr,'Visible','off');
  set(bdep,'Visible','off');
  set(btype,'Visible','off');

  vfield=get(bfield,'value');
  vmeth=get(bmeth,'Value');
  vincr=get(bincr,'Value');
  vdep=get(bdep,'Value');
  vtype=get(btype,'Value');
  vtype=get(btype,'Value');

  set(bpts,'Visible','off');
  vpts=get(btype,'Value');
  set(bbty,'Visible','off');
  vbty=get(bbty,'Value');
  set(bbnd,'Visible','off');
  vbnd=get(bbnd,'Value');
  set(bsp,'Visible','off');
  vsp=get(bsp,'Value');
  end;

  if vsp==1;
    sp=menu('What form of plot?','subplots','overlay');
  end;
  if nsec>1;
    if sp==1;
      subplot(nsec,1,ksec);
      set(gca,'visible','off');
    end;
  end;

% DEFINE GEOGRAPHIC BOX
  if ksec==1;
    if vbnd==1;
      bounds=menu('How to define geographic box?','min/max','hardcode','ginput');
    end;
  end;

  if vtype==1;
     if cp(1:3)=='SGI';
       dtype=questdlg('What format is your data file?',...

        'data','user','done');
     else;
       dtype=questdlg('What format is your data file?',...

         'format question','data','user','done','data');
     end;

%   LOAD DATA
    if dtype=='data';
      if nargin<5;
%        cruise='al8209';
        cruise=input('Enter >4-digit cruise code: ','s');
      end;
      if cruise(:,1:5)~='loade';
%        cru=cruise(ksec,:);
         cru=cruise;

        if cp(1:3)=='SGI';
           dir='/data5/jmanning/ctd/data/';

        elseif cp(1:3)=='PCW';

           dir='f:\ctd\data\';

        end;   
        disp(['loading ',cru,'...']);
        eval(['load ',dir,cru,'.data']);
        eval(['d=',cru,';']);
      else; cru='loaded';
      end;
    elseif dtype=='user';
      disp('Hardcoded to ask user for data info');
      keyn=input('Enter key number to subselect: ');
      d=buildmat('n','n',1,[keyn keyn],...
        '/home3/ocn/jmanning/gbs95/barb/hydfsh.dat',3);
    end;
  end;

  if vdep==1;
    dep=input('What layer depth (positive number; enter zero for bottom or 999 for layer)? '); 
    if dep==999;
      rng=input('Enter range of depth to average: ');
    end;
  end;

%   grab the variable of interest
  if vfield==1;
    wvar=menu('Which "z" variable?','temp','salt','dens','sta#');
    cfield=cf(wvar,:);
  end;

% Extract data differently depending on what data type you loaded

  if dtype=='user';
%   grab the x & y
    x=d(:,1);
    y=d(:,2);
    z=d(:,3);

  elseif dtype=='data';
    if str2num(cru(3:4))>70&str2num(cru(3:4))<99;
      yr=str2num(cru(3:4));
    else;
       yr=input('2-digit year: ');
       disp(['Hardcoded to ',num2str(yr)]);
    end;
    if ksec==1|stim==2|vtype==1;
      trng=input('Enter start day of month,day,hhmm(gmt) and end mth,day,hhmm: ');
      yd1=julian(trng(1),trng(2),yr,trng(3));   
      yd2=julian(trng(4),trng(5),yr,trng(6));   
    end;
   
    if dep ~=0;
      if dep==999;
        idd=find(d(:,3)>=rng(1)&d(:,3)<rng(2)&d(:,4)>=yd1&d(:,4)<=yd2);
      else;
        idd=find(d(:,3)==dep&d(:,4)>=yd1&d(:,4)<=yd2);
      end;
    elseif dep==0;
      idd=find(diff(d(:,3))<0&d(1:length(d)-1,4)>=yd1&d(1:length(d)-1,4)<=yd2);
    end;

    if isempty(idd); disp('WARNING:No data found at this specification');end;

%   grab the x & y
    x=d(idd,10);
    y=d(idd,9);
    if wvar==4;wvar=7;end;
    z=d(idd,wvar+4);

  end

  gbox=bound(bounds,x,y);

% define some ranges of x & y for text positioning purposes later
  gboxy=gbox(4)-gbox(3);
  gboxx=gbox(2)-gbox(1);

  if vmeth==1|exist('scales')==0&batch~=1;
    gd=menu('Grid data?','use griddata',...
                         'use sagas mincurvi',...
                         'use sagas kriging',...
                         'use sagas objmap',...
                          'none');       
    if gd==5;
      zi=z;yi=y;xi=x;
    else;
      if gd>2;
        scales=input('Enter x and y length scales to search: ');
        ngpt=input('Enter number of grid points (typically 25): ');
        opt=input('Enter OPT as described in help & defaulted as [32 8 500 1/3 1]: ');
        if isempty(opt);opt=[32 8 500 1/3 1];end;
      end;
      [zi,xi,yi]=gridopts(x,y,z,gd,ngpt,.5,scales,opt);
    end;
  else
    if gd==5;
      zi=z;yi=y;xi=x;
    else;
      disp(['Hardcoded to ',cgd(gd,:),' method']);
      [zi,xi,yi]=gridopts(x,y,z,gd,25,.5,[.3 .15]);
    end;
  end;



% %%%%%%%%%%%%%%%%%%  DEFINE   CONTOUR INTERVAL %%%%%%%%%%%%%%%%%%%

  if ksec==1|vincr==1&batch~=1;

    incr=menu('What contour interval?','min to max by 1',...
               'prompt user',...
               'specified in code',...

               'not contouring');
    disp('Hardcoded contour intervals to data defined.');
    [rg,mi,ma]=rangejm(z);
    if incr==1;
      v=min(z):rjm/6:max(z);
      ci=floor(rjm/6);
      cl=ci*2;;
    elseif incr==2;
      v=input('Enter min:inc:max contour int: ');
      ci=mean(diff(v));
      cl=floor((max(v)-min(v))/3/ci)*2*ci;
    elseif incr==3;
      v=[4:1:20];
      ci=1;
      cl=2;
    end;
  end;
  if batch==1;incr=3;v=[4:1:20];ci=1;cl=2;end;


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%     blank out 

    if ksec==1|sblk==2&length(blanker)<=1&sblk~=3;
      hold on;
      hh=plot(x,y,'+');
      set(gca,'aspectratio',[1 .78]);
      axis([gbox(1)-gboxx/10 gbox(2)+gboxx/10 gbox(3)-gboxy/10 gbox(4)+gboxy/10]);
      set(gca,'position',[.15 .15 .65 .65]) 
      disp('enter 7 points')
      [xb,yb]=ginput(7);
%     close the polygon
      xb=[xb;xb(1)];yb=[yb;yb(1)];
      blanker=[xb yb];
%     find points inside (ie bb=1)
      set(hh,'visible','off')
    end;
    
    if sblk~=3;
      xb=blanker(:,1);yb=blanker(:,2);
      [Xi,Yi]=meshgrid(xi,yi);
      [bb]=inpolygon(Xi,Yi,xb,yb);

%     we can "blank out" in different ways
%     1) try to set values to reasonable values
%     2) set to NaNs
      bom=2;
      if bom==1;
        blanktry
      elseif bom==2;
        for ix=1:length(xi);
          for iy=1:length(yi);
            if bb(ix,iy)==0; zi(ix,iy)=NaN; end;
          end;
        end;
      end;    
    end;    

%%%%%%%%%%%%%%%%%%%%%%%%   Put down bathy shades if wanted %%%%%%%%

% In case of wbth>2, put down the shades NOW
  if vbty==1;
    wbth=menu('What bathy option?',' none',' isobath',' limeburner shades',' julios shades');
  end;
  if wbth>2;
    georbat(1,0,0,wbth-2,1);
  end;
  
 
%%%%%%%%%%%%%%%%%%%%%%%%%%  Do the Contouring Now %%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%% DEFINE METHOD OF CONTOURING %%%%%%%%%%%%%%%%%%
  if batch~=1;  
    ptype=menu('Plot type?',...
         '1) pcolor & contour',...
         '2) econtour w/fill & labels',...
         '3) econtour w/labels',...
         '4) econtour wo/labels',...
         '5) econtour w/fill & no labels',...
         '6) station plot');
  else;
    ptype=5;
  end;

      if ptype==1;
        if gd<=4;
          pcolor(xi,yi,zi);
          hold on
%          set(gca,'position',[.15 .15 .65 .65]) 
  	  cs=econtour(xi,yi,zi,v,'linewidth',3);
        else;
%  	  pcolor(x2(1:ncasts) ,pmatrix(1:maxmax,indexmax),zz(1:maxmax,1:ncasts));
          pcolor(x,y,z);
          caxis([min(v) max(v)])
          hbar=cbar(gca,'v',ci,ci*2);
          hold on
%  	  cs=contour(x2(1:ncasts) ,pmatrix(1:maxmax,indexmax),zz(1:maxmax,1:ncasts),v);
        end;
%  	clabel(cs,'manual')
        shading interp
      elseif ptype==2;
        disp('Hardcoded to use EXTCONTOUR.');
        if gd<=4;
          econtour(xi,yi,zi,v,'fill','label',200,'fontsize',fs,'linewidth',.01,'color','k');
        else;
  	  econtour(x2(1:ncasts),pmatrix(1:maxmax,indexmax),zz(1:maxmax,1:ncasts),v,'fill');
        end;
        caxis([min(v) max(v)]);
        if ksec==nsec|vfield==1;
          hbar=cbar(gca,'v',ci,cl);
        end;
      elseif ptype==3;
         axis(gbox);

         if cp(1:3)=='PCW';
           cd e:\atsee\newextc;
           extcontour(xi,yi,zi,v,'label',175,'fontsize',fs,'linewidth',5,'color','g');
         else;
           econtour(xi,yi,zi,v,'label',175,'fontsize',fs,...
              'fontweight','bold','linewidth',5,'color','g');
         end;
      elseif ptype==4;
        ss=econtour(xi,yi,zi,v,'linewidth',3,'color','r');
      elseif ptype==5;
        disp('Hardcoded to use econtour fill.');
        econtour(xi,yi,zi,v,'fill');
        if ksec==nsec|vfield==1;
          caxis([min(v) max(v)]);
%          cl=floor((max(v)-min(v))/3/ci*2*ci);
%          titl=input('Color bar title?','s')
          if batch==1;
            hbar=cbar_batch(gca,'h',ci,cl);
          else;
            hbar=cbar(gca,'h',ci,cl);
          end;
        end;
      elseif ptype==6;
        dots=menu('Dot size?','same for all','relative to "z"');
        if dots==1;

           if cp(1:3)=='PCW';
             load e:\atsee\ccodemat
           end;
          sizesym(x,y,-1*ones(length(x),1),6,1,'g')
        else;
          lol=menu('Scale dot size with log?','y','n');
          if lol==1;nsp=-1*nsec;else;nsp=nsec;end;
          sizesym(x,y,-1*z,nsp,.9,'z')
        end;
      end;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%   OVERLAYS?  %%%%%%%%%%%%%%%%%

%    pltfish

%%%%%%%%%%%%%%%%%%%%%%%%%%%   Fix Axis up  %%%%%%%%%%%%%%%


%   add basemap & axis labels
    hold on;
    axis(gbox);
    if wbth==2;
        georbat(1,0,0,wbth-2,1);
        lllabel(60,60,40,42,-69,-66);
    end;

%   title with day-mth time of observations
    if ksec==1|stim==2&dtype=='data';
      if trng(1)==trng(4);
        title([num2str(trng(2)),'-',num2str(trng(5)),num2str(caldaym(trng(1))),' 19',...
          num2str(yr)],'fontsize',fs+2);
      else;
        title([num2str(trng(2)),num2str(caldaym(trng(1))),' -',...
          num2str(trng(5)),num2str(caldaym(trng(4))),' 19',...
          num2str(yr)],'fontsize',fs+2);
      end;
    end;

%   annotate depth in lower right if depth changes
    if vdep==1;
      if dep==0; depth='bottom';else;depth=[num2str(dep),' meter'];end;
       disp('Hardcoded to NOT label variable & depth');
%      text(gbox(2)-gboxx/2.5,gbox(3)+gboxy/30,depth,... 
%         'fontsize',fs);
%      text(gbox(2)-gboxx/2.5,gbox(3)+gboxy/40,cfield,... 
%         'fontsize',fs);
    end;

%   annotate grid method if that changes
    if vmeth==1;
      text(gbox(1)+gboxx/10,gbox(3),cgd(gd,:),... 
         'fontsize',fs);
    end;

%   annotate isobaths?
    if ksec==nsec;
      text(-68.6,40.35 ,'100m','rotation',30,'color',[1 .62 .4])
      text(-67.48,41.07,'60m','rotation',10,'color',[1 .62 .4])
    end;

%   fix axis according to subplot
    if sp==1;
      if ksec~=nsec;
        set(gca,'xticklabels',[ ])
        xlabel(' ');
      end;
      set(gca,'position',[.15 .975-(ksec/nsec*0.9) .65 (1/nsec*0.85)]) 
    end;

% add white dots at original points    
  if  ksec==1|vpts==1&batch~=1;
    pts=questdlg('Plot points?','yes',' no');
  end;
  if pts(1:2)=='ye';
    plot(x,y,'w+','markersize',4);
    disp('Warning: number of cast not posted');
%    text(min(get(gca,'xtick'))+gboxx/5,min(get(gca,'ytick')),[num2str(length(x)),' casts'],...
%     'verticalalignment','bottom');
  end;

    disp('make modifications to this panel now...')



%    keyboard;

%  clear in case of overlays
  if ksec>1&sp==2;
    clear xi yi zi x y z;
  end;

% end of loop through sections
end;

orient tall;
%    set(gcf,'paperposition',[1 1.5 6 8]);

clear wvar;

 

   
