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

%  License:
%
%  Please contact the author at email: fguevara at math dot utah dot edu 
%  if you find this demo useful. Please also credit the author if you use this
%  demo in public. Portions of the code are automatically generated by Matlab
%  and as far as I understand are Copyright Mathworks, inc.
%  
%  Copyright (c) 2012, Fernando Guevara Vasquez 
%  All rights reserved.
%
%  Redistribution and use in source and binary forms, with or without
%  modification, are permitted provided that the following conditions are met:
%  
%   * Redistributions of source code must retain the above copyright notice,
%   this list of conditions and the following disclaimer.
%
%   * 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.
%


% Last Modified by GUIDE v2.5 27-Mar-2012 00:40:53

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @greendemo_OpeningFcn, ...
                   'gui_OutputFcn',  @greendemo_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 greendemo is made visible.
function greendemo_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 greendemo (see VARARGIN)

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



% wave regime
k0=1; la0=2*pi/k0; c0=1; k=k0;

% radius of surface
Rs = 2*la0;
% number of points on the surface
Ns = 2^6; theta=(0:Ns-1)'*2*pi/Ns;
ps = Rs*[cos(theta),sin(theta)];

% mask to remember the actual sources that are turned on
theta_mask = zeros(size(theta));

% incident field direction
ti = pi/3;

% incident field
ui = @(r,t) exp(1i*k*r.*cos(t-ti));
% single and double layer potentials on circle of radius Rs
sld = 1i*k*cos(theta-ti).*ui(Rs,theta);
dld = ui(Rs,theta);

% discretize visualization region
Nx = 128; Ny=Nx;
xmax = 3*la0; ymax=xmax; 
x0 = 0*la0; y0 = 0*la0;
x = linspace(x0-xmax,x0+xmax,Nx); y = linspace(y0-ymax,y0+ymax,Ny);
[X,Y] = meshgrid(x,y);
RR = sqrt(X.^2 + Y.^2);
TT = atan2(Y,X);
idx = find((0.98*Rs < RR) & (RR < 1.02*Rs));

% precalculate sources
for i=1:Ns,
 % distance to source:
 R=sqrt((X-ps(i,1)).^2 + (Y-ps(i,2)).^2);
 % evaluate single layer potential
 SL=sld(i)*(1i/4)*besselh(0,k*R);
 % evaluate double layer potential
 DL=dld(i)*k*(1i/4)*besselh(1,k*R)...
  .*( ps(i,1)*(X-ps(i,1)) + ps(i,2)*(Y-ps(i,2)) )./(Rs * R);
 SL = SL*(2*pi*Rs)/Ns;
 DL = DL*(2*pi*Rs)/Ns;
 src{i}=real(SL-DL);
end;

% initialize canvas
SL=zeros(size(X)); DL=zeros(size(X));
SL(idx)=2; DL(idx)=0;
axis(handles.axes1);
imagesc(x/la0,y/la0,real(SL-DL));  axis xy;
caxis([-1 1]);colormap(jet(65));


% save stuff for later
handles.draw_mode=@or;
handles.pressed=0;
handles.la0=la0; handles.k0=k0; handles.c0=c0;
handles.ps=ps; handles.Rs=Rs;
handles.ui=ui; handles.sld=sld; handles.dld=dld;
handles.Nx=Nx; handles.Ny=Ny; handles.Ns=Ns;
handles.xmax=xmax; handles.ymax=ymax;
handles.x=x; handles.y=y;
handes.RR=RR; handles.TT=TT;
handles.X=X; handles.Y=Y;
handles.idx=idx;
handles.theta_mask=theta_mask;
handles.src=src;

% Update handles structure
guidata(hObject, handles);




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


% --- Outputs from this function are returned to the command line.
function varargout = greendemo_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;


% --- Executes on mouse press over axes background.
function axes1_ButtonDownFcn(hObject, eventdata, handles)
% hObject    handle to axes1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


function redraw(handles)
la0=handles.la0; ps=handles.ps; idx=handles.idx;
field = zeros(size(handles.X));
for i=find(handles.theta_mask)',
    field = field+handles.src{i};
end;
field(idx)=2;

axis(handles.axes1);
%imagesc(handles.x/la0,handles.y/la0,real(SL-DL));
imagesc(handles.x/la0,handles.y/la0,field);
axis xy;
caxis([-1 1]);colormap(jet(65));
hold on;
for i=find(handles.theta_mask)',
     plot(ps(i,1)/la0,ps(i,2)/la0,'ko','MarkerSize',10,'markerfacecolor','k');
end;
hold off;


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

% Hint: place code in OpeningFcn to populate axes1


% --- Executes on key press with focus on figure1 or any of its controls.
function figure1_WindowKeyPressFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (see GCBO)
% eventdata  structure with the following fields (see FIGURE)
%	Key: name of the key that was pressed, in lower case
%	Character: character interpretation of the key(s) that was pressed
%	Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles    structure with handles and user data (see GUIDATA)


% --- Executes on mouse press over figure background, over a disabled or
% --- inactive control, or over an axes background.
function figure1_WindowButtonDownFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.pressed=1;
pt = get(handles.axes1,'CurrentPoint');

% translate coordinates into an angle
alpha = atan2(pt(3),pt(1));
% find closest angle to alpha in theta array
i=mod(round(alpha*handles.Ns/(2*pi)),handles.Ns)+1;
handles.theta_mask(i) = handles.draw_mode(handles.theta_mask(i),1);
guidata(hObject,handles);
redraw(handles)


% --- Executes on mouse press over figure background, over a disabled or
% --- inactive control, or over an axes background.
function figure1_WindowButtonUpFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.pressed=0;
guidata(hObject,handles);


% --- Executes on mouse motion over figure - except title and menu.
function figure1_WindowButtonMotionFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
if (handles.pressed)
    pt = get(handles.axes1,'CurrentPoint');

    % translate coordinates into an angle
    alpha = atan2(pt(3),pt(1));
    % find closest angle to alpha in theta array
    i=mod(round(alpha*handles.Ns/(2*pi)),handles.Ns)+1;
    handles.theta_mask(i) = handles.draw_mode(handles.theta_mask(i),1);
    guidata(hObject,handles);
    redraw(handles)
end;


% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.theta_mask(:)=0;
guidata(hObject,handles);
redraw(handles)

% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.theta_mask = ~handles.theta_mask;
guidata(hObject,handles);
redraw(handles);


% --- Executes on selection change in popupmenu1.
function popupmenu1_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns popupmenu1 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenu1
 % Determine the selected data set.
str = get(hObject, 'String');
val = get(hObject,'Value');
% Set current data to the selected data set.
switch str{val};
case 'or' % User selects or.
 handles.draw_mode = @or;
case 'xor' % User selects xor.
 handles.draw_mode = @xor;
end
guidata(hObject,handles);

% --- Executes during object creation, after setting all properties.
function popupmenu1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenu1 (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
