function [] = MemristorToolbox()
% MemristorToolbox Help File.
% This Memristor Toolbox GUI is an accessible and interactive graphical
% tutorial about memristors within the MATLAB and Simulink environment.
%
% To navigate around the Toolbox, simply use press the different push buttons. 
%
% The most effective way to navigate is to use the Next & Previous buttons in the lower right corner of the GUI. 
% These buttons will bring you through the entirety of the Toolbox.
%
%
%
%
% Copyright (c) 2013, Raymond Carley & Adrian Walsh
% University College Dublin, Ireland


% Check to see if the Toolbox is already open
hf = findall(0,'Tag',mfilename);
if isempty(hf) % Toolbox is not open
    % Build the Toolbox
    hf = createUI();
else % Toolbox is already open
    % Bring it to the front
    figure(hf);
end

end

function S = createUI()
% The Toolbox is not already open, so build it.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%  Initialization tasks
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Clear the Command Window
clc
clear all

% Font Sizes
tg_font = 16;
section_font = 12;
footnote_font = 10;
panel_font = 14;

% Colour Selection
sky_blue = [0.529 0.807 0.921];         
light_sky_blue = [0.529 0.807 0.98];    

blue3 = [0.0078 0.5765 0.8784];
blue3a= [0.5137 0.8274 0.9961];
blue3b= [0 0.302 0.4941];

% Colour Variables
% % blue3 & blue3b are the main two colours
% bg_colour = light_sky_blue;
% panel_colour = 'white';
bg_colour    = blue3;
panel_colour = blue3b;
text_colour  ='w';
panel_text_colour ='w';
%  For Panels with Axes
panel_axis_colour      =blue3b;    %blue3b
panel_axis_text_colour ='w';       %'w'
axis_colour            ='w';       %'w'
S.axis_colour          ='w';       %'w'
axis_bg_colour         =blue3;     %blue3
S.axis_bg_colour       =blue3;     %blue3
data.linecolour        ='w';       %'w'
% pb_nav_colour= blue3a;



% To keep track of where the user is in the GUI
data.section = 0;
data.subsection = 0;
data.subsubsection = 0;


% change path to be in the MemristorGUI directory
p = mfilename('fullpath');
if(ispc)
    idp = max(strfind(p,'\'));
elseif(isunix)
    idp = max(strfind(p,'/'));
end
S.home_path = p(1:idp);
cd(S.home_path);


% Path of Simulink files
S.simulink = strcat(S.home_path,'simulink');
addpath(genpath(strcat(S.home_path,'simulink')));

%Simulink Model Names
S.model.IV         ='measure_iv_resistance';
S.model.Neuro      ='Associative_Memory';
S.model.Memory     ='Memristor_Memory_Cell';
S.model.Inverter   ='Inverting_Amplifier_Biolek_Feedback';
S.model.Noninverter='Non_Inverting_Amplifier_Biolek_Feedback';
S.model.Chaos      ='Memristor_Based_Chua_Chaotic_Oscillator';
S.model.Phase      ='Phaseshift_Oscillator_BCM';
S.model.Rect       ='BCM_Rectifier';
S.model.STBCM      ='Square_to_Sawtooth_BCM';
S.model.STnovel    ='Square_to_Sawtooth_Novel';


% % Reset the memory files
% load('memory.mat')
% installed = 0;
% nosplash = 0;
% save('memory.mat','installed','nosplash')


% Build the Models
load('memory.mat') % load the memory file

% check to see if the model has been installed already
if(installed==0) %#ok<*NODEF>
    installed=1; %#ok<*NASGU>
    save('memory.mat','installed','nosplash')
    
    cd(S.simulink);
    ssc_build Memristor
    cd(S.home_path);
end

% Copyright Message
%Copyright (c) 2013, Raymond Carley & Adrian Walsh
S.copyright = 'Copyright (c) 2013 , Raymond Carley & Adrian Walsh';


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%  Construct the components
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Main Figure
S.SCR = get(0,'Screensize');  % Get screensize.
S.fh = figure(  'Tag',mfilename,...
                'numbertitle','off',...
                'menubar','none',...
                'units','pixels',...
                'position',[S.SCR(3)/2-450 ,S.SCR(4)/2-350 , 900, 700],...
                'name','Memristor Toolbox',...
                'color',bg_colour,...
                'visible','off',...
                'resize','off');

% HOME & Section Toggles              
S.hometg = uicontrol(   'style','pushbutton',...
                        'units','pixels',...
                        'position',[5 655 75 40],...
                        'string','Home',...
                        'fontsize',tg_font);
S.sectiontg = uicontrol('style','pushbutton',...
                        'units','pixels',...
                        'position',[110 655 75 40],...
                        'string','Intro',...
                        'fontsize',tg_font,...
                        'visible','off');
                
% Arrows between the toggles            
S.arrow(1) = uicontrol( 'style','text',...
                        'units','pixels',...
                        'position',[85 665 20 20],...
                        'visible','off',...
                        'string','>',...
                        'fontsize',16,'fontweight','normal',...
                        'backgroundcolor', bg_colour);
 
S.arrow(2) = uicontrol( 'style','text',...
                        'units','pixels',...
                        'position',[190 665 20 20],...
                        'visible','off',...
                        'string','>',...
                        'fontsize',16,'fontweight','normal',...
                        'backgroundcolor', bg_colour);
% Main Title Text           
S.title = uicontrol('style','text',...
                    'units','pixels',...
                    'position',[210 654 480 39],...
                    'visible','on',...
                    'string',{'Memristor Toolbox'},...
                    'fontsize',24,...
                    'backgroundcolor', bg_colour,...
                    'ForegroundColor', text_colour,...
                    'HorizontalAlignment','center');

% Navigation Menu - Popup          
S.popup = uicontrol('style','popupmenu',...
                    'units','pixels',...
                    'position',[700 655 200 30],...
                    'visible','on',...
                    'string',{'Jump to Section:',...
                    'Home',...
                    '1. Intro',...
                    '1. Intro > What is a Memristor?',...
                    '1. Intro > Fundamental Variables',...
                    '1. Intro > Charge-Flux Relationship',...
                    '1. Intro > Memristor Equations',...
                    '1. Intro > Pinched Hysteresis Loops',...
                    '1. Intro > Memristor Timeline',...
                    '1. Intro > HP Memristor 1',...
                    '1. Intro > HP Memristor 2',...
                    '1. Intro > Interactive Plot',...
                    '1. Intro > Input Your Own Equation',...
                    '2. Terminology',...
                    '2. Terminology > Terms',...
                    '2. Terminology > Bibliography',...
                    '3. Applications',...
                    '3. Applications > Intro to Applications',...
                    '3. Applications > Intro to Simulink',...
                    '3. Applications > Simulink Plotting',...
                    '3. Applications > Memory Circuits',...
                    '3. Applications > Neuromorphic Engineering',...
                    '3. Applications > Programmable Circuits',...
                    '3. Applications > PC - Op-Amps',...
                    '3. Applications > PC - Oscillators',...
                    '3. Applications > PC - Rectifiers & Converters',...
                    '4. Build Your Own Circuit',...
                    '4. Build Your Own Circuit > Build Circuit',...
                    '4. Build Your Own Circuit > Build Model'},...
                    'fontsize',12,...
                    'backgroundcolor', 'white');
  
                
% Forward & Back Buttons
S.next = uicontrol( 'style','pushbutton',...
                    'units','pixels',...
                    'position',[785 5 110 40],...
                    'string','Next',...
                    'fontsize',section_font-2);
S.previous = uicontrol( 'style','pushbutton',...
                        'units','pixels',...
                        'position',[670 5 110 40],...
                        'string','Previous',...
                        'fontsize',section_font-2);
           
% Main Text           
S.text(1) = uicontrol(  'style','text',...
                        'units','pixels',...
                        'position',[180 560 540 35],...
                        'visible','on',...
                        'string',{'To Start - Please Choose a Section:'},...
                        'fontsize',24,...
                        'backgroundcolor', bg_colour,...
                        'ForegroundColor', text_colour,...
                        'horizontalalignment','center');

% Middle Text           
S.text(2) = uicontrol(  'style','text',...
                        'units','pixels',...
                        'position',[20 535 860 50],...
                        'visible','off',...
                        'string',{'Lower Text'},...
                        'fontsize',14,...
                        'backgroundcolor', bg_colour,...
                        'ForegroundColor', text_colour,...
                        'horizontalalignment','center');
                    
% Footnote Text
S.foot = uicontrol( 'style','text',...
                    'units','pixels',...
                    'position',[20 5 645 35],...
                    'visible','on',...
                    'string',S.copyright,...
                    'fontsize',footnote_font,...
                    'backgroundcolor', bg_colour,...
                    'ForegroundColor', text_colour,...
                    'horizontalalignment','left'); 
                                        
% Memristor Symbols at top right and left
S.img.mem = imread('images/Memristor Symbol/memb3a.png');
S.ax(1) = axes( 'units','pixels',...
                'position',[43 600 110 40]);
imshow(S.img.mem,'Parent',S.ax(1),'Border','loose');      

S.ax(2) = axes( 'units','pixels',...
                'position',[747 600 110 40]);
imshow(S.img.mem,'Parent',S.ax(2),'Border','loose');

% Create a Help pull-down menu
S.menu = uimenu('Parent',S.fh,...
                'Label','Help');
labels = {'Application Help','About'};
callbacks = {{@menu_help,S},{@menu_about,S}};
for idx = 1:length(labels)
    uimenu( 'Parent',S.menu,...
            'Label',labels{idx},...
            'Callback',callbacks{idx});
end             
                    
% Home Screen - Boxes to choose all sections visible
S.home = uipanel(   S.fh,'units','pixels',...
                    'position',[70 70 760 450],...
                    'backgroundcolor', panel_colour,...
                    'Foregroundcolor', panel_text_colour,...
                    'Title', 'Navigation Selection');
                    
    % Home Push Buttons to control section selection                
    W = {S.home,'style','pushbutton',...
                    'units','normalized',...
                    'fontsize',tg_font,...
                    'position'};  % Save some typing.               
    S.homepb.pb(1) = uicontrol(W{:},[0.05 0.55 0.40 0.40],'string','1. Introduction & Tutuorial');               
    S.homepb.pb(2) = uicontrol(W{:},[0.55 0.55 0.40 0.40],'string','2. Terminology & Bibliography');
    S.homepb.pb(3) = uicontrol(W{:},[0.05 0.05 0.40 0.40],'string','3. Sample Applications');
    S.homepb.pb(4) = uicontrol(W{:},[0.55 0.05 0.40 0.40],'string','4. Build Your Own Circuit');
    
            
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Sections
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 1.Introduction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Intro Section - Boxes to choose all subsections
S.intro.home.panel = uipanel(  S.fh,'units','pixels',...
                    'position',[70 70 760 450],...
                    'backgroundcolor', panel_colour,...
                    'Foregroundcolor', panel_text_colour,...
                    'Title', 'Intro',...
                    'visible','off');
    % Intro Push Buttons to control subsection selection
    W = {S.intro.home.panel,'style','pushbutton',...
                    'units','normalized',...
                    'fontsize',section_font,...
                    'position'};  % Save some typing.               
    S.intro.home.pb(1) = uicontrol(W{:},[0.05 0.71 0.26 0.24],'string','What is a Memristor?');               
    S.intro.home.pb(2) = uicontrol(W{:},[0.37 0.71 0.26 0.24],'string','Fundamental Variables');
    S.intro.home.pb(3) = uicontrol(W{:},[0.69 0.71 0.26 0.24],'string','Charge-Flux Relationship');
    S.intro.home.pb(4) = uicontrol(W{:},[0.05 0.38 0.26 0.24],'string','Memristor Equations');
    S.intro.home.pb(5) = uicontrol(W{:},[0.37 0.38 0.26 0.24],'string','Pinched Hysteresis Loops');
    S.intro.home.pb(6) = uicontrol(W{:},[0.69 0.38 0.26 0.24],'string','Memristor Timeline');
    S.intro.home.pb(7) = uicontrol(W{:},[0.05 0.19 0.26 0.10],'string','HP Memristor 1');
    S.intro.home.pb(8) = uicontrol(W{:},[0.05 0.05 0.26 0.10],'string','HP Memristor 2');
    S.intro.home.pb(9) = uicontrol(W{:},[0.37 0.05 0.26 0.24],'string','Interactive Plot');          
    S.intro.home.pb(10) = uicontrol(W{:},[0.69 0.05 0.26 0.24],'string','Input Your Own Equation');                

% IMAGES For Intro Section                
W = {'units','pixels',...
     'position',[5 50 890 505]};  % Save some typing. 
S.ax(5) = axes(W{:}); % What is a Memristor?
S.imgintro(1) = imshow('images/intro_what.png',    'Parent',S.ax(5));
S.ax(6) = axes(W{:}); % Fundamental Variables
S.imgintro(2) = imshow('images/intro_variable.png','Parent',S.ax(6));
S.ax(7) = axes(W{:}); % Q Phi Defining Functions
S.imgintro(3) = imshow('images/intro_qphi.jpg',    'Parent',S.ax(7));
S.ax(8) = axes(W{:}); % General Defining Functions
S.imgintro(4) = imshow('images/intro_geneqn.jpg',  'Parent',S.ax(8));
S.ax(9) = axes(W{:}); % Pinched Hysteresis Loops
S.imgintro(5) = imshow('images/intro_pinched.png', 'Parent',S.ax(9)); 
S.ax(10) = axes(W{:}); % Memristor Timeline
S.imgintro(6) = imshow('images/intro_timeline.png','Parent',S.ax(10));      
S.ax(11) = axes(W{:}); % HP Memristor
S.imgintro(7) = imshow('images/intro_HP1.png',      'Parent',S.ax(11));  
S.ax(12) = axes(W{:}); % HP Memristor
S.imgintro(8) = imshow('images/intro_HP2.png',      'Parent',S.ax(12));

%%%%%%%%%%%%%%%%%%%%%
% Hysteresis Plot
%%%%%%%%%%%%%%%%%%%%%
S.intro.plot.panel = uipanel(  S.fh,'units','pixels',...
                                'position',[70 70 760 450],...
                                'backgroundcolor', panel_axis_colour,...
                                'Foregroundcolor', panel_axis_text_colour,...
                                'Title', 'User Input',...
                                'visible','off');

%Dropdown Choice Menu
% Navigation Menu - Popup          
S.intro.plot.popup(1) = uicontrol('parent', S.intro.plot.panel,...
                    'style','popupmenu',...
                    'units','normalized',...
                    'position',[0.30 0.86 0.175 0.075],...
                    'visible','on',...
                    'string',{'Ideal Memristor',...
                    'HP Memristor'},...
                    'fontsize',12,...
                    'backgroundcolor', 'white');
S.intro.plot.popup(2) = uicontrol('parent', S.intro.plot.panel,...
                    'style','popupmenu',...
                    'units','normalized',...
                    'position',[0.30 0.71 0.175 0.075],...
                    'visible','on',...
                    'string',{'Sine Wave',...
                    'Square Wave',...
                    'Triangle Wave',...
                    'Staircase',...
                    'DC Source'},...
                    'fontsize',12,...
                    'backgroundcolor', 'white');
                            
%Input Fields
W = {'parent', S.intro.plot.panel,...
                    'style','edit',...
                    'units','normalized',...
                    'position',[0.05 0.45 0.40 0.10],...
                    'fontsize',section_font,...
                    'position'}; % Save some typing.
    S.intro.plot.ip(1) = uicontrol(W{:},[0.30 0.39 0.15 0.10],'string',{'1'}); %Amp
    S.intro.plot.ip(2) = uicontrol(W{:},[0.30 0.26 0.15 0.10],'string',{'1'}); %Freq
% Text
W = {'parent', S.intro.plot.panel,...
                    'style','text',...
                    'units','normalized',...
                    'visible','on',...
                    'fontsize',panel_font,...
                    'backgroundcolor', panel_axis_colour,...
                    'ForegroundColor', panel_axis_text_colour,...
                    'horizontalalignment','left',...
                    'position'}; % Save some typing.
    S.intro.plot.text(1) = uicontrol(W{:},[0.050 0.39 0.25 0.07],'string',{'Input Amplitude:'});
    S.intro.plot.text(2) = uicontrol(W{:},[0.045 0.27 0.25 0.07],'string',{'Input Frequency (Hz):'});
    S.intro.plot.text(3) = uicontrol(W{:},[0.045 0.83 0.22 0.115],'string',{'Choose Memristor Type:'});
    S.intro.plot.text(4) = uicontrol(W{:},[0.045 0.71 0.25 0.07],'string',{'Choose Input Type:'});

%Push Button
W = {S.intro.plot.panel,'style','pushbutton',...
                'units','normalized',...
                'fontsize',section_font,...
                'position'};  % Save some typing.               
    S.intro.plot.pb(1) = uicontrol(W{:},[0.18 0.05 0.13 0.11],'string','Plot');               
   
    % Axis
    S.ax(15) = axes( 'Parent', S.intro.plot.panel,...
                    'units','normalized',...
                    'position',[0.58 0.13 0.36 0.74],...
                    'XColor',axis_colour,'YColor',axis_colour,...
                    'Color',axis_bg_colour);
    grid  (S.ax(15),'on');
    xlabel(S.ax(15),'Voltage (V)','FontSize',15,'Color',S.axis_colour);
    ylabel(S.ax(15),'Current (A)','FontSize',15,'Color',S.axis_colour);
    title (S.ax(15),'Current Vs. Voltage','FontSize',15,'Color',S.axis_colour);
    grid  (S.ax(15),'on');
    set   (S.ax(15),   'FontSize',15,...
                    'XColor',S.axis_colour,'YColor',S.axis_colour,...
                    'Color',S.axis_bg_colour);
    axis  (S.ax(15),[-5 5 -2.5 2.5])
    
    
    
%%%%%%%%%%%%%%%%%%%%%
% User Input
%%%%%%%%%%%%%%%%%%%%%
S.intro.user.panel = uipanel(  S.fh,'units','pixels',...
                                'position',[70 70 760 450],...
                                'backgroundcolor', panel_axis_colour,...
                                'Foregroundcolor', panel_axis_text_colour,...
                                'Title', 'User Input',...
                                'visible','off');

%Input Fields
W = {'parent', S.intro.user.panel,...
                    'style','edit',...
                    'units','normalized',...
                    'position',[0.05 0.45 0.40 0.10],...
                    'fontsize',section_font,...
                    'position'}; % Save some typing.
    S.intro.user.ip(1) = uicontrol(W{:},[0.05 0.45 0.40 0.10],'string',{'ip'});
    S.intro.user.ip(2) = uicontrol(W{:},[0.05 0.20 0.40 0.10],'string',{'x'});
    S.intro.user.ip(3) = uicontrol(W{:},[0.30 0.87 0.15 0.10],'string',{'1'});
    S.intro.user.ip(4) = uicontrol(W{:},[0.30 0.74 0.15 0.10],'string',{'1'});
% Text
W = {'parent', S.intro.user.panel,...
                    'style','text',...
                    'units','normalized',...
                    'visible','on',...
                    'fontsize',panel_font,...
                    'backgroundcolor', panel_axis_colour,...
                    'ForegroundColor', panel_axis_text_colour,...
                    'horizontalalignment','left',...
                    'position'}; % Save some typing.
    S.intro.user.text(1) = uicontrol(W{:},[0.050 0.87 0.25 0.07],'string',{'Input Amplitude:'});
    S.intro.user.text(2) = uicontrol(W{:},[0.045 0.75 0.25 0.07],'string',{'Input Frequency (Hz):'});
    S.intro.user.text(3) = uicontrol(W{:},[0.015 0.565 0.40 0.1],'string',{'Enter the Memristor State Equation' '(dx/dt = ip):'});
    S.intro.user.text(4) = uicontrol(W{:},[0.015 0.32 0.40 0.11],'string',{'Enter the Memristance R(x), from the output equation y = R(x)ip:'});
          
%Push Button
W = {S.intro.user.panel,'style','pushbutton',...
                'units','normalized',...
                'fontsize',section_font,...
                'position'};  % Save some typing.               
    S.intro.user.pb(1) = uicontrol(W{:},[0.18 0.05 0.13 0.11],'string','Plot');               
% Axis
S.ax(16) = axes( 'Parent', S.intro.user.panel,...
                'units','normalized',...
                'position',[0.55 0.15 0.40 0.75],...
                'XColor',axis_colour,'YColor',axis_colour,...
                'Color',axis_bg_colour);
    xlabel(S.ax(16),'Voltage (V)','FontSize',15,'Color',S.axis_colour);
    ylabel(S.ax(16),'Current (A)','FontSize',15,'Color',S.axis_colour);
    title (S.ax(16),'Current Vs. Voltage','FontSize',15,'Color',S.axis_colour);
    grid  (S.ax(16),'on');
    set(S.ax(16),   'FontSize',15,...
                    'XColor',S.axis_colour,'YColor',S.axis_colour,...
                    'Color',S.axis_bg_colour);
    axis  (S.ax(16),[-5 5 -2.5 2.5])            
                
                
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 2.Termminology
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Terminology Panel
S.terms.panel = uipanel(  S.fh,'units','pixels',...
                    'position',[70 70 760 450],...
                    'backgroundcolor', panel_colour,...
                    'Foregroundcolor', panel_text_colour,...
                    'Title', 'Terms',...
                    'visible','off');

% Intro Push Buttons to control subsection selection
W = {S.terms.panel, 'style','pushbutton',...
                    'units','normalized',...
                    'fontsize',tg_font,...
                    'position'};  % Save some typing.               
    S.terms.pb(1) = uicontrol(W{:},[0.05 0.55 0.40 0.40],'string','Terminology');               
    S.terms.pb(2) = uicontrol(W{:},[0.55 0.55 0.40 0.40],'string','Bibliography');
                
% IMAGES For Terms Section                
W = {'units','pixels',...
     'position',[5 50 890 505]};  % Save some typing.                   
% Terminology Content
S.ax(20) = axes(W{:});
S.imgterms(1) = imshow('images/terms.png','Parent',S.ax(20));
% Bibliography Content
S.ax(21) = axes(W{:});
S.imgterms(2) = imshow('images/bib.jpg','Parent',S.ax(21));

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 3.Applications
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Applications Section - Boxes to choose all subsections
S.apps.home.panel = uipanel(  S.fh,'units','pixels',...
                    'position',[70 70 760 450],...
                    'backgroundcolor', panel_colour,...
                    'Foregroundcolor', panel_text_colour,...
                    'Title', 'Apps',...
                    'visible','off');  

% Push Buttons to control section selection
W = {S.apps.home.panel,'style','pushbutton',...
                'units','normalized',...
                'fontsize',section_font,...
                'position'};  % Save some typing.               
    S.apps.home.pb(1) = uicontrol(W{:},[0.05 0.71 0.26 0.24],'string','Intro to Applications');
    S.apps.home.pb(2) = uicontrol(W{:},[0.37 0.71 0.26 0.24],'string','Intro to Simulink');
    S.apps.home.pb(3) = uicontrol(W{:},[0.69 0.71 0.26 0.24],'string','Simulink Plotting');
    S.apps.home.pb(4) = uicontrol(W{:},[0.05 0.38 0.26 0.24],'string','Memory Circuits');
    S.apps.home.pb(5) = uicontrol(W{:},[0.37 0.38 0.26 0.24],'string','Neuromorphic Engineering');
    S.apps.home.pb(6) = uicontrol(W{:},[0.69 0.38 0.26 0.24],'string','<html>Programmable Circuits<br>(PC)');
    S.apps.home.pb(7) = uicontrol(W{:},[0.05 0.05 0.26 0.24],'string','PC - Op-Amps');
    S.apps.home.pb(8) = uicontrol(W{:},[0.37 0.05 0.26 0.24],'string','PC - Oscillators');
    S.apps.home.pb(9) = uicontrol(W{:},[0.69 0.05 0.26 0.24],'string','<html>PC - Rectifiers <br>& Converters');


W = {'units','pixels',...
     'position',[5 50 890 505]};  % Save some typing.     
% Applications Introduction
S.ax(30) = axes(W{:});
S.imgapps(1) = imshow('images/apps_intro.png','Parent',S.ax(30));
% Simulink Introduction
S.ax(31) = axes(W{:});
S.imgapps(2) = imshow('images/apps_simulink_intro.png','Parent',S.ax(31));


%%%%%%%%%%%%%%%%%%%%%
% I-V Curve --> Simulink Plotting
%%%%%%%%%%%%%%%%%%%%%    
S.apps.iv.panel = uipanel(  S.fh,'units','pixels',...
                                'position',[5 70 890 450],...
                                'backgroundcolor', panel_axis_colour,...
                                'Foregroundcolor', panel_axis_text_colour,...
                                'Title', 'I-V Curve',...
                                'visible','off');                    

% Start & Stop Buttons
W = {S.apps.iv.panel,'style','pushbutton',...
                    'units','normalized',...
                    'fontsize',section_font,...
                    'position'};  % Save some typing.               
    S.apps.all.pb(1) = uicontrol(W{:},[0.08 0.87 0.15 0.1],'string','Start');
    S.apps.all.pb(2) = uicontrol(W{:},[0.30 0.87 0.15 0.1],'string','Stop', 'Enable','off');
    S.apps.all.pb(3) = uicontrol(W{:},[0.19 0.72 0.15 0.1],'string','Open Circuit');
            
% Axis
S.ax(18) = axes( 'Parent', S.apps.iv.panel,...
                'units','normalized',...
                'XColor',axis_colour,'YColor',axis_colour,...
                'Color',axis_bg_colour,'FontSize',20,...
                'Box','on',...
                'position',[0.08 0.14 0.37 0.47]);
    xlabel(S.ax(18),'Voltage','FontSize',20);
    ylabel(S.ax(18),'Current','FontSize',20);
    title (S.ax(18),'Current Vs. Voltage','Color',axis_colour,'FontSize',20);
    grid  (S.ax(18),'on');
    axis  (S.ax(18),[-1 1 -33 33])

    
    
S.ax(19) = axes( 'Parent', S.apps.iv.panel,...
                'units','normalized',...
                'XColor',axis_colour,'YColor',axis_colour,...
                'Color',axis_bg_colour,'FontSize',20,...
                'Box','on',...
                'position',[0.58 0.14 0.37 0.47]);
%                     'position',[0.58 0.1 0.37 0.70]);
    xlabel(S.ax(19),'Time','FontSize',20);
    ylabel(S.ax(19),'Memristance','FontSize',20);
    title (S.ax(19),'Memristance Vs. Time','Color',axis_colour,'FontSize',20);
    grid  (S.ax(19),'on');
    axis  (S.ax(19),[0 5 0 13])
% Circuit Diagram
S.ax(32) = axes('Parent', S.apps.iv.panel,...
                'units','pixels',...
                'position',[515 310 229 122]);
S.imgapps(3) = imshow('images/apps_sim_intro_white.png','Parent',S.ax(32));    

%%%%%%%%%%%%%%%%%%%%%
% Open Circuit Button
%%%%%%%%%%%%%%%%%%%%%          
S.open_circuit = uicontrol(S.fh,'style','pushbutton',...
                    'units','pixels',...
                    'fontsize',section_font,...
                    'position',[400 565 100 35],...
                    'string','Open Circuit',...
                    'visible','off');


%%%%%%%%%%%%%%%%%%%%%
% Memory Circuits
%%%%%%%%%%%%%%%%%%%%% 
W = {'units','pixels',...
     'position',[5 50 890 505]};  % Save some typing. 
% Neuromorphic Explanation
S.ax(33) = axes(W{:});
S.imgapps(4) = imshow('images/apps_memory1.jpg','Parent',S.ax(33));
S.ax(34) = axes(W{:});
S.imgapps(5) = imshow('images/apps_memory2.jpg','Parent',S.ax(34));
S.ax(35) = axes(W{:});
S.imgapps(6)= imshow('images/apps_memory3.jpg','Parent',S.ax(35));
% S.ax(36) = axes(W{:});
% S.imgapps(7)= imshow('images/apps_memory3.jpg','Parent',S.ax(36));
%%%%%%%%%%%%%%%%%%%%%
% Neuromorphic
%%%%%%%%%%%%%%%%%%%%% 
W = {'units','pixels',...
     'position',[5 50 890 505]};  % Save some typing. 
% Neuromorphic Explanation
S.ax(37) = axes(W{:});
S.imgapps(8) = imshow('images/apps_neuro1.png','Parent',S.ax(37));
S.ax(38) = axes(W{:});
S.imgapps(9) = imshow('images/apps_neuro2.png','Parent',S.ax(38));
S.ax(39) = axes(W{:});
S.imgapps(10)= imshow('images/apps_neuro3.png','Parent',S.ax(39));

%%%%%%%%%%%%%%%%%%%%%
% Programmable Circuits (PC)
%%%%%%%%%%%%%%%%%%%%% 
S.ax(40) = axes(W{:});
S.imgapps(11)= imshow('images/apps_PC.jpg','Parent',S.ax(40));
%%%%%%%%%%
% (PC) Op-Amp
%%%%%%%%%%
% Applications Section - Boxes to choose all subsections
S.apps.opamp.panel = uipanel(  S.fh,'units','pixels',...
                    'position',[70 70 760 450],...
                    'backgroundcolor', panel_colour,...
                    'Foregroundcolor', panel_text_colour,...
                    'Title', 'PC-Opamp',...
                    'visible','off');  

% Terminology Push Buttons to control section selection
W = {S.apps.opamp.panel,'style','pushbutton',...
                'units','normalized',...
                'fontsize',section_font,...
                'position'};  % Save some typing.               
S.apps.opamp.pb(1) = uicontrol(W{:},[0.05 0.55 0.40 0.40],'string','Inverting Amplifier');
S.apps.opamp.pb(2) = uicontrol(W{:},[0.55 0.55 0.40 0.40],'string','Non-Inverting Amplifier');

% Images
W = {'units','pixels',...
     'position',[5 50 890 505]};  % Save some typing. 
S.ax(41) = axes(W{:});
S.imgapps(12) = imshow('images/apps_PC_invert.png','Parent',S.ax(41));
S.ax(42) = axes(W{:});
S.imgapps(13) = imshow('images/apps_PC_noninvert.png','Parent',S.ax(42));

%%%%%%%%%%
% (PC) Oscillators
%%%%%%%%%%
% Applications Section - Boxes to choose all subsections
S.apps.osc.panel = uipanel(  S.fh,'units','pixels',...
                    'position',[70 70 760 450],...
                    'backgroundcolor', panel_colour,...
                    'Foregroundcolor', panel_text_colour,...
                    'Title', 'PC-Oscillators',...
                    'visible','off');  

% Terminology Push Buttons to control section selection
W = {S.apps.osc.panel,'style','pushbutton',...
                'units','normalized',...
                'fontsize',section_font,...
                'position'};  % Save some typing.               
S.apps.osc.pb(1) = uicontrol(W{:},[0.05 0.55 0.40 0.40],'string','Chua Chaotic Oscillator');
S.apps.osc.pb(2) = uicontrol(W{:},[0.55 0.55 0.40 0.40],'string','Phaseshift Oscillator-BCM');

% Images
W = {'units','pixels',...
     'position',[5 50 890 505]};  % Save some typing. 
S.ax(43) = axes(W{:});
S.imgapps(14) = imshow('images/apps_PC_chua.png','Parent',S.ax(43));
S.ax(44) = axes(W{:});
S.imgapps(15) = imshow('images/apps_PC_phaseshift.png','Parent',S.ax(44));


%%%%%%%%%%
% (PC) Rectifiers & Converters
%%%%%%%%%%
% Applications Section - Boxes to choose all subsections
S.apps.rect.panel = uipanel( S.fh,'units','pixels',...
                            'position',[70 70 760 450],...
                            'backgroundcolor', panel_colour,...
                            'Foregroundcolor', panel_text_colour,...
                            'Title', 'PC-Rect&Conv',...
                            'visible','off');  

% Terminology Push Buttons to control section selection
W = {S.apps.rect.panel,'style','pushbutton',...
                'units','normalized',...
                'fontsize',section_font,...
                'position'};  % Save some typing.               
S.apps.rect.pb(1) = uicontrol(W{:},[0.05 0.55 0.40 0.40],'string','BCM Rectifier');
S.apps.rect.pb(2) = uicontrol(W{:},[0.55 0.55 0.40 0.40],'string','Square to Sawtooth Wave');

% Images
W = {'units','pixels',...
     'position',[5 50 890 505]};  % Save some typing. 
S.ax(45) = axes(W{:});
S.imgapps(16) = imshow('images/apps_PC_rect.png','Parent',S.ax(45));
S.ax(46) = axes(W{:});
S.imgapps(17) = imshow('images/apps_PC_sawtooth.png','Parent',S.ax(46));



% % % Real time plotting - to be added in later version.
% % Chaotic Chua Oscillator - Plotting
% S.apps.chaos.panel = uipanel(  S.fh,'units','pixels',...
%                                 'position',[70 70 760 450],...
%                                 'backgroundcolor', panel_axis_colour,...
%                                 'Foregroundcolor', panel_axis_text_colour,...
%                                 'Title', 'Chaotic Oscillator',...
%                                 'visible','off');
% 
% % Start & Stop Buttons
% W = {S.apps.chaos.panel,'style','pushbutton',...
%                     'units','normalized',...
%                     'fontsize',section_font,...
%                     'position'};  % Save some typing.               
%     S.apps.chaos.pb(1) = uicontrol(W{:},[0.08 0.87 0.15 0.1],'string','Start');
%     S.apps.chaos.pb(2) = uicontrol(W{:},[0.30 0.87 0.15 0.1],'string','Stop', 'Enable','off');
%     S.apps.chaos.pb(3) = uicontrol(W{:},[0.19 0.72 0.15 0.1],'string','Open Circuit');
%     
% 
% % Axis
% S.ax(45) = axes( 'Parent', S.apps.chaos.panel,...
%                 'units','normalized',...
%                 'position',[0.55 0.15 0.40 0.75],...
%                 'XColor',axis_colour,'YColor',axis_colour,...
%                 'Color',axis_bg_colour);
%     grid  (S.ax(45),'on');                
%     xlabel(S.ax(45),'Voltage');
%     ylabel(S.ax(45),'Current');
%     title (S.ax(45),'Current Vs. Voltage','Color',axis_colour);
%     grid  (S.ax(45),'on');
% %     axis  (S.ax(45),[-5*10^-5 5*10^-5 -5 5])
% %     axis  (S.ax(45),[-5 5 -5*10^-5 5*10^-5])
%     axis  (S.ax(45),[-5 5 -2.5 2.5])            
   


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 4.Build Your Own Circuit
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Build Your Own Circuit Section - Boxes to choose all subsections
S.build.panel = uipanel(  S.fh,'units','pixels',...
                    'position',[70 70 760 450],...
                    'backgroundcolor', panel_colour,...
                    'Foregroundcolor', panel_text_colour,...
                    'Title', 'Build',...
                    'visible','off');    
                
    % Build Push Buttons to control subsection selection
    W = {S.build.panel,'style','pushbutton',...
                    'units','normalized',...
                    'fontsize',tg_font,...
                    'position'};  % Save some typing.               
    S.build.pb(1) = uicontrol(W{:},[0.05 0.55 0.40 0.40],'string','Build Your Own Circuit');               
    S.build.pb(2) = uicontrol(W{:},[0.55 0.55 0.40 0.40],'string','Build Your Own Model');
                
% IMAGES For Build Section                
W = {'units','pixels',...
     'position',[5 50 890 505]};  % Save some typing.    
% Build Your Own Circuit Instructions
S.ax(50) = axes(W{:});
S.imgbuild(1) = imshow('images/buildcircuit1.jpg','Parent',S.ax(50));
S.ax(51) = axes(W{:});
S.imgbuild(2) = imshow('images/buildcircuit2.jpg','Parent',S.ax(51));
S.ax(52) = axes(W{:});
S.imgbuild(3) = imshow('images/buildcircuit3.jpg','Parent',S.ax(52));
S.ax(53) = axes(W{:});
S.imgbuild(4) = imshow('images/buildcircuit4.jpg','Parent',S.ax(53));
S.ax(54) = axes(W{:});
S.imgbuild(5) = imshow('images/buildcircuit5.jpg','Parent',S.ax(54));
S.ax(55) = axes(W{:});
S.imgbuild(6) = imshow('images/buildcircuit6.jpg','Parent',S.ax(55));
S.ax(56) = axes(W{:});
S.imgbuild(7) = imshow('images/buildcircuit7.jpg','Parent',S.ax(56));
S.ax(57) = axes(W{:});
S.imgbuild(8) = imshow('images/buildcircuit8.jpg','Parent',S.ax(57));
% S.ax(58) = axes(W{:});
% S.imgbuild(8) = imshow('images/buildcircuit2.jpg','Parent',S.ax(58));
% Build Your Own Model Instructions
S.ax(59) = axes(W{:});
S.imgbuild(9) = imshow('images/buildmodel1.jpg','Parent',S.ax(59));
S.ax(60) = axes(W{:});
S.imgbuild(10) = imshow('images/buildmodel2.jpg','Parent',S.ax(60));
S.ax(61) = axes(W{:});
S.imgbuild(11) = imshow('images/buildmodel3.jpg','Parent',S.ax(61));
S.ax(62) = axes(W{:});
S.imgbuild(12) = imshow('images/buildmodel4.jpg','Parent',S.ax(62));
S.ax(63) = axes(W{:});
S.imgbuild(13) = imshow('images/buildmodel5.jpg','Parent',S.ax(63));



% S.ax(52) = axes(W{:});
% S.imgbuild(3) = imshow('images/buildmodel1.jpg','Parent',S.ax(52));
% S.ax(53) = axes(W{:});
% S.imgbuild(4) = imshow('images/buildmodel2.jpg','Parent',S.ax(53));
% S.ax(54) = axes(W{:});
% S.imgbuild(5) = imshow('images/buildmodel3.jpg','Parent',S.ax(54));
% S.ax(55) = axes(W{:});
% S.imgbuild(6) = imshow('images/buildmodel4.jpg','Parent',S.ax(55));
% S.ax(56) = axes(W{:});
% S.imgbuild(7) = imshow('images/buildmodel5.jpg','Parent',S.ax(56));
                   
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%  Initialization tasks
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% make the main figure visible again once all components are added
set(S.fh,'Visible','on') 
guidata(S.fh, data);  % store the GUI Data - may be unnecessary

set(S.imgintro(:), 'visible','off')
set(S.imgterms(:), 'visible','off')
set(S.imgapps(:),  'visible','off')
set(S.imgbuild(:), 'visible','off')

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%  Callbacks for MemristorGUI
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

set(S.hometg,      {'callback'},{{@home_top_nav,S}})
set(S.sectiontg,   {'callback'},{{@section_top_nav,S}})
set(S.homepb.pb(:),{'callback'},{{@homepb,S}})
set(S.popup,       {'callback'},{{@popup,S}})

% Next & Previous Buttons
set(S.next,    {'callback'},{{@next_previous,S}})
set(S.previous,{'callback'},{{@next_previous,S}})

%%%%%%%%%%%%%%%%%%%%%%
%Sections
%%%%%%%%%%%%%%%%%%%%%%
set(S.intro.home.pb(:),{'callback'},{{@intro_section,S}})
set(S.intro.plot.pb(:),{'callback'},{{@plot_hysteresis,S}})
set(S.intro.user.pb(:),{'callback'},{{@plot_user,S}})
set(S.terms.pb(:),     {'callback'},{{@terms_section,S}})
set(S.apps.home.pb(:), {'callback'},{{@apps_section,S}})
set(S.apps.all.pb(:),  {'callback'},{{@plot_simulink,S}})
set(S.apps.opamp.pb(:),{'callback'},{{@opamppb,S}})
set(S.apps.osc.pb(:),  {'callback'},{{@oscpb,S}})
set(S.apps.rect.pb(:), {'callback'},{{@rectpb,S}})
set(S.open_circuit,    {'callback'},{{@open_circuit,S}})
set(S.build.pb(:),     {'callback'},{{@build_section,S}})

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%  Utility functions for MemristorGUI
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Open the Splash Screen
if(nosplash==0)
    menu_about(S.fh,0,S);
end

end





%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Navigation
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function [] = homepb(h, eventdata, S)
% Callback for push buttons on Home Screen

% set(S.home, 'visible','off')
off(h,S);
data = guidata(S.fh); % retrieve GUI Data

switch h
    case S.homepb.pb(1) %Intro
        intro(h,S);
    case S.homepb.pb(2) % Terminology
        terms(h,S);
    case S.homepb.pb(3) % Applications
        apps(h,S);
    case S.homepb.pb(4) % Build Your Own Circuit
        build(h,S);
    otherwise
end

end


function data = home_top_nav(h, eventdata, S)
% Callback for Home button in top left

off(h,S);
data = guidata(S.fh); % retrieve GUI Data

set(S.home, 'visible','on')
set(S.arrow(:), 'visible','off')
set(S.sectiontg,'visible','off')
set(S.title, 'string','Memristor Toolbox')
set(S.text(1),'string',{'To Start - Please Choose a Section:'})
set(S.text(1),'visible','on')
data.section = 0;
data.subsection = 0;
data.subsubsection = 0;
guidata(S.fh, data);  % store the GUI Data
end


function [] = section_top_nav(h, eventdata, S)
% Callback for Section button in top left

off(h,S);
data = guidata(S.fh); % retrieve GUI Data
set(S.arrow(2), 'visible','off')

    switch data.section
        case 1 %Intro
            intro(h,S);
        case 2 % Terminology
            terms(h,S);
        case 3 % Applications
            apps(h,S);
        case 4 % Build Your Own Circuit
            build(h,S)
        otherwise
            set(S.title,'string','Error - Please Return to Home or Restart Toolbox')
    end
    
guidata(S.fh, data);  % store the GUI Data
end


function [] = next_previous(h, eventdata, S)
% Callback for Next & Previous Buttons (bottom right)

off(h,S);
data = guidata(S.fh); % retrieve GUI Data

% Calculate the new values of data.section & data.subsection
switch h
    case S.next % Move to the NEXT section or subsection
        switch data.section
            case 0
                data.section = 1;
                data.subsection = 0;
            case 1
                if(data.subsection == 10)
                    data.section = 2;
                    data.subsection = 0;
                else
                    data.subsection = data.subsection + 1;
                end
            case 2
                if(data.subsection == 2)
                    data.section = 3;
                    data.subsection = 0;
                else
                    data.subsection = data.subsection + 1;
                end
            case 3
                if(data.subsection == 9 && data.subsubsection >=2) %9 subsections
                    data.section = 4;
                    data.subsection = 0;
                    data.subsubsection = 0;
                elseif(data.subsection == 4 && data.subsubsection <2)
                    data.subsubsection = data.subsubsection +1;
                elseif(data.subsection == 5 && data.subsubsection <2)
                    data.subsubsection = data.subsubsection +1;
                elseif(data.subsection == 7 && data.subsubsection <2)
                    data.subsubsection = data.subsubsection +1;
                elseif(data.subsection == 8 && data.subsubsection <2)
                    data.subsubsection = data.subsubsection +1;
                elseif(data.subsection == 9 && data.subsubsection <2)
                    data.subsubsection = data.subsubsection +1;
                else
                    data.subsection = data.subsection + 1;
                    data.subsubsection = 0;
                end
            case 4
                if(data.subsection == 1 && data.subsubsection <7)
                    data.subsubsection = data.subsubsection +1;
                elseif(data.subsection == 2 && data.subsubsection <4)
                    data.subsubsection = data.subsubsection +1;
                elseif(data.subsection == 2)
                    data.section = 0;
                    data.subsection = 0;
                    data.subsubsection = 0;
                else
                    data.subsection = data.subsection + 1;
                    data.subsubsection = 0;
                end
        end         
    case S.previous % Move to the PREVIOUS section or subsection
        switch data.section
            case 0
            case 1
                if(data.subsection == 0)
                    data.section=0; %go back to home
                    data.subsection=0;
                else
                    data.subsection = data.subsection - 1;
                end
            case 2
                if(data.subsection == 0)
                    data.section=1;     % go back section 1
                    data.subsection=10;  % 10 intro subsections
                else
                    data.subsection = data.subsection - 1;
                end   
            case 3
                if(data.subsection == 0)
                    data.section = 2;
                    data.subsection = 2;    % 2 terms subsections
                    data.subsubsection = 0;
                elseif(data.subsection == 4 && data.subsubsection > 0)
                    data.subsubsection = data.subsubsection -1;
                elseif(data.subsection == 5 && data.subsubsection > 0)
                    data.subsubsection = data.subsubsection -1;
                elseif(data.subsection == 7 && data.subsubsection > 0)
                    data.subsubsection = data.subsubsection -1;
                elseif(data.subsection == 8 && data.subsubsection > 0)
                    data.subsubsection = data.subsubsection -1;
                elseif(data.subsection == 9 && data.subsubsection > 0)
                    data.subsubsection = data.subsubsection -1;
                else
                    data.subsection = data.subsection - 1;
                    data.subsubsection = 0;
                end
            case 4
                if(data.subsection == 0)
                    data.section = 3;
                    data.subsection = 9;    % 9 apps subsections
                    data.subsubsection = 0;
                elseif(data.subsection == 1 && data.subsubsection > 0)
                    data.subsubsection = data.subsubsection -1;
                elseif(data.subsection == 2 && data.subsubsection > 0)
                    data.subsubsection = data.subsubsection -1;
                else
                    data.subsection = data.subsection - 1;
                    data.subsubsection = 0;
                end
        end
    otherwise
end

guidata(S.fh, data);  % store the GUI Data

% Execute the command for the section the user is now currently at
switch data.section
    case 0 %Home
        home_top_nav(h, eventdata, S);
    case 1 %Intro
        switch data.subsection
            case 0
                intro(h,S);
            case 1
                intro_section(S.intro.home.pb(1),eventdata, S);
            case 2
                intro_section(S.intro.home.pb(2),eventdata, S);
            case 3
                intro_section(S.intro.home.pb(3),eventdata, S);    
            case 4
                intro_section(S.intro.home.pb(4),eventdata, S);
            case 5
                intro_section(S.intro.home.pb(5),eventdata, S);
            case 6
                intro_section(S.intro.home.pb(6),eventdata, S);
            case 7
                intro_section(S.intro.home.pb(7),eventdata, S);
            case 8
                intro_section(S.intro.home.pb(8),eventdata, S);
            case 9
                intro_section(S.intro.home.pb(9),eventdata, S);
            case 10
                intro_section(S.intro.home.pb(10),eventdata, S);
        end             
    case 2 % Terminology
        switch data.subsection
            case 0
                terms(h,S);
            case 1
                terms_section(S.terms.pb(1),eventdata, S);
            case 2
                terms_section(S.terms.pb(2),eventdata, S);
        end
    case 3 % Applications
        switch data.subsection
            case 0
                apps(h,S);
            case 1
                apps_section(S.apps.home.pb(1),eventdata, S);
            case 2
                apps_section(S.apps.home.pb(2),eventdata, S);
            case 3
                apps_section(S.apps.home.pb(3),eventdata, S);
            case 4
                apps_section(S.apps.home.pb(4),eventdata, S);
            case 5
                apps_section(S.apps.home.pb(5),eventdata, S);
            case 6
                apps_section(S.apps.home.pb(6),eventdata, S);
            case 7 % Opamps
                switch data.subsubsection
                    case 0
                        apps_section(S.apps.home.pb(7),eventdata, S);
                    case 1
                        opamppb(S.apps.opamp.pb(1), eventdata, S);
                    case 2
                        opamppb(S.apps.opamp.pb(2), eventdata, S);
                end
            case 8 % PC - Oscillators
                switch data.subsubsection
                    case 0
                        apps_section(S.apps.home.pb(8),eventdata, S);
                    case 1
                        oscpb(S.apps.osc.pb(1), eventdata, S);
                    case 2
                        oscpb(S.apps.osc.pb(2), eventdata, S);
                end
            case 9 % PC - Rectifiers & Converters
                switch data.subsubsection
                    case 0
                        apps_section(S.apps.home.pb(9),eventdata, S);
                    case 1
                        rectpb(S.apps.rect.pb(1), eventdata, S);
                    case 2
                        rectpb(S.apps.rect.pb(2), eventdata, S);
                end
        end
    case 4 % Build Your Own Circuit
        switch data.subsection
            case 0
                build(h,S);
            case 1
                build_section(S.build.pb(1),eventdata, S);
            case 2
                build_section(S.build.pb(2),eventdata, S);
        end
    otherwise
end

% Don't overwrite the GUIDATA
% guidata(S.fh, data);  % store the GUI Data
end


function popup(h, eventdata, S)
% Callback for the Popup Menu in the top right of the GUI
off(h,S);
data = guidata(S.fh); % retrieve GUI Data

val = get(h,'Value');
string_list = get(h,'String');
selected_string = string_list{val}; % Convert from cell array
                                    % to string
% Proceed with callback...
data.subsubsection = 0;

switch selected_string
    case 'Home'
        data = home_top_nav(h, eventdata, S);
    case '1. Intro'
        data = intro(h,S);
    case '1. Intro > What is a Memristor?'
        data = intro_section(S.intro.home.pb(1),eventdata, S);
    case '1. Intro > Fundamental Variables'
        data = intro_section(S.intro.home.pb(2),eventdata, S);
    case '1. Intro > Charge-Flux Relationship'
        data = intro_section(S.intro.home.pb(3),eventdata, S);
    case '1. Intro > Memristor Equations'
        data = intro_section(S.intro.home.pb(4),eventdata, S);   
    case '1. Intro > Pinched Hysteresis Loops'
        data = intro_section(S.intro.home.pb(5),eventdata, S);
    case '1. Intro > Memristor Timeline'
        data = intro_section(S.intro.home.pb(6),eventdata, S);    
    case '1. Intro > HP Memristor 1'
        data = intro_section(S.intro.home.pb(7),eventdata, S);
    case '1. Intro > HP Memristor 2'
        data = intro_section(S.intro.home.pb(8),eventdata, S);
    case '1. Intro > Interactive Plot'
        data = intro_section(S.intro.home.pb(9),eventdata, S);
    case '1. Intro > Input Your Own Equation'
        data = intro_section(S.intro.home.pb(10),eventdata, S);
    case '2. Terminology'
        data = terms(h,S);
    case '2. Terminology > Terms'
        data = terms_section(S.terms.pb(1),eventdata,S);
    case '2. Terminology > Bibliography'
        data = terms_section(S.terms.pb(2),eventdata,S);
    case '3. Applications'
        data = apps(h,S);
    case '3. Applications > Intro to Applications'
        data = apps_section(S.apps.home.pb(1),eventdata,S);
    case '3. Applications > Intro to Simulink'
        data = apps_section(S.apps.home.pb(2),eventdata,S);
    case '3. Applications > Simulink Plotting'
        data = apps_section(S.apps.home.pb(3),eventdata,S);
    case '3. Applications > Memory Circuits'
        data = apps_section(S.apps.home.pb(4),eventdata,S);
    case '3. Applications > Neuromorphic Engineering'
        data = apps_section(S.apps.home.pb(5),eventdata,S);
    case '3. Applications > Programmable Circuits'
        data = apps_section(S.apps.home.pb(6),eventdata,S);
    case '3. Applications > PC - Op-Amps'
        data = apps_section(S.apps.home.pb(7),eventdata,S);
    case '3. Applications > PC - Oscillators'
        data = apps_section(S.apps.home.pb(8),eventdata,S);
    case '3. Applications > PC - Rectifiers & Converters'
        data = apps_section(S.apps.home.pb(9),eventdata,S);
    case '4. Build Your Own Circuit'
        data = build(h,S);
    case '4. Build Your Own Circuit > Build Circuit'        
        data = build_section(S.build.pb(1),eventdata,S);
    case '4. Build Your Own Circuit > Build Model'
        data = build_section(S.build.pb(2),eventdata,S);
    otherwise
end


guidata(S.fh, data);  % store the GUI Data
end



%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Sections
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function data = intro(h, S)
% Callback for togglebuttons.
off(h,S);
data = guidata(S.fh); % retrieve GUI Data

set(S.title, 'string','1. Introduction & Tutorial')
set(S.sectiontg,'string','Intro')
set(S.arrow(1), 'visible','on')
set(S.sectiontg, 'visible','on')
set(S.intro.home.panel, 'visible','on') 
set(S.text(1),'string',{'Introduction - Please Choose a Topic:'})
set(S.text(1),'visible','on')
set(S.imgintro(:), 'visible','off')

set(S.previous,'string','Previous - Home')
data.section = 1;
data.subsection = 0;
data.subsubsection = 0;
guidata(S.fh, data);  % store the GUI Data
end

function data = terms(h, S)
% Callback for togglebuttons.

off(h,S);
data = guidata(S.fh); % retrieve GUI Data

set(S.title, 'string','2. Terminology & Bibliography')
set(S.sectiontg,'string','Terms')
set(S.arrow(1), 'visible','on')
set(S.sectiontg, 'visible','on')
set(S.terms.panel, 'visible','on')
set(S.text(1),'string',{'Memristor Basic Terminology'})
set(S.text(1),'visible','on')

set(S.previous,'string','Previous - Intro')
data.section = 2;
data.subsection = 0;
data.subsubsection = 0;
guidata(S.fh, data);  % store the GUI Data
end

function data = apps(h, S)
% Callback for togglebuttons.

off(h,S);
data = guidata(S.fh); % retrieve GUI Data

set(S.title, 'string','3. Sample Applications')
set(S.sectiontg,'string','Apps')
set(S.arrow(1), 'visible','on')
set(S.sectiontg, 'visible','on')
set(S.apps.home.panel, 'visible','on')
set(S.text(1),'string',{'Sample Applications - Please Choose a Topic:'})
set(S.text(1),'visible','on')

set(S.previous,'string','Previous - Terms')
data.section = 3;
data.subsection = 0;
data.subsubsection = 0;
guidata(S.fh, data);  % store the GUI Data
end

function data = build(h, S)
% Callback for togglebuttons.

off(h,S);
data = guidata(S.fh); % retrieve GUI Data

set(S.title, 'string','4. Build Your Own Circuit')
set(S.sectiontg,'string','Build')
set(S.arrow(1), 'visible','on')
set(S.sectiontg, 'visible','on')
set(S.build.panel, 'visible','on')
set(S.text(1),'string',{'Please Choose an Option:'})
set(S.text(1),'visible','on')

set(S.previous,'string','Previous - Apps')
data.section = 4;
data.subsection = 0;
data.subsubsection = 0;
guidata(S.fh, data);  % store the GUI Data
end




%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 1.Introduction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function data = intro_section(h,eventdata, S)
% Callback for togglebuttons.

data = guidata(S.fh); % retrieve GUI Data

set(S.intro.home.panel, 'visible','off')
set(S.arrow(1), 'visible','on')
set(S.sectiontg, 'visible','on')
set(S.arrow(2), 'visible','on')
set(S.sectiontg,'string','Intro')
set(S.text(:),'visible','off')      % Will probably want to put some text in later
set(S.next,'string','Next')
set(S.previous,'string','Previous')

% Set the footer
set(S.foot,'string',{'[4] L. Chua, "Resistance switching memories are memristors," Applied Physics A, vol. 102, no. 4, pp. 765-783 LA - English, 2011.'})
ref_HP = '[3] D. B. Strukov, G. S. Snider, D. R. Stewart, and R. S. Williams, "The missing memristor found," Nature, vol. 453, no. 7191, pp. 80-83, May 2008.';
data.section = 1;

switch h
    case S.intro.home.pb(1)
        set(S.imgintro(1), 'visible','on')
        set(S.title, 'string','What is a Memristor?')
        data.subsection = 1;
        set(S.foot,'string',S.copyright);
    case S.intro.home.pb(2)
        set(S.imgintro(2), 'visible','on')
        set(S.title, 'string','Fundamental Variables')
        data.subsection = 2;
        set(S.foot,'string',S.copyright);
    case S.intro.home.pb(3)
        set(S.imgintro(3), 'visible','on')
        set(S.title, 'string','Q - Phi Relationship')
        data.subsection = 3;
    case S.intro.home.pb(4)
        set(S.imgintro(4), 'visible','on')
        set(S.title, 'string','Memristor Defining Equations')
        data.subsection = 4;
    case S.intro.home.pb(5)
        set(S.imgintro(5), 'visible','on')
        set(S.title, 'string','Pinched Hysteresis Loops')
        data.subsection = 5;
    case S.intro.home.pb(6)
        set(S.imgintro(6), 'visible','on')
        set(S.title, 'string','Memristor Timeline')
        data.subsection = 6;
        set(S.foot,'string','');
    case S.intro.home.pb(7)
        set(S.imgintro(7), 'visible','on')
        set(S.title, 'string','HP Memristor 1')
        data.subsection = 7;
        set(S.foot,'string',ref_HP);
    case S.intro.home.pb(8)
        set(S.imgintro(8), 'visible','on')
        set(S.title, 'string','HP Memristor 2')
        data.subsection = 8;
        set(S.foot,'string',ref_HP);
    case S.intro.home.pb(9) 
        set(S.title, 'string','Interactive Plot')
        data.subsection = 9;
        set(S.foot,'string',S.copyright);
        set(S.intro.plot.panel,'visible','on');
        set(S.text(2),'visible','on',...
                      'string',['Below you can simulate the I (current) - V (Voltage) characteristic (Hysteresis Curve) '...
                                'of an ideal or an HP memristor. After choosing the parameters, click "Plot"']);
        
    case S.intro.home.pb(10)
        set(S.title, 'string','Input Your Own Equation')
        data.subsection = 10;   
        set(S.intro.user.panel,'visible','on');
        set(S.foot,'string',S.copyright);
        
        set(S.text(2),'visible','on',...
                      'string','Enter the following parameters, then click "Plot"');
                  
        %Symbolic Variables for plotting
        syms ip x; % input, state 
        set(S.next, 'string','Next - Terms')        
    otherwise
        data.subsection = 0; % Failure
end
    
guidata(S.fh, data);  % store the GUI Data
end



%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 2. Terminology & Bibliography
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function data = terms_section(h,eventdata, S)
% Callback for togglebuttons.

set(S.terms.panel,'visible','off')
set(S.arrow(1),   'visible','on')
set(S.arrow(2),   'visible','on')
set(S.sectiontg,  'visible','on')
set(S.sectiontg,  'string','Terms')
set(S.text(:),    'visible','off')      % Will probably want to put some text in later
set(S.next,       'string','Next')
set(S.previous,   'string','Previous')

data = guidata(S.fh); % retrieve GUI Data
data.section = 2;

switch h
    case S.terms.pb(1) % Apps intro
        set(S.imgterms(1), 'visible','on')
        set(S.title, 'string','Terminology')
        data.subsection = 1;
    case S.terms.pb(2)
        set(S.imgterms(2), 'visible','on')
        set(S.title, 'string','Bibliography')
        data.subsection = 2;
        set(S.next, 'string','Next - Apps')
    otherwise
        data.subsection = 0; % Failure
end 
guidata(S.fh, data);  % store the GUI Data
end




%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 3. Applications
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function data = apps_section(h,eventdata, S)
% Callback for togglebuttons.

set(S.apps.home.panel, 'visible','off')
set(S.arrow(1), 'visible','on')
set(S.arrow(2), 'visible','on')
set(S.sectiontg,'visible','on')
set(S.sectiontg,'string' ,'Apps')
set(S.text(:),  'visible','off')      % Will probably want to put some text in later
set(S.next,     'string' ,'Next')
set(S.previous, 'string' ,'Previous')

data = guidata(S.fh); % retrieve GUI Data
data.section = 3;

switch h
    case S.apps.home.pb(1) % Apps intro
        set(S.imgapps(1), 'visible','on')
        set(S.title, 'string','Introduction to Applications')
        data.subsection = 1;
    case S.apps.home.pb(2)
        set(S.imgapps(2), 'visible','on')
        set(S.title, 'string','Introduction to Simulink')
        data.subsection = 2;
    case S.apps.home.pb(3)
        set(S.title, 'string','Simulink Plotting')
        data.subsection = 3;
        set(S.imgapps(3), 'visible','on')
        set(S.text(2),'string',{'Press "Start" to begin the real-time plotting of data from the simulink circuit.'...
                                 'The circuit is a memristor in series with an AC voltage source '})
        set(S.text(2),'visible','on')
        set(S.apps.iv.panel,'visible','on');
        set(S.foot,'string',S.copyright);
        
        data.modelName = S.model.IV;
        data.ax(1) = S.ax(18);
        data.ax(2) = S.ax(19);
        data.graphs = 2; % number of graphs to be displayed
        data = SetupModel(S, data);

    case S.apps.home.pb(4) % Memory Circuits
        set(S.title, 'string','Memory Circuits')
        data.subsection = 4;
        set(S.open_circuit,'visible','on');
        switch data.subsubsection
            case 0
                set(S.imgapps(4), 'visible','on')
            case 1
                set(S.imgapps(5), 'visible','on')
            case 2
                set(S.imgapps(6), 'visible','on')
        end
    case S.apps.home.pb(5) % Neuromorphic
        set(S.title, 'string','Neuromorphic Engineering')
        data.subsection = 5;
        set(S.open_circuit,'visible','on');
        switch data.subsubsection
            case 0
                set(S.imgapps(8), 'visible','on')
            case 1
                set(S.imgapps(9), 'visible','on')
            case 2
                set(S.imgapps(10), 'visible','on')
        end
    case S.apps.home.pb(6) % Programmable Circuits
        set(S.title, 'string','Programmable Circuits')
        data.subsection = 6;
        set(S.imgapps(11), 'visible','on')
        
%         set(S.text(2),'string',{'Chaotic Chua Oscillator'...
%                                  ''})
%         set(S.text(2),'visible','on')
%         set(S.apps.chaos.panel,'visible','on');
%         set(S.foot,'string',S.copyright);
%         
%         data.modelName = S.model.Chaos;
%         data.ax(1) = S.ax(45);
% %         data.ax(2) = S.ax(19);
%         data.graphs = 1; % number of graphs to be displayed
%         data = SetupModel(S, data);

    case S.apps.home.pb(7) % PC - Op-Amps
        set(S.title, 'string','PC Op-Amps')
        set(S.apps.opamp.panel, 'visible','on')
        data.subsection = 7;
    case S.apps.home.pb(8) % PC - Oscillators
        set(S.title, 'string','PC - Oscillators')
        set(S.apps.osc.panel, 'visible','on')
        data.subsection = 8;
    case S.apps.home.pb(9) % PC - Rectifiers & Converters
        set(S.title, 'string','PC - Rectifiers & Converters')
        set(S.apps.rect.panel, 'visible','on')
        data.subsection = 9;
        
        %         set(S.text(1),'string',{'Programmable Circuits - Please Choose an Area:'})
%         set(S.text(1),'visible','on')      


    otherwise
        data.subsection = 0; % Failure
end 
guidata(S.fh, data);  % store the GUI Data
end


function [] = opamppb(h, eventdata, S)
% Callback for togglebuttons.

off(h,S);
data = guidata(S.fh); % retrieve GUI Data

switch h
    case S.apps.opamp.pb(1) %Inverting Amplifier
        set(S.open_circuit,'visible','on');
        set(S.imgapps(12), 'visible','on')
        data.subsubsection = 1;
    case S.apps.opamp.pb(2) %Non-Inverting Amplifier
        set(S.open_circuit,'visible','on');
        set(S.imgapps(13), 'visible','on')
        data.subsubsection = 2;
    otherwise
end
guidata(S.fh, data);  % store the GUI Data
end

function [] = oscpb(h, eventdata, S)
% Callback for togglebuttons.

off(h,S);
data = guidata(S.fh); % retrieve GUI Data

switch h
    case S.apps.osc.pb(1) %Memristor_Based_Chua_Chaotic_Oscillator
        set(S.open_circuit,'visible','on');
        set(S.imgapps(14), 'visible','on')
        data.subsubsection = 1;
    case S.apps.osc.pb(2) %Phaseshift_Oscillator_BCM
        set(S.open_circuit,'visible','on');
        set(S.imgapps(15), 'visible','on')
        data.subsubsection = 2;
    otherwise
end
guidata(S.fh, data);  % store the GUI Data
end

function [] = rectpb(h, eventdata, S)
% Callback for togglebuttons.

off(h,S);
data = guidata(S.fh); % retrieve GUI Data

switch h
    case S.apps.rect.pb(1) %BCM_Rectifier
        set(S.open_circuit,'visible','on');
        set(S.imgapps(16), 'visible','on')
        data.subsubsection = 1;
    case S.apps.rect.pb(2) %Square_to_Sawtooth
        set(S.open_circuit,'visible','on');
        set(S.imgapps(17), 'visible','on')
        data.subsubsection = 2;
        set(S.next, 'string','Next - Build')
    otherwise
end

end

function [] = open_circuit(h, eventdata, S)
% Callback for toggle button to open the Simulink Circuit.
data = guidata(S.fh); % retrieve GUI Data

switch data.subsection
    case 4 % Memory Circuits
        open_system(S.model.Memory);
    case 5 % Neuromorphic
        open_system(S.model.Neuro);
    case 7 % PC - Op-Amps
        switch data.subsubsection
            case 1
                open_system(S.model.Inverter);
            case 2
                open_system(S.model.Noninverter);
        end
    case 8 % PC - Oscillators
        switch data.subsubsection
            case 1
                open_system(S.model.Chaos);
            case 2
                open_system(S.model.Phase);
        end
    case 9 % PC - Rectifiers & Converters
        switch data.subsubsection
            case 1
                open_system(S.model.Rect);
            case 2
                open_system(S.model.STBCM);
                open_system(S.model.STnovel);
        end
    otherwise
end

end



%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 4. Build Your Own Circuit
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function data = build_section(h,eventdata, S)
% Callback for togglebuttons.

set(S.build.panel   ,'visible','off')
set(S.arrow(1)      ,'visible','on')
set(S.sectiontg     ,'visible','on')
set(S.arrow(2)      ,'visible','on')
set(S.sectiontg     ,'string','Build')
set(S.text(:)       ,'visible','off')      % Will probably want to put some text in later
set(S.next          ,'string','Next')
set(S.previous      ,'string','Previous')


data = guidata(S.fh); % retrieve GUI Data
data.section = 4;

switch h
    case S.build.pb(1) % Build Your Own Circuit
        set(S.title, 'string','Build Your Own Circuit')
        data.subsection = 1;
        switch data.subsubsection
            case 0
                set(S.imgbuild(1), 'visible','on');
%                 cd(S.simulink_path);
                simulink; % Open the Simulink Browser
                open('Memristor_lib'); % Open the Memristor Library
                % Open a New Blank Simulink File
                try   %the new model could already be open
                    open_system(new_system('Custom_Memristor_Circuit'));
                end
            case 1
                set(S.imgbuild(2), 'visible','on')
            case 2
                set(S.imgbuild(3), 'visible','on')
            case 3
                set(S.imgbuild(4), 'visible','on')                
            case 4
                set(S.imgbuild(5), 'visible','on')                
            case 5
                set(S.imgbuild(6), 'visible','on')                
            case 6
                set(S.imgbuild(7), 'visible','on')
            case 7
                set(S.imgbuild(8), 'visible','on')
        end
    case S.build.pb(2) % Build Your Own Model
        set(S.title, 'string','Build Your Own Model')
        data.subsection = 2;
        switch data.subsubsection
            case 0
                open('New_memristor.ssc')
                set(S.imgbuild(9), 'visible','on')
            case 1
                set(S.imgbuild(10), 'visible','on')
            case 2
                set(S.imgbuild(11), 'visible','on')
            case 3
                set(S.imgbuild(12), 'visible','on')
            case 4
                set(S.imgbuild(13), 'visible','on')
                set(S.next       , 'string','Next - Home')
        end
    otherwise
        data.subsection = 0; % Failure
end 
guidata(S.fh, data);  % store the GUI Data
end



%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Function for plotting ideal & HP memristors
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function plot_hysteresis(h,eventdata,S)

a  = get(S.intro.plot.ip(1),'String'); % amplitude input
f  = get(S.intro.plot.ip(2),'String'); % frequency input (Hz)

a=str2double(a{1});
f=str2double(f{1});

% Get the selected Memristor
val = get(S.intro.plot.popup(1),'Value');
string_list = get(S.intro.plot.popup(1),'String');
memristor = string_list{val}; % Convert from cell array
                                    % to string

% Get the selected Input Type
val = get(S.intro.plot.popup(2),'Value');
string_list = get(S.intro.plot.popup(2),'String');
input = string_list{val}; % Convert from cell array
                                    % to string
t=(0:0.05:(100*pi)); % time steps 

% current input                                                                     
switch input
    case 'Sine Wave'
        i = a*sin(f*t);
    case 'Square Wave'
        i = a * square(f*t,50);
    case 'Triangle Wave'
        i = a*sawtooth(2*f*t,0.5);
    case 'Staircase'
        i = a*fix(f*t);
    case 'DC Source'
        i = a.*ones(1,length(t));

end
i=i'; % Change i into a column vector
                
switch memristor
    case 'Ideal Memristor' %Charge Controlled Ideal Memristor
        x=zeros(length(t),1); %Preallocate x - the state variable
        x(1)= 0.4; % give x and initial condition

        % Solve the differential State equation incrementally
        % Xn = Xn-1 + dx
        for j=2:length(t)
            x(j) = (x(j-1) + i(j)*(t(j)-t(j-1)));   
        end
        R = x; % solve for the Memristance (R(x))
        v = R.*i; % solve for the output current
        
    case 'HP Memristor'
        R_off=100;  %Off Resistance
        R_on=2;     %On Resistance
        u_v=10e-14; %Average Ion Mobility
        D = 10e-9;  %length of the device
        
        w=zeros(length(t),1); %Preallocate w - the width of doped region(the state)
        w(1)=0;

        for j=2:length(t)
            w(j) = (w(j-1) - (u_v*(R_on/D)*i(j))*(t(j)-t(j-1)));
        end

        M = ((R_on*(w./D)) + R_off*(1-(w./D)));
        v=M.*i;
end


plot  (S.ax(15),v,i,'linewidth',2,'Color',S.axis_colour)
grid  (S.ax(15),'on');                
xlabel(S.ax(15),'Voltage (V)','FontSize',15,'Color',S.axis_colour);
ylabel(S.ax(15),'Current (A)','FontSize',15,'Color',S.axis_colour);
title (S.ax(15),'Current Vs. Voltage','FontSize',15,'Color',S.axis_colour);
grid  (S.ax(15),'on');
set   (S.ax(15),   'FontSize',15,...
                'XColor',S.axis_colour,'YColor',S.axis_colour,...
                'Color',S.axis_bg_colour);
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Function for plotting user inputted memristor equation
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function plot_user(h,eventdata,S)
%Symbolic Variables for plotting
syms ip x;

state = get(S.intro.user.ip(1),'String');
M  = get(S.intro.user.ip(2),'String');
a  = get(S.intro.user.ip(3),'String');
f  = get(S.intro.user.ip(4),'String');

a=str2double(a{1});
f=str2double(f{1});

% save('variablesA', 'a', 'f','state')


T=(0:0.05:(3*pi)-0.1);
u=a*sin(f*T);
state = subs(state,ip,u);
x_val=zeros(1,length(T)); %Preallocate x_val - the state variable with values worked out
x_val(1)=5e-5;
for i=2:length(u)   
    x_val(i) = ((x_val(i-1))+((state(i) * (T(i)-(T(i-1))))));    
end

M =subs(M,x,x_val);
M(M<=0.1)=.1;
y = M.*u;

plot  (S.ax(16),u,y,'linewidth',2,'Color',S.axis_colour)
grid  (S.ax(16),'on');                
xlabel(S.ax(16),'Voltage (V)','FontSize',15,'Color',S.axis_colour);
ylabel(S.ax(16),'Current (A)','FontSize',15,'Color',S.axis_colour);
title (S.ax(16),'Current Vs. Voltage','FontSize',15,'Color',S.axis_colour);
grid  (S.ax(16),'on');

set(S.ax(16),   'FontSize',15,...
                'XColor',S.axis_colour,'YColor',S.axis_colour,...
                'Color',S.axis_bg_colour);

end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Simulink Listeners - to control and extract data from Simulink models
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function plot_simulink(h,eventdata, S)
% Function to plot the data from the simulink models

data = guidata(S.fh); % retrieve GUI Data

% % reset the line(s)
% for idx = 1:length(data.lineHandles)
%     set(data.lineHandles(idx),...
%         'XData',[],...
%         'YData',[]);
% end

switch h
    case S.apps.all.pb(1) % Start Button
        
        % Load the model if required (it may have been closed manually).
        if ~modelIsLoaded(data.modelName)
            load_system(data.modelName);
        end
        
        
        % reset the line(s)
        for idx = 1:length(data.lineHandles)
            set(data.lineHandles(idx),...
                'XData',[],...
                'YData',[]);
        end
        
        try %#ok<*TRYNC>
            set(data.lineHandles(:),'visible','on'); % turn on lines
        end
        
        % set the simulation mode to normal
        set_param(data.modelName,'SimulationMode','normal');
        % Set a listener on the Gain block in the model's StartFcn
        set_param(data.modelName,'StartFcn','localAddEventListener');
        % start the model
        set_param(data.modelName,'SimulationCommand','start');

        % toggle the buttons
        % Turn off the Start button
        set(S.apps.all.pb(1),'Enable','off');
        % Turn on the Stop button
        set(S.apps.all.pb(2),'Enable','on');

    case S.apps.all.pb(2) % Stop Button
        % stop the model
        set_param(data.modelName,'SimulationCommand','stop');
        
        % toggle the buttons
        % Turn on the Start button
        set(S.apps.all.pb(1),'Enable','on');
        % Turn off the Stop button
        set(S.apps.all.pb(2),'Enable','off');
        
        % Remove the listener on the Gain block in the model's StartFcn
        localRemoveEventListener;
        
    case S.apps.all.pb(3) % Open The Circuit
        open_system(data.modelName);
end        

end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Callback Function for adding an event listener to the gain block
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function localAddEventListener

% % get the application data
% ad = guidata(gcbo);
data = guidata(gcbo); % retrieve GUI Data


% % execute any original startFcn that the model may have had
% if ~isempty(data.originalStartFcn)
%     evalin('Base',data.originalStartFcn);
% end

% Add the listener(s)
% For this example all events call into the same function
data.eventHandle = cell(1,length(data.viewing));
for idx = 1:length(data.viewing)
    data.eventHandle{idx} = ...
        add_exec_event_listener(data.viewing(idx).blockName,...
        data.viewing(idx).blockEvent, data.viewing(idx).blockFcn);
end


% % store the changed app data
% guidata(gcbo,ad);
guidata(gcbo, data);  % store the GUI Data

end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Callback Function for executing the event listener on the gain block
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function localEventListener_v(block, eventdata)

% get the application data
hf = findall(0,'tag',mfilename);
data = guidata(hf);

% Get the handle to the line that currently needs updating
thisLineHandle = data.lineHandles(1);

xdata = get(thisLineHandle,'XData');
value = block.InputPort(1).Data;
newXData = [xdata value];
newYData = get(hf,'UserData');  % Recall the Y values
set(thisLineHandle,...
    'XData',newXData,...
    'YData',newYData);
% save('variables', 'newXData', 'newYData')

% disp(newXData);
% disp(newYData);

% guidata(hf,data);


end

function localEventListener_i(block, eventdata)

% get the application data
hf = findall(0,'tag',mfilename);
data = guidata(hf);

% Get the handle to the line that currently needs updating
thisLineHandle = data.lineHandles(1);

ydata = get(thisLineHandle,'YData');
value = block.InputPort(1).Data;
newYData1 = [ydata value];
set(hf,'UserData',newYData1);    % use UserData to save the Y values
% save('y', 'newYData1')
end

function localEventListener_m(block, eventdata)

% get the application data
hf = findall(0,'tag',mfilename);
data = guidata(hf);

% Get the handle to the line that currently needs updating
thisLineHandle = data.lineHandles(2);

xdata = get(thisLineHandle,'XData');
ydata = get(thisLineHandle,'YData');
value = block.InputPort(1).Data;
sTime = block.CurrentTime;
newXData = [xdata sTime];
newYData = [ydata value];

set(thisLineHandle,...
    'XData',newXData,...
    'YData',newYData);
end

%Unused Function
function localEventListener1(block, eventdata) %#ok
% 
% % Note: this callback is called by all the block listeners.  No effort has
% % been made to time synchronise the data from each signal.  Rather it is
% % assumed that since each block calls this function at every time step and
% % hence the time synchronisation will come "for free".  This may not be the
% % case for other models and additional code may be required for them to
% % work/display data correctly.
% 
% % get the application data
% hf = findall(0,'tag',mfilename);
% data = guidata(hf);
% 
% 
% % Get the handle to the line that currently needs updating
% thisLineHandle = ...
%     data.lineHandles([data.viewing.blockHandle]==block.BlockHandle);
% 
% % Get the data currently being displayed on the axis
% xdata = get(thisLineHandle,'XData');
% ydata = get(thisLineHandle,'YData');
% % Get the simulation time and the block data
% sTime = block.CurrentTime;
% value = block.InputPort(1).Data;
% 
% 
% % Only the last 1001 points worth of data
% % The model sample time is 0.001 so this represents 1000 seconds of data
% % if length(xdata) < 1001
%     newXData = [xdata sTime];
%     newYData = [ydata value];
% % else
% %     newXData = [xdata(2:end) sTime];
% %     newYData = [ydata(2:end) value];
% % end
% 
% % Display the new data set
% set(thisLineHandle,...
%     'XData',newXData,...
%     'YData',newYData);
% 
% % % The axes limits may also need changing
% % newXLim = [max(0,sTime-10) max(10,sTime)];
% % set(data.handles.plotAxes,'Xlim',newXLim);
% 
end



%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Function to check that model is still loaded
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function modelLoaded = modelIsLoaded(modelName)

try
    modelLoaded = ...
        ~isempty(find_system('Type','block_diagram','Name',modelName));
catch ME
    % Return false if the model can't be found
    modelLoaded = false;
end
end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Function to load model and get certain of its parameters
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function data = localLoadModel(data)

% Load the simulink model
if ~modelIsLoaded(data.modelName)
    load_system(data.modelName);
end


% Create some application data storing various
% pieces of information about the model's original state.
% These will be used to "reset" the model to its original state when
% the UI is closed.

% List the blocks that are to have listeners applied
data.viewing = struct(...
    'blockName','',...
    'blockHandle',[],...
    'blockEvent','',...
    'blockFcn',[]);
% Every block has a name
data.viewing(1).blockName = sprintf('%s/Voltage',data.modelName);
data.viewing(2).blockName = sprintf('%s/Current',data.modelName);
data.viewing(3).blockName = sprintf('%s/Memristance',data.modelName);
% That block has a handle
% (This will be used in the graphics drawing callback, and is done here
% as it should speed things up rather than searching for the handle
% during every event callback.)
data.viewing(1).blockHandle = get_param(data.viewing(1).blockName,'Handle');
data.viewing(2).blockHandle = get_param(data.viewing(2).blockName,'Handle');
data.viewing(3).blockHandle = get_param(data.viewing(3).blockName,'Handle');
% List the block event to be listened for
data.viewing(1).blockEvent = 'PostOutputs';
data.viewing(2).blockEvent = 'PostOutputs';
data.viewing(3).blockEvent = 'PostOutputs';
% List the function to be called
% (These must be subfunctions within this mfile).
data.viewing(1).blockFcn = @localEventListener_v;
data.viewing(2).blockFcn = @localEventListener_i;
data.viewing(3).blockFcn = @localEventListener_m;

% Save some of the models original info that this UI may change
% (and needs to change back again when the simulation stops)
data.originalStopTime = get_param(data.modelName,'Stoptime');
data.originalMode =  get_param(data.modelName,'SimulationMode');
data.originalStartFcn = get_param(data.modelName,'StartFcn');

% We'll also have a flag saying if the model has been previously built
data.modelAlreadyBuilt = false;

end




%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Function to Setup the Given Model and Load it
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function data = SetupModel(S, data)

% Load the simulink model
    data = localLoadModel(data);


    % Put an empty line on the axes for each signal that will be
    % monitored
    % Save the line handles, which will be useful to have in an
    % array during the graphics updating routine.
    nlines = data.graphs;
    hl = nan(1,nlines);
    % colourOrder = get(data.ax1,'ColorOrder');
    for idx = 1:nlines
        hl(idx) = line('Parent',data.ax(idx),...
            'XData',[],...
            'YData',[],...
            'EraseMode','background',...
            'LineWidth',3,...
            'Color',data.linecolour,...
            'Tag',sprintf('signalLine%d',idx));

        % 'Color',colourOrder(mod(idx-1,size(colourOrder,1))+1,:),...

    end
    data.lineHandles = hl;
    S.lineHandles = hl;
end




%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Callback Function for removing the event listener from the gain block
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function localRemoveEventListener()

% get the application data
data = guidata(gcbo);

% return the startFcn to its original value
set_param(data.modelName,'StartFcn',data.originalStartFcn);

% delete the listener(s)
for idx = 1:length(data.eventHandle)
    if ishandle(data.eventHandle{idx})
        delete(data.eventHandle{idx});
    end
end
% remove this field from the app data structure
data = rmfield(data,'eventHandle');
%save the changes
guidata(gcbo,data);
end



%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Callback Function for viewing the documentation/help
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function menu_help(h,eventdata,S) %#ok<*INUSD>

% Just view the help for the primary function in this file
doc(mfilename);
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Callback Function for viewing an about box
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function S = menu_about(h,eventdata,S) %#ok<*INUSL>

% Create an about box
SCR = get(0,'Screensize');  % Get screensize.
S.splash.fh = dialog(   'position',[SCR(3)/2-300 ,SCR(4)/2-200 , 600, 400],...
                        'color','w',...
                        'name','Memristor Toolbox' );

%559 x 421
% UCD Logo Symbol
UCD = imread('images/UCD_Logo.png');
splash.ax(1) = axes( 'Parent', S.splash.fh,...
                'units','pixels',...
                'position',[5 150 173 250]);
imshow(UCD,'Parent',splash.ax(1),'Border','loose');

% Text Image
UCD = imread('images/splash.png');
splash.ax(2) = axes( 'Parent', S.splash.fh,...
                'units','pixels',...
                'position',[180 70 420 330]);
imshow(UCD,'Parent',splash.ax(2),'Border','loose');


% Checkbox - for not opening the splash screen again - currently does nothing.
S.splash.box = uicontrol('Parent',S.splash.fh,...
                        'style','checkbox',...
                        'units','normalized',...
                        'fontsize',12,...
                        'BackgroundColor','w',...
                        'position',[0.65 0.05 0.35 0.10],...
                        'string','Don''t show this box again',...
                        'Value',0);  
                    
% Close Button                    
S.splash.pb = uicontrol('Parent',S.splash.fh,...
                        'style','pushbutton',...
                        'units','normalized',...
                        'fontsize',12,...
                        'position',[0.43 0.05 0.14 0.10],...
                        'string','Continue',...
                        'Callback',{@splash_pb,S});
             
end

% Function to delete the Splash Screen Figure & save the checkbox selection
function splash_pb(h,eventdata,S) 
    load('memory.mat','installed')
    nosplash = get (S.splash.box,'Value'); %#ok<NASGU>
    save('memory.mat','installed','nosplash')


    delete(S.splash.fh) %Delete Splash Screen Figure
end



%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Switch Everything Off
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [] = off(h, S)
% Turn all elements off
data = guidata(S.fh); % retrieve GUI Data

set(S.home, 'visible','off')
set(S.text, 'visible','off')

set(S.intro.home.panel,'visible','off')
set(S.intro.plot.panel,'visible','off')
set(S.intro.user.panel,'visible','off')
set(S.terms.panel,     'visible','off')
set(S.apps.home.panel, 'visible','off')
set(S.apps.iv.panel,   'visible','off')
set(S.apps.opamp.panel,'visible','off')
set(S.apps.osc.panel,  'visible','off')
set(S.apps.rect.panel, 'visible','off')
% set(S.apps.chaos.panel,'visible','off')
set(S.build.panel,     'visible','off')

set(S.next,'string','Next')
set(S.previous,'string','Previous')
set(S.foot,'string',S.copyright);
try
    set(data.lineHandles(:),'visible','off'); % turn off lines
end

set(S.open_circuit,'visible','off');

set(S.imgintro(:), 'visible','off')
set(S.imgterms(:), 'visible','off')
set(S.imgapps(:),  'visible','off')
set(S.imgbuild(:), 'visible','off')

cd(S.home_path);
end



%%%%%%%%%%%%%%%%%%%%%
% Misc Code
%%%%%%%%%%%%%%%%%%%%%

% Notes:
% Max Image 890x505 (31.4cm x 17.82cm)
% 50 from bottom, 5 from either side, 555 from top


% % Find the path of the simulink models
% x=which('Memristor_lib')
% if(ispc)
% idx = max(strfind(x,'\'));
% elseif(isunix)
% idx = max(strfind(x,'/'));
% end
% S.simulink_path = x(1:idx); 

% % POSITIONS OF PUSBUTTONS
%     'position',[0.05 0.71 0.26 0.24],...
%     'position',[0.37 0.71 0.26 0.24],... 
%     'position',[0.69 0.71 0.26 0.24],...
%     'position',[0.05 0.38 0.26 0.24],...
%     'position',[0.37 0.38 0.26 0.24],...
%     'position',[0.69 0.38 0.26 0.24],...
%     'position',[0.05 0.05 0.26 0.24],...
%     'position',[0.37 0.05 0.26 0.24],...
%     'position',[0.69 0.05 0.26 0.24],...
