function menu_callbacks_airs(action)
%
% NAME: menu_callbacks_airs.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: 
%  AIRS Analyzer Toolkit (AIRatee)
%       
% CALLING SEQUENCE: 
%    menu_callbacks_airs(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_airs('loadChannelProperties')
%
% MODIFICATION HISTORY: 
%	  Written by:	 Kevin Baggett  15-Jul-2002 (UW-SSEC)
%     Coordinator:   Paolo Antonelli
%
% REVISION INFORMATION (RCS Keyword):
%   $Id: menu_callbacks_airs.m,v 1.5 2003/04/18 16:09:51 kevinb Exp $
%
%------------------------------------------------------------------------------

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

rcs_id =  '$Id: menu_callbacks_airs.m,v 1.5 2003/04/18 16:09:51 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 'loadChannelProperties'
     try
         if isunix
             [h.FileName, h.PathName]=uigetfile('channelProps*.m','AIRS Channel Properties File');
         else
             [h.FileName, h.PathName]=uigetfile('channelProps*.m','AIRS Channel Properties File');
         end
         addpath(h.PathName);
         functionName=strtok(h.FileName,'*.m');
         eval(functionName); %returns structure noise
         h.goodChannelIndex=find(noise.badFlag==0);
         guidata(gcf,h);
         msgbox(sprintf('Channel properties file %s loaded!',h.FileName)); 
      catch
          msgbox('File not loaded!');
      end
     guidata(gcf,h);
   case 'loadAIRSData'
     %try
         if isunix
             [h.FileName, h.PathName]=uigetfile('../Data/*','AIRS Input File');
         else
             [h.FileName, h.PathName]=uigetfile('..\Data\*','AIRS Input File');
         end
         % add file path to guidata before calling changeChannel
         h.doflipud=0;
         h.dofliplr=0;
	 if isfield(h,'radiances')
		h=rmfield(h,'radiances');
	 end
         guidata(gcf,h);
         changeChannel;
        
	 h=guidata(gcf); 
         set(h.mnuChangeChannel,'Enable','on');
         set(h.mnuSelect,'Enable','on');
         set(h.mnuPlot,'Enable','on');
         set(h.mnuMainRefresh,'Enable','on');
         set(h.mnuVariables,'Enable','on');
         set(h.mnuSettings,'Enable','on');
         set(h.mnuVariable1,'Checked','on');
         guidata(gcf,h);
 
%      catch
%          msgbox('File not loaded!');
%      end
   case 'changeChannel'
       changeChannel;
       % Radiance always loaded first after changing the channel
       h=guidata(gcf);
       set(h.mnuVariable1,'Checked','on');
       set(h.mnuVariable2,'Checked','off');
       guidata(gcf,h);
   case 'channelPlot'
     %uncheck current item before checking a new one
     children=get(h.mnuVariables,'Children');
     for i=1:length(children)
         set(children(i),'Checked','off');
     end
     set(gcbo,'Checked','On');
     
     h.currentVar=get(gcbo,'Label');
     switch h.currentVar
     case 'Radiance'
        plotband(h.currentWavenumber,h.selectedBand,h.time,h.currentVar,h.plotRadiances,h.axDisplay,h.doflipud,h.dofliplr,h.curColormap);
     case 'Brightness Temperature' 
        plotband(h.currentWavenumber,h.selectedBand,h.time,h.currentVar,h.temperature,h.axDisplay,h.doflipud,h.dofliplr,h.curColormap);
     end
     
     guidata(gcf,h);
   case 'Animate'
     f=openfig('animate','reuse');
     hanim=guihandles(f);
     h1=guidata(1);
     set(hanim.edStartWavenumber,'String',num2str(h1.wavenumbers(1)));
     set(hanim.edEndWavenumber,'String',num2str(h1.wavenumbers(end)));
     hanim.figNum=f;
     guidata(f,hanim);
   case 'Play'
     h1=guidata(1);
     playDirection=get(gcbo,'Label');
     startIndx=find_indx(h1.wavenumbers,str2num(get(h.edStartWavenumber,'String')));
     endIndx=find_indx(h1.wavenumbers,str2num(get(h.edEndWavenumber,'String')));
     increment=str2num(get(h.edIncrement,'String'));
     if ~isfield(h1,'curProjection')
         h1.curProjection='mercator';
     end
     animate(startIndx,endIndx,increment,h1.curColormap,h.axAnimate,str2num(get(h.edPlay,'String')),playDirection,h1.curProjection,h.figNum,h.txtMessage);
   case 'projection'
     projection=get(gcbo,'Label');
     figNum=openfig('project','reuse');
     h.curProjection=projection;
     cla;
     switch h.currentVar
     case 'Radiance'
	    units='Radiance (mW/m^2/ster/cm^{-1})';
        project(h.plotRadiances,h.latitude,h.longitude,projection,figNum,units);
     case 'Brightness Temperature'
	    units='Brightness Temperature (K)';
        project(h.temperature,h.latitude,h.longitude,projection,figNum,units);
     end
     guidata(1,h);
     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
       plotband(h.currentWavenumber,h.selectedBand,h.time,h.currentVar,h.plotRadiances,h.axDisplay,h.doflipud,h.dofliplr,h.curColormap);
       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
       plotband(h.currentWavenumber,h.selectedBand,h.time,h.currentVar,h.plotRadiances,h.axDisplay,h.doflipud,h.dofliplr,h.curColormap);
       guidata(gcf,h);
   case 'SelectRegion'
     rectStruc=SelectRegion(h.axDisplay);
     rectangle('Position',rectStruc.rect,'EdgeColor','m','LineWidth',2);
     h.origrect=rectStruc.rect;
     [imagex,imagey]=size(h.plotRadiances);
     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
     %attach rectangle attributes to the main figure for later use
     %AIRS data to read is flipped on its side in this case - so exchange x,y values
     %h.rect=fliprect(rectStruc.rect);
     h.rect=rectStruc.rect;
     set(h.mnuLevel2,'Enable','on');
     set(h.mnuPlot,'Enable','on');
     set(h.mnuDataOutput,'Enable','on');
     guidata(gcf,h);
   case 'SelectRadiance'
       % get 1 point from user input
       [x,y]=ginput(1);
       f=openfig('spectra','reuse');
       [dim1,dim2,dim3]=size(h.radiances);
       if h.doflipud
	    y=dim2-y;
       end
       if h.dofliplr
	    x=dim3-x;
       end
       data.wavenumbers=h.wavenumbers;
       data.spectraRad=squeeze(h.radiances(:,floor(y),floor(x)));
       data.latitude=h.latitude(floor(y),floor(x));
       data.longitude=h.longitude(floor(y),floor(x));
       plot(data.wavenumbers,data.spectraRad);
       ylabel('Radiance (W/m^2/ster/cm^{-1})');
       xlabel('Wavenumber (cm^{-1})');
       title(sprintf('Radiance Spectra at Latitude %7.3f, Longitude %7.3f',data.latitude,data.longitude));
       set(gca,'YLim',[0 200]);
       guidata(f,data);
   case 'SelectBT'
       % get 1 point from user input
       [x,y]=ginput(1);
       f=openfig('spectra','reuse');
       [dim1,dim2,dim3]=size(h.radiances);
       if h.doflipud
	    y=dim2-y;
       end
       if h.dofliplr
	    x=dim3-x;
       end
       % get only radiance for that point and convert to BT
       radToConvert=h.radiances(:,floor(y),floor(x));
       data.bt=rad2bt(h.wavenumbers,radToConvert);
       data.wavenumbers=h.wavenumbers;
       data.latitude=h.latitude(floor(y),floor(x));
       data.longitude=h.longitude(floor(y),floor(x));
       plot(data.wavenumbers,data.bt);
       ylabel('Brightness Temperature (K)');
       xlabel('Wavenumber (cm^{-1})');
       title(sprintf('Brightness Temperature Spectra at Latitude %7.3f, Longitude %7.3f',data.latitude,data.longitude));
       guidata(f,data);
   case 'SaveSpectra' %save spectra to a Matlab file
       data=guidata(gcf);
       [fn,pn]=uiputfile(['*.mat'],'Save Matlab Output File');
       eval(sprintf('save %s%s data;',pn,fn));
   case 'Colormap' % setting of the colormap
       %uncheck current item before checking a new one
       children=get(h.mnuColormap,'Children');
       for i=1:length(children)
          set(children(i),'Checked','off');
       end
       set(gcbo,'Checked','On');
       curColormap=get(gcbo,'Label');
       switch curColormap
       case 'Default (Gray Scale Inverted)'
           cc=colormap(gray(264));
           h.curColormap=colormap(flipud(cc));
       case 'Jet'
           h.curColormap=colormap(jet(264));
       case 'Winter'
           h.curColormap=colormap(winter(264));
       case 'Bone'
           h.curColormap=colormap(bone(264));
       end
       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);
     linerect=getLineRegion(x,y,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,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,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);
     switch hreg.var
     case 'Radiance'
         plotValues=h.plotRadiances;
     case 'Brightness Temperature'
         plotValues=h.temperature;
     end
     %plot imagedata for the particular band and selected region (optional 7th argument)
%     hreg.boxdata=plotband(h.currentWavenumber,h.selectedBand,h.time,hreg.var,h.plotRadiances,hreg.axDisplay,h.doflipud,h.dofliplr,h.rect);
     hreg.curImage=plotband(h.currentWavenumber,h.selectedBand,h.time,hreg.var,plotValues,hreg.axDisplay,h.doflipud,h.dofliplr,h.curColormap,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.radiances,h1.wavenumbers,h.axScatter,h.label,graphColor,h1.doflipud,h1.dofliplr);
         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'
       f=openfig('txtOutput','reuse');
       htxt=guihandles(f);
       guidata(gcf,htxt);
       %chkValues set from txtOutput.fig callback and saved (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
          [h.imagedata,bandAvail,data.lat,data.lon]=plotband(h1.FileName,h1.PathName,h1.band,h1.axDisplay,0,'',1,h1.rect);
          [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
            [h.imagedata,bandAvail]=plotband(h1.FileName,h1.PathName,evalin('base',sprintf('chkValues.bandSelected(%i);',i)),h1.axDisplay,0,'''Radiance''',0,h1.rect);
            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
                [h.imagedata,bandAvail]=plotband(h1.FileName,h1.PathName,allBandsSelected(i),h1.axDisplay,0,'''Reflectance''',0,h1.rect);
                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
                [h.imagedata,bandAvail]=plotband(h1.FileName,h1.PathName,1,h1.axDisplay,0,'''Reflectance''',0,h1.rect);
                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
                [h.imagedata,bandAvail]=plotband(h1.FileName,h1.PathName,allBandsSelected(i),h1.axDisplay,0,'''Temperature''',0,h1.rect);
                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
                [h.imagedata,bandAvail]=plotband(h1.FileName,h1.PathName,20,h1.axDisplay,0,'''Temperature''',0,h1.rect);
                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/MOD35*.hdf','Cloud Mask File');
            else
                 [CMFileName, CMPathName]=uigetfile('..\Data\*','Cloud Mask File');
            end
			
         	%% READ IN CLOUD MASK, ONLY BYTE 1 
            cloudmask = readModisCloudMask([CMPathName CMFileName],1,h1.rect);
            data.mask=cloudmask.byte1.mask';
            data.mask=fliplr(rot90(mask));
            [x y]=size(data.mask);
            data.mask=reshape(mask,x*y,1);
            maskxy=[x,y];
            [varStr,formatStr]=buildTextOutputString(varStr,formatStr,'Cloud Mask');
       end
       if evalin('base','chkValues.cloudTopPressure;')
           [ctPressureData,mod06FileName]=mod06Reader('Cloud Top Pressure',[]);
           data.ctPressureData1km=expandTo1KmRes(ctPressureData,h1.rect);
           data.ctPressureData1km=fliplr(flipud(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
        data.ctTempData1km=expandTo1KmRes(ctTempData,h1.rect);
        data.ctTempData1km=fliplr(flipud(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
        data.effEmissivity1km=expandTo1KmRes(effEmissivity,h1.rect);
        data.effEmissivity1km=fliplr(flipud(data.effEmissivity1km));
        [x y]=size(data.effEmissivity1km);
        data.effEmissivity1km=reshape(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');
                else
                    matlabFileName='output.mat';
                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));
                   keyboard
		   [indx1,indx2,indx3]=intersect(evalin('base','chkValues.bandSelected;'),evalin('base','chkValues.irBandSelected;'));
                   data.bt=data.bt(indx2,:,:);
               end
               if exist('maskxy')
                   [x,y]=size(data.mask);
                   data.mask=reshape(data.mask,x,maskxy(1),maskxy(2));
               end
               if exist('ctpressxy')
                   [x,y]=size(data.ctPressureData1km);
                   data.ctPressureData1km=reshape(data.ctPressureData1km,x,ctpressxy(1),ctpressxy(2));
               end
               if exist('cttempxy')
                   [x,y]=size(data.ctTempData1km);
                   data.ctTempData1km=reshape(data.ctTempData1km,x,cttempxy(1),cttempxy(2));
               end    
               if exist('phasexy')
                   [x,y]=size(data.phaseData1km);
                   data.phaseData1km=reshape(data.phaseData1km,x,phasexy(1),phasexy(2));
               end
               if exist('emisxy')
                   [x,y]=size(data.effEmissivity1km);
                   data.effEmissivity1km=reshape(data.effEmissivity1km,x,emisxy(1),emisxy(2));
               end
               eval(sprintf('save %s%s data',pn,fn));
           end
           msgbox([pn fn ' saved!']);
       else
           msgbox('No file saved');
       end
   case 'OutputOK'
       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.latlon=get(h.chkLatLon,'Value');
       chkValues.outputFormat=get(h.popOutputFormat,'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);
        keyboard
        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.radiances,h1.wavenumbers,h.axScatter,h.label,graphColor,h1.doflipud,h1.dofliplr);
        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.curImage);
     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);
     hrgb.curRGBUnits='Microns';
     switch hrgb.var
     case 'Radiance'
         plotValues=h.plotRadiances;
     case 'Brightness Temperature'
         plotValues=h.temperature;
     end

     %plot imagedata for the particular band and selected region (optional 9th argument)
     %boxdata=(h.FileName,h.PathName,h.band,hrgb.axDisplay,1,hrgb.var,0,h.rect);
     plotband(h.currentWavenumber,h.selectedBand,h.time,hrgb.var,plotValues,hrgb.axDisplay,h.doflipud,h.dofliplr,h.curColormap,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); 
     hcur=guidata(gcf);
     redband=str2num(get(hcur.edRedValue,'String'));
     greenband=str2num(get(hcur.edGreenValue,'String'));
     blueband=str2num(get(hcur.edBlueValue,'String'));
     % convert microns to wavenumbers
     if strcmp(hcur.curRGBUnits,'Microns');
         redband=1e+4/redband;
         greenband=1e+4/greenband;
         blueband=1e+4/blueband;
     end
     % find nearest indices to rgb
     redIndx=find_indx(h1.wavenumbers,redband);
     greenIndx=find_indx(h1.wavenumbers,greenband);
     blueIndx=find_indx(h1.wavenumbers,blueband);
     h.rgbdata=rgbPlot(h1.FileName,h1.PathName,redband,greenband,blueband,h.axDisplay,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);
       if ~isempty(h)
        axes(h.axDisplay);
       end
       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,h1.doflipud,h1.dofliplr,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
     switch h.currentVar
     case 'Radiance'
        plotband(h.currentWavenumber,h.selectedBand,h.time,h.currentVar,h.plotRadiances,h.axDisplay,h.doflipud,h.dofliplr,h.curColormap);
     case 'Brightness Temperature' 
        plotband(h.currentWavenumber,h.selectedBand,h.time,h.currentVar,h.temperature,h.axDisplay,h.doflipud,h.dofliplr,h.curColormap);
     end

     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.rect);
     axes(h.axDisplay);
     cla;
     imagesc(h.curImage);
     set(gca,'XTick',[],'YTick',[]);
     title(sprintf('Channel %10.4f, %s %s Data',h1.currentWavenumber,h1.selectedBand,h1.currentVar));
     c=colorbar;
     set(c,'Units','Pixels');
     label=get(c,'XLabel');
     switch h1.currentVar
     case 'Radiance'
        set(label,'String','Radiance (W/m^2/ster/cm^{-1})');
     case 'Brightness Temperature'
        set(label,'String','Brightness Temperature (K)');
     end

     %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
