function fig = PLsort(action, varargin)
% This is the machine-generated representation of a Handle Graphics object
% and its children.  Note that handle values may change when these objects
% are re-created. This may cause problems with any callbacks written to
% depend on the value of the handle at the time the object was saved.
% This problem is solved by saving the output as a FIG-file.
%
% To reopen this object, just type the name of the M-file at the MATLAB
% prompt. The M-file and its associated MAT-file must be on your path.
% 
% NOTE: certain newer features in MATLAB may not have been saved in this
% M-file due to limitations of this format, which has been superseded by
% FIG-files.  Figures which have been annotated using the plot editor tools
% are incompatible with the M-file/MAT-file format, and should be saved as
% FIG-files.

if nargin<1,
  action='InitializePLsort';
end;

feval(action,varargin{:});
return;

%%%
%%%   Sub-function - InitializePLsort
%%%

function InitializePLsort()

load PLsort

h0 = figure('Units','normalized', ...
	'Color',[0 0.9 0.9], ...
	'Colormap',mat0, ...
	'FileName','C:\plgui\mygui\PLsort.m', ...
	'Name','VPR: ROI/TRROI Copy', ...
	'MenuBar','none', ...
	'NumberTitle','off', ...
	'PaperPosition',[18 180 576 432], ...
	'PaperUnits','points', ...
	'Position',[0.01 .01 .95 0.95], ...
	'Tag','VPR Manual Sort', ...
	'ToolBar','none');
h1 = uicontrol('Parent',h0, ...
	'Units','normalized', ...
	'BackgroundColor',[0 0.95 0.95], ...
	'ListboxTop',0, ...
	'Position',[0.5544747081712063 0.1092896174863388 0.4182879377431906 0.7377049180327869], ...
	'Style','frame', ...
	'Tag','Frame1');
h1 = uicontrol('Parent',h0, ...
	'Units','normalized', ...
	'BackgroundColor',[0 0.95 0.95], ...
	'ListboxTop',0, ...
	'Position',[0.01945525291828794 0.1092896174863388 0.4182879377431907 0.7377049180327869], ...
	'Style','frame', ...
	'Tag','Frame1');
h1 = uicontrol('Parent',h0, ...
	'Units','normalized', ...
	'BackgroundColor',[0 0.95 0.95], ...
	'Callback','PLsort CopyRois', ...
	'FontWeight','bold', ...
	'ListboxTop',0, ...
	'Position',[0.4571984435797665 0.4918032786885246 0.07684824902723736 0.07240437158469945], ...
	'String','->COPY->', ...
	'Tag','Pushbutton1');
h1 = uicontrol('Parent',h0, ...
	'Units','normalized', ...
	'BackgroundColor',[0 0.9 0.9], ...
	'FontWeight','bold', ...
	'ListboxTop',0, ...
	'Position',[0.0195    0.8880    0.1002    0.0355], ...
	'String','Base Path', ...
	'Style','text', ...
	'Tag','StaticText1');
h1 = uicontrol('Parent',h0, ...
	'Units','normalized', ...
	'BackgroundColor',[0 0.9 0.9], ...
	'FontWeight','bold', ...
	'ListboxTop',0, ...
	'Position',[0.2043    0.8880    0.1002    0.0355], ...
	'String','Cruise', ...
	'Style','text', ...
	'Tag','StaticText1');
h1 = uicontrol('Parent',h0, ...
	'Units','normalized', ...
	'BackgroundColor',[0 0.9 0.9], ...
	'FontWeight','bold', ...
	'ListboxTop',0, ...
	'Position',[0.3794    0.8880    0.1002    0.0342], ...
	'String','VPR Tow', ...
	'Style','text', ...
	'Tag','StaticText1');
h1 = uicontrol('Parent',h0, ...
	'Units','normalized', ...
	'BackgroundColor',[1 1 1], ...
	'Callback','PLsort GetCruises', ...
	'FontSize',12, ...
	'HorizontalAlignment','left', ...
	'ListboxTop',0, ...
	'Position',[0.1167    0.9    0.0885    0.03], ...
	'String','c:\data', ...
	'Style','edit', ...
	'Tag','EditText Disc', ...
   'TooltipString','Enter base path and press Return (= Enter)');
h1 = uicontrol('Parent',h0, ...
	'Units','normalized', ...
	'BackgroundColor',[0 0.95 0.95], ...
	'FontSize',12, ...
	'FontWeight','bold', ...
	'ListboxTop',0, ...
	'Position',[0.1556    0.7787    0.1119    0.0273], ...
	'String','ROIS', ...
	'Style','text', ...
	'Tag','StaticText2');
h1 = uicontrol('Parent',h0, ...
	'Units','normalized', ...
	'BackgroundColor',[0 0.95 0.95], ...
	'FontSize',12, ...
	'FontWeight','bold', ...
	'ListboxTop',0, ...
	'Position',[0.6128404669260701 0.7786885245901639 0.316147859922179 0.03278688524590164], ...
	'String','TRROIS  (Training ROIs)', ...
	'Style','text', ...
   'Tag','StaticText2');
h1 = uicontrol('Parent',h0, ...
	'Units','normalized', ...
	'BackgroundColor',[0 0.95 0.95], ...
	'Callback','close(gcbf)', ...
	'FontWeight','bold', ...
	'ListboxTop',0, ...
	'Position',[0.7 0.04 0.06 0.04], ...
	'String','EXIT', ...
	'Tag','Pushbutton1');
h1 = uicontrol('Parent',h0, ...
	'Units','normalized', ...
	'BackgroundColor',[0 0.95 0.95], ...
	'Callback','sort_help', ...
	'FontWeight','bold', ...
	'ListboxTop',0, ...
	'Position',[0.55 0.04 0.06 0.04], ...
	'String','HELP', ...
	'Tag','Pushbutton Help', ...
	'TooltipString','Help for Focus Detection');
h1 = uicontrol('Parent',h0, ...
	'Units','normalized', ...
	'BackgroundColor',[1 1 1], ...
	'FontSize',12, ...
	'HorizontalAlignment','left', ...
	'ListboxTop',0, ...
	'Position',[0.37    0.74    0.04    0.025], ...
	'String','1000', ...
	'Style','edit', ...
	'Tag','EditText NumRois', ...
   'TooltipString','Enter Number of ROIs to be copied (per hour).');
h1 = uicontrol('Parent',h0, ...
	'Units','normalized', ...
	'BackgroundColor',[0 0.95 0.95], ...
	'FontWeight','bold', ...
	'ListboxTop',0, ...
	'Position',[0.29    0.73    0.08    0.03], ...
	'String','ROIs/Hour', ...
	'Style','text', ...
	'Tag','StaticText1', ...
   'TooltipString','Number of ROIs to be copied (per hour). Enter all to copy all rois for selected hours.');

GetCruises(gcf);
if nargout > 0, fig = h0; end

function GetCruises(fig)

if nargin<1,
   h=gcbf;
else
   h=fig;
end;

if ~isempty(h)
  %delete existing popups
  h1=findobj(h,'Tag','PopupMenu Cruise'); delete(h1);
  h1=findobj(h,'Tag','PopupMenu Tow'); delete(h1);
  h1=findobj(h,'Tag','StaticText Days'); delete(h1);
  h1=findobj(h,'Tag','Listbox Hours'); delete(h1);
  h1=findobj(h,'Tag','StaticText TRDays'); delete(h1);
  h1=findobj(h,'Tag','Listbox TRHours'); delete(h1);
  %find cruises
  h1=findobj(h,'Tag','EditText Disc');
  disc=get(h1,'String');
  cruises=dir(disc);
  discarray=str2mat(cruises.name);
  if size(discarray,1)>2,    
     discarray=discarray(3:size(discarray,1),:);
     discarray=str2mat('Select',discarray);
     h1 = uicontrol('Parent',h, ...  
          'Units','normalized', ...
          'BackgroundColor',[1 1 1], ...
          'Callback','PLsort GetTows', ...
          'ListboxTop',0, ...
          'Position',[0.282 0.89 0.0720 0.035], ...
          'String',discarray, ...
          'max',size(discarray,1), ...
          'min',1, ...
          'Style','popupmenu', ...
          'Tag','PopupMenu Cruise', ...
          'TooltipString','Select Cruise', ...
          'Value',1);
  end
end


function GetTows()

h=gcbf;
if ~isempty(h)
  %delete existing tow/day/hour objects
  h1=findobj(h,'Tag','PopupMenu Tow'); delete(h1);
  h1=findobj(h,'Tag','StaticText Days'); delete(h1);
  h1=findobj(h,'Tag','Listbox Hours'); delete(h1);
  h1=findobj(h,'Tag','StaticText TRDays'); delete(h1);
  h1=findobj(h,'Tag','Listbox TRHours'); delete(h1);
  %find tows
  h1=findobj(h,'Tag','EditText Disc');
  disc=get(h1,'String');
  h1=findobj(h,'Tag','PopupMenu Cruise');
  dummystring=get(h1,'String');v=get(h1,'value');
  cruise=deblank(dummystring(v,:));
  pathname=[disc,filesep,cruise,filesep,'rois'];
  tows=dir([pathname '\v*']);
  towarray=str2mat(tows.name);
  if ~isempty(towarray),
     towarray=sortrows(towarray);
     towarray=str2mat('Select',towarray);
     h1 = uicontrol('Parent',h, ...  
          'Units','normalized', ...
          'BackgroundColor',[1 1 1], ...
          'Callback','PLsort ShowRoiTree;PLsort ShowTRRoiTree', ...
          'ListboxTop',0, ...
          'Position',[0.458 0.89 0.0720 0.035], ...
          'String',towarray, ...
          'max',size(towarray,1), ...
          'min',1, ...
          'Style','popupmenu', ...
          'Tag','PopupMenu Tow', ...
          'TooltipString','Select VPR #', ...
          'Value',1);
  end
end

function ShowRoiTree()

h=gcbf;
if ~isempty(h)
   %delete existing roi tree
   h1=findobj(h,'Tag','StaticText Days'); delete(h1);
   h1=findobj(h,'Tag','Listbox Hours'); delete(h1);
   %find days for this tow
   h1=findobj(h,'Tag','EditText Disc');
   disc=get(h1,'String');
   h1=findobj(h,'Tag','PopupMenu Cruise');
   dummystring=get(h1,'String');v=get(h1,'value');
   cruise=deblank(dummystring(v,:));
   h1=findobj(h,'Tag','PopupMenu Tow');
   dummystring=get(h1,'string');v=get(h1,'value');
   tow=deblank(dummystring(v,:));
   pathname=[disc,filesep,cruise,filesep,'rois',filesep,tow];
   days=dir([pathname '\d*']);
   dayarray=str2mat(days.name);
   if ~isempty(dayarray),
      dayarray=sortrows(dayarray);
      for j=1:size(dayarray,1),
         h1 = uicontrol('Parent',h, ...
            'Units','normalized', ...
            'BackgroundColor',[0 0.95 0.95], ...
            'FontWeight','bold', ...
            'ListboxTop',0, ...
            'Position',[.05+0.08*(j-1)   0.7    0.05    0.03], ...
            'String',dayarray(j,:), ...
            'Style','text', ...
            'Tag','StaticText Days');
         pathname2=[pathname, filesep, dayarray(j,:)];
         hours=dir([pathname2 '\h*']);
         hr=sortrows(str2mat(hours.name));
         if ~isempty(hr),
            nk=size(hr,1);
            for k=1:nk,
               [s,w]=dos(['dir /b ' pathname2 filesep deblank(hr(k,:)) filesep '*.tif | wc -l']);
               w=fliplr(deblank(fliplr(w(1:size(w,2)-1))));%gets rid of leading blanks and trailing cr.
               if k==1,
                  hr=str2mat([deblank(hr(k,:)) ' (' w ')'], hr(k+1:size(hr,1),:));
               elseif k==nk
                  hr=str2mat(hr(1:k-1,:), [deblank(hr(k,:)) ' (' w ')']);
               else
                  hr=str2mat(hr(1:k-1,:), [deblank(hr(k,:)) ' (' w ')'], hr(k+1:size(hr,1),:));
               end
            end;
            h1 = uicontrol('Parent',h, ...
               'Units','normalized', ...
               'BackgroundColor',[1 1 1], ...
               'Position',[.04+0.08*(j-1)   0.7-((nk+2)*.02)    0.072    (nk+2)*0.02], ...
               'String',[blanks(size(hr,2));hr;blanks(size(hr,2))], ...
               'fontname','helvetica', ...
               'fontsize',7, ...
               'Style','listbox', ...
               'Tag','Listbox Hours', ...
               'min',1, ...
               'max',max(nk)+2, ...
               'Value',[]);
         end
      end
   end
end;

function ShowTRRoiTree()

h=gcbf;
if ~isempty(h)
   %delete existing trroi tree
   h1=findobj(h,'Tag','StaticText TRDays'); delete(h1);
   h1=findobj(h,'Tag','Listbox TRHours'); delete(h1);
   %find days for this tow
   h1=findobj(h,'Tag','EditText Disc');
   disc=get(h1,'String');
   h1=findobj(h,'Tag','PopupMenu Cruise');
   dummystring=get(h1,'String');v=get(h1,'value');
   cruise=deblank(dummystring(v,:));
   h1=findobj(h,'Tag','PopupMenu Tow');
   dummystring=get(h1,'string');v=get(h1,'value');
   tow=deblank(dummystring(v,:));
   pathname=[disc,filesep,cruise,filesep,'trrois',filesep,tow];
   days=dir([pathname '\d*']);
   dayarray=str2mat(days.name);
   if ~isempty(dayarray),
      dayarray=sortrows(dayarray);
      for j=1:size(dayarray,1),
         h1 = uicontrol('Parent',h, ...
            'Units','normalized', ...
            'BackgroundColor',[0 0.95 0.95], ...
            'FontWeight','bold', ...
            'ListboxTop',0, ...
            'Position',[.59+0.08*(j-1)   0.7    0.05    0.03], ...
            'String',dayarray(j,:), ...
            'Style','text', ...
            'Tag','StaticText TRDays');
         pathname2=[pathname, filesep, dayarray(j,:)];
         hours=dir([pathname2 '\h*']);
         hr=sortrows(str2mat(hours.name));
         if ~isempty(hr),
            nk=size(hr,1);
            for k=1:nk,
               [s,w]=dos(['dir /b ' pathname2 filesep deblank(hr(k,:)) filesep '*.tif | wc -l']);
               w=fliplr(deblank(fliplr(w(1:size(w,2)-1))));%gets rid of leading blanks and trailing cr.
               if k==1,
                  hr=str2mat([deblank(hr(k,:)) ' (' w ')'], hr(k+1:size(hr,1),:));
               elseif k==nk
                  hr=str2mat(hr(1:k-1,:), [deblank(hr(k,:)) ' (' w ')']);
               else
                  hr=str2mat(hr(1:k-1,:), [deblank(hr(k,:)) ' (' w ')'], hr(k+1:size(hr,1),:));
               end
            end;
            h1 = uicontrol('Parent',h, ...
               'Units','normalized', ...
               'BackgroundColor',[1 1 1], ...
               'Position',[.58+0.08*(j-1)   0.7-((nk+2)*.02)    0.072    (nk+2)*0.02], ...
               'String',[blanks(size(hr,2));hr;blanks(size(hr,2))], ...
               'fontname','helvetica', ...
               'fontsize',7, ...
               'Style','listbox', ...
               'Tag','Listbox TRHours', ...
               'min',1, ...
               'max',max(nk)+2, ...
               'Value',[]);
         end
      end
   end
end;

function CopyRois()

h=gcbf;
if ~isempty(h)
   %delete existing trroi tree
   h1=findobj(h,'Tag','StaticText TRDays'); delete(h1);
   h1=findobj(h,'Tag','Listbox TRHours'); delete(h1);
   
   hcopying = uicontrol('Parent',h, ...
        'Units','normalized', ...
        'BackgroundColor',[0 0.95 0.95], ...
        'FontWeight','bold', ...
        'ListboxTop',0, ...
        'Position',[.59   0.7    0.3    0.03], ...  
        'String','Copying Files...(This can take several minutes)', ...     
        'Style','text', ...      
        'Tag','StaticText Copying');
   %get # of rois to be copied per hour
   h1=findobj(h,'Tag','EditText NumRois');
   numrois=get(h1,'String');
   %find path for this tow
   h1=findobj(h,'Tag','EditText Disc');
   disc=get(h1,'String');
   h1=findobj(h,'Tag','PopupMenu Cruise');
   dummystring=get(h1,'String');v=get(h1,'value');
   cruise=deblank(dummystring(v,:));
   h1=findobj(h,'Tag','PopupMenu Tow');
   dummystring=get(h1,'string');v=get(h1,'value');
   tow=deblank(dummystring(v,:));
   roipath=[disc,filesep,cruise,filesep,'rois',filesep,tow];   
   trroipath=[disc,filesep,cruise,filesep,'trrois',filesep,tow];
   %specify cygwin path
   c1='c:\cygwin\bin';%dos fileseps
   c2='c:/cygwin/bin';%cygwin fileseps
   %make the trrois path if it doesnt already exist
   path1=[disc,filesep,cruise,filesep,'trrois'];
   if isempty(dir(path1));dos(['mkdir ' path1]);end;
   path1=[path1,filesep,tow];if isempty(dir(path1));dos(['mkdir ' path1]);end;
   days=dir([roipath filesep 'd*']);
   dayarray=str2mat(days.name);
   dayarray=sortrows(dayarray);
   h1=findobj(h,'Tag','Listbox Hours');
   h1=flipud(h1);
   for j=1:size(h1,1);%loop through the days
      roipath2=[roipath,filesep,dayarray(j,:)];
      hrstr=get(h1(j),'string');
      v=get(h1(j),'value');
      if min(v)>1 & max(v)<size(hrstr,1),
         trroipath2=[trroipath,filesep,dayarray(j,:)];
         if isempty(dir(trroipath2));dos(['mkdir ' trroipath2]);end;
         for k=1:length(v),
            hour=hrstr(v(k),1:3);
            trroipath3=[trroipath2 filesep hour filesep];
            roipath3=[roipath2 filesep hour];
            if isempty(dir(trroipath3));dos(['mkdir ' trroipath3]);end;
            if strcmpi('all',numrois),
               dos(['xcopy ' roipath3 ' ' trroipath3 ' /q']);
            else
               roipath4=roipath3;roipath4(roipath4=='\')='/';%need to use forward slashes with bash
               trroipath4=trroipath3;trroipath4(trroipath4=='\')='/';
               nnumrois=str2num(numrois);
               nnumroishr=str2num(hrstr(v(k),6:size(deblank(hrstr(v(k),:)),2)-1));
               if nnumroishr<nnumrois, nnumrois=nnumroishr; end;
               if nnumrois>500,%copy 500 at a time due to limitations of cp source buffer
                   nr=floor(nnumrois/500);
                   for n=1:nr;
                      dos([c1 '\bash -c "' c2 '/cp `' c2 '/find ' roipath4 ' -name *.tif | ' c2 '/head -' num2str(n*500) ' | ' c2 '/tail -500` ' trroipath4 '"']);
                   end
                   leftovers=nnumrois-nr*500;
                   if leftovers>0,
                     leftover=num2str(leftovers);
                     dos([c1 '\bash -c "' c2 '/cp `' c2 '/find ' roipath4 ' -name *.tif | ' c2 '/head -' num2str(nnumrois) ' | ' c2 '/tail -' leftover '` ' trroipath4 '"']);
                   end
               else
                   dos([c1 '\bash -c "' c2 '/cp `' c2 '/find ' roipath4 ' -name *.tif | ' c2 '/head -' num2str(nnumrois) '` ' trroipath4 '"']);
               end
             end %if ALL
          end %for k
       end %if min(v)>1 ...
    end % for j
   delete(hcopying);
   ShowTRRoiTree;
end
