function menu_callbacks_modis(action)
%
% NAME: menu_callbacks_modis.m
%
% FILE TYPE: function
%
% LANGUAGE: 
%	  Matlab, (http://www.mathworks.com)
%         Version 6.x
%       
% PURPOSE: switchboard function for all menu actions
%
% DESCRIPTION:
%
% COPYRIGHT INFORMATION:  
%	  (C) COPYRIGHT UW/SSEC ALL RIGHTS RESERVED, 2001
%	      Space Science & Engineering Center
%	      University of Wisconsin - Madison  
%     
% CATEGORY: 
%  MODIS Analyzer Toolkit (MANATee)
%       
% CALLING SEQUENCE: 
%    menu_callbacks_modis(action)
%
% INPUTS: action: a string corresponding to the menu action to be performed
%         e.g. 'load', 'bandplot', 'ScatterPlot'
%
% OPTIONAL INPUTS: 
%       
% OUTPUTS: None
%
% OPTIONAL OUTPUTS:
% 
% FILES:
%
%    REQUIRED:
%
%    INPUT:
%
%    OUTPUT:
%
% GLOBAL VARIABLES: scattercount, subcount, regionfigcount, linefigcount
%                   (persistent counting variables)
%  
% INTERNAL or EXTERNAL CALLS:
%
% SIDE EFFECTS: 
%       
% RESTRICTIONS: 
%
%    VERSION DEPENDENCIES: will not work with version 5 due to changes in GUI (i.e., openfig command)
%
%    TOOLBOX DEPENDENCIES:  
%
%    OS DEPENDENCIES:
%
%    OTHER DEPENDENCIES OR RESTRICTIONS:
%
% RELATED TOPICS:
%
% PROCEDURE or THEORY: 
%
% EXAMPLE or USAGE: menu_callbacks_modis('load')
%
% MODIFICATION HISTORY: 
%	  Written by:	 Kevin Baggett  31-Aug-2001 (UW-SSEC)
%     Coordinator:   Paolo Antonelli
%
% REVISION INFORMATION (RCS Keyword):
%   $Id: menu_callbacks_modis.m,v 1.68 2003/05/13 22:36:41 kevinb Exp $
%
%------------------------------------------------------------------------------

%------------------------------------------------------------------------------
%                REVISION INFORMATION (RCS Keyword variable)
%------------------------------------------------------------------------------

rcs_id =  '$Id: menu_callbacks_modis.m,v 1.68 2003/05/13 22:36:41 kevinb Exp $' ;

persistent scattercount; %count of number of boxes drawn on the scatter plot
persistent subcount; %count the number of subregions selected on scatter plot region
persistent regionfigcount; % counts number of region figures open 
persistent linefigcount % counts number of line figures open

if isempty(scattercount)
    scattercount=0;
    regionfigcount=0;
    linefigcount=0;
    subcount=0;
end
h=guidata(gcf);

switch(action)
   case 'load'
     try
         if isunix
             [h.FileName, h.PathName]=uigetfile('../Data/*.hdf','Input File');
         else
             [h.FileName, h.PathName]=uigetfile('..\Data\*','Input File');
         end
         %get imagedata for band 1 by default
	     h.vartoplot='''radiance''';
         h.doflipud=0; % initialize so that plot comes in as is
         h.dofliplr=0;
         set(h.mnuVariable1,'Checked','on');
         set(h.mnuVariable1,'Label','radiance');
         set(h.mnuVariable2,'Label','reflectance');
         h.band=1;
         [h.imagedata,bandAvail,h.latitude,h.longitude]=plotband(h.FileName,h.PathName,h.band,h.axDisplay,1,h.vartoplot,1,h.doflipud,h.dofliplr);
         %Enable buttons and menus that were disabled until file is loaded
         guidata(gcf,h);
         if bandAvail
	        set(h.mnuBand,'Enable','on');	
             set(h.mnuVariables,'Enable','on');
             set(h.mnuSelect,'Enable','on');
             set(h.mnuAnimate,'Enable','on');
             set(h.mnuMainRefresh,'Enable','on');
             set(h.mnuSettings,'Enable','on');
             set(h.mnuExport,'Enable','on');
             set(h.mnuFlipUD,'Checked','off');
             set(h.mnuFlipLR,'Checked','off');
             mouseMove(1);
         else
            msgbox('No contrast for visible band. Try infrared bands (20-25,27-36)');
            set(h.mnuBand,'Enable','on');
         end
     catch
         msgbox('File not loaded!');
     end
   case 'bandplot'
     %uncheck current item before checking a new one
     children=get(h.mnuVariables,'Children');
     for i=1:length(children)
         set(children(i),'Checked','off');
     end
     
     % compare callback object Label to see if selecting from Band menu or Variable menu
     if ~strncmp(get(gcbo,'Tag'),'mnuVariable',11)
        h.band=str2num(strtok(get(gcbo,'Label'),' '));
        visible=[1:19 26]; %visible MODIS bands
        if ismember(h.band,visible)
           set(h.mnuVariable1,'Label','radiance');
           set(h.mnuVariable2,'Label','reflectance');
        else %infrared 
           set(h.mnuVariable1,'Label','radiance');
           set(h.mnuVariable2,'Label','temperature');
        end
        h.vartoplot='''radiance''';
        set(h.mnuVariable1,'Checked','on');
     else
         variableToPlot=get(gcbo,'Label');
         h.vartoplot=['''' variableToPlot ''''];
         set(gcbo,'Checked','on');
     end
     [h.imagedata,bandAvail]=plotband(h.FileName,h.PathName,h.band,h.axDisplay,1,h.vartoplot,0,h.doflipud,h.dofliplr);
     guidata(gcf,h);
     if bandAvail
         set(h.mnuVariables,'Enable','on');
         set(h.mnuSelect,'Enable','on');
         set(h.mnuAnimate,'Enable','on');
         set(h.mnuMainRefresh,'Enable','on');
         set(h.mnuSettings,'Enable','on');
         set(h.mnuExport,'Enable','on');
         mouseMove(1);
     else
        set(h.mnuVariables,'Enable','off');
        set(h.mnuSelect,'Enable','off');
        set(h.mnuAnimate,'Enable','off');
        set(h.mnuMainRefresh,'Enable','off');
        set(h.mnuSettings,'Enable','off');
        set(h.mnuExport,'Enable','off');
        set(h.mnuPlot,'Enable','off');
        set(h.mnuLevel2,'Enable','off');
        set(h.mnuDataOutput,'Enable','off');
        msgbox('No contrast for visible band. Try infrared bands (20-25,27-36)');
        set(h.mnuBand,'Enable','on');
     end
   case 'contrast'
     contrast(h.imagedata);
   case 'animate'
     f=openfig('animate','reuse');
     hanim=guihandles(f);
     guidata(f,hanim);
   case 'exportFigure'
     f=openfig('export','reuse');
     hExport=guihandles(f);
     guidata(f,hExport);
     waitfor(f); % set filename to save and format
     exportFilename=evalin('base','exportFilename;');
     exportFormat=lower(evalin('base','exportFormat;'));
     set(gcf,'Units','inches');
     pos=get(gcf,'Position');
      keyboard
     exportfig(gcf,exportFilename,'Format',exportFormat,'Color','cmyk','Height',pos(4),'Width',pos(3),'Renderer','zbuffer');
     set(gcf,'Units','pixels');
   case 'Play'
     h1=guidata(1);
     sel_band=get_selected_entries(h.lstBand);
     playDirection=get(gcbo,'Label');
     animate(h1.FileName,h1.PathName,sel_band,h.axAnimate,str2num(get(h.edPlay,'String')),playDirection,h1.doflipud,h1.dofliplr,h1.rect,h.txtMessage);
   case 'projection'
     projection=get(gcbo,'Label');
     figNum=openfig('project','reuse');
     cla;
   	 project(h.imagedata.mimage,h.latitude,h.longitude,projection,figNum);
   case 'FlipUD' %flips image up and down until user unchecks it
       if strcmp(get(gcbo,'Checked'),'on');
           set(gcbo,'Checked','off');
           h.doflipud=0;
       else
           set(gcbo,'Checked','on');
           h.doflipud=1;
       end
       [h.imagedata,bandAvail,h.latitude,h.longitude]=plotband(h.FileName,h.PathName,h.band,h.axDisplay,1,h.vartoplot,1,h.doflipud,h.dofliplr);
       guidata(gcf,h);
   case 'FlipLR' %flips image left and right until user unchecks it
       if strcmp(get(gcbo,'Checked'),'on');
           set(gcbo,'Checked','off');
           h.dofliplr=0;
       else
           set(gcbo,'Checked','on');
           h.dofliplr=1;
       end
       [h.imagedata,bandAvail,h.latitude,h.longitude]=plotband(h.FileName,h.PathName,h.band,h.axDisplay,1,h.vartoplot,1,h.doflipud,h.dofliplr);
       guidata(gcf,h);
   case 'SelectRegion'
     rectStruc=SelectRegion(h.axDisplay);
     rectangle('Position',rectStruc.rect,'EdgeColor','m','LineWidth',2);
     % get size of overall image
     [imagex,imagey]=size(h.imagedata.mimage);
     %attach rectangle attributes to the main figure for later use
     %MODIS data to read is flipped on its side in this case - so exchange x,y values
     if h.doflipud
         rectStruc.rect(2)=imagex-(rectStruc.rect(2)+rectStruc.rect(4));
     end
     if h.dofliplr
         rectStruc.rect(1)=imagey-(rectStruc.rect(1)+rectStruc.rect(3));
     end

     h.origrect=rectStruc.rect;
     
     h.rect=fliprect(rectStruc.rect);
     set(h.mnuLevel2,'Enable','on');
     set(h.mnuPlot,'Enable','on');
     set(h.mnuDataOutput,'Enable','on');
     guidata(gcf,h);
   case 'SelectLine'
     % get 2 points from user input  
     [x,y]=ginput(2);
     %plot line on main figure before opening new figure
     dimImage=size(h.imagedata.mimage);
     % take care of when things are flipped
     tempx=x;
     tempy=y;
     if h.doflipud
         tempy=dimImage(1)-y;
     end
     if h.dofliplr
         tempx=dimImage(2)-x;
     end
     linerect=getLineRegion(tempx,tempy,dimImage);
     
     if ~isempty(linerect)
         hold on;
         plot(x,y,'m');

         f=openfig('line');
         hline=guihandles(f);
         hline.rect=linerect;
         
         var=getCheckedItem(h.mnuVariables);
         hline.var=['''' var '''']; %need 4 ' to make a single quote here
         set(hline.lstBand,'String',getband(var));
         
         %get region surrounding line and plot it
         hline.linedata=plotband(h.FileName,h.PathName,h.band,hline.axDisplay,1,hline.var,0,h.doflipud,h.dofliplr,hline.rect);
         
         %plot line on new display axis
         [row col]=size(hline.linedata.mimage);
         [hline.xinterp,hline.yinterp,hline.reverse]=plotLineOnRegion(x,y,row,col,hline.axDisplay);
         
         % get lat and lon data
	%      hline.linedata.latitude=h.latitude(floor(hline.rect(1))+1:floor(hline.rect(1))+floor(hline.rect(3)),...
	%                 floor(hline.rect(2))+1:floor(hline.rect(2))+floor(hline.rect(4)));
	%      hline.linedata.longitude=h.longitude(floor(hline.rect(1))+1:floor(hline.rect(1))+floor(hline.rect(3)),...
	%                 floor(hline.rect(2))+1:floor(hline.rect(2))+floor(hline.rect(4)));
        hline.linedata.latitude=h.latitude;
        hline.linedata.longitude=h.longitude;
	
         %increment and store line figure handle to main figure so it can be closed later
         %during main window refresh
         linefigcount=linefigcount+1;
         h.linefig(linefigcount)=f;
         guidata(1,h);
         guidata(f,hline);
         mouseMove(5);
     else
         msgbox('Line too close to the edge. Please select again');
     end
   case 'XSectionPlot'
     % make a cross section plot of the current variable
     h1=guidata(1);
     sel_band=get_selected_entries(h.lstBand);
     imagedata=zeros(length(h.xinterp),length(sel_band));
     for i=1:length(sel_band)
         linedata=plotband(h1.FileName,h1.PathName,sel_band(i),h.axDisplay,0,h.var,0,h1.doflipud,h1.dofliplr,h.rect);
         axes(h.axCrossSection);
         hold on;
         for j=1:length(h.xinterp)
            imagedata(j,i)=linedata.mimage(h.yinterp(j),h.xinterp(j));
         end
         set(gca,'XTick',[]);
         legendcell{i}=num2str(sel_band(i));
     end
     plot(imagedata);
     % put letter labels along the cross-section plots
     minval=min(min(imagedata));
     num_points=length(h.xinterp);
     pts_by_3=floor(num_points/3);
     if (max(h.xinterp)-min(h.xinterp) < 100)
         pts=[h.yinterp(1) h.yinterp(pts_by_3) h.yinterp(2*pts_by_3) h.yinterp(num_points)];
     else
         pts=[h.xinterp(1) h.xinterp(pts_by_3) h.xinterp(2*pts_by_3) h.xinterp(num_points)];
     end
     if h.reverse
        text(pts,[minval minval minval minval],{'D';'C';'B';'A'});
     else
        text(pts,[minval minval minval minval],{'A';'B';'C';'D'});
     end
     legend(legendcell);
   case 'LoadScatterPlot'
     scattercount=0;
     f=openfig('region');
     hreg=guihandles(f);
     set(hreg.mnuGetPoints,'Enable','off');
     set(hreg.mnuSelectSub,'Enable','off');
     set(hreg.mnuPseudochannel,'Enable','off');
     %store figure handle to main figure
     regionfigcount=regionfigcount+1;
     h.regionfig(regionfigcount)=f;
          %get variable popup current value
     hreg.var=['''' getCheckedItem(h.mnuVariables) ''''];
     %plot imagedata for the particular band and selected region (optional 10th argument)
     hreg.boxdata=plotband(h.FileName,h.PathName,h.band,hreg.axDisplay,1,hreg.var,0,h.doflipud,h.dofliplr,h.rect);
     %get lat and lon based on h.rect
%      hreg.boxdata.latitude=h.latitude(floor(h.rect(1))+1:floor(h.rect(1))+floor(h.rect(3)),...
%                 floor(h.rect(2))+1:floor(h.rect(2))+floor(h.rect(4)));
%      hreg.boxdata.longitude=h.longitude(floor(h.rect(1))+1:floor(h.rect(1))+floor(h.rect(3)),...
%                 floor(h.rect(2))+1:floor(h.rect(2))+floor(h.rect(4)));
    hreg.boxdata.latitude=h.latitude;
    hreg.boxdata.longitude=h.longitude;
     hreg.rect=h.origrect;
     guidata(f,hreg);
     guidata(1,h);
     mouseMove(3);
 case 'ScatterPlot'
     if ~isempty(str2num(get(h.txtEdit1,'String')) | str2num(get(h.txtEdit5,'String')))
         h.xch=[str2num(get(h.txtEdit1,'String')); str2num(get(h.txtEdit2,'String')); ...
		        str2num(get(h.txtEdit3,'String')); str2num(get(h.txtEdit4,'String'))];
         h.ych=[str2num(get(h.txtEdit5,'String')); str2num(get(h.txtEdit6,'String')); ...
		        str2num(get(h.txtEdit7,'String')); str2num(get(h.txtEdit8,'String'))];
         h.ops=[popupstr(h.popOp1); popupstr(h.popOp2); popupstr(h.popOp3); ...
		        popupstr(h.popOp4); popupstr(h.popOp5); popupstr(h.popOp6)];
         % x axis label 
         h.label{1}=getScatterLabel(h.xch,h.ops(1:3));
         %y axis label
         h.label{2}=getScatterLabel(h.ych,h.ops(4:6));
         %refresh scatter plot
    	 axes(h.axScatter);
         cla;
	     h1=guidata(1);
         subcount=1;
         graphColor=h1.plotStyle(subcount,:);
         h.data=scatterplot(h.xch,h.ych,h.ops,h1.rect,h1.PathName,h1.FileName,h.axScatter,h.label,graphColor);
         guidata(gcf,h);
         set(h.mnuGetPoints,'Enable','on');
         set(h.mnuSelectSub,'Enable','on');
         set(h.mnuPseudochannel,'Enable','on');
     else
         msgbox('Fill in missing X and Y axis values!');
         guidata(gcf,h);
     end
   case 'DataOutput' % loads data output figure, then outputs based on user selection (chkValues)
       f=openfig('txtOutput','reuse');
       htxt=guihandles(f);
       guidata(gcf,htxt);
       %chkValues set from txtOutput.fig callback and saved in base workspace
       % (see OutputOK block below)
       waitfor(f);
       chkValuesAvailable=evalin('base','exist(''chkValues'');');
       if ~chkValuesAvailable
		    m=msgbox('No text output generated on Close');
	        waitfor(m);	
		    break;
       end
       h1=guidata(1);
       varStr='';
       formatStr='';
       if evalin('base','chkValues.latlon;')
          % flip latlon argument - second to last in plotband call - and blank vartoplot argument
        if evalin('base','chkValues.outputRegion==1') % selected region (h1.rect argument)
            [h.imagedata,bandAvail,data.lat,data.lon]=plotband(h1.FileName,h1.PathName,h1.band,h1.axDisplay,0,'',1,h.doflipud,h.dofliplr,h1.rect);
        else  % entire granule
            [h.imagedata,bandAvail,data.lat,data.lon]=plotband(h1.FileName,h1.PathName,h1.band,h1.axDisplay,0,'',1,h.doflipud,h.dofliplr);
        end
          [x,y]=size(data.lat);
          data.lat=reshape(data.lat,x*y,1);
          data.lon=reshape(data.lon,x*y,1);
          latlonxy=[x,y];
          [varStr,formatStr]=buildTextOutputString(varStr,formatStr,'LatLon');
       end
       if evalin('base','chkValues.radiance;')
         numBandsSelected=length(evalin('base','chkValues.bandSelected;'));
         for i=1:numBandsSelected
            if evalin('base','chkValues.outputRegion==1') % selected region
                [h.imagedata,bandAvail]=plotband(h1.FileName,h1.PathName,evalin('base',sprintf('chkValues.bandSelected(%i);',i)),h1.axDisplay,0,'''Radiance''',0,h.doflipud,h.dofliplr,h1.rect);
            else %entire granule
                [h.imagedata,bandAvail]=plotband(h1.FileName,h1.PathName,evalin('base',sprintf('chkValues.bandSelected(%i);',i)),h1.axDisplay,0,'''Radiance''',0,h.doflipud,h.dofliplr);
            end
            h.imagedata.mimage=fliplr(flipud(h.imagedata.mimage));
            [x y]=size(h.imagedata.mimage);
            data.radiance(i,:)=reshape(h.imagedata.mimage,x*y,1)';
         end
         radxy=[x,y];
         [varStr,formatStr]=buildTextOutputString(varStr,formatStr,'Radiance',numBandsSelected);
       end
       if evalin('base','chkValues.reflectance;')
        allBandsSelected=evalin('base','chkValues.bandSelected;');
        numBandsSelected=length(allBandsSelected);
        for i=1:numBandsSelected
            try
                % function kicks out if not a visible band where reflectance available
                if evalin('base','chkValues.outputRegion==1') % selected region
                    [h.imagedata,bandAvail]=plotband(h1.FileName,h1.PathName,allBandsSelected(i),h1.axDisplay,0,'''Reflectance''',0,h.doflipud,h.dofliplr,h1.rect);
                else
                    [h.imagedata,bandAvail]=plotband(h1.FileName,h1.PathName,allBandsSelected(i),h1.axDisplay,0,'''Reflectance''',0,h.doflipud,h.dofliplr);
                end
                h.imagedata.mimage=fliplr(flipud(h.imagedata.mimage));
                [x y]=size(h.imagedata.mimage);
                data.reflectance(i,:)=reshape(h.imagedata.mimage,x*y,1)';
            catch
                % make sure get the same size x and y, use known reflectance band 1
                if evalin('base','chkValues.outputRegion==1') % selected region
                    [h.imagedata,bandAvail]=plotband(h1.FileName,h1.PathName,1,h1.axDisplay,0,'''Reflectance''',0,h.doflipud,h.dofliplr,h1.rect);
                else
                    [h.imagedata,bandAvail]=plotband(h1.FileName,h1.PathName,1,h1.axDisplay,0,'''Reflectance''',0,h.doflipud,h.dofliplr);
                end 
                h.imagedata.mimage=fliplr(flipud(h.imagedata.mimage));
                [x y]=size(h.imagedata.mimage);
                data.reflectance(i,:)=zeros(x*y,1)';
            end
        end
        refxy=[x,y];
        [varStr,formatStr]=buildTextOutputString(varStr,formatStr,'Reflectance',numBandsSelected);
       end
       if evalin('base','chkValues.noRef;')
           f=msgbox('Reflectance values not available for infrared bands');
           waitfor(f);
       end
       if evalin('base','chkValues.bt;')
         allBandsSelected=evalin('base','chkValues.bandSelected;');
         numBandsSelected=length(allBandsSelected);
         for i=1:numBandsSelected
            try
                % function kicks out if not an infrared band where bt available
                if evalin('base','chkValues.outputRegion==1') % selected region
                    [h.imagedata,bandAvail]=plotband(h1.FileName,h1.PathName,allBandsSelected(i),h1.axDisplay,0,'''Temperature''',0,h.doflipud,h.dofliplr,h1.rect);
                else  %entire granule
                    [h.imagedata,bandAvail]=plotband(h1.FileName,h1.PathName,allBandsSelected(i),h1.axDisplay,0,'''Temperature''',0,h.doflipud,h.dofliplr);
                end
                h.imagedata.mimage=fliplr(flipud(h.imagedata.mimage));
                [x y]=size(h.imagedata.mimage);
                data.bt(i,:)=reshape(h.imagedata.mimage,x*y,1)';
            catch
                %make sure to get same size x and y - use known bt band 20
                if evalin('base','chkValues.outputRegion==1') % selected region
                    [h.imagedata,bandAvail]=plotband(h1.FileName,h1.PathName,20,h1.axDisplay,0,'''Temperature''',0,h.doflipud,h.dofliplr,h1.rect);
                else % entire granule
                    [h.imagedata,bandAvail]=plotband(h1.FileName,h1.PathName,20,h1.axDisplay,0,'''Temperature''',0,h.doflipud,h.dofliplr);
                end
                h.imagedata.mimage=fliplr(flipud(h.imagedata.mimage));
                [x y]=size(h.imagedata.mimage);
                data.bt(i,:)=zeros(x*y,1)';
            end
         end
         btxy=[x,y];
         [varStr,formatStr]=buildTextOutputString(varStr,formatStr,'Brightness Temperature',numBandsSelected);
       end
       if evalin('base','chkValues.noBT;')
           f=msgbox('Brightness Temperatures not available for visible bands!');
           waitfor(f);
       end
       if evalin('base','chkValues.cloudMask;')
            if isunix
                 [CMFileName, CMPathName]=uigetfile('../Data/M*D35*.hdf','Cloud Mask File');
            else
                 [CMFileName, CMPathName]=uigetfile('..\Data\*','Cloud Mask File');
            end
			
         	%% READ IN CLOUD MASK, ONLY BYTE 1 
            if evalin('base','chkValues.outputRegion==1')
                cloudmask = readModisCloudMask([CMPathName CMFileName],1,h1.rect);
            else % read the entire granule
                cloudmask = readModisCloudMask([CMPathName CMFileName],1);
            end
            data.mask=cloudmask.byte1.mask';
            data.mask=fliplr(rot90(data.mask));
            [x y]=size(data.mask);
            data.mask=reshape(data.mask,x*y,1);
            maskxy=[x,y];
            [varStr,formatStr]=buildTextOutputString(varStr,formatStr,'Cloud Mask');
       end
       if evalin('base','chkValues.mod03')
           % output MOD03 variables lat/lon (full res), satellite height and zenith
           if isunix
                 [mod03FileName, mod03PathName]=uigetfile('../Data/M*D03*.hdf','MOD03 File');
           else
                 [mod03FileName, mod03PathName]=uigetfile('..\Data\*','MOD03 File');
           end
           data.mod03Data=readProductsFromMod03([mod03PathName mod03FileName],...
               {'scanStartTime','latitude','longitude','satHeight','scanAngle'});
       end
       if evalin('base','chkValues.cloudTopPressure;')
           [ctPressureData,mod06FileName]=mod06Reader('Cloud Top Pressure',[]);
		   if evalin('base','chkValues.expandTo1km;')
               	data.ctPressureData1km=expandTo1KmRes(ctPressureData,h1.rect);
		   else
			data.ctPressureData1km=ctPressureData;
		   end
           data.ctPressureData1km=fliplr(flipud(data.ctPressureData1km));
           [x y]=size(data.ctPressureData1km);
           data.ctPressureData1km=reshape(data.ctPressureData1km,x*y,1);
           ctpressxy=[x,y];
           [varStr,formatStr]=buildTextOutputString(varStr,formatStr,'Cloud Top Pressure');
       end
       if evalin('base','chkValues.cloudTopTemp;')
        if exist('mod06FileName')
            ctTempData=mod06Reader('Cloud Top Temperature',[],mod06FileName);
        else
            [ctTempData,mod06FileName]=mod06Reader('Cloud Top Temperature',[]);
        end
		if evalin('base','chkValues.expandTo1km;')
            	data.ctTempData1km=expandTo1KmRes(ctTempData,h1.rect);
		else
            	data.ctTempData1km=ctTempData;
		end
        data.ctTempData1km=fliplr(flipud(data.ctTempData1km));
        [x y]=size(data.ctTempData1km);
        data.ctTempData1km=reshape(data.ctTempData1km,x*y,1);
        cttempxy=[x,y];
        [varStr,formatStr]=buildTextOutputString(varStr,formatStr,'Cloud Top Temperature');
       end
       if evalin('base','chkValues.cloudPhase;')
        if exist('mod06FileName')
            phaseData=mod06Reader('Cloud Phase',[],mod06FileName);
        else
            [phaseData,mod06FileName]=mod06Reader('Cloud Phase',[]);
        end
        data.phaseData1km=expandTo1KmRes(phaseData,h1.rect);
        data.phaseData1km=fliplr(flipud(data.phaseData1km));
        [x y]=size(data.phaseData1km);
        data.phaseData1km=reshape(data.phaseData1km,x*y,1);
        phasexy=[x,y];
        [varStr,formatStr]=buildTextOutputString(varStr,formatStr,'Cloud Phase');
       end
       if evalin('base','chkValues.effCloudEmissivity;')
        if exist('mod06FileName')
            effEmissivity=mod06Reader('Effective Cloud Emissivity',[],mod06FileName);
        else
            [effEmissivity,mod06FileName]=mod06Reader('Effective Cloud Emissivity',[]);
        end
		if evalin('base','chkValues.expandTo1km;')
            	data.effEmissivity1km=expandTo1KmRes(effEmissivity,h1.rect);
		else
			data.effEmissivity1km=effEmissivity;
		end
        data.effEmissivity1km=fliplr(flipud(data.effEmissivity1km));
        [x y]=size(data.effEmissivity1km);
        data.effEmissivity1km=reshape(data.effEmissivity1km,x*y,1);
        emisxy=[x,y];
        [varStr,formatStr]=buildTextOutputString(varStr,formatStr,'Effective Cloud Emissivity');
       end
       if ~strcmp(varStr,'')
           %output the text file of results
           try
                % currently output of text or matlab only
                if evalin('base','chkValues.outputFormat==2;')
                    [fn,pn]=uiputfile(['*.txt'],'Save Text Output File');
                    fid=fopen([pn fn],'wt');
                else
                    [fn,pn]=uiputfile(['*.mat'],'Save Matlab Output File');
                end
           catch
                if evalin('base','chkValues.outputFormat==2')
                    fid=fopen('output.txt','wt');
                    disp('Saving output.txt by default...');
                else
                    matlabFileName='output.mat';
                    disp('Saving output.mat by default...');
                end
           end
           
           if evalin('base','chkValues.outputFormat==2') %text output
               if isfield(data,'bt')
                [x y]=size(data.bt);
               elseif isfield(data,'radiance')
                    [x y]=size(data.radiance);
               elseif isfield(data,'reflectance')
                    [x y]=size(data.reflectance);
               end
                endofline='\n';
				i=1:y';
				eval(sprintf('var=[%s];',varStr));
                var=reshape(var,length(i),length(var)/length(i));
                fprintf(fid,'%s\n',varStr);
                eval(sprintf('fprintf(fid,''%s%s'',var'');',formatStr,endofline));
               fclose(fid);
           else %matlab output
               if exist('latlonxy')
                   data.lat=reshape(data.lat,latlonxy(1),latlonxy(2));
                   data.lon=reshape(data.lon,latlonxy(1),latlonxy(2));
               end
               if exist('radxy')
                   [x,y]=size(data.radiance);
                   data.radiance=reshape(data.radiance,x,radxy(1),radxy(2));
               end
               if exist('refxy')
                   [x,y]=size(data.reflectance);
                   data.reflectance=reshape(data.reflectance,x,refxy(1),refxy(2));
		   [indx1,indx2,indx3]=intersect(evalin('base','chkValues.bandSelected;'),evalin('base','chkValues.visBandSelected;'));
                   data.reflectance=data.reflectance(indx2,:,:);
               end
               if exist('btxy')
                   [x,y]=size(data.bt);
                   data.bt=reshape(data.bt,x,btxy(1),btxy(2));
		   [indx1,indx2,indx3]=intersect(evalin('base','chkValues.bandSelected;'),evalin('base','chkValues.irBandSelected;'));
                   data.bt=data.bt(indx2,:,:);
               end
               if exist('maskxy')
                   data.mask=reshape(data.mask,maskxy(1),maskxy(2));
               end
               if exist('ctpressxy')
                   data.ctPressureData1km=reshape(data.ctPressureData1km,ctpressxy(1),ctpressxy(2));
               end
               if exist('cttempxy')
                   data.ctTempData1km=reshape(data.ctTempData1km,cttempxy(1),cttempxy(2));
               end    
               if exist('phasexy')
                   data.phaseData1km=reshape(data.phaseData1km,phasexy(1),phasexy(2));
               end
               if exist('emisxy')
                   data.effEmissivity1km=reshape(data.effEmissivity1km,emisxy(1),emisxy(2));
               end
               if isfield(data,'mod03Data')
                   data.Latitude=data.mod03Data.Latitude;
                   data.Longitude=data.mod03Data.Longitude;
                   data.satHeight=data.mod03Data.satHeight;
                   data.satZenith=data.mod03Data.satZenith;
                   data.Time=data.mod03Data.Time;
                   data=rmfield(data,'mod03Data');
                   % change output of bt to match collocation software
                   if isfield(data,'bt')
                       selBands=evalin('base','chkValues.irBandSelected;');
                       for i=1:length(selBands)
                           eval(sprintf('data.band%iBT=squeeze(data.bt(i,:,:));',selBands(i)));
                       end
                       data=rmfield(data,'bt');
                   end
               end
               keyboard
               eval(sprintf('save %s%s '' data ''' ',pn,fn));
           end
           msgbox([pn fn ' saved!']);
       else
           msgbox('No file saved');
       end
   case 'OutputOK' % OK button from the Data Output screen
       bandEntries=get(h.lstBands,'String');
       bandSelected=get(h.lstBands,'Value');
       txtBand=bandEntries(bandSelected,:);
       allBands=[1:36];
       visible=[1:19,26];
       infrared=[20:25,27:36];
       if ismember(bandSelected,1) % get all bands selected
            selBand=allBands;
       elseif ismember(bandSelected,2) % get visible only
            selBand=visible;
       elseif ismember(bandSelected,3) % get infrared only
            selBand=infrared;
       else
            for i=1:length(txtBand)
                selBand(i)=str2num(txtBand{i});
            end
       end
       chkValues.bandSelected=selBand;
       chkValues.cloudMask=get(h.chkCloudMask,'Value');
       chkValues.radiance=get(h.chkRadiance,'Value');
       % reflectance available for visible, brightness temp for infrared
       chkValues.reflectance=get(h.chkReflectance,'Value');
       chkValues.noRef=0;
       if chkValues.reflectance
           indx=find(ismember(selBand,infrared)==1);
           if length(indx)>0
               chkValues.noRef=1;
           end
           indx=find(ismember(selBand,visible)==1);
           if length(indx)==0
               chkValues.reflectance=0;
               indx=find(ismember(selBand,infrared)==1);
           end
           chkValues.visBandSelected=selBand(indx);
       end
       chkValues.bt=get(h.chkBT,'Value');
       chkValues.noBT=0;
       if chkValues.bt
           indx=find(ismember(selBand,visible)==1);
           if length(indx)>0
               chkValues.noBT=1;
           end
           indx=find(ismember(selBand,infrared)==1);
           if length(indx)==0
               chkValues.bt=0;
               indx=find(ismember(selBand,visible)==1);
           end
           chkValues.irBandSelected=selBand(indx);
       end
       chkValues.cloudPhase=get(h.chkCloudPhase,'Value');
       chkValues.cloudTopPressure=get(h.chkCloudTopPressure,'Value');
       chkValues.cloudTopTemp=get(h.chkCloudTopTemp,'Value');
       chkValues.effCloudEmissivity=get(h.chkEffEmissivity,'Value');
       chkValues.expandTo1km=get(h.chkExpandTo1km,'Value');
       chkValues.latlon=get(h.chkLatLon,'Value');
       chkValues.outputFormat=get(h.popOutputFormat,'Value');
       chkValues.outputRegion=get(h.popOutputRegion,'Value');
       chkValues.mod03=get(h.chkMOD03,'Value');
       assignin('caller','chkValues',chkValues);
       close(gcf);
   case 'SelectSub' %select subregion on the scatter plot
     h1=guidata(1);
     if subcount >= 1 & subcount < h1.plotStyleCount
        subcount=subcount+1;
        graphColor=h1.plotStyle(subcount,:);
        rectStruc=SelectRegion(h.axDisplay);
        h1=guidata(1);
        rectangle('Position',rectStruc.rect,'EdgeColor',strtok(graphColor,'.'));
        OrgRect=h1.rect;
        %flip rectStruc since original plot is on its side
        rectStruc.rect(1:2)=fliplr(rectStruc.rect(1:2))+OrgRect(1:2);
        h.subrect=rectStruc.rect;
        h.subdata=scatterplot(h.xch,h.ych,h.ops,h.subrect,h1.PathName,h1.FileName,h.axScatter,h.label,graphColor);
        guidata(gcf,h);
        mouseMove(4);
    else
        msgbox(sprintf('Only %i colors available! Refresh',h1.plotStyleCount-1));
    end
   case 'GetPoints' % go from scatter plot back to selected region
     h1=guidata(1);
     if scattercount==0
         %scale values between 0 and 1
         h.newimage=scaleimage(h.boxdata.mimage,h1.band);
     end
     if scattercount<h1.scatstylecount
     	scattercount=scattercount+1;
     	rectScat=SelectRegion(h.axScatter);
     	rectangle('Position',rectScat.rect,'EdgeColor',h1.scatterStyle(scattercount,:));
        h.newimage=mapback(h.newimage,h.data.x,h.data.y,rectScat.rect,h.axDisplay,h1.scatterStyle(scattercount,:));
     else
        %disable get points button 
	    text=sprintf('Unable to plot more than %i colors. Refresh.',h1.scatstylecount);
	    msgbox(text);
        set(h.mnuGetPoints,'Enable','off');
     end
     guidata(gcf,h);
   case 'Pseudochannel'
     selChannel=get(gcbo,'Label');
     f=openfig('pseudo');
     hps=guihandles(f);
     axes(hps.axDisplay);
     cla;
     if strcmp(selChannel,'Plot X Channel')
         imagesc(h.data.x);
         title(h.label{1});
         c=colorbar;
	 set(c,'Units','Pixels');
         hps.pseudodata=h.data.x;
     else
         imagesc(h.data.y);
         title(h.label{2});
         c=colorbar;
	 set(c,'Units','Pixels');
         hps.pseudodata=h.data.y;
     end
     set(gca,'XTick',[],'YTick',[]);
     %attach data to figure for mousemove
     hps.latitude=h.boxdata.latitude;
     hps.longitude=h.boxdata.longitude;
     guidata(gcf,hps);

   case 'RGB'
     f=openfig('rgb','reuse');
     hrgb=guihandles(f);
     %get variable popup current value
     hrgb.var=['''' getCheckedItem(h.mnuVariables) ''''];
     %plot imagedata for the particular band and selected region (optional 10th argument)
     boxdata=plotband(h.FileName,h.PathName,h.band,hrgb.axDisplay,1,hrgb.var,0,h.doflipud,h.dofliplr,h.rect);
     % get lat and lon data
%      hrgb.latitude=h.latitude(floor(h.rect(1))+1:floor(h.rect(1))+floor(h.rect(3)),...
%                 floor(h.rect(2))+1:floor(h.rect(2))+floor(h.rect(4)));
%      hrgb.longitude=h.longitude(floor(h.rect(1))+1:floor(h.rect(1))+floor(h.rect(3)),...
%                 floor(h.rect(2))+1:floor(h.rect(2))+floor(h.rect(4)));
    hrgb.latitude=h.latitude;
    hrgb.longitude=h.longitude;
     guidata(f,hrgb);
     set(hrgb.mnuContrastRGB,'Enable','Off');
     guidata(1,h);
     %reset pos variable in mouseMove
     mouseMove(2);
   case 'RGBPlot'
     h1=guidata(1); 
     redband=get_selected_entries(h.lstRed);
     greenband=get_selected_entries(h.lstGreen);
     blueband=get_selected_entries(h.lstBlue);
     h.rgbdata=rgbPlot(h1.FileName,h1.PathName,redband,greenband,blueband,h.axDisplay,h1.doflipud,h1.dofliplr,h1.rect);
     set(h.mnuContrastRGB,'Enable','on');
     guidata(gcf,h);
   case 'contrastRGB'
     f=openfig('contrastRGB','reuse');
     hRGB=guihandles(f);
     guidata(f,hRGB);
     redColorData=h.rgbdata.redimagedata.mimage;
     set(hRGB.edRedMin,'String',num2str(min(min(redColorData))));
     set(hRGB.edRedMax,'String',num2str(max(max(redColorData))));
     greenColorData=h.rgbdata.greenimagedata.mimage;
     set(hRGB.edGreenMin,'String',num2str(min(min(greenColorData))));
     set(hRGB.edGreenMax,'String',num2str(max(max(greenColorData))));
     blueColorData=h.rgbdata.blueimagedata.mimage;
     set(hRGB.edBlueMin,'String',num2str(min(min(blueColorData))));
     set(hRGB.edBlueMax,'String',num2str(max(max(blueColorData))));
     waitfor(f); % rgbVals set here
     rgbVals=evalin('base','rgbVals');
     % scale image by new min and max values
     rgbImage(:,:,1)=(redColorData-rgbVals.redMin)/(rgbVals.redMax-rgbVals.redMin);
     rgbImage(:,:,2)=(greenColorData-rgbVals.greenMin)/(rgbVals.greenMax-rgbVals.greenMin);
     rgbImage(:,:,3)=(blueColorData-rgbVals.blueMin)/(rgbVals.blueMax-rgbVals.blueMin);
     indxLTZero=find(rgbImage<0);
     if ~isempty(indxLTZero)
        rgbImage(indxLTZero)=0;
     end
     indxGTOne=find(rgbImage>1);
     if ~isempty(indxGTOne)
        rgbImage(indxGTOne)=1;
     end
     axes(h.axDisplay);
     cla;
     imagesc(rgbImage);
   case 'getMainMotion'
     if isfield(h,'imagedata') 
         mouseMove(1,h.axDisplay,h.txtXCoord,h.txtYCoord,h.txtValue,h.imagedata.mimage');
     end
   case 'getLineMotion'
     if isfield(h,'linedata')
         mouseMove(5,h.axDisplay,h.txtXCoord,h.txtYCoord,h.linedata.latitude,...
             h.linedata.longitude,h.txtValue,h.linedata.mimage);  
     end
   case 'getRegionMotion'
     if isfield(h,'boxdata')  
         mouseMove(3,h.axDisplay,h.txtXCoord,h.txtYCoord,h.boxdata.latitude,...
             h.boxdata.longitude,h.txtValue,h.boxdata.mimage);
     end
   case 'getScatterMotion'
     if isfield(h,'data')
         mouseMove(4,h.axDisplay,h.txtXCoord,h.txtYCoord,h.boxdata.latitude,...
             h.boxdata.longitude,h.txtXAxisVal,h.data.x);
         mouseMove(4,h.axDisplay,h.txtXCoord,h.txtYCoord,h.boxdata.latitude,...
             h.boxdata.longitude,h.txtYAxisVal,h.data.y);
     end
   case 'getRGBMotion'
     if isfield(h,'rgbdata')
         set(h.txtRLabel,'String',h.rgbdata.redvar(2:length(h.rgbdata.redvar)-1));
          mouseMove(2,h.axDisplay,h.txtXCoord,h.txtYCoord,h.latitude,...
              h.longitude,h.txtRedVal,h.rgbdata.redimagedata.mimage);   
         set(h.txtBLabel,'String',h.rgbdata.bluevar(2:length(h.rgbdata.bluevar)-1));
          mouseMove(2,h.axDisplay,h.txtXCoord,h.txtYCoord,h.latitude,...
              h.longitude,h.txtBlueVal,h.rgbdata.blueimagedata.mimage);
         set(h.txtGLabel,'String',h.rgbdata.greenvar(2:length(h.rgbdata.greenvar)-1));
          mouseMove(2,h.axDisplay,h.txtXCoord,h.txtYCoord,h.latitude,...
              h.longitude,h.txtGreenVal,h.rgbdata.greenimagedata.mimage);
     end
   case 'getPseudoMotion'
       if isfield(h,'pseudodata')
          mouseMove(6,h.axDisplay,h.txtLatVal,h.txtLonVal,h.latitude,...
              h.longitude,h.txtValue,h.pseudodata);   
       end
   case 'SetContrast'
       [cmin,cmax]=caxis;
       f=openfig('settings');
       hset=guihandles(f);
       guidata(f,hset);
       set(hset.edCMin,'String',num2str(cmin));
       set(hset.edCMax,'String',num2str(cmax));
       waitfor(f);
       axes(h.axDisplay);
       set(gca,'CLim',[cmin cmax]);
       c=colorbar;
       set(c,'Units','pixels');
   case 'CloudMask'
     f=openfig('cloudMask','reuse');
     hcm=guihandles(f);
     try
        if isunix
             [hcm.CMFileName, hcm.CMPathName]=uigetfile('../Data/*35*.hdf','Cloud Mask File');
        else
             [hcm.CMFileName, hcm.CMPathName]=uigetfile('..\Data\*','Cloud Mask File');
        end
        guidata(gcf,hcm);
        [temp,rem]=strtok(hcm.CMFileName,'.');
        [yearday,rem]=strtok(rem,'.');
        yr=yearday(length(yearday)-6:length(yearday)-3);
        dy=yearday(length(yearday)-2:length(yearday));
        hr=strtok(rem,'.');
		plotString = sprintf('MODIS %s %s %s UTC',yr,dy,hr);
		
     	%% READ IN CLOUD MASK, ONLY BYTE 1 
		%disp('Reading in byte 1 of the cloud mask data...');
		cloudmask = readModisCloudMask([hcm.CMPathName hcm.CMFileName],1,h.rect);
		%% DISPLAY CLOUD MASK (BYTE 1, BITS 1 & 2) AS X,Y IMAGE 
		plotCloudMaskSingleBit(cloudmask, [1 1], plotString, f)

		%% DISPLAY CLOUD MASK (BYTE 1, BIT2 1 & 2) ON MAP
%         latlon.latitude=h.latitude;
%         latlon.longitude=h.longitude;
%         displayLatLon=[min(min(h.latitude)) max(max(h.latitude)) min(min(h.longitude)) max(max(h.longitude))];
%         fmap=openfig('project');
%  		displayCloudMaskOnMap2(cloudmask,latlon,plotString,fmap,displayLatLon);

      catch
          msgbox('Cloud Mask File not loaded!');
      end
   case 'RemoveClear' %remove clear sky from scatter plot according to cloud mask 
     f=openfig('removeClear','reuse');
     hrc=guihandles(f);
     h1=guidata(1);
     try
        if isunix
             [hrc.CMFileName, hrc.CMPathName]=uigetfile('../Data/*35*.hdf','Cloud Mask File');
        else
             [hrc.CMFileName, hrc.CMPathName]=uigetfile('..\Data\*','Cloud Mask File');
        end
        guidata(gcf,hrc);
		
     	%% READ IN CLOUD MASK, ONLY BYTE 1 
		%disp('Reading in byte 1 of the cloud mask data...');
		cloudmask = readModisCloudMask([hrc.CMPathName hrc.CMFileName],1,h.rect);
        mask=cloudmask.byte1.mask';
        indxToRemove=find(mask==2|mask==3);
        graphColor='r.';
        h.data=scatterplot(h.xch,h.ych,h.ops,h1.rect,h1.PathName,h1.FileName,hrc.axDisplay,h.label,graphColor,indxToRemove);
    catch
        msgbox('Cloud Mask Information not loaded!')
    end
   case 'PrecWater'
     f=openfig('precWater','reuse');
     hpw=guihandles(f);
     %try
        if isunix
             [hpw.PWFileName, hpw.PWPathName]=uigetfile('../Data/*07*.hdf','Precipitable Water File');
        else
             [hpw.PWFileName, hpw.PWPathName]=uigetfile('..\Data\*','Precipitable Water File');
        end
        guidata(gcf,hpw);
        [temp,rem]=strtok(hpw.PWFileName,'.');
        [yearday,rem]=strtok(rem,'.');
        yr=yearday(length(yearday)-6:length(yearday)-3);
        dy=yearday(length(yearday)-2:length(yearday));
        hr=strtok(rem,'.');
		plotString = sprintf('MODIS %s %s %s UTC',yr,dy,hr);
		
        axes(hpw.axDisplay);
        cla;
		precWater = readProductsFromMod07([hpw.PWPathName hpw.PWFileName],'Water_Vapor');
        imagesc(precWater.Water_Vapor);
        title(plotString);
        set(gca,'XTick',[],'YTick',[]);
        c=colorbar;
        label=get(c,'XLabel');
        set(label,'String','Precipitable Water (mm)');
	set(c,'Units','Pixels');
%       catch
%           msgbox('File not loaded!');
%       end
   case 'Cloud Phase'
       mod06Reader(action,h.rect);
   case 'Cloud Top Pressure'
       mod06Reader(action,h.rect);
   case 'Cloud Top Temperature'
       mod06Reader(action,h.rect);
   case 'Effective Cloud Emissivity'
       mod06Reader(action,h.rect);
   case 'MainRefresh'
     %reload current image
     %get imagedata for that particular band
     h.imagedata=plotband(h.FileName,h.PathName,h.band,h.axDisplay,1,h.vartoplot,0,h.doflipud,h.dofliplr);
     set(h.mnuPlot,'Enable','off');
     set(h.mnuLevel2,'Enable','off');
     set(h.mnuDataOutput,'Enable','off');
     guidata(gcf,h);
     %close all scatter fig plots and start over
     %if figs already closed, reset the regionfigcount
     try
         for i=1:regionfigcount
      	    figure(h.regionfig(i));
       	    close(gcf);
         end
         regionfigcount=0;
     catch
         regionfigcount=0;
     end
     
     %close all line fig plots and reset linefigcount
     try
         for i=1:linefigcount
             figure(h.linefig(i));
             close(gcf);
         end
         linefigcount=0;
     catch
         linefigcount=0;
     end
     figure(1);
    case 'ScatterRefresh'
     scattercount=0;
     subcount=1;
     h1=guidata(1);
     graphColor=h1.plotStyle(subcount,:);
     rescatter(h.data,h.axScatter,h.label,graphColor,1);
     set(h.mnuGetPoints,'Enable','on');
     %also refresh plotted image
     %replot imagedata for that particular band
     h.boxdata=plotband(h1.FileName,h1.PathName,h1.band,h.axDisplay,1,h.var,0,h1.doflipud,h1.dofliplr,h1.rect);
     h.boxdata.latitude=h1.latitude;
     h.boxdata.longitude=h1.longitude;
     guidata(gcf,h);
    case 'LineRefresh'
     %only need to refresh cross-section axes
     axes(h.axCrossSection);
     cla;
    case 'RGBRefresh'
     axes(h.axDisplay);
     cla;
 end
