function varargout = C_ImagebProcessing(varargin)
% C_IMAGEBPROCESSING MATLAB code for C_ImagebProcessing.fig
%      C_IMAGEBPROCESSING, by itself, creates a new C_IMAGEBPROCESSING or raises the existing
%      singleton*.
%
%      H = C_IMAGEBPROCESSING returns the handle to a new C_IMAGEBPROCESSING or the handle to
%      the existing singleton*.
%
%      C_IMAGEBPROCESSING('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in C_IMAGEBPROCESSING.M with the given input arguments.
%
%      C_IMAGEBPROCESSING('Property','Value',...) creates a new C_IMAGEBPROCESSING or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before C_ImagebProcessing_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to C_ImagebProcessing_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 C_ImagebProcessing

% Last Modified by GUIDE v2.5 17-Jun-2012 17:30:40

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @C_ImagebProcessing_OpeningFcn, ...
                   'gui_OutputFcn',  @C_ImagebProcessing_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(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 C_ImagebProcessing is made visible.
function C_ImagebProcessing_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 C_ImagebProcessing (see VARARGIN)

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

set(handles.g1,'Visible','off');
set(handles.g2,'Visible','off');
set(handles.dim,'Enable','off');
set(handles.path,'Enable','off');
set(handles.save,'Enable','off');
set(handles.s1,'Enable','off');
set(handles.s2,'Enable','off');
set(handles.s3,'Enable','off');
set(handles.s4,'Enable','off');
set(handles.g3,'Visible','off');
set(handles.g4,'Visible','off');
set(handles.s5,'Enable','off');
set(handles.s6,'Enable','off');
set(handles.s7,'Enable','off');
set(handles.s8,'Enable','off');
set(handles.s9,'Enable','off');
set(handles.slider1,'Enable','off');
set(handles.slider2,'Enable','off');
set(handles.slider3,'Enable','off');
set(handles.slider4,'Enable','off');
set(handles.slider5,'Enable','off');
set(handles.set1,'Enable','off');
set(handles.set2,'Enable','off');
set(handles.set3,'Enable','off');
set(handles.set4,'Enable','off');
set(handles.set5,'Enable','off');
set(handles.rv,'Enable','off');
set(handles.gv,'Enable','off');
set(handles.bv,'Enable','off');
set(handles.cv,'Enable','off');
set(handles.bbv,'Enable','off');
set(handles.reset,'Enable','off');
set(handles.e1,'Enable','off');
set(handles.e2,'Enable','off');
set(handles.resize,'Enable','off');
set(handles.chres,'Enable','off');
set(handles.sres,'Enable','off');
set(handles.set5,'Enable','off');
set(handles.rrv,'Enable','off');
set(handles.slider6,'Enable','off');
set(handles.s10,'Enable','off');
set(handles.s6,'Enable','off');
set(handles.p1,'Enable','off');
set(handles.p2,'Enable','off');
set(handles.p3,'Enable','off');
set(handles.p4,'Enable','off');
set(handles.p5,'Enable','off');
set(handles.p6,'Enable','off');
set(handles.p7,'Enable','off');
set(handles.selectcm,'Enable','off');
set(handles.setcm,'Enable','off');
set(handles.invc,'Enable','off');
set(handles.autoa,'Enable','off');
set(handles.rgbo,'Enable','off');
set(handles.rgbm,'Enable','off');
set(handles.autocon,'Enable','off');
set(handles.crop,'Enable','off');
set(handles.n1,'Enable','off');
set(handles.n3,'Enable','off');
set(handles.n4,'Enable','off');
set(handles.n5,'Enable','off');
set(handles.dim2,'Enable','off');
set(handles.info,'Enable','off');
set(handles.f1,'Enable','off');
set(handles.f2,'Enable','off');
set(handles.f3,'Enable','off');
set(handles.f4,'Enable','off');
set(handles.dia,'Enable','off');
set(handles.ero,'Enable','off');
set(handles.strel,'Enable','off');
set(handles.strels,'Enable','off');
set(handles.strelv,'Enable','off');
set(handles.dfh1,'Enable','off');
set(handles.dfh2,'Enable','off');
% Update handles structure

guidata(hObject, handles);

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

% --- Outputs from this function are returned to the command line.
function varargout = C_ImagebProcessing_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 updateg4(handles)
r=handles.img(:,:,1);
g=handles.img(:,:,2);
b=handles.img(:,:,3);
x=size(r); x=(1:x(1,2));
r=r(1,:); g=g(1,:); b=b(1,:);
axes(handles.g4); plot(x,r,'r');
hold on
plot(x,g,'g'); plot(x,b,'b'); hold off;

% --- Executes on button press in load.
function load_Callback(hObject, eventdata, handles)
% hObject    handle to load (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Browse the file from user
[file path]=uigetfile({'*.jpg';'*.bmp';'*.jpeg';'*.png'}, 'Load Image File within Avilable Extensions');
image=[path file];
handles.file=image;
if (file==0)
    warndlg('You did not selected any file ') ; % fille is not selected
end
 [fpath, fname, fext]=fileparts(file);
 validex=({'.bmp','.jpg','.jpeg','.png'});
 found=0;
 for (x=1:length(validex))
 if (strcmpi(fext,validex{x}))
     found=1;
     set(handles.dim,'Enable','on');
set(handles.path,'Enable','on');
set(handles.save,'Enable','on');
set(handles.s1,'Enable','on');
set(handles.s2,'Enable','on');
set(handles.s3,'Enable','on');
set(handles.s4,'Enable','on');
set(handles.s5,'Enable','on');
set(handles.s6,'Enable','on');
set(handles.s7,'Enable','on');
set(handles.s8,'Enable','on');
set(handles.s9,'Enable','on');
set(handles.slider1,'Enable','on');
set(handles.slider2,'Enable','on');
set(handles.slider3,'Enable','on');
set(handles.slider4,'Enable','on');
set(handles.slider5,'Enable','on');
set(handles.set1,'Enable','on');
set(handles.set2,'Enable','on');
set(handles.set3,'Enable','on');
set(handles.set4,'Enable','on');
set(handles.set5,'Enable','on');
set(handles.rv,'Enable','on');
set(handles.gv,'Enable','on');
set(handles.bv,'Enable','on');
set(handles.cv,'Enable','on');
set(handles.bbv,'Enable','on');
set(handles.reset,'Enable','on');
set(handles.e1,'Enable','on');
set(handles.e2,'Enable','on');
set(handles.resize,'Enable','on');
set(handles.chres,'Enable','on');
set(handles.sres,'Enable','on');
set(handles.set5,'Enable','on');
set(handles.rrv,'Enable','on');
set(handles.slider6,'Enable','on');
set(handles.s10,'Enable','on');
%set(handles.g2,'Visible','on');
set(handles.p1,'Enable','on');
set(handles.p2,'Enable','on');
set(handles.p3,'Enable','on');
set(handles.p4,'Enable','on');
set(handles.selectcm,'Enable','on');
set(handles.setcm,'Enable','on');
set(handles.invc,'Enable','on');
set(handles.autoa,'Enable','on');
set(handles.rgbo,'Enable','on');
set(handles.rgbm,'Enable','on');
set(handles.autocon,'Enable','on');
set(handles.crop,'Enable','on');
set(handles.n1,'Enable','on');
set(handles.n3,'Enable','on');
set(handles.n4,'Enable','on');
set(handles.n5,'Enable','on');
set(handles.dim2,'Enable','on');
set(handles.info,'Enable','on');
set(handles.f1,'Enable','on');
set(handles.f2,'Enable','on');
set(handles.f3,'Enable','on');
set(handles.f4,'Enable','on');
set(handles.dia,'Enable','on');
set(handles.ero,'Enable','on');
set(handles.strel,'Enable','on');
set(handles.strels,'Enable','on');
set(handles.strelv,'Enable','on');
set(handles.dfh1,'Enable','on');
set(handles.dfh2,'Enable','on');

     handles.img=imread(image);
handles.i=imread(image);
h = waitbar(0,'Please wait...');
steps = 100;
for step = 1:steps
    % computations take place here
    waitbar(step / steps)
end
close(h)
 axes(handles.g1); cla; imshow(handles.img);
 axes(handles.g2); cla; imshow(handles.img);
 [dimen]=size(handles.img); dimen=num2str(dimen); set(handles.dim,'String',dimen);
 s=num2str(size(handles.img)); set(handles.dim2,'String',s);
 set(handles.path,'String',image);
 guidata(hObject,handles);
break;
 end
 end
if (found==0)
     errordlg('Selected file does not match available extensions. Please select file from available extensions [ .jpg, .jpeg, .bmp, .png] ','Image Format Error');
end
% Disply image in current axes.

 set(handles.g3,'Visible','on');
set(handles.g4,'Visible','on');

% RGB component graph
r=handles.i(:,:,1);
g=handles.i(:,:,2);
b=handles.i(:,:,3);
x=size(r); x=(1:x(1,2));
r=r(1,:); g=g(1,:); b=b(1,:);
axes(handles.g3); plot(x,r,'r');
hold on
plot(x,g,'g'); plot(x,b,'b'); hold off;

updateg4(handles)

% --- Executes on button press in save.
function save_Callback(hObject, eventdata, handles)
% hObject    handle to save (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
[file path]= uiputfile('*.jpg','Save Image as');
save=[path file]; imwrite(handles.img,save,'jpg');

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

% Hints: get(hObject,'String') returns contents of dim as text
%        str2double(get(hObject,'String')) returns contents of dim as a double

% --- Executes during object creation, after setting all properties.
function dim_CreateFcn(hObject, eventdata, handles)
% hObject    handle to dim (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

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

% Hints: get(hObject,'String') returns contents of path as text
%        str2double(get(hObject,'String')) returns contents of path as a double

% --- Executes during object creation, after setting all properties.
function path_CreateFcn(hObject, eventdata, handles)
% hObject    handle to path (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in pushbutton3.
function pushbutton3_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% --- Executes on slider movement.
function slider1_Callback(hObject, eventdata, handles)
% hObject    handle to slider1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
x=get(hObject,'Value');
r=handles.img(:,:,1);
g=handles.img(:,:,2); b=handles.img(:,:,3);
r1=r+x; rcon=cat(3,r1,g,b);
axes(handles.g2); cla; imshow(rcon)
set(handles.rv,'String',num2str(x));
handles.img=rcon;
r=handles.img(:,:,1);
g=handles.img(:,:,2);
b=handles.img(:,:,3);
x=size(r); x=(1:x(1,2));
r=r(1,:); g=g(1,:); b=b(1,:);
axes(handles.g4); plot(x,r,'r');
hold on
plot(x,g,'g'); plot(x,b,'b'); hold off;

% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider

% --- Executes during object creation, after setting all properties.
function slider1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to slider1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

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

% Hints: get(hObject,'String') returns contents of rv as text
%        str2double(get(hObject,'String')) returns contents of rv as a double

% --- Executes during object creation, after setting all properties.
function rv_CreateFcn(hObject, eventdata, handles)
% hObject    handle to rv (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on slider movement.
function slider2_Callback(hObject, eventdata, handles)
% hObject    handle to slider2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

x=get(hObject,'Value');
r=handles.img(:,:,1);
g=handles.img(:,:,2); b=handles.img(:,:,3);
g1=g+x; gcon=cat(3,r,g1,b);
axes(handles.g2); cla; imshow(gcon)
set(handles.gv,'String',num2str(x));
handles.img=gcon;

updateg4(handles)
% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider

% --- Executes during object creation, after setting all properties.
function slider2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to slider2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

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

% Hints: get(hObject,'String') returns contents of gv as text
%        str2double(get(hObject,'String')) returns contents of gv as a double

% --- Executes during object creation, after setting all properties.
function gv_CreateFcn(hObject, eventdata, handles)
% hObject    handle to gv (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on slider movement.
function slider3_Callback(hObject, eventdata, handles)
% hObject    handle to slider3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
x=get(hObject,'Value');
r=handles.img(:,:,1);
g=handles.img(:,:,2); b=handles.img(:,:,3);
b1=b+x; bcon=cat(3,r,g,b1);
axes(handles.g2); cla; imshow(bcon)
set(handles.bv,'String',num2str(x));
handles.img=bcon;
updateg4(handles)
% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider

% --- Executes during object creation, after setting all properties.
function slider3_CreateFcn(hObject, eventdata, handles)
% hObject    handle to slider3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

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

% Hints: get(hObject,'String') returns contents of bv as text
%        str2double(get(hObject,'String')) returns contents of bv as a double

% --- Executes during object creation, after setting all properties.
function bv_CreateFcn(hObject, eventdata, handles)
% hObject    handle to bv (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on slider movement.
function slider4_Callback(hObject, eventdata, handles)
% hObject    handle to slider4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
x=get(hObject,'Value');
img=handles.img;
img=img.*x;
axes(handles.g2); cla; imshow(img)
set(handles.cv,'String',num2str(x));
handles.img=img;
updateg4(handles)
% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider

% --- Executes during object creation, after setting all properties.
function slider4_CreateFcn(hObject, eventdata, handles)
% hObject    handle to slider4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

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

% Hints: get(hObject,'String') returns contents of cv as text
%        str2double(get(hObject,'String')) returns contents of cv as a double

% --- Executes during object creation, after setting all properties.
function cv_CreateFcn(hObject, eventdata, handles)
% hObject    handle to cv (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on slider movement.
function slider5_Callback(hObject, eventdata, handles)
% hObject    handle to slider5 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
x=get(hObject,'Value');
img=handles.img;
img=img+x;
axes(handles.g2); cla; imshow(img)
set(handles.bbv,'String',num2str(x));
handles.img=img;
updateg4(handles)
% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider

% --- Executes during object creation, after setting all properties.
function slider5_CreateFcn(hObject, eventdata, handles)
% hObject    handle to slider5 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

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

% Hints: get(hObject,'String') returns contents of bbv as text
%        str2double(get(hObject,'String')) returns contents of bbv as a double

% --- Executes during object creation, after setting all properties.
function bbv_CreateFcn(hObject, eventdata, handles)
% hObject    handle to bbv (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in reset.
function reset_Callback(hObject, eventdata, handles)
% hObject    handle to reset (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.img=handles.i;
axes(handles.g2); cla; imshow(handles.img);
updateg4(handles);
s=num2str(size(handles.img)); set(handles.dim2,'String',s);
guidata(hObject,handles);

% --- Executes on button press in set1.
function set1_Callback(hObject, eventdata, handles)
% hObject    handle to set1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
axes(handles.g2); img=getimage;
handles.img=img; imshow(handles.img);
updateg4(handles);
guidata(hObject,handles);

% --- Executes on button press in set2.
function set2_Callback(hObject, eventdata, handles)
% hObject    handle to set2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
axes(handles.g2); img=getimage;
handles.img=img; imshow(handles.img);
updateg4(handles);
guidata(hObject,handles);

% --- Executes on button press in set3.
function set3_Callback(hObject, eventdata, handles)
% hObject    handle to set3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
axes(handles.g2); img=getimage;
handles.img=img; imshow(handles.img);
updateg4(handles);
guidata(hObject,handles);

% --- Executes on button press in set4.
function set4_Callback(hObject, eventdata, handles)
% hObject    handle to set4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
axes(handles.g2); img=getimage;
handles.img=img; imshow(handles.img);
updateg4(handles);
guidata(hObject,handles);

% --- Executes on button press in set5.
function set5_Callback(hObject, eventdata, handles)
% hObject    handle to set5 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
axes(handles.g2); img=getimage;
handles.img=img; imshow(handles.img);
updateg4(handles);
guidata(hObject,handles);

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

% Hints: get(hObject,'String') returns contents of e1 as text
%        str2double(get(hObject,'String')) returns contents of e1 as a double

% --- Executes during object creation, after setting all properties.
function e1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to e1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

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

% Hints: get(hObject,'String') returns contents of e2 as text
%        str2double(get(hObject,'String')) returns contents of e2 as a double

% --- Executes during object creation, after setting all properties.
function e2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to e2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in resize.
function resize_Callback(hObject, eventdata, handles)
% hObject    handle to resize (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
h=str2num(get(handles.e1,'String'));
w=str2num(get(handles.e2,'String'));
handles.img=imresize(handles.img, [h w]);
axes(handles.g2); cla; imshow(handles.img);
updateg4(handles);
s=num2str(size(handles.img)); set(handles.dim2,'String',s);
guidata(hObject,handles);

% --- Executes on selection change in chres.
function chres_Callback(hObject, eventdata, handles)
% hObject    handle to chres (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
val=get(hObject,'Value');
switch val
    case 1
        warndlg('Please select a resolution value');
    case 2   %256x256
            handles.res=handles.img;
            axes(handles.g2); cla;
            handles.res=imresize(imresize(handles.res,.5),1);
            imshow(handles.res);
            guidata(hObject, handles);
            handles.img=handles.res;
            updateg4(handles);

    case 3  % 128X128
            handles.res=handles.img;
            axes(handles.g2); cla;
            handles.res=imresize(imresize(handles.res,1/2),2);
            imshow(handles.res);
            guidata(hObject, handles);
            handles.img=handles.res; updateg4(handles);

    case 4 % 64x64
            handles.res=handles.img;
            axes(handles.g2); cla;
            handles.res=imresize(imresize(handles.res,1/4),4);
            imshow(handles.res);
            guidata(hObject, handles);
           handles.img=handles.res;  updateg4(handles);

    case 5  % 32x32
           handles.res=handles.img;
            axes(handles.g2); cla;
            handles.res=imresize(imresize(handles.res,1/8),8);
            imshow(handles.res);
            guidata(hObject, handles);
           handles.img=handles.res;  updateg4(handles);

        case 6  % 16x16
            handles.res=handles.img;
            axes(handles.g2); cla;
            handles.res=imresize(imresize(handles.res,1/16),16);
            imshow(handles.res);
            guidata(hObject, handles);
           handles.img=handles.res;  updateg4(handles);

        case 7  % 8x8
            handles.res=handles.img;
            axes(handles.g2); cla;
            handles.res=imresize(imresize(handles.res,1/32),32);
            imshow(handles.res);
            guidata(hObject, handles);
            handles.img=handles.res; updateg4(handles);
end

        % Hints: contents = cellstr(get(hObject,'String')) returns chres contents as cell array
%        contents{get(hObject,'Value')} returns selected item from chres

% --- Executes during object creation, after setting all properties.
function chres_CreateFcn(hObject, eventdata, handles)
% hObject    handle to chres (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in sres.
function sres_Callback(hObject, eventdata, handles)
% hObject    handle to sres (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.img=handles.res;
axes(handles.g2); cla; imshow(handles.img);
s=num2str(size(handles.img)); set(handles.dim2,'String',s);
guidata(hObject,handles);
updateg4(handles);

% --- Executes on slider movement.
function slider6_Callback(hObject, eventdata, handles)
% hObject    handle to slider6 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
rrv=(get(hObject,'Value'));
handles.rot=handles.img;
handles.rot=imrotate(handles.rot,rrv);
axes(handles.g2); cla; imshow(handles.rot);
guidata(hObject,handles)
% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider

% --- Executes during object creation, after setting all properties.
function slider6_CreateFcn(hObject, eventdata, handles)
% hObject    handle to slider6 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

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

% Hints: get(hObject,'String') returns contents of rrv as text
%        str2double(get(hObject,'String')) returns contents of rrv as a double

% --- Executes during object creation, after setting all properties.
function rrv_CreateFcn(hObject, eventdata, handles)
% hObject    handle to rrv (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in set6.
function set6_Callback(hObject, eventdata, handles)
% hObject    handle to set6 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.img=handles.rot;
axes(handles.g2); cla; imshow(handles.img);
updateg4(handles);
guidata(hObject,handles);

% --- Executes on button press in p1.
function p1_Callback(hObject, eventdata, handles)
% hObject    handle to p1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
h = waitbar(0,'Please wait...');
steps = 100;
for step = 1:steps
    % computations take place here
    waitbar(step / steps)
end
close(h)
imageinfo(handles.file);

% --- Executes on button press in p2.
function p2_Callback(hObject, eventdata, handles)
% hObject    handle to p2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
if (get(hObject,'Value')==get(hObject,'Max'))
axes(handles.g2); imdistline
elseif (get(hObject,'Value')==get(hObject,'Min'))
    axes(handles.g2); imshow(handles.img)
end
% Hint: get(hObject,'Value') returns toggle state of p2

% --- Executes on button press in p3.
function p3_Callback(hObject, eventdata, handles)
% hObject    handle to p3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
impixelinfo;
% Hint: get(hObject,'Value') returns toggle state of p3

% --- Executes on button press in p4.
function p4_Callback(hObject, eventdata, handles)
% hObject    handle to p4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
if (get(hObject,'Value')==get(hObject,'Max'))
axes(handles.g2); impixelregion
elseif (get(hObject,'Value')==get(hObject,'Min'))
    axes(handles.g2); imshow(handles.img)
end

% Hint: get(hObject,'Value') returns toggle state of p4

% --- Executes on button press in p5.
function p5_Callback(hObject, eventdata, handles)
% hObject    handle to p5 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
imscrollpanel(handles.g2,handles.img);

% --- Executes on button press in p6.
function p6_Callback(hObject, eventdata, handles)
% hObject    handle to p6 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
imoverview(handles.image)

% --- Executes on button press in p7.
function p7_Callback(hObject, eventdata, handles)
% hObject    handle to p7 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% --- Executes on selection change in selectcm.
function selectcm_Callback(hObject, eventdata, handles)
% hObject    handle to selectcm (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.cm=handles.img;
val=get(hObject,'Value');
switch val
    case 1
        helpdlg('Please first select a color map','Color Map help');
    case 2
        handles.cm=rgb2ind(handles.cm,jet);
        handles.cm=ind2rgb(handles.cm,jet);
        axes(handles.g2); cla; imshow(handles.cm);
        guidata(hObject,handles);
        handles.img=handles.cm;
        updateg4(handles);
    case 3
        handles.cm=rgb2ind(handles.cm,HSV);
        handles.cm=ind2rgb(handles.cm,HSV);
        axes(handles.g2); cla; imshow(handles.cm);
        guidata(hObject,handles);
        handles.img=handles.cm;
        updateg4(handles);
    case 4
        handles.cm=rgb2ind(handles.cm,hot);
        handles.cm=ind2rgb(handles.cm,hot);
        axes(handles.g2); cla; imshow(handles.cm);
        guidata(hObject,handles);
        handles.img=handles.cm;
        updateg4(handles);
    case 5
        handles.cm=rgb2ind(handles.cm,cool);
        handles.cm=ind2rgb(handles.cm,cool);
        axes(handles.g2); cla; imshow(handles.cm);
        guidata(hObject,handles);
        handles.img=handles.cm;
        updateg4(handles);
    case 6
        handles.cm=rgb2ind(handles.cm,spring);
        handles.cm=ind2rgb(handles.cm,spring);
        axes(handles.g2); cla; imshow(handles.cm);
        guidata(hObject,handles);
        handles.img=handles.cm;
        updateg4(handles);
    case 7
        handles.cm=rgb2ind(handles.cm,summer);
        handles.cm=ind2rgb(handles.cm,summer);
        axes(handles.g2); cla; imshow(handles.cm);
        guidata(hObject,handles);
        handles.img=handles.cm;
       updateg4(handles);
    case 8
        handles.cm=rgb2ind(handles.cm,autumn);
        handles.cm=ind2rgb(handles.cm,autumn);
        axes(handles.g2); cla; imshow(handles.cm);
        guidata(hObject,handles);
        handles.img=handles.cm;
        updateg4(handles);
    case 9
        handles.cm=rgb2ind(handles.cm,winter);
        handles.cm=ind2rgb(handles.cm,winter);
        axes(handles.g2); cla; imshow(handles.cm);
        guidata(hObject,handles);
        handles.img=handles.cm;
        updateg4(handles);
    case 10
        handles.cm=rgb2ind(handles.cm,gray);
        handles.cm=ind2rgb(handles.cm,gray);
        axes(handles.g2); cla; imshow(handles.cm);
        guidata(hObject,handles);
        handles.img=handles.cm;
        updateg4(handles);
    case 11
        handles.cm=rgb2ind(handles.cm,bone);
        handles.cm=ind2rgb(handles.cm,bone);
        axes(handles.g2); cla; imshow(handles.cm);
        guidata(hObject,handles);
        handles.img=handles.cm;
        updateg4(handles);
    case 12
        handles.cm=rgb2ind(handles.cm,copper);
        handles.cm=ind2rgb(handles.cm,copper);
        axes(handles.g2); cla; imshow(handles.cm);
        guidata(hObject,handles);
        handles.img=handles.cm;
        updateg4(handles);
    case 13
        handles.cm=rgb2ind(handles.cm,pink);
        handles.cm=ind2rgb(handles.cm,pink);
        axes(handles.g2); cla; imshow(handles.cm);
        guidata(hObject,handles);
        handles.img=handles.cm;
        updateg4(handles);
    case 14
        handles.cm=rgb2ind(handles.cm,lines);
        handles.cm=ind2rgb(handles.cm,lines);
        axes(handles.g2); cla; imshow(handles.cm);
        guidata(hObject,handles);
        handles.img=handles.cm;
        updateg4(handles);
end
% Hints: contents = cellstr(get(hObject,'String')) returns selectcm contents as cell array
%        contents{get(hObject,'Value')} returns selected item from selectcm

% --- Executes during object creation, after setting all properties.
function selectcm_CreateFcn(hObject, eventdata, handles)
% hObject    handle to selectcm (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in setcm.
function setcm_Callback(hObject, eventdata, handles)
% hObject    handle to setcm (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.img=handles.cm;
axes(handles.g2); cla; imshow(handles.img);
updateg4(handles);
guidata(hObject,handles);

% --- Executes on button press in invc.
function invc_Callback(hObject, eventdata, handles)
% hObject    handle to invc (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
x=handles.img;
r=x(:,:,1); r=256-r;
g=x(:,:,2); g=256-g;
b=x(:,:,3); b=256-b;
handles.img=cat(3,r,g,b);
axes(handles.g2); cla; imshow(handles.img);
updateg4(handles);
guidata(hObject,handles);
% --- Executes on button press in autoa.
function autoa_Callback(hObject, eventdata, handles)
% hObject    handle to autoa (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    handles.img= imadjust(handles.img,[.2 .3 0; .6 .7 1],[]);
   axes(handles.g2); cla; imshow(handles.img);
   guidata(hObject,handles);
   updateg4(handles);

% --- Executes on button press in rgbo.
function rgbo_Callback(hObject, eventdata, handles)
% hObject    handle to rgbo (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
r=handles.i(:,:,1);
g=handles.i(:,:,2);
b=handles.i(:,:,3);
figure,subplot(1,3,1)
imshow(r); title('RED Plane');
subplot(1,3,2)
imshow(g); title('Green Plane');
subplot(1,3,3)
imshow(b); title('Blue Plane');
% --- Executes on button press in rgbm.
function rgbm_Callback(hObject, eventdata, handles)
% hObject    handle to rgbm (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
r=handles.img(:,:,1);
g=handles.img(:,:,2);
b=handles.img(:,:,3);
figure,subplot(1,3,1)
imshow(r); title('RED Plane');
subplot(1,3,2)
imshow(g); title('Green Plane');
subplot(1,3,3)
imshow(b); title('Blue Plane');

% --- Executes on button press in exit.
function exit_Callback(hObject, eventdata, handles)
% hObject    handle to exit (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
close all;

% --- Executes on button press in autocon.
function autocon_Callback(hObject, eventdata, handles)
% hObject    handle to autocon (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
r=handles.img(:,:,1);  r=histeq(r);
g=handles.img(:,:,2);  g=histeq(g);
b=handles.img(:,:,3);  b=histeq(b);
handles.img=cat(3,r,g,b);
axes(handles.g2); cla; imshow(handles.img);
guidata(hObject,handles);
updateg4(handles);

% --- Executes on button press in n1.
function n1_Callback(hObject, eventdata, handles)
% hObject    handle to n1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA
    handles.img = imnoise(handles.img,'gaussian');
    axes(handles.g2); cla; imshow(handles.img);
guidata(hObject,handles);
updateg4(handles);

% --- Executes on button press in n3.
function n3_Callback(hObject, eventdata, handles)
% hObject    handle to n3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
h = waitbar(0,'Please wait...');
steps = 200;
for step = 1:steps
    % computations take place here
    waitbar(step / steps)
end
close(h)
handles.img = imnoise(handles.img,'poisson');
    axes(handles.g2); cla; imshow(handles.img);
guidata(hObject,handles);
updateg4(handles);

% --- Executes on button press in n4.
function n4_Callback(hObject, eventdata, handles)
% hObject    handle to n4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.img = imnoise(handles.img,'salt & pepper',0.02);
    axes(handles.g2); cla; imshow(handles.img);
guidata(hObject,handles);
updateg4(handles);

% --- Executes on button press in n5.
function n5_Callback(hObject, eventdata, handles)
% hObject    handle to n5 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.img = imnoise(handles.img,'speckle',0.04);
    axes(handles.g2); cla; imshow(handles.img);
guidata(hObject,handles);
updateg4(handles);

% --- Executes on button press in f1.
function f1_Callback(hObject, eventdata, handles)
% hObject    handle to f1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
h=fspecial('average');
handles.img=imfilter(handles.img,h,'replicate');
axes(handles.g2); cla; imshow(handles.img)
guidata(hObject,handles);
updateg4(handles);

% --- Executes on button press in crop.
function crop_Callback(hObject, eventdata, handles)
% hObject    handle to crop (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
imcrop(handles.g2);
handles.img=getimage(gca); close;
axes(handles.g2); cla; imshow(handles.img)
s=num2str(size(handles.img)); set(handles.dim2,'String',s);
guidata(hObject,handles);
updateg4(handles);

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

% Hints: get(hObject,'String') returns contents of dim2 as text
%        str2double(get(hObject,'String')) returns contents of dim2 as a double

% --- Executes during object creation, after setting all properties.
function dim2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to dim2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in info.
function info_Callback(hObject, eventdata, handles)
% hObject    handle to info (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
h = waitbar(0,'Please wait...');
steps = 100;
for step = 1:steps
    % computations take place here
    waitbar(step / steps)
end
close(h)
imageinfo(handles.g2);

% --- Executes on button press in dia.
function dia_Callback(hObject, eventdata, handles)
% hObject    handle to dia (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.mori=handles.img;
str=strel(handles.strel,handles.value);
handles.mori=imdilate(handles.mori,str);
axes(handles.g2); cla; imshow(handles.mori)
guidata(hObject,handles);
handles.img=handles.mori;
updateg4(handles);

%imscrollpanel(handles.g2,handles.img);

% --- Executes on button press in f3.
function f3_Callback(hObject, eventdata, handles)
% hObject    handle to f3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
r=medfilt2(handles.img(:,:,1)); g=medfilt2(handles.img(:,:,2)); b=medfilt2(handles.img(:,:,3));
handles.img=cat(3,r,g,b);
axes(handles.g2); cla; imshow(handles.img);
guidata(hObject,handles);
updateg4(handles);

% --- Executes on button press in f2.
function f2_Callback(hObject, eventdata, handles)
% hObject    handle to f2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
hsize=[8 8]; sigma=1.7;
h=fspecial('gaussian',hsize,sigma);
handles.img=imfilter(handles.img,h,'replicate');
axes(handles.g2); cla; imshow(handles.img);
guidata(hObject,handles);
updateg4(handles);

% --- Executes on button press in f4.
function f4_Callback(hObject, eventdata, handles)
% hObject    handle to f4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
h=fspecial('unsharp');
handles.img=imfilter(handles.img,h,'replicate');
axes(handles.g2); cla; imshow(handles.img)
guidata(hObject,handles);
updateg4(handles);

% --- Executes on button press in ero.
function ero_Callback(hObject, eventdata, handles)
% hObject    handle to ero (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.mori=handles.img;
str=strel(handles.strel,handles.value);
handles.mori=imerode(handles.mori,str);
axes(handles.g2); cla; imshow(handles.mori)
guidata(hObject,handles);
handles.img=handles.mori;
updateg4(handles);

% --- Executes on selection change in strel.
function strel_Callback(hObject, eventdata, handles)
% hObject    handle to strel (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
val=get(hObject,'Value');
switch val
        case 1
        helpdlg('Please first select Structring Element and value ','Morphological Operations');
        case 2
        handles.strel='diamond';
        case 3
        handles.strel='disk';
        case 4
        helpdlg('Value must be a nonnegative multiple of 3.','Octagon Structure Help');
        handles.strel='octagon';
end
guidata(hObject,handles);
% Hints: contents = cellstr(get(hObject,'String')) returns strel contents as cell array
%        contents{get(hObject,'Value')} returns selected item from strel

% --- Executes during object creation, after setting all properties.
function strel_CreateFcn(hObject, eventdata, handles)
% hObject    handle to strel (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function strelv_Callback(hObject, eventdata, handles)
% hObject    handle to strelv (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.value=str2num(get(hObject,'String'));
guidata(hObject,handles);
% Hints: get(hObject,'String') returns contents of strelv as text
%        str2double(get(hObject,'String')) returns contents of strelv as a double

% --- Executes during object creation, after setting all properties.
function strelv_CreateFcn(hObject, eventdata, handles)
% hObject    handle to strelv (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in strels.
function strels_Callback(hObject, eventdata, handles)
% hObject    handle to strels (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.img=handles.mori;
axes(handles.g2); cla; imshow(handles.img)
guidata(hObject,handles);
updateg4(handles);

% --- Executes on button press in dfh1.
function dfh1_Callback(hObject, eventdata, handles)
% hObject    handle to dfh1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
helpdlg('Click and draw a free hand on ORIGNAL image & then press ENTER. ');
axes(handles.g1); improfile; grid on;

% --- Executes on button press in dfh2.
function dfh2_Callback(hObject, eventdata, handles)
% hObject    handle to dfh2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
helpdlg('Click and draw a free hand on MODIFIED image & then press ENTER. ');
axes(handles.g2); improfile; grid on;

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


classdef LineSpecEnum < matlab.mixin.SetGet
    %LineSpecEnum Summary of this class goes here
    %   Detailed explanation goes here

    enumeration
        SolidLine('Solid Line', '-')
        DashedLine('Dashed Line', '--')
        DottedLine('Dotted Line', ':')
        DashedDotLine('Dashed-dot Line', '-.')
    end

    properties
        name char = '';
        linespec char = '';
    end

    methods
        function obj = LineSpecEnum(name, linespec)
            obj.name = name;
            obj.linespec = linespec;
        end
    end

    methods(Static)
        function [listBoxStr, m] = getListboxStr()
            m = enumeration('LineSpecEnum');
            listBoxStr = {m.name};
        end

        function [enum, ind] = getEnumForListboxStr(nameStr)
            m = enumeration('LineSpecEnum');
            ind = find(ismember({m.name},nameStr),1,'first');
            enum = m(ind);
        end

        function [ind, enum] = getIndForName(name)
            m = enumeration('LineSpecEnum');
            ind = find(ismember({m.name},name),1,'first');
            enum = m(ind);
        end
    end
end


function MTEXmenu
% show up MTEX menu

try
  g = getGitInfo;
  v = ['MTEX (' g.branch ')'];
catch
  v = getMTEXpref('version');
end

disp(' ');
if isempty(javachk('desktop'))
  if verLessThan('matlab','7.13')
    s = v;
  else
    s = ['' v ''];
  end
  disp([ s  ...
    ' (show documentation)'])
  disp('  Import pole figure data')
  disp('  Import EBSD data')
  disp('  Import ODF data')
  disp(' ');

  if isappdata(0,'MTEXInstalled') && getappdata(0,'MTEXInstalled')
    disp('  Uninstall MTEX')
    disp(' ');
  else
    disp('  Install MTEX for future sessions')
    disp(' ');
  end

end


% EEG_EVENTTYPES  - return a list of event or urevent types in a dataset and
%                     the respective number of events of each type. Output event
%                     types are sorted in reverse order of their number. If no
%                     outputs, print this list on the commandline instead.
%
% Usage:
%        >> [types,numbers] = eeg_eventtypes(EEG);
% Inputs:
%        EEG        - EEGLAB dataset structure
% Outputs:
%        types      - cell array of event type strings
%        numbers    - vector giving the numbers of each event type in the data
%
% Example:
%           >> eeg_eventtypes(EEG);       % print number of each event types
%
% Author: Scott Makeig, SCCN/INC/UCSD, April 28, 2004-

%        >> [types,numbers] = eeg_eventtypes(EEG,types);
%        >> [types,numbers] = eeg_eventtypes(EEG,'urevents',types);
% Inputs:
%        EEG        - EEGLAB dataset structure
%        'urevents' - return event information for the EEG.urevent structure
%        types      - {cell array} of event types to return or print.
% Outputs:
%        types      - cell array of event type strings
%        numbers    - vector giving the numbers of each event type in the data
%
% Note:  Numeric (ur)event types are converted to strings, so, for example,
%        types {13} and {'13'} are not distinguished.
%
% Example:
%           >> eeg_eventtypes(EEG);       % print number of each event types
%
% Currently disabled:
%           >> eeg_eventtypes(EEG,'urevent');  % print hist. of urevent types
%           >> eeg_eventtypes(EEG,{'rt'});% print number of 'rt' events
%           >> eeg_eventtypes(EEG,'urevent',{'rt','break'});
%                                         % print numbers of 'rt' and 'break'
%                                         % type urevents

% Copyright (C) 2004 Scott Makeig, SCCN/INC/UCSD, smakeig@ucsd.edu
%
% This file is part of EEGLAB, see http://www.eeglab.org
% for the documentation and details.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%
% 1. Redistributions of source code must retain the above copyright notice,
% this list of conditions and the following disclaimer.
%
% 2. Redistributions in binary form must reproduce the above copyright notice,
% this list of conditions and the following disclaimer in the documentation
% and/or other materials provided with the distribution.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
% THE POSSIBILITY OF SUCH DAMAGE.
%
%
% event types can be numbers, Stefan Debener, 05/12/2006,
% added 2nd and 3rd args, sorted outputs by number, Scott Makeig, 09/12/06

function [types,numbers] = eeg_eventtypes(EEG,arg2,arg3)

if nargin< 1
   help eeg_eventtypes
   return
end
if ~isstruct(EEG)
   error('EEG argument must be a dataset structure')
end

if ~isfield(EEG,'event')
   error('EEG.event field not found');
end
if nargin > 1
    error('Multiple input arguments are currently disabled');
end

UREVENTS = 0; % flag returning info for urevents instead of events
typelist = [];
if nargin>1
   if ischar(arg2)
       if strcmp(arg2,'urevent') || strcmp(arg2,'urevents')
            UREVENTS = 1; % change flag
       else
            error('second argument string not understood')
       end
       if nargin>2
            if iscell(arg3)
                  typelist = arg3;
            end
       end
   elseif iscell(arg2)
       typelist = arg2;
   end
end
if ~isempty(typelist)     % cast to cell array of strings
   for k=1:length(typelist)
       if isnumeric(typelist{k})
          typelist{k} = num2str(typelist{k});
       end
   end
end

if ~UREVENTS
   nevents = length(EEG.event);
   alltypes = cell(nevents,1);
   for k=1:nevents
       if isnumeric(EEG.event(k).type)
          alltypes{k} = num2str(EEG.event(k).type);
       else
          alltypes{k} = EEG.event(k).type;
       end
   end
else
   nevents = length(EEG.urevent);
   alltypes = cell(nevents,1);
   for k=1:nevents
       if isnumeric(EEG.urevent(k).type)
          alltypes{k} = num2str(EEG.urevent(k).type);
       else
          alltypes{k} = EEG.urevent(k).type;
       end
   end
end

[types i j] = unique_bc(alltypes);

istypes = 1:length(types);
notistypes = [];
if ~isempty(typelist)
  notistypes = ismember_bc(typelist,types);
  istypes = ismember_bc(types,typelist(find(notistypes==1))); % types in typelist?
  notistypes = typelist(find(notistypes==0));
end

types(~istypes) = []; % restrict types to typelist

ntypes = length(types);
numbers = zeros(ntypes + length(notistypes),1);
for k=1:ntypes
  numbers(k) = length(find(j==k));
end
types = [types(:); notistypes(:)]; % concatenate the types not found
ntypes = length(types);
for j = 1:length(notistypes)
   numbers(k+j) = 0;
end

% sort types in reverse order of event numbers
[numbers nsort] = sort(numbers);
numbers = numbers(end:-1:1);
types = types(nsort(end:-1:1));

%
% print output on commandline %%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if nargout < 1
  fprintf('\n');
  if UREVENTS
    fprintf('EEG urevent types:\n\n')
  else
    fprintf('EEG event types:\n\n')
  end

  maxx = 0;
  for k=1:ntypes
    x = length(types{k});
    if x > maxx
        maxx = x; % find max type name length
    end
  end
  for k=1:ntypes
    fprintf('  %s',types{k});
    for j=length(types{k})+1:maxx+4
       fprintf(' ');
    end
    fprintf('%d\n',numbers(k));
 end
 fprintf('\n');
 clear types % no return variables
end


function params = init_default_params(params)

% Initialize default parameters

if ~isfield(params, 'interpolation_method')
    params.interpolation_method = 'none';
end
if ~isfield(params, 'interpolation_centering')
    params.interpolation_centering = false;
end
if ~isfield(params, 'interpolation_windowing')
    params.interpolation_windowing = false;
end
if ~isfield(params, 'clamp_position')
    params.clamp_position = false;
end
if ~isfield(params, 'update_projection_matrix')
    params.update_projection_matrix = true;
end
if ~isfield(params, 'proj_init_method')
    params.proj_init_method = 'pca';
end
if ~isfield(params, 'use_detection_sample')
    params.use_detection_sample = true;
end
if ~isfield(params, 'use_projection_matrix')
    params.use_projection_matrix = true;
end
if ~isfield(params, 'use_sample_merge')
    params.use_sample_merge = true;
end
if ~isfield(params, 'CG_use_FR')
    params.CG_use_FR = true;
end
if ~isfield(params, 'CG_standard_alpha')
    params.CG_standard_alpha = true;
end
if ~isfield(params, 'neglect_higher_frequency')
    params.neglect_higher_frequency = false;
end

if params.use_projection_matrix == false
    params.proj_init_method = 'none';
    params.update_projection_matrix = false;
end


classdef HBoxFlex < uix.HBox & uix.mixin.Flex
    %uix.HBoxFlex  Flexible horizontal box
    %
    %  b = uix.HBoxFlex(p1,v1,p2,v2,...) constructs a flexible horizontal
    %  box and sets parameter p1 to value v1, etc.
    %
    %  A horizontal box lays out contents from left to right.  Users can
    %  resize contents by dragging the dividers.
    %
    %  See also: uix.VBoxFlex, uix.GridFlex, uix.HBox, uix.HButtonBox

    %  Copyright 2009-2016 The MathWorks, Inc.
    %  $Revision: 1682 $ $Date: 2018-06-11 16:57:09 +0100 (Mon, 11 Jun 2018) $

    properties( Access = public, Dependent, AbortSet )
        DividerMarkings % divider markings [on|off]
    end

    properties( Access = private )
        ColumnDividers = uix.Divider.empty( [0 1] ) % column dividers
        FrontDivider % front divider
        DividerMarkings_ = 'on' % backing for DividerMarkings
        MousePressListener = event.listener.empty( [0 0] ) % mouse press listener
        MouseReleaseListener = event.listener.empty( [0 0] ) % mouse release listener
        MouseMotionListener = event.listener.empty( [0 0] ) % mouse motion listener
        ActiveDivider = 0 % active divider index
        ActiveDividerPosition = [NaN NaN NaN NaN] % active divider position
        MousePressLocation = [NaN NaN] % mouse press location
        BackgroundColorListener % background color listener
    end

    methods

        function obj = HBoxFlex( varargin )
            %uix.HBoxFlex  Flexible horizontal box constructor
            %
            %  b = uix.HBoxFlex() constructs a flexible horizontal box.
            %
            %  b = uix.HBoxFlex(p1,v1,p2,v2,...) sets parameter p1 to value
            %  v1, etc.

            % Create front divider
            frontDivider = uix.Divider( 'Parent', obj, ...
                'Orientation', 'vertical', ...
                'BackgroundColor', obj.BackgroundColor * 0.75, ...
                'Visible', 'off' );

            % Create listeners
            backgroundColorListener = event.proplistener( obj, ...
                findprop( obj, 'BackgroundColor' ), 'PostSet', ...
                @obj.onBackgroundColorChange );

            % Store properties
            obj.FrontDivider = frontDivider;
            obj.BackgroundColorListener = backgroundColorListener;

            % Set Spacing property (may be overwritten by uix.set)
            obj.Spacing = 5;

            % Set properties
            try
                uix.set( obj, varargin{:} )
            catch e
                delete( obj )
                e.throwAsCaller()
            end

        end % constructor

    end % structors

    methods

        function value = get.DividerMarkings( obj )

            value = obj.DividerMarkings_;

        end % get.DividerMarkings

        function set.DividerMarkings( obj, value )

            % Check
            assert( ischar( value ) && any( strcmp( value, {'on','off'} ) ), ...
                'uix:InvalidArgument', ...
                'Property ''DividerMarkings'' must be ''on'' or ''off'.' )

            % Set
            obj.DividerMarkings_ = value;

            % Mark as dirty
            obj.Dirty = true;

        end % set.DividerMarkings

    end % accessors

    methods( Access = protected )

        function onMousePress( obj, source, eventData )
            %onMousePress  Handler for WindowMousePress events

            % Check whether mouse is over a divider
            loc = find( obj.ColumnDividers.isMouseOver( eventData ) );
            if isempty( loc ), return, end

            % Capture state at button down
            divider = obj.ColumnDividers(loc);
            obj.ActiveDivider = loc;
            obj.ActiveDividerPosition = divider.Position;
            root = groot();
            obj.MousePressLocation = root.PointerLocation;

            % Make sure the pointer is appropriate
            obj.updateMousePointer( source, eventData );

            % Activate divider
            frontDivider = obj.FrontDivider;
            frontDivider.Position = divider.Position;
            divider.Visible = 'off';
            frontDivider.Parent = [];
            frontDivider.Parent = obj;
            frontDivider.Visible = 'on';

        end % onMousePress

        function onMouseRelease( obj, ~, ~ )
            %onMousePress  Handler for WindowMouseRelease events

            % Compute new positions
            loc = obj.ActiveDivider;
            if loc > 0
                root = groot();
                delta = root.PointerLocation(1) - obj.MousePressLocation(1);
                iw = loc;
                jw = loc + 1;
                ic = loc;
                jc = loc + 1;
                divider = obj.ColumnDividers(loc);
                contents = obj.Contents_;
                ip = uix.getPosition( contents(ic), 'pixels' );
                jp = uix.getPosition( contents(jc), 'pixels' );
                oldPixelWidths = [ip(3); jp(3)];
                minimumWidths = obj.MinimumWidths_(iw:jw,:);
                if delta < 0 % limit to minimum distance from left neighbor
                    delta = max( delta, minimumWidths(1) - oldPixelWidths(1) );
                else % limit to minimum distance from right neighbor
                    delta = min( delta, oldPixelWidths(2) - minimumWidths(2) );
                end
                oldWidths = obj.Widths_(iw:jw);
                newPixelWidths = oldPixelWidths + delta * [1;-1];
                if oldWidths(1) < 0 && oldWidths(2) < 0 % weight, weight
                    newWidths = oldWidths .* newPixelWidths ./ oldPixelWidths;
                elseif oldWidths(1) < 0 && oldWidths(2) >= 0 % weight, pixels
                    newWidths = [oldWidths(1) * newPixelWidths(1) / ...
                        oldPixelWidths(1); newPixelWidths(2)];
                elseif oldWidths(1) >= 0 && oldWidths(2) < 0 % pixels, weight
                    newWidths = [newPixelWidths(1); oldWidths(2) * ...
                        newPixelWidths(2) / oldPixelWidths(2)];
                else % sizes(1) >= 0 && sizes(2) >= 0 % pixels, pixels
                    newWidths = newPixelWidths;
                end
                obj.Widths_(iw:jw) = newWidths;
            else
                return
            end

            % Deactivate divider
            obj.FrontDivider.Visible = 'off';
            divider.Visible = 'on';

            % Reset state at button down
            obj.ActiveDivider = 0;
            obj.ActiveDividerPosition = [NaN NaN NaN NaN];
            obj.MousePressLocation = [NaN NaN];

            % Mark as dirty
            obj.Dirty = true;

        end % onMouseRelease

        function onMouseMotion( obj, source, eventData )
            %onMouseMotion  Handler for WindowMouseMotion events

            loc = obj.ActiveDivider;
            if loc == 0 % hovering, update pointer
                obj.updateMousePointer( source, eventData );
            else % dragging column divider
                root = groot();
                delta = root.PointerLocation(1) - obj.MousePressLocation(1);
                iw = loc;
                jw = loc + 1;
                ic = loc;
                jc = loc + 1;
                contents = obj.Contents_;
                ip = uix.getPosition( contents(ic), 'pixels' );
                jp = uix.getPosition( contents(jc), 'pixels' );
                oldPixelWidths = [ip(3); jp(3)];
                minimumWidths = obj.MinimumWidths_(iw:jw,:);
                if delta < 0 % limit to minimum distance from left neighbor
                    delta = max( delta, minimumWidths(1) - oldPixelWidths(1) );
                else % limit to minimum distance from right neighbor
                    delta = min( delta, oldPixelWidths(2) - minimumWidths(2) );
                end
                obj.FrontDivider.Position = ...
                    obj.ActiveDividerPosition + [delta 0 0 0];
            end

        end % onMouseMotion

        function onBackgroundColorChange( obj, ~, ~ )
            %onBackgroundColorChange  Handler for BackgroundColor changes

            backgroundColor = obj.BackgroundColor;
            highlightColor = min( [backgroundColor / 0.75; 1 1 1] );
            shadowColor = max( [backgroundColor * 0.75; 0 0 0] );
            columnDividers = obj.ColumnDividers;
            for jj = 1:numel( columnDividers )
                columnDivider = columnDividers(jj);
                columnDivider.BackgroundColor = backgroundColor;
                columnDivider.HighlightColor = highlightColor;
                columnDivider.ShadowColor = shadowColor;
            end
            frontDivider = obj.FrontDivider;
            frontDivider.BackgroundColor = shadowColor;

        end % onBackgroundColorChange

    end % event handlers

    methods( Access = protected )

        function redraw( obj )
            %redraw  Redraw contents
            %
            %  c.redraw() redraws the container c.

            % Call superclass method
            redraw@uix.HBox( obj )

            % Create or destroy column dividers
            b = numel( obj.ColumnDividers ); % current number of dividers
            c = max( [numel( obj.Widths_ )-1 0] ); % required number of dividers
            if b < c % create
                for ii = b+1:c
                    divider = uix.Divider( 'Parent', obj, ...
                        'Orientation', 'vertical', ...
                        'BackgroundColor', obj.BackgroundColor );
                    obj.ColumnDividers(ii,:) = divider;
                end
            elseif b > c % destroy
                % Destroy dividers
                delete( obj.ColumnDividers(c+1:b,:) )
                obj.ColumnDividers(c+1:b,:) = [];
                % Update pointer
                if c == 0 && strcmp( obj.Pointer, 'left' )
                    obj.unsetPointer()
                end
            end

            % Compute container bounds
            bounds = hgconvertunits( ancestor( obj, 'figure' ), ...
                [0 0 1 1], 'normalized', 'pixels', obj );

            % Retrieve size properties
            widths = obj.Widths_;
            minimumWidths = obj.MinimumWidths_;
            padding = obj.Padding_;
            spacing = obj.Spacing_;

            % Compute column divider positions
            xColumnSizes = uix.calcPixelSizes( bounds(3), widths, ...
                minimumWidths, padding, spacing );
            xColumnPositions = [cumsum( xColumnSizes(1:c,:) ) + padding + ...
                spacing * transpose( 0:c-1 ) + 1, repmat( spacing, [c 1] )];
            yColumnPositions = [padding + 1, max( bounds(4) - 2 * padding, 1 )];
            yColumnPositions = repmat( yColumnPositions, [c 1] );
            columnPositions = [xColumnPositions(:,1), yColumnPositions(:,1), ...
                xColumnPositions(:,2), yColumnPositions(:,2)];

            % Position column dividers
            for ii = 1:c
                columnDivider = obj.ColumnDividers(ii);
                columnDivider.Position = columnPositions(ii,:);
                switch obj.DividerMarkings_
                    case 'on'
                        columnDivider.Markings = columnPositions(ii,4)/2;
                    case 'off'
                        columnDivider.Markings = zeros( [0 1] );
                end
            end

        end % redraw

        function reparent( obj, oldFigure, newFigure )
            %reparent  Reparent container
            %
            %  c.reparent(a,b) reparents the container c from the figure a
            %  to the figure b.

            % Update listeners
            if isempty( newFigure )
                mousePressListener = event.listener.empty( [0 0] );
                mouseReleaseListener = event.listener.empty( [0 0] );
                mouseMotionListener = event.listener.empty( [0 0] );
            else
                mousePressListener = event.listener( newFigure, ...
                    'WindowMousePress', @obj.onMousePress );
                mouseReleaseListener = event.listener( newFigure, ...
                    'WindowMouseRelease', @obj.onMouseRelease );
                mouseMotionListener = event.listener( newFigure, ...
                    'WindowMouseMotion', @obj.onMouseMotion );
            end
            obj.MousePressListener = mousePressListener;
            obj.MouseReleaseListener = mouseReleaseListener;
            obj.MouseMotionListener = mouseMotionListener;

            % Call superclass method
            reparent@uix.HBox( obj, oldFigure, newFigure )

            % Update pointer
            if ~isempty( oldFigure ) && ~strcmp( obj.Pointer, 'unset' )
                obj.unsetPointer()
            end

        end % reparent

    end % template methods

    methods( Access = protected )

        function updateMousePointer ( obj, source, eventData  )

            oldPointer = obj.Pointer;
            if any( obj.ColumnDividers.isMouseOver( eventData ) )
                newPointer = 'left';
            else
                newPointer = 'unset';
            end
            switch newPointer
                case oldPointer % no change
                    % do nothing
                case 'unset' % change, unset
                    obj.unsetPointer()
                otherwise % change, set
                    obj.setPointer( source, newPointer )
            end

        end % updateMousePointer

    end % helpers methods

end % classdef


function planC = insertDCMStruct(planC,dcmFileName)
%
%Insert structures from dcm file into the currently open planC.
%
% 06/05/2015
%
% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.
%
% This file is part of The Computational Environment for Radiotherapy Research (CERR).
%
% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.
%
% CERR has been financially supported by the US National Institutes of Health under multiple grants.
%
% CERR is distributed under the terms of the Lesser GNU Public License.
%
%     This version of CERR is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
%
% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
% See the GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with CERR.  If not, see <http://www.gnu.org/licenses/>.
%
% AI 2/13/20 Updated to account for pt orientation

global stateS

if ~exist('planC','var')
    global planC
end
indexS = planC{end};

if ~exist('dcmFileName','var')
    [fileName, dirName] = uigetfile('*.dcm','Pick Structure file');
    dcmFileName = fullfile(dirName,fileName);
end

[dcmObj, isDcm] = scanfile_mldcm(dcmFileName);
dcmdirS = [];
if isDcm
    dcmdirS = dcmdir_add(dcmFileName, dcmObj, dcmdirS);
    dcmObj.clear;
else
    error('Invalid DICOM data')
end

% Read CERROptions.json
pathStr = getCERRPath;
optName = [pathStr 'CERROptions.json'];
optS = opts4Exe(optName);

scanOriS = planC{indexS.scan};
for scanNum = 1:length(scanOriS)
    imageOrientationPatient = scanOriS(scanNum).scanInfo(1).imageOrientationPatient;
    scanOriS(scanNum).imageOrientationPatient = imageOrientationPatient;
end

dataS = populate_planC_field('structures', dcmdirS.PATIENT, optS, scanOriS);

% Tolerance to determine oblique scan (think about passing it as a
% parameter in future)
numScans = length(planC{indexS.scan});
obliqTol = 1e-3;
isObliqScanV = zeros(1,numScans);

% Check scan to associate the strucutres
scanUIDc = {planC{indexS.scan}.scanUID};
scanTypesC = {};
for i = 1 : numScans
    scanTypesC{i} = [num2str(i) '.  ' planC{indexS.scan}(i).scanType];

    ImageOrientationPatientV = planC{indexS.scan}(i).scanInfo(1).imageOrientationPatient;

    % Check for obliqueness
    %     if ~isempty(ImageOrientationPatientV) && max(abs((abs(ImageOrientationPatientV) - [1 0 0 0 1 0]'))) <= obliqTol
    %         isObliqScanV(i) = 0;
    %     end
    if ~isempty(ImageOrientationPatientV)
        if max(abs((ImageOrientationPatientV(:) - [1 0 0 0 1 0]'))) < 1e-3
            isObliqScanV(i) = 0;
        elseif max(abs((ImageOrientationPatientV(:) - [-1 0 0 0 1 0]'))) < 1e-3
            isObliqScanV(i) = 0;
        elseif max(abs((ImageOrientationPatientV(:) - [-1 0 0 0 -1 0]'))) < 1e-3
            isObliqScanV(i) = 0;
        elseif max(abs((ImageOrientationPatientV(:) - [1 0 0 0 -1 0]'))) < 1e-3
            isObliqScanV(i) = 0;
        else
            isObliqScanV(i) = 1;
        end
    else
        if ~isempty(planC{indexS.scan}(i).scanInfo(1).imageOrientationPatient)
            ImageOrientationPatientV = planC{indexS.scan}(i).scanInfo(1).imageOrientationPatient;
        else
            ImageOrientationPatientV = [];
            isObliqScanV(i) = 1;
        end

    end

end

% Return if not a valid RTStruct file
if isempty(dataS)
    CERRStatusString('File not valid.')
    return
end

if ~ismember(dataS(1).assocScanUID,scanUIDc)
    if ~exist('dcmFileName','var')
        scanInd = listdlg('PromptString','Select Scan to associate structures',...
            'SelectionMode','single',...
            'ListString',scanTypesC);
    else
        scanInd = 1;
    end
    if ~isempty(scanInd)
        [dataS.assocScanUID] = deal(scanUIDc{scanInd});
    else
        return
    end
end
numStructs = length(planC{indexS.structures});

for i=1:length(dataS)
    dataS(i) = sortStructures(dataS(i),isObliqScanV,optS,planC);
    colorNum = numStructs + i;
    if isempty(dataS(i).structureColor)
        color = stateS.optS.colorOrder( mod(colorNum-1, size(stateS.optS.colorOrder,1))+1,:);
        dataS(i).structureColor = color;
    end
end
%Find any structures in dataS not already in planC.
toDeleteV = [];
for i=length(dataS):-1:1
    %     newStructName = temp_planC{temp_planC{end}.structures}(i).structureName;
    newStructData = dataS(i).contour;
    for j=1:length(planC{planC{end}.structures})
        oldStructName = planC{planC{end}.structures}(j).structureName;
        oldStructData = planC{planC{end}.structures}(j).contour;
        if isequal(newStructData, oldStructData)
            disp(['Structure "',oldStructName,'" already exists. Duplicate structure will not be inserted.']);
            toDeleteV = [toDeleteV, i];
            break;
        end
    end
end
dataS(toDeleteV) = [];
if ~isempty(planC{indexS.structures})
    for strNum = 1:length(dataS)
        planC{indexS.structures} = dissimilarInsert(planC{indexS.structures},dataS(strNum),length(planC{indexS.structures})+1);
    end
else
    planC{indexS.structures} = dataS;
end

editStructNumV = (numStructs+1):length(planC{indexS.structures});
planC = getRasterSegs(planC,editStructNumV);
%planC = setUniformizedData(planC);
for strNum = editStructNumV
    planC = updateStructureMatrices(planC, strNum);
end

if isfield(stateS, 'CERRFile')
    stateS.structsChanged = 1;
    CERRRefresh
end

CERRStatusString('Done inserting structures.')


% (this is just an interface)
function varargout = mydatesod_inv (varargin)
    [varargout{1:nargout}] = mydatesodi (varargin{:});
end

%!test
%! % just check whether it runs:
%! mydatesod_inv(1, 2);


function [Param, extra] = parsepv(Param, pvpairs, varargin)
%PARSEPV Parses parameter/value pairs
%
% NewParam = parsepv(Param, pvpairs)
% [NewParam, extra] = parsepv(Param, pvpairs, 'returnextra')
%
% This function is an extension of parse_pv_pairs.  It allows the option of
% returning unrecognized parameter/value pairs, rather than erroring.
%
% Input variables:
%
%   Param:          1 x 1 structure holding default parameters (fieldnames)
%                   and values
%
%   pvpairs:        1 x n cell array of parameter/value pairs
%
%   'returnextra':  if this string is included, the function will return a
%                   cell array holding any unrecognized parameters and the
%                   corresponding values.  Otherwise, it will error if a
%                   parameter is not recognized.
%
% Output variables:
%
%   NewParam:       1 x 1 struct identical to Param but with defaults
%                   replaced by the values from pvpairs
%
%   extra:          1 x m cell array of any unrecognized parameter/value
%                   pairs

% Copyright 2009 Kelly Kearney

if nargin == 3
    returnextra = strcmpi(varargin{1}, 'returnextra');
else
    returnextra = false;
end

npv = length(pvpairs);
n = npv/2;

if n~=floor(n)
  error 'Property/value pairs must come in PAIRS.'
end
if n<=0
  % just return the defaults
  if returnextra
      extra = cell(0);
  end
  return
end

if ~isstruct(Param)
    error 'No structure for defaults was supplied'
end

if returnextra
    extra = cell(0);
end

% there was at least one pv pair. process any supplied
propnames = fieldnames(Param);
lpropnames = lower(propnames);
for i=1:n
    p_i = lower(pvpairs{2*i-1});
    v_i = pvpairs{2*i};

    ind = strmatch(p_i,lpropnames,'exact');
    if isempty(ind)
        ind = find(strncmp(p_i,lpropnames,length(p_i)));
        if isempty(ind)
            if returnextra
                extra = [extra pvpairs(2*i-1:2*i)];
                continue;
            else
                error(['No matching property found for: ',pvpairs{2*i-1}]);
            end
        elseif length(ind)>1
            error(['Ambiguous property name: ',pvpairs{2*i-1}])
        end
    end
    p_i = propnames{ind};

    % override the corresponding default in params
    Param = setfield(Param,p_i,v_i);

end


function test_bug1450

% MEM 2gb
% WALLTIME 00:10:00
% DEPENDENCY mergestruct

% ft_checkconfig used to be responsible for mergestruct, but on 19-10-2015
% that moved to ft_preable_init which is called prior to ft_checkconfig

% this test script should be explicit about ft_default
global ft_default
ft_default = [];
ft_default.field1 = 1;
ft_default.field2 = 2;
ft_default.field3 = 3;
ft_default.sub.field1 = 1;
ft_default.sub.field2 = 2;
ft_default.sub.field3 = 3;
ft_default.sub.sub.field1 = 1;
ft_default.sub.sub.field2 = 2;
ft_default.sub.sub.field3 = 3;
ft_default.sub.sub.sub.field1 = 1;
ft_default.sub.sub.sub.field2 = 2;
ft_default.sub.sub.sub.field3 = 3;
ft_default.sub.sub.sub.sub(1).field1 = 1.1;
ft_default.sub.sub.sub.sub(2).field1 = 1.2;
ft_default.sub.sub.sub.sub(3).field1 = 1.3;

cfg = [];
cfg = mergestruct(cfg, ft_default);
assert(isequal(cfg, ft_default));

cfg = [];
cfg.field1 = 1;
cfg = mergestruct(cfg, ft_default);
% field1 should remain as it is, field 2 and 3 should have been added
assert(isequal(cfg, ft_default));

cfg = [];
cfg.sub = [];
cfg = mergestruct(cfg, ft_default);
% the subfields should have been added
assert(isequal(cfg, ft_default));

cfg = [];
cfg.sub.field1 = 1;
cfg = mergestruct(cfg, ft_default);
% the sub-fields 2 and 3 should have been added, sub-field 1 should remain as it is
assert(isequal(cfg, ft_default));

cfg = [];
cfg.sub.sub.field1 = 1;
cfg = mergestruct(cfg, ft_default);
% do the same test, but now two levels deep
assert(isequal(cfg, ft_default));

cfg = [];
cfg.sub.sub.sub.field1 = 1;
cfg = mergestruct(cfg, ft_default);
% do the same test, but now three levels deep
assert(isequal(cfg, ft_default));

cfg = [];
cfg.sub.sub.sub.sub.field2 = 2;
cfg = mergestruct(cfg, ft_default);
% should be concatenated
assert(numel(cfg.sub.sub.sub.sub)==4);


function ok = validate(qual)
% Checks that an object of type Seg_Quality obeys certain rules
% that must always be true.
% Inputs:
%   qual: the object to be checked.
% Outputs:
%   ok: a boolean value indicating whether the object is valid.

assert(nargin==1)
assert(isa(qual,'Seg_Quality'))

ok = iscell(qual.ids);
ok = ok && (size(qual.values,2)==length(qual.ids));


%% shiftV
% Below is a demonstration of the features of the |shiftV| function

%%
clear; close all; clc;

%% Syntax
% |[Vv]=shiftV(V,v);|

%% Description
% UNDOCUMENTED
%% Examples
%
%%
%
% <<gibbVerySmall.gif>>
%
% _*GIBBON*_
% <www.gibboncode.org>
%
% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>
%%
% _*GIBBON footer text*_
%
% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>
%
% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for
% image segmentation, image-based modeling, meshing, and finite element
% analysis.
%
% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.


function cleanInplane()
%
% function cleanInplane()
%
% Deletes:
%   Gray/coords.mat
%   Gray/dataType/corAnal.mat (for each dataType)
%   Gray/dataType/*.mat (all other parameter maps)
%
% If you change this function make parallel changes in:
%     cleanFlat, cleanDataType
%
% djh, 2/2001

global HOMEDIR
global dataTYPES

for typeNum = 1:length(dataTYPES)
    dataTypeName = dataTYPES(typeNum).name;
    % Delete corAnal and parameter map files
    datadir = fullfile(HOMEDIR,'Inplane',dataTypeName);
    delete(fullfile(datadir,'*.mat'));
    % Delete tSeries (if there are any)
    [nscans,scanDirList] = countDirs(fullfile(datadir,'TSeries','Scan*'));
    for s=1:nscans
        delete(fullfile(datadir,'TSeries',scanDirList{s},'*.mat'));
    end
end


function test_bug2170

% MEM 2gb
% WALLTIME 00:10:00
% DEPENDENCY ft_filetype ft_read_event

% the 3rd dataset is different in the sense that it is a *.fif file accompanied
% by an *.eve file. Those files are also used in the Tristan babysquid74 system.

filename1 = dccnpath('/home/common/matlab/fieldtrip/data/test/original/meg/neuromag306/raw.fif');
filename2 = dccnpath('/home/common/matlab/fieldtrip/data/test/original/meg/neuromag306/run_01_raw.fif');
filename3 = dccnpath('/home/common/matlab/fieldtrip/data/test/bug2170/an05a4_ss.fif');

assert(ft_filetype(filename1, 'neuromag_fif'));
assert(ft_filetype(filename2, 'neuromag_fif'));
assert(ft_filetype(filename3, 'neuromag_fif'));

event1 = ft_read_event(filename1);
event2 = ft_read_event(filename2);
event3 = ft_read_event(filename3);

% Note: on 7 June 2017 Robert made a change to ft_read_trigger, causing
% chantype='other trigger' also to be returned. In the 1st and 2nd dataset that
% corresponds to STI201 and STI301.

type = unique({event1.type});
for i=1:numel(type)
  figure
  tmp = event1(strcmp({event1.type}, type{i}));
  plot([tmp.sample], [tmp.value], '.')
  title(type{i})
end

assert(length(unique({event1.type}))==7+3+1); % 'STI001' 'STI002' 'STI003' 'STI004' 'STI009' 'STI010' 'STI011' 'STI101' 'STI201' 'STI301' and an additional 'Trigger'
assert(length(unique({event2.type}))==2);     % 'STI101' and 'STI201'
assert(length(unique({event3.type}))==2);     % 'STI101' and 'trigger'


function chrpak_test011 ( )

%*****************************************************************************80
%
%% TEST011 tests CH_CAP.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    10 June 2007
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST011\n' );
  fprintf ( 1, '  CH_CAP uppercases a character.\n' );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  C  CH_CAP(C)\n' );
  fprintf ( 1, '\n' );

  c = 'F';
  fprintf ( 1, '  %c      %c\n', c, ch_cap ( c ) );
  c = 'f';
  fprintf ( 1, '  %c      %c\n', c, ch_cap ( c ) );
  c = '1';
  fprintf ( 1, '  %c      %c\n', c, ch_cap ( c ) );
  c = 'b';
  fprintf ( 1, '  %c      %c\n', c, ch_cap ( c ) );
  c = '&';
  fprintf ( 1, '  %c      %c\n', c, ch_cap ( c ) );

  return
end