image thumbnail
from Circadian Clock Model Visualisation Tools by Paul Brown
Moving 2/3D plots and network diagram of an ode model of the circadian clock gene network

locke_05b_network(mode)
function locke_05b_network(mode)

global LIGHT_COLS;
global TEMPERATURE;
global modelname;
global spaces;

global listOfPFiles;
global listOfEFiles;
global paramFile;
global envFile;
global title;
global legend1;
global aspect;

if nargin == 0   %initialisation
   % colormap('default');
    feature ('javafigures',0);  %must re-anable dwhen closing!!!!!!!!!!!!
    LoadingTime('init');
    modelname = 'locke_05b';
    LIGHT_COLS = [];
    TEMPERATURE = [];
    spaces = {'     '};
    my_Dir = pwd;

    %get settings required for analysis
    [Settings, SettingVals] = textread('Settings.set','%[^=]%*c%[^\n]');
    for j = 1:size(Settings, 1); %search names for a match with state name
        %when found, get corresponding value
        if strcmp(Settings(j), 'LD') ~= 0
            %wavelengths expected in vals file
            LIGHT_COLS = SplitString(SettingVals(j));%separates names delimited by spaces
        elseif strcmp(Settings(j), 'TEMP') ~= 0
            TEMPERATURE = str2double(SettingVals(j));
        elseif strcmp(Settings(j), 'exePath') ~= 0
            exePath = char(SettingVals(j)); 
        elseif strcmp(Settings(j), 'paramFile') ~= 0
            paramFile = char(SettingVals(j));
        elseif strcmp(Settings(j), 'envFile') ~= 0
            envFile = char(SettingVals(j));
        end
    end
  %  delete('Settings.set');
    LoadingTime;
    paramFile = strcat(exePath,paramFile);
    %find all params files
    if ~isempty(exePath)
        chdir(exePath);
    end
    l = dir(strcat(paramFile, '*.pv'));
    listOfPFiles = cell(0);
    for i = 1:size(l,1)
        fn = l(i).name;
        %remove ext
        fn = fn(1:size(fn,2)-3);
        listOfPFiles = [listOfPFiles; {fn}];
    end
    if isempty(l)
        ShowError('No parameters files can be found! Unable to launch the program.');
        return;
    end
    LoadingTime;
    if ~isempty(LIGHT_COLS) | TEMPERATURE > 0
        envFile = strcat(exePath,envFile);
        l = dir(strcat(envFile, '*.env'));
        listOfEFiles = cell(0);
        for i = 1:size(l,1)
            fn = l(i).name;
            %remove ext
            fn = fn(1:size(fn,2)-4);
            listOfEFiles = [listOfEFiles; {fn}];
        end
        if isempty(l)
            ShowError('No environment files can be found! Unable to launch the program.');
            return;
        end
    else
        listOfEFiles = {'NA'};
    end
    LoadingTime;
    SetParamsFile(paramFile, listOfPFiles{1});
    SetEnvFile(envFile, listOfEFiles{1});
    
    chdir(my_Dir);
    
    title = modelname;
    modelname = strcat(exePath, modelname);
    LoadingTime;
    vc;
else
    vc(mode);
end


%=============================================
function vc(action)

global speedHndl;
global valHndl;
global pValUpHndl;
global pValDownHndl;
global ApplyPHndl;
global defHndl;
global eValUpHndl;
global eValDownHndl;
global ApplyEHndl;
global edefHndl;
global envValHndl;
global envHndl;
global pHndl;
global envparamsHndl
global pulseHndl;
global pValues;
global pDefValues;
global envDefValues;
global envValues;
global tfinal;
global y0;
global pnames;
global lastDay;
global pulseOn;
global t;
global spaces;
global CP;
global pauseHndl;
global envParams;
global modelEnvs;
global listOfPFiles;
global listOfEFiles;
global pFilesHndl;
global eFilesHndl;
global paramFile;
global envFile;
global LIGHT_COLS;
global TEMPERATURE;
global title;
global btncol;
global colours;
global envCols;
global btnLen;
global pmode;
global Blocks;
global BlockIndexes;
global SubBlocks;
global SubBlockIndexes;
global BlockPosition;
global light;
global lightidx;
global temperature;
global maxSize;
global maxHeadSize;
global timeHndl;
global Arrows;
global ArrowSizes;
global LightSizes
global linewidth;
global rates;
global effectOfLight;
global xRange;
global yRange;
global axHndl;
global xmin;
global xmax;
global ymin;
global ymax;
global x_op;
global y_ops;
global time_to_plot;
global colours;
global lcolours;
global dcolours;
global envCols;
global head;
global tail;
global envLine;
global PlotEnv;
global showLegendSubMenu;
global showMarkersSubMenu;
global ShowMarkers;
global ShowLegend;
global pmode;
global eplotHndl;
global axSelectHndl;
global axHndl;
global naxHndl;
global t_toplot;
global y_toplot;
global env_toplot;
global resolution;
global maxres;
global ArrowHeads;
global LightArrowHeads;
global recording;
global recHndl;
global opfile;


maxres = 20;    %every 20th point plotted

MyName = 'vc';
if nargin == 0,
    action='initialize';
end;
play= 1;
stop=-1;

if strcmp(action,'initialize'),
    btncol = [0.8 0.8 0.8];
    innerframecol = [0.2 0.2 0.2];
    tfinal=10000;
    resolution = maxres/2;
    numCycles = 5;  %num periods to showon time axis
    envCols = [[1 1 1];[0 0 1];[0 1 0];[1 0 0];[1 0 0];[1 0 1];[1 1 0]];   %light colours
    pmode = 'stopped';
    recording = 0;
    
    oldFigNumber=watchon;
    figNumber=figure('Name',char(strcat({'Visualise Model Network - '}, title)),'NumberTitle','off','Visible','off', 'colormap', jet(64), 'CloseRequestFcn', 'locke_05b_network(''close'')');
    LoadingTime;
    pos = get(figNumber, 'Position');
    aspect = 1.2;
    pos(3) = pos(4) * aspect;
    set(figNumber, 'Position', pos);
    LoadingTime;
    colordef(figNumber,'black');
    LoadingTime;


    %===================================
    % Information for all buttons
    labelColor=[0.8 0.8 0.8];
    btnLen=0.175;
    btnWid=0.075;
    % Spacing between the button and the next command's label
    spacing=0.025;
    %====================================
    % The CONSOLE frames
    frmBorder=0.02;
    yPos=0.05;
    frmPos=[0.025 0.025 0.225 0.95];
    h=uicontrol( ...
        'Style','frame', ...
        'Units','normalized', ...
        'Position',frmPos, ...
        'BackgroundColor',[0.50 0.50 0.50]);
    
    
    %====================================
    % The START button
    btnNumber=1;
    yPos=0.90-(btnNumber-1)*(btnWid+spacing);
    labelStr='Start';
    callbackStr='locke_05b_network(''start'');';

    % Generic button information
    btnPos=[0.05 0.04 btnLen/4 0.0625];
    startHndl=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'CData', GetImage(labelStr), ...
        'BackgroundColor', btncol, ...
        'Callback',callbackStr);

    %====================================
    % The STOP button
    btnNumber=2;
    yPos=0.90-(btnNumber-1)*(btnWid+spacing);
    labelStr='Stop';
    % Setting userdata to -1 (=stop) will stop the demo.
    callbackStr='locke_05b_network(''stop'');';
    
    % Generic  button information
    btnPos=[0.05 + btnLen * 0.5 0.04 btnLen/4 0.0625];
    stopHndl=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Enable','off', ...
        'BackgroundColor', btncol, ...
        'CData', GetImage(labelStr), ...
        'Callback',callbackStr);
    %========================================
    %pause button
    labelStr='Pause';
    callbackStr='locke_05b_network(''pause'');';
    
    % Generic  button information
    btnPos=[0.05 + btnLen/4 0.04 btnLen/4 0.0625];
    pauseHndl=uicontrol( ...
        'Style','togglebutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Enable','off', ...
        'BackgroundColor', btncol, ...
        'CData', GetImage(labelStr), ...
        'Value',0, ...
        'Callback',callbackStr);
    
     %========================================
    %record button
    labelStr='RecordOff';
    callbackStr='locke_05b_network(''record'');';
    
    % Generic  button information
    btnPos=[0.05 + btnLen*0.75 0.04 btnLen/4 0.0625];
    recHndl=uicontrol( ...
        'Style','togglebutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Enable','on', ...
        'BackgroundColor', btncol, ...
        'CData', GetImage(labelStr), ...
        'Max', 1, 'Min', 0, ...
        'Value',0, ...
        'Callback',callbackStr);
    %=========================================
    %select files
    h=uicontrol( ...
        'Style','frame', ...
        'Units','normalized', ...
        'Position',[0.0375 0.63 0.2 0.33], ...
        'BackgroundColor',innerframecol);
    labelHndl=uicontrol('Style', 'text','Units','normalized','position',[0.05 0.905 btnLen 0.05],'string','Parameters File','BackgroundColor', innerframecol, 'ForegroundColor', 'w');

    callbackStr='locke_05b_network(''changePfile'')';
    pFilesHndl=uicontrol( ...
        'Style','popup', ...
        'Units','normalized', ...
        'String', listOfPFiles, ...
        'position',[0.0475 0.875 btnLen 0.05], ...
        'call',callbackStr);
        
     % The parameters listbox
    callbackStr='locke_05b_network(''param'')';
    pHndl=uicontrol( ...
        'Style','listbox', ...
        'Units','normalized', ...
        'position',[0.0475 0.77 btnLen 0.1], ...
        'call',callbackStr);

    callbackStr='locke_05b_network(''paramValKeyPress'')';
    valHndl=uicontrol( ...
        'Style','edit',...
        'Units','normalized', ...
        'position',[0.0475 + btnLen*0.2 0.71 btnLen*0.4 0.05], ...
        'Enable','on', ...
        'HorizontalAlignment', 'right', ...
        'call',callbackStr);
    callbackStr='locke_05b_network(''pValUp'')';
    pValUpHndl=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',[0.0475 + btnLen*0.6 0.71 btnLen/5 0.05], ...
        'String','>', ...
        'Callback',callbackStr);  
    callbackStr='locke_05b_network(''pValDown'')';
    pValDownHndl=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',[0.0475 0.71 btnLen/5 0.05], ...
        'String','<', ...
        'Callback',callbackStr);
     %default button
    callbackStr='locke_05b_network(''setdef'')';
    defHndl=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',[0.0475+ btnLen*0.8 0.71 btnLen/5 0.05], ...
        'String','D', ...
        'Callback',callbackStr);  
    callbackStr='locke_05b_network(''applyPChange'')';
    ApplyPHndl=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',[0.0475 0.6475 btnLen 0.0625], ...
        'String','Apply', ...
        'Callback',callbackStr);   
  
    %============================================
    %env controls
    h=uicontrol( ...
        'Style','frame', ...
        'Units','normalized', ...
        'Position',[0.0375 0.165 0.2 0.44], ...
        'BackgroundColor',innerframecol);
   labelHndl=uicontrol('Style', 'text','Units','normalized','position',[0.05 0.55 btnLen 0.05],'string','Environment File','BackgroundColor', innerframecol, 'ForegroundColor', 'w');

    callbackStr='locke_05b_network(''changeEfile'')';
    eFilesHndl=uicontrol( ...
        'Style','popup', ...
        'Units','normalized', ...
        'String', listOfEFiles, ...
        'position',[0.05 0.52 btnLen 0.05], ...
        'call',callbackStr);

    % The LD listbox
    btnNumber=3;
    ypos=0.90-(btnNumber-1)*(btnWid+spacing);
    callbackStr='locke_05b_network(''env'')';
    envHndl=uicontrol( ...
        'Style','popup', ...
        'Units','normalized', ...
        'String', modelEnvs, ...
        'position',[0.05 0.465 btnLen*0.75 0.05], ...
        'call',callbackStr);
    callbackStr='locke_05b_network(''plotEnv'')';
    eplotHndl=uicontrol( ...
        'Style','togglebutton', ...
        'Units','normalized', ...
        'Position',[0.05 + btnLen*0.75 0.465 btnLen/4 0.05], ...
        'String','P', ...
        'Value', 0, 'Max', 1, 'Min', 0, ...
        'Callback',callbackStr);  
    
    callbackStr='locke_05b_network(''envParams'')';
    envparamsHndl=uicontrol( ...
        'Style','listbox', ...
        'Units','normalized', ...
        'position',[0.05 0.36 btnLen 0.1], ...
        'call',callbackStr);

    callbackStr='locke_05b_network(''envValKeyPress'')';
    envValHndl=uicontrol( ...
        'Style','edit',...
        'Units','normalized', ...
        'position',[0.05 + btnLen*0.2 0.3 btnLen*0.4 0.05], ...
        'Enable','on', ...
        'HorizontalAlignment', 'right', ...
        'call',callbackStr);
    callbackStr='locke_05b_network(''eValUp'')';
    eValUpHndl=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',[0.05 + btnLen*0.6 0.3 btnLen/5 0.05], ...
        'String','>', ...
        'Callback',callbackStr);  
    callbackStr='locke_05b_network(''eValDown'')';
    eValDownHndl=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',[0.05 0.3 btnLen/5 0.05], ...
        'String','<', ...
        'Callback',callbackStr);
    %default button
    callbackStr='locke_05b_network(''setedef'')';
    edefHndl=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',[0.05+ btnLen*0.8 0.3 btnLen/5 0.05], ...
        'String','D', ...
        'Callback',callbackStr);  
    callbackStr='locke_05b_network(''applyEChange'')';
    ApplyEHndl=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',[0.05 0.2375 btnLen 0.0625], ...
        'String','Apply', ...
        'Callback',callbackStr);   
    
    %pulse button
    callbackStr='locke_05b_network(''pulse'')';
    pulseHndl=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',[0.05 0.1775 btnLen 0.0625], ...
        'String','Pulse', ...
        'Enable','off', ...
        'Callback',callbackStr);
      %====================================
    % The Axes buttons
    labelStr='Auto';
    callbackStr='locke_05b_network(''scale'')';
    scaleHndl=uicontrol( ...
        'Style','push', ...
        'Units','normalized', ...
        'position',[0.935 0.05 0.05 0.05], ...
        'string',labelStr, ...
        'Enable', 'off', ...
        'call',callbackStr);

    labelStr='E';
    callbackStr='locke_05b_network(''enlargeScale'')';
    enlargeHndl=uicontrol( ...
        'Style','push', ...
        'Units','normalized', ...
        'position',[0.935 0.15 0.05 0.05], ...
        'string',labelStr, ...
        'Enable', 'off', ...
        'call',callbackStr);
    labelStr='R';
    callbackStr='locke_05b_network(''reduceScale'')';
    reduceHndl=uicontrol( ...
        'Style','push', ...
        'Units','normalized', ...
        'position',[0.935 0.1 0.05 0.05], ...
        'string',labelStr, ...
        'Enable', 'off', ...
        'call',callbackStr);

    lbs = cell(0);
    lbs = [lbs; {'All'}; {'X'}; {'Y'}];
    axSelectHndl=uicontrol( ...
        'Style','popup', ...
        'Units','normalized', ...
        'position',[0.935 0.2 0.05 0.05], ...
        'string',lbs, ...
        'Enable', 'off', ...
        'HorizontalAlignment', 'right', ...
        'Value', 1);
   LoadingTime;
   
    %====================================
   
    % The speed slider
    labelStr='Speed';
    callbackStr='locke_05b_network(''speed'')';
    speedHndl=uicontrol( ...
        'Style','slider',...
        'Units','normalized', ...
        'Value', 0.5, ...
        'position',[0.05 0.11 btnLen 0.025], ...
        'string',labelStr, ...
        'call',callbackStr);
    labelHndl=uicontrol('Style', 'text','Units','normalized','position',[0.05 0.135 btnLen 0.025],'string','Speed','BackgroundColor', [0.5 0.5 0.5], 'ForegroundColor', 'w');
    timeHndl=uicontrol('FontSize', 10,'Style', 'text','Units','normalized','position',[0.8 0.95 0.2 0.05],'BackgroundColor', [0.2 0.2 0.2], 'ForegroundColor', 'w');

    %menu
  %  plotMenuHndl = uimenu('Label', 'Plot');
  %  showLegendSubMenu  = uimenu(plotMenuHndl, 'Label', 'Show Legend', 'Checked', 'on', 'Callback', 'locke_05b_plot(''ShowLegend'');');
  %  showMarkersSubMenu  = uimenu(plotMenuHndl, 'Label', 'Show Markers', 'Checked', 'on', 'Callback', 'locke_05b_plot(''ShowMarkers'');');
    
  %  ShowMarkers = 1;
  %  ShowLegend = 1;
    %==============================
    %fill controls
   FillParamsControls
   FillEnvControls;
   LoadingTime;
   time_to_plot = GetCP * numCycles; %time to show in one block on time series
   xmin = 0;xmax=time_to_plot;
   ymin=0;ymax=2;
   set(eplotHndl, 'Value', 0);
  
   
   %draw model
  

    naxHndl = axes( ...
        'Units','normalized', 'Position',[0.325 0.25 0.6 0.7],'Visible','on');
     set(naxHndl, ...     
        'XLim',[0 1],'YLim',[0 1], ...
        'Drawmode','fast', ...
        'Visible','on', ...
        'NextPlot','add', 'visible', 'off');
    axHndl = axes( ...
        'Units','normalized', 'Position',[0.325 0.05 0.6 0.2],'Visible','on');
     set(axHndl, ...     
        'XLim',[xmin xmax],'YLim',[ymin ymax], ...
        'Drawmode','fast', ...
        'Visible','on', ...
        'NextPlot','add');
    [Blocks, SubBlocks, BlockPosition, BlockIndexes, SubBlockIndexes, light, lightidx, temperature, Arrows, ArrowHeads, LightArrowHeads] = DrawModel;
    % Uncover the figure
     y_ops = zeros(1,size(Blocks,2));  %one for each op, 0 - hidden, 1  -show 
    y_ops(1)=1;
    hndlList=[startHndl stopHndl envHndl speedHndl pHndl valHndl envparamsHndl envValHndl pulseHndl pauseHndl defHndl pFilesHndl eFilesHndl pValUpHndl pValDownHndl ApplyPHndl eValUpHndl eValDownHndl ApplyEHndl edefHndl timeHndl eplotHndl scaleHndl enlargeHndl reduceHndl axSelectHndl axHndl naxHndl recHndl];
    if isempty(LIGHT_COLS) & TEMPERATURE == 0
        set([eFilesHndl envHndl envparamsHndl envValHndl pulseHndl eValUpHndl eValDownHndl ApplyEHndl edefHndl eplotHndl],'Enable','off');
    end
        
    set(figNumber,'Visible','on', ...
        'UserData',hndlList);
    watchoff(oldFigNumber);
    figure(figNumber);
    LoadingTime('finished');  
elseif strcmp(action,'start'),
    cla(axHndl);
    pulseOn = zeros(size(modelEnvs,1),1);
    figNumber=gcf;

    hndlList=get(figNumber,'UserData');
    startHndl=hndlList(1);
    stopHndl=hndlList(2);
    envHndl=hndlList(3);
    speedHndl=hndlList(4);
    pHndl = hndlList(5);
    valHndl = hndlList(6);
    envparamsHndl = hndlList(7);
    envValHndl = hndlList(8);
    pulseHndl = hndlList(9);
    pauseHndl = hndlList(10);
    defHndl = hndlList(11);
    pFilesHndl = hndlList(12);
    eFilesHndl = hndlList(13);
    pValUpHndl = hndlList(14);
    pValDownHndl = hndlList(15);
    ApplyPHndl = hndlList(16);
    eValUpHndl = hndlList(17);
    eValDownHndl = hndlList(18);
    ApplyEHndl = hndlList(19);
    edefHndl = hndlList(20);
    timeHndl = hndlList(21);
    eplotHndl = hndlList(22);
    scaleHndl = hndlList(23);
    enlargeHndl = hndlList(24);
    reduceHndl = hndlList(25);
    axSelectHndl = hndlList(26);
    axHndl = hndlList(27);
    naxHndl = hndlList(28);
    recHndl = hndlList(29);
    %need blocks in this list to detect clicks
    set([startHndl pFilesHndl eFilesHndl],'Enable','off');

    set([stopHndl speedHndl pauseHndl scaleHndl enlargeHndl reduceHndl axSelectHndl],'Enable','on');
    PlotEnv = get(eplotHndl,'Value');
    if ~isempty(LIGHT_COLS) | TEMPERATURE > 0
        set(pulseHndl, 'Enable', 'on');
    end
    sp = resolution/maxres;
    set(speedHndl, 'Value', sp);
    pmode = 'play';
 
    % ====== Start of Demo
    set(figNumber,'Backingstore','off');
    xmin = 0; xmax = time_to_plot;
    cp = GetCP;
    tv = [xmin:cp:xmax]; 
    set(axHndl,'XLim',[xmin xmax]);
    set(axHndl, 'XTick', tv); 
    y = y0(:);
    xlabel('Time');
   
    ylabel('Output Level');
    SetAxes;
    t0=0;
    pow = 1/3;
    tol = 0.001;
    t = t0;

    hmax = (tfinal - t)/5;  %step sizes
    hmin = (tfinal - t)/200000; % 0.05 s
    h = (tfinal - t)/100;   
    t_toplot = t;
    y_toplot = y;
    env_toplot = 0;
    lastDay = [t0;y]; 
    rates = [];
    effectOfLight = [];
    tau = tol * max(norm(y,'inf'),1);   %allowed error
 
    resolution = floor(maxres * get(speedHndl, 'Value'));
    if resolution < 1 
        resolution=1;
    end
    minValue = zeros(1, size(Blocks,2));
    maxValue = ones(1, size(Blocks,2));
    minRate = zeros(1, size(Arrows,1));
    maxRate = ones(1, size(Arrows,1));
    minLight = zeros(size(light,1), size(light,2));
    maxLight = ones(size(light,1), size(light,2));
    % The main loop
    num_points = 0;
    fnum = 0;
   % if recording == 1
    %    opfile = avifile(GetAVIName);
    %end
    Mv = [];
    while (strcmp(pmode, 'play'))
        if t + h > tfinal, h = tfinal - t; end
        % Compute the slopes
        try
            [ld_val day] = GetLD(t);
            [t_val tempday] = GetTemp(t);
            s1 = equations(t, y, pValues, ld_val, t_val);   %derrivatives
            s2 = equations(t+h, y+h*s1, pValues, ld_val, t_val);
            s3 = equations(t+h/2, y+h*(s1+s2)/4, pValues, ld_val, t_val);
   
            % Estimate the error and the acceptable error
            delta = norm(h*(s1 - 2*s3 + s2)/3,'inf');
            tau = tol*max(norm(y,'inf'),1.0);
 
            % Update the solution only if the error is acceptable
            ts = t;
            ys = y;
            if delta <= tau
                num_points = num_points + 1;
                t = t + h;
                y = y + h*(s1 + 4*s3 + s2)/6;
               
                if mod(num_points, resolution) == 0
                    y_toplot = [y_toplot y];
                    t_toplot = [t_toplot t];
                    %see if light values same as last timepoint
                   % match = 1;
                    %for i = 2:size(env_toplot,1)
                     %   if env_plot
                    %end
                    rates = [rates ArrowSizes]; 
                    %save last 48 hours to calc axis limits required
                    data = [t; y];
                    lastDay = [lastDay data];
                    effectOfLight = [effectOfLight LightSizes];
                    toremove = find(lastDay(1,:) <= (t - 2*GetCP));
                    lastDay(:,toremove) = [];
                    rates(:,toremove) = [];
                    effectOfLight(:,toremove) = [];
                       %find range of vlaues for each output over last 2 days
                    for i = 1:size(BlockIndexes,1)
                        idx = BlockIndexes{i} + 1; %plus one as row 1 is time
                        m = lastDay(idx,:);
                        if size(m,1) > 1
                            m = sum(m);%sum of 1 or more ops for each timepoint
                        end
                        minValue(i) = min(m);
                        maxValue(i) = max(m);
                    end
                    %same for rates
                    for i = 1:size(Arrows,1)
                        idx = Arrows(i,2);
                        m = rates(idx,:);
                        if size(m,1) > 1
                            m = sum(m);%sum of 1 or more ops for each timepoint
                        end
                       minRate(i) = min(m);
                        maxRate(i) = max(m);
                    end
                    %and light arrows
                    for i = 1:size(light,1)
                        for j = 1:size(light,2)
                            idx = lightidx(i,j);
                            m = effectOfLight(idx,:);
                            if size(m,1) > 1
                                m = sum(m);%sum of 1 or more
                            end
                            minLight(i,j) = min(m);
                            maxLight(i,j) = max(m);
                        end 
                    end
                
                    %set box size
                    for i = 1:size(Blocks,2)
                       idx = BlockIndexes{i};
                       currentSize = sum(y(idx));
                       if currentSize < minValue(i)
                           currentSize = 0.1;
                       elseif currentSize > maxValue(i)
                           currentSize = 1;
                       elseif maxValue(i) == minValue(i)
                           currentSize = 0.5;   %constant
                       else
                           currentSize = (currentSize - minValue(i))/(maxValue(i) - minValue(i));
                       end
                       if currentSize < 0.1
                           currentSize = 0.1;
                       end
                       if ~isreal(currentSize)
                            currentSize = real(currentSize);
                       end
                       currentSize = currentSize * maxSize;
                       set(Blocks(1,i), 'Position', [BlockPosition(i,1) - currentSize/2 BlockPosition(i,2) - currentSize/2 currentSize currentSize]);
                        %sub blocks
                       subBlockidx =  Blocks(2,i);
                       %ratio of sub to main block
                       if subBlockidx > 0
                            subidx = SubBlockIndexes{subBlockidx};
                            subSize = (sum(y(subidx)) / sum(y(idx)));
                            if subSize < 0.01
                                subSize = 0.01;
                            end
                            subSize = currentSize * subSize;
                            set(SubBlocks(subBlockidx), 'Position', [BlockPosition(i,1) - currentSize/2 BlockPosition(i,2) + currentSize/2 - subSize currentSize subSize]);
                       end
                    end
                   %set arrow thicknesses
                   for i = 1:size(Arrows,1)
                       idx = Arrows(i,2);
                       currentSize = sum(ArrowSizes(idx));
                       if currentSize < minRate(i)
                           currentSize = 0.1;
                       elseif currentSize > maxRate(i)
                           currentSize = 1;
                       elseif maxRate(i) == minRate(i)
                           currentSize = 0.5;   %constant
                       else
                           currentSize = (currentSize - minRate(i))/(maxRate(i) - minRate(i));
                       end
                       if currentSize < 0.1
                           currentSize = 0.1;
                       end
                       if ~isreal(currentSize)
                            currentSize = real(currentSize);
                       end
                       if Arrows(i,3) > 0 
                            cs = currentSize * maxSize;
                            xc = get(ArrowHeads(Arrows(i,3)), 'XData');
                            yc = get(ArrowHeads(Arrows(i,3)), 'YData');
                            d = get(ArrowHeads(Arrows(i,3)), 'Tag');
                            if d == 'd' %down arrow
                                set(ArrowHeads(Arrows(i,3)), 'XData', [xc(1); xc(1) + cs/2; xc(1) - cs/2], 'YData', [yc(1); yc(1) + cs/2; yc(1) + cs/2]);
                                %line end
                                lc = get(Arrows(i,1),'YData');
                                lc(2) = yc(1) + cs/2;
                                set(Arrows(i,1), 'YData', lc);
                            elseif d == 'l' %left facing
                                set(ArrowHeads(Arrows(i,3)), 'XData', [xc(1); xc(1) + cs/2; xc(1) + cs/2], 'YData', [yc(1); yc(1) - cs/2; yc(1) + cs/2]);
                                %line end
                                lc = get(Arrows(i,1),'XData');
                                lc(2) = xc(1) + cs/2;
                                set(Arrows(i,1), 'XData', lc);
                            elseif d == 'u' %up facing
                                set(ArrowHeads(Arrows(i,3)), 'XData', [xc(1); xc(1) - cs/2; xc(1) + cs/2], 'YData', [yc(1); yc(1) - cs/2; yc(1) - cs/2]);
                                %line end
                                lc = get(Arrows(i,1),'YData');
                                lc(2) = yc(1) - cs/2;
                                set(Arrows(i,1), 'YData', lc); 
                            elseif d == 'r' %right facing
                                set(ArrowHeads(Arrows(i,3)), 'XData', [xc(1); xc(1) - cs/2; xc(1) - cs/2], 'YData', [yc(1); yc(1) + cs/2; yc(1) - cs/2]);
                                %line end
                                lc = get(Arrows(i,1),'XData');
                                lc(2) = xc(1) - cs/2;
                                set(Arrows(i,1), 'XData', lc);
                            elseif d == 'ir' %vertcal inhibitory
                                ml = (yc(1) + yc(2))/2;
                                set(ArrowHeads(Arrows(i,3)), 'XData', [xc(1); xc(2); xc(1) - cs/4; xc(1) - cs/4], 'YData', [ml - cs/2; ml + cs/2; ml + cs/2; ml - cs/2]);
                                %line end
                                lc = get(Arrows(i,1),'XData');
                                lc(2) = xc(1) - cs/4;
                                set(Arrows(i,1), 'XData', lc);
                            elseif d == 'il' %vertcal inhibitory
                                ml = (yc(1) + yc(2))/2;
                                set(ArrowHeads(Arrows(i,3)), 'XData', [xc(4) + cs/4; xc(4) + cs/4; xc(3); xc(4)], 'YData', [ml - cs/2; ml + cs/2; ml + cs/2; ml - cs/2]);
                                %line end
                                lc = get(Arrows(i,1),'XData');
                                lc(2) = xc(4) + cs/4;
                                set(Arrows(i,1), 'XData', lc);   
                            end
                       end
                       set(Arrows(i,1), 'LineWidth', linewidth * currentSize);
                   end
                   %light
                    for j = 1:size(day,1)
                        for i = 1:size(light,2)
                            colour = eval(get(light(j,i), 'Tag'));
                            dv = day(j);
                            if dv > 1
                                dv = 1;
                            end
                            colour = colour * dv;
                            idx = lightidx(j,i);
                            currentSize = sum(LightSizes(idx));
                            if currentSize < minLight(j,i)
                                currentSize = 0.1;
                            elseif currentSize > maxLight(j,i)
                                currentSize = 1;
                            elseif maxLight(i) == minLight(i)
                                currentSize = 0.5;   %constant
                            else
                                currentSize = (currentSize - minLight(i))/(maxLight(i) - minLight(i));
                            end
                           if currentSize < 0.1
                                currentSize = 0.1;
                           end
                           if ~isreal(currentSize)
                                currentSize = real(currentSize);
                           end
                           cs = currentSize * maxSize;
                           xc = get(LightArrowHeads(j,i), 'XData');
                           yc = get(LightArrowHeads(j,i), 'YData');
                           d = get(LightArrowHeads(j,i), 'Tag');
                           if d == 'ld' %left-down arrow
                               set(LightArrowHeads(j,i), 'XData', [xc(1); xc(1) + cs; xc(3)], 'YData', [yc(1); yc(2); yc(1) + cs], 'FaceColor', colour, 'EdgeColor', colour);
                               %line end
                               lcy = get(light(j,i),'YData');
                               lcx = get(light(j,i),'XData');
                               lcy(2) = yc(1) + cs/2;
                               lcx(2) = xc(1) + cs/2;
                               set(light(j,i), 'YData', lcy, 'XData', lcx);           
                           elseif d == 'ru' %right-up arrow
                               set(LightArrowHeads(j,i), 'XData', [xc(1); xc(1) - cs; xc(3)], 'YData', [yc(1); yc(2); yc(1) - cs], 'FaceColor', colour, 'EdgeColor', colour);
                               %line end
                               lcy = get(light(j,i),'YData');
                               lcx = get(light(j,i),'XData');
                               lcy(2) = yc(1) - cs/2;
                               lcx(2) = xc(1) - cs/2;
                               set(light(j,i), 'YData', lcy, 'XData', lcx);
                               
                           end
                           set(light(j,i), 'color', colour, 'LineWidth',linewidth * currentSize );
                        end
                    end
                    if tempday ~= 0
                        for i = 1:size(temperature,1)
                            set(temperature(i), 'Visible', 'on');
                        end
                    else
                        for i = 1:size(temperature,1)
                            set(temperature(i), 'Visible', 'off');
                        end
                    end
                    str =sprintf('Time = %5.1f', t);
                    set(timeHndl, 'String', str);
                    %update plot
                
                   %add the selected env cycle
                    lv = [];
                    e = get(envHndl,'Value');
                    offVal = envValues(e,5);
                   for i = 1:size(ld_val,1)
                       if ld_val(i) > offVal
                           lv = [lv; ymin + (ymax-ymin)/10;];
                       else
                           lv = [lv; ymin+ (ymax-ymin)/100];
                       end
                   end
                   env_toplot = [env_toplot lv];
                   
                    if ~isempty(envValues) & PlotEnv ~=0
                       envColour = envCols(e,:);
                       for e = 1:size(env_toplot,1)
                           set(envLine,'Parent', axHndl,'color',envColour, 'Visible', 'on', 'YData', env_toplot(e,:), 'XData', t_toplot); 
                       end
                    end
                    for i = 1:size(y_ops,2)
                        if y_ops(i) ~= 0
                            plotdata = y_toplot(BlockIndexes{i},:);
                            if size(plotdata,1) > 1
                                plotdata = sum(plotdata);%block is sum of 2 ops
                            end
                        %    if (day > 0 | tempday > 0) & (min(plotdata) <= envYval) & PlotEnv ~= 0
                         %       lineColour = 'k';
                         %   else
                                %set marker depending on whether block is
                                %ellipse or rectange
                            lineColour = get(Blocks(1,i), 'FaceColor');
                          %  end    
                            set(head(i),'parent', axHndl,'color',lineColour,'MarkerEdgeColor', lineColour, 'MarkerFaceColor', lineColour,'xdata',t,'ydata',plotdata(end))  %current time point
                            set(tail(i),'parent', axHndl,'color',lineColour,'xdata',t_toplot,'ydata',plotdata)  %rest   
                        end    
                    end
                    if recording
                       %fnum = fnum+1;
                       pos = get(figNumber, 'Position');
                       Mv = [Mv;getframe(figNumber, [pos(3) * 0.325 pos(4) * 0.05 pos(3) * 0.6 pos(4) * 0.9])];
                       %ned to reset file nam ebetween runs
                       %imwrite(Mv.cdata, strcat('img', '.tiff'), 'tiff', 'WriteMode', 'append', 'Compression', 'packbits', 'Resolution', 72);
                       %opfile = addframe(opfile, naxHndl);
                    end
                    %update x axis
                    if t > xmax
                        xmin = xmax;
                        xmax = xmin + time_to_plot;
                        set(axHndl, 'XLim',[xmin xmax]);
                        cp = time_to_plot/5;
                        tv = [xmin:cp:xmax]; 
                        set(axHndl, 'XTick', tv);
                        t_toplot = t;
                        y_toplot = y;
                        env_toplot = 0;
                    end
                    drawnow;
                end
            end
            % Update the step size
            if delta ~= 0.0
                h = min(hmax, 0.9*h*(tau/delta)^pow);
            end
        catch
           [msg id] = lasterr;
           ShowError(strcat({'Error evaluating the model file. '},msg, '.')); 
           vc('stop');
        end
       
    end;    % Main loop ...

    pmode = 'stopped';
    % ====== End of Demo
   % if recording == 1
    %    close(opfile);
     %   opfile = 0;
    %end
    if ~isempty(Mv) %no resizin gif recording
        movie2avi(Mv,GetAVIName);
       % save('d:\Movie1', 'Mv');
    end
    set([startHndl pFilesHndl],'Enable','on');
    if ~isempty(LIGHT_COLS) | TEMPERATURE > 0
         set(eFilesHndl,'Enable','on');
    end
    set([stopHndl pulseHndl pauseHndl scaleHndl enlargeHndl reduceHndl axSelectHndl],'Enable','off');
    feature ('javafigures',1);
elseif strcmp(action,'speed')
    resolution=floor(get(speedHndl, 'Value') * maxres);
    if resolution < 1 
        resolution=1;
    end
elseif strcmp(action, 'param')  %select a param
    p = get(pHndl, 'Value');
    set(valHndl, 'String',pValues(p));
elseif strcmp(action, 'envParams')  %env listbox
    %move slider
    p = get(envparamsHndl, 'Value');    %parameter
    e = get(envHndl, 'Value');  %cycle eg 'white'
    set(envValHndl, 'String',envValues(e,p));
elseif strcmp(action, 'pulse')  %pulse button
      pulseOn(get(envHndl, 'Value')) = t; 
elseif strcmp(action, 'pause')  %pulse button
    ps = get(pauseHndl, 'Value');
    while ps > 0
        pause(1);
        ps = get(pauseHndl, 'Value');
    end
elseif strcmp(action, 'stop') 
    set(pauseHndl, 'Value', 0);
    pmode = 'stopped';
elseif strcmp(action, 'close') 
    locke_05b_network('stop');
    feature ('javafigures',1);
    delete(gcf);
elseif strcmp(action, 'setdef')  
    p = get(pHndl, 'Value');
    set(valHndl, 'String', pDefValues(p));
elseif strcmp(action, 'changePfile')  
    p = get(pFilesHndl, 'Value');
    p = listOfPFiles{p};
    SetParamsFile(paramFile, p)
    FillParamsControls;
elseif strcmp(action, 'changeEfile')  
    p = get(eFilesHndl, 'Value');
    p = listOfEFiles{p};
    SetEnvFile(envFile, p)
    FillEnvControls(get(envHndl,'Value'));
elseif strcmp(action, 'env') 
    FillEnvControls(get(envHndl,'Value'));
elseif strcmp(action, 'applyPChange')
    p = get(pHndl, 'Value');
    pv = get(valHndl, 'String');
    to_remove = [];
    for i = 1:size(pv,2)
       if ~isstrprop(pv(i), 'digit') & ~strcmp('.', pv(i))
          to_remove = [to_remove i];
       end
    end
    pv(to_remove) = [];
    dps = find(pv == '.');
    if size(dps,2) > 1
        pv(dps(2:end)) = [];
    end
    if isempty(pv) | str2double(pv) < 0
        pv = '0';
    end
    set(valHndl, 'String', pv);
    pValues(p) = str2double(pv);   
    %update listbox view
    str = get(pHndl, 'String');
    ln = char(str(p));
    idx = strfind(ln, char(spaces));
    param_name = ln(1:idx - 1);
    str(p) = strcat(param_name, spaces, num2str(pValues(p)));
    set(pHndl, 'String', str);
elseif strcmp(action, 'pValUp')
    p = get(pHndl, 'Value');
    pv = get(valHndl, 'String');
    %ensure a valid number in text box
    to_remove = [];
    for i = 1:size(pv,2)
       if ~isstrprop(pv(i), 'digit') & ~strcmp('.', pv(i))
          to_remove = [to_remove i];
       end
    end
    pv(to_remove) = [];
    dps = find(pv == '.');
    if size(dps,2) > 1
        pv(dps(2:end)) = [];
    end
    if isempty(pv) | str2double(pv) < 0
        pv = '0';
    end
    %increment by 10% of default value
    if pDefValues(p) ~= 0
        newval = str2double(pv) + (pDefValues(p)/10);
    else
        newval = str2double(pv) + 0.1;
    end
    pv = num2str(newval);
    set(valHndl, 'String', pv);
elseif strcmp(action, 'pValDown')
    p = get(pHndl, 'Value');
    pv = get(valHndl, 'String');
    %ensure a valid number in text box
    to_remove = [];
    for i = 1:size(pv,2)
       if ~isstrprop(pv(i), 'digit') & ~strcmp('.', pv(i))
          to_remove = [to_remove i];
       end
    end
    pv(to_remove) = [];
    dps = find(pv == '.');
    if size(dps,2) > 1
        pv(dps(2:end)) = [];
    end
    if isempty(pv) | str2double(pv) < 0
        pv = '0';
    end
    %decrement by 10% of default value
     if pDefValues(p) ~= 0
        newval = str2double(pv) - (pDefValues(p)/10);
    else
        newval = str2double(pv) - 0.1;
    end
    if newval < 0
        newval = 0;
    end
    pv = num2str(newval);
    set(valHndl, 'String', pv);
elseif strcmp(action, 'eValDown')
    p = get(envparamsHndl, 'Value');    %parameter eg time on
    e = get(envHndl, 'Value');  %cycle eg 'white'
    pv = get(envValHndl, 'String');%value
    to_remove = [];
    for i = 1:size(pv,2)
       if ~isstrprop(pv(i), 'digit') & ~strcmp('.', pv(i)) & ~strcmp('-', pv(i))
          to_remove = [to_remove i];
       end
    end
    pv(to_remove) = [];
    %only allow '-' in first position
    to_remove = [];
    for i = 2:size(pv,2)
       if strcmp('-', pv(i))
          to_remove = [to_remove i];
       end
    end
    pv(to_remove) = [];
    
    dps = find(pv == '.');
    if size(dps,2) > 1
        pv(dps(2:end)) = [];
    end
    if isempty(pv)
        pv = '0';
    end
    %increment value
    newVal = str2double(pv);
    if p == 1 %cp
        if newVal >= 3
            newVal = newVal - 1;
        else
            newVal = 2;
        end
    elseif p == 2 | p == 3 | p == 7       %dawn/dusk pulselength
        if newVal >= 1
            newVal = newVal - 1;
        else
            newVal = 0;
        end
    elseif p == 5 | p == 4 | p == 6  %Ioff Ion, pulse size
        if ~isempty(LIGHT_COLS)
            if e <= size(LIGHT_COLS,1)
                %light selected
                if newVal >= 0.1
                    newVal = newVal - 0.1;
                else
                    newVal = 0;
                end
            else
                %temp
                newVal = newVal - 1;
            end
        else
            %temp
            newVal = newVal - 1;
        end
    end
    pv = num2str(newVal);
    set(envValHndl, 'String', pv);
elseif strcmp(action, 'eValUp')
    p = get(envparamsHndl, 'Value');    %parameter eg time on
    e = get(envHndl, 'Value');  %cycle eg 'white'
    pv = get(envValHndl, 'String');%value
    to_remove = [];
    for i = 1:size(pv,2)
       if ~isstrprop(pv(i), 'digit') & ~strcmp('.', pv(i)) & ~strcmp('-', pv(i))
          to_remove = [to_remove i];
       end
    end
    pv(to_remove) = [];
    %only allow '-' in first position
    to_remove = [];
    for i = 2:size(pv,2)
       if strcmp('-', pv(i))
          to_remove = [to_remove i];
       end
    end
    pv(to_remove) = [];
    
    dps = find(pv == '.');
    if size(dps,2) > 1
        pv(dps(2:end)) = [];
    end
    if isempty(pv)
        pv = '0';
    end
    %increment value
    newVal = str2double(pv);
    if p == 1 | p == 2 | p == 3 | p == 7       %cp dawn/dusk pulselength
        newVal = newVal + 1;
    elseif p == 5 | p == 4 | p == 6  %Ioff Ion, pulse size
        if ~isempty(LIGHT_COLS)
            if e <= size(LIGHT_COLS,1)
                %light selected
                newVal = newVal + 0.1;
            else
                %temp
                newVal = newVal + 1;
            end
        else
            %temp
            newVal = newVal + 1;
        end
    end
    pv = num2str(newVal);
    set(envValHndl, 'String', pv); 
elseif strcmp(action, 'applyEChange')
    p = get(envparamsHndl, 'Value');    %parameter eg time on
    e = get(envHndl, 'Value');  %cycle eg 'white'
    pv = get(envValHndl, 'String');%value
    to_remove = [];
    for i = 1:size(pv,2)
       if ~isstrprop(pv(i), 'digit') & ~strcmp('.', pv(i)) & ~strcmp('-', pv(i))
          to_remove = [to_remove i];
       end
    end
    pv(to_remove) = [];
    %only allow '-' in first position
    to_remove = [];
    for i = 2:size(pv,2)
       if strcmp('-', pv(i))
          to_remove = [to_remove i];
       end
    end
    pv(to_remove) = [];
    
    dps = find(pv == '.');
    if size(dps,2) > 1
        pv(dps(2:end)) = [];
    end
    if isempty(pv)
        pv = '0';
    end
    set(envValHndl, 'String', pv);
    envValues(e,p) = str2double(pv); 
    %validate change
    
    if p == 1
        %if a light cp changed, change for all lights
       if ~isempty(LIGHT_COLS)
           if e <= size(LIGHT_COLS,1)
               envValues(1:size(LIGHT_COLS,1),1) = str2double(pv); 
               %reduce any on of off times greater than cp
               tooLarge = find(envValues(1:size(LIGHT_COLS,1),2) > str2double(pv));
               envValues(tooLarge,2) = str2double(pv);
               tooLarge = find(envValues(1:size(LIGHT_COLS,1),3) > str2double(pv));
               envValues(tooLarge,3) = str2double(pv);
           end
       end
       if e > size(LIGHT_COLS,1)
            if envValues(e,2) > str2double(pv)
                envValues(e,2) = str2double(pv);
            end
            if envValues(e,3) > str2double(pv)
                envValues(e,3) = str2double(pv);
            end
       end
    elseif p == 2 %time on so mak esure cp and time off are at least equal to this
       if ~isempty(LIGHT_COLS)
           if e <= size(LIGHT_COLS,1)
              if envValues(e,1) <  str2double(pv)
                  envValues(1:size(LIGHT_COLS,1),1) = str2double(pv); 
              end
           end
       end
       if e > size(LIGHT_COLS,1)
            if envValues(e,1) < str2double(pv)
                envValues(e,1) = str2double(pv);
            end
       end 
       if envValues(e,3) < str2double(pv)
           envValues(e,3) = str2double(pv); 
       end
    elseif p == 3   %time off so make sure cp at least equal to this, and time on no greater
        if ~isempty(LIGHT_COLS)
           if e <= size(LIGHT_COLS,1)
              if envValues(e,1) <  str2double(pv)
                  envValues(1:size(LIGHT_COLS,1),1) = str2double(pv); 
              end
           end
       end
       if e > size(LIGHT_COLS,1)
            if envValues(e,1) < str2double(pv)
                envValues(e,1) = str2double(pv);
            end
       end 
       if envValues(e,2) > str2double(pv)
           envValues(e,2) = str2double(pv); 
       end
    elseif p == 4   %ion value, ensure ioff value no greater 
       if envValues(e,5) > str2double(pv)
           envValues(e,5) = str2double(pv); 
       end
    elseif p == 5    %ioff value, ensure ion is not less
        if envValues(e,4) < str2double(pv)
           envValues(e,4) = str2double(pv); 
       end
    end 
    %update listbox view
    str = get(envparamsHndl, 'String');
    for i = 1:size(str,1)
        ln = char(str(i));
        idx = strfind(ln, char(spaces));
        env_name = ln(1:idx - 1);
        str(i) = strcat(env_name, spaces, num2str(envValues(e,i)));
    end 
    set(envparamsHndl, 'String', str);
elseif strcmp(action, 'setedef')  
    p = get(envparamsHndl, 'Value');    %parameter eg time on
    e = get(envHndl, 'Value');  %cycle eg 'white'
    set(envValHndl, 'String', envDefValues(e,p));%value
elseif strcmp(action, 'plotEnv')
    PlotEnv = get(eplotHndl,'Value');
elseif strcmp(action, 'scale')  %auto set scale
    %find last cycle of data, usually 24 hours
    ymin = -1;
    ymax = -1;
    for i = 1:size(y_ops,2)
        if y_ops(1,i) > 0
            idx = BlockIndexes{i} + 1; %plus one as row 1 is time
            m = lastDay(idx,:);
            if size(m,1) > 1
                m = sum(m);%sum of 1 or more ops for each timepoint
            end
             if ymin > min(m) |  ymin < 0
                 ymin = min(m);  
             end
             if ymax < max(m)
                 ymax = max(m);
             end
        end
    end
    if ymax <= ymin
        ymax = ymin + 1;
    end
    set(axHndl, 'YLim',[ymin ymax]);

elseif strcmp(action, 'reduceScale')
    ax = get(axSelectHndl, 'Value');
    if (ax == 1 | ax == 2) %x axis
       time_to_plot = (xmax-xmin) * 2;
        xmin = floor(t);
        xmax = xmin + time_to_plot;
        cp = ((xmax-xmin)/5);
        tv = [xmin:cp:xmax]; 
        set(axHndl, 'XTick', tv);
        set(axHndl, 'XLim',[xmin xmax]);
        t_toplot = t_toplot(end);
        y_toplot = y_toplot(:,end);
        env_toplot = env_toplot(end);
    end
    if (ax == 1 | ax == 3)
        ymin = ymin / 2;
        ymax = ymax * 2;
        set(axHndl, 'YLim',[ymin ymax]);
    end
elseif strcmp(action, 'enlargeScale')
    ax = get(axSelectHndl, 'Value');
    if (ax == 1 | ax == 2)
        time_to_plot = (xmax-xmin) / 2;
        xmin = floor(t);
        xmax = xmin + time_to_plot;
        cp = ((xmax-xmin)/5);
        tv = [xmin:cp:xmax]; 
        set(axHndl, 'XTick', tv);
        if xmax <= xmin
            xmax = xmin + 1;
        end
        set(axHndl, 'XLim',[xmin xmax]);
        t_toplot = t_toplot(end);
        y_toplot = y_toplot(:,end);
        env_toplot = env_toplot(end);
    end
    if (ax == 1 | ax == 3)
        ymin = ymin * 2;
        ymax = ymax / 2;
        if ymax <= ymin
            ymax = ymin + 1;
        end
        set(axHndl, 'YLim',[ymin ymax]);
    end
elseif strcmp(action, 'record')
    r = get(recHndl, 'Value');
    if r == 0
        recording = 0;
        set(recHndl, 'CData', GetImage('RecordOff'));
       % feature ('javafigures',1);
    else
        recording = 1;
        set(recHndl, 'CData', GetImage('RecordOn'));
      %  feature ('javafigures',0);
    end 
elseif isnumeric(action)
    if y_ops(1,action) > 0
        y_ops(1,action) = 0;
        set(head(action), 'visible', 'off');
        set(tail(action), 'visible', 'off');
    else
        y_ops(1,action) = 1;
        set(head(action), 'visible', 'on');
        set(tail(action), 'visible', 'on');
    end
end;    % if strcmp(action, ...
 
%============================================
function v = GetParamValues(pFile, m)

[Names, Values] = textread(strcat(pFile, '.pv'),'%[^=]%*c%f');

v = zeros(size(m, 1),1);
for i = 1:size(m,1);
    for j = 1:size(Names, 1); %search names for a match with state name
        %when found, get corresponding value
        if strcmp(Names(j), m(i)) ~= 0;
            v(i) = Values(j);
        end
    end
end

%============================================
function SetParamsFile(fp, pFile)

global pnames;
global y0;
global pValues;
global pDefValues;
global pValues;
global modelname;
global spaces;
global pHndl;
global valHndl;
  
%read initial states and constants from values file made by interface file
opkeys = textread(strcat(modelname, '.sts'),'%*d,%[^,]%*[^\n]');
y0 = GetParamValues(strcat(fp, pFile), opkeys);    %remove ox states???

pnames = textread(strcat(modelname, '.prm'),'%*d,%[^,]%*[^\n]');
pValues = GetParamValues(strcat(fp, pFile), pnames);
for i = 1:size(pnames,1)
    pnames{i} = char(strcat(pnames{i}, spaces, num2str(pValues(i))));
end
pDefValues = pValues;


%===========================================
function SetEnvFile(fp, eFile)

global envDefValues;
global envValues;
global envparamsHndl;
global envValHndl;
global envParams;
global LIGHT_COLS
global TEMPERATURE;
global spaces;
global modelEnvs;
global defpulselen;
global defldcp ;   
global defon;
global defoff;
global defion;
global defioff;
global defion;
global deftcp;
global defton;
global deftoff;
global defhtemp;
global deflowtemp;
global defhtemp;
global defpulselen;
global envNames;

%get default env params from file
try
    if ~isempty(LIGHT_COLS) | TEMPERATURE > 0
        fid = fopen(strcat(fp,eFile, '.env'), 'rt');
    end
    
    if ~isempty(LIGHT_COLS)
        defon = zeros(size(LIGHT_COLS,1),1);
        defoff = ones(size(LIGHT_COLS,1),1) * 12;
        defion = ones(size(LIGHT_COLS,1),1);
        defioff = zeros(size(LIGHT_COLS,1),1);
        i = [];
        while isempty(i) & ~feof(fid)
            str = fgets(fid);
            i= strfind(str, '(ld=');
        end
        type = str(i+4:end-1);
        num_col = size(LIGHT_COLS,1);
        ldvals = [];
        str = fgets(fid);
        while str(1) ~= '(' & ~feof(fid)
            if strncmp(str, 'Regime1', 7)   %only bother with first regime
                temp.Name = str(1:strfind(str, '=') - 1);
                temp.Value = str2double(str(strfind(str, '=') + 1:end));
                ldvals = [ldvals temp];
            end
            str = fgets(fid);
        end

        for j = 1:size(ldvals,2)
            if strcmp(ldvals(j).Name, 'Regime1CP') ~= 0
                defldcp = ldvals(j).Value;
            end
        end
        
        for col = 1:num_col 
            search_str = strcat('Regime1', char(LIGHT_COLS{col}));  %RegimeXColour
            for j = 1:size(ldvals,2)
                if strcmp(ldvals(j).Name, strcat(search_str, 'On')) ~= 0
                    defon(col) = ldvals(j).Value; 
                elseif strcmp(ldvals(j).Name, strcat(search_str, 'Off')) ~= 0
                    defoff(col) = ldvals(j).Value;
                elseif strcmp(ldvals(j).Name, strcat(search_str, 'Ion')) ~= 0
                    defion(col) = ldvals(j).Value;   
                elseif strcmp(ldvals(j).Name, strcat(search_str, 'Ioff')) ~= 0
                    defioff(col) = ldvals(j).Value;  
                end
            end
        end
    end
    if TEMPERATURE > 0
        defton = 0;
        deftoff = 12;
        defhtemp =  25;
        deflowtemp = 10;
        i = [];
        frewind(fid);
        while isempty(i) & ~feof(fid)
            str = fgets(fid);
            i= strfind(str, '(temp=');
        end
        type = str(i+6:end-1);
        tempvals = [];
        str = fgets(fid);
        while str(1) ~= '(' & ~feof(fid)
            if strncmp(str, 'TempRegime1', 11)   %
                temp.Name = str(1:strfind(str, '=') - 1);
                temp.Value = str2double(str(strfind(str, '=') + 1:end));
                tempvals = [tempvals temp];
            end
            str = fgets(fid);
        end
        for j = 1:size(tempvals,2)
            if strcmp(tempvals(j).Name, 'TempRegime1CP') ~= 0
                deftcp = tempvals(j).Value;
            end
        end
        search_str = 'TempRegime1';
        for j = 1:size(tempvals,2)
            if strcmp(tempvals(j).Name, strcat(search_str, 'TemperatureOn')) ~= 0
                defton = tempvals(j).Value; 
            elseif strcmp(tempvals(j).Name, strcat(search_str, 'TemperatureOff')) ~= 0
                deftoff = tempvals(j).Value;
            elseif strcmp(tempvals(j).Name, strcat(search_str, 'TemperatureTon')) ~= 0
                defhtemp = tempvals(j).Value;   
            elseif strcmp(tempvals(j).Name, strcat(search_str, 'TemperatureToff')) ~= 0
                deflowtemp = tempvals(j).Value;  
            end
        end 
    end
    if ~isempty(LIGHT_COLS) | TEMPERATURE > 0
        status = fclose(fid);
    end
catch
    ShowError(strcat({'The environemt file '}, eFile, {' cannot be read. Using default values instead'})); 
    status = fclose(fid);
    if ~isempty(LIGHT_COLS)
        defldcp = 24;
        defon = zeros(size(LIGHT_COLS,1),1);
        defoff = ones(size(LIGHT_COLS,1),1) * 12;
        defion = ones(size(LIGHT_COLS,1),1);
        defioff = zeros(size(LIGHT_COLS,1),1);  
    end
    if TEMPERATURE > 0
        deftcp = 24;
        defton = 0;
        deftoff = 12;
        defhtemp =  25;
        deflowtemp = 10;
    end
end
modelEnvs = cell(0);
envValues = [];
defpulselen = 1;
if ~isempty(LIGHT_COLS)
    for i = 1:size(LIGHT_COLS,1)
        envValues = [envValues; defldcp defon(i) defoff(i) defion(i) defioff(i) defion(i) defpulselen];
        modelEnvs = [modelEnvs; LIGHT_COLS(i)]; 
    end 
end
 
if TEMPERATURE > 0
    envValues = [envValues; deftcp defton deftoff defhtemp deflowtemp defhtemp defpulselen]; 
    modelEnvs = [modelEnvs; {'Temperature'}];
end

if isempty(modelEnvs)
    modelEnvs = {'NA'};
end

envDefValues = envValues;

%============================================
function ShowError(msg)

msgbox(msg,'An Error Has Occurred','error','modal');
   
%============================================
function result = SplitString(ln)
%returns col vector of names, can't cope with multiple consecutive spaces.
%remove trailing blanks
line = char(ln);
if size(line,2) <= 1    %no colours
    result = {};
else
    while isspace(line(size(line,2))) & size(line,2) > 1
        line = line(1:size(line,2)-1);
    end 
    %remove any leading blanks
    while isspace(line(1)) & size(line,2) > 1
        line = line(2:size(line,2));
    end    
    %split 
    spaces = isspace(line);
    start = find(spaces);   %location of spaces in the list
    result = cell(size(start,2)+1,1);
    %first name has no space at start 
    if size(start,2) == 0   %only 1 colour
        result(1,1) = {line};
    else                    %more than 1
        result(1,1) = {line(1:start(1)-1)};
        for i = 1:size(start,2)-1
            result(i+1,1) = {line(start(i)+1:start(i+1)-1)};    
        end
        %last name has no space at end
        result(size(result,1),1) = {line(start(size(start,2))+1:size(line,2))};
    end
end

%======================================================
function [val, day] = GetLD(t)

global LIGHT_COLS;
global pulseOn;
global envHndl;
global envValues;

if isempty(LIGHT_COLS)
    val = [];
    day = 0;
else
    day = zeros(size(LIGHT_COLS,1));
    currentLight = get(envHndl, 'Value');%one selected
    %vector with entry for each colour
    val = zeros(size(LIGHT_COLS,1));
    for i = 1:size(LIGHT_COLS,1)
        %for each colour
        cp = envValues(i,1);    %cp for that colour
        dawn = envValues(i,2);
        dusk = envValues(i,3);
        onVal = envValues(i,4);
        offVal = envValues(i,5);
        pulseVal = envValues(i,6);
        pulseLen= envValues(i,7);
        if dusk > cp
            dusk = cp;
        end
        if dawn > dusk
            dawn = dusk;
        end
      
        if pulseOn(i) > 0 & t >= pulseOn(i) & t < (pulseOn(i) + pulseLen)
            val(i) = pulseVal;
        else
            if mod(t,cp) >= dawn & mod(t,cp) < dusk
                val(i) = onVal;
            else
                val(i) = offVal;
            end
        end
        day(i) = val(i)/onVal;
    end   
end

%======================================================
function [val, day] = GetTemp(t)

global TEMPERATURE;
global envValues;
global pulseOn;
global envHndl;
global modelEnvs;

if TEMPERATURE == 0 
   val = [];
   day = 0;
else
    day = 0;
    cp = envValues(end,1);    %cp for that colour
    dawn = envValues(end,2);
    dusk = envValues(end,3);
    onVal = envValues(end,4);
    offVal = envValues(end,5);
    pulseVal = envValues(end,6);
    pulseLen= envValues(end,7);
        
    if dusk > cp
        dusk = cp;
    end
    if dawn > dusk
        dawn = dusk;
    end       
    if  pulseOn(end) > 0 & t >= pulseOn(end) & t < (pulseOn(end) + pulseLen)
        val = pulseVal;
    else
        if mod(t,cp) >= dawn & mod(t,cp) < dusk
            val = onVal;
        else
            val = offVal;
        end
    end
    currentEnv = get(envHndl, 'Value');%one selected
    if (currentEnv == size(modelEnvs,1)) & val ~= offVal
        day = 1;
    end
end

%========================================================
function val = GetCP()  %cp of colour selected

global envValues;
global envHndl;

if ~isempty(envValues)
    currentEnv = get(envHndl, 'Value');%one selected
    val = envValues(currentEnv,1);
else
   val = 24;%model has no ld or temp 
end

%==========================================================
function FillParamsControls()


global pHndl;
global pnames;
global valHndl;
global pValues;

set(pHndl,'String', pnames);
set(pHndl,'Value', 1);
set(valHndl,'String', pValues(1));

%===========================================================
function FillEnvControls(idx)

global envparamsHndl;
global envParams;
global envValHndl;

global envValues;
global TEMPERATURE;
global defpulselen;
global LIGHT_COLS;
global defldcp ;   
global defon;
global defoff;
global defion;
global defioff;
global defion;
global deftcp;
global defton;
global deftoff;
global defhtemp;
global deflowtemp;
global defhtemp;
global defpulselen;
global spaces;

if nargin < 1
    idx = 1;
end


defpulselen = 1;

if ~isempty(LIGHT_COLS)
    if idx <= size(LIGHT_COLS,1)
        %light selected
        selected = 'ld';
    elseif TEMPERATURE > 0
        %temp
        selected = 'temp';
    else
        % no env
        selected = 'none';
    end   
elseif TEMPERATURE > 0
    selected = 'temp';
else
    %no env
    selected = 'none';
end
        
envParamsList = cell(7);
if strcmp(selected,'ld')
     envParamsList = [{char(strcat('LD Cycle Period',spaces,num2str(envValues(idx,1))))}; ... 
                {char(strcat('On Time',spaces,num2str(envValues(idx,2))))}; ...
                {char(strcat('Off Time',spaces,num2str(envValues(idx,3))))}; ...
                {char(strcat('On Value',spaces,num2str(envValues(idx,4))))}; ...
                {char(strcat('Off Value',spaces,num2str(envValues(idx,5))))}; ...
                {char(strcat('Pulse Value',spaces,num2str(envValues(idx,6))))}; ...
                {char(strcat('Pulse Length',spaces,num2str(envValues(idx,7))))}];
elseif strcmp(selected,'temp')
    envParamsList = [{char(strcat('Temp Cycle Period',spaces,num2str(envValues(idx,1))))}; ... 
                {char(strcat('On Time',spaces,num2str(envValues(idx,2))))}; ...
                {char(strcat('Off Time',spaces,num2str(envValues(idx,3))))}; ...
                {char(strcat('High Value',spaces,num2str(envValues(idx,4))))}; ...
                {char(strcat('Low Value',spaces,num2str(envValues(idx,5))))}; ...
                {char(strcat('Pulse Value',spaces,num2str(envValues(idx,6))))}; ...
                {char(strcat('Pulse Length',spaces,num2str(envValues(idx,7))))}]; 
end

if ~strcmp(selected,'none')
    set(envparamsHndl,'String', envParamsList);
    set(envparamsHndl,'Value', 1);
    set(envValHndl,'String', envValues(idx,1));
end
%==========================================================
function img = GetImage(idx)

global btncol;

img = ones(16,16,3);
for i = 1:16
    for j = 1:16
        img(i,j,:) = btncol;
    end
end

if strcmp(idx, 'Start')
    for i = 1:15    %start button arrow
        for j = 0:(7 - abs(8 - i))
            img(i,5+j,:) = [ 0 0 1];
        end
    end
elseif strcmp(idx, 'Stop')
    for i = 5:12   
        for j = 5:12
            img(i,j,:) = [ 0 0 1];
        end
    end
elseif strcmp(idx, 'RecordOff')
    for i = 5:12   
        for j = 5:12
            img(i,j,:) = [ 0 0 1];
        end
    end
    for j = 7:10
       img(4,j,:) = [0 0 1]; 
       img(13,j,:) = [0 0 1]; 
    end
    for i = 7:10
       img(i,4,:) = [0 0 1]; 
       img(i,13,:) = [0 0 1]; 
    end
elseif strcmp(idx, 'RecordOn')
    for i = 5:12   
        for j = 5:12
            img(i,j,:) = [1 0 0 ];
        end
    end
    for j = 7:10
       img(4,j,:) = [1 0 0]; 
       img(13,j,:) = [1 0 0]; 
    end
    for i = 7:10
       img(i,4,:) = [1 0 0]; 
       img(i,13,:) = [1 0 0]; 
    end
else
    for i = 5:12
       img(i,5,:) = [0 0 1]; 
       img(i,6,:) = [0 0 1]; 
       img(i,11,:) = [0 0 1]; 
       img(i,12,:) = [0 0 1]; 
    end
end


%====================================================
function LoadingTime(p)

persistent fg;
persistent progbar;


if nargin == 0
    %increment
    p = get(progbar, 'Position');
    p(3) = p(3) + 0.075;
    set(progbar, 'Position', p); 
    drawnow;
elseif strcmp(p, 'init')
    scrsz = get(0,'ScreenSize');
    pos = [scrsz(3)* (3/8) scrsz(4)* (11/24) scrsz(3)/4 scrsz(4)/12];

    fg=figure( 'Name','Loading...','Position', pos, 'NumberTitle','off','Visible','on', ...
        'Menubar', 'none', 'Resize', 'off', 'Toolbar', 'none');
    progbar=uicontrol( ...
        'Style','frame', ...
        'Units','normalized', ...
        'Position',[0.125 0.333 0.075  0.333], ...
        'BackgroundColor',[0 0 1]);
    drawnow;
elseif strcmp(p, 'finished')
    set(progbar, 'Position', [0.125 0.333 0.75  0.333]);
    drawnow;
    delete(fg);
    if exist('Launching.txt', 'file') == 2
        delete('Launching.txt');
    end
end

%======================================================
function [idximg, colmap] = RGBtoIndx(img)
%converts an rgb image to an indexed image and colourmap
persistent lastimg;
persistent lastidximg;
persistent map;

if 1%isempty(lastimg)
    map = zeros(256,3);
    idximg = zeros(size(img,1), size(img,2));
    for row = 1:size(img,1)
        for col = 1:size(img,2)
            pc = [0 0 0];
            pc(1) = img(row,col,1);
            pc(2) = img(row,col,2);
            pc(3) = img(row,col,3);
            if sum(pc == [0 0 0]) < 3
                for i = 2:size(map,1)
                    mc = [0 0 0];
                    mc(1) = map(i,1);
                    mc(2) = map(i,2);
                    mc(3) = map(i,3);
                    if sum(mc == [0 0 0]) == 3
                        map(i,1) = pc(1);
                        map(i,2) = pc(2);
                        map(i,3) = pc(3);
                        idximg(row,col) = i;
                        break;
                    elseif mc == pc
                        idximg(row,col) = i;
                        break;
                    end
                end
            end
        end
    end
    lastimg = img;
    lastidximg = idximg;
    for row = 1:size(map,1)
        for col = 1:size(map,2)
            if map(row,col) > 1
                map = map./255;
                colmap = map;
                return;
            end
        end
    end
    colmap = map;
else
    idximg = lastidximg;
    for row = 1:size(img,1)
        for col = 1:size(img,2)
            if sum(img(row,col,:) == lastimg(row,col,:)) < 3
                %changed since last frame
                if sum(img(row,col,:)) == 0
                    idximg(row,col) = 1;
                else
                    for i = 2:size(map,1)
                        if map(i,1) == img(row,col,1) & map(i,2) == img(row,col,2) & map(i,3) == img(row,col,3)  
                            idximg(row,col) = i;
                            break;
                        elseif sum(map(i,:)) == 0
                            map(i,1) = img(row,col,1);
                            if map(i,1) > 1
                                map(i,1) = map(i,1) / 255;
                            end
                            map(i,2) = img(row,col,2);
                            if map(i,2) > 1
                                map(i,2) = map(i,2) / 255;
                            end
                            map(i,3) = img(row,col,3);
                            if map(i,3) > 1
                                map(i,3) = map(i,3) / 255;
                            end
                            idximg(row,col) = i;
                            break;
                        end        
                    end
                end
            end
        end
    end
    lastimg = img;
    lastidximg = idximg;
    colmap = map;
end



%========================================================
function SetAxes

global y_ops;
global head;
global tail;
global envLine;
global PlotEnv;
global Blocks;

head = [];
tail = [];
for i = 1:size(y_ops,2)
    if y_ops(i) ~= 0
        v = 'on';
    else
        v = 'off';  %visibility of lines
    end
    if strcmp(get(Blocks(1,i), 'Tag'),'e')
        mk = '.';
        mks = 21;
    else
        mk = 's';
        mks=7;
    end
    head = [head; line('Marker', mk, 'MarkerSize', mks,'erase','xor', 'xdata', [], 'ydata', [], 'zdata', [],'Visible', v)];
    tail = [tail; line('LineStyle','-', 'erase','xor', 'xdata', [], 'ydata', [],'zdata', [], 'Visible', v)]; 
    envLine = line('LineStyle','-', 'erase','xor', 'xdata', [], 'ydata', [], 'Visible', v);
end
if PlotEnv == 0
    v = 'off';
end

%===================================================
function s = GetAVIName()

r = 1;
while exist(strcat('recording', num2str(r), '.avi'), 'file') == 2
    r = r + 1;
end
s = strcat('recording', num2str(r), '.avi');



%====================================================
function dydt = equations(t, y, pPV, pLD, pTEMP)

global ArrowSizes;
global LightSizes;
global NumStates;

P = pPV;
LD_VAL = pLD;
TEMP_VAL = pTEMP;
NumStates = size(y,1);

%TO DO : INSERT EQUATIONS HERE
Dark = 1 - LD_VAL(1);
if Dark < 0 
    Dark = 0;
end

LHYox = y(14);
TOC1ox = y(15);
Xox = y(16);
Yox = y(17); 


dydt = zeros(17,1);
% cLm - Level of LHY mRNA
dydt(1) = LD_VAL(1)*P(1)*y(13)+(P(2)*(y(9))^P(3))/(P(4)^P(3) + (y(9))^P(3)) - (P(5)*y(1))/(P(6) + y(1));
% cLc - Level of cytoplasmic LHY protein
dydt(2) = P(66)*LHYox+P(7)*y(1) - P(8)*y(2) + P(9)*y(3) - (P(10)*y(2))/(P(11) + y(2));
% cLn - Level of nuclear LHY protein
dydt(3) = P(8)*y(2) - P(9)*y(3) - (P(12)*y(3))/(P(13) + y(3));
% cTm - Level of TOC1 mRNA
dydt(4) = ( (P(14)*(y(12)^P(15))) / (P(16)^P(15) + y(12)^P(15)) ) * ((P(17)^P(18)) / (P(17)^P(18) + y(3)^P(18))) - (P(19)*y(4))/(P(20) + y(4));
% cTc - Level of cytoplasmic TOC1 protein
dydt(5) = P(67)*TOC1ox+P(21)*y(4) - P(22)*y(5) + P(23)*y(6) - (Dark * P(24) + P(25)) * ((y(5)) /(P(26) + y(5)) );
% cTn - Level of nuclear TOC1 protein
dydt(6) = P(22)*y(5) - P(23)*y(6)- (Dark * P(27) + P(28)) * ((y(6))/ (P(29) + y(6)));
% cXm - Level of X mRNA
dydt(7) = (P(30) * (y(6))^P(31))/(P(32)^P(31) + (y(6))^P(31)) - (P(33) * y(7))/(P(34) + y(7));
% cXc - Level of cytoplasmic protein X
dydt(8) = P(68)*Xox+P(35)*y(7) - P(36)*y(8) + P(37)*y(9) - (P(38) * y(8))/(P(39) + y(8));
% cXn - Level of nuclear protein X
dydt(9) = P(36)*y(8) - P(37)*y(9) - (P(40)*y(9))/(P(41) + y(9));
% cYm - Level of Y mRNA
dydt(10) = (LD_VAL(1)*P(42)*y(13) + ((LD_VAL(1)*P(43) + P(44))*(P(45)^P(48)) /( P(45)^P(48) + y(6)^P(48)))) * ((P(46)^P(47)) / (P(46)^P(47) + y(3)^P(47))) - (P(49)*y(10))/(P(50) + y(10));
% cYc - Level of cytoplasmic protein Y
dydt(11) = P(69)*Yox+P(51)*y(10) - P(52)*y(11) + P(53)*y(12) - (P(54)*y(11))/(P(55) + y(11));
% cYn - Level of nuclear protein Y
dydt(12) = P(52)*y(11) - P(53)*y(12) - (P(56)*y(12))/(P(57)+y(12));
% cPn - Level of nuclear protein P
dydt(13) = P(70)+ Dark * P(58) - (P(61)*y(13))/(P(59) + y(13)) - P(60) * LD_VAL(1)* y(13);
% cLmox - Level of LHY mRNA from constitutive gene
dydt(14) = P(62)-(P(5)*LHYox)/(P(6)+LHYox);
% cTmox - Level of TOC1 mRNA from constitutive gene
dydt(15) = P(63)-(P(19)*TOC1ox)/(P(20)+TOC1ox);
% cXmox - Level of protein X mRNA from constitutive gene
dydt(16) = P(64) - (P(33)*Xox)/(Xox + P(34));
% cYmox - Level of protein Y mRNA from constitutive gene
dydt(17) = P(65) - (P(49)*Yox)/(Yox + P(50));


%Rates control arrow thicknesses

ArrowSizes = [P(66)*LHYox+P(7)*y(1); ...
        1/(((P(17)^P(18)) / (P(17)^P(18) + y(3)^P(18)))); ...
        1/(((P(46)^P(47)) / (P(46)^P(47) + y(3)^P(47)))); ...
        P(67)*TOC1ox+P(21)*y(4); ...
        1/(((LD_VAL(1)*P(43) + P(44))*(P(45)^P(48)) /( P(45)^P(48) + y(6)^P(48)))); ...
        P(69)*Yox+P(51)*y(10); ...
        ( (P(14)*(y(12)^P(15))) / (P(16)^P(15) + y(12)^P(15)) ); ...
        (P(30) * (y(6))^P(31))/(P(32)^P(31) + (y(6))^P(31)); ...
        P(68)*Xox+P(35)*y(7); ...
        (P(2)*(y(9))^P(3))/(P(4)^P(3) + (y(9))^P(3))
        ];
a  =LD_VAL(1)*P(42)*y(13) + ((LD_VAL(1)*P(43) + P(44))*(P(45)^P(48)) /( P(45)^P(48) + y(6)^P(48)));
LightSizes = [LD_VAL(1)*y(13); LD_VAL(1); a];

%==============================================================
function [blocks, subblocks, positions, indexes, subindexes, light, lightidx, temp, arrows, arrowheads, lightarrowheads] = DrawModel()

global maxSize;
global maxHeadSize;
global linewidth;
global colours;
global lcolours;
global dcolours;
global opIndexes;
global naxHndl;

%% Create figure
%figure1 = gcf;

linecol = [1 1 1];  %white
linewidth = 10;
maxHeadSize = 30;
colours = [1 1 0; 0 1 1; 0 1 0;1 0 1; 1 0 0;0 0 1; 1 1 1];   %yellow, cyan, green, magenta, red, blue, white
lcolours = [1 1 0; 0 1 1; 0 1 0;1 0 1; 1 0 0;0 0 1; 1 1 1];   %yellow, cyan, green, magenta, red, blue, white
dcolours = [0.5 0.5 0; 0 0.5 0.5; 0 0.5 0;0.5 0 0.5; 0.5 0 0;0 0 0.5; 0.5 0.5 0.5];   %yellow, cyan, green, magenta, red, blue, white


%blocks = [];subblocks = [];positions =[];indexes = [];subindexes = []; light = [];lightidx = [];temp=[];arrows=[];return;

%% Create lines
%col 1 is handle to arrow, col 2 indicates what controls its thickness
 arrows = [ ...
            line('Parent', naxHndl,'XData', [0.55 0.95],'YData', [0.95 0.95],'LineWidth',linewidth,'Color',linecol, 'Tag', 'l') 1 0; ...
            line('Parent', naxHndl,'XData', [0.95 0.95],'YData',[0.675 0.05],'LineWidth',linewidth,'Color',linecol, 'Tag', 'l') 3 0; ...
            line('Parent', naxHndl,'XData', [0.95 0.95],'YData',[0.675 0.5],'LineWidth',linewidth,'Color',linecol, 'Tag', 'l') 2 0; ...
            line('Parent', naxHndl,'XData', [0.05 0.05],'YData',[0.05 0.45],'LineWidth',linewidth,'Color',linecol, 'Tag', 'l') 5 0; ...
           ];

%arrows, col2 is index controlling what sets the thickness of the arrow
arrows = [arrows; ...
            line('Parent', naxHndl,'XData', [0.95 0.95],'YData',[0.95 0.875],'LineWidth',linewidth,'Color',linecol, 'Tag', 'a') 1 1; ...
            line('Parent', naxHndl,'XData', [0.05 0.05],'YData',[0.55 0.575],'LineWidth',linewidth,'Color',linecol, 'Tag', 'a') 8 3; ...
            line('Parent', naxHndl,'XData', [0.45 0.2],'YData',[0.5 0.5],'LineWidth',linewidth,'Color',linecol, 'Tag', 'a') 4 2; ...
            line('Parent', naxHndl,'XData', [0.05 0.05],'YData',[0.775 0.8],'LineWidth',linewidth,'Color',linecol, 'Tag', 'a') 9 4; ...
            line('Parent', naxHndl,'XData', [0.1 0.35],'YData',[0.95 0.95],'LineWidth',linewidth,'Color',linecol, 'Tag', 'a') 10 5; ...
            line('Parent', naxHndl,'XData', [0.5 0.5],'YData',[0.1 0.125],'LineWidth',linewidth,'Color',linecol, 'Tag', 'a') 6 8; ...
            line('Parent', naxHndl,'XData', [0.5 0.5],'YData',[0.325 0.35],'LineWidth',linewidth,'Color',linecol, 'Tag', 'a') 7 9; ...
        ];
%inhibitory arrows
arrows = [arrows; ...
            line('Parent', naxHndl,'XData', [0.95 0.55],'YData', [0.5 0.5], 'LineWidth',linewidth,'Color',linecol, 'Tag', 'a') 2 10; ...
            line('Parent', naxHndl,'XData',[0.95 0.55],'YData', [0.05 0.05], 'LineWidth',linewidth,'Color',linecol, 'Tag', 'a') 3 7; ...
            line('Parent', naxHndl,'XData',[0.05 0.45],'YData', [0.05 0.05], 'LineWidth',linewidth,'Color',linecol, 'Tag', 'a') 5 6; ...
        ];
%light handles returned so can be turned on and off
light = [ ...
        line('Parent', naxHndl,'XData', [0.275 0.1],'YData', [0.725 0.55],'LineWidth',linewidth,'LineStyle',':','Color',[1 1 0], 'Tag', '[1 1 0]') ...
        line('Parent', naxHndl,'XData', [0.275 0.45],'YData', [0.725 0.9],'LineWidth',linewidth,'LineStyle',':','Color',[1 1 0], 'Tag', '[1 1 0]') ...
        line('Parent', naxHndl,'XData', [0.725 0.55],'YData', [0.275 0.1],'LineWidth',linewidth,'LineStyle',':','Color',[1 1 0], 'Tag', '[1 1 0]') ...
        ];        %annotation(figure1,'arrow',[0.475 0.475],[0.95 0.55],'LineWidth',10,'LineStyle',':','Color',[1 1 0],'HeadStyle','rectangle', 'HeadWidth',30,'HeadLength',8,  'Tag', '[1 1 0]') ...
lightarrowheads = [ ...
                  fill([0.1; 0.2; 0.1] ,[0.55;0.55; 0.65],[1 1 0],'Parent', naxHndl, 'EdgeColor', [1 1 0], 'Tag', 'ld') ...
                  fill([0.45; 0.35; 0.45] ,[0.9;0.9; 0.8],[1 1 0],'Parent', naxHndl, 'EdgeColor', [1 1 0], 'Tag', 'ru') ...
                  fill([0.55; 0.65; 0.55] ,[0.1;0.1; 0.2],[1 1 0],'Parent', naxHndl, 'EdgeColor', [1 1 0], 'Tag', 'ld') ...
                    ];
lightidx = [2 1 3];

arrowheads =[ ...
            fill([0.95; 1; 0.9] ,[0.775;0.875; 0.875],linecol,'Parent', naxHndl, 'EdgeColor', linecol, 'Tag', 'd');
            fill([0.1; 0.2; 0.2] ,[0.5;0.45; 0.55],linecol,'Parent', naxHndl, 'EdgeColor', linecol, 'Tag', 'l');
            fill([0.05; 0; 0.1] ,[0.675;0.575; 0.575],linecol,'Parent', naxHndl, 'EdgeColor', linecol, 'Tag', 'u');
            fill([0.05; 0; 0.1] ,[0.9;0.8; 0.8],linecol,'Parent', naxHndl, 'EdgeColor', linecol, 'Tag', 'u');
            fill([0.45; 0.35; 0.35] ,[0.95;1; 0.9],linecol,'Parent', naxHndl, 'EdgeColor', linecol, 'Tag', 'r');
            fill([0.45; 0.45; 0.4; 0.4] ,[0;0.1;0.1;0],linecol,'Parent', naxHndl, 'EdgeColor', linecol, 'Tag', 'ir');
            fill([0.6; 0.6; 0.55; 0.55] ,[0;0.1;0.1;0],linecol,'Parent', naxHndl, 'EdgeColor', linecol, 'Tag', 'il');
            fill([0.5; 0.45; 0.55] ,[0.225;0.125; 0.125],linecol,'Parent', naxHndl, 'EdgeColor', linecol, 'Tag', 'u');
            fill([0.5; 0.45; 0.55] ,[0.45; 0.35; 0.35],linecol,'Parent', naxHndl, 'EdgeColor', linecol, 'Tag', 'u');
            fill([0.6; 0.6; 0.55; 0.55] ,[0.45;0.55;0.55;0.45],linecol,'Parent', naxHndl, 'EdgeColor', linecol, 'Tag', 'il');
            ];

 temp = [];
%RNAs
lhyRNA = [0.5 0.95]; %coordinates of center
yRNA = [0.5 0.05];
xRNA = [0.05 0.725];
toc1RNA = [0.5 0.5];
maxSize = 0.1;

hlhyRNA = rectangle('Parent', naxHndl,'Curvature', 1, 'Position',[lhyRNA(1) - maxSize/2 lhyRNA(2) - maxSize/2 maxSize maxSize],'FaceColor',colours(3,:),'LineStyle','none', 'Tag', 'e', 'ButtonDownFcn', 'locke_05b_network(1)');
hxRNA = rectangle('Parent', naxHndl,'Curvature', 1, 'Position',[xRNA(1) - maxSize/2 xRNA(2) - maxSize/2 maxSize maxSize],'FaceColor',colours(1,:),'LineStyle','none', 'Tag', 'e', 'ButtonDownFcn', 'locke_05b_network(5)');
htoc1RNA = rectangle('Parent', naxHndl,'Curvature', 1, 'Position',[toc1RNA(1) - maxSize/2 toc1RNA(2) - maxSize/2 maxSize maxSize],'FaceColor',colours(5,:),'LineStyle','none', 'Tag', 'e', 'ButtonDownFcn', 'locke_05b_network(3)');
hyRNA = rectangle('Parent', naxHndl,'Curvature', 1, 'Position',[yRNA(1) - maxSize/2 yRNA(2) - maxSize/2 maxSize maxSize],'FaceColor',colours(2,:),'LineStyle','none', 'Tag', 'e', 'ButtonDownFcn', 'locke_05b_network(7)');

%labels
fs = 10;
text('Parent', naxHndl,'FontSize',fs, 'Position',[0.5 0.85],'Color',[1 1 1],'HorizontalAlignment','left','String',{'LHY', 'mRNA'},'Interpreter','none');
text('Parent', naxHndl,'FontSize',fs, 'Position',[0.35 0.125],'Color',[1 1 1],'HorizontalAlignment','left','String',{'Y mRNA'},'Interpreter','none');
text('Parent', naxHndl,'FontSize',fs, 'Position',[0.125 0.725],'Color',[1 1 1],'HorizontalAlignment','left','String',{'X mRNA'},'Interpreter','none');
text('Parent', naxHndl,'FontSize',fs, 'Position',[0.45 0.6],'Color',[1 1 1],'HorizontalAlignment','left','String',{'TOC1', 'mRNA'},'Interpreter','none');

%proteins
lhyProtein = [0.95 0.725]; %coordinates of center
yProtein = [0.5 0.275];
xProtein = [0.05 0.95];
toc1Protein = [0.05 0.5];
%pProtein = [0.475 0.5];

%nuclear proteins
nlhyProtein = lhyProtein; %coordinates of center
nyProtein = yProtein;
nxProtein = xProtein;
ntoc1Protein = toc1Protein;

colours = [1 1 0; 0 1 1; 0 1 0;1 0 1; 1 0 0;0 0 1; 1 1 1];   %yellow,
%cyan, green, magenta, red, blue, white
%dark cytoplasmic, light nuclear
hlhyProtein = rectangle('Parent', naxHndl,'Position', [lhyProtein(1) - maxSize/2 lhyProtein(2) - maxSize/2 maxSize maxSize],'FaceColor',dcolours(3,:),'LineStyle','-', 'Tag', 'r', 'ButtonDownFcn', 'locke_05b_network(2)');
hxProtein = rectangle('Parent', naxHndl,'Position', [xProtein(1) - maxSize/2 xProtein(2) - maxSize/2 maxSize maxSize],'FaceColor',dcolours(1,:),'LineStyle','-', 'Tag', 'r', 'ButtonDownFcn', 'locke_05b_network(6)');
htoc1Protein = rectangle('Parent', naxHndl,'Position', [toc1Protein(1) - maxSize/2 toc1Protein(2) - maxSize/2 maxSize maxSize],'FaceColor',dcolours(5,:),'LineStyle','-', 'Tag', 'r', 'ButtonDownFcn', 'locke_05b_network(4)');
hyProtein = rectangle('Parent', naxHndl,'Position', [yProtein(1) - maxSize/2 yProtein(2) - maxSize/2 maxSize maxSize],'FaceColor',dcolours(2,:),'LineStyle','-', 'Tag', 'r', 'ButtonDownFcn', 'locke_05b_network(8)');
%hpProtein = annotation(figure1,'rectangle',[pProtein(1) - maxSize/2 pProtein(2) - maxSize/2 maxSize maxSize],'FaceColor',[1 0 1],'LineStyle','none');

hnlhyProtein = rectangle('Parent', naxHndl,'Position',  [nlhyProtein(1) - maxSize/2 nlhyProtein(2) - maxSize/2 maxSize maxSize],'FaceColor',lcolours(3,:),'LineStyle','-', 'Tag', 'r', 'ButtonDownFcn', 'locke_05b_network(2)');
hnxProtein = rectangle('Parent', naxHndl,'Position', [nxProtein(1) - maxSize/2 nxProtein(2) - maxSize/2 maxSize maxSize],'FaceColor',lcolours(1,:),'LineStyle','-', 'Tag', 'r', 'ButtonDownFcn', 'locke_05b_network(6)');
hntoc1Protein = rectangle('Parent', naxHndl,'Position', [ntoc1Protein(1) - maxSize/2 ntoc1Protein(2) - maxSize/2 maxSize maxSize],'FaceColor',lcolours(5,:),'LineStyle','-', 'Tag', 'r', 'ButtonDownFcn', 'locke_05b_network(4)');
hnyProtein = rectangle('Parent', naxHndl,'Position', [nyProtein(1) - maxSize/2 nyProtein(2) - maxSize/2 maxSize maxSize],'FaceColor',lcolours(2,:),'LineStyle','-', 'Tag', 'r', 'ButtonDownFcn', 'locke_05b_network(8)');

%labels
text('Parent', naxHndl,'FontSize',fs, 'Position',[0.825 0.725],'Color',[1 1 1],'HorizontalAlignment','left','String',{'LHY', 'Protein'},'Interpreter','none');
text('Parent', naxHndl,'FontSize',fs, 'Position',[0.35 0.275],'Color',[1 1 1],'HorizontalAlignment','left','String',{'Y Protein'},'Interpreter','none');
text('Parent', naxHndl,'FontSize',fs, 'Position',[0.125 0.9],'Color',[1 1 1],'HorizontalAlignment','left','String',{'X Protein'},'Interpreter','none');
text('Parent', naxHndl,'FontSize',fs, 'Position',[0.075 0.425],'Color',[1 1 1],'HorizontalAlignment','left','String',{'Toc1 Protein'},'Interpreter','none');
%annotation(figure1,'textbox','FontSize',fs, 'Position',[pProtein(1) - maxSize/2 pProtein(2) - maxSize*1.5 maxSize maxSize],'EdgeColor','none','LineStyle','none','Color',[1 1 1],'FitHeightToText','on','FontWeight','demi','HorizontalAlignment','center','String',{'P Protein'},'Interpreter','none');

%return vector of handels to blocks representing states
blocks = [hlhyRNA hlhyProtein htoc1RNA htoc1Protein hxRNA hxProtein hyRNA hyProtein; ...
            0 1 0 2 0 3 0 4]; %sub blocks
subblocks = [hnlhyProtein hntoc1Protein hnxProtein hnyProtein];

positions = [lhyRNA; lhyProtein; toc1RNA; toc1Protein; xRNA; xProtein; yRNA; yProtein];
indexes = cell(8,1); %indicates which block represents which state
indexes{1} = [1];
indexes{2} = [2 3]; %sum of two states
indexes{3} = [4];
indexes{4} = [5 6];
indexes{5} = [7];
indexes{6} = [8 9];
indexes{7} = [10];
indexes{8} = [11 12];

subindexes = cell(4,1); %indicates which block represents which state
subindexes{1} = [3];
subindexes{2} = [6];
subindexes{3} = [9];
subindexes{4} = [12];

%opIndexes = [hlhyRNA;hlhyProtein;hnlhyProtein]; %block for each state

%




 

 

 



 

  



Contact us at files@mathworks.com