Code covered by the BSD License  

Highlights from
TxtMsg Create

image thumbnail
from TxtMsg Create by Robert M. Flight
GUI generates a function useful for sending text messages from Matlab

txtmsg_create(varargin)
function varargout = txtmsg_create(varargin)
% This function is to used to generate a function that is able to send text
% messages to a particular user from MatLab. The function generated is
% specific to the username supplied, and the email password, email address,
% and cellphone texting number are stored in the file, but the file is
% preparsed into Matlab code, a p-file, making it more difficult to
% actually see the contents of the file. This keeps the password and
% address relatively secure. The M-file used to generate the p-file is
% permanently deleted.
%
% If your cell phone carrier is not shown, you may also input the entire
% text address into the phone number field, if known (carriers generally
% supply this information).
%
% This is currently only set up to use gmail accounts, but could probably be
% modified to use any smtp account if the user so wished. If you figure
% that out, please let me know.
%
% This function was inspired by: 
% send_text_message.m - Ke Feng, Sept. 2007
% logindlg.m - Jeremy Smith
%
% Robert M. Flight, November 4, 2007
% rflight79@gmail.com
% V 1.1: 17.12.07 - Changed to create a preparsed P-file to avoid saving the
% password and email address information *anywhere* in plain text.
% V 1.0: 4.11.07 - original version
%

global carrierlist;

carrierlist.name = {'AllTell';'AT&T';'Boost';...
    'Cingular';'Cingular 2'; 'NexTel';'Sprint';...
    'TMobile'; 'Verizon'; 'Virgin'; 'Aliant'; 'Rogers'; 'Telus'};

carrierlist.address = {'@message.alltel.com'; '@mmode.com';...
    '@myboostmobile.com'; '@cingularme.com'; '@mobile.mycingular.com';...
    '@messaging.nextel.com'; '@messaging.sprintpcs.com'; '@tmomail.net';...
    '@vtext.com'; '@vmobl.com'; '@txt.aliant.net'; '@pcs.rogers.com';...
    '@msg.telus.com'};

clear carrierlist;

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

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

% Update handles structure
guidata(hObject, handles);

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


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

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

function edit1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

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

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

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

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

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

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

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

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

function edit6_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit6 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

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

% Actual creates the M file and mat files that store the data.
function createfunction(hObject, eventdata, handles)
global carrierlist; % get the carrier information

% Get the various pieces of information required from the GUI
hgmailadd = findobj('Tag','gmail_address');
gmailadd = get(hgmailadd,'String');

hcarrier = findobj('Tag','carrier_info');
selval = get(hcarrier,'Value');

hcellyesno = findobj('Tag','cellyesnocheckbox');
yesno = get(hcellyesno,'Value');

hphone = findobj('Tag','cellphonenumber');
phonenum = get(hphone,'String');
phonenum = phonenum(phonenum ~= 45);    % remove dashes in phone number if present

husernam = findobj('Tag','username');
unam = get(husernam,'String');

% Want to either combine the phone number provide with the texting address
% from the carrier list, or take the full address provided by the user if
% their carrier is not in the list.
if yesno ~= 1
    totalnum = [phonenum, carrierlist.address{selval}];
else
    totalnum = phonenum;
end %if

% strip off the 1 at beginning of phone number if it exists, this should
% not be in the email address for texting
if totalnum(1) == '1'
    totalnum = totalnum(2:end);
end %if

% Now get the stored password in the figure's UserData
hfig = findobj('Name','TxtMsg Create');
passw = get(hfig,'UserData');

% The two passwords have to be identical for this to work
if (size(passw{1}) ~= size(passw{2})) | (sum(passw{1} - passw{2}) ~= 0)
    errordlg('Passwords are not the same!');
end %if

% Check that the person entered a username.
if length(unam) == 0
    errordlg('Username Required!');
end %if

% Change the state of the random number generator to try and make sure that
% the filenames generated are unique and hard to reproduce. Also dont want
% filenames that say 'password', email address.
initstat = sum(100*clock);
rand('twister',initstat);
filnam = num2str(floor(rand(1,10)*10));
filnam = filnam(~isspace(filnam));

pfilnam = [filnam, num2str(double('p')), '.mat'];
pw = passw{1};
% save(pfilnam,'pw');

gfilnam = [filnam, num2str(double('g')), '.mat'];
pn = totalnum;
gm = gmailadd;
% save(gfilnam,'gm','pn');

% This mat file contains the actual contents of the *.m file to be written
% as a series of cellstrings, if you need to make permanent modifications
% to the output file, then modify the strings in here.
load txtmsg.mat;

% Change the required lines to use the new filenames
txtmsg_text{4} = ['function ', unam, '_txtmsg(varargin)'];
txtmsg_text{18} = ['gm = ''', gm, '''; pw = ''', pw, ''';'];
txtmsg_text{19} = ['pn = ''', pn, ''';'];
[nlin,m] = size(txtmsg_text);

htag = get(hObject,'Tag');

% Create all required files and spit out the messages depending on whether
% the user hits 'Create', or 'Test'
if strcmp(htag,'createbutton')  % if hit create
    
    functfilnam = [unam, '_txtmsg.m'];
    fid = fopen(functfilnam,'w+');

    for ilin = 1:nlin
        fprintf(fid,'%s\n',txtmsg_text{ilin});
    end %for

    fclose(fid);
    
    evalstr = ['pcode ', functfilnam];
    eval(evalstr);
    
    % Get the recycle state so we can put it back after deleting the M file
    recstat = recycle;
    
    % turn recycling off so the M file is permanently deleted
    recycle('off');
    delete(functfilnam);
    recycle(recstat); % put recycle state back to what it was whether off or on
    newfilnam = [functfilnam(1:end-1), 'p'];
    
    % Tell the user what files were made so they can move them to wherever
    % they need them.
    messag = {'The following files were created:';...
        ''; newfilnam;...
        ''; 'These must be on the Matlab path to be used';...
        '';
        'Messages will be sent using:';...
        gmailadd; totalnum};
    h = msgbox(messag,'Files Created','help');
    
else    % otherwise they hit "test", all files are deleted after the test.
    functfilnam = ['delete_txttest.m'];
    fid = fopen(functfilnam,'w+');
    for ilin = 1:nlin
        fprintf(fid,'%s\n',txtmsg_text{ilin});
    end %for
    fclose(fid);
    messag = 'This is a test';
    sub = 'Test Message';
    
    msg = {'Text Message sent to:'; totalnum};
    msgbox(msg,'Test Sent!','help');
    
    evalstr = [functfilnam(1:end-2), '(sub,messag);'];
    eval(evalstr);
    
    % delete all the created files, so someone else doesnt stumble across
    % them
    delete(functfilnam,gfilnam,pfilnam);
    
end %if
    
% This function hides the password with asterisks, the password is still
% stored in 'UserData', and will be stored as text in the binary mat file,
% but it should still be better than plaintext in the *.m file.
function hidepass(h,event,handles)

hfig = findobj('Name','TxtMsg Create');
passw = get(hfig,'UserData');   % get the old passwords
key = get(hfig,'currentkey');   % which key was pressed?

% which password are we modifying?
if get(h,'Tag') == 'passwa'
    tmppas = passw{1};
    id = 1;
else
    tmppas = passw{2};
    id = 2;
end %if

switch key
    case 'backspace'
        tmppas = tmppas(1:end-1);
    otherwise
        tmppas = [tmppas get(hfig,'currentcharacter')];
end %switch

passw{id} = tmppas;
set(hfig,'UserData',passw);

% actually write out the asterixes to represent the password
sizepass = size(tmppas);
if sizepass(2) > 0
    asterix(1,1:sizepass(2)) = '*';
    set(h,'String',asterix)
else
    set(h,'String','');
end %if
 
% Clears the variable "carrierlist" from the global workspace when the
% figure is deleted.
function del_function(hObject,event,data)
clear global carrierlist;
% delete(hObject);

% --- Creates and returns a handle to the GUI figure. 
function h1 = txtmsg_create_LayoutFcn(policy)
global carrierlist;
% policy - create a new figure or use a singleton. 'new' or 'reuse'.

persistent hsingleton;
if strcmpi(policy, 'reuse') & ishandle(hsingleton)
    h1 = hsingleton;
    return;
end

appdata = [];
appdata.GUIDEOptions = struct(...
    'active_h', [], ...
    'taginfo', struct(...
    'figure', 2, ...
    'text', 7, ...
    'edit', 7, ...
    'checkbox', 2, ...
    'pushbutton', 2), ...
    'override', 0, ...
    'release', 13, ...
    'resize', 'none', ...
    'accessibility', 'callback', ...
    'mfile', 1, ...
    'callbacks', 1, ...
    'singleton', 1, ...
    'syscolorfig', 1, ...
    'blocking', 0, ...
    'lastSavedFile', 'C:\Robert\Research\program_development\remote_notif\remote1_export.m');
appdata.lastValidTag = 'figure1';
appdata.GUIDELayoutEditor = [];

passw{1} = '';
passw{2} = '';

h1 = figure(...
'Units','characters',...
'Color',[0.925490196078431 0.913725490196078 0.847058823529412],...
'Colormap',[0 0 0.5625;0 0 0.625;0 0 0.6875;0 0 0.75;0 0 0.8125;0 0 0.875;0 0 0.9375;0 0 1;0 0.0625 1;0 0.125 1;0 0.1875 1;0 0.25 1;0 0.3125 1;0 0.375 1;0 0.4375 1;0 0.5 1;0 0.5625 1;0 0.625 1;0 0.6875 1;0 0.75 1;0 0.8125 1;0 0.875 1;0 0.9375 1;0 1 1;0.0625 1 1;0.125 1 0.9375;0.1875 1 0.875;0.25 1 0.8125;0.3125 1 0.75;0.375 1 0.6875;0.4375 1 0.625;0.5 1 0.5625;0.5625 1 0.5;0.625 1 0.4375;0.6875 1 0.375;0.75 1 0.3125;0.8125 1 0.25;0.875 1 0.1875;0.9375 1 0.125;1 1 0.0625;1 1 0;1 0.9375 0;1 0.875 0;1 0.8125 0;1 0.75 0;1 0.6875 0;1 0.625 0;1 0.5625 0;1 0.5 0;1 0.4375 0;1 0.375 0;1 0.3125 0;1 0.25 0;1 0.1875 0;1 0.125 0;1 0.0625 0;1 0 0;0.9375 0 0;0.875 0 0;0.8125 0 0;0.75 0 0;0.6875 0 0;0.625 0 0;0.5625 0 0],...
'IntegerHandle','off',...
'InvertHardcopy',get(0,'defaultfigureInvertHardcopy'),...
'MenuBar','none',...
'Name','TxtMsg Create',...
'NumberTitle','off',...
'PaperPosition',get(0,'defaultfigurePaperPosition'),...
'Position',[103.8 34 91.4 27.4615384615385],...
'Resize','off',...
'HandleVisibility','callback',...
'Tag','figure1',...
'UserData',passw,...
'Visible','on',...
'DeleteFcn',@del_function,...
'CreateFcn', {@local_CreateFcn, blanks(0), appdata} );


% set(h1,'UserData',passw);

appdata = [];
appdata.lastValidTag = 'text1';

h2 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',12,...
'FontWeight','bold',...
'HorizontalAlignment','left',...
'Position',[4.4 23 25.2 3],...
'String','GMail Address',...
'Style','text',...
'Tag','text1',...
'CreateFcn', {@local_CreateFcn, blanks(0), appdata} );

figcol = get(h2,'BackgroundColor');
set(h1,'Color',figcol);

appdata = [];
appdata.lastValidTag = 'text2';

h3 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',12,...
'FontWeight','bold',...
'HorizontalAlignment','left',...
'Position',[4.4 20.6153846153846 27.4 2.46153846153846],...
'String','GMail Password',...
'Style','text',...
'Tag','text2',...
'CreateFcn', {@local_CreateFcn, blanks(0), appdata} );

appdata = [];
appdata.lastValidTag = 'text3';

h4 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',12,...
'FontWeight','bold',...
'HorizontalAlignment','left',...
'Position',[4.4 14.4615384615385 30.2 3],...
'String','Cell Phone Carrier',...
'Style','text',...
'Tag','text3',...
'CreateFcn', {@local_CreateFcn, blanks(0), appdata} );

appdata = [];
appdata.lastValidTag = 'text4';

h5 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',12,...
'FontWeight','bold',...
'HorizontalAlignment','left',...
'Position',[4.4 8.3076923076923 30.2 3.23076923076923],...
'String',{  'Phone Number'; '(7 Digits)' },...
'Style','text',...
'Tag','text4',...
'CreateFcn', {@local_CreateFcn, blanks(0), appdata} );

appdata = [];
appdata.lastValidTag = 'text5';

h6 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',12,...
'FontWeight','bold',...
'HorizontalAlignment','left',...
'Position',[4.4 18.1538461538461 27.2 2.38461538461538],...
'String','Again',...
'Style','text',...
'Tag','text5',...
'CreateFcn', {@local_CreateFcn, blanks(0), appdata} );

appdata = [];
appdata.lastValidTag = 'edit1';

h7 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'BackgroundColor',[1 1 1],...
'FontSize',12,...
'FontWeight','bold',...
'Position',[42.4 23.9230769230769 42.8 2.07692307692308],...
'String',blanks(0),...
'Style','edit',...
'TooltipString','Enter Full Address',...
'CreateFcn', {@local_CreateFcn,  blanks(0), appdata} ,...
'Tag','gmail_address');

appdata = [];
appdata.lastValidTag = 'edit2';

h8 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'BackgroundColor',[1 1 1],...
'KeyPressfcn',@hidepass,...
'FontSize',12,...
'FontWeight','bold',...
'Position',[42.4 21 42.8 2.07692307692308],...
'String',blanks(0),...
'Style','edit',...
'TooltipString','GMail Password',...
'CreateFcn', {@local_CreateFcn,  blanks(0), appdata} ,...
'Tag','passwa');

appdata = [];
appdata.lastValidTag = 'edit3';

h9 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'BackgroundColor',[1 1 1],...
'KeyPressfcn',@hidepass,...
'FontSize',12,...
'FontWeight','bold',...
'Position',[42.4 18.4615384615385 42.8 2.07692307692308],...
'String',blanks(0),...
'Style','edit',...
'TooltipString','Password again for verification',...
'CreateFcn', {@local_CreateFcn,  blanks(0), appdata} ,...
'Tag','passwb');

appdata = [];
appdata.lastValidTag = 'edit4';

h10 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'BackgroundColor',[1 1 1],...
'FontSize',12,...
'FontWeight','bold',...
'Position',[42.4 15.3846153846154 42.8 2.07692307692308],...
'String',carrierlist.name,...
'Style','popupmenu',...
'TooltipString','Cell Phone Carrier',...
'Value',1,...
'CreateFcn', {@local_CreateFcn,  blanks(0)', appdata} ,...
'Tag','carrier_info');

appdata = [];
appdata.lastValidTag = 'edit5';

h11 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'BackgroundColor',figcol,...
'FontSize',10,...
'FontWeight','bold',...
'Position',[42.4 12.5384615384615 42.8 2.07692307692308],...
'String','Carrier Not Present',...
'Style','checkbox',...
'TooltipString','Check this if your cell carrier is not listed above',...
'CreateFcn', {@local_CreateFcn, blanks(0), appdata} ,...
'Tag','cellyesnocheckbox');

appdata = [];
appdata.lastValidTag = 'checkbox1';

h12 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'BackgroundColor',[1 1 1],...
'FontSize',12,...
'FontWeight','bold',...
'Position',[42.4 9.46153846153846 42.8 2.07692307692308],...
'String',blanks(0),...
'Style','edit',...
'TooltipString','7 Digits of cell phone number',...
'Tag','cellphonenumber',...
'CreateFcn', {@local_CreateFcn, blanks(0), appdata} );

appdata = [];
appdata.lastValidTag = 'text6';

h13 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',12,...
'FontWeight','bold',...
'HorizontalAlignment','left',...
'Position',[4.4 4.46153846153846 30.2 3],...
'String','User',...
'Style','text',...
'Tag','username_label',...
'CreateFcn', {@local_CreateFcn, blanks(0), appdata});

appdata = [];
appdata.lastValidTag = 'edit6';

h14 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'BackgroundColor',[1 1 1],...
'FontSize',12,...
'FontWeight','bold',...
'Position',[42.4 5.38461538461538 42.8 2.07692307692308],...
'String',blanks(0),...
'Style','edit',...
'TooltipString','username of the individual using this function',...
'CreateFcn', {@local_CreateFcn, blanks(0), appdata} ,...
'Tag','username');

appdata = [];
appdata.lastValidTag = 'pushbutton1';

h15 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback',@createfunction,...
'FontSize',12,...
'FontWeight','bold',...
'Position',[19.8 1.61538461538462 22.4 2.69230769230769],...
'String','Create!',...
'Tag','createbutton',...
'CreateFcn', {@local_CreateFcn, blanks(0), appdata} );

appdata = [];
appdata.lastValidTag = 'pushbutton2';

h16 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback',@createfunction,...
'FontSize',12,...
'FontWeight','bold',...
'Position',[49.8 1.61538461538462 22.4 2.69230769230769],...
'String','Test',...
'Tag','testbutton',...
'CreateFcn', {@local_CreateFcn, blanks(0), appdata} );

hsingleton = h1;
clear carrierlist

% --- Set application data first then calling the CreateFcn. 
function local_CreateFcn(hObject, eventdata, createfcn, appdata)

if ~isempty(appdata)
   names = fieldnames(appdata);
   for i=1:length(names)
       name = char(names(i));
       setappdata(hObject, name, getfield(appdata,name));
   end
end

if ~isempty(createfcn)
   eval(createfcn);
end


% --- Handles default GUIDE GUI creation and callback dispatch
function varargout = gui_mainfcn(gui_State, varargin)


%   GUI_MAINFCN provides these command line APIs for dealing with GUIs
%
%      REMOTE1_EXPORT, by itself, creates a new REMOTE1_EXPORT or raises the existing
%      singleton*.
%
%      H = REMOTE1_EXPORT returns the handle to a new REMOTE1_EXPORT or the handle to
%      the existing singleton*.
%
%      REMOTE1_EXPORT('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in REMOTE1_EXPORT.M with the given input arguments.
%
%      REMOTE1_EXPORT('Property','Value',...) creates a new REMOTE1_EXPORT or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before untitled_OpeningFunction gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to untitled_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".

%   Copyright 1984-2006 The MathWorks, Inc.
%   $Revision: 1.1.6.3 $ $Date: 2006/10/10 02:22:41 $

gui_StateFields =  {'gui_Name'
    'gui_Singleton'
    'gui_OpeningFcn'
    'gui_OutputFcn'
    'gui_LayoutFcn'
    'gui_Callback'};
gui_Mfile = '';
for i=1:length(gui_StateFields)
    if ~isfield(gui_State, gui_StateFields{i})
        error('MATLAB:gui_mainfcn:FieldNotFound', 'Could not find field %s in the gui_State struct in GUI M-file %s', gui_StateFields{i}, gui_Mfile);
    elseif isequal(gui_StateFields{i}, 'gui_Name')
        gui_Mfile = [gui_State.(gui_StateFields{i}), '.m'];
    end
end

numargin = length(varargin);

if numargin == 0
    % REMOTE1_EXPORT
    % create the GUI only if we are not in the process of loading it
    % already
    gui_Create = true;
elseif local_isInvokeActiveXCallback(gui_State, varargin{:})
    % REMOTE1_EXPORT(ACTIVEX,...)
    vin{1} = gui_State.gui_Name;
    vin{2} = [get(varargin{1}.Peer, 'Tag'), '_', varargin{end}];
    vin{3} = varargin{1};
    vin{4} = varargin{end-1};
    vin{5} = guidata(varargin{1}.Peer);
    feval(vin{:});
    return;
elseif local_isInvokeHGCallbak(gui_State, varargin{:})
    % REMOTE1_EXPORT('CALLBACK',hObject,eventData,handles,...)
    gui_Create = false;
else
    % REMOTE1_EXPORT(...)
    % create the GUI and hand varargin to the openingfcn
    gui_Create = true;
end

if ~gui_Create
    % In design time, we need to mark all components possibly created in
    % the coming callback evaluation as non-serializable. This way, they
    % will not be brought into GUIDE and not be saved in the figure file
    % when running/saving the GUI from GUIDE.
    designEval = false;
    if (numargin>1 && ishghandle(varargin{2}))
        fig = varargin{2};
        while ~isempty(fig) && ~isa(handle(fig),'figure')
            fig = get(fig,'parent');
        end
        
        designEval = isappdata(0,'CreatingGUIDEFigure') || isprop(fig,'__GUIDEFigure');
    end
        
    if designEval
        beforeChildren = findall(fig);
    end
    
    % evaluate the callback now
    varargin{1} = gui_State.gui_Callback;
    if nargout
        [varargout{1:nargout}] = feval(varargin{:});
    else       
        feval(varargin{:});
    end
    
    % Set serializable of objects created in the above callback to off in
    % design time. Need to check whether figure handle is still valid in
    % case the figure is deleted during the callback dispatching.
    if designEval && ishandle(fig)
        set(setdiff(findall(fig),beforeChildren), 'Serializable','off');
    end
else
    if gui_State.gui_Singleton
        gui_SingletonOpt = 'reuse';
    else
        gui_SingletonOpt = 'new';
    end

    % Check user passing 'visible' P/V pair first so that its value can be
    % used by oepnfig to prevent flickering
    gui_Visible = 'auto';
    gui_VisibleInput = '';
    for index=1:2:length(varargin)
        if length(varargin) == index || ~ischar(varargin{index})
            break;
        end

        % Recognize 'visible' P/V pair
        len1 = min(length('visible'),length(varargin{index}));
        len2 = min(length('off'),length(varargin{index+1}));
        if ischar(varargin{index+1}) && strncmpi(varargin{index},'visible',len1) && len2 > 1
            if strncmpi(varargin{index+1},'off',len2)
                gui_Visible = 'invisible';
                gui_VisibleInput = 'off';
            elseif strncmpi(varargin{index+1},'on',len2)
                gui_Visible = 'visible';
                gui_VisibleInput = 'on';
            end
        end
    end
    
    % Open fig file with stored settings.  Note: This executes all component
    % specific CreateFunctions with an empty HANDLES structure.

    
    % Do feval on layout code in m-file if it exists
    gui_Exported = ~isempty(gui_State.gui_LayoutFcn);
    % this application data is used to indicate the running mode of a GUIDE
    % GUI to distinguish it from the design mode of the GUI in GUIDE. it is
    % only used by actxproxy at this time.   
    setappdata(0,genvarname(['OpenGuiWhenRunning_', gui_State.gui_Name]),1);
    if gui_Exported
        gui_hFigure = feval(gui_State.gui_LayoutFcn, gui_SingletonOpt);
        % openfig (called by local_openfig below) does this for guis without
        % the LayoutFcn. Be sure to do it here so guis show up on screen.
        movegui(gui_hFigure,'onscreen');
    else
        gui_hFigure = local_openfig(gui_State.gui_Name, gui_SingletonOpt, gui_Visible);
        % If the figure has InGUIInitialization it was not completely created
        % on the last pass.  Delete this handle and try again.
        if isappdata(gui_hFigure, 'InGUIInitialization')
            delete(gui_hFigure);
            gui_hFigure = local_openfig(gui_State.gui_Name, gui_SingletonOpt, gui_Visible);
        end
    end
    rmappdata(0,genvarname(['OpenGuiWhenRunning_', gui_State.gui_Name]));

    % Set flag to indicate starting GUI initialization
    setappdata(gui_hFigure,'InGUIInitialization',1);

    % Fetch GUIDE Application options
    gui_Options = getappdata(gui_hFigure,'GUIDEOptions');
    % Singleton setting in the GUI M-file takes priority if different
    gui_Options.singleton = gui_State.gui_Singleton;

    if ~isappdata(gui_hFigure,'GUIOnScreen')
        % Adjust background color
        if gui_Options.syscolorfig
            set(gui_hFigure,'Color', get(0,'DefaultUicontrolBackgroundColor'));
        end

        % Generate HANDLES structure and store with GUIDATA. If there is
        % user set GUI data already, keep that also.
        data = guidata(gui_hFigure);
        handles = guihandles(gui_hFigure);
        if ~isempty(handles)
            if isempty(data)
                data = handles;
            else
                names = fieldnames(handles);
                for k=1:length(names)
                    data.(char(names(k)))=handles.(char(names(k)));
                end
            end
        end
        guidata(gui_hFigure, data);
    end

    % Apply input P/V pairs other than 'visible'
    for index=1:2:length(varargin)
        if length(varargin) == index || ~ischar(varargin{index})
            break;
        end

        len1 = min(length('visible'),length(varargin{index}));
        if ~strncmpi(varargin{index},'visible',len1)
            try set(gui_hFigure, varargin{index}, varargin{index+1}), catch break, end
        end
    end

    % If handle visibility is set to 'callback', turn it on until finished
    % with OpeningFcn
    gui_HandleVisibility = get(gui_hFigure,'HandleVisibility');
    if strcmp(gui_HandleVisibility, 'callback')
        set(gui_hFigure,'HandleVisibility', 'on');
    end

    feval(gui_State.gui_OpeningFcn, gui_hFigure, [], guidata(gui_hFigure), varargin{:});

    if isscalar(gui_hFigure) && ishandle(gui_hFigure)
        % Update handle visibility
        set(gui_hFigure,'HandleVisibility', gui_HandleVisibility);

        % Call openfig again to pick up the saved visibility or apply the
        % one passed in from the P/V pairs
        if ~gui_Exported
            gui_hFigure = local_openfig(gui_State.gui_Name, 'reuse',gui_Visible);
        elseif ~isempty(gui_VisibleInput)
            set(gui_hFigure,'Visible',gui_VisibleInput);
        end
        if strcmpi(get(gui_hFigure, 'Visible'), 'on')
            figure(gui_hFigure);
            
            if gui_Options.singleton
                setappdata(gui_hFigure,'GUIOnScreen', 1);
            end
        end

        % Done with GUI initialization
        rmappdata(gui_hFigure,'InGUIInitialization');
    end

    % If handle visibility is set to 'callback', turn it on until finished with
    % OutputFcn
    if isscalar(gui_hFigure) && ishandle(gui_hFigure)
        gui_HandleVisibility = get(gui_hFigure,'HandleVisibility');
        if strcmp(gui_HandleVisibility, 'callback')
            set(gui_hFigure,'HandleVisibility', 'on');
        end
        gui_Handles = guidata(gui_hFigure);
    else
        gui_Handles = [];
    end

    if nargout
        [varargout{1:nargout}] = feval(gui_State.gui_OutputFcn, gui_hFigure, [], gui_Handles);
    else
        feval(gui_State.gui_OutputFcn, gui_hFigure, [], gui_Handles);
    end

    if isscalar(gui_hFigure) && ishandle(gui_hFigure)
        set(gui_hFigure,'HandleVisibility', gui_HandleVisibility);
    end
end

function gui_hFigure = local_openfig(name, singleton, visible)

% openfig with three arguments was new from R13. Try to call that first, if
% failed, try the old openfig.
if nargin('openfig') == 2
    % OPENFIG did not accept 3rd input argument until R13,
    % toggle default figure visible to prevent the figure
    % from showing up too soon.
    gui_OldDefaultVisible = get(0,'defaultFigureVisible');
    set(0,'defaultFigureVisible','off');
    gui_hFigure = openfig(name, singleton);
    set(0,'defaultFigureVisible',gui_OldDefaultVisible);
else
    gui_hFigure = openfig(name, singleton, visible);
end

function result = local_isInvokeActiveXCallback(gui_State, varargin)

try
    result = ispc && iscom(varargin{1}) ...
             && isequal(varargin{1},gcbo);
catch
    result = false;
end

function result = local_isInvokeHGCallbak(gui_State, varargin)

try
    fhandle = functions(gui_State.gui_Callback);
    result = ~isempty(findstr(gui_State.gui_Name,fhandle.file)) || ...
             (ischar(varargin{1}) ...
             && isequal(ishandle(varargin{2}), 1) ...
             && ~isempty(strfind(varargin{1},[get(varargin{2}, 'Tag'), '_'])));
catch
    result = false;
end

Contact us at files@mathworks.com