function webmaster(fctn, varargin)
%  to choose sections of shipboard data - called from plotmaster (gplotadcp)

%see web.doc for more details. 
% Summary:
%    make section plots of shipboard adcp data (contour and vector).
%    vector plots are on topography and can have color-coded
%            temperature vectors
%    figures are saved as eps from matlab and translated to .eps
%    html files are generated to cross- and self- reference the gif files
%
% Files: in the working directory (e.g. cruiseID/web)
%        cruiseID.eps    colored contour topography figure 
%        cruiseID.gif       (copy of *.eps in gif format)
%        nav.eps       overview: topography, adcp vectors,  section labels
%        nav.gif        (copy of nav.eps in gif format)
%        nav_exten.html   html file reads nav.gif (or whatever the
%                         extension was): active locations point to
%                         vector plots in vect_*.html
%        cont_*.eps   contour plot of section in eps
%        vect_*.eps   vector plot of section in eps (incl. topog and temp)
%        cont_*.gif       (copy of cont_*.eps in gif)
%        vect_*.gif       (copy of vect_*.eps in gif)
%        cont_*.html   reads cont_*.gif, points to nav.gif and vect.gif
%        vect_*.html   reads vect_*.gif, points to nav.gif and cont.gif
%
%        sectinfo.mat    *** important*** DO NOT DELETE
%        This file contains a structure sect_info (see web.doc)
%    Direct adaption of websectt: Jules: 98/07/17;  EF  99/02/27;  Jules 00/09/07

% web plotting switchyard function
global ALLFIG
switch(fctn)
   case 'setup'                % from plotmasterweb - orig. call
      close(gcf);
      websetup;
   case 'main'                % from gplotweb - btnOK
      % first save all window values in structure
      v1 = findobj(gcf,'Tag','txtboxtitle');
      v2 = findobj(gcf,'Tag','txtboxyear');
      v3 = findobj(gcf,'Tag','txtboxctddbase');
      v4 = findobj(gcf,'Tag','txtboxstafile');
      v5 = findobj(gcf,'Tag','txtboxgs');
      v6 = findobj(gcf,'Tag','txtboxconvert');
      v7 = findobj(gcf,'Tag','txtboxnewext');
      v8 = findobj(gcf,'Tag','txtboxtranslator');
      v9 = findobj(gcf,'Tag','txtboxdbase');
      for m = 1:9;
         gstr = sprintf('vbl1= get(v%d,''string'');',m);
         eval(gstr)
         gstr = sprintf('ALLFIG.webwin.v%d = vbl1;', m);
         eval(gstr)
      end
      
      main
   case 'help'
      noticeOK('Help is on the way...')
end

%%%%%%%%%%%

function websetup()   %Establish paths

global XYDATA
global UVDATA
global CONTFIG
global VECFIG
global ALLFIG

% [db_path, uifile]  = fileparts(ALLFIG.default_path);
% db_path = [db_path, '/']; 
% XYDATA.default_path = db_path;
VECFIG.outpath = ALLFIG.outpath;
CONTFIG.outpath = ALLFIG.outpath;
VECFIG.loadpath = ALLFIG.outpath;
CONTFIG.loadpath = ALLFIG.outpath;
pp = pwd;
marks = findstr(pp,filesep);
cruiseID = upper(pp(marks(end)+1:end));
% dbname = pp(marks(end)+1:end); 
if length(cruiseID) == 6 & ~isletter(cruiseID(end)) 
   cruisetitle = cruiseID;
else % largely obsolete
   pp = what;
   marks = findstr(pp.path,filesep);
   cruiseID = upper(pp.path(marks(end)+1:end));
   if length(cruiseID) == 6 & ~isletter(cruiseID(end))
      cruisetitle = cruiseID;
   else
      cruisetitle = '';
   end
end;

if ~isempty(cruisetitle) % guess yearbase
   yrsuf = cruisetitle(3:4);
   if str2num(yrsuf) > 70
      yb = strcat('19',yrsuf);
   else
      yb = strcat('20',yrsuf);
   end
else
   yb = '2002';
end

gplotweb

han = findobj(gcf,'tag','txtboxtitle');
set(han,'string',cruisetitle);
bnd = findobj(gcf,'tag','txtboxdbase');
set(bnd,'string',ALLFIG.dbpath);
ybs = findobj(gcf,'tag','txtboxyear');
set(ybs,'string', yb);

%% test for REDO
if isfield(ALLFIG, 'webwin')
   if ALLFIG.webwin.v9(end-16:end) == ALLFIG.dbpath(end-16:end)
      v1 = findobj(gcf,'Tag','txtboxtitle');
      v2 = findobj(gcf,'Tag','txtboxyear');
      v3 = findobj(gcf,'Tag','txtboxctddbase');
      v4 = findobj(gcf,'Tag','txtboxstafile');
      v5 = findobj(gcf,'Tag','txtboxgs');
      v6 = findobj(gcf,'Tag','txtboxconvert');
      v7 = findobj(gcf,'Tag','txtboxnewext');
      v8 = findobj(gcf,'Tag','txtboxtranslator');
      v9 = findobj(gcf,'Tag','txtboxdbase');
      for m = 1:9
         gstr = sprintf('set(v%d,''string'', ALLFIG.webwin.v%d)',m,m);
         eval(gstr)
      end  
   end
end

%%%%%%%%%%%

function main()      % make and/or load shipboard data and process

global XYDATA
global UVDATA
global CONTFIG
global VECFIG
global ALLFIG
global CONTOUR_PREFIX VECTOR_PREFIX  NEW_EXTENSION
evalin('base','global VECFIG_PREFIX')
evalin('base','global CONTOUR_PREFIX')
evalin('base','global NEW_EXTENSION')

han = findobj(gcf,'tag','txtboxtitle');
cruise_name = get(han,'string');
if isempty(cruise_name)
   noticeOK('Please fill in Cruise ID: ');
   return
end
ybs = findobj(gcf,'tag','txtboxyear');
ybstr = get(ybs,'string');
year_base = str2num(ybstr);
ctbn = findobj(gcf,'tag','txtboxctddbase');
ctddb = get(ctbn,'string');
sfh = findobj(gcf,'tag','txtboxstafile');
sta_file = get(sfh,'string');
trh = findobj(gcf,'tag','txtboxtranslator');
translator = get(trh,'string');
nex = findobj(gcf,'tag','txtboxnewext');
NEW_EXTENSION = get(nex,'string');
new_extension = NEW_EXTENSION;
csh = findobj(gcf,'tag','txtboxconvert');
CONVERT_SWITCHES = get(csh,'string');
gsh = findobj(gcf,'tag','txtboxgs');
GS_SWITCHES = get(gsh,'string');
bnd = findobj(gcf,'tag','txtboxdbase');
dbname = get(bnd,'string');
XYDATA.dbname = dbname; % e.g. =  /home/../a0000dir.blk
t_file = [];
sect_colors = 'mb';
sect_color = sect_colors(1);
fontsize = 18;
set(0,'defaultaxesfontsize',14)
CONTOUR_PREFIX = 'cont_';
VECTOR_PREFIX = 'vect_';

close

if (strcmp(translator,'i')) % big If = the active code from webglobs
   convert_bin = 'convert';
   [errmsg,bin]=unix(sprintf('which %s',convert_bin));
   badi = find(bin==10); bin(badi)=[];  %eliminate existing newlines
   if (strcmp(convert_bin,bin(end-length(convert_bin)+1:end)))
      convert_bin = bin;
   else
      help iconvert
      error(sprintf('Check your path to %s\n',convert_bin))
   end
end

uvfile = 'c_sect_uv.mat';
xyfile = 'c_sect_xy.mat'; % new scheme, standard files from adcpsect.py
uvfilev = 'v_sect_uv.mat';
xyfilev = 'v_sect_xy.mat'; % new scheme

while ( ~exist(uvfile, 'file') | ~exist(xyfile, 'file') | ~exist(uvfilev, 'file') | ~exist(xyfilev, 'file') )
   msg = sprintf(' \nThe needed *.mat files not found.\nDo you want to run adcpsect again?');
   yn = select(msg, 'Yes', 'No (will find)','Cancel');
   if yn == 1
      msg = sprintf('\n\nCreate both contour and vector files.\n \n');
      msg = sprintf('%sUse Intervals for contours \nand use prefix = c_sect.\n\n', msg);
      msg = sprintf('%sUse Boundaries for vectors \nand use prefix = v_sect.\n', msg);
      noticeOK(msg);
      uiwait 
      str = sprintf('! adcpsect.py -d %s -o %s --web', ALLFIG.dbpath, ALLFIG.outpath);
      eval(str)
   elseif yn == 2
      % first retrieve contour data.   
      % Equals basic reference data (maps, etc.)
      % of course, user can substitute vector *.mat data
      % e.g., if contours not to be made (i.e. double up)
      gplotconfig    % being used as dialog form only.
      
      xh = findobj(gcf,'tag','btnCancel');
      set(xh,'Callback','close(gcbf);')
      tp = findobj(gcf,'tag','txtboxconfig');
      pathroot = pwd;
      guess = fullfile(pathroot, '*_xy.mat');
      set(tp, 'string', guess);
      set(tp,'HorizontalAlignment','right');
      nst = findobj(gcf,'tag','StaticText3');
      set(nst,'string',sprintf('Enter path to _xy.mat file for Contours:'));
      uiwait
      % call back goes to plotmaster('okcallback3') 
      % which establishes ALLFIG.fullfilename, and closes

      uvfile = [ALLFIG.fullfilename(1:end-6), 'uv.mat'];
      xyfile = [ALLFIG.fullfilename(1:end-6), 'xy.mat']; 
      
      % repeat exercise for vector data
      gplotconfig % being used as dialog form only
      
      xh = findobj(gcf,'tag','btnCancel');
      set(xh,'Callback','close(gcbf);')    
      tp = findobj(gcf,'tag','txtboxconfig');
      pathroot = pwd;
      guess = fullfile(pathroot, '*_xy.mat');
      set(tp, 'string', guess);
      set(tp,'HorizontalAlignment','right');
      nst = findobj(gcf,'tag','StaticText3');
      set(nst,'string','Enter path to _xy.mat file for Vectors:');
      uiwait
      % call back goes to plotmaster('okcallback3') 
      % which establishes ALLFIG.fullfilename, and closes

      uvfilev = [ALLFIG.fullfilename(1:end-6), 'uv.mat'];
      xyfilev = [ALLFIG.fullfilename(1:end-6), 'xy.mat']; 
   else
      return  %break
   end
end

UVDATA = load(uvfile);
XYDATA = load(xyfile);
preparedata

notice('Working . . . ', 1);
load(uvfile);
load(xyfile);  % hist. redundancy; easiest to retain
x=unwrap_lon(xyt(1,:)'); 
% x=xyt(1,:)';
y=xyt(2,:)';
dday=xyt(3,:)';
n=length(uv(1,:));
u=uv(:,1:2:n);
v=uv(:,2:2:n);
badi=find((isnan(dday)) | (isnan(x)) | isnan(y));
dday(badi)=[];
x(badi)=[];
y(badi)=[];
u(:,badi)=[];
v(:,badi)=[];

%currently u,v are averages from 25:10:450 (see web_as.prl)
%mean upper level velocities (d_start and d_end were set in webglobs.m)
d_start = 100; d_end = 150; % temps -- both subject to immediate revision
jdepth=find((zc>=d_start)&(zc<=d_end)); 
um=mean(u(:,jdepth)');
vm=mean(v(:,jdepth)');
[lonrange latrange] = map_range(x, y);
xykey = [lonrange(1)+.05*diff(lonrange)  latrange(1)+diff(latrange)*.05];
if (diff(latrange)<=diff(lonrange));    %wide
   degperinch=diff(lonrange)/7; %set degperinch by width
else                                    %tall
   degperinch=diff(latrange)/7; % 7 = max_inches; %set degperinch by height
end
orientation='tall';

%%get topography
%use largest decimation for whole cruise
if exist('ss_block') & max(abs(latrange))<70 
   [top_lon,top_lat,topog]= ss_block(lonrange,latrange,9);
else
   [topog, top_lon, top_lat] = m_tbase([lonrange, latrange]);
end

while 1  %%%%% GRAND ACTIVE LOOP %%%%% ******************************
   
   ALLFIG.out = [];
   sect_colors=['mb'];
   sect_color=sect_colors(1);
   firstplt2 %loads current sectinfo (if it exists) and start the plots
   set(1, 'position', [ 6 40 500 360]);
   set(2, 'position', [ 514 40 500 360]);
   %%%%%%%% MAIN MENU %%%%%%%%*************
   sec_menu_num = select('Edit sections: ', ...
      'Redo adcpsect', ...
      'Add new section(s)', ...
      'Edit existing sections(s)', ...
      'Delete section(s)', ...
      'Finished / (re)write "html/png" files', ...
      'Cancel / Abandon');
   
   switch sec_menu_num
      
   case 1 % Redo adcpsect
      str = sprintf('! adcpsect.py -d %s -o %s --web', ALLFIG.dbpath, ALLFIG.outpath);
      eval(str)
   case 2 % Add new section --- (one full loop)
      brakeout = 0;
      ii=gxytzoom2(XYDATA.x,XYDATA.y,XYDATA.dday); 
      if isempty(ii), break; end;
      %get the new section name
      sec_name = [];
      while isempty(sec_name)
         msg = sprintf('Please enter section name:  \n(new or to overwrite previous) ');
         cell_sec_name = getdatadlg(msg,'SECTIONS');
         if ~isempty(cell_sec_name), sec_name = cell_sec_name{1}; end;  % convert from 'cell' type return
         if isempty(cell_sec_name),
            yn = select('Do you wish to cancel the new section ?','Yes','No');
            if yn == 1
               brakeout = select('Do you wish to abandon selecting new sections ?','Yes','No');
               if brakeout == 1, break; end % naming section   
            end
         end 
      end
      if brakeout == 1, break; end % grand active loop -> to main menu
      
      which_plots = select('Make which plots?','Contour only', 'Vector only', 'Both'); 
      if which_plots ~= 2
         llnum = select('Plot contours against ?',...
         'Longitude (x)','Latitude (y)', 'Time (t)'); %, 'No contours');
      else
         llnum = 4;
      end
      if which_plots == 1, llnum = llnum + 4; end;
      CONTFIG.reftype = llnum; % must be here, not misplaced
      localreftype = llnum; % still needs saving locally
%   CONTFIG.reftype's complete code:
%          1 both, long
%          2 both, lat
%          3 both, time
%          4 vec only
%          5 cont only, long
%          6 cont only, lat
%          7 cont only, time
      
      f1;plot(x,y,'k');hold on;axis('equal');
      h=plot(x(ii),y(ii),sect_color) ;lw(h,2)
      pause(1.5)        
      message1 = sprintf('When you get the crosshairs in figure(1),  ');
      message2 = sprintf('%s\nclick for the location of the left edge \nof the text.  ', message1);
      notice(message2, 1.5);
      [xtext_loc,ytext_loc]=ginput(1);
      h=text(xtext_loc, ytext_loc, sec_name); set(h,'color', sect_color);
      set(h,'fontsize',fontsize);
      
      %now plot it on figure(2)
      figure(2) %now go back and pick an active region for this section
      hold on
      sect_color=sect_colors(~(sect_colors==sect_color)); %i.e. switch colors
      plot(x,y,'k');hold on;axis('equal');    
      h=plot(x(ii),y(ii),sect_color) ;lw(h,2)
      pause(1.5)
      h=text(xtext_loc,ytext_loc,sec_name);set(h,'color',sect_color);
      set(h,'fontsize',fontsize);
      
      %get the appropriate index and store the info in a structure
      if (~exist('sect_info'))  %create  it
         sect_matchi=1;
      else  %it exists.  now either overwrite one entry or append
         %first look for a match of sec_name in the sect_info data structure
         sect_matchi=[];
         for jj=1:length(sect_info)
            if (strcmp(sect_info(jj).name, sec_name))
               sect_matchi=jj;
               break; %i.e. we have a match: now exit to the next stage
            end
         end
         if (isempty(sect_matchi)) % ( no match:append with a new section)
            sect_matchi=1+length(sect_info);
         end
      end
      sect_info(sect_matchi).dates=[min(dday(ii)) max(dday(ii))];
      sect_info(sect_matchi).llnum=llnum;
      sect_info(sect_matchi).xytext=[xtext_loc,ytext_loc];
      sect_info(sect_matchi).name=sec_name;
      sect_info(sect_matchi).ii=ii; %[min(ii) max(ii)];
      save6 sectinfo  sect_info
      CONTFIG.printfilefn = sprintf('cont_%s', sec_name);
      VECFIG.printfilefn = sprintf('vect_%s', sec_name);

      mksecplt2 %  ### key line:  new version -> calls to "gplot" output options ########
      
      sect_info(end).llnum = localreftype;  %CONTFIG.reftype;
      sect_info(end).ii=ii;  % contour based (no longer used) %[min(ii) max(ii)];
      if exist('fig_position','var')
         save6 sectinfo ...
		      sect_info fig_position ax_position paperposition box_cx box_cy;
      end
      
   case 3  % Edit existing section(s)
      ALLFIG.type = 2;
      picksections;
      uiwait
      if ~isempty(ALLFIG.out), 
         msg = '';
         load sectinfo
         for jj = 1:length(sect_info)
            vln = sprintf('webvspecs_%s.mat', sect_info(jj).name);
            cln = sprintf('webcspecs_%s.mat', sect_info(jj).name); 
            if ALLFIG.out(jj,1)
               if ALLFIG.out(jj, 2)
                  if ~exist(cln, 'file')
                     msg = sprintf('%sNo contour file for section %s found\n', msg, sect_info(jj).name);
                  else
                     contourmaster('configsetup', cln)
                     uiwait
                  end
               end
               if ALLFIG.out(jj, 3)
                  if ~exist(vln, 'file')
                     msg = sprintf('%sNo vector file for section %s found\n', msg, sect_info(jj).name);
                  else
                     vectormaster('configsetup', vln)
                     uiwait
                  end
               end      
            end
         end
         if ~isempty(msg), 
            notice(msg, 2); 
         end
      end
      ALLFIG.out = [];
      
   case 4  % Delete section(s)
      ALLFIG.type = 1;
      picksections;
      uiwait
      if ~isempty(ALLFIG.out)
         load sectinfo
         reps = length(sect_info);
         for jj = reps:-1:1
            if ALLFIG.out(jj) 
               success = 1;
               scratch = sprintf('delete *%s.*  ;',sect_info(jj).name);
               eval(scratch, 'success = 0;')
               if success == 0, noticeOK('No accessory files to delete'); end;
               sect_info(jj) = [];
            end
         end
         
         if exist('ax_position','var')
            save6 sectinfo ax_position fig_position box_cx box_cy paperposition sect_info 
         else 
            save6 sectinfo sect_info
         end
         
         close(1); close(2);
         firstplt % reloads the plots
         set(1, 'position', [ 5 40 500 360]);
         set(2, 'position', [ 512 40 500 360]);
         
         msg = sprintf('Deletion(s) complete. \n\nWhen deletions are completed, \n');
         msg = sprintf('%sYou will need to re-write html files \n(i.e. nav_exten & sec_list.html).', msg);
         notice(msg, 2);
      end
      ALLFIG.out = [];

   case 5 % Finished/(re)write
      break
      % just continue on to final processing
   case 6 % Cancel/Abandon
      hold off;
      close all;
      notice('Done ...', 0.3);
      disp('Done ...')
      return;
   end % switch cases   
end %%%%% grand active loop %%%%% end %% MAIN MENU %%%%%%%%%

%%%%%%%%%%% FINAL PROCESSING

notice('Do not disturb the Large Figure No. 2 while it is being processed',2);
notice('Wait for new menu',2);
pause(4); 

wrapitup2;  %saves sectinfo and position information; major plotting
thumbnail; % create mini_nav.eps & mini_nav.gif for web page thumbnail
close all   

% %============  html ==============
message = sprintf(' Write the .html files ?\n(Highly recommended!)');
yn = select(message,'Yes','No');
if yn == 1
   notice('Writing .html files now, Please wait ');
   hold off;
   wrt_html2(cruise_name,sect_info,box_cx,box_cy);  
else
   disp('Not writing html files')
end

%============ new extension  ==============
doemall=(1==0);   %start false
for sect_matchi=1:length(sect_info)
   if (~doemall)
      menu_num=...
         select(sprintf(' Make a %s for section %s (convert from eps to %s)?',...
         NEW_EXTENSION, sect_info(sect_matchi).name, NEW_EXTENSION), ...
         'Yes','No','Yes to the rest','No to the rest');
      if (menu_num==3) %whip through next iteration(s)
         doemall=(1==1);
      end
      if (menu_num==4)
         break
      end
   end
   
   if ((menu_num==1) | (doemall))
      sec_name=sect_info(sect_matchi).name;
      fnmc = sprintf('cont_%s.eps', sec_name);
      fnmv = sprintf('vect_%s.eps', sec_name);
      if exist(fnmc,'file'), which_kind = 1; end;
      if exist(fnmv,'file'), which_kind = 2; end;
      if exist(fnmc,'file') & exist(fnmv,'file'), which_kind = 3; end;
      if ~exist(fnmc,'file') & ~exist(fnmv,'file'), which_kind = 4; end;
      notice('Working ... ', 0.3)
      
      switch which_kind
         
      case 1 % contour only
         thistype = CONTOUR_PREFIX;
      case 2 % vector only
         thistype = VECTOR_PREFIX; 
      case 3 % both
         thistype = CONTOUR_PREFIX; % do one extra before dropping through
         if (strcmp(translator,'i'))
            iconvert([thistype,sec_name], 'eps', new_extension,CONVERT_SWITCHES)
         else  %if (strcmp(translator,'g'))
            gsconvert([thistype,sec_name],'eps',new_extension,GS_SWITCHES)
         end 
         thistype = VECTOR_PREFIX;
      case 4 % none
         msg = sprintf('Neither %s nor %s found', fnmc, fnmv);
         noticeOK(msg);
         break
      end
      
      %convert eps to another file type 
      if (strcmp(translator,'i'))
         iconvert([thistype,sec_name], 'eps', new_extension,CONVERT_SWITCHES)
      else  %if (strcmp(translator,'g'))
         gsconvert([thistype,sec_name],'eps',new_extension,GS_SWITCHES)
      end 
   end
end  % for

%%%%% end final processing %%%%%%
hold off;
close all;
eval('! chmod 775 *.*')
notice('Done ...', 0.3);
disp('Done ...')