function varargout = collocation(varargin)
% COLLOCATION M-file for collocation.fig
%      COLLOCATION, by itself, creates a new COLLOCATION or raises the existing
%      singleton*.
%
%      H = COLLOCATION returns the handle to a new COLLOCATION or the handle to
%      the existing singleton*.
%
%      COLLOCATION('Property','Value',...) creates a new COLLOCATION using the
%      given property value pairs. Unrecognized properties are passed via
%      varargin to collocation_OpeningFcn.  This calling syntax produces a
%      warning when there is an existing singleton*.
%
%      COLLOCATION('CALLBACK') and COLLOCATION('CALLBACK',hObject,...) call the
%      local function named CALLBACK in COLLOCATION.M with the given input
%      arguments.
%
%      *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 collocation

% Last Modified by GUIDE v2.5 17-Oct-2005 15:52:21

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @collocation_OpeningFcn, ...
                   'gui_OutputFcn',  @collocation_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 collocation is made visible.
function collocation_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   unrecognized PropertyName/PropertyValue pairs from the
%            command line (see VARARGIN)

set(handles.select_menu, 'Enable', 'off');
set(handles.redraw_menu, 'Enable', 'off');
set(handles.save_menu, 'Enable', 'off');
set(handles.cbar_options, 'Enable', 'off');
set(handles.text5,'String','AIRS Title');
set(handles.new_wn,'String','872.0');


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

% Update handles structure
guidata(hObject, handles);

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


% --- Outputs from this function are returned to the command line.
function varargout = collocation_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 load_menu_Callback(hObject, eventdata, handles)
% hObject    handle to load_menu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Read in all of the data filenames
% Load in the following only in order to save memory space:
% Read in AIRS and MODIS collocation data: handles.colloc.data
% Read in AIRS brighteness temperature at channel 763: 
%      handles.airs.data
%      handles.airs.wavenumber, handles.airs.channel
%      handles.airs.lat, handles.airs.lon
% Read in MODIS pixels' latitude/longitude: 
%      handles.modis.lat and :handles.modis.lon
global lock_cbar;

disp('Load Data ....')
handles = readDataFilenames(handles);

% Read AIRS and MODIS collocation data
disp('  Load AIRS and MODIS Collocation ...')
if strcmp(handles.colloc.filename(end-2:end), 'txt')
  data = read_collocation(handles.colloc.filename);
else
  var = handles.colloc.filename(1:end-4);
  s = ['load ' var ';'];
  eval(s)
  clear var
end
handles.colloc.data = data;
clear data;


% Read AIRS default channel(675) data and lat/lon
disp('  Load AIRS ...')
data = read_eos_fields_airs2(handles.airs.filename.level1b);

%add new handles!

handles.airs.spectral_freq=data.spectral_freq;
handles.airs.channel = 675;
handles.airs.wavenumber = data.spectral_freq(handles.airs.channel);
[nchannel, handles.airs.pixels_across, handles.airs.scanlines] = size(data.radiances);
handles.airs.data = zeros(handles.airs.pixels_across, handles.airs.scanlines);
handles.airs.data = rad2bt(handles.airs.wavenumber, ...
                    squeeze(data.radiances(handles.airs.channel, :, :)));
handles.airs.lat = data.Latitude;
handles.airs.lon = data.Longitude;
clear data; clear tmp;

handles = load_modis03(handles);

disp('  Data Load Finished')

% Plot AIRS brightness teperature on GUI figure
%%Initally make color bar limits unlocked (fit to image)
lock_cbar = false;
plotAirsImage(handles);

set(handles.select_menu, 'Enable', 'on');
set(handles.redraw_menu, 'Enable', 'on');
set(handles.save_menu, 'Enable', 'on');
set(handles.cbar_options, 'Enable', 'on');

% Update handles structure
guidata(hObject, handles);



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

% Get mouse selected geographical region
data = select_region(handles.colloc_axes);
h = findobj(handles.colloc_axes, 'Type', 'surface');
x = get(h, 'XData');
y = get(h, 'YData');
airs_index = searchElementRegion(x, y, data.x_limit, data.y_limit);
if isempty(airs_index)
  errordlg('No AIRS Elementis are selected', 'Try again');
  return
end
handles.airs.index = airs_index;
clear airs_index; clear x; clear y; clear h;

% Draw a rectangle on the map
axes(handles.colloc_axes)
hold on
plotm(data.boundary.lat, data.boundary.lon, 'w-')


% Get selected MODIS domain
if isempty(handles.modis.lat)
  handles = load_modis03(handles);
end
handles = select_modis_domain(handles);

% Show selected data of MODIS map
handles.modis.refine = [];
handles.modis.sub_geo = data.latLonLimit;
modisDisplay('airs', handles.airs, 'modis', handles.modis, 'colloc', handles.colloc);
handles.modis.lat = [];
handles.modis.lon = [];
clear data;

% Update handles structure
guidata(hObject, handles);



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

% Plot AIRS brightness teperature on GUI figure
plotAirsImage(handles);


% --------------------------------------------------------------------
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)

save_image(handles.colloc_figure)


% --------------------------------------------------------------------
function new_handles = readDataFilenames(handles)
% Read filenames for collocation
% AIRS, MODIS level1b, MODIS level03 and AIRS-MODIS collocation
%
fn = readFilenames;
handles.airs.filename.level1b = fn.airs;
handles.airs.filename.flag = fn.airs_flag;
handles.airs.filename.profiles = fn.profiles;
handles.airs.filename.cmask = fn.airs_cmask;
handles.airs.filename.cmask_layer = fn.airs_cmask_layer;
handles.airs.filename.cphase_layer = fn.airs_cphase_layer;
handles.modis.filename.level1b = fn.modis1b;
handles.modis.filename.modis03 = fn.modis03;
handles.modis.filename.modis35 = fn.modis35;
handles.modis.filename.modis06 = fn.modis06;
handles.modis.filename.tpw = fn.modis_tpw;
handles.modis.filename.cmask = fn.modis_cmask;
handles.colloc.filename = fn.colloc;
new_handles = handles;


% --------------------------------------------------------------------
function plotAirsImage(handles)
% Plot AIRS brightness teperature on GUI figure
global lock_cbar

drawnow
figure(handles.colloc_figure)
axes(handles.colloc_axes);
cla

%%Added if statement 10/17/2005 JS...whether or not user has selected
%%fixed colorbar or not
if lock_cbar == 1
	keywords = {'mercator', 'magentamap', 'colorbar', 'colorbar_fixed', 'jetcolormap'};
else
	keywords = {'mercator', 'magentamap', 'colorbar', 'jetcolormap'};
end
imageTitle = sprintf('AIRS  Channel %4d [%7.2f cm ^{-1}]  Brightness Temperature', ...
             handles.airs.channel, handles.airs.wavenumber);    
handles.colloc_axes = plotSingleImageAxes(handles.airs.data, ...
                    handles.airs.lat, handles.airs.lon, handles.colloc_axes, keywords);
set(handles.text5,'String',imageTitle);
newHandles = handles;

% --------------------------------------------------------------------
function loadNewChannel(handles)
% handles    structure with handles and user data (see GUIDATA)
%%Added Sept/2005 JS Loads new BT image on main screen based on 
%%wavenumber supplied by user.

disp('Load Data ....')

% Read AIRS new channel data and lat/lon
disp('  Load AIRS ...')

data = read_eos_fields_airs(handles.airs.filename.level1b);
[nchannel, handles.airs.pixels_across, handles.airs.scanlines] = size(data.radiances);
handles.airs.data = zeros(handles.airs.pixels_across, handles.airs.scanlines);
handles.airs.data = rad2bt(handles.airs.wavenumber, ...
                    squeeze(data.radiances(handles.airs.channel, :, :)));
handles.airs.lat = data.Latitude;
handles.airs.lon = data.Longitude;
clear data; clear tmp;
plotAirsImage(handles);

%---------------------------------------------------------------------
% --- Executes during object creation, after setting all properties.
function new_wn_CreateFcn(hObject, eventdata, handles)
%%Added Sept/2005 JS Part of GUI that allows user to input wavenumber they
%%would like to view
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

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

%%Added Sept/2005 JS Determines AIRS channel closest to desired wavenum
%%user entered on main GUI.
user_wn=str2double(get(hObject,'String'));
nearest_airs=findnear(handles.airs.spectral_freq,user_wn);
handles.airs.channel = nearest_airs(1,2);
handles.airs.wavenumber=handles.airs.spectral_freq(handles.airs.channel);
loadNewChannel(handles);


% --------------------------------------------------------------------
function cbar_options_Callback(hObject, eventdata, handles)
% hObject    handle to cbar_options (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
%%Added function as part of the option for a user to fix the BT
%%colorbar to certain values 10/17/2005 JS

% --------------------------------------------------------------------
function lock_limits_Callback(hObject, eventdata, handles)
% hObject    handle to lock_limits (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
%%Added function as part of the option for a user to fix the BT
%%colorbar to certain values 10/17/2005 JS
global lock_cbar;
global cbar_limits;
lock_cbar = true;
user_min = inputdlg('Choose a BT min:  ');
while isempty(user_min) 
	uiwait(msgbox('Invalid Entry!','Enter BT Min','modal'));
	user_min = inputdlg('Choose a BT min:  ');
end
user_min = cell2mat(user_min);
user_min = str2num(user_min);
while user_min < 0
	uiwait(msgbox('Negative numbers not allowed!','Enter BT Min','modal'));
	user_min = inputdlg('Choose a BT min:  ');
	user_min = cell2mat(user_min);
	user_min = str2num(user_min);
end

user_max = inputdlg('Choose a BT max:  ');
while isempty(user_max) 
	uiwait(msgbox('Invalid Entry!','Enter BT Max','modal'));
	user_max = inputdlg('Choose a BT max:  ');
end
user_max = cell2mat(user_max);
user_max = str2num(user_max);
while user_max < 0
	uiwait(msgbox('Negative numbers not allowed!','Enter BT Max','modal'));
	user_max = inputdlg('Choose a BT max:  ');
	user_max = cell2mat(user_max);
	user_max = str2num(user_max);
end
while user_max < user_min
	uiwait(msgbox('Max must be larger than min!','Enter BT Max','modal'));
	user_max = inputdlg('Choose a BT max:  ');
	user_max = cell2mat(user_max);
	user_max = str2num(user_max);
end
cbar_limits=[user_min user_max];
%%Call plot procedure to refresh image with new limits
plotAirsImage(handles);


% --------------------------------------------------------------------
function unlock_limits_Callback(hObject, eventdata, handles)
% hObject    handle to unlock_limits (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
%%Added function as part of the option for a user to fix the BT
%%colorbar to certain values 10/17/2005 JS
global lock_cbar;
lock_cbar = false;
