function varargout = modsimrand(varargin)
% MODSIMRAND - Using MATLAB as a test bench for PN generator.
%   MODSIMRAND opens a GUI that demonstrates how to visualize a
%   ModelSim VHDL model using MATLAB.  This demo requires a temporary
%   directory to generate a working ModelSim VHDL project.  After
%   creating the VHDL project, this demo starts ModelSim (this 
%   requires access to ModelSim from the command line).  Furthermore,
%   the project is compiled and the hardware simulation is run.
%   (Resolution limit is set to 1 nsec).  
%
% See also: HDLDAEMON

%   Copyright 2003-2011 The MathWorks, Inc.
%     

% Last Modified by GUIDE v2.5 25-Jun-2003 17:50:23

% Begin initialization code - DO NOT EDIT

gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @modsimrand_OpeningFcn, ...
                   'gui_OutputFcn',  @modsimrand_OutputFcn, ...
                   'gui_LayoutFcn',  @modsimrand_LayoutFcn, ...
                   'gui_Callback',   []);
if nargin & isstr(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% names
function n = demo_name;     n = mfilename;
function n = callback_name; n = [demo_name '_plot'];
function n = tmpdir_name;   n = demo_name; %'tmpdir_name';
function n = dofile_name;   n = demo_name; %'dofile_name';
function n = srcdir_name;   n = demo_name; %'srcdir_name';

function n = tempworkdir
if strcmp(computer,'PCWIN'),
    n = tempdir;
else
    n = tempname;
end

function lang = get_language(handles)
langVal = get(handles.languagepopup,'Value');
langStr = get(handles.languagepopup,'String');
lang = langStr{langVal};

% --- Executes just before modsimrand is made visible.
function modsimrand_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 modsimrand (see VARARGIN)

% Choose default command line output for modsimrand
handles.output = hObject;
set(handles.projdiretext,'String',tempworkdir);
% Update handles structure
guidata(hObject, handles);

% This sets up the initial plot - only do when we are invisible
% so window can get raised using modsimrand.
%if strcmp(get(hObject,'Visible'),'off')
fixtag = get(handles.StartupPlot,'Tag');
axes(handles.StartupPlot);
plot([1 1]);
title('PN Sequence Startup');
xlabel('Time (# simulator steps)');
set(handles.StartupPlot,'Tag',fixtag);

fixtag = get(handles.HistoPlot,'Tag');
edges = linspace(0,2^32,26);
axes(handles.HistoPlot);
% bar(edges,zeros(1,26),'histc');
bar(edges,zeros(1,26),'histc')
title('Histogram of PN Sequence');
xlabel('Bins of generated random numbers');
set(handles.HistoPlot,'Tag',fixtag);

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

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


% --- Executes on button press in tempbutton.
function tempbutton_Callback(hObject, eventdata, handles)
% hObject    handle to tempbutton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.projdiretext,'string',tempworkdir);

% --- Executes during object creation, after setting all properties.
function projdiretext_CreateFcn(hObject, eventdata, handles)
% hObject    handle to projdiretext (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
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

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

% Hints: get(hObject,'String') returns contents of projdiretext as text
%        str2double(get(hObject,'String')) returns contents of projdiretext as a double
set(handles.projdiretext,'Value',4);

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

% --- Executes during object creation, after setting all properties.
function portnumberetext_CreateFcn(hObject, eventdata, handles)
% hObject    handle to portnumberetext (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
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

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

% Hints: get(hObject,'String') returns contents of portnumberetext as text
%        str2double(get(hObject,'String')) returns contents of portnumberetext as a double
% WISH: error handling here is not as robust as it could be.
port = eval(get(hObject,'String'));
if isnumeric(port),
    port = round(port);
    if port < 0 || port > 66535,
        msg = {['Specified TCP/IP port number: ''' num2str(port) ''' is illegal.'],...
                'Please select an unused value from 1024 to 49151,',...
                'or select 0 to let the computer choose the port number.' };
        errordlg(msg,'Port Selection Error','modal')
        port = get(hObject,'UserData');       % Reset to old value
        set(hObject,'String',num2str(port));
    else
        if port ~= 0 && (port < 1024  || port > 49151),
            msg = {['Specified TCP/IP port number: ''' num2str(port) ''' is not recommended.'],...
                    'Please select an unused value from 1024 to 49151,',...
                    'or select 0 to let the computer choose the port number.' };
            warndlg(msg,'Port Selection Warning','modal')
        end
        % store port number on UserData.  This should always match the
        % String in the edit box (ie, we don't plug in the actual port
        % if the user requests 0)
        set(hObject,'UserData',port);
        % This should only change the contents of the edit box if we
        % had to round the number
        set(hObject,'String',num2str(port));    
    end
else
    % WISH: handle non-numeric entry
end

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

directory_name = uigetdir(get(handles.projdiretext,'String'),'Select VHDL Project Directory');
if( ~isnumeric(directory_name) ) 
    set(handles.projdiretext,'String',directory_name)
end
    

% --- Executes when user attempts to close ModsimrandFig.
function ModsimrandFig_CloseRequestFcn(hObject, eventdata, handles)
% hObject    handle to ModsimrandFig (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: delete(hObject) closes the figure
delete(hObject);


% --- Executes during object creation, after setting all properties.
function dirselectpopup_CreateFcn(hObject, eventdata, handles)
% hObject    handle to dirselectpopup (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
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end


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

% Hint: get(hObject,'Value') returns toggle state of SharedMemory
h = [handles.portnumberetext handles.text2 handles.text2a];
if get(hObject,'value'),
    set(h,'Enable','off');  % Disable button and labels
else
    set(h,'Enable','on');   % Enable button and labels
end


% --- Executes on button press in browsebutton.
function browsebutton_Callback(hObject, eventdata, handles)
% hObject    handle to browsebutton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
directory_name = uigetdir(get(handles.projdiretext,'String'),'Select VHDL Project Directory');
if( ~isnumeric(directory_name) ),
    set(handles.projdiretext,'String',directory_name);
end


% --- Executes on button press in editbutton.
function editbutton_Callback(hObject, eventdata, handles)
% hObject    handle to browsebutton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
edit(fullfile(matlabroot,'toolbox','edalink','extensions','modelsim','modelsimdemos',[callback_name '.m']));

% --- Executes on selection in languagepopup_Callback.
function languagepopup_Callback(hObject, eventdata, handles)
% hObject    handle to browsebutton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
string = get(hObject,'String');
value = get(hObject,'Value');

% --- Executes on button press in startbutton.
function startbutton_Callback(hObject, eventdata, handles)
% hObject    handle to startbutton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
%
% Start hdldaemon and configure <callback_name>.m
disp('To enable access from ModelSim, HDLDaemon is used with appropriate link settings.');
disp('The following messages are produced by HDLDaemon to indicate link status ...');
if get(handles.SharedMemory,'value')
    % shared memory
    dstatus = hdldaemon('status');
    if isempty(dstatus)
        % not running - start it
        dstatus = hdldaemon;
    elseif strcmp(dstatus.comm,'shared memory')
        % already running
        % user knows what's happening from previous hdldaemon('status')
        if strcmp(computer,'GLNX86'),
            hdldaemon('kill');
            dstatus = hdldaemon;
        end
    elseif strcmp(dstatus.comm,'sockets')
        % running with different comm - stop and restart it
        disp('Shutting down HDLDaemon to restart it with shared memory');
        hdldaemon('kill');
        dstatus = hdldaemon;
    else
        error(message('HDLLink:modsimrand:InvalidDaemonStatus'));
    end
    vsim_comm = '';
else
    % sockets
    dstatus = hdldaemon('status');
    portnum = get(handles.portnumberetext,'UserData');
    if isempty(dstatus)
        % not running - start it
        dstatus = hdldaemon('socket',portnum);
    elseif strcmp(dstatus.comm,'shared memory')
        % running with different comm - stop and restart it
        disp('Shutting down HDLDaemon to restart it with sockets');
        hdldaemon('kill');
        dstatus = hdldaemon('socket',portnum);
    elseif strcmp(dstatus.comm,'sockets')
        % are we running on the same port?
        if portnum == 0 || portnum == str2num(dstatus.ipc_id)
            % either user doesn't care or requested same port
            % leave server running
            if strcmp(computer,'GLNX86'),
                hdldaemon('kill');
                dstatus = hdldaemon('socket',portnum);
            end
        else
            % different port - stop and restart it
            disp('Shutting down HDLDaemon to restart it with different port number');
            hdldaemon('kill');
            dstatus = hdldaemon('socket',portnum);
        end                
    else
        error(message('HDLLink:modsimrand:InvalidReturnStatus'));
    end
    % dstatus should be current
    vsim_comm = ['-socket ' dstatus.ipc_id];
end

% set up project directory and construct '.do' file
projdirbase = get(handles.projdiretext,'String');
warning off MATLAB:MKDIR:DirectoryExists
mkdir(projdirbase,tmpdir_name);
warning on MATLAB:MKDIR:DirectoryExists
projdir = fullfile(projdirbase,tmpdir_name);
projdofile = fullfile(projdir,[dofile_name '.do']);
unixprojdir =  [ '"' strrep(projdir,'\','/') '"']; 
switch get_language(handles)
    case 'VHDL'
        entity_name = demo_name;
        srcfile = fullfile(matlabroot,'toolbox','edalink','extensions','modelsim','modelsimdemos','vhdl',srcdir_name, [entity_name '.vhd']);
        srcfile = ['"' strrep(srcfile,'\','/') '"'];   
        build = {...
                ['vcom -performdefaultbinding ' srcfile],...
            };
    case 'Verilog' 
        entity_name = demo_name;
        srcfile = fullfile(matlabroot,'toolbox','edalink','extensions','modelsim','modelsimdemos','vlog',srcdir_name, [entity_name '.v']);
        srcfile = ['"' strrep(srcfile,'\','/') '"'];   
        build = {...
                ['vlog ' srcfile],...
            };
    otherwise
        error(message('HDLLink:modsimrand:InvalidLanguage'));
end

tclstart = {...
        ['cd ' unixprojdir],...
        'vlib work',...
        build{:},...
        ['vsimmatlab  work.' entity_name ],...   %% By default, start
        ['matlabtb ' entity_name ' -mfunc ' callback_name ' -rising /' entity_name '/clk ' vsim_comm],...
        ['force sim:/' entity_name '/clk 0 0,1 5 ns -repeat 10 ns']...
        ['force sim:/' entity_name '/clk_en 1'],...
        ['force sim:/' entity_name '/reset 1 0,0 50 ns'],...
        'run 80000',...
    };

 % Disable gui features
 hdisables = [hObject, ...
             handles.browsebutton, ...
             handles.portnumberetext, ...
             handles.projdiretext, ...
             handles.SharedMemory, ...
             handles.languagepopup];
set(hdisables,'Enable','off');

% finally: start simulation
vsim('tclstart',tclstart,'startupfile',projdofile);

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

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

h1 = figure(...
'Units','characters',...
'CloseRequestFcn','modsimrand(''ModsimrandFig_CloseRequestFcn'',gcf,[],guidata(gcf))',...
'Color',[0.831372549019608 0.815686274509804 0.784313725490196],...
'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],...
'DoubleBuffer','on',...
'InvertHardcopy',get(0,'defaultfigureInvertHardcopy'),...
'MenuBar','none',...
'Name','modsimrand',...
'NumberTitle','off',...
'PaperPosition',get(0,'defaultfigurePaperPosition'),...
'Position',[74 38 127 51],...
'Visible','off',...
'Renderer',get(0,'defaultfigureRenderer'),...
'RendererMode','manual',...
'Resize','off',...
'Tag','ModsimrandFig',...
'UserData',zeros(1,0));

movegui(h1);    % ensure gui is onscreen, regardless of resolution
set(h1,'Visible','on');

setappdata(h1, 'GUIDEOptions', struct(...
'active_h', 1, ...
'taginfo', struct(...
'figure', 2, ...
'axes', 3, ...
'pushbutton', 6, ...
'popupmenu', 3, ...
'togglebutton', 2, ...
'text', 7, ...
'edit', 3, ...
'frame', 2, ...
'checkbox', 2), ...
'override', 1, ...
'release', 13, ...
'resize', 'none', ...
'accessibility', 'on', ...
'mfile', 1, ...
'callbacks', 1, ...
'singleton', 1, ...
'syscolorfig', 1));

h2 = axes(...
'Parent',h1,...
'ALim',get(0,'defaultaxesALim'),...
'ALimMode','manual',...
'CameraPosition',[0.5 0.5 9.16025403784439],...
'CameraPositionMode','manual',...
'CameraTarget',[0.5 0.5 0.5],...
'CameraTargetMode','manual',...
'CameraUpVector',[0 1 0],...
'CameraUpVectorMode','manual',...
'CameraViewAngle',6.60861036031192,...
'CameraViewAngleMode','manual',...
'CLim',get(0,'defaultaxesCLim'),...
'CLimMode','manual',...
'Color',get(0,'defaultaxesColor'),...
'ColorOrder',get(0,'defaultaxesColorOrder'),...
'DataAspectRatio',get(0,'defaultaxesDataAspectRatio'),...
'DataAspectRatioMode','manual',...
'PlotBoxAspectRatio',get(0,'defaultaxesPlotBoxAspectRatio'),...
'PlotBoxAspectRatioMode','manual',...
'Position',[0.0737833594976452 0.45166163141994 0.676609105180534 0.253776435045317],...
'TickDir',get(0,'defaultaxesTickDir'),...
'TickDirMode','manual',...
'XColor',get(0,'defaultaxesXColor'),...
'XLim',get(0,'defaultaxesXLim'),...
'XLimMode','manual',...
'XTick',[0 0.2 0.4 0.6 0.8 1],...
'XTickLabel',{ '0  ' '0.2' '0.4' '0.6' '0.8' '1  ' },...
'XTickLabelMode','manual',...
'XTickMode','manual',...
'YColor',get(0,'defaultaxesYColor'),...
'YLim',get(0,'defaultaxesYLim'),...
'YLimMode','manual',...
'YTick',[0 0.2 0.4 0.6 0.8 1],...
'YTickLabel',{ '0  ' '0.2' '0.4' '0.6' '0.8' '1  ' },...
'YTickLabelMode','manual',...
'YTickMode','manual',...
'ZColor',get(0,'defaultaxesZColor'),...
'ZLim',get(0,'defaultaxesZLim'),...
'ZLimMode','manual',...
'ZTick',[0 0.5 1],...
'ZTickLabel','',...
'ZTickLabelMode','manual',...
'ZTickMode','manual',...
'Tag','StartupPlot',...
'UserData',999234);


h3 = get(h2,'title');

set(h3,...
'Parent',h2,...
'Color',[0 0 0],...
'HorizontalAlignment','center',...
'Position',[0.494047619047619 1.03869047619048 1.00005459937205],...
'VerticalAlignment','bottom',...
'HandleVisibility','off');

h4 = get(h2,'xlabel');

set(h4,...
'Parent',h2,...
'Color',[0 0 0],...
'HorizontalAlignment','center',...
'Position',[0.494047619047619 -0.139880952380953 1.00005459937205],...
'VerticalAlignment','cap',...
'HandleVisibility','off');

h5 = get(h2,'ylabel');

set(h5,...
'Parent',h2,...
'Color',[0 0 0],...
'HorizontalAlignment','center',...
'Position',[-0.172619047619048 0.491071428571429 1.00005459937205],...
'Rotation',90,...
'VerticalAlignment','bottom',...
'HandleVisibility','off');

h6 = get(h2,'zlabel');

set(h6,...
'Parent',h2,...
'Color',[0 0 0],...
'HorizontalAlignment','right',...
'Position',[-1.06547619047619 2.15178571428571 1.00005459937205],...
'HandleVisibility','off',...
'Visible','off');

h7 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'ListboxTop',0,...
'Position',[0.8 38.6153846153846 125 11.8461538461538],...
'String',{ '' },...
'Style','frame',...
'Tag','frame1');


h8 = axes(...
'Parent',h1,...
'ALim',get(0,'defaultaxesALim'),...
'ALimMode','manual',...
'CameraPosition',[0.5 0.5 9.16025403784439],...
'CameraPositionMode','manual',...
'CameraTarget',[0.5 0.5 0.5],...
'CameraTargetMode','manual',...
'CameraUpVector',[0 1 0],...
'CameraUpVectorMode','manual',...
'CameraViewAngle',6.60861036031192,...
'CameraViewAngleMode','manual',...
'CLim',get(0,'defaultaxesCLim'),...
'CLimMode','manual',...
'Color',get(0,'defaultaxesColor'),...
'ColorOrder',get(0,'defaultaxesColorOrder'),...
'DataAspectRatio',get(0,'defaultaxesDataAspectRatio'),...
'DataAspectRatioMode','manual',...
'PlotBoxAspectRatio',get(0,'defaultaxesPlotBoxAspectRatio'),...
'PlotBoxAspectRatioMode','manual',...
'Position',[0.0737833594976452 0.0740181268882175 0.668759811616955 0.253776435045317],...
'TickDir',get(0,'defaultaxesTickDir'),...
'TickDirMode','manual',...
'XColor',get(0,'defaultaxesXColor'),...
'XLim',get(0,'defaultaxesXLim'),...
'XLimMode','manual',...
'XTick',[0 0.2 0.4 0.6 0.8 1],...
'XTickLabel',{ '0  ' '0.2' '0.4' '0.6' '0.8' '1  ' },...
'XTickLabelMode','manual',...
'XTickMode','manual',...
'YColor',get(0,'defaultaxesYColor'),...
'YLim',get(0,'defaultaxesYLim'),...
'YLimMode','manual',...
'YTick',[0 0.2 0.4 0.6 0.8 1],...
'YTickLabel',{ '0  ' '0.2' '0.4' '0.6' '0.8' '1  ' },...
'YTickLabelMode','manual',...
'YTickMode','manual',...
'ZColor',get(0,'defaultaxesZColor'),...
'ZLim',get(0,'defaultaxesZLim'),...
'ZLimMode','manual',...
'ZTick',[0 0.5 1],...
'ZTickLabel','',...
'ZTickLabelMode','manual',...
'ZTickMode','manual',...
'Tag','HistoPlot',...
'UserData',zeros(1,0));


h9 = get(h8,'title');

set(h9,...
'Parent',h8,...
'Color',[0 0 0],...
'HorizontalAlignment','center',...
'Position',[0.49702380952381 1.03869047619048 1.00005459937205],...
'VerticalAlignment','bottom',...
'HandleVisibility','off');

h10 = get(h8,'xlabel');

set(h10,...
'Parent',h8,...
'Color',[0 0 0],...
'HorizontalAlignment','center',...
'Position',[0.49702380952381 -0.139880952380952 1.00005459937205],...
'VerticalAlignment','cap',...
'HandleVisibility','off');

h11 = get(h8,'ylabel');

set(h11,...
'Parent',h8,...
'Color',[0 0 0],...
'HorizontalAlignment','center',...
'Position',[-0.169642857142857 0.491071428571429 1.00005459937205],...
'Rotation',90,...
'VerticalAlignment','bottom',...
'HandleVisibility','off');

h12 = get(h8,'zlabel');

set(h12,...
'Parent',h8,...
'Color',[0 0 0],...
'HorizontalAlignment','right',...
'Position',[-1.05059523809524 3.63988095238095 1.00005459937205],...
'HandleVisibility','off',...
'Visible','off');

% s: space
% b: button width
% w: frame width
b1 = .25;
b2 = .15;
s = (1 - 2 * b1 - b2)/4;
p1 = [ s                0.77 b1 0.05 ];
p2 = [ 2*s + b1         0.77 b2 0.05 ];
p3 = [ 3*s + b1 + b2    0.77 b1 0.05 ];

% 'Start' button
h13 = uicontrol(...
'Parent',h1,...
'Units','normalized',...
'Callback','modsimrand(''startbutton_Callback'',gcbo,[],guidata(gcbo))',...
'CData',[],...%See g1018175
'FontSize',10,...
'ListboxTop',0,...
'Position',p1,...
'String','Start simulation',...
'Tag','startbutton',...
'UserData',zeros(1,0));

% 'Edit callback' button
h13a = uicontrol(...
'Parent',h1,...
'Units','normalized',...
'Callback','modsimrand(''editbutton_Callback'',gcbo,[],guidata(gcbo))',...
'CData',[],...%See g1018175
'FontSize',10,...
'ListboxTop',0,...
'Position',p3,...
'String','View callback MATLAB function',...
'Tag','editbutton',...
'UserData',zeros(1,0));

% 'Language' popup
h13b = uicontrol(...
'Parent',h1,...
'Units','normalized',...
'Callback','modsimrand(''languagepopup_Callback'',gcbo,[],guidata(gcbo))',...
'CData',[],...%See g1018175
'FontSize',10,...
'ListboxTop',0,...
'Position',p2,...
'String',{'VHDL', 'Verilog'},...
'Enable','on',...
'Style','popupmenu',...
'Tag','languagepopup',...
'UserData',zeros(1,0));

if ispc
    set(h13b,'BackgroundColor','white');
else
    set(h13b,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

h14 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'BackgroundColor',[1 1 1],...
'Callback','modsimrand(''projdiretext_Callback'',gcbo,[],guidata(gcbo))',...
'FontSize',9,...
'HorizontalAlignment','left',...
'ListboxTop',0,...
'Position',[2.8 46.7692307692308 104.8 1.69230769230769],...
'String','- Demo Project Directory - ',...
'Style','edit',...
'CreateFcn','modsimrand(''projdiretext_CreateFcn'',gcbo,[],guidata(gcbo))',...
'Tag','projdiretext');


% 'Position',[26.8 + 6 42.5384615384615 14.6 1.61538461538462],...
    
h15 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'BackgroundColor',[1 1 1],...
'Callback','modsimrand(''portnumberetext_Callback'',gcbo,[],guidata(gcbo))',...
'Enable','off',...
'FontSize',9,...
'HorizontalAlignment','left',...
'ListboxTop',0,...
'Position',[26.8 - 6 42.5384615384615 14.6 1.61538461538462],...
'String','0',...
'Style','edit',...
'CreateFcn','modsimrand(''portnumberetext_CreateFcn'',gcbo,[],guidata(gcbo))',...
'Tag','portnumberetext',...
'UserData',0);


% 'String','Port number or service:',...
% 'Position',[4 42.6153846153846 23.2 + 5 1.38461538461538 ],...
    
h16 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',10,...
'Enable','off',...
'ListboxTop',0,...
'Position',[4 42.6153846153846 23.2 - 7 1.38461538461538 ],...
'String','Port number:',...
'HorizontalAlignment', 'left',...
'Style','text',...
'Tag','text2');

% 'Position',[49 42.6153846153846 23.2 + 30 1.38461538461538 ],...
h16a = uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',10,...
'Enable','off',...
'ListboxTop',0,...
'Position',[37 42.6153846153846 23.2 + 30 1.38461538461538 ],...
'String','(Enter 0 to let computer choose port number)',...
'HorizontalAlignment', 'left',...
'Style','text',...
'Tag','text2a');


h17 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',10,...
'HorizontalAlignment','left',...
'ListboxTop',0,...
'Position',[99.8 20.8461538461538 26 12],...
'String',{ 'Plots the integer ' 'values produced ' 'during the first ' '2400 cycles after ' 'a reset.  ' '' },...
'Style','text',...
'Tag','text3');


h18 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',10,...
'HorizontalAlignment','left',...
'ListboxTop',0,...
'Position',[99.8 3.38461538461539 26 12.6923076923077],...
'String',{ 'Plots the distribution' 'of values produced' 'by the generator after ' 'the startup period. ' 'This will approach' '(statistically) a flat' 'response for a good ' 'PN generator.' '' },...
'Style','text',...
'Tag','text4');


h19 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'FontSize',10,...
'HorizontalAlignment','left',...
'ListboxTop',0,...
'Position',[2.8 48.5384615384615 47.2 1.53846153846154],...
'String','Generate VHDL project in directory:',...
'Style','text',...
'Tag','text5');


h20 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback','modsimrand(''SharedMemory_Callback'',gcbo,[],guidata(gcbo))',...
'FontSize',10,...
'ListboxTop',0,...
'Position',[4 44.3846153846154 66.2 2.07692307692308],...
'String','Shared memory',...
'Style','checkbox',...
'Value',1,...
'Tag','SharedMemory');


h21 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback','modsimrand(''browsebutton_Callback'',gcbo,[],guidata(gcbo))',...
'ListboxTop',0,...
'Position',[108.6 46.7692307692308 14 1.84615384615385],...
'String','Browse',...
'Tag','browsebutton');



hsingleton = h1;


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

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(message('HDLLink:modsimrand:CannotFindField', gui_StateFields{ i }, gui_Mfile));        
    elseif isequal(gui_StateFields{i}, 'gui_Name')
        gui_Mfile = [getfield(gui_State, gui_StateFields{i}), '.m'];
    end
end

numargin = length(varargin);

gui_Create = 0;
if numargin == 0
    % MODSIMRAND (no ags)
    % do create
    gui_Create = 1;
elseif numargin == 1
    % MODSIMRAND('Function')
    if ~ischar(varargin{1})
        error(message('HDLLink:modsimrand:InvalidArgument', gui_State.gui_Name, gui_State.gui_Name));
    else
        % use feval below to call this string as a callback
    end
elseif numargin > 1
    % MODSIMRAND('Param', Value)
    % MODSIMRAND('Callback', hObject, ...)
    if ~ischar(varargin{1})
        error(message('HDLLink:modsimrand:InvalidArgument', gui_State.gui_Name, gui_State.gui_Name));
    end
    if ~ishandle(varargin{2})
        % do create with p/v pairs
        gui_Create = 1;
    end
end

if gui_Create == 0
    varargin{1} = gui_State.gui_Callback;
    if nargout
        [varargout{1:nargout}] = feval(varargin{:});
    else
        feval(varargin{:});
    end
else
    % check for an even number of input args if any were specified
    if mod(numargin,2)
        error(message('HDLLink:modsimrand:PropertyPair', [ gui_State.gui_Name, '.m' ]));
    end
    
    if gui_State.gui_Singleton
        gui_SingletonOpt = 'reuse';
    else
        gui_SingletonOpt = 'new';
    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 script if it exists
    if ~isempty(gui_State.gui_LayoutFcn)
        gui_hFigure = feval(gui_State.gui_LayoutFcn, gui_SingletonOpt);
    else
        if nargin('openfig')==3 
            gui_hFigure = openfig(gui_State.gui_Name, gui_SingletonOpt, 'invisible');            
            if isappdata(gui_hFigure, 'InGUIInitialization')
                delete(gui_hFigure);
                gui_hFigure = openfig(gui_State.gui_Name, gui_SingletonOpt, 'invisible');            
            end
        else
            % OPENFIG did not accept extra input options until R13,
            % shuffle default figure visible to prevent the figure
            % from showing up too soon.
            gui_OldDefaultVisible = get(0,'defaultFigureVisible');
            set(0,'defaultFigureVisible','off');
            gui_hFigure = openfig(gui_State.gui_Name, gui_SingletonOpt);
            if isappdata(gui_hFigure, 'InGUIInitialization')
                delete(gui_hFigure);
                gui_hFigure = openfig(gui_State.gui_Name, gui_SingletonOpt);            
            end
            set(0,'defaultFigureVisible',gui_OldDefaultVisible);
        end
    end
    
    % Check if figure was opened already and is getting reused
    gui_SkipInitialization = 0;
    if gui_State.gui_Singleton
        if isappdata(gui_hFigure,'GUIOnScreen')
            set(gui_hFigure,'Visible','on');
            gui_SkipInitialization = 1;
        else
            setappdata(gui_hFigure,'GUIOnScreen', 1);
        end
    end
    
    if gui_SkipInitialization
        % Throw a warning if there are any input arguments
        if numargin
            warning(message('HDLLink:modsimrand:IgnoredPVPair'));
        end
    else
        % Set flag to indicate starting GUI initialization
        setappdata(gui_hFigure,'InGUIInitialization',1);

        % Fetch GUIDE Application options
        gui_Options = getappdata(gui_hFigure,'GUIDEOptions');
        
        % Adjust default background color
        if gui_Options.syscolorfig
            set(gui_hFigure,'Color', get(0,'DefaultUicontrolBackgroundColor'));
        end
        
        % Apply user P/V pairs to gui_hFigure
        gui_MakeVisible = 1;
        gui_UserArgs = {};
        for i=1:2:length(varargin)
            % If user specified 'Visible','off' in p/v pairs, don't make the
            % figure visible.
            len = min(length('visible'),length(varargin{i}));
            if strncmpi(varargin{i},'visible',len) & strcmpi(varargin{i+1},'off')
                gui_MakeVisible = 0;
            end
            % Apply p/v pairs until we run out of valid pairs, remaining p/v pairs are
            % passed on to OpeningFcn as user args.
            try
                set(gui_hFigure, varargin{i}, varargin{i+1});
            catch
                gui_UserArgs = varargin(i:end);
                break;
            end
        end
        
        % Generate HANDLES structure for use in setup and callbacks.
        gui_Handles = guihandles(gui_hFigure);
        
        % If handle visibility is set to 'callback', turn it on until finished
        % with OpeningFcn
        gui_Options.HandleVisibility = get(gui_hFigure,'HandleVisibility');
        
        % Call gui opening function with no output args
        if strcmp(gui_Options.HandleVisibility, 'callback')
            set(gui_hFigure,'HandleVisibility', 'on');
        end
        
        feval(gui_State.gui_OpeningFcn, gui_hFigure, [], gui_Handles, gui_UserArgs{:});
        
        % If the figure got closed, gui_hFigure will be an invalid handle.
        if ishandle(gui_hFigure)
            % The OpeningFcn may have modified guidata, get the latest copy.
            gui_Handles = guidata(gui_hFigure);
            
            % Reset handle visibility
            set(gui_hFigure,'HandleVisibility', gui_Options.HandleVisibility);
        end

        % Make figure visible
        if ishandle(gui_hFigure) & gui_MakeVisible
            set(gui_hFigure, 'Visible', 'on')
        end        
        
        % Done with GUI initialization
        rmappdata(gui_hFigure,'InGUIInitialization');
    end
    
    % Call the gui Output function
    gui_Options.HandleVisibility = get(gui_hFigure,'HandleVisibility');
    gui_Handles = guidata(gui_hFigure);

    % If handle visibility is set to 'callback', turn it on
    % until finished with OutputFcn
    if ishandle(gui_hFigure) & strcmp(gui_Options.HandleVisibility, 'callback')
        set(gui_hFigure,'HandleVisibility', 'on');
    end
    
    % gui_handles is populated, gui_hFigure must be valid
    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
    
    % OutputFcn may have deleted the figure, skip updates to handle visibility
    % if so.
    if ishandle(gui_hFigure)
        set(gui_hFigure,'HandleVisibility', gui_Options.HandleVisibility);
    end
end    

