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_plot(mode)
function locke_05b_plot(mode)

global LIGHT_COLS
global TEMPERATURE;
global modelname;
global spaces;
global eqns;
global listOfPFiles;
global listOfEFiles;
global paramFile;
global envFile;
global title;
global legend1;

if nargin == 0   %initialisation
     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);
    eqns = @equations;%eval(['!', char(modelname)]); 
    
    title = modelname;
    modelname = strcat(exePath, modelname);
    LoadingTime;
    vc;
else
    vc(mode);
end


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

global speed;
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 xopHndl;
global yopHndl;
global zopHndl;
global tsopHndl;
global styleHndl;
global dimHndl;
global numStates;
global numParams;
global pValues;
global pDefValues;
global envDefValues;
global envValues;
global xmin;
global xmax;
global ymin;
global ymax;
global zmin;
global zmax;
global x_op;
global y_op;
global z_op;
global opnames;
global numStates;
global numParams;
global tfinal;
global y0;
global pnames;
global lastDay;
global axHndl;
global numCycles;
global pulseOn;
global t;
global time_to_plot;
global aspect;
global spaces;
global CP;
global pauseHndl;
global eqns;
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 PlotStyle;
global PlotDim;
global zText;
global colours;
global envCols;
global head;
global tail;
global envLine;
global pmode;
global eplotHndl;
global PlotEnv;
global cps;
global phases;
global meantau;
global phaseHndl;
global btnLen;
global aspect;
global UpDateLegend;
global axSelectHndl;
global showLegendSubMenu;
global showMarkersSubMenu;
global ShowMarkers;
global ShowLegend;
global resolution;
global maxres;
global envCols;
global t_toplot;
global y_toplot;
global env_toplot;
global tol;
global recording;
global recHndl;

persistent old_rotation;
persistent old_tilt;

maxres = 20;    %every 20th point plotted

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


legend1 = [];

if strcmp(action,'initialize'),
    resolution = maxres/2;
    aspect = 1.5;
    innerframecol = [0.25 0.25 0.25];
    btncol = [0.8 0.8 0.8];
    numCycles = 5;  %num periods to showon time axis
    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
    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;
    speed = 50;
    tfinal=10000;
    oldFigNumber=watchon;
    figNumber=figure('Name',char(strcat({'Visualise Model Outputs - '}, title)),'NumberTitle','off','Visible','off', 'CloseRequestFcn', 'locke_05b_plot(''close'')');
    LoadingTime;
    pos = get(figNumber, 'Position');
    pos(3) = pos(3) * aspect;    %increase width
    set(figNumber, 'Position', pos);
    rotate3d on;
    LoadingTime;
    colordef(figNumber,'black');
    axes( ...
        'Units','normalized', 'Position',[0.4/aspect 0.22 0.3*aspect 0.75],'Visible','off');

    text(0,0,'Press the play button to begin','HorizontalAlignment','center');
    axis([-1 1 -1 1]);
    LoadingTime;

    %===================================
    % Information for all buttons
    labelColor=[0.8 0.8 0.8];
    btnLen=0.20;
    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.05/aspect 0.05 0.25/aspect 0.9];
    h=uicontrol( ...
        'Style','frame', ...
        'Units','normalized', ...
        'Position',frmPos, ...
        'BackgroundColor',[0.50 0.50 0.50]);
    frmPos=[1 - (0.25/aspect + 0.05/aspect) 0.05 0.25/aspect 0.9];
    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_plot(''start'');';

    % Generic button information
    btnPos=[(0.075/aspect) 0.075 (btnLen/aspect)/4 0.0625];
    startHndl=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Interruptible','on', ...
        '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_plot(''stop'');';
    
    % Generic  button information
    btnPos=[(0.075/aspect) + (btnLen/aspect)/2 0.075 (btnLen/aspect)/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_plot(''pause'');';
    
    % Generic  button information
    btnPos=[(0.075/aspect) + (btnLen/aspect)/4 0.075 (btnLen/aspect)/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='newlocke_05b_network2(''record'');';
   
    btnPos=[(0.075/aspect) + (btnLen/aspect)*3/4 0.075 (btnLen/aspect)/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);
     %====================================
    % The CLOSE button
    labelStr='Close';
    callbackStr='locke_05b_plot(''close'');';
    closeHndl= uicontrol( ...
        'Style','push', ...
        'Units','normalized', ...
        'position',[(0.075/aspect)  0.075 btnLen/aspect 0.0625], ...
        'string',labelStr, ...
        'visible', 'off', ...
        'call',callbackStr);
    %=========================================
    %select files
    h=uicontrol( ...
        'Style','frame', ...
        'Units','normalized', ...
        'Position',[(0.0625/aspect) 0.6825 0.225/aspect 0.255], ...
        'BackgroundColor',innerframecol);
    callbackStr='locke_05b_plot(''changePfile'')';
    pFilesHndl=uicontrol( ...
        'Style','popup', ...
        'Units','normalized', ...
        'String', listOfPFiles, ...
        'position',[(0.075/aspect) 0.825 btnLen/aspect 0.05], ...
        'call',callbackStr);
    labelHndl=uicontrol('Style', 'text','Units','normalized','position',[0.075/aspect 0.875 btnLen/aspect 0.05],'string','Parameters File','BackgroundColor', innerframecol, 'ForegroundColor', 'w');
    
    callbackStr='locke_05b_plot(''changeEfile'')';
    eFilesHndl=uicontrol( ...
        'Style','popup', ...
        'Units','normalized', ...
        'String', listOfEFiles, ...
        'position',[(0.075/aspect) 0.7 btnLen/aspect 0.05], ...
        'call',callbackStr);
    labelHndl=uicontrol('Style', 'text','Units','normalized','position',[0.075/aspect 0.75 btnLen/aspect 0.05],'string','Environment File','BackgroundColor', innerframecol, 'ForegroundColor', 'w');
    %====================================

    % The LD listbox
    h=uicontrol( ...
        'Style','frame', ...
        'Units','normalized', ...
        'Position',[1 - (0.25/aspect + 0.0375/aspect) 0.425 0.225/aspect 0.5125], ...
        'BackgroundColor',innerframecol);
    btnNumber=3;
    ypos=0.90-(btnNumber-1)*(btnWid+spacing);
    callbackStr='locke_05b_plot(''env'')';
    envHndl=uicontrol( ...
        'Style','popup', ...
        'Units','normalized', ...
        'String', modelEnvs, ...
        'position',[1 - (0.25/aspect + 0.025/aspect) 0.825 (btnLen/aspect)*0.8 0.05], ...
        'call',callbackStr);
    labelHndl=uicontrol('Style', 'text','Units','normalized','position',[1 - (0.25/aspect + 0.025/aspect) 0.875 btnLen/aspect 0.05],'string','Environment','BackgroundColor', innerframecol, 'ForegroundColor', 'w');
    callbackStr='locke_05b_plot(''plotEnv'')';
    eplotHndl=uicontrol( ...
        'Style','togglebutton', ...
        'Units','normalized', ...
        'Position',[1 - (0.25/aspect + 0.025/aspect) + (btnLen/aspect)*0.8 0.825 (btnLen/aspect)/5 0.05], ...
        'String','P', ...
        'Interruptible','on', ...
        'Value', 0, 'Max', 1, 'Min', 0, ...
        'Callback',callbackStr);  
    
    
    callbackStr='locke_05b_plot(''envParams'')';
    envparamsHndl=uicontrol( ...
        'Style','listbox', ...
        'Units','normalized', ...
        'position',[1 - (0.25/aspect + 0.025/aspect) 0.6375 btnLen/aspect 0.175], ...
        'call',callbackStr);
    % The env value controls
    callbackStr='locke_05b_plot(''envValKeyPress'')';
    envValHndl=uicontrol( ...
        'Style','edit',...
        'Units','normalized', ...
        'position',[(1 - (0.25/aspect + 0.025/aspect)) + (btnLen/aspect)*0.2 0.575 (btnLen/aspect)*0.4 0.05], ...
        'Enable','on', ...
        'HorizontalAlignment', 'right', ...
        'call',callbackStr);
    callbackStr='locke_05b_plot(''eValUp'')';
    eValUpHndl=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',[1 - (0.25/aspect + 0.025/aspect) + (btnLen/aspect)*0.6 0.575 (btnLen/aspect)/5 0.05], ...
        'String','>', ...
        'Interruptible','on', ...
        'Callback',callbackStr);  
    callbackStr='locke_05b_plot(''eValDown'')';
    eValDownHndl=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',[1 - (0.25/aspect + 0.025/aspect) 0.575 (btnLen/aspect)/5 0.05], ...
        'String','<', ...
        'Interruptible','on', ...
        'Callback',callbackStr);
    %default button
    callbackStr='locke_05b_plot(''setedef'')';
    edefHndl=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',[1 - (0.25/aspect + 0.025/aspect)+ (btnLen/aspect)*0.8 0.575 (btnLen/aspect)/5 0.05], ...
        'String','D', ...
        'Interruptible','on', ...
        'Callback',callbackStr);  
    callbackStr='locke_05b_plot(''applyEChange'')';
    ApplyEHndl=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',[1 - (0.25/aspect + 0.025/aspect) 0.5 (btnLen/aspect) 0.0625], ...
        'String','Apply', ...
        'Interruptible','on', ...
        'Callback',callbackStr);   
    
    %pulse button
    callbackStr='locke_05b_plot(''pulse'')';
    pulseHndl=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',[1 - (0.25/aspect + 0.025/aspect) 0.4375 btnLen/aspect 0.0625], ...
        'String','Pulse', ...
        'Interruptible','on', ...
        'Enable','off', ...
        'Callback',callbackStr);
   LoadingTime;
    %====================================
    % The parameters listbox
    h=uicontrol( ...
        'Style','frame', ...
        'Units','normalized', ...
        'Position',[1 - (0.25/aspect + 0.0375/aspect) 0.0625 0.225/aspect 0.35], ...
        'BackgroundColor',innerframecol);
    callbackStr='locke_05b_plot(''param'')';
    pHndl=uicontrol( ...
        'Style','listbox', ...
        'Units','normalized', ...
        'position',[1 - (0.25/aspect + 0.025/aspect) 0.2125 btnLen/aspect 0.1375], ...
        'call',callbackStr);
    labelHndl=uicontrol('Style', 'text','Units','normalized','position',[1 - (0.25/aspect + 0.025/aspect) 0.35 btnLen/aspect 0.05],'string','Parameters','BackgroundColor', innerframecol, 'ForegroundColor', 'w');
    
    %====================================

    callbackStr='locke_05b_plot(''paramValKeyPress'')';
    valHndl=uicontrol( ...
        'Style','edit',...
        'Units','normalized', ...
        'position',[(1 - (0.25/aspect + 0.025/aspect)) + (btnLen/aspect)*0.2 0.15 (btnLen/aspect)*0.4 0.05], ...
        'Enable','on', ...
        'HorizontalAlignment', 'right', ...
        'call',callbackStr);
    callbackStr='locke_05b_plot(''pValUp'')';
    pValUpHndl=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',[1 - (0.25/aspect + 0.025/aspect) + (btnLen/aspect)*0.6 0.15 (btnLen/aspect)/5 0.05], ...
        'String','>', ...
        'Interruptible','on', ...
        'Callback',callbackStr);  
    callbackStr='locke_05b_plot(''pValDown'')';
    pValDownHndl=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',[1 - (0.25/aspect + 0.025/aspect) 0.15 (btnLen/aspect)/5 0.05], ...
        'String','<', ...
        'Interruptible','on', ...
        'Callback',callbackStr);
     %default button
    callbackStr='locke_05b_plot(''setdef'')';
    defHndl=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',[1 - (0.25/aspect + 0.025/aspect)+ (btnLen/aspect)*0.8 0.15 (btnLen/aspect)/5 0.05], ...
        'String','D', ...
        'Interruptible','on', ...
        'Callback',callbackStr);  
    callbackStr='locke_05b_plot(''applyPChange'')';
    ApplyPHndl=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',[1 - (0.25/aspect + 0.025/aspect) 0.075 (btnLen/aspect) 0.0625], ...
        'String','Apply', ...
        'Interruptible','on', ...
        'Callback',callbackStr);   
     %====================================
 
    % The Axes buttons
    labelStr='Auto';
    callbackStr='locke_05b_plot(''scale'')';
    scaleHndl=uicontrol( ...
        'Style','push', ...
        'Units','normalized', ...
        'position',[0.4/aspect 0.05 0.0333*aspect 0.05], ...
        'string',labelStr, ...
        'Enable', 'off', ...
        'call',callbackStr);
    
    labelStr='E';
    callbackStr='locke_05b_plot(''enlargeScale'')';
    enlargeHndl=uicontrol( ...
        'Style','push', ...
        'Units','normalized', ...
        'position',[0.4/aspect + 0.0333*aspect 0.05 0.0333*aspect 0.05], ...
        'string',labelStr, ...
        'Enable', 'off', ...
        'call',callbackStr);
    labelStr='R';
    callbackStr='locke_05b_plot(''reduceScale'')';
    reduceHndl=uicontrol( ...
        'Style','push', ...
        'Units','normalized', ...
        'position',[0.4/aspect + 0.0666*aspect 0.05 0.0333*aspect 0.05], ...
        'string',labelStr, ...
        'Enable', 'off', ...
        'call',callbackStr);

    lbs = cell(0);
    lbs = [lbs; {'All'}; {'X'}; {'Y'}; {'Z'}];
    axSelectHndl=uicontrol( ...
        'Style','popup', ...
        'Units','normalized', ...
        'position',[0.4/aspect + 0.1*aspect 0.05 0.03*aspect 0.05], ...
        'string',lbs, ...
        'Enable', 'off', ...
        'HorizontalAlignment', 'right', ...
        'Value', 1);
    labelHndl=uicontrol('Style', 'text','Units','normalized','position',[0.4/aspect 0 0.13*aspect 0.05],'string','Scale','BackgroundColor', [0.2 0.2 0.2], 'ForegroundColor', 'w');

   
    
     %====================================
    % The speed slider
    labelStr='Speed';
    callbackStr='locke_05b_plot(''speed'')';
    speedHndl=uicontrol( ...
        'Style','slider',...
        'Units','normalized', ...
        'Value', 0.5, ...
        'position',[0.4/aspect + 0.2*aspect 0.05 0.1*aspect 0.05], ...
        'string',labelStr, ...
        'call',callbackStr);
    labelHndl=uicontrol('Style', 'text','Units','normalized','position',[0.4/aspect + 0.2*aspect 0 0.1*aspect 0.05],'string','Speed','BackgroundColor', [0.2 0.2 0.2], 'ForegroundColor', 'w');
 
    %======================================
    %axis selectors
     h=uicontrol( ...
        'Style','frame', ...
        'Units','normalized', ...
        'Position',[(0.0625/aspect) 0.1475 0.225/aspect 0.5225], ...
        'BackgroundColor',innerframecol);
    labelHndl=uicontrol('Style', 'text','Units','normalized','position',[0.075/aspect 0.5875 btnLen/aspect 0.05],'string','Style','BackgroundColor', innerframecol, 'ForegroundColor', 'w');
    callbackStr='locke_05b_plot(''setDim'');';
    dimHndl=uicontrol( ...
        'Style','popup', ...
        'Units','normalized', ...
        'String', ['2D'; '3D'], ...
        'position',[(0.075/aspect) 0.5375 (btnLen/aspect)/3 0.05], ...
         'call',callbackStr, ...
        'Value', 1);
    callbackStr='locke_05b_plot(''setStyle'');';
    styleHndl=uicontrol( ...
        'Style','popup', ...
        'Units','normalized', ...
        'String', ['Time Series'; 'Limit Cycle'], ...
        'position',[(0.075/aspect)+(btnLen/aspect)/3 0.5375 (btnLen/aspect)* (2/3) 0.05], ...
        'call',callbackStr, ...
        'Value', 1);
    
    callbackStr='locke_05b_plot(''axesChange'');';
    xopHndl=uicontrol( ...
        'Style','popup', ...
        'Units','normalized', ...
        'position',[(0.075/aspect) 0.4125 btnLen/aspect 0.05], ...
        'call',callbackStr, ...
        'Value', 1);
    labelHndl=uicontrol('Style', 'text','Units','normalized','position',[0.075/aspect 0.4625 btnLen/aspect 0.05],'string','X axis','BackgroundColor', innerframecol, 'ForegroundColor', 'w');
    yopHndl=uicontrol( ...
        'Style','popup', ...
        'Units','normalized', ...
        'position',[(0.075/aspect) 0.2875 btnLen/aspect 0.05], ...
        'call',callbackStr, ...
        'Value', 1);
    labelHndl=uicontrol('Style', 'text','Units','normalized','position',[0.075/aspect 0.3375 btnLen/aspect 0.05],'string','Y axis','BackgroundColor', innerframecol, 'ForegroundColor', 'w');
    zopHndl=uicontrol( ...
        'Style','popup', ...
        'Units','normalized', ...
        'position',[(0.075/aspect) 0.1625 btnLen/aspect 0.05], ...
        'call',callbackStr, ...
        'Value', 1);
    zText=uicontrol('Style', 'text','Units','normalized','position',[0.075/aspect 0.2125 btnLen/aspect 0.05],'string','Z axis','BackgroundColor', innerframecol, 'ForegroundColor', 'w');
    tsopHndl=uicontrol( ...
        'Style','list', ...
        'Units','normalized', ...
        'position',[(0.075/aspect) 0.1625 btnLen/aspect 0.175], ...
        'call',callbackStr, ...
        'Max', 5, ...
        'Min', 0, ...
        'Value', 1);      
    %==============================
 
    %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;
   phaseHndl = [];
   set(eplotHndl, 'Value', 0);
    
    % Uncover the figure
    hndlList=[startHndl stopHndl envHndl closeHndl speedHndl pHndl valHndl scaleHndl xopHndl yopHndl zopHndl envparamsHndl envValHndl pulseHndl enlargeHndl reduceHndl pauseHndl defHndl pFilesHndl eFilesHndl pValUpHndl pValDownHndl ApplyPHndl eValUpHndl eValDownHndl ApplyEHndl edefHndl tsopHndl styleHndl dimHndl eplotHndl axSelectHndl recHndl phaseHndl ];
    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'); 
   time_to_plot = GetCP() * 5; %time to show in one block on time series
   ymin = 0; ymax = 10;
    zmin = 0; zmax = 10;
elseif strcmp(action,'start'),
     Mv = [];
    pulseOn = zeros(size(modelEnvs,1),1);
    axHndl=gca;
    figNumber=gcf;
    cla reset;
    hndlList=get(figNumber,'UserData');
    startHndl=hndlList(1);
    stopHndl=hndlList(2);
    envHndl=hndlList(3);
    closeHndl=hndlList(4);
    speedHndl=hndlList(5);
    pHndl = hndlList(6);
    valHndl = hndlList(7);
    scaleHndl = hndlList(8);
    xopHndl = hndlList(9);
    yopHndl = hndlList(10);
    zopHndl = hndlList(11);
    envparamsHndl = hndlList(12);
    envValHndl = hndlList(13);
    pulseHndl = hndlList(14);
    enlargeHndl = hndlList(15);
    reduceHndl = hndlList(16);
    pauseHndl = hndlList(17);
    defHndl = hndlList(18);
    pFilesHndl = hndlList(19);
    eFilesHndl = hndlList(20);
    pValUpHndl = hndlList(21);
    pValDownHndl = hndlList(22);
    ApplyPHndl = hndlList(23);
    eValUpHndl = hndlList(24);
    eValDownHndl = hndlList(25);
    ApplyEHndl = hndlList(26);
    edefHndl = hndlList(27);
    tsopHndl = hndlList(28);
    styleHndl = hndlList(29);
    dimHndl = hndlList(30);
    eplotHndl = hndlList(31);
    axSelectHndl = hndlList(32);
    recHndl = hndlList(33);
    phaseHndl = hndlList(34:end);
    
    PlotEnv = get(eplotHndl,'Value');
    
    set([startHndl closeHndl  pFilesHndl eFilesHndl  styleHndl dimHndl],'Enable','off');
   % xopHndl yopHndl zopHndl tsopHndl
    set([stopHndl speedHndl scaleHndl enlargeHndl reduceHndl pauseHndl axSelectHndl],'Enable','on');
    if ~isempty(LIGHT_COLS) | TEMPERATURE > 0
        set(pulseHndl, 'Enable', 'on');
    end
   % sp = sqrt(resolution/maxres);
   % set(speedHndl, 'Value', sp);
    pmode = 'play';
 
    % ====== Start of Demo
    set(figNumber,'Backingstore','off');
  
    if strcmp(PlotStyle, 'TS')     %plotting time series
        xmin = 0; xmax = time_to_plot;
        cp = GetCP();
        tv = [xmin:cp:xmax]; 
        set(gca, 'XTick', tv);
    else
        xmin = 0; xmax =10;
    end
    if isempty(ymin)
        ymin = 0; ymax = 10;
    end
    if isempty(zmin)
        zmin = 0; zmax = 10;
    end
    if ~isempty(old_rotation)
        r = old_rotation;
    else
        r = 315;
    end
    if ~isempty(old_tilt)
        t = old_tilt;
    else
        t = 30;
    end
    if strcmp(PlotDim, '3D')  %3d 
        set(axHndl, ...     
        'XLim',[xmin xmax],'YLim',[ymin ymax],'ZLim',[zmin zmax], ... %'XTick',[xmin (xmin + xmax)/2 xmax],'YTick',[ymin (ymin + ymax)/2 ymax],'ZTick',[zmin (zmin + zmax)/2 zmax], ...
        'Userdata',play, ...
        'Drawmode','fast', ...
        'Visible','on', ...
        'NextPlot','add', ...
        'Userdata',play, ...
        'View',[r,t]);
    else    %2d 
        set(axHndl, ...     
        'XLim',[xmin xmax],'YLim',[ymin ymax], ... %'XTick',[xmin (xmin + xmax)/2 xmax],'YTick',[ymin (ymin + ymax)/2 ymax],'ZTick', ...
        'Userdata',play, ...
        'Drawmode','fast', ...
        'Visible','on', ...
        'NextPlot','add', ...
        'Userdata',play);
    end
    
    y = y0(:);
    SetAxes(pmode);
    
    t0=0;
    pow = 1/3;
    t = t0;
    hmax = (tfinal - t)/5;  %step sizes
    hmin = (tfinal - t)/200000; % 0.05 s
    h = (tfinal - t)/100;   
    old_y = y;
    old_t = t;
    lastDay = [t0;y];
    old_day = 0;
    old_tempday = 0;
    lastZT0 = 0;
    
   
    resolution = floor(maxres * get(speedHndl, 'Value')^2);
    if resolution < 1 
        resolution=1;
    end
    tol = 1e-7 * (1e+4)^(get(speedHndl, 'Value')^2);%higher tolerance for faster speeds.
    tau = tol * max(norm(y,'inf'),1);   %allowed error
    num_points = 0;
    t_toplot = t;
    env_toplot = 0;
    y_toplot = y;
   
    % The main loop
    while (get(axHndl,'Userdata')==play)% & (h >= hmin)
        a = cputime;
        if t + h > tfinal, h = tfinal - t; end
        % Compute the slopes
        try
            [ld_val day] = GetLD(t);
            [t_val tempday] = GetTemp(t);
            s1 = feval(eqns, t, y, pValues, ld_val, t_val);   %derrivatives
            s2 = feval(eqns, t+h, y+h*s1, pValues, ld_val, t_val);
            s3 = feval(eqns, t+h/2, y+h*(s1+s2)/4, pValues, ld_val, t_val);
   
            % Estimate the error and the acceptable error
            tol = 1e-7 * (1e+4)^(get(speedHndl, 'Value')^2);%higher tolerance for faster speeds.
            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;
                %save last 48 hours to calc axis limits required
                if mod(num_points, resolution) == 0
                    data = [t; y];
                    lastDay = [lastDay data];   
                    peaksfound = zeros(size(lastDay,1)-1,1);
                    t_toplot = [t_toplot t];
                   % y_toplot = [y_toplot y];
                    %t_toplot = [t_toplot t];
                   
                    if size(lastDay,2) > 4
                        %last 3 points
                        for i = 2:size(lastDay,1)   %top row is time
                        %     if (lastDay(i,size(lastDay,2)-4) < lastDay(i,size(lastDay,2)-3)) & (lastDay(i,size(lastDay,2)-3) <= lastDay(i,size(lastDay,2)-2)) & (lastDay(i,size(lastDay,2)-1) <= lastDay(i,size(lastDay,2)-2)) & (lastDay(i,size(lastDay,2)) < lastDay(i,size(lastDay,2)-1))
                            if (lastDay(i,size(lastDay,2)-2) < lastDay(i,size(lastDay,2)-1)) & (lastDay(i,size(lastDay,2)) < lastDay(i,size(lastDay,2)-1))
                                peaksfound(i-1,1) = 1;
                            end
                        end
                        %calc  tau and phase
                        if strcmp(PlotStyle, 'TS')
                            if strcmp(PlotDim, '2D')
                                for i = 1:size(phases,1)
                                    if peaksfound(y_op(i),1) == 1
                                        cps(i,1) = cps(i,2);
                                        cps(i,2) = t;   %time of last 2 peaks
                                        if (cps(i,1) > 0)
                                            meantau(i) = (cps(i,2) - cps(i,1));
                                        end
                                        phases(i) = t - lastZT0;
                                    end
                                end
                            else
                                if peaksfound(y_op,1) == 1
                                    cps(1,1) = cps(1,2);
                                    cps(1,2) = t;   %time of last 2 peaks
                                    if (cps(1,1) > 0)
                                        meantau(1) = (cps(1,2) - cps(1,1));
                                    end
                                    phases(1) = t - lastZT0;
                                end
                                if peaksfound(z_op,1) == 1
                                    cps(2,1) = cps(2,2);
                                    cps(2,2) = t;   %time of last 2 peaks
                                    if (cps(2,1) > 0)
                                        meantau(2) = (cps(2,2) - cps(2,1));
                                    end
                                    phases(2) = t - lastZT0;
                                end
                            end
                        else    %LC
                            if peaksfound(x_op,1) == 1
                                cps(1,1) = cps(1,2);
                                cps(1,2) = t;   %time of last 2 peaks
                                if (cps(1,1) > 0)
                                    meantau(1) = (cps(1,2) - cps(1,1));
                                end
                                phases(1) = t - lastZT0;
                            end
                            if peaksfound(y_op,1) == 1
                                cps(2,1) = cps(2,2);
                                cps(2,2) = t;   %time of last 2 peaks
                                if (cps(2,1) > 0)
                                    meantau(2) = (cps(2,2) - cps(2,1));
                                end
                                phases(2) = t - lastZT0;
                            end
                            if strcmp(PlotDim, '3D')
                                if peaksfound(z_op,1) == 1
                                    cps(3,1) = cps(3,2);
                                    cps(3,2) = t;   %time of last 2 peaks
                                    if (cps(3,1) > 0)
                                        meantau(3) = (cps(3,2) - cps(3,1));
                                    end
                                    phases(3) = t - lastZT0;
                                end 
                            end
                        end
                    
                    
                    end
                    toremove = find(lastDay(1,:) <= (t - 2 * GetCP()));
                    lastDay(:,toremove) = [];
                    if ((day > 0) & (old_day == 0)) | ((tempday > 0) & (old_tempday == 0))
                        lastZT0 = t;
                    end
                
                    if UpDateLegend ~= 0    %axes changed since last update
                        for i = 1:size(phaseHndl,2)
                            delete(phaseHndl(i));
                        end
                        phaseHndl = [];
                        for i = 1:size(phases,1)
                            %phaseHndl = [phaseHndl uicontrol('Style',
                            %'text','Units','normalized','position',[((0.4 + 0.3*aspect^2)/aspect) - (2*btnLen/aspect) 0.97 - i*0.05 2*btnLen/aspect 0.05],'BackgroundColor', [0 0 0], 'ForegroundColor', 'w')];
                            phaseHndl = [phaseHndl uicontrol('Style', 'text','Units','normalized','position',[0.4/aspect + 0.05*aspect 0.97 - i*0.03 0.25*aspect 0.03],'BackgroundColor', [0 0 0], 'ForegroundColor', 'w', 'HorizontalAlignment', 'right')];
                        end
                        UpDateLegend = 0;
                    end
                    if ShowLegend == 0
                        for i = 1:size(phaseHndl,2)
                            set(phaseHndl, 'Visible', 'off'); 
                        end
                    else
                        for i = 1:size(phaseHndl,2)
                            set(phaseHndl, 'Visible', 'on'); 
                        end
                    end

                    if strcmp(PlotStyle, 'TS')
                        if strcmp(PlotDim, '2D')
                            for i = 1:size(phaseHndl,2)
                                if size(y_op,2) > 1
                                    legCol = colours(i,:);
                                else
                                    legCol = [1 1 1];
                                end
                                set(phaseHndl(1,i), 'ForeGroundColor', legCol);
                                set(phaseHndl(1,i), 'String', strcat(opnames{y_op(i)}, sprintf(' - Phase = %6.2f, Tau = %6.2f', phases(i), meantau(i))));
                            end
                        else
                            set(phaseHndl(1,1), 'String', strcat(opnames{y_op}, sprintf(' - Phase = %6.2f, Tau = %6.2f', phases(1), meantau(1))));
                            set(phaseHndl(1,2), 'String', strcat(opnames{z_op}, sprintf(' - Phase = %6.2f, Tau = %6.2f', phases(2), meantau(2))));
                        end
                    else
                        set(phaseHndl(1,1), 'String', strcat(opnames{x_op}, sprintf(' - Phase = %6.2f, Tau = %6.2f', phases(1), meantau(1))));
                        set(phaseHndl(1,2), 'String', strcat(opnames{y_op}, sprintf(' - Phase = %6.2f, Tau = %6.2f', phases(2), meantau(2))));
                        if strcmp(PlotDim, '3D')
                            set(phaseHndl(1,3), 'String', strcat(opnames{z_op}, sprintf(' - Phase = %6.2f, Tau = %6.2f', phases(3), meantau(3))));
                        end
                    end

                
                    % Update the plot
                    y_toplot = [y old_y];
            
                    %set marker size
                    if ShowMarkers > 0 
                        v = get(axHndl, 'view');
                        rotation = v(1);
                        if rotation < 0
                            rotation = rotation + 360;
                        end
                        tilt = abs(v(2));
                
                        xlen = xmax-xmin;
                        ylen = ymax-ymin;
                        zlen = zmax-zmin;
                        if strcmp(PlotStyle, 'LC') %lower x value is closer
                            currentx = (max([0 (xmax - y_toplot(x_op,1))]))/xlen;
                        else    %time series
                            currentx = (xmax - t)/xlen;
                        end
                        currenty = [];
                        for i = 1:size(y_op,2)
                            currenty =[currenty; (max([0 (ymax - y_toplot(y_op(i),1))]))/ylen];
                        end
                        if strcmp(PlotDim, '3D')
                            currentz = (max([0 (y_toplot(z_op,1)-zmin)]))/zlen;
                        else
                            currentz = 0.5;
                        end 
                        %axes may be flipped
                        if (tilt >= 90 & tilt < 180) | (tilt >= 270)
                            if rotation >= 180
                                currentx = 1 - currentx;
                            end
                            if (rotation < 90) | (rotation >= 270)
                                currenty = 1 - currenty;
                            end
                            currentz  = 1 - currentz;
                        else
                            if rotation < 180
                                currentx = 1 - currentx;
                            end
                            if (rotation >= 90) & (rotation < 270)
                                currenty = 1 - currenty;
                            end
                        end
  
                        rotation = rotation* 0.0175;    %covert to radians
                        tilt = tilt* 0.0175;
                        for i = 1:size(head,1)
                            set(head(i), 'visible', 'on');
                            ms = sqrt( (abs(sin(tilt)) * currentz)^2 + (abs(cos(tilt)) * ((currenty(i) * abs(cos(rotation)) + currentx * abs(sin(rotation)) ) / (abs(cos(rotation)) + abs(sin(rotation)))))^2 );
                            if get(head(i), 'Marker') == '.'
                                set(head(i), 'markersize', 75*ms^2);
                            else
                                set(head(i), 'markersize', 25*ms^2);
                            end
                        end
                    else
                        for i = 1:size(head,1)
                            set(head(i), 'visible', 'off');
                        end 
                    end
                    if strcmp(PlotStyle, 'TS') % time series, each line a single colour
                        %add the selected env cycle
                        %if ~isempty(envValues)
                        %    envColour = envCols(get(envHndl,'Value'));
                        %    envYval = ymin + (ymax-ymin)/100;
                        %    if (day > 0 | tempday > 0) & PlotEnv ~= 0
                        %        set(envLine, 'Visible', 'on');
                        %    else
                        %        set(envLine, 'Visible', 'off');
                        %    end    
                        %end
                        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 strcmp(PlotDim, '3D')
                            if (day > 0 | tempday > 0)
                                lineColour = 'y';
                            else
                                lineColour = 'c'; 
                            end
                            set(head,'color',lineColour,'MarkerEdgeColor', lineColour, 'MarkerFaceColor', lineColour,'xdata',t,'ydata',y_toplot(y_op,1),'zdata',y_toplot(z_op,1))  %current time point
                            set(tail,'color',lineColour,'xdata',[t old_t],'ydata',y_toplot(y_op,:),'zdata',y_toplot(z_op,:))  %rest    
                            if ~isempty(envValues) & PlotEnv  ~= 0 
                                envColour = envCols(e,:);
                                for e = 1:size(env_toplot,1)
                                    set(envLine,'color',envColour,'Visible', 'on', 'YData', env_toplot(e,:), 'XData', t_toplot,'zdata',ones(1,size(t_toplot,2))* zmin);
                                end
                            end
                        else
                            if ~isempty(envValues) & PlotEnv ~=0
                                envColour = envCols(e,:);
                                set(envLine,'color',envColour,'Visible', 'on', 'YData', env_toplot(e,:), 'XData', t_toplot);
                            end
                            for i = 1:size(y_op,2)
                                if size(y_op,2) == 1
                                    if (day > 0 | tempday > 0)
                                        lineColour = 'y'; 
                                    else
                                        lineColour = 'c'; 
                                    end
                                else
                                    lineColour = colours(i,:); 
                                end
                                set(head(i),'color',lineColour,'MarkerEdgeColor', lineColour, 'MarkerFaceColor', lineColour,'xdata',t,'ydata',y_toplot(y_op(i),1))  %current time point
                                set(tail(i),'color',lineColour,'xdata',[t old_t],'ydata',y_toplot(y_op(i),:))  %rest   
                            end
                        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(gca, 'XTick', tv);
                            t_toplot = t;
                            env_toplot = 0;
                        end
                    else    %limit cycle
                        if (day > 0 | tempday > 0)
                            lineColour = 'y'; 
                        else
                            lineColour = 'c'; 
                        end  
                        if strcmp(PlotDim, '3D')
                            set(head,'color',lineColour,'MarkerEdgeColor', lineColour, 'MarkerFaceColor', lineColour,'xdata',y_toplot(x_op,1),'ydata',y_toplot(y_op,1),'zdata',y_toplot(z_op,1))  %current time point
                            set(tail,'color',lineColour,'xdata',y_toplot(x_op,:),'ydata',y_toplot(y_op,:),'zdata',y_toplot(z_op,:))  %rest    
                        else
                            set(head,'color',lineColour,'MarkerEdgeColor', lineColour, 'MarkerFaceColor', lineColour,'xdata',y_toplot(x_op,1),'ydata',y_toplot(y_op,1))  %current time point
                            set(tail,'color',lineColour,'xdata',y_toplot(x_op,:),'ydata',y_toplot(y_op,:))  %rest    
                        end
                    end
                    %check for peaks
                
                    drawnow;
                    if recording
                       pos = get(figNumber, 'Position');
                      % [0.4/aspect 0.22 0.3*aspect 0.75]
                       Mv = [Mv;getframe(figNumber, [pos(3) * (0.35/aspect) pos(4) * 0.15 pos(3) * 0.4*aspect pos(4) * 0.85])];
                    end
                    old_y = y;
                    old_t = t;
                    old_day = day;
                    old_tempday = tempday;
                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';
    
    for i = 1:size(phaseHndl,2)
        delete(phaseHndl(i));
    end
    % ====== End of Demo
    set([startHndl closeHndl xopHndl yopHndl zopHndl pFilesHndl tsopHndl styleHndl dimHndl],'Enable','on');
    if ~isempty(LIGHT_COLS) | TEMPERATURE > 0
         set(eFilesHndl,'Enable','on');
    end
    set([stopHndl scaleHndl pulseHndl enlargeHndl reduceHndl pauseHndl axSelectHndl],'Enable','off');
    if strcmp(PlotDim, '3D')
        v = get(axHndl, 'view');
        old_rotation = v(1);
        if old_rotation < 0
            old_rotation = old_rotation + 360;
        end
        old_tilt = abs(v(2));
    end
    if ~isempty(Mv) %no resizin gif recording
        movie2avi(Mv,GetAVIName);
       % save('d:\Movie1', 'Mv');
    end
    
elseif strcmp(action,'speed')
    resolution=floor(get(speedHndl, 'Value')^2 * 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, 'scale')  %auto set scale
    ax = get(axSelectHndl, 'Value');
    %find last cycle of data, usually 24 hours
    if strcmp(PlotStyle, 'LC') & (ax == 1 | ax == 2) %not time
        xmin = min(lastDay(x_op + 1, :));
        xmax = max(lastDay(x_op + 1, :));
        if xmax == xmin
            xmax = xmin + 1;
        end
        set(axHndl, 'XLim',[xmin xmax]);
    end
    if ax == 1 | ax == 3
        ymin = min(lastDay(y_op(1) + 1, :));
        ymax = max(lastDay(y_op(1) + 1, :));
        for i = 2:size(y_op,2)
            if min(lastDay(y_op(i) + 1, :)) < ymin
                ymin = min(lastDay(y_op(i) + 1, :));
            end
            if max(lastDay(y_op(i) + 1, :)) > ymax
                ymax = max(lastDay(y_op(i) + 1, :));
            end  
        end
        if ymax == ymin
            ymax = ymin + 1;
        end
        set(axHndl, 'YLim',[ymin ymax]);
    end
    if strcmp(PlotDim, '3D')  & (ax == 1 | ax == 4)
        zmin = min(lastDay(z_op + 1, :));
        zmax = max(lastDay(z_op + 1, :));
        if zmax == zmin
            zmax = zmin + 1;
        end
        set(axHndl, 'ZLim',[zmin zmax]);
    end
elseif strcmp(action, 'reduceScale')
    ax = get(axSelectHndl, 'Value');
    if (ax == 1 | ax == 2)
        if strcmp(PlotStyle, 'LC') % not time
            xmin = xmin / 2;
            xmax = xmax * 2; 
        else    
            time_to_plot = (xmax-xmin) * 2;
            xmin = floor(t);
            xmax = xmin + time_to_plot;
       %     cp = GetCP();
        %    while cp < (time_to_plot/5)  %too many ticks
         %      cp = cp*2; 
          %  end
            cp = ((xmax-xmin)/5);
            tv = [xmin:cp:xmax]; 
            set(gca, 'XTick', tv);
        end
        set(axHndl, 'XLim',[xmin xmax]);
    end
    if (ax == 1 | ax == 3)
        ymin = ymin / 2;
        ymax = ymax * 2;
        set(axHndl, 'YLim',[ymin ymax]);
    end
    
    if strcmp(PlotDim, '3D') & (ax == 1 | ax == 4)
       zmin = zmin /2;
       zmax = zmax * 2;
       set(axHndl, 'ZLim',[zmin zmax]);
    end
elseif strcmp(action, 'enlargeScale')
     ax = get(axSelectHndl, 'Value');
    if (ax == 1 | ax == 2)
        if strcmp(PlotStyle, 'LC') %not time
            xmin = xmin * 2;
            xmax = xmax / 2;  
        else
            time_to_plot = (xmax-xmin) / 2;
            xmin = floor(t);
            xmax = xmin + time_to_plot;
           % cp = GetCP();
           % while cp > ((xmax-xmin)/5)  %not enough ticks
           %    cp = cp/2; 
           % end
            cp = ((xmax-xmin)/5);
            tv = [xmin:cp:xmax]; 
            set(gca, 'XTick', tv);
        end
        if xmax <= xmin
            xmax = xmin + 1;
        end
        set(axHndl, 'XLim',[xmin xmax]);
    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
   
    if strcmp(PlotDim, '3D') & (ax == 1 | ax == 4)
       zmin = zmin * 2;
        zmax = zmax / 2;
        if zmax <= zmin
            zmax = zmin + 1;
        end
        set(axHndl, 'ZLim',[zmin zmax]);
    end
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);
    set(axHndl,'Userdata',-1);
elseif strcmp(action, 'close') 
    locke_05b_plot('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);
   % pValues(p) = newval;   
    %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, '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);
    %pValues(p) = newval;   
    %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, '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);
%    envValues(e,p) = newVal;  
    %if a light cp changed, change for all lights
%    if p == 1 
%       if ~isempty(LIGHT_COLS)
%           if e <= size(LIGHT_COLS,1)
%              envValues(1:size(LIGHT_COLS,1),1) = str2double(pv);  
%           end
%       end
%    end 
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);
 %   envValues(e,p) = newVal;  
    %if a light cp changed, change for all lights
 %   if p == 1 
 %      if ~isempty(LIGHT_COLS)
 %          if e <= size(LIGHT_COLS,1)
 %             envValues(1:size(LIGHT_COLS,1),1) = str2double(pv);  
 %          end
 %      end
 %   end 
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, 'setDim')  
    SetStyle(); 
elseif strcmp(action, 'setStyle')  
    SetStyle();  
elseif strcmp(action, 'axesChange')
    SetAxes(pmode);
elseif strcmp(action, 'plotEnv')
    PlotEnv = get(eplotHndl,'Value');
elseif strcmp(action, 'ShowLegend')
    s = get(showLegendSubMenu, 'Checked');
    if strcmp(s, 'on')
        ShowLegend = 0;
        set(showLegendSubMenu, 'Checked', 'off')
    else
        ShowLegend = 1;
        set(showLegendSubMenu, 'Checked', 'on')
    end
elseif strcmp(action, 'ShowMarkers')
    s = get(showMarkersSubMenu, 'Checked');
    if strcmp(s, 'on')
        ShowMarkers = 0;
        set(showMarkersSubMenu, 'Checked', 'off')
    else
        ShowMarkers = 1;
        set(showMarkersSubMenu, 'Checked', 'on')
    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 
end;    % if strcmp(action, ...

%===================================================
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 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 opnames;
global pnames;
global y0;
global pValues;
global numStates;
global pDefValues;
global pValues;
global numParams;
global xopHndl;
global yopHndl;
global zopHndl;
global modelname;
global spaces;
global pHndl;
global valHndl;

[opkeys opnames] = textread(strcat(modelname, '.sts'),'%*d,%[^,],%*[^,],%[^,]%*[^\n]');
for i = 1:size(opnames,1)
    str = char(opnames(i,:));
    if strncmpi(str,'Initial level of ', 17)
        str = str(18:end);
        opnames{i} = str;
    elseif strncmpi(str,'Level of ', 9)
        str = str(10:end);
        opnames{i} = str;
    end
end
        
%read initial states and constants from values file made by interface file
y0 = GetParamValues(strcat(fp, pFile), opkeys);    %remove ox states???
numStates = size(y0,1);

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

numParams = size(pValues,1);
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 = 0;
    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
        if (currentLight == i) & val(i) ~= offVal
            day = 1;
        end
    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 xopHndl;
global opnames;
global yopHndl;
global zopHndl;
global pHndl;
global pnames;
global valHndl;
global pValues;

SetStyle();
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 SetStyle()

global tsopHndl;
global xopHndl;
global yopHndl;
global zopHndl;
global styleHndl;
global dimHndl;
global PlotStyle;
global PlotDim;
global opnames;
global zText;
global eplotHndl;
global PlotEnv;
global LIGHT_COLS;
global TEMPERATURE;
global axSelectHndl

persistent old_x;
persistent old_y;
persistent old_z;

old_x = get(xopHndl, 'Value');
old_y = get(yopHndl, 'Value');
old_z = get(zopHndl, 'Value');


s = get(styleHndl, 'Value');
d = get(dimHndl, 'Value');

if d == 1   %2d
    PlotDim = '2D';
    lbs = cell(0);
    lbs = [lbs; {'All'}; {'X'}; {'Y'}];
    if s == 1   %2d time series
        set(xopHndl,'String', 'Time');
        set(xopHndl,'Value',1);
        set(tsopHndl,'Visible', 'on');
        set(tsopHndl,'String',opnames);
        set(yopHndl,'Visible', 'off');
        PlotStyle = 'TS';
    else    %2d limit cycle
        set(xopHndl,'String',opnames);
        set(xopHndl,'Value',old_x);
        set(tsopHndl,'Visible', 'off');
        set(yopHndl,'Visible', 'on');
        set(yopHndl,'String',opnames);
        set(yopHndl,'Value',old_y);
        PlotStyle = 'LC';
    end
    set(zopHndl,'Visible', 'off');
    set(zText,'Visible', 'off');
else    %3d
    PlotDim = '3D';
    lbs = cell(0);
    lbs = [lbs; {'All'}; {'X'}; {'Y'}; {'Z'}];
    if s == 1   %3d time series
        set(xopHndl,'String', 'Time');
        set(xopHndl,'Value',1);
        PlotStyle = 'TS';
    else    %3d limit cycle
        set(xopHndl,'String',opnames);
        set(xopHndl,'Value',old_x);
        PlotStyle = 'LC';
    end
    set(tsopHndl,'Visible', 'off');
    set(yopHndl,'Visible', 'on');
    set(yopHndl,'String',opnames);
    set(yopHndl,'Value',old_y);
    set(zopHndl,'Visible', 'on');
    set(zText,'Visible', 'on');
    set(zopHndl,'String', opnames);
    set(zopHndl,'Value',old_z);
end
set(axSelectHndl, 'String',lbs);

if strcmp(PlotStyle, 'LC') | (isempty(LIGHT_COLS) & TEMPERATURE == 0)
    set(eplotHndl, 'Enable', 'off');
    set(eplotHndl, 'Value', 0);
else
    set(eplotHndl, 'Enable', 'on');
    set(eplotHndl, 'Value', PlotEnv);
end

%========================================
function SetAxes(p)

global xopHndl;
global yopHndl;
global zopHndl;
global x_op;
global y_op;
global z_op;
global PlotDim;
global PlotStyle;
global tsopHndl;
global opnames;
global head;
global tail;
global envLine;
global PlotEnv;
global cps;
global phases;
global meantau;
global aspect;
global btnLen;
global UpDateLegend;


if strcmp(p, 'play')
    v = 'on';
else
    v = 'off';  %visibility of lines
end
    
legend('off');

x_op = get(xopHndl, 'Value');
str = get(xopHndl, 'String');
if size(str,1) == 1
    xlabel(str)
else
    xlabel(str(x_op,:));
end
if strcmp(PlotStyle, 'TS')
    if strcmp(PlotDim, '2D')
        y_op = get(tsopHndl, 'Value');
        if size(y_op,2) < 1 
            ShowError('No outputs are selected!');
            vc('stop');
            return;
        end
        cps = zeros(size(y_op,2),2);%cp for each selected op, 2 cols for last 2 peaks
        phases = zeros(size(y_op,2),1);
        meantau = zeros(size(y_op,2),1);
        if size(y_op,2) > 1
            ylabel('Output Level');
        else
            ylabel(opnames{y_op}); 
        end
        z_op = [];
        zlabel('');
    else
        y_op = get(yopHndl, 'Value');
        ylabel(opnames{y_op});
        z_op = get(zopHndl, 'Value');
        zlabel(opnames{z_op});
        cps = zeros(2,2);
        phases = zeros(2,1);
        meantau = zeros(2,1);
    end
else
     y_op = get(yopHndl, 'Value');
     ylabel(opnames{y_op});
     if strcmp(PlotDim, '2D')
        cps = zeros(2,2);
        phases = zeros(2,1);
        meantau = zeros(2,1);
     else
         z_op = get(zopHndl, 'Value');
         zlabel(opnames{z_op}); 
         cps = zeros(3,2);
         phases = zeros(3,1);
         meantau = zeros(3,1);
     end
end

%labels


Markers = ['.' 's' 'h' '^' 'd'];


if strcmp(PlotStyle, 'LC')
    if strcmp(PlotDim, '3D')
        head = line('Marker',Markers(1),'erase','xor', 'xdata', [], 'ydata', [], 'zdata', [], 'Visible', v);    
        tail=line('LineStyle','-','erase','none', 'xdata', [], 'ydata', [], 'zdata', [], 'Visible', v);
    else
        head = line('Marker',Markers(1),'erase','xor', 'xdata', [], 'ydata', [], 'zdata', [], 'Visible', v);
        tail=line('LineStyle','-','erase','none', 'xdata', [], 'ydata', [], 'zdata', [], 'Visible', v);
    end
    
else
    if strcmp(PlotDim, '3D')
        head = line('Marker',Markers(1),'erase','xor', 'xdata', [], 'ydata', [], 'zdata', [], 'Visible', v);
        tail=line('LineStyle','-', 'erase','none', 'xdata', [], 'ydata', [], 'zdata', [], 'Visible', v);
    else
        head = [];
        tail = [];
        if size(y_op,2) > 7
           y_op(8:end) = [];
         %  msgbox('You cannot select more than 7 outputs at once.','Too many outputs','warn','modal'); 
           set(tsopHndl,'Value', y_op);
        end
        for i = 1:size(y_op,2)
            head = [head; line('Marker',Markers(i), 'erase','xor', 'xdata', [], 'ydata', [], 'zdata', [], 'Visible', v)];
            tail = [tail; line('LineStyle','-', 'erase','none', 'xdata', [], 'ydata', [], 'zdata', [], 'Visible', v)]; 
        end
    end  
    if PlotEnv == 0
        v = 'off';
    end
    envLine = line('LineStyle','-', 'erase','none', 'Visible', v);
end

UpDateLegend = 1;

%====================================================
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 dydt = equations(t, y, pPV, pLD, pTEMP)


P = pPV;
LD_VAL = pLD;
TEMP_VAL = pTEMP;

%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));


        

Contact us at files@mathworks.com