function varargout = airsDisplay(varargin)
% AIRSDISPLAY M-file for airsDisplay.fig
%      AIRSDISPLAY, by itself, creates a new AIRSDISPLAY or raises the existing
%      singleton*.
%
%      H = AIRSDISPLAY returns the handle to a new AIRSDISPLAY or the handle to
%      the existing singleton*.
%
%      AIRSDISPLAY('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in AIRSDISPLAY.M with the given input arguments.
%
%      AIRSDISPLAY('Property','Value',...) creates a new AIRSDISPLAY or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before airsDisplay_OpeningFunction gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to airsDisplay_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help airsDisplay

% Last Modified by GUIDE v2.5 19-Sep-2005 19:42:57

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @airsDisplay_OpeningFcn, ...
                   'gui_OutputFcn',  @airsDisplay_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin & isstr(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before airsDisplay is made visible.
function airsDisplay_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to airsDisplay (see VARARGIN)

% Get image data from collocation.fig
if(nargin > 3)
    for index = 1:2:(nargin-3),
        if nargin-3==index break, end
        switch lower(varargin{index})
         case 'airs'
           airs = varargin{index+1};
           handles.airs.filename = airs.filename;
           handles.airs.index = airs.oval_index;
           clear airs;
         case 'modis'
           modis = varargin{index+1};
           handles.modis.filename = modis.filename;
           clear modis; 
         case 'colloc'
           handles.colloc = varargin{index+1};
        end
    end
end

% Read AIRS data and lat/lon
disp('  Load AIRS ...')
data = read_eos_fields_airs(handles.airs.filename.level1b);
data.spectral_freq(1262) = NaN;
data.spectral_freq(1865) = NaN;
[nchannel, pixels_across, scanlines] = size(data.radiances);

% Find selected AIRS element index in 2D matrix
[row, col] = ind2sub([pixels_across, scanlines], handles.airs.index);
handles.airs.lat = data.Latitude(row, col);
handles.airs.lon = data.Longitude(row, col);
handles.airs.time = data.Time(1,1);

% Get selected AIRS Brightness temperature
tmp = zeros(nchannel, 1);
for n = 1:nchannel
  tmp(n, 1) = real(rad2bt(data.spectral_freq(n), ...
                            squeeze(data.radiances(n, row, col))));
end

% Get good quality channels only
handles = load_airs_flag(handles);
ind = find(handles.airs.flag == 0);
num = length(ind);
wavenumber = zeros(num, 1);
wavenumber(:) = data.spectral_freq(ind);
handles.airs.wavenumber = wavenumber;

clear data; clear wavenumber;

data = zeros(num, 1);
data(:) = tmp(ind);
handles.airs.data = data;
clear tmp; clear data;


% Plot selected MODIS data on GUI figure
plot_airs_bt(handles);

% Get selected MODIS domain
handles.machineFormat = 'ieee-be';
handles.modis.cmap = [0,0,0;0,0,1;...
                      0.5,0.5,0.5;1,0,1;...
                      0,1,0;0,1,1;...
                      0.5,0.5,1;1,1,0;1,0,0];
handles.modis.num_color = length(handles.modis.cmap);

% Read MODIS Level03 geographical data
handles = load_modis03(handles);

% Get selected MODIS domain
handles = select_modis_domain(handles);
handles.modis.lat = [];
handles.modis.lon = [];

% Saperate MODIS element according their classification mask
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%Changed from Classification to Band 31 as not to require use
%%%%of jliclass9_new.dat classification mask
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%handles.modis.select_name = 'Classification Mask';
%handles = load_data(handles);
handles.modis.select_name = 'MODIS Level1b';
handles.modis.band = 31;
handles = load_modis1b(handles);

% Plot selected classification mask
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%Actually plotting MODIS 31 BT instead of cmask since 
%%%%not wanting to require use of jliclass9_new.dat
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
handles = select_modis(handles);
handles = plot_cmask(handles);
handles.modis.sub_data = [];
handles.modis.sub_lat = [];
handles.modis.sub_lon = [];

% Get and plot MODIS data 
handles.modis.cluster_index = cluster_modis_elements(handles.modis.data, ...
                              handles.modis.index, handles.modis.num_color);
handles.modis.data = [];

% Read MODIS level1b data
handles.modis.x_band = 31;
handles.modis.axis_variable = 'x';
handles.modis.x_label = ['Band ' num2str(handles.modis.x_band) ' (K)'];
handles.modis.x_data = read_mod1b(handles.modis.filename.level1b, handles.modis.x_band);
handles.modis.y_band = 2;
handles.modis.axis_variable = 'y';
handles.modis.y_label = ['Band ' num2str(handles.modis.y_band) ' (%)'];
handles.modis.y_data = read_mod1b(handles.modis.filename.level1b, handles.modis.y_band);

handles = get_modis_scatter(handles);
scatter_plot(handles)

set(handles.image_save_menu, 'Checked', 'on');
set(handles.data_save_menu, 'Checked', 'off');

% Choose default command line output for airsDisplay
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes airsDisplay wait for user response (see UIRESUME)
% uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = airsDisplay_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;


% --------------------------------------------------------------------
function save_menu_Callback(hObject, eventdata, handles)
% hObject    handle to save_menu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function image_save_menu_Callback(hObject, eventdata, handles)
% hObject    handle to image_save_menu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

set(handles.image_save_menu, 'Checked', 'on');
set(handles.data_save_menu, 'Checked', 'off');

save_image(handles.airs_figure);

% Update handles structure
guidata(hObject, handles);


% --------------------------------------------------------------------
function data_save_menu_Callback(hObject, eventdata, handles)
% hObject    handle to data_save_menu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

set(handles.image_save_menu, 'Checked', 'off');
set(handles.data_save_menu, 'Checked', 'on');

save_modis_index(handles);

% Update handles structure
guidata(hObject, handles);


% --------------------------------------------------------------------
function var_menu_Callback(hObject, eventdata, handles)
% hObject    handle to var_menu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function x_var_menu_Callback(hObject, eventdata, handles)
% hObject    handle to x_var_menu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

handles.modis.axis_variable = 'x';

% Update handles structure
guidata(hObject, handles);


% --------------------------------------------------------------------
function y_var_menu_Callback(hObject, eventdata, handles)
% hObject    handle to y_var_menu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

handles.modis.axis_variable = 'y';

% Update handles structure
guidata(hObject, handles);


% --------------------------------------------------------------------
function diff_y_var_menu_Callback(hObject, eventdata, handles)
% hObject    handle to diff_y_var_menu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function modis1b_x_var_menu_Callback(hObject, eventdata, handles)
% hObject    handle to modis1b_x_var_menu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function modis1b_y_var_menu_Callback(hObject, eventdata, handles)
% hObject    handle to modis1b_y_var_menu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function plot_airs_bt(handles)

disp('Plot Selected AIRS Brightness Temperature')

drawnow
figure(handles.airs_figure)
axes(handles.airs_axes)

plot(handles.airs.wavenumber, handles.airs.data, 'k')
xlabel(['Wavenumber (cm-1>)'])
ylabel('Brightness Temperature')
imageTitle = sprintf('AIRS  Brightness Temperature at [%4.1f, %5.1f], record number %g', ...
             handles.airs.lat, handles.airs.lon, handles.airs.index);     
title(imageTitle)
xmin = min(handles.airs.wavenumber);
xmax = max(handles.airs.wavenumber);
set(gca, 'XLim', [xmin xmax])
ymin=200;
ymax=320;
%ymin = min(min(handles.airs.data));
%ymax = max(max(handles.airs.data));
set(gca, 'YLim', [ymin ymax])
newHandles = handles;
% --------------------------------------------------------------------
function plot_airs_bt_zoom(handles,zoom_data)

disp('Plot Selected AIRS Brightness Temperature')

drawnow
figure(handles.airs_figure)
axes(handles.airs_axes)

plot(handles.airs.wavenumber, handles.airs.data, 'k')
xlabel(['Wavenumber (cm-1>)'])
ylabel('Brightness Temperature')
imageTitle = sprintf('AIRS  Brightness Temperature at [%4.1f, %5.1f], record number %g', ...
             handles.airs.lat, handles.airs.lon, handles.airs.index);     
title(imageTitle)
xmin = zoom_data.x_limit(1);
xmax = zoom_data.x_limit(2);
set(gca, 'XLim', [xmin xmax])
ymin = zoom_data.y_limit(1);
ymax = zoom_data.y_limit(2);
set(gca, 'YLim', [ymin ymax])
%ymin=200;
%ymax=320;
%ymin = min(min(handles.airs.data(xmin:xmax)));
%ymax = max(max(handles.airs.data(xmin:xmax)));
%set(gca, 'YLim', [ymin ymax])

% --------------------------------------------------------------------
function [newHandles] = plot_cmask(handles)

%disp('Plot MODIS Classification mask')

drawnow
figure(handles.airs_figure)
axes(handles.cmask_axes)
cla

% Get map keywords
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%Changed colormap to jet instead of cmask since not plotting cmask
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
keywords = {'mercator', 'colorbar', 'magentamap', 'jetcolormap'};
%imageTitle = ['MODIS Classification Mask'];
imageTitle = ['MODIS Band 31 BT'];

handles.camsk_axes = plotSingleImageAxes(handles.modis.sub_data, handles.modis.sub_lat, ...
      handles.modis.sub_lon, handles.cmask_axes, keywords);
title(imageTitle)

newHandles = handles;


% --------------------------------------------------------------------
function diff_x_var_menu_Callback(hObject, eventdata, handles)
% hObject    handle to diff_x_var_menu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function redraw_bt_Callback(hObject, eventdata, handles)
% hObject    handle to redraw_bt (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

plot_airs_bt(handles);

% --------------------------------------------------------------------
function select_wn_Callback(hObject, eventdata, handles)
% hObject    handle to select_wn (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
%%Added 9/2005 for user to zoom on BT display on top of airsDisplay

%Get mouse selected BT region
data=select_wn(handles.airs_axes);
zoom_data=data;
plot_airs_bt_zoom(handles, zoom_data);

% --------------------------------------------------------------------
function save_spectra_menu_Callback(hObject, eventdata, handles)
% hObject    handle to save_spectra_menu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
%%Added 10/2005 JS to save AIRS BT Spectra to ASCII from airsDisplay


initial_t = datenum('1/1/1993');
file_time = handles.airs.time;
file_date = (file_time/86400.0) + initial_t;
file_date = datestr(file_date);

%Get file name to write to and then write data
[fileName, dataPath]=uiputfile('../*.txt','Filenames File');
fid = fopen([dataPath fileName], 'w');
if (fid < 0)
	error('Cannot open file');
end
fprintf(fid, '%%******************************************\n');
fprintf(fid, '%%AIRS BT Spectra\n');
fprintf(fid, '%%Saved from Display GUI Matlab program\n');
fprintf(fid, '%%Corresponding AIRS granule is: %s\n',handles.airs.filename.level1b);
fprintf(fid, '%%Date of AIRS Granule is: %s\n',file_date);
fprintf(fid, '%%Spectra corresponds to AIRS record number, Lat, Lon:\n');
fprintf(fid, '%%%6.0f %6.2f %6.2f\n',handles.airs.index, handles.airs.lat, handles.airs.lon);
fprintf(fid, '%%******************************************\n');
fprintf(fid, '%%Wavenumber Brightness Temperature\n');
num_channels=size(handles.airs.data);
for i=1:num_channels
	fprintf(fid, '%8.3f %4.2f\n', handles.airs.wavenumber(i),handles.airs.data(i));
end
%closing file
fclose(fid);
disp('Spectra Save Complete');



