% 
% extract factors from structure
    for i=1:size( data.factorprops.Concentration,2)
        factname=lower(data.factorprops.Index2Name{i});
        eval([[factname,'_p'],'=reshape(','data.factorprops.Concentration(:,i),[ data.cellprops.cellsize]);']);
        eval([[factname,'_i'],'=','data.factorprops.Name2Index.(factname);']);
    end
% insert model in here
%% To run on the cluster
% MTtboxCommandGrace('Name','MT_Paper1_20121121','N_steps',[500:500:2000],...
%       'ORTHO_TOP',1,'modelname',[1,2],'growth_rate',[1:7],'Rescue_rate',[1:4],'Use','Cluster');

%%Begin cluster run stuff
    if (~isfield(data,'noGui') || data.noGui == 0) || data.iterations<0
        rng('shuffle'); % to seed from the same number each time use 1234 instead of 'shuffle'
        %data.userdata.ranges.growth_rate.range{1} = 0.0005; %1
        %data.userdata.ranges.growth_rate.range{2} = 0.001; %1
        %data.userdata.ranges.growth_rate.range{3} = 0.003; %1
        %data.userdata.ranges.growth_rate.index = 2;
        
        %data.userdata.ranges.Rescue_rate.range{1} = 0.5; %2
        %data.userdata.ranges.Rescue_rate.range{2} = 0.3; %2
        %data.userdata.ranges.Rescue_rate.index = 1;
        
        %data.userdata.ranges.shrink_rate.range = num2cell(0.2); %5
        %data.userdata.ranges.shrink_rate.index = 1;
        
        data.userdata.ranges.modelname.range{1} = 'MODEL1'; %5
        data.userdata.ranges.modelname.range{2} = 'MODEL2'; %5
        data.userdata.ranges.modelname.index = 1;
    end
    % == Do not change the following
    fields=fieldnames(data.userdata.ranges);
    fprintf(1,'\n');
     titlestring=sprintf('%s -\n',data.projectname);
    for i=1:length(fields)
        fieldname=fields{i};
        eval(sprintf('%s=(data.userdata.ranges.(fieldname).range{data.userdata.ranges.(fieldname).index});',fieldname));
        if ischar(data.userdata.ranges.(fieldname).range{1})
            titlestring=[titlestring,' ',sprintf('%s: %s\n ',fieldname,data.userdata.ranges.(fieldname).range{data.userdata.ranges.(fieldname).index})];
        else
            titlestring=[titlestring,' ',sprintf('%s: %f\n ',fieldname,data.userdata.ranges.(fieldname).range{data.userdata.ranges.(fieldname).index})];
        end
    end
    fprintf(1,'%s\n',titlestring);
    if MT_haveGUI( data )
        singlestep=get(gcbo,'tag');
        if isfield(data,'view_steps') && rem(data.iterations,data.plotoptions.view_steps)==0 || strcmp(singlestep,'pushbutton_step')
            if isfield(data.plotprops,'TitleH') && ishandle( data.plotprops.TitleH)
                set(data.plotprops.TitleH,'String',titlestring,'Parent',data.plotprops.AxesH,'interpret','none');
            end
        end
    else % The following is for use on the cluster
        if rem(data.iterations,data.plotoptions.view_steps)==0 
            set(data.plotprops.TitleH,'String',titlestring,'Parent',data.plotprops.AxesH,'interpret','none');
        end
    end
    % == End of do not change
    if data.iterations==0
        %% 
        %%
        %SET time per step
        %data.cellprops.secondsPerStep=7.5; % frame rate in experimental data
        % set default parameters
        data=mtSETMTprops(data,...
            'thicknessMicrons', 0.0250,...
            'minvox',0.0250,...
            'growthrate',0.500,...
            'shrinkrate',0,...
            'shrinkheadrate',5,...
            'catastropherate',5,...
            'maxAlignToSurfAngle',40,...
            'maxZipToMTAngle',20,...
            'bendpriority','membrane',...
            'maxSpawnAngle',40,...
            'maxAge',0,...
            'nuclspont',0.0180,...
            'nuclonMT',0.0150,...
            'probCatastropheWhenHit',0.0200,...
            'probPauseOnCollision',0.8000,...
            'probSpontaneousCatastrophe',0,...
            'backwardBranching',0,...
            'parallelspawnprob',[],...
            'wraparound',0,...
            'FaceColor',[0 0 1],...
            'FaceAlpha',0.4000,...
            'Label',-6,...
            'isLayer',0,...
            'Static',0,...
            'InUse',1     );
        % modify parameters according to the model
        %Change MT properties (from those shown at the bottom of the file)
        %(For a full list of properties click on help for this function.)
        data=mtSETMTprops(data,...
            'thicknessMicrons',0.025,...
            'growthrate',0.05,...
            'shrinkrate',0,... 0.005,... %3,...
            'nuclonMT',0.015,...
            'nuclspont',0.018,...
            'maxAlignToSurfAngle',20,...
            'maxZipToMTAngle',20,...
            'probPauseOnCollision',0.8, ...
            'probCatastropheWhenHit',0.02,...
            'maxSpawnAngle',40);
        %
        % Allard et al parameters for 21 degree wildtype
        % data.userdata.fgp=0.2/60;
        % data.userdata.fgs=0.17/60;
        % data.userdata.fpg=2.01/60;
        % data.userdata.fps=1.02/60;
        % data.userdata.fsg=1.0/60;
        % data.userdata.fsp=0.31/60;

        % Test patterns in factors id_a and s_a
        % I = checkerboard(3);
        % for i=1:data.cellprops.cellsize(3)
        %    id_a_p(1:24,1:24,i)=I;
        % end
        %
        % Offset spot
        % selectedRow=getClipSliceNumber(data); % to appear on both clip planes
        % selectedCol=round(data.cellprops.cellsize(2)/3);
        % selectedDepth=round(data.cellprops.cellsize(3)/2);
        % spotRad=1;
        % for i=selectedRow-spotRad:selectedRow+spotRad
        %     for j=selectedCol-spotRad:selectedCol+spotRad
        %         for k=selectedDepth-spotRad:selectedDepth+spotRad
        %             id_a_p(i,j,k)=0.1;
        %         end
        %     end
        % end
        %        
        % % insert a sheet of 1's into s_a_p plasma_membrane and allow to diffuse
        % id_a_p(data.cellprops.Vol~=data.organelleprops.cytoplasm.Label)=0;
        % s_a_p=id_a_p;
        % data=setupDiffusion(data,'Factorname','s_a','DiffK',[0.2,0.0],...
        %    'RegionLists',{{'cytoplasm'},{'plasma_membrane','microtubules','vacuole','cell_wall'}});
        %
        % Factors overlaying side and top/bottom edges of cytoplasm
        % midx=round(data.cellprops.cellsize(1)/2);
        % midy=round(data.cellprops.cellsize(2)/2);
        % midz=round(data.cellprops.cellsize(3)/2);
        % cytoplasm_ind=find(data.cellprops.Vol==data.organelleprops.cytoplasm.Label);
        % [xx,yy,zz]=ind2sub(data.cellprops.cellsize,cytoplasm_ind);
        % max_cyt_x=max(xx);
        % max_cyt_y=max(yy);
        % min_cyt_x=min(xx);
        % min_cyt_y=min(yy);

        % setup wrapping
        % data=MT_wrap(data,'setup');

        % id_b_p(1:min_cyt_x+1,:,:)=1;
        % id_b_p(max_cyt_x-1:end,:,:)=1;
        % id_a_p(:,1:min_cyt_y+1,:)=1;
        % id_a_p(:,max_cyt_y-1:end,:)=1;
        % s_a_p(:)=0;
        % data=setupDiffusion(data,'Factorname','s_a','DiffK',[0.02,0.0],...
        %     'RegionLists',{{'cytoplasm'},{'plasma_membrane','microtubules','vacuole','cell_wall'}});
        % s_b_p(:)=0;
        % data=setupDiffusion(data,'Factorname','s_b','DiffK',[0.1,0.0],...
        %     'RegionLists',{{'cytoplasm'},{'plasma_membrane','microtubules','vacuole','cell_wall'}});    
        switch modelname
            case 'MODEL1'
            case 'MODEL2'
        end
    else
        %% 
        %%
        % plot profiles of factors in the context of the cytoplasm region
        %plotrows=2;
        %plotcols=1;
        %FactorProfilePlot(data,{'s_b','cytoplasm'},'x',plotrows,plotcols,1);
        %FactorProfilePlot(data,'s_a','y',plotrows,plotcols,2);
        %
        % _Code to run the model_
        % Cell wide changes to, for example, factors
        % s_a_p(region(data,id_a_p,'cytoplasm'))=1;% generate (clamp) intersecting with cytoplasm
        % s_b_p(region(data,id_b_p,'cytoplasm'))=1;% generate (clamp)

        %
        % s_a_p(region(data,id_a_p,'cytoplasm'))=1;% generate (clamp)
        % s_a_p=s_a_p*(1-0.01); % decay
        % s_b_p(region(data,id_b_p,'cytoplasm'))=1;% generate (clamp)
        % s_b_p=s_b_p*(1-0.01); % decay
        %
        %Make changes here
        %% 
        %%
        %  Wrap where needed by creating new MTs that form the wrap
        % data=MT_wrap(data,'run');        
        %
        % _Checking and changes to individual MTs_
        %so ~0.25 per square (cubic) micron
        for i_MT=1:length(data.working.dyn.microtubules.Org)
            MT=data.working.dyn.microtubules.Org(i_MT);
            % useful debug tip - when trying to find the index given the ID, (e.g. by right clicking an MT) use
            % ind=MT_ID2ind(data,ID);
            %
            % Some examples of code
            % case 'ALLARD_FIG2_NO_WRAP'
            %     % Because we approximate shrinkage (catastrophe) by deleting the MT there are only two
            %     % options at this point: growing and paused
            %     if MT.Growing % is paused and could grow
            %         R=rand;
            %         if R<rate2prob(data,data.userdata.fgs) % approximation to catastrophic shrink rate
            %             MT.Alive=false;
            %         elseif R<(rate2prob(data,data.userdata.fgs)+rate2prob(data,data.userdata.fgp)) % pause
            %             MT.Growing=false;
            %         end
            %     else
            %         R=rand;
            %         if R<rate2prob(data,data.userdata.fps) % approximation to catastrophic shrink rate
            %             MT.Alive=false;
            %         elseif R<(rate2prob(data,data.userdata.fpg)+rate2prob(data,data.userdata.fps)) % grow
            %             MT.Growing=true;
            %         end
            %     end
            %     switch subversion
            %         case 'STOP_GROWING_AT_EDGE'
            %             if hasHit('Static',MT)
            %                 MT.Growing=false;
            %             end
            %     end

            % length of MT
            %if size(MT.Verts,1)==1
            %    MTlength=0;
            %else
            %    diffs=diff(MT.Verts).^2; % calculate length of MT
            %    MTlength=sum(sqrt(sum(diffs,2))); % microns
            %end
            %
            % if MTlength>0.5
            %    MT.Props.nuclonMT=min(1,0.4*MTlength); % observed approx. 0.007 per micron per sec
            % else
            %    MT.Props.nuclonMT=0;
            % end
            %
            %ageMT=data.working.CellAge;% seconds
            %maxAgeColour=20;
            %MT.Props.FaceColor=[max(0,min(1,1-ageMT/maxAgeColour)), 0.5, max(0,min(1,ageMT/maxAgeColour))];
            %
            %if ~MT.Growing  % hit anything and did not co-align
            %if  MT.BoundPLM or hasJustHit('PLM',MT)
            %
            %hit=hasHit('Static',MT); % has the MT hit a static organelle?
            %if hit
            %    MT.Growing=false; % ensure that MTs that have co-aligned with the membrane stop growing
            %    if rand<0.1 
            %        MT.Alive=false; % kill a proportion of MTs that collided with static organelle
            %    end
            %end
            %   Alternatively, if there are factors denoting particular sides (see A above)
            %   Aside=sampleFactor(id_a_p,MT,'Positive');
            %   Bside=sampleFactor(id_b_p,MT,'Positive');
            %   if Aside>0 || Bside>0
            %       if rand<0.000 % only keep them going with a certain probability
            %           MT.Alive=true;
            %       else
            %           MT.Alive=false;
            %       end
            %   end
            % if rand>Bside % if Bside is zero alway kill
            %    MT.Alive=false;
            % end

            %if MT.BoundMic or hasJustHit('MT',MT)
            % old if ~isempty( MT.Hit ) && ~isempty( MT.Hit(end).hitmt ) % Hit another MT now or in the past
            %if hasHit('MT',MT)
            %    if rand<(1-MT.props.probPauseOnCollision) 
            %        MT.Alive=false;
            %    end
            %end
            %if rand<(MT.props.probCatastropheWhenHit)
            %    MT.Alive=false;
            %end            %
            %if  MT.BoundPLM && MT.Growing  % hit plasma_membrane and aligned
            %elseif MT.BoundPLM && ~MT.Growing  % hit plasma_membrane and NOT aligned
            %end
            %
            %if  MT.BoundMic && MT.Growing  % hit another microtubule and aligned
            %elseif MT.BoundMic && ~MT.Growing  % hit another microtubule and NOT aligned
            %    MT.Alive=false;
            %end
            %
            %if  MT.BoundVac && MT.Growing  % hit vacuole membrane and aligned
            %elseif MT.BoundVac && ~MT.Growing  % hit vacuole membrane and NOT aligned
            %end
            %
            %% 
            %%
            % _Keep the following_
            % Clear flags from collision detector
            MT.BoundPLM=false;
            MT.BoundMic=false;
            MT.BoundVac=false;
            MT.BoundWll=false;
            data.working.dyn.microtubules.Org(i_MT)=MT;
        end
        %MTStats(data); % Plot distributions and other stats
        %%
    end

% put factors back into structure
    for i=1:size( data.factorprops.Concentration,2)
        factname=lower(data.factorprops.Index2Name{i});
        eval(['data.factorprops.Concentration(:,i)=',[factname,'_p(:);']]);
    end    
%% 
%%
% _Parameters initialised when the project was first created._
