%fratxPub1.       Copyright (C) 2011 Franklin B. Krasne.   
%This file is free software; you can redistribute it and/or modify it under the terms of the GNU General 
%Public License as published by the Free Software Foundation; either version 3 of the License, or (at your 
%option) any later version.
%This file is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the 
%implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
%See the GNU General Public License for more details. You should have received a copy of the GNU General 
%Public License  along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
%02111-1307, USA. 

%[Author note to himself:This is an annotated version of the program 
%(fratx327.m)used to do simulations for Krasne et al (2011). Its immediate progenitor is fratxWEBd.m 
%which is a  cleaned up version of the programs used for the simulations.]

%                     BRIEF TABLE OF CONTENTS
%            Lines numbers are those shown when the program
%                    is opened in the Matlab Editor
%Line number -- <103 is Matlab code for GUI setup  
% 103		Introductory  text followed by preliminaries related to display, graphing, etc.
% 170		Parameters values and variable initialization.
%	354		Function run_continue
%	1177	Special events called from GUI (e.g. Hx, Hs, consolidate, etc).
%	1300	Functions used by other routines
%	1331	Reset Experiment, Reset (New Fraidy), Quit, Intialize Fraidy.
%	1464	Various untilities. Including in order: Replot/Animate, SSdone (make 
%  Exp array from short method of scheduling), Various functions used in short 
%  scheduling method, Make (i.e. load) Long Schedule (i.e. externally written 
%  Exp array written as Excel text tab-delimited text file), goKeyboard, and 
%  routines to familiarize FRAT to contexts without explicitly writing suitable 
%  experience into experimental schedules.
%	2314	Various functions written by Matlab to initialize GUI controls.

%The following is code generated by Matlab for the GUI (Some of the
%uicontrol setup stuff is placed at the end of the program):
function varargout = fratxPub1(varargin)
%FRATXPUB1 M-file for fratxPub1.fig
%      FRATXPUB1, by itself, creates a new FRATXPUB1 or raises the existing
%      singleton*.%
%      H = FRATXPUB1 returns the handle to a new FRATXPUB1 or the handle to
%      the existing singleton*.
%      FRATXPUB1('Property','Value',...) creates a new FRATXPUB1 using the
%      given property value pairs. Unrecognized properties are passed via
%      varargin to fratxPub1_OpeningFcn.  This calling syntax produces a
%      warning when there is an existing singleton*.

%      FRATXPUB1('CALLBACK') and FRATXPUB1('CALLBACK',hObject,...) call the
%      local function named CALLBACK in FRATXPUB1.M with the given input
%      arguments.

%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help fratxPub1
% Last Modified by GUIDE v2.5 02-Nov-2011 12:01:47

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @fratxPub1_OpeningFcn, ...
                   'gui_OutputFcn',  @fratxPub1_OutputFcn, ...
                   'gui_LayoutFcn',  [], ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
   gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before fratxPub1 is made visible.
function fratxPub1_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   unrecognized PropertyName/PropertyValue pairs from the
%            command line (see VARARGIN)
% Choose default command line output for fratxPub1
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

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

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

% Get default command line output from handles structure
varargout{1} = handles.output;
%%%%%%%%%%%%%%%%%%%%END OF MATLAB-GENERATED CODE%%%%%%%%%%%%%%%%%%%%%%%%

             %Preliminaries related to graphing, display, etc

%   The code above is all code generated by Matlab to program the GUI, which
%was constructed using the editor provided for that purpose by Matlab.  The
%code written by the Author is all below this point.  Some of this code is
%for various utilities such as a routine for constructing the schedule for
%running experiments, whereas othe code is the implemntation of the model
%described in Krasne, Fanselow, and Zelikowsky (2011).  
%  A table of contents giving line numbers appears at the start of the program. 
%An attempt has been made to 
%provide some explanation of the code for the model proper here within the program. It is 
%presumed that it is this code that readers may wish to alter for their own
%purposes.  The utility code is not internally documented and it has not been 
%cleaned up for external consumption. 
%   It will be assumed that the reader has access to the
%mathematical description of the model provided on-line in the
%Supplementary Materials for the paper henceforth referred to here simply 
%as the "Supplement". The sections of the Supplement are numbered 
%for convenient reference, and these will be referred to here as necessary.
%   The Supplement contains a table relating the variable names used within the
%program to those used in the mathematical discription. The latter were
%selected to facilitate writing mathematical expressions, but since Greek
%letters, subscripts, etc are not available within Matlab,
%variable names differ somewhat between the program itself and the mathematical
%description of it. A table of equivalents is given in the Manual accompanying this program. Note also 
%that in order to increase readability without
%using extensive dashes, case of letters in variable and parameter names
%was adjusted arbitrarily to help the eye parse long variable names.  E.g.
%the "CEM" and "cem" in "CEMs==1" and  "Acem", respectively, both refer to central nucleus. 
%   Another notational matter worth mention is that in the mathematical
%description of the Supplement we generally specified the nucleus and cell
%type of a variable as a subscript; thus "A subscript LAp" was the
%activation of principal cells of LA.  However, in the program, the
%amygdala principal cells of LA were called "p" cells, the principal cells
%of BL were called "q", the inhibitors of LA were referred to as "i" cells
%and the inhibitors of BL were called "j" cells. Thus the activation of LA
%princpal cells in the program is simply Ap.
  %Finally, note that this version of the program includes an animation utility carried
%over from the teaching version of the program from which this research version was
%derived (with considerable substantive changes, including a signifcantly
%more complicated amygdala anatomy, and removal of many teaching-related features). 
%The animation utility requires several files loaded in the lines below.  These files must be
%included in the same folder as the .m file itself.  If they are not wanted,
%they and the parts of the program that use them can easily be removed.
%They are of virtually no scientific value, but were retained in this
%version simply because the author is fond of the animation.

hmainTemp=gcf;
figure(1)
set(1,'Name','Animation') 
A=imread('Slide1.jpg'); 
imshow(A,'InitialMagnification',50) 
global positionFig1
positionFig1=get(1,'Position'); 
positionFig1 = positionFig1-[0 200 0 0];
hFig1Axes=gca;
positionFig1Axes=get(hFig1Axes, 'Position');
positionFig1Axes(1)=0; positionFig1Axes(2)=0;
set(hFig1Axes,'Position',positionFig1Axes)
set(1,'Position',positionFig1)
global hmain animateflag
load fratframes1   %loads array fratnormframes used for animation.
load fratshkd3frames  %loads array of same name used for animation.
hmain=hmainTemp;
animateflag=0;

                  %CODE FOR MODEL PROPER BEGINS HERE.
                         %Declarations

%Parameters                         
global alphaLA betaLA etaLA zetaLA alphaBL betaBL etaBL zetaBL thrshElig
global psec ArMultLA ArMultBL
global thrshRp thrshRq 
global Gi Gj Gr Kp Ki Kq2 Kj Dp Dq
global Np
global VpMax VqMaxCa VqMax ViMax VjMax
global Habitcx HabitBL HabitLA
global ExtFactorSwitch LA_BLplastSwitch Gpq
global Nrows 
global E Gus netMax
global Gleak a b c d 
global bmode bbot btop bother
global zmode zbot ztop zother
global NTcntxt NTcntxt_cs NTcntxt_0 q 
%Note:NTcntxt_0 is the number of neurons representing the context alone in
%the absence of any CS.  It was set to zero in all simulations of Krasne et
%al (2011).
global Grp Grq Gp_cem Gp_cemON 
global ilTau ilExp ilCmpndTau ilCmpndExp
global ilHxTau ilHxExp ilHxCmpndTau ilHxCmpndExp
global NPcs NPcntxt NPcntxt_cs NPcntxt_0 
global NHcs NHcntxt NHcntxt_cs NHcntxt_0 NIcs NIcntxt NIcntxt_cs NIcntxt_0
global NT NP NH NI %Working arrays of Ns that have been specified elsewhere
global thrshRi thrshRj thrshXp endXp thrshXq endXq thrshXi gammaXi thrshXj gammaXj 
global Fsmrd0 mxHx  mx
global conrate ilIncr ilHxIncr ilIncrCmpnd ilHxIncrCmpnd
global opThrsh pi maxsec maxhabit starthabit endhabit Habit 

%Control variables
global hConsolButton hHxButton hHsButton
global fig2on fig3on fig4on fig5on fig8on fig9on fig10on 
global Ishk naloxone
global LAs Hs Hx BLs CEMs PFCs hilABCto1Button hilHxABCto1Button PAGptx PAGmuscimol
global pcentHs
global FamAllCntxts 
global hBLsButton
global hLAsButton  hCEMsButton hPFCsButton
global KeepOldFraidy
global SS SSdurations SSrests 

%Pameter values:
alphaLA=.015; 
betaLA=.000003;
etaLA=.01;     
zetaLA=0;
alphaBL=.009;
betaBL=7e-7; 
etaBL=.01;  
zetaBL=.0000;
Gus=100000;
Gi=8;
Gj=8;
Gr=1; 
psec=.2;
ArMultLA=1;
ArMultBL=1;
Gpq=2;
Gp_cemON=1;
VpMax=80;  
VqMaxCa=80;
VqMax=66.67;
ViMax=30 ;
VjMax=30; 
opThrsh=0.2;
pi=1.25;
BlkExp=2;  
NPcs=100;
NPcntxt=1; 
NPcntxt_cs=0;
NIcntxt=0;
NHcntxt=200;
NHcntxt_cs=250; 
NTcntxt=56;
NTcntxt_cs=250;

NPcntxt_0=0;     
NHcs=0;             
NIcs=0;
NTcntxt_0=0;
NIcntxt_cs=0;
NHcntxt_0=0;  
NIcntxt_0=0;  

Np=1;
%startLTPfactorLA=0.5; 
%startLTPfactorBL=0.5;
%thrshRp=startLTPfactorLA*VpMax;
%thrshRq=startLTPfactorBL*VqMax;

                       %Equivalents in pre-public version:
thrshRp=40;            %  =startLTPfactorLA*VpMax 
thrshRi=40;            %  =startLTPfactorLA*VpMax
thrshRq=40;            %  =startLTPfactorBL*VqMaxCa
thrshRj=40;            %  =startLTPfactorBL*VqMaxCa
thrshXp=20; endXp=50; 
thrshXq=20; endXq=50;
thrshXi=0; gammaXi=13;
thrshXj=0; gammaXj=13;
a=.3;  
b=.66;
c=.9; %rise rate of freezing
d=.3; %fall rate of freezing (0 min; 1 max)
maxsec=0.4;
conrate=.1;
ilIncr=.003; 
ilIncrCmpnd=.03;
ilHxIncr=.005;
ilHxIncrCmpnd=.005;
thrshElig=.05;
Grp=20; Grq=20;
ilTau=.6; ilExp=2.5; ilCmpndTau=.1; ilCmpndExp=1;
ilHxTau=.2;
ilHxExp=2.5; ilHxCmpndTau=.1; ilHxCmpndExp=1;
mx=.9875; mxHx=.98;
ExtFactorSwitch=0; 
LA_BLplastSwitch=0;
E=100;
Ishk=100;
  
%Author self-note: The following N arrays are for convenience in later calculations and
%were moved here from function initializefraidy where they were placed at
%a time when N's were changed by the program.  Things should be revised
%so that NI and NH and replace NI as appropriate.
NP=[NPcntxt NPcntxt NPcntxt NPcs NPcs NPcntxt_cs NPcntxt_cs NPcntxt_cs NPcntxt_cs NPcntxt_cs NPcntxt_cs NPcntxt_0 NPcntxt_0 NPcntxt_0];
NH=[NHcntxt NHcntxt NHcntxt NHcs NHcs NHcntxt_cs NHcntxt_cs NHcntxt_cs NHcntxt_cs NHcntxt_cs NHcntxt_cs NHcntxt_0 NHcntxt_0 NHcntxt_0];
NI=[NIcntxt NIcntxt NIcntxt NIcs NIcs NIcntxt_cs NIcntxt_cs NIcntxt_cs NIcntxt_cs NIcntxt_cs NIcntxt_cs NIcntxt_0 NIcntxt_0 NIcntxt_0];
NT=[NTcntxt NTcntxt NTcntxt 0 0 ...
NTcntxt_cs NTcntxt_cs NTcntxt_cs NTcntxt_cs NTcntxt_cs NTcntxt_cs NTcntxt_0 NTcntxt_0 NTcntxt_0];
NI=NI;
NH=NH;  
PFCs=0; LAs=0; BLs=0; CEMs=0;Hs=0;Hx=0;
hConsolButton=0; hHxButton=0; hHsButton=0;hBLsButton=0;
hLAsButton=0; hCEMsButton=0;hPFCsButton=0; hilABCto1Button=0;hilHxABCto1Button=0;  
Dp=1; Dq=1;
Gp=0 ;Gq=0;
Kp=1/VpMax;
Kq1=1/VqMaxCa;
Kq2=1/VqMax;
Ki=1/ViMax;
Kj=1/VjMax;
Gleak=1; 
netMax=80;
ch=.2; %context rep habituation factor
bmode=2;  
bbot=0; 
btop=65;
bother=50;
zmode=3;  
zbot=20;
ztop=50;
zother=0;
maxhabit=1;  
starthabit=20;  
endhabit=150; 
Habit=[ch ch ch 1 1 1 1 1 1 1 1 1 1 1]; %ch=contextual habit (<1). Habituation factors discount 
Habitcx=[Habit Habit Habit];            %the effectiveness of pure contextual inputs to amygdala    
HabitLA=Habitcx;          
HabitBL=[Habit 1];
Habit=[Habit Habit Habit Habit];  
q=1;
Gp_cem=0;
naloxone=0;
pcentHs=100;
Nrows=10000;
Fsmrd0=zeros(Nrows,1);
SS=[1 0 0 0;
    2 0 0 0;
    3 0 0 0;
    4 0 0 0;
    5 0 0 0];
SSdurations=[0 0 0 0 0 0];
SSrests=[0 0 0 0];
FamAllCntxts=1;  
fig2on=0; fig3on=0; fig4on=0; fig5on=0; fig8on=0; fig9on=0; fig10on=0;   
PAGptx=0;PAGmuscimol=0;
%H=zeros(1,14*4) ; %At least temporarily replaced by Habit array  
KeepOldFraidy=0;
initializefraidy

               %End of parameter-setting and initialization  

%The function run_continue, which follows, is the basic work-horse of the model.  It is
%called by hitting the Go Run/Continue button of the Gui. After a few
%preliminaries this sets in motion execution of the experiment scheduled in
%the Exp array described below. It does this line by line via the loop, 
%for j=1:Nsched, where Nsched is the number of lines in the Exp array. A break in
%execution of the schedule can be programmed into Exp so that various procedures
%such as consolidation, production of certain lesions, etc can be called from
%the GUI.  When such breaks occur,the Exp row number at which execution should resume
%is set equal to ContinueAt, and when the Run/Continue button is again hit the
%run_continue function starts up again at this row of the Exp schedule.  At 
%the end of running, the operator can either hit the "NewFraidy" button,
%which essentially erases all memory of the experiment just done, or can
%hit the "Reset Exp" button, which allows a new experiment to be done
%without erasing FRAT's memory of the previous events.  If the Reset Exp
%option is used, the previous graphs and the information in them is erased,
%but FRAT's "nervous system" maintains whatever state it was in.

% --- Executes on button press in run_continue.
function run_continue_Callback(hObject, eventdata, handles)
%Declarations 

%Parameters
global alphaLA betaLA etaLA zetaLA alphaBL betaBL etaBL zetaBL Gleak a b c d
global psec ArMultLA ArMultBL E opThrsh pi
global Gi Gj Dp Dq HabitBL HabitLA maxsec
global Np Ncxi Ncxt Ncxp Nhc VpDist VqDist VpMax VqMax ViMax VjMax Gpq
global thrshRp thrshRi thrshRq thrshRj thrshXp endXp thrshXq endXq thrshXi gammaXi thrshXj gammaXj
global thrshElig
global ilTau ilExp ilCmpndTau ilCmpndExp
global ilHxTau ilHxExp ilHxCmpndTau ilHxCmpndExp mx mxHx Gp_cemON

%Variables evaluated in W_INDEPENDENT EVALUATIONS routine
global inptCS1 inptCS2 inptA inptB inptC 
global AcxpCS1 AcxpCS2 AcxpA AcxpB AcxpC AcxpA1 AcxpA2 AcxpB1 AcxpB2 AcxpC1 AcxpC2
global rNcxpCS1 rNcxpCS2 rNcxpA rNcxpB rNcxpC rNcxpA1 rNcxpA2 rNcxpB1 rNcxpB2 rNcxpC1 rNcxpC2 
global AcxiA AcxiB AcxiC  
global rNcxiA rNcxiB rNcxiC  
global AcxtA AcxtB AcxtC AcxtA1 AcxtA2 AcxtB1 AcxtB2 AcxtC1 AcxtC2 
global rNcxtA rNcxtB rNcxtC rNcxtA1 rNcxtA2 rNcxtB1 rNcxtB2 rNcxtC1 rNcxtC2 
global AhcA AhcB AhcC AhcA1 AhcA2 AhcB1 AhcB2 AhcC1 AhcC2
global rNhcA rNhcB rNhcC rNhcA1 rNcxt rNhcA2 rNhcB1 rNhcB2 rNhcC1 rNhcC2 
global Ap Ai Ar Af Afhist
global rNcxp rNhc rNcxi 
global coefficientLA coefficientBL us Act
global NT NP NH NI

%Other variables of run_continue
global Gpe Gie Gqe Gje Wp Ui Wq Uj Vq Vj Vp Bp Bq CaI Vi Exp  
global ContinueAt interrupt x Fsmrd Nsched nextstart Npoints interval
global recalcActs 
global ilA ilB ilC ilA1 ilA2 ilB1 ilB2 ilC1 ilC2 il
global ilHxA ilHxB ilHxC ilHxA1 ilHxA2 ilHxB1 ilHxB2 ilHxC1 ilHxC2 ilHx
global conA conB conC conA1 conA2 conB1 conB2 conC1 conC2 con
global Fsmrd0 Aop AopPrv Gp_cem
global eligibleLA eligibleBL
global oldAq oldAu oldAx Ax oldRinput newRinput Au AopPrv

%Variables used for displays and graphing
global Wdata Eventdata Net_Actdata netErecipI
global fig2on fig3on fig4on fig5on fig8on fig9on

%Variables associated with in special treatments or GUI input
global  Hx Hs BLs naloxone morphine Ishk FamAllCntxts
global consolidate
global CEMs LAs PFCs PAGptx PAGmuscimol  pcentHs

%Handles
global hmain 

%Experiments are specified by an array called Exp that is constructed either
%externally or by she "Short" scheduling utility callable from the FRAT GUI.
% Each row of Exp has in order: 
%       1         2      3     4     5     6      7
%  row number,  cntxt,  cs1,  cs2,  us,  pause,  dur (# of 1 sec comutation intervals)
%Col 1: Exp array row #
%Col 2: Context. 1~A, 2~B, 3~C.  0~no context; used optionally when a pause
%       in the expreriment is scheduled.
%Col 3: 1~CS1 on; 0~CS1 off
%Col 4: 1~CS2 on; 0~CS2 off 
%Col 5: 1~US on; 0~US off
%Col 6: 0~no pause; 1~pause experiment until Run/Resume button on GUI hit.
%       When value is unity (pause called) other column 2,3,4,5, and 7 values are
%       ignored.
%Col 7: Number of computation intervals during which to apply
%       specifications of this row. Not relevant for lines requesting a
%       pause.

%Cortical and hippocampal inputs to the amygdala are represented, often in
%parallel, by specific variables, such as AcxpA (i.e. the activation of the
%cortical cxp cell type representing context A) and by arrays (or portion
%of an array) that carry the same information for all inputs of some
%category. This is done to simplify certain calculations.  In such cases
%the 14 types of stimulus that innervate amygdala are generally represented in the
%following order:

%   1    2       3     4   5   6   7   8   9   10  11  12  13  14
%cntxtA cntxtB cntxtC cs1 cs2 A*1 A*2 B*1 B*2 C*1 C*2 A*0 B*0 C*0  

%Thus AcxpA might also be represented as Acxp(1).

%Some arrays repeat this sequence for inputs from the separate cell populations
%cxp, hc, cxi, and cxt, as required for the computation being done.

hh=findobj('Tag','run_continue');
set(hh,'BackgroundColor','red');
if ContinueAt==1  %This is the first run of program or after a reset 
  %Some required initializations. 
  Nsched = size(Exp,1); 
  Npoints=0;   
  morphine=0;
  consolidate=0;
  for j=1:Nsched   %Calculate Npoints for graphs.
    if Exp(j,6)==1
      Npoints=Npoints+1 ; %Make room in graph to place line indicating pause.
    else
      Npoints=Npoints+Exp(j,7);  %Regular line.
    end  
  end
  oldAq=0; oldAu=0; oldAx=0; Ax=0; oldRinput=0; newRinput=0;Au=0; AopPrv=0;
  
  interval=0; nextstart=1;
  Act=zeros(1,14*4);  %Act is the full set of activations from which Vp and Vi are calculated.
  if FamAllCntxts==1
    if Hx==0 && Hs==0, ilA=1;il(1)=1;ilB=1;il(2)=1;ilC=1;il(3)=1;end
  end  
end   %endof ifContinueAt==1   

figure(7); openfigs(7)=1;  
set(7,'Name','Progress')
set(7,'Units','normalized','Position',[.2 .2 .6 .1])
bars=[0 Npoints];
barh(bars)
if ContinueAt >1, close(4);close(2);close(3);close(8);close(5);close(9);end

%%%%%%%%%%%%%%%%%%%%%%Start implementing rows of Exp array%%%%%%%%%%%%%%%

for j=ContinueAt :Nsched %Interprets lines of Experimental Schedule Array (Exp)
  %inpt CS1, CS2, A, B, C, US, and Pause Execution are read from lines of 
  %Experimental Schedule Array (Exp)which is constructed from information entered 
  %on GUI or written independently (see instructions for using program
  %for details or explanation above).
  cntxt=Exp(j,2); cs1=Exp(j,3); cs2=Exp(j,4); us=Exp(j,5); dur=Exp(j,7); interrupt=Exp(j,6);
  if interrupt==1
    ContinueAt=j+1;
    interval=interval+1; 
    Eventdata(interval,1:6)=[interval cntxt cs1 cs2 us interrupt];
    Wdata(interval,1:6)=Wdata(interval-1,1:6); %So not zero.
    break    %BREAK 
  end
  %Calculate coefficient. See Supplement Section  2.4.1-.4
  %Transform Exp info to inpt form for convenience in following calculations:
  if cs1==1, inptCS1=1; else inptCS1=0;end
  if cs2==1, inptCS2=1; else inptCS2=0;end
  if cntxt==1, inptA=1; else inptA=0;end
  if cntxt==2, inptB=1; else inptB=0;end
  if cntxt==3, inptC=1; else inptC=0;end
    
  %..........Steps 1-4 (2.4.1-.4)of Supplement follow........... 
  %These calculate activations and rN values for cortical and hippocampal cells.  
  %We call this set of steps W_INDEPENDENT EVALUATIONS.  
  %It is used twice and repeated in full each time, because it runs faster 
  %that way than if called as a subroutine.
    
  %W_INDEPENDENT EVALUATIONS (Annotated version; repetition used below is 
      %identical but not annotated). This pass done at start of new line of Exp:
    
  %Obtain consolidation status (0 or 1)and extent of implicit learning mediated by hippocampus, 
  %as well as implicit learning mediated by representation cortex (when hippocampus 
  %has been ablated) from con, il, and ilHx arrays.  Switches Hx, Hs,
  %PFCs, BLs, LAs, and CEMs (x for ablated, s for suppressed) are defined
  %on p 13 of SUPPLEMENTARY MATERIALS and obtained from the GUI and interpreted 
  %in separate functions below.  
  conA=con(1);conB=con(2);conC=con(3);conA1=con(6);conA2=con(7);conB1=con(8);
  conB2=con(9);conC1=con(10);conC2=con(11);
  ilA=il(1);ilB=il(2);ilC=il(3);ilA1=il(6);ilA2=il(7);ilB1=il(8);ilB2=il(9);ilC1=il(10);ilC2=il(11);
  ilHxA=ilHx(1);ilHxB=ilHx(2);ilHxC=ilHx(3);ilHxA1=ilHx(6);ilHxA2=ilHx(7);ilHxB1=ilHx(8);ilHxB2=ilHx(9);ilHxC1=ilHx(10);ilHxC2=ilHx(11);
  
  %Set cxp A and rN values (Supplement Step 1, Sect 2.4.1):
  if inptCS1==1, AcxpCS1=1; rNcxpCS1=1; else AcxpCS1=0;rNcxpCS1=0;end
  if inptCS2==1, AcxpCS2=1; rNcxpCS2=1; else AcxpCS2=0;rNcxpCS2=0;end
  if inptA==1, AcxpA=1; rNcxpA=1; else AcxpA=0;rNcxpA=0;end
  if inptB==1, AcxpB=1; rNcxpB=1; else AcxpB=0;rNcxpB=0;end
  if inptC==1, AcxpC=1; rNcxpC=1; else AcxpC=0;rNcxpC=0;end
  AcxpA1=AcxpA*AcxpCS1;rNcxpA1=AcxpA1;
  AcxpA2=AcxpA*AcxpCS2;rNcxpA2=AcxpA2;
  AcxpB1=AcxpB*AcxpCS1;rNcxpB1=AcxpB1;
  AcxpB2=AcxpB*AcxpCS2;rNcxpB2=AcxpB2;
  AcxpC1=AcxpC*AcxpCS1;rNcxpC1=AcxpC1;
  AcxpC2=AcxpC*AcxpCS2;rNcxpC2=AcxpC2;
  
  %Get hc A and rN values as a function of cxp values (Supplement Step 2, Sect 2.4.2):
  %con specifies the consolidation state for each configural stimulus.
  %0=unconsolidated; 1= consolidated. Once the representation of a
  %stimulus as moved to cortex or if hc is absent or suppressede Ahc for
  %that stimulus is zero.
  AhcA=ilA*(1-conA)*(1-Hx)*(1-Hs*(pcentHs/100))*AcxpA*rNcxpA; rNhcA=AhcA;
  AhcB=ilB*(1-conB)*(1-Hx)*(1-Hs*(pcentHs/100))*AcxpB*rNcxpB; rNhcB=AhcB;
  AhcC=ilC*(1-conC)*(1-Hx)*(1-Hs*(pcentHs/100))*AcxpC*rNcxpC; rNhcC=AhcC;
  %Note: Ahc values for context/CS compounds are geometric means of
  %activations for the context and the CS so that if either is zero, Ahc
  %for the compound will be zero.
  AhcA1=ilA1*(1-conA1)*(1-Hx)*(1-Hs*(pcentHs/100))*sqrt(AcxpA*AcxpCS1)*sqrt(rNcxpA*rNcxpCS1); rNhcA1=AhcA1;
  AhcA2=ilA2*(1-conA2)*(1-Hx)*(1-Hs*(pcentHs/100))*sqrt(AcxpA*AcxpCS2)*sqrt(rNcxpA*rNcxpCS2); rNhcA2=AhcA2;
  AhcB1=ilB1*(1-conB1)*(1-Hx)*(1-Hs*(pcentHs/100))*sqrt(AcxpB*AcxpCS1)*sqrt(rNcxpB*rNcxpCS1); rNhcB1=AhcB1;
  AhcB2=ilB2*(1-conB2)*(1-Hx)*(1-Hs*(pcentHs/100))*sqrt(AcxpB*AcxpCS2)*sqrt(rNcxpB*rNcxpCS2); rNhcB2=AhcB2;
  AhcC1=ilC1*(1-conC1)*(1-Hx)*(1-Hs*(pcentHs/100))*sqrt(AcxpC*AcxpCS1)*sqrt(rNcxpC*rNcxpCS1); rNhcC1=AhcC1;
  AhcC2=ilC2*(1-conC2)*(1-Hx)*(1-Hs*(pcentHs/100))*sqrt(AcxpC*AcxpCS2)*sqrt(rNcxpC*rNcxpCS2); rNhcC2=AhcC2;
  
  %Get cxi values as a function of hc values, or if consolidation of a
  %stimulus  has occurred or if hc is ablated and coritically compensated 
  %incidental learning is occurring, then in terms of cxp values (Supplement Step 3, Sect 2.4.3):
  %Note that input to cxi cells comes from hc initially in normal FRAT but
  %comes from cxp cells after consolidation or if hc is ablated. The linsig function 
  %is used as a simple way to keep A and rN between zero and unity as required by
  %their definitions.  Also note that in the simulations of Krasne et al (2011)the number of cxi neurons 
  %is set to zero for reasons given in the paper. 
  AcxiA=ilA*((1-conA)*AhcA + linsig(conA+ilHxA  ,0,1)*AcxpA)*((1-conA)*rNhcA + conA*rNcxpA); rNcxiA=AcxiA;
  AcxiB=ilB*((1-conB)*AhcB + linsig(conB+ilHxB  ,0,1)*AcxpB)*((1-conB)*rNhcB + conB*rNcxpB); rNcxiB=AcxiB;
  AcxiC=ilC*((1-conC)*AhcC + linsig(conC+ilHxC  ,0,1)*AcxpC)*((1-conC)*rNhcC + conC*rNcxpC); rNcxiC=AcxiC;
  
  %Get cxt values as a function of cxp values (Supplement Step 4, Sect 2.4.4):
  %Note that cxt cells get input from cxp cells only if consolidation has
  %occurred and/or if cortically compensated incidental learning has
  %occurred.
  AcxtA=linsig(conA+ilHxA,0,1)*AcxpA*rNcxpA; rNcxtA=AcxtA;
  AcxtB=linsig(conB+ilHxB,0,1)*AcxpB*rNcxpB; rNcxtB=AcxtB;
  AcxtC=linsig(conC+ilHxC,0,1)*AcxpC*rNcxpC; rNcxtC=AcxtC;
  AcxtA1=linsig(conA1+ilHxA1,0,1)*sqrt(AcxpA*AcxpCS1)*sqrt(rNcxpA*rNcxpCS1);rNcxtA1=AcxtA1;
  AcxtA2=linsig(conA2+ilHxA2,0,1)*sqrt(AcxpA*AcxpCS2)*sqrt(rNcxpA*rNcxpCS2);rNcxtA2=AcxtA2;
  AcxtB1=linsig(conB1+ilHxB1,0,1)*sqrt(AcxpB*AcxpCS1)*sqrt(rNcxpB*rNcxpCS1);rNcxtB1=AcxtB1;
  AcxtB2=linsig(conB2+ilHxB2,0,1)*sqrt(AcxpB*AcxpCS2)*sqrt(rNcxpB*rNcxpCS2);rNcxtB2=AcxtB2;
  AcxtC1=linsig(conC1+ilHxC1,0,1)*sqrt(AcxpC*AcxpCS1)*sqrt(rNcxpC*rNcxpCS1);rNcxtC1=AcxtC1;
  AcxtC2=linsig(conC2+ilHxC2,0,1)*sqrt(AcxpC*AcxpCS2)*sqrt(rNcxpC*rNcxpCS2);rNcxtC2=AcxtC2;   

  if PFCs==1 %This obliterates cxt cell values to conform to experimental 
             %obervations that consolidated context fear is not expressed
             %if PFC is ablated (Supplement Sect 2.5.2):
    AcxtA=0;rNcxtA=0;
    AcxtB=0;rNcxtB=0;
    AcxtC=0;rNcxtC=0;
    AcxtA1=0;rNcxtA1=0;
    AcxtA2=0;rNcxtA2=0;
    AcxtB1=0;rNcxtB1=0;
    AcxtB2=0;rNcxtB2=0;
    AcxtC1=0;rNcxtC1=0;
    AcxtC2=0;rNcxtC2=0;
  end

  %Reminder: Entries within arrays are in order
  %   1    2       3     4   5   6   7   8   9   10  11  12  13  14
  %cntxtA cntxtB cntxtC cs1 cs2 A*1 A*2 B*1 B*2 C*1 C*2 A*0 B*0 C*0      

  %The lines from here to the end of this routine place the results of the
  %above evaluations into arrays that allow later calculations to be
  %specified more compactly.  Note that these arrays were constructed to have
  %entries for A*0, B*0, and C*0,which correspond to conjunctions of the 
  %form context A but CS absence,etc., but these were assumed to be null for
  %the purposes of the simulations done in Krasne et al (2011).
  rNcxp=[rNcxpA rNcxpB rNcxpC rNcxpCS1 rNcxpCS2 rNcxpA1 rNcxpA2 rNcxpB1 rNcxpB2 rNcxpC1 rNcxpC2 0 0 0];
  Ncxp=rNcxp.*NP; 
  rNhc=[rNhcA rNhcB rNhcC 0 0 rNhcA1 rNhcA2 rNhcB1 rNhcB2 rNhcC1 rNhcC2 0 0 0];
  Nhc=rNhc.*NH;
  rNcxi=[rNcxiA rNcxiB rNcxiC 0 0 0 0 0 0 0 0 0 0 0];
  Ncxi=rNcxi.*NI;
  rNcxt=[rNcxtA rNcxtB rNcxtC 0 0 rNcxtA1 rNcxtA2 rNcxtB1 rNcxtB2 rNcxtC1 rNcxtC2 0 0 0];
  Ncxt=rNcxt.*NT;

  NLAactive=[Ncxp Ncxi Ncxt];
  NBLactive=[Nhc Np]; %For use later

  ActLA=(1-LAs)*[AcxpA AcxpB AcxpC AcxpCS1 AcxpCS2 AcxpA1 AcxpA2 AcxpB1 AcxpB2 AcxpC1 AcxpC2 0 0 0 ...   
         AcxiA AcxiB AcxiC 0       0       0      0      0      0      0      0      0 0 0 ...
         AcxtA AcxtB AcxtC 0       0       AcxtA1 AcxtA2 AcxtB1 AcxtB2 AcxtC1 AcxtC2 0 0 0];   

  for k=1:3*14 %Set activation to zero if N=0; needed so eligibility calculations work right
    if NLAactive(k)==0,ActLA(k)=0;end
  end

  %The following coefficient array is used to simplify  calculation of
  %activations at later steps.
  coefficientLA=ActLA.*NLAactive.*HabitLA;
  %END OF W_INDEPENDENT EVALUATIONS (end annotated version). This pass done @ start new line of Exp
    
  %%%%Calculations done for every computation interval (once per nominal second)%%%%
  for i= 1 : dur  %This repeats the current line of Exp dur times.
    interval=interval+1; %update calculation interval ("one-sec" time-step)
    %Write event data to data array:
    Eventdata(interval,1:6)=[interval cntxt cs1 cs2 us interrupt]; %Enter info into arrays for making graphs  

    if recalcActs==1 %If implicit learning has occurred during the previous interval, 
                     %we need to do W_INDEPENDENT EVALUATIONS again before evaluating amygdala.
      %W_INDEPENDENT EVALUATIONS: (Calculations identical to annotated version above)
      conA=con(1);conB=con(2);conC=con(3);conA1=con(6);conA2=con(7);conB1=con(8);
      conB2=con(9);conC1=con(10);conC2=con(11);
      ilA=il(1);ilB=il(2);ilC=il(3);ilA1=il(6);ilA2=il(7);ilB1=il(8);ilB2=il(9);ilC1=il(10);ilC2=il(11);
      ilHxA=ilHx(1);ilHxB=ilHx(2);ilHxC=ilHx(3);ilHxA1=ilHx(6);ilHxA2=ilHx(7);ilHxB1=ilHx(8);ilHxB2=ilHx(9);ilHxC1=ilHx(10);ilHxC2=ilHx(11);
       
      if inptCS1==1, AcxpCS1=1; rNcxpCS1=1; else AcxpCS1=0;rNcxpCS1=0;end
      if inptCS2==1, AcxpCS2=1; rNcxpCS2=1; else AcxpCS2=0;rNcxpCS2=0;end
      if inptA==1, AcxpA=1; rNcxpA=1; else AcxpA=0;rNcxpA=0;end
      if inptB==1, AcxpB=1; rNcxpB=1; else AcxpB=0;rNcxpB=0;end
      if inptC==1, AcxpC=1; rNcxpC=1; else AcxpC=0;rNcxpC=0;end
      AcxpA1=AcxpA*AcxpCS1;rNcxpA1=AcxpA1;
      AcxpA2=AcxpA*AcxpCS2;rNcxpA2=AcxpA2;
      AcxpB1=AcxpB*AcxpCS1;rNcxpB1=AcxpB1;
      AcxpB2=AcxpB*AcxpCS2;rNcxpB2=AcxpB2;
      AcxpC1=AcxpC*AcxpCS1;rNcxpC1=AcxpC1;
      AcxpC2=AcxpC*AcxpCS2;rNcxpC2=AcxpC2;

      AhcA=ilA*(1-conA)*(1-Hx)*(1-Hs*(pcentHs/100))*AcxpA*rNcxpA; rNhcA=AhcA;
      AhcB=ilB*(1-conB)*(1-Hx)*(1-Hs*(pcentHs/100))*AcxpB*rNcxpB; rNhcB=AhcB;
      AhcC=ilC*(1-conC)*(1-Hx)*(1-Hs*(pcentHs/100))*AcxpC*rNcxpC; rNhcC=AhcC;
      AhcA1=ilA1*(1-conA1)*(1-Hx)*(1-Hs*(pcentHs/100))*sqrt(AcxpA*AcxpCS1)*sqrt(rNcxpA*rNcxpCS1); rNhcA1=AhcA1;
      AhcA2=ilA2*(1-conA2)*(1-Hx)*(1-Hs*(pcentHs/100))*sqrt(AcxpA*AcxpCS2)*sqrt(rNcxpA*rNcxpCS2); rNhcA2=AhcA2;
      AhcB1=ilB1*(1-conB1)*(1-Hx)*(1-Hs*(pcentHs/100))*sqrt(AcxpB*AcxpCS1)*sqrt(rNcxpB*rNcxpCS1); rNhcB1=AhcB1;
      AhcB2=ilB2*(1-conB2)*(1-Hx)*(1-Hs*(pcentHs/100))*sqrt(AcxpB*AcxpCS2)*sqrt(rNcxpB*rNcxpCS2); rNhcB2=AhcB2;
      AhcC1=ilC1*(1-conC1)*(1-Hx)*(1-Hs*(pcentHs/100))*sqrt(AcxpC*AcxpCS1)*sqrt(rNcxpC*rNcxpCS1); rNhcC1=AhcC1;
      AhcC2=ilC2*(1-conC2)*(1-Hx)*(1-Hs*(pcentHs/100))*sqrt(AcxpC*AcxpCS2)*sqrt(rNcxpC*rNcxpCS2); rNhcC2=AhcC2;
  
      AcxiA=ilA*((1-conA)*AhcA + linsig(conA+ilHxA,0,1)*AcxpA)*((1-conA)*rNhcA+conA*rNcxpA); rNcxiA=AcxiA;
      AcxiB=ilB*((1-conB)*AhcB + linsig(conB+ilHxB,0,1)*AcxpB)*((1-conB)*rNhcB+conB*rNcxpB); rNcxiB=AcxiB;
      AcxiC=ilC*((1-conC)*AhcC + linsig(conC+ilHxC,0,1)*AcxpC)*((1-conC)*rNhcC+conC*rNcxpC); rNcxiC=AcxiC;
   
      AcxtA=linsig(conA+ilHxA,0,1)*AcxpA*rNcxpA; rNcxtA=AcxtA;
      AcxtB=linsig(conB+ilHxB,0,1)*AcxpB*rNcxpB; rNcxtB=AcxtB;
      AcxtC=linsig(conC+ilHxC,0,1)*AcxpC*rNcxpC; rNcxtC=AcxtC;
    
      AcxtA1=linsig(conA1+ilHxA1,0,1)*sqrt(AcxpA*AcxpCS1)*sqrt(rNcxpA*rNcxpCS1);rNcxtA1=AcxtA1;
      AcxtA2=linsig(conA2+ilHxA2,0,1)*sqrt(AcxpA*AcxpCS2)*sqrt(rNcxpA*rNcxpCS2);rNcxtA2=AcxtA2;
      AcxtB1=linsig(conB1+ilHxB1,0,1)*sqrt(AcxpB*AcxpCS1)*sqrt(rNcxpB*rNcxpCS1);rNcxtB1=AcxtB1;
      AcxtB2=linsig(conB2+ilHxB2,0,1)*sqrt(AcxpB*AcxpCS2)*sqrt(rNcxpB*rNcxpCS2);rNcxtB2=AcxtB2;
      AcxtC1=linsig(conC1+ilHxC1,0,1)*sqrt(AcxpC*AcxpCS1)*sqrt(rNcxpC*rNcxpCS1);rNcxtC1=AcxtC1;
      AcxtC2=linsig(conC2+ilHxC2,0,1)*sqrt(AcxpC*AcxpCS2)*sqrt(rNcxpC*rNcxpCS2);rNcxtC2=AcxtC2;   
        
      if PFCs==1
        AcxtA=0;rNcxtA=0;
        AcxtB=0;rNcxtB=0;
        AcxtC=0;rNcxtC=0;
        AcxtA1=0;rNcxtA1=0;
        AcxtA2=0;rNcxtA2=0;
        AcxtB1=0;rNcxtB1=0;
        AcxtB2=0;rNcxtB2=0;
        AcxtC1=0;rNcxtC1=0;
        AcxtC2=0;rNcxtC2=0;
      end
      %Reminder: Entries within arrays are in order 
      %   1    2       3     4   5   6   7   8   9   10  11  12  13  14
      %cntxtA cntxtB cntxtC cs1 cs2 A*1 A*2 B*1 B*2 C*1 C*2 A*0 B*0 C*0      
   
      rNcxp=[rNcxpA rNcxpB rNcxpC rNcxpCS1 rNcxpCS2 rNcxpA1 rNcxpA2 rNcxpB1 rNcxpB2 rNcxpC1 rNcxpC2 0 0 0];
      Ncxp=rNcxp.*NP; 
      rNhc=[rNhcA rNhcB rNhcC 0 0 rNhcA1 rNhcA2 rNhcB1 rNhcB2 rNhcC1 rNhcC2 0 0 0];
      Nhc=rNhc.*NH;
      rNcxi=[rNcxiA rNcxiB rNcxiC 0 0 0 0 0 0 0 0 0 0 0];
      Ncxi=rNcxi.*NI;
      rNcxt=[rNcxtA rNcxtB rNcxtC 0 0 rNcxtA1 rNcxtA2 rNcxtB1 rNcxtB2 rNcxtC1 rNcxtC2 0 0 0];
      Ncxt=rNcxt.*NT;
      NLAactive=[Ncxp Ncxi Ncxt];
      NBLactive=[Nhc Np]; 
    
      ActLA=(1-LAs)*[AcxpA AcxpB AcxpC AcxpCS1 AcxpCS2 AcxpA1 AcxpA2 AcxpB1 AcxpB2 AcxpC1 AcxpC2 0 0 0 ...   
         AcxiA AcxiB AcxiC 0       0       0      0      0      0      0      0      0 0 0 ...
         AcxtA AcxtB AcxtC 0       0       AcxtA1 AcxtA2 AcxtB1 AcxtB2 AcxtC1 AcxtC2 0 0 0];   
      for k=1:3*14
        if NLAactive(k)==0,ActLA(k)=0;end
      end
      coefficientLA=ActLA.*NLAactive.*HabitLA;
      %END OF W_INDEPENDENT EVALUATIONS (un-annotated version)
    end %End of "if recalcActs==1"
    
    %Evaluations of amygdala activation levels and other
    %evaluations that are affected by amygdala synaptic weights are done
    %now. (Supplement Step 5, Sect 2.4.5). Some of these evaluations are done 
    %again after weights are changed.
    
    %Supplement Step 5A, Sect 2.4.5.1
    %AMYG EVALS:
    %LA evaluations:
    Wp=dot(coefficientLA,Gpe); Ui=dot(coefficientLA,Gie); %These dot products make subsequenct 
                                                          %calculations more convenient.
    Vi=Ui*E/(1+Ui); Ai=linsig(Vi,0,ViMax);  %Calculate depolarzation (V) and activity (A)for inhbitory
                                             %interneurons.
    VpDist=Wp*E/(1+Wp);   %Calculate V for distal compartment of p cell.
    Vp = Dp*VpDist/(1+Ai*Gi); Ap=linsig(Vp,0,VpMax); %Get V for prox compartent and activation.
    if LAs==1, Vp=0; Vi=0;Ai=0;Ap=0; end  %Effect LA suppression if called for by GUI.
    
    %BL evaluations:
    ActBL=[AhcA  AhcB  AhcC  0       0       AhcA1  AhcA2  AhcB1  AhcB2  AhcC1  AhcC2  0 0 0 Ap];
    %Note that Ap has been tacked on to the end of the above array and to BL cell
    %synaptic weight arrays because the LA principal cells provide one of the inputs to BL cells.
    %However, in this version of the program the LA-to-BL synapses are not plastic.
    
    %Set activation to zero if N=0; needed so eligibility works right.  
    %This is just a precaution. (Eligibility of an afferet synapse on an 
    %amygdala neuron for change on interval n+1 is a function of its activation level
    %on interval n; however, we were concerned that in some cases the program might, due to a
    %programming oversight, calculate an activation for an afferent for
    %which rN or N are zero.  This would have no impact in most cases, since
    %if N=0, the product of A*N*rN will be zero.  However, an elevated activation 
    %could lead to an unwanted elgibility for change being created):
    for k=1:14  
      if NBLactive(k)==0,ActBL(k)=0;end
    end  
    coefficientBL=ActBL.*NBLactive.*HabitBL;
    Wq=dot(coefficientBL,Gqe); Uj=dot(coefficientBL,Gje);
    Vj=Uj*E/(1+Uj); Aj=linsig(Vj,0,VjMax);       
    VqDist=Wq*E/(1+Wq);                           
    Vq=Dq*VqDist/(1+Aj*Gj); Aq=linsig(Vq,0,VqMax); 
    if BLs==1, Vq=0;Vj=0;Aj=0;Aq=0; end  %Effect BL suppression if requested by GUI          
    %END AMYG EVALS

    %.....Supplement Step 5B (Sect 2.4.5.2). Evaluate CEm..........
    if BLs==0     
      Acem=Aq;
    else
      Acem=linsig(Ap*Gp_cem,0,1);
    end 
    if CEMs==1, Acem=0; end
    
    %.............Supplement Step 6 (Sect 2.4.6).................
    %Calcuclate Af and Freezing scores and save latter in array for later
    %plotting:
    if us==0, Af=linsig(Acem,a,b);else Af=0; end
    
    Afhist(interval)=Af; %Write Af to array for later plotting
    if interval==1
      Fsmrd0(interval)=0; %Fsmrd is a temporally smeared version of Af
    else
      if Afhist(interval)> Fsmrd0(interval-1)
        Fsmrd0(interval)=Fsmrd0(interval-1)+c*(Afhist(interval)-Fsmrd0(interval-1));
      else
        Fsmrd0(interval)=Fsmrd0(interval-1) - d*(Fsmrd0(interval-1) - Afhist(interval));
      end  
    end
    %Fsmrd is the freezing score that gets plotted.
    if us==0, Fsmrd(interval)=Fsmrd0(interval); else Fsmrd(interval)=0;end
    
    %...........Not in Supplement........... 
    %These values that give something of a picture of what is going on in 
    %LA and  BL are calculated and saved in an array for later plotting:
    netErecipI(interval,1)=VpDist/E;
    netErecipI(interval,2)= 1+Ai*Gi;
    netErecipI(interval,3)=VqDist/E;
    netErecipI(interval,4)=1+Aj*Gj;
    Net_Actdata(interval,1:4)=[Vp Ap Vq Aq];       
      
    %......Supplement Step 7 (Sect 2.4.7). Calculate Ar and Ax.......
    %Calculate Ar and Ax first time
    %Used from previous computation interval: 
    %oldRinput used to compute change (uses previous naloxone value)
    %AopPrv used to discount Au for prior CR
    Aop=linsig(Acem,opThrsh,1);
    As=linsig(Acem,0,maxsec);
    Au=us*(Ishk/100)*(1-((1-naloxone)*AopPrv)^pi);
    newRinput=Au+psec*As;
    Ar=linsig(newRinput-oldRinput,0,1);
    if (Ar>0)||(us==1),Ax=0;else Ax=(1-naloxone)*Aop;end
    if PAGptx==1, Ax=1;end   %A few experiments for Supplement were done under this condition
    if PAGmuscimol==1, Ax=0;end  %      "
    
    %...Supplement Step 8 (Sect 2.4.8). Calculate p cell backprop activity....
    %and inhib interneuron Ca levels.
    Bp=100*linsig(Vp+100*Ar*ArMultLA,0,100);
    Bq=100*linsig(Vq+100*Ar*ArMultBL,0,100);
    kappaLA=100;kappaBL=100;
    CaI=100*linsig(Ap*VpMax+ kappaLA*Ar, 0, 100); %the multiplier of Ar here was 
    CaJ=100*linsig(Aq*VqMax+ kappaBL*Ar, 0, 100);
    if LAs==1, Bp=0; CaI=0; end
    if BLs==1, Bq=0; CaJ=0; end
      
    %......Supplement Step 9 (Sect 2.4.9) Update amygdala synaptic weights...
    for k=1:14*3
      if Ar>0
        deltaGpe= eligibleLA(k)*Ar*alphaLA*linsig(Bp,thrshRp,E);
        deltaGie=-eligibleLA(k)*Ar*etaLA*linsig(CaI,thrshRi,E); %note: thrshRi=thrshRp
      else
        deltaGie= eligibleLA(k)*Ax*betaLA*BumpCa(CaI,thrshXi,E,gammaXi);
        deltaGpe=-eligibleLA(k)*Ax*zetaLA*BumpB(Bp,thrshXp,endXp);        
      end  
      Gpe(k)=Gpe(k)+deltaGpe; Gie(k)=Gie(k)+deltaGie;   
      if Gpe(k)<0, Gpe(k)=0;end
      if Gie(k)<0, Gie(k)=0;end
    end
    for k=1:14
      if Ar>0 
        deltaGqe=eligibleBL(k)*Ar*alphaBL*linsig(Bq,thrshRq,E);
        deltaGje=-eligibleBL(k)*Ar*etaBL*linsig(CaJ,thrshRj,E);          
      else
        deltaGje= eligibleBL(k)*Ax*betaBL*BumpCa(CaJ,thrshXj,E,gammaXj);
        deltaGqe=-eligibleBL(k)*Ax*zetaBL*BumpB(Bq,thrshXq,endXq);
      end  
      Gqe(k)=Gqe(k)+deltaGqe; Gje(k)=Gje(k)+deltaGje;       
      if Gqe(k)<0, Gqe(k)=0;end
      if Gje(k)<0, Gje(k)=0;end
    end  
      Gqe(15)=Gpq; Gje(15)=0; %Perhaps these should be made plastic.
      
    %.......Place current values into array for later graphing..................
    netErecipI(interval,1)=VpDist/E;
    netErecipI(interval,2)= 1+Ai*Gi;
    netErecipI(interval,3)=VqDist/E;
    netErecipI(interval,4)=1+Aj*Gj;
    Net_Actdata(interval,1:4)=[Vp Ap Vq Aq]; 

    %Color Order: red grn blk purple cyan  
    %Variables to be graphed later assigned as convenient:
    Wdata(interval,1)=0;   %plotted red
    Wdata(interval,2)=0;   %plotted green
    Wdata(interval,3)=0;   %plotted black
    Wdata(interval,4)=0;   %plotted purple
    Wdata(interval,5)=0;   %plotted cyan 
    Wdata(interval,6)=0;   %plotted gray

    %..............Step 10: Re-evaluate Amyg ......................
    %AMYG EVALS
    Wp=dot(coefficientLA,Gpe); Ui=dot(coefficientLA,Gie); 
    Vi=Ui*E/(1+Ui); Ai=linsig(Vi,0,ViMax);  %Ai=Ki*Vi;
    VpDist=Wp*E/(1+Wp);
    Vp = Dp*VpDist/(1+Ai*Gi); Ap=linsig(Vp,0,VpMax);
    if LAs==1, Vp=0; Vi=0;Ai=0;Ap=0; end 

    ActBL=(1-BLs)*[AhcA  AhcB  AhcC  0       0       AhcA1  AhcA2  AhcB1  AhcB2  AhcC1  AhcC2  0 0 0 Ap];
    for k=1:14 %Set activation to zero if N=0; needed so eligibility works right
      if NBLactive(k)==0,ActBL(k)=0;end
    end  
    coefficientBL=ActBL.*NBLactive.*HabitBL;
    Wq=dot(coefficientBL,Gqe); Uj=dot(coefficientBL,Gje);
    Vj=Uj*E/(1+Uj); Aj=linsig(Vj,0,VjMax);        
    VqDist=Wq*E/(1+Wq);
    Vq=Dq*VqDist/(1+Aj*Gj); Aq=linsig(Vq,0,VqMax); 
    if BLs==1, Vq=0;Vj=0;Aj=0;Aq=0; end
    %END AMYG EVALS  
    
    %...........Step 11: Update LA-CE connectivity....................
    if BLs==1 && Ap>0 && us==1 && CEMs==0, Gp_cem=Gp_cemON; end

    %.....Step 12: Calculate A'cem, R'inpt, and various "old" values under new synaptic weights.....
    Ar=0;
    if BLs==0
      Acem=Aq;
    else
      Acem=linsig(Ap*Gp_cem,0,1);
    end  
    if CEMs==1, Acem=0; end
    Aop=linsig(Acem,opThrsh,1);
    As=linsig(Acem,0,maxsec);        
    Au=us*(Ishk/100)*(1-((1-naloxone)*AopPrv)^pi);      
    oldRinput=Au+psec*As;
    AopPrv=Aop; 

    %............Step 13: Update incidental learning..................   
    %Whenever incidental learning occurs the flag, recalcActs is set so
    %that W_INDEPENDENT EVALUATIONS, which are ordinarily done only at the
    %start of each line of the Exp schedule but which are affected by incidental learning,
    %will be re-run.
    if Hx==0 && Hs==0      
      if AcxpA>.01 
        recalcActs=1; 
        ilo=ilA;if ilA<mx,  ilA=ilA+ ilTau*(1-ilA)^ilExp;  else ilA=1;end
        Gqe(1)=Gqe(1)*(ilo/ilA) ;  
        Gje(1)=Gje(1)*(ilo/ilA) ;
      end  
      if AcxpB>.01
        recalcActs=1;
        ilo=ilB;if ilB<mx,  ilB=ilB+ ilTau*(1-ilB)^ilExp;  else ilB=1;end
        Gqe(2)=Gqe(2)*(ilo/ilB) ;
        Gje(2)=Gje(2)*(ilo/ilB) ;
      end  
      if AcxpC>.01  
        recalcActs=1;
        ilo=ilC;if ilC<mx,  ilC=ilC+ ilTau*(1-ilC)^ilExp;  else ilC=1;end
        Gqe(3)=Gqe(3)*(ilo/ilC) ;
        Gje(3)=Gje(3)*(ilo/ilC) ;
      end  

      if AcxpA>.01 && AcxpCS1>.01 
        recalcActs=1;
        ilo=ilA1;if ilA1<mx,ilA1=ilA*linsig(ilA1+ilCmpndTau*(1-ilA1)^ilCmpndExp,0,ilA);else ilA1=1;end 
        Gqe(6)=Gqe(6)*(ilo/ilA1) ;
        Gje(6)=Gje(6)*(ilo/ilA1) ;
      end     
      if AcxpA>.01 && AcxpCS2>.01
        recalcActs=1;
        ilo=ilA2;if ilA2<mx, ilA2=ilA*linsig(ilA2+ilCmpndTau*(1-ilA2)^ilCmpndExp,0,ilA);else ilA2=1;end 
        Gqe(7)=Gqe(7)*(ilo/ilA2) ;
        Gje(7)=Gje(7)*(ilo/ilA2) ;
      end  
      if AcxpB>.01 && AcxpCS1>.01
        recalcActs=1;
        ilo=ilB1;if ilB1<mx, ilB1=ilB*linsig(ilB1+ilCmpndTau*(1-ilB1)^ilCmpndExp,0,ilB);else ilB1=1;end  %Try this
        Gqe(8)=Gqe(8)*(ilo/ilB1) ;
        Gje(8)=Gje(8)*(ilo/ilB1) ;
      end  
      if AcxpB>.01 && AcxpCS2>.01 
        recalcActs=1;
        ilo=ilB2;if ilB2<mx, ilB2=ilB*linsig(ilB2+ilCmpndTau*(1-ilB2)^ilCmpndExp,0,ilB);else ilB2=1;end  
        Gqe(9)=Gqe(9)*(ilo/ilB2) ;
        Gje(9)=Gje(9)*(ilo/ilB2) ;
      end  
      if AcxpC>.01 && AcxpCS1>.01 
        recalcActs=1;
        ilo=ilC1;if ilC1<mx, ilC1=ilC*linsig(ilC1+ilCmpndTau*(1-ilC1)^ilCmpndExp,0,ilC);else ilC1=1;end
        Gqe(10)=Gqe(10)*(ilo/ilC1) ;
        Gje(10)=Gje(10)*(ilo/ilC1) ;
      end
      if AcxpC>.01 && AcxpCS2>.01
        recalcActs=1;
        ilo=ilC2;if ilC2<mx, ilC2=ilC*linsig(ilC2+ilCmpndTau*(1-ilC2)^ilCmpndExp,0,ilC);else ilC2=1;end
        Gqe(11)=Gqe(11)*(ilo/ilC2) ;
        Gje(11)=Gje(11)*(ilo/ilC2) ;
      end
      il=[ilA ilB ilC 0 0 ilA1 ilA2 ilB1 ilB2 ilC1 ilC2 0 0 0];
      
    elseif Hx==1 && PFCs<1
      if AcxpA>.01  
        recalcActs=1;
        ilHxo=ilHxA;if ilHxA<mxHx,ilHxA=ilHxA+ilHxTau*(1-ilHxA)^ilHxExp;else ilHxA=1;end
        Gpe(29)=Gpe(29)*(ilHxo/ilHxA) ;
        Gie(29)=Gie(29)*(ilHxo/ilHxA) ;
      end  
      if AcxpB>.01  
        recalcActs=1;
        ilHxo=ilHxB;if ilHxB<mxHx,ilHxB=ilHxB+ilHxTau*(1-ilHxB)^ilHxExp;else ilHxB=1;end
        Gpe(30)=Gpe(30)*(ilHxo/ilHxB) ;
        Gie(30)=Gie(30)*(ilHxo/ilHxB) ;
      end
      if AcxpC>.01
        recalcActs=1;
        ilHxo=ilHxC;if ilHxC<mxHx,ilHxC=ilHxC+ilHxTau*(1-ilHxC)^ilHxExp;else ilHxC=1;end
        Gpe(31)=Gpe(31)*(ilHxo/ilHxC) ;
        Gie(31)=Gie(31)*(ilHxo/ilHxC) ;
      end 
      
      if AcxpA>.01 && AcxpCS1>.01 
        recalcActs=1;
        ilHxo=ilHxA1;if ilHxA1<mxHx, ilHxA1=ilHxA*linsig(ilHxA1+ ilHxCmpndTau*(1-ilHxA1)^ilHxCmpndExp,0,ilHxA);else ilHxA1=1;end  %Try this
        Gpe(34)=Gpe(34)*(ilHxo/ilHxA1) ;
        Gie(34)=Gie(34)*(ilHxo/ilHxA1) ;
      end     
      if AcxpA>.01 && AcxpCS2>.01
        recalcActs=1;
        ilHxo=ilHxA2;if ilHxA2<mxHx, ilHxA2=ilHxA*linsig(ilHxA2+ilHxCmpndTau*(1-ilHxA2)^ilHxCmpndExp,0,ilHxA);else ilHxA2=1;end  %Try this
        Gpe(35)=Gpe(35)*(ilHxo/ilHxA2) ;
        Gie(35)=Gie(35)*(ilHxo/ilHxA2) ;
      end  
      if AcxpB>.01 && AcxpCS1>.01 
        recalcActs=1;
        ilHxo=ilHxB1;if ilHxB1<mxHx, ilHxB1=ilHxB*linsig(ilHxB1+ilHxCmpndTau*(1-ilHxB1)^ilHxCmpndExp,0,ilHxB);else ilHxB1=1;end  %Try this
        Gpe(36)=Gpe(36)*(ilHxo/ilHxB1) ;
        Gie(36)=Gie(36)*(ilHxo/ilHxB1) ;
      end  
      if AcxpB>.01 && AcxpCS2>.01 
        recalcActs=1;
        ilHxo=ilHxB2;if ilHxB2<mxHx, ilHxB2=ilHxB*linsig(ilHxB2+ilHxCmpndTau*(1-ilHxB2)^ilHxCmpndExp,0,ilHxB);else ilHxB2=1;end  %Try this
        Gpe(37)=Gpe(37)*(ilHxo/ilHxB2) ;
        Gie(37)=Gie(37)*(ilHxo/ilHxB2) ;
      end  
      if AcxpC>.01 && AcxpCS1>.01 
        recalcActs=1;
        ilHxo=ilHxC1;if ilHxC1<mxHx, ilHxC1=ilHxC*linsig(ilHxC1+ilHxCmpndTau*(1-ilHxC1)^ilHxCmpndExp,0,ilHxC);else ilHxC1=1;end  %Try this
        Gpe(38)=Gpe(38)*(ilHxo/ilHxC1) ;
        Gie(38)=Gie(38)*(ilHxo/ilHxC1) ;
      end  
      if AcxpC>.01 && AcxpCS2>.01 
        recalcActs=1;
        ilHxo=ilHxC2;if ilHxC2<mxHx, ilHxC2=ilHxC*linsig(ilHxC2+ilHxCmpndTau*(1-ilHxC2)^ilHxCmpndExp,0,ilHxC);else ilHxC2=1;end  %Try this
        Gpse(39)=Gpe(39)*(ilHxo/ilHxC2) ;
        Gie(39)=Gie(39)*(ilHxo/ilHxC2) ;
      end        
      ilHx=[ilHxA ilHxB ilHxC 0 0 ilHxA1 ilHxA2 ilHxB1 ilHxB2 ilHxC1 ilHxC2 0 0 0];
    end  % End of "if Hx==0 && Hs==0".       
    %...............................end update of implicit learning
 
    %....................Step 14: UPDATE ELEGIBILITY.......................
    for k=1:14*3
      eligibleLA(k)=linsig(ActLA(k),thrshElig,1); 
    end  
    for k=1:14;
      eligibleBL(k)=linsig(ActBL(k),thrshElig,1);  
    end  
    if coefficientBL(15)>0, eligibleBL(15)=1;else eligibleBL(15)=0;end; %Prob never used.
    %...........................end update eligibility............    
      
    if mod(interval,50)==0  %For Progress graph during computations
      pause(.1) %If don't put a pause in here, graph doesn't get made until end.
      bars=[interval Npoints];
      barh(bars);
    end    
  end  %End of "for i= 1 : dur" (within-line for loop)
end   %End of  "for j=ContinueAt :Nsched" (lines of Exp table)

%.............Code for graphs made by function run_continue................
%This code does not affect simulations.

if interval>=Npoints
  hh=findobj('Tag','run_continue');
  set(hh,'BackgroundColor','white');        
end    

BW=1; %~Black and White. Makes non-color graphs for publication.    
clear x
x=(1:interval);  
close(7)
MyColorOrder=...
  [1 0 0;... %red
  0 1 0;...  %green  
  0 0 1;...   %blue
  0 0 0;...   %black
  0.8  0  1;...   %purple
  0 1 1;...     %cyan
  0.8 0.8 0.8;];  %gray

figure(4)
fig4on=1;
set(4,'Name','Ad-hoc plots')
set(gcf,'DefaultAxesColorOrder',MyColorOrder)
plot(x,Wdata(1:interval,1: 6)/Gleak,'LineWidth',1); 

figure(5)
if BW==1,set(gcf,'DefaultAxesColorOrder',[0 0 0;.749 0 .749;1 0 0]),end
fig5on=1;
posit=get(5,'Position');
set(5,'Name','Events','Position',[posit(1) posit(2) posit(3) 75])
%To plot contexts as diff colors all on one line must displace, limit axes &
%to 0<1:
yA=Eventdata(1:interval,2)-1; yB=Eventdata(1:interval,2)-2; yC=Eventdata(1:interval,2)-3;
y0=Eventdata(1:interval,2);
yCS1=Eventdata(1:interval,3)*.15+.2;
yCS2=Eventdata(1:interval,4)*.15+.4;
yUS=Eventdata(1:interval,5)*.15+.6;
plot(x,yA,'o','MarkerFaceColor','b','MarkerEdgeColor','b','MarkerSize',5)
hold;
plot(x,yB,'o','MarkerFaceColor','r','MarkerEdgeColor','r','MarkerSize',5);
plot(x,yC,'o','MarkerFaceColor','g','MarkerEdgeColor','g','MarkerSize',5);
plot(x,y0,'o',   'MarkerFaceColor','k','MarkerEdgeColor','k',   'MarkerSize',5);
plot(x,[yCS1 yCS2 yUS]);
%Plot verticle lines at pauses (interrupts):
interruptsX=[];
interruptsY=[];
for p=1:interval
  if Eventdata(p,6)==1
    interruptsX=[interruptsX p p];
    interruptsY=[interruptsY 0 1];  
  end %if  
end %for  
plot(interruptsX,interruptsY)
ylim([0 .9]);
xlim([0 Npoints]);

figure(2)
fig2on=1;
set(2,'Name','Vp (red) & Vq (blue)')
%plot(x,Net_Actdata(1:interval,1));
plot(x,Net_Actdata(1:interval,1),'r');
hold
plot(x,Net_Actdata(1:interval,3),'b');
xlim([0 Npoints]);

figure(3)
fig3on=1;
set(3,'Name','Ap(red),Aq(blue),Af(green)')
plot(x,Net_Actdata(1:interval,2),'r');
hold
plot(x,Net_Actdata(1:interval,4),'b');
plot(x,Afhist(1:interval,1),'g');
xlim([0 Npoints]);

figure(9)
fig9on=1;
set(9,'Name','Graph of 10*Efactor and Idivisor')
plot(x,10*netErecipI(1:interval,1),'r');
hold;
plot(x,netErecipI(1:interval,2),'b');
plot(x,10*netErecipI(1:interval,3),'g');
plot(x,netErecipI(1:interval,4),'k');
xlim([0 Npoints]);

figure(8)
if BW==0
  USpoint='r';
  USpointEdge='r';
  Fcolor='b';
elseif BW==1 
  USpoint='w';
  USpointEdge='r';
  Fcolor='k';
end  
fig8on=1;
set(8,'Name','Graph of Fsmrd & Fcs')
clear nonusacts
nonusacts= Fsmrd(1:interval) - 2*(1-Eventdata(1:interval,5)); %don't know why orientation of Fsmrd is OK
hold;
plot(x,Fsmrd(1:interval),Fcolor) 
plot(x,nonusacts(1:interval),'o','MarkerFaceColor',USpoint,'MarkerEdgeColor',USpointEdge,...
  'MarkerSize',3)     
ylim([0 1]);
xlim([0 Npoints]);

figure(hmain)
FigFrontposit =[232    46   560   420];
Fig5posit =[232    46   560    75];
hinfront=2;
figure(hinfront)
set(hinfront,'Position',FigFrontposit)
  
figure(5) 
set(5,'Position',Fig5posit)  %was 5
  
%Arrange figures for copying to powerpoint frame
figure(5)
set(5,'Position',[50 1 950 50])  %Bottom position
figure(8)
set(8,'Position',[50 50 950 125]) 
figure(9)
set(9,'Position',[50 175 950 125])
figure(2)
set(2,'Position',[50 300 950 125 ])
figure(3)
set(3,'Position',[50 425 950 125])
figure(4)
set(4,'Position',[50 550 950 125])  %Top position
%%%%%%%%%%%%%%%%%End of graphing code%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%Special events called from GUI%%%%%%%%%%%%%%%%

% --- Executes on button press in Hx.
function Hx_Callback(hObject, eventdata, handles)
global Hx rNhcA rNhcB rNhcC rNhcA1 rNhcA2 rNhcB1 rNhcB2 rNhcC1 rNhcC2 hHxButton
hHxButton=hObject;
set(hHxButton,'BackgroundColor','red')
rNhcA=0;rNhcB=0;rNhcC=0;rNhcA1=0;rNhcA2=0;rNhcB1=0;rNhcB2=0;rNhcC1=0;rNhcC2=0;
Lhc=0;
Hx=1;

% --- Executes on button press in BLs.
function BLs_Callback(hObject, eventdata, handles)
global BLs hBLsButton
hBLsButton=hObject;  
if BLs==0
  set(hBLsButton,'BackgroundColor','red')
  BLs=1;
elseif BLs==1 
  set(hBLsButton,'BackgroundColor','white')
  BLs=0;
end  

% --- Executes on button press in Hs.
function Hs_Callback(hObject, eventdata, handles)
global Hs hHsButton
hHsButton=hObject;  
if Hs==0
  set(hHsButton,'BackgroundColor','red')
  Hs=1;
elseif Hs==1 
  set(hHsButton,'BackgroundColor','white')
  Hs=0;
end

% --- Executes on button press in LAs.
function LAs_Callback(hObject, eventdata, handles)
global LAs hLAsButton
hLAsButton=hObject;
if LAs==0
  set(hLAsButton,'BackgroundColor','red')
  LAs=1;
elseif LAs==1 
  set(hLAsButton,'BackgroundColor','white')
  LAs=0;
end

% --- Executes on button press in PFCs.
function PFCs_Callback(hObject, eventdata, handles)
global PFCs hPFCsButton
hPFCsButton=hObject;
if PFCs==0
  set(hPFCsButton,'BackgroundColor','red')
  PFCs=1;
elseif PFCs==1 
  set(hPFCsButton,'BackgroundColor','white')
  PFCs=0;
end
  
% --- Executes on button press in CEMs.
function CEMs_Callback(hObject, eventdata, handles)
global CEMs hCEMsButton
hCEMsButton=hObject;
if CEMs==0
  set(hCEMsButton,'BackgroundColor','red')
  CEMs=1;
elseif CEMs==1 
  set(hCEMsButton,'BackgroundColor','white')
  CEMs=0;
end
  
% --- Executes on button press in consolidate.
function consolidate_Callback(hObject, eventdata, handles)
%The strategy here is strictly pragmatic.  See Supplement, Special Events for explanation.
%(FBK note: Extinction Journal May5, 2010
%discusses.)
global con  il ilHx Gpe  Gqe Gie  Gje consolidate Gi Gj
global E ViMax VjMax VpMax VqMax Gpq
global NP NI NT NH HabitBL HabitLA hConsolButton PFCs BLs LAs
hConsolButton=hObject;
set(hConsolButton,'BackgroundColor','red')
consolidate=1;
if PFCs==1, return,end
 
NLA=[NP NI NT];
NBL=[NH 1];
ilHx=il;
 
%Calculate Gpe's for cxt inputs of cntxts and conjunctions
phi=E/VpMax;
for j=1:14  %coefficientBL, etc have 15 elements, but we don't use last element here.
  if j==4||j==5, continue,end
  if il(j)>0 && BLs==0 && LAs==0
    nBL=NBL(j)*HabitBL(j)*il(j)^2;
    Aq=(E/VqMax)*nBL*Gqe(j)/(1+nBL*Gqe(j));
    nLA=NLA(14*2+j)*HabitLA(14*2+j)*ilHx(j)^2;
    Gpe(14*2+j)=(1/nLA)*Aq/(phi*(1+Gpq)-Aq*(1+Gpq*phi));
  end
end
 
%Calcuclate Gie's for cxt inputs cntxts and conjunctions
gam=E*Gi/ViMax;
for j=1:14  
  if j==4||j==5, continue,end
  if il(j)>0 && BLs==0 && LAs==0
    nBL=NBL(j)*HabitBL(j)*il(j)^2;
    nLA=NLA(14*2+j)*HabitLA(14*2+j)*ilHx(j)^2;
    Aj=(E/VjMax)*nBL*Gje(j)/(1+nBL*Gje(j)); 
    Aq=1/(1+Gj*Aj);
    Gie(14*2+j)=(1/nLA)*(1-Aq)*(1+Gpq)/(Aq*gam-(1-Aq)*(1+Gpq));
    Gje(j)=0;
  end
end
 
for j=1:14  
  if j==4||j==5, continue,end
  if il(j)>0 
    con(j)=1;
    il(j)=0;
  end  
end
%%%%%%%%%%%%%%%%%%%%%%%End of Special Events%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%Functions used frequently by above routines%%%%%%%%%%%%

%The "Bump" functions are used in calculating factors that determine weight
%changes as a function of Ca in inhibitory interneurons and of
%back-propagating spike amplitude in principal cells of amygdala. The
%linsig function is a linear ramp that starts rising from zero at "start" and
%that hits 1 and stays there at "stop". It is used extensively throughout
%as an activation function and for other purposes.

function y=BumpCa(x,ExponentThrsh,ExponentMxAt,phi)
th=ExponentThrsh;
ma=ExponentMxAt;
ph=phi;
y=1-exp(-1*ph*linsig(x,th,ma));

function y=BumpB(x,Thrsh, EndAt)
th=Thrsh;
ea=EndAt;
y=0;
if x>th && x<ea, y=1;end

function y=linsig(x, start, stop)
if x<start 
  y=0;
elseif x>=stop  
  y=1;
else
  y=(x-start)/(stop-start);
end 
                

%%%%%%%%%%%%%%%%%%%%% Some important functions called from GUI %%%%%%%%%%%%%%%%%%%%%%                

%---Executes on button press in Reset Exp. (i.e New exp on old frat)
function resetexp_Callback(hObject, eventdata, handles)
global KeepOldFraidy
KeepOldFraidy=1;
reset_Callback(hObject, eventdata, handles) %i.e. Calls "Reset Fraidy" and 
                                            %hence intializefraidy
                                            %but with KeepOldFraidy flag
                                            %set to 1

% --- Executes on button press in RESET. %i.e. "New Fraidy"
function reset_Callback(hObject, eventdata, handles)
global ContinueAt interrupt
global positionFig1
global fig2on fig3on fig4on fig5on fig8on fig9on %fig10on
if fig2on==1;close(2);fig2on=0;end
if fig3on==1;close(3);fig3on=0;end
if fig4on==1;close(4);fig4on=0;end
if fig5on==1;close(5);fig5on=0;end
if fig8on==1;close(8);fig8on=0;end
if fig9on==1;close(9);fig9on=0;end
ContinueAt=1;interrupt=0;
figure(1)
set(1,'Position',positionFig1)
initializefraidy

% --- Executes on button press in Quit.
function Quit_Callback(hObject, eventdata, handles)
close all hidden

%Used by several other routines.  
function initializefraidy
  
%Variables evaluated in W_INDEPENDENT EVALUATIONS routine:
global inptCS1 inptCS2 inptA inptB inptC
global AcxpCS1 AcxpCS2 AcxpA AcxpB AcxpC AcxpA1 AcxpA2 AcxpB1 AcxpB2 AcxpC1 AcxpC2 Scx Lcx
global rNcxpCS1 rNcxpCS2 rNcxpA rNcxpB rNcxpC rNcxpA1 rNcxpA2 rNcxpB1 rNcxpB2 rNcxpC1 rNcxpC2          
global AcxiA AcxiB AcxiC
global rNcxiA rNcxiB rNcxiC 
global  AcxtA AcxtB AcxtC AcxttA1 AcxtA2 AcxtB1 AcxtB2 AcxtC1 AcxtC2
global  rNcxtA rNcxtB rNcxtC rNcxtA1 rNcxtA2 rNcxtB1 rNcxtB2 rNcxtC1 rNcxtC2
global  AhcA AhcB AhcC AhcA1 AhcA2 AhcB1 AhcB2 AhcC1 AhcC2 Shc Lhc
global  rNhcA rNhcB rNhcC rNhcA1 rNhcA2 rNhcB1 rNhcB2 rNhcC1 rNhcC2

%Other variables of run_continue
global Gpe Gie Gqe Gje
global eligibleLA eligibleBL
global Fsmrd
global ContinueAt netErecipI
global interrupt Nrows
global Ap Ai Af Sam Lam rNp rNi  Ar Aus %rNr rNus Spagd Lpagd rNf Spagv Lpagv
global con il ilHx consolidate recalcActs
global ilA ilB ilC ilA1 ilA2 ilB1 ilB2 ilC1 ilC2 
global ilHxA ilHxB ilHxC ilHxA1 ilHxA2 ilHxB1 ilHxB2 ilHxC1 ilHxC2 
global conA conB conC conA1 conA2 conB1 conB2 conC1 conC2
global oldAq oldAu oldAx Ax oldRinput newRinput Au coefficientLA coefficientBL
global Wp Wq Ui Uj 
global usPrv AqPrv  %VpI ApI VqI AqI VpII ApII VqII AqII
global Fsmrd0 Aop AopPrv 
global Gp_cem

%Variables used for displays and graphing
global Wdata Eventdata Net_Actdata Afhist

%Init variables associated with in special treatments or GUI input
global hConsolButton KeepOldFraidy
global BLs Hx Hs LAs PFCs CEMs hBLsButton hHxButton hHsButton hLAsButton hCEMsButton hPFCsButton
global hilABCto1Button hilHxABCto1Button

%These initial items are done whenever initializefraidy is called, which is
%at the start of the program and whenever run/continue is begun.:
ContinueAt=1; %Set here and then again every time have New Fraidy
interrupt=0; %This is set when read line of Exp and zeroed at reset
%SelectedData=zeros(Nrows,5);% not used yet
Wdata=zeros(Nrows,6);
Eventdata=zeros(Nrows, 6 );
Net_Actdata=zeros(Nrows, 4 );
Afhist=zeros(Nrows,1);
Fsmrd=zeros(Nrows, 1  );
netErecipI = zeros(Nrows,4); 
Fsmrd0=zeros(Nrows,1);  
recalcActs=0;

%The following items are done whenever frat's memory needs to be erased
%(i.e NOT continuing a previous experiment)
if KeepOldFraidy==0
  LAs=0;CEMs=0; BLs=0;Hx=0;Hs=0; PFCs=0;
  consolidate=0;   
  if hConsolButton>0, set(hConsolButton,'BackgroundColor','white');end
  if hHxButton>0, set(hHxButton,'BackgroundColor','white');end
  if hHsButton>0, set(hHsButton,'BackgroundColor','white');end
  if hBLsButton>0, set(hBLsButton,'BackgroundColor','white');end
  if hCEMsButton>0, set(hCEMsButton,'BackgroundColor','white');end
  if hLAsButton>0, set(hLAsButton,'BackgroundColor','white');end
  if hPFCsButton>0, set(hPFCsButton,'BackgroundColor','white');end
  if hilABCto1Button>0, set(hilABCto1Button,'BackgroundColor','white');end    
  if hilHxABCto1Button>0, set(hilHxABCto1Button,'BackgroundColor','white');end
  Gp_cem=0;
  ilA=0;ilB=0;ilC=0;ilA1=0;ilA2=0;ilB1=0;ilB2=0;ilC1=0;ilC2=0;
  ilHxA=0;ilHxB=0;ilHxC=0;ilHxA1=0;ilHxA2=0;ilHxB1=0;ilHxB2=0;ilHxC1=0;ilHxC2=0;
  conA=0;conB=0;conC=0;conA1=0;conA2=0;conB1=0;conB2=0;conC1=0;conC2=0;
  con=[0 0 0 0 0 0 0 0 0 0 0 0 0 0];
  il= [0 0 0 0 0 0 0 0 0 0 0 0 0 0];  
  ilHx=il;  
  usPrv=0;AqPrv=0; Aop=0; 
  Gpe=zeros(1,14*3); Gie=zeros(1,14*3);
  Gqe= zeros(1,14+1); Gje=zeros(1,14+1);
  inptCS1=0; inptCS2=0; inptA=0; inptB=0; inptC=0;  
  AcxpCS1=0; AcxpCS2=0; AcxpA=0; AcxpB=0; AcxpC=0; AcxpA1=0; AcxpA2=0; AcxpB1=0; AcxpB2=0; AcxpC1=0; AcxpC2=0; Scx=0; Lcx=1;
  rNcxpCS1=1; rNcxpCS2=1; rNcxpA=1; rNcxpB=1; rNcxpC=1; rNcxpA1=1; rNcxpA2=1; rNcxpB1=1; rNcxpB2=1; rNcxpC1=1; rNcxpC2=1; 
  AcxiA=0; AcxiB=0; AcxiC=0;  
  rNcxiA=1; rNcxiB=1; rNcxiC=1;   
  AcxtA=0; AcxtB=0; AcxtC=0; AcxttA1=0; AcxtA2=0; AcxtB1=0; AcxtB2=0; AcxtC1=0; AcxtC2=0; 
  rNcxtA=1; rNcxtB=1; rNcxtC=1; rNcxtA1=1; rNcxtA2=1; rNcxtB1=1; rNcxtB2=1; rNcxtC1=1; rNcxtC2=1; 
  AhcA=0; AhcB=0; AhcC=0; AhcA1=0; AhcA2=0; AhcB1=0; AhcB2=0; AhcC1=0; AhcC2=0; Shc=0; Lhc=1;
  rNhcA=1; rNhcB=1; rNhcC=1; rNhcA1=1; rNhcA2=1; rNhcB1=1; rNhcB2=1; rNhcC1=1; rNhcC2=1; 
  Ap=0; Ai=0; Sam=0; Lam=1; rNp=1; rNi=1;  Ar=0; rNr=1;  Aus=0; rNus=1; Af=0; %Spagd=0; 
  eligibleLA=zeros(1,3*14);
  eligibleBL=zeros(1,14+1);
  oldAq=0; oldAu=0; oldAx=0; Ax=0; oldRinput=0; newRinput=0; Au=0; AopPrv=0;
  Wp=zeros(1,3*14);
  Ui=zeros(1,3*14);
  Wq=zeros(1,14+1);
  Uj=zeros(1,14+1); 
  coefficientLA=zeros(1,3*14); coefficientBL=zeros(1,14+1);
  Af=0;
end  
KeepOldFraidy=0;
%//////////////////////////////////////////////////////////////////////////
%            END OF CODE THAT IS PART OF THE MODEL PROPER
%//////////////////////////////////////////////////////////////////////////

%%%%%%%%%%%%%%%%%%%%%%%%%%Various Utilities%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% --- Executes on button press in replot (replot & animate code)
function replot_Callback(hObject, eventdata, handles)

global Eventdata 
global Fsmrd %Graphs already made so don't need most data arrays.
global replotFrom replotTo animateflag
global fratnormframes hmain fratshkd3frames

StimDur=1500;  %1000 points at a 10K sampling rate would be  0.1 sec per interval
AnimationInterval=.15;
ShortInterval=.02;
if animateflag==1 
  sampfreq=10000;
  xsound=[1:StimDur];
  CS1sound=.2*sin(2*xsound);
  CS2sound=.4*sin(.5*xsound);
  for j=1 : StimDur ;USsound(j)=2*(rand-.5);end
  j=1;
  %hiThresh=.9
  figure(1)
  hE1=annotation('ellipse',[.2 .8 .1 .15]); 
  hE2=annotation('ellipse',[.7 .2 .1 .15]);
  %set(hE, 'FaceColor', 'b');
  flopped=0;
  cycles=0; %REMOVE AFTER PROBLEM FIXED
  JitterArray=[-1 1 1 -1]
  cs1was=0;cs2was=0;
  for i=replotFrom : replotTo
    time1=clock;
    cs1=Eventdata(i,3);
    cs2=Eventdata(i,4);
    us=Eventdata(i,5);
    cntxt=Eventdata(i,2);
    if cs1==1 && us==0 
      %annotation('ellipse',[.5 .8 .1 .1]) %may screw up frame
      sound(CS1sound,sampfreq) 
    end
    if cs2==1 && us==0
      sound(CS2sound,sampfreq)
    end
    if us==1
      sound(USsound,sampfreq)
    end
    Thresh=rand;
    Fscore=Fsmrd(i);
%end frame selecting
    if cntxt==1
      cntxtColor='r';
    elseif cntxt==2  
      cntxtColor='g';
    elseif cntxt==3
      cntxtColor='b';
    else
      cntxtColor=[.8 .8 .8];
    end
  if cs1==1
    set(hE1,'FaceColor','y');
  else
    set(hE1,'FaceColor',cntxtColor);
  end  
  if cs2==1
    set(hE2,'FaceColor','y');
  else
    set(hE2,'FaceColor',cntxtColor);
  end  
    
  if us==0
    if Fscore>Thresh
      j=j;
    else
      j=j+1; if j>77, j=1; end
    end 
    set(1,'Color',cntxtColor)
    movie(1,fratnormframes(j))    
    time2=clock;
    elapsed=etime(time2,time1);
    while  elapsed <AnimationInterval 
      time2=clock;
      elapsed=etime(time2,time1);
    end 
  elseif us==1
    time2=clock;
    elapsed=0;
    k=0;
    while elapsed<AnimationInterval
      time3=clock;
      selapsed=0;
      %Determine and display next frame
      k=k+1;
      j=j+JitterArray(k);
      set(1,'Color',cntxtColor)
      movie(1,fratshkd3frames(j))
      while selapsed<ShortInterval
        time4=clock;
        selapsed=etime(time4,time3);
      end %while selapsed<ShortInterval  
      time2=clock
      elapsed=etime(time2,time1)
    end %while elapsed<AnimationInterval
    cs1was=cs1;cs2was=cs2;
  end  

  end  %for i=...?
  set(1,'Color',[.8 .8 .8]) 
end      % if animate==1??

figure(4)
axis([replotFrom   replotTo   -inf inf])

%Vp graph
figure(2)
axis([replotFrom replotTo -inf inf])

%Ap graph & Af graph
figure(3)
axis([replotFrom   replotTo   0   1])

figure(hmain)
%Fsmrd graph
figure(8)
xlim([replotFrom replotTo])

%Event graphs
figure(5)
xlim([replotFrom replotTo])

%netE and recip netI graphs
figure(9)
xlim([replotFrom replotTo])

%Vp graphs
figure(2)
xlim([replotFrom replotTo])

%Firing rate graph
figure(10)
xlim([replotFrom replotTo])

%THE FOLLOWING CALLBACK MAKES THE Exp ARRAY WHEN THE SHORT SCHEDULE DONE BUTTON IS CLICKED
function SSdonecb(hObject, eventdata)
%global NAcq1 CntxtAcq1 CSAcq1 NAcq2 CntxtAcq2 CSAcq2 NExt1 CntxtExt1 CSExt1
%global NExt2 CntxtExt2 CSExt2 NExt3 CntxtExt3 CSExt3 ITI CSdurAcq USdur CSdurExt hshort
global Exp SS SSdurations hshort SSrests 
Exp=[];

%Note: These variables have all been set to zero as default
%so that SS will have a full set of entries no matter what user does.
%ITIs are time between end of co-terminating CS and/or US and start of next
%CS or US, which ever comes first.
%To program a US without any CS, let choose CS=0 rather than 1 or 2; CS
%(not U&S)duration will be adde3d to ITI.
%To program an extinction period without any CSs or USs also let CS=0; CS duration
%will be added to ITI.
%
% SS=[1 NAcq1 CntxtAcq1 CSAcq1;...
%     2 NAcq2 CntxtAcq2 CSAcq2;...
%     3 NExt1 CntxtExt1 CSExt1;...
%     4 NExt2 CntxtExt2 CSExt2;...   
%     5 NExt3 CntxtExt3 CSExt3];
% SSdurations=  [ITI CSdurAcq USdur CSdurExt ACLdur ENDdur];

%SS (short sched) is an array whose rows are, respectively,   Aq1,Aq2,Aq3,Ext1,Ext2 (ie. 5 rows) 
%and whose  columns are,respectively,    N, cntxt, CS.  ITI, csdur, and usdur also are available.  
%Later I will want to add   context aclimitization periods at the start of the exp, but I will do
%that later.  The following is an algorithm for constructing an
%Experiment schedule from ShrtScd:
%Experiment entries:
%         1        2     3   4   5  6   7
%    entry_number,cntxt,cs1,cs2,us,pause,dur
k=0;
%US=[1 1 0 0 0];
ITI=SSdurations(1);
CSdurAcq=SSdurations(2);
USdur=SSdurations(3);
CSdurExt=SSdurations(4);
ACLdur=SSdurations(5);
ENDdur=SSdurations(6);
 Nper1=SS(1,2); Cntxtper1=SS(1,3); CSper1=SS(1,4);
 Nper2=SS(2,2); Cntxtper2=SS(2,3); CSper2=SS(2,4);
 Nper3=SS(3,2); Cntxtper3=SS(3,3); CSper3=SS(3,4);
 Nper4=SS(4,2); Cntxtper4=SS(4,3); CSper4=SS(4,4);   
 Nper5=SS(5,2); Cntxtper5=SS(5,3); CSper5=SS(5,4);
 for j=1:5
   if SS(j,4)<0,CSdur(j)=CSdurAcq; else CSdur(j)=CSdurExt;end
 end
 
%SumDurations=sum(SSdurations);  %old version
SumDurations=SSdurations(1)+SSdurations(2)+SSdurations(3)+SSdurations(4)+SSdurations(6);
%Construction of Exp array. There are 5 periods to the exp:
%Aq1,Aq2,Ext1,Ext2,Ext3.
%Each of these is composed of n repetitions of 3 lines, one each for:
%ITI, CS period prior to  US onset,CS+US period.

%NOTE FEB 8, 2009: I AM GOING TO ADD CONTEXT ACCLIMITIZATION PERIODS OF
%LENGTH ACLdur at the start of each of these periods

if SumDurations>0  %Make new Exp only if there are entries in the short schedule
for j=1 : 5
  cs1=0;cs2=0;n=0;cntxt=0;us=0;
  n=abs(SS(j,2));
  if n==0, continue, end
  if SS(j,2)<0  %Insert a pause line in Exp file
    Exp=[Exp; k+1 0 0 0 0 1 0];
    k = k+1; 
  end   
  cntxt=SS(j,3);
  if abs(SS(j,4))==3 %what is now j was 1, probably erroreously
    cs1=0;
    cs2=0;
  elseif abs(SS(j,4))==1
    cs1=1;
    cs2=0;
  elseif abs(SS(j,4))==2
    cs1=0;
    cs2=1;
  end
  if SS(j,4)<0, us=1;end
  clear Block
  Block =...
    [ cntxt 0 0 0 0 ITI;...
     cntxt cs1 cs2 0 0 CSdur(j)-USdur;...
     cntxt cs1 cs2 us 0 USdur];
  Block1 =...
    [ cntxt 0 0 0 0 ITI+ACLdur;...
     cntxt cs1 cs2 0 0 CSdur(j)-USdur;...
     cntxt cs1 cs2 us 0 USdur];
   
  clear Z
  Z=[] ;
  Z=[Z;Block1];
  for m=1:n-1 
  Z=[Z ;Block];
  end  
  ENDPERIOD=[cntxt 0 0 0 0 ENDdur];
  Z=[Z;ENDPERIOD];   
 %clear eventnos
  %eventnos=[k+1:k+3*n+2]  %+2 added on for ACL and ENDPERIOD lines.
     %Weird: if I place a space after the n in the above equation, the +2
     %is interpreted as an extra array element.
     
 %Add rests and pre-rest pauses as necessary:
  extralines=0;
  if j<5
    if SSrests(j)<0 
      Z=[Z;0 0 0 0 1 0];
      extralines=extralines+1;
    end
    %deal with interval numbers
    if abs(SSrests(j))>0 
      Z=[Z;0 0 0 0 0 abs(SSrests(j))];
      extralines=extralines+1;  
    end     
  end     
  
  clear eventnos
  %eventnos=[k+1:k+3*n+2+extralines];  %+2 added on for ACL and ENDPERIOD lines.
     %Weird: if I place a space after the n in the above equation, the +2
     %is interpreted as an extra array element.   
     
  eventnos=[k+1:k+3*n+1+extralines];  %revision for neg ACLs   
  k=length(eventnos);  % in prep for next iteration
  Z=[eventnos' Z];
  Exp=[Exp;Z]; 
end %of iteration j
end; %end of make Exp procedure
close(hshort)

% --- Executes on button press in MakeShortSchd.
function MakeShortSchd_Callback(hObject, eventdata, handles)
%Here we make all the little edit boxes and a button to say entry is
  %complete. The boxes are set up here and the callbacks labeled, but the
  %callbacks for reading the boxes are free-standing click-started
  %functions.  Actually constructing Exp is done by the callback called by
  %the Done button:
%global NAcq1 CntxtAcq1 CSAcq1 NAcq2 CntxtAcq2 CSAcq2 NExt1 CntxtExt1 CSExt1
%global NExt2 CntxtExt2 CSExt2 NExt3 CntxtExt3 CSExt3 ITI CSdurAcq USdur CSdurExt hshort
global SS SSdurations hshort SSrests

%  ITI CSdurAcq USdur CSdurExt

%NAcq1=0;CntxtAcq1=0; CSAcq1=0; NAcq2=0; CntxtAcq2=0; CSAcq2=0; NExt1=0; CntxtExt1=0; CSExt1=0;
%NExt2=0; CntxtExt2=0; CSExt2=0; NExt3=0; CntxtExt3=0; CSExt3=0; ITI=0; CSdurAcq=0; USdur=0; CSdurExt=0;
instruction=[...
  'Neg N or Rest =Init pause ';...
  'Contexts A, B, or C       ';...
  'CSs 0,1,or 2;             ';...
  ' + as suffx(no space) =US ';...
  'Durations in sec          ';...
  'ITI ~btw stimuli & bef 1st';...
  'US dur=0 for "none"       '];
  
top=500;  %was 370
hshort = figure;
set(hshort, 'Position',[200 100  545 600])
hinstruction = uicontrol('Style','text','HorizontalAlignment','left','Parent',hshort, 'String',instruction,'Position',[180  200 155 110]);
                                                                                    %      180 200 100 100

%%%%%%There follows pairs of labels and edit boxes for filling in%%%%%%%%%%
%%%%%%                     info for Short Sched                       %%%%%
hLabel1=uicontrol('Style','text','Parent',hshort, 'String','N Per1','Position',[20 top 60 20],...
  'BackgroundColor','g');
hBox1=uicontrol('Style','edit','Parent',hshort,'String',num2str(SS(1,2)),'Position',[90 top 60 20],'Callback',@box1cb);

hLabel2=uicontrol('Style','text','Parent',hshort, 'String','Cntxt Per1','Position',[20 top-20 60 20],...
  'BackgroundColor','g');
switch SS(1,3)
  case 0
    entry='0';
  case 1
    entry='A';
  case 2
    entry='B';
  case 3
    entry='C';
end
hBox2=uicontrol('Style','edit','Parent',hshort,'String',entry,'Position',[90 top-20 60 20],'Callback',@box2cb);

hLabel3=uicontrol('Style','text','Parent',hshort, 'String','CS/US Per1','Position',[20 top-40 60 20],...
  'BackgroundColor','g');

SSentry=SS(1,4);
if SSentry<0 
  entry=strcat(num2str(-1*SSentry),'+');
  if SSentry==-3, entry='0+';end;
else
  entry=num2str(SSentry);
end

hBox3=uicontrol('Style','edit','Parent',hshort,'String',entry,'Position',[90 top-40 60 20],'Callback',@box3cb);

%%% Insert-line for rest
hLabel22=uicontrol('Style','text','Parent',hshort, 'String','Rest1(days)','Position',[20 top-60 60 20]);
hBox22=uicontrol('Style','edit','Parent',hshort,'String',num2str(SSrests(1)),'Position',[90 top-60 60 20],'Callback',@box22cb);


hLabel4=uicontrol('Style','text','Parent',hshort, 'String','N Per2','Position',[20 top-80 60 20],...
  'BackgroundColor','g');
hBox4=uicontrol('Style','edit','Parent',hshort,'String',num2str(SS(2,2)),'Position',[90 top-80 60 20],'Callback',@box4cb);

hLabel5=uicontrol('Style','text','Parent',hshort, 'String','Cntxt Per2','Position',[20 top-100 60 20],...
  'BackgroundColor','g');
switch SS(2,3)
  case 0
    entry='0';
  case 1
    entry='A';
  case 2
    entry='B';
  case 3
    entry='C';
end
hBox5=uicontrol('Style','edit','Parent',hshort,'String',entry,'Position',[90 top-100 60 20],'Callback',@box5cb);

hLabel6=uicontrol('Style','text','Parent',hshort, 'String','CS/US Per2','Position',[20 top-120 60 20],...
  'BackgroundColor','g');
%NEW STUFF--for transforming info in arrays into box string
SSentry=SS(2,4);
if SSentry<0 
  entry=strcat(num2str(-1*SSentry),'+');
  if SSentry==-3, entry='0+';end;
else
  entry=num2str(SSentry);
end
%END NEW STUFF
hBox6=uicontrol('Style','edit','Parent',hshort,'String',entry,'Position',[90 top-120 60 20],'Callback',@box6cb);

%%% Addition of lines for rests between Periods
hLabel23=uicontrol('Style','text','Parent',hshort, 'String','Rest2(days)','Position',[20 top-140 60 20]);
hBox23=uicontrol('Style','edit','Parent',hshort,'String',num2str(SSrests(2)),'Position',[90 top-140 60 20],'Callback',@box23cb);

hLabel7=uicontrol('Style','text','Parent',hshort, 'String','N Per3','Position',[20 top-160 60 20],...
  'BackgroundColor','g');
hBox7=uicontrol('Style','edit','Parent',hshort,'String',num2str(SS(3,2)),'Position',[90 top-160 60 20],'Callback',@box7cb);

hLabel8=uicontrol('Style','text','Parent',hshort, 'String','Cntxt Per3','Position',[20 top-180 60 20],...
  'BackgroundColor','g');
switch SS(3,3)
  case 0
    entry='0';
  case 1
    entry='A';
  case 2
    entry='B';
  case 3
    entry='C';
end
hBox8=uicontrol('Style','edit','Parent',hshort,'String',entry,'Position',[90 top-180 60 20],'Callback',@box8cb);

hLabel9=uicontrol('Style','text','Parent',hshort, 'String','CS/US Per3','Position',[20 top-200 60 20],...
  'BackgroundColor','g');
SSentry=SS(3,4);
if SSentry<0 
  entry=strcat(num2str(-1*SSentry),'+');
  if SSentry==-3, entry='0+';end;
else
  entry=num2str(SSentry);
end
hBox9=uicontrol('Style','edit','Parent',hshort,'String',entry,'Position',[90 top-200 60 20],'Callback',@box9cb);

%%% Insert line for rest
hLabel24=uicontrol('Style','text','Parent',hshort, 'String','Rest3(days)','Position',[20 top-220 60 20]);
hBox24=uicontrol('Style','edit','Parent',hshort,'String',num2str(SSrests(3)),'Position',[90 top-220 60 20],'Callback',@box24cb);

hLabel10=uicontrol('Style','text','Parent',hshort, 'String','N Per4','Position',[20 top-240 60 20],...
  'BackgroundColor','g');
hBox10=uicontrol('Style','edit','Parent',hshort,'String',num2str(SS(4,2)),'Position',[90 top-240 60 20],'Callback',@box10cb);

hLabel11=uicontrol('Style','text','Parent',hshort, 'String','Cntxt Per4','Position',[20 top-260 60 20],...
  'BackgroundColor','g');
switch SS(4,3)
  case 0
    entry='0';
  case 1
    entry='A';
  case 2
    entry='B';
  case 3
    entry='C';
end
hBox11=uicontrol('Style','edit','Parent',hshort,'String',entry,'Position',[90 top-260 60 20],'Callback',@box11cb);

hLabel12=uicontrol('Style','text','Parent',hshort, 'String','CS/US Per4','Position',[20 top-280 60 20],...
  'BackgroundColor','g');
SSentry=SS(4,4);
if SSentry<0 
  entry=strcat(num2str(-1*SSentry),'+');
  if SSentry==-3, entry='0+';end;
else
  entry=num2str(SSentry);
end

hBox12=uicontrol('Style','edit','Parent',hshort,'String',entry,'Position',[90 top-280 60 20],'Callback',@box12cb);

%%% Insert line for rest
hLabel25=uicontrol('Style','text','Parent',hshort, 'String','Rest4(days)','Position',[20 top-300 60 20]);
hBox25=uicontrol('Style','edit','Parent',hshort,'String',num2str(SSrests(4)),'Position',[90 top-300 60 20],'Callback',@box25cb);

hLabel13=uicontrol('Style','text','Parent',hshort,'String','N Per5','Position',[20 top-320 60 20,],...
  'BackgroundColor','g');
hBox13=uicontrol('Style','edit','Parent',hshort,'String',num2str(SS(5,2)),'Position',[90 top-320 60 20],'Callback',@box13cb);

hLabel14=uicontrol('Style','text','Parent',hshort, 'String','Cntxt Per5','Position',[20 top-340 60 20],...
  'BackgroundColor','g');
switch SS(5,3)
  case 0
    entry='0';
  case 1
    entry='A';
  case 2
    entry='B';
  case 3
    entry='C';
end
hBox14=uicontrol('Style','edit','Parent',hshort,'String',entry,'Position',[90 top-340 60 20],'Callback',@box14cb);

hLabel15=uicontrol('Style','text','Parent',hshort, 'String','CS/US Per5','Position',[20 top-360 60 20],...
  'BackgroundColor','g');
SSentry=SS(5,4);
if SSentry<0 
  entry=strcat(num2str(-1*SSentry),'+');
  if SSentry==-3, entry='0+';end;
else
  entry=num2str(SSentry);
end
hBox15=uicontrol('Style','edit','Parent',hshort,'String',entry,'Position',[90 top-360 60 20],'Callback',@box15cb);

hLabel16=uicontrol('Style','text','Parent',hshort, 'String','ITI','Position',[20 top-380 60 20],...
  'BackgroundColor','cyan');
hBox16=uicontrol('Style','edit','Parent',hshort,'String',num2str(SSdurations(1)),'Position',[90 top-380  60 20],'Callback',@box16cb);

hLabel17=uicontrol('Style','text','Parent',hshort,'String','CSdurAcq','Position',[20 top-400 60 20,],...
  'BackgroundColor','cyan');
hBox17=uicontrol('Style','edit','Parent',hshort,'String',num2str(SSdurations(2)),'Position',[90 top-400 60 20],'Callback',@box17cb);

hLabel18=uicontrol('Style','text','Parent',hshort, 'String','USdur','Position',[20 top-420 60 20],...
  'BackgroundColor','cyan');
hBox18=uicontrol('Style','edit','Parent',hshort,'String',num2str(SSdurations(3)),'Position',[90 top-420 60 20],'Callback',@box18cb);

hLabel19=uicontrol('Style','text','Parent',hshort, 'String','CSdurExt','Position',[20 top-440 60 20],...
  'BackgroundColor','cyan');
hBox19=uicontrol('Style','edit','Parent',hshort,'String',num2str(SSdurations(4)),'Position',[90 top-440 60 20],'Callback',@box19cb);


%Addition of lines for entering ACLdur and ENDdur
hLabel20=uicontrol('Style','text','Parent',hshort, 'String','ACLdur','Position',[20 top-460 60 20],...
  'BackgroundColor','cyan');
hBox20=uicontrol('Style','edit','Parent',hshort,'String',num2str(SSdurations(5)),'Position',[90 top-460 60 20],'Callback',@box20cb);

hLabel21=uicontrol('Style','text','Parent',hshort, 'String','ENDdur','Position',[20 top-480 60 20],...
  'BackgroundColor','cyan');
hBox21=uicontrol('Style','edit','Parent',hshort,'String',num2str(SSdurations(6)),'Position',[90 top-480 60 20],'Callback',@box21cb);

hSSdone=uicontrol('String','Done','Parent',hshort,'Position',[180 100 150 40],'Callback',@SSdonecb);

%For reference:
% SS=[1 0 0 0;     1 2 3 4
%     2 0 0 0;     5 6 7 8
%     3 0 0 0;    9 10 11 12 
%     4 0 0 0;   13 14 15 16
%     5 0 0 0];  17 18 19 20
                 
% SSdurations     1 2 3 4 5
% SSrests         1 2 3 4

%%%%%%%%%%CALLBACKS FOR READING AND ITERPRETING %%%%%%%%%%%%%%%
%%%%%%%%%%PROGRAMMING BOXES WHEN THEY ARE FILLED%%%%%%%%%%%%%
function box1cb(hObject, eventdata)  %Read NPer1
  global SS; SS(1,2)=str2double(get(hObject,'string'));
function box2cb(hObject, eventdata)  %Read CntxtPer1
  global SS; 
  value=(get(hObject,'string'));
  if value=='A'
    SS(1,3)=1;
  elseif value=='B'
    SS(1,3)=2;
  elseif value=='C'
    SS(1,3)=3;
  elseif value=='0'
    SS(1,3)=0;
  end 
function box3cb(hObject, eventdata) %Read CSPer1
  Str=get(hObject,'string');
  Str=strtrim(Str);
  if Str(end)=='+'
      L=length(Str);
      myCS=-1*str2double(Str(1:L-1));
      %if Str=='0+', myCS=-3;end;
      if cmpstr(Str,'0+')==1, myCS=-3;end
  else
      myCS=str2double(Str);
  end
  global SS; SS(1,4)=myCS; %Only this line is diff for each entry

  function box4cb(hObject, eventdata) %Read NPer2
  global SS; SS(2,2)= str2double(get(hObject,'string'))  ;
  
function box5cb(hObject, eventdata)  %Read CntxtPer2
  global SS; 
  value=(get(hObject,'string'));
  if value=='A'
    SS(2,3)=1;
  elseif value=='B'
    SS(2,3)=2;
  elseif value=='C'
    SS(2,3)=3;
  elseif value=='0'
    SS(2,3)=0;
  end   
function box6cb(hObject, eventdata)  %Read CSPer2
  Str=get(hObject,'string');
  Str=strtrim(Str);
  if Str(end)=='+'
      L=length(Str);
      myCS=-1*str2double(Str(1:L-1));
      %if Str=='0+', myCS=-3;end;
      if cmpstr(Str,'0+')==1, myCS=-3;end
  else
      myCS=str2double(Str);
  end
  global SS; SS(2,4)=myCS; %Only this line is diff for each entry

function box7cb(hObject, eventdata)  %Read NPer3
  global SS; SS(3,2)=str2double(get(hObject,'string'))  ;
function box8cb(hObject, eventdata)  %Read CntxtPer3
  global SS
  value=(get(hObject,'string'));
  if value=='A'
    SS(3,3)=1;
  elseif value=='B'
    SS(3,3)=2;
  elseif value=='C'
    SS(3,3)=3;
  elseif value=='0'
    SS(3,3)=0;
  end
function box9cb(hObject, eventdata)  %Read CSPer3
  Str=get(hObject,'string');
  Str=strtrim(Str);
  if Str(end)=='+'
      L=length(Str);
      myCS=-1*str2double(Str(1:L-1));
      %if Str=='0+', myCS=-3;end;
      if cmpstr(Str,'0+')==1, myCS=-3;end
  else
      myCS=str2double(Str);
  end
  global SS; SS(3,4)=myCS; %Only this line is diff for each entry

function box10cb(hObject, eventdata)  %Read NPer4
  global SS; SS(4,2)=str2double(get(hObject,'string'))  ;
function box11cb(hObject, eventdata)  %Read CntxtPer4
  global SS
  value=(get(hObject,'string'));
  if value=='A'
    SS(4,3)=1;
  elseif value=='B'
    SS(4,3)=2;
  elseif value=='C'
    SS(4,3)=3;
  elseif value=='0'
    SS(4,3)=0;
  end
function box12cb(hObject, eventdata) %Read CSPer4
  Str=get(hObject,'string');
  Str=strtrim(Str);
  if Str(end)=='+'
      L=length(Str);
      myCS=-1*str2double(Str(1:L-1));
      %if Str=='0+', myCS=-3;end;
      if cmpstr(Str,'0+')==1, myCS=-3;end
  else
      myCS=str2double(Str);
  end
  global SS; SS(4,4)=myCS; %Only this line is diff for each entry

function box13cb(hObject, eventdata)  %Read NPer5
  global SS; SS(5,2)=str2double(get(hObject,'string'))  ;
function box14cb(hObject, eventdata) %Read CntxtPer5
  global SS;
  value=(get(hObject,'string'));
  if value=='A'
    SS(5,3)=1;
  elseif value=='B'
    SS(5,3)=2;
  elseif value=='C'
    SS(5,3)=3;
  elseif value=='0'
    SS(5,3)=0;
  end

  function box15cb(hObject, eventdata)  %Read CSPer5
  Str=get(hObject,'string');
  Str=strtrim(Str);
  if Str(end)=='+'
      L=length(Str);
      myCS=-1*str2double(Str(1:L-1));
      %if Str=='0+', myCS=-3;end;
      if cmpstr(Str,'0+')==1, myCS=-3;end
  else
      myCS=str2double(Str);
  end
  global SS; SS(5,4)=myCS; %Only this line is diff for each entry

function box16cb(hObject, eventdata)  %Read ITI
  global SSdurations; SSdurations(1)= str2double(get(hObject,'string')); 
function box17cb(hObject, eventdata)  %Read CSdurAcq
  global SSdurations; SSdurations(2)= str2double(get(hObject,'string'));
function box18cb(hObject, eventdata)  %Read USdur
  global SSdurations; SSdurations(3)= str2double(get(hObject,'string'));
function box19cb(hObject, eventdata)  %Read CSdurExt
  global SSdurations; SSdurations(4)= str2double(get(hObject,'string'));
function box20cb(hObject, eventdata)  %Read ACLdur (Acclimitization in front of 1st ITI
  global SSdurations; SSdurations(5)= str2double(get(hObject,'string'));
function box21cb(hObject, eventdata)  %Read ENDdur 
  global SSdurations; SSdurations(6)= str2double(get(hObject,'string'));
  
%Rest 1  
function box22cb(hObject, eventdata)
  global SSrests; SSrests(1)= str2double(get(hObject,'string'));
%Rest 2
function box23cb(hObject, eventdata)
  global SSrests; SSrests(2)= str2double(get(hObject,'string'));
%Rest 3
function box24cb(hObject, eventdata)
  global SSrests; SSrests(3)= str2double(get(hObject,'string'));
%Rest 4
function box25cb(hObject, eventdata)
  global SSrests; SSrests(4)= str2double(get(hObject,'string'));
  
%%%End of code for reading and interpreting Short Schedule boxes.%%%%

% --- Executes on button press in MakeLongSchd.
function MakeLongSchd_Callback(hObject, eventdata, handles)
global Exp SchedFname hSchedFnameBox
Exp=[];
%LOAD EXTERNAL FILE. 
%Note: This routine sets the matrix Exp equal to the array in a file with
%a .txt extension that has been prepared by entering the array elements
%into an excel spread sheet and saving as a text file located (presently)
%in the current working directory (but a different path can be specified 
%in the next line. At present it gets restored in binary file along with 
%the SS array if one hits Save.
FullFname=strcat(SchedFname,'.txt');
Exp=load(FullFname);
pause(.25)
  set(hSchedFnameBox,'BackgroundColor','white')
  set(hSchedFnameBox,'BackgroundColor','red')
  pause(.25)
  set(hSchedFnameBox,'BackgroundColor','white')

% --- Executes on button press in KeepSchd.
function KeepSchd_Callback(hObject, eventdata, handles)
  global Exp SchedFname hSchedFnameBox SS SSdurations SSrests
  pause(.25)
  set(hSchedFnameBox,'BackgroundColor','white')
  set(hSchedFnameBox,'BackgroundColor','red')
  pause(.25)
  set(hSchedFnameBox,'BackgroundColor','white')
 % 'Here are Frank & SS in Keep'
 % Frank
 % SS
  Experiment=Exp;  %This is to avoid confusing local and global variables, etc.
  save(SchedFname, 'Experiment','SS','SSdurations','SSrests') %would other format have assumed .mat?

% --- Executes on button press in GetSchd.
function GetSchd_Callback(hObject, eventdata, handles)
  global Exp SchedFname hSchedFnameBox SS SSdurations SSrests
  
  load(SchedFname) %.mat is assumed by this format. 
                   %"load SchedFname" looks for a file with the name "SchedFname".                                        .
   
  Exp=Experiment;  %Experiment is whatthe saved Exp files are called in .mat files
  set(hSchedFnameBox,'BackgroundColor','red')
  pause(.25)
  set(hSchedFnameBox,'BackgroundColor','white')
   % GetButtonBlinksRed

%Probably can discard this function  
function GetButtonBlinksRed
global hSchedFnameBox
set(hSchedFnameBox,'BackgroundColor','red')
%pause(.25)
%set(hSchedFnameBox,'BackgroundColor','white')    

% --- Executes on button press in animate.
function animate_Callback(hObject, eventdata, handles)
global animateflag
animateflag = get(hObject,'Value');

% --- Executes on button press in goKeyboard. 
function goKeyboard_Callback(hObject, eventdata, handles)
global alphaLA betaLA etaLA zetaLA alphaBL betaBL etaBL zetaBL Gus
global Gi Gj Gr Gpq VpMax VqMaxCa VqMax ViMax VjMax
global opThrsh pi 
global startLTPfactorLA startLTPfactorBL  a b c d morphine oldAu oldAq 
global psec ArMultLA ArMultBL maxsec Gpe Gqe Gie Gje ilIncr ilHxIncr  ilIncrCmpnd ilHxIncrCmpnd thrshElig naloxone
global PFCx  BLs
global Grp Grq
global ilTau ilExp ilCmpndTau ilCmpndExp
global ilHxTau ilHxExp ilHxCmpndTau ilHxCmpndExp 
global mx mxHx
global NP NH NI NT NI NH 
global NPcntxt NPcs NPcntxt_cs  NPcntxt_0
global NHcntxt NHcs NHcntxt_cs NHcntxt_0 
global NIcntxt NIcs NIcntxt_cs NIcntxt_0 
global NTcntxt NTcntxt_cs NTcntxt_0 Np
global Gp_cem BLs Gp_cemON PAGptx PAGmuscimol
global thrshRp thrshRi thrshRq thrshRj thrshXp endXp thrshXq endXq thrshXi phiXi thrshXj phiXj

disp('///////////////////////////////////////////////////////////////////////////////')
disp('alphaLA         betaLA        etaLA          zetaLA')
disp([alphaLA betaLA etaLA zetaLA])
disp('alphaBL         betaBL        etaBL          zetaBL')
disp([alphaBL         betaBL        etaBL          zetaBL])
disp('Gi           Gj           Gr         Gpq   Gp_cemON')
disp([Gi           Gj           Gr             Gpq  Gp_cemON])
disp('VpMax          VqMaxCa           VqMax    NTcntxt_cs   ')
disp([VpMax          VqMaxCa           VqMax     NTcntxt_cs])
disp('ViMax          VjMax             psec      maxsec')
disp([ViMax           VjMax  psec     maxsec])
disp('opThrsh       pi          startLTPfactorLA      startLTPfactorBL')
disp([opThrsh       pi          startLTPfactorLA      startLTPfactorBL])
disp('NPcntxt                NTcntxt        NHcntxt            NHcntxt_cs ')
disp([NPcntxt                NTcntxt        NHcntxt            NHcntxt_cs ])
disp('a           b             c            d')
disp([a           b             c           d])
disp('ilTau  ilExp  ilCmpndTau  ilCmpndExp ilHxTau ilHxExp ilHxCmpndTau ilHxCmpndExp')
disp([ilTau  ilExp  ilCmpndTau  ilCmpndExp ilHxTau ilHxExp ilHxCmpndTau ilHxCmpndExp ])
disp('thrshElig     NPcntxt_cs   Grp  Grq')
disp([thrshElig   NPcntxt_cs Grp Grq])
disp('mx   mxHx ArMultLA ArMultBL')
disp([mx mxHx ArMultLA ArMultBL])
disp ('PAGptx  PAGmuscimol')
disp ([PAGptx   PAGmuscimol])

disp('///////////////////////////////////////////////////////////////////////////////')
keyboard

  NP=[NPcntxt NPcntxt NPcntxt NPcs NPcs NPcntxt_cs NPcntxt_cs NPcntxt_cs NPcntxt_cs NPcntxt_cs NPcntxt_cs NPcntxt_0 NPcntxt_0 NPcntxt_0];
  NH=[NHcntxt NHcntxt NHcntxt NHcs NHcs NHcntxt_cs NHcntxt_cs NHcntxt_cs NHcntxt_cs NHcntxt_cs NHcntxt_cs NHcntxt_0 NHcntxt_0 NHcntxt_0];
  NI=[NIcntxt NIcntxt NIcntxt NIcs NIcs NIcntxt_cs NIcntxt_cs NIcntxt_cs NIcntxt_cs NIcntxt_cs NIcntxt_cs NIcntxt_0 NIcntxt_0 NIcntxt_0];
  NT=[NTcntxt NTcntxt NTcntxt 0 0 ...
  NTcntxt_cs NTcntxt_cs NTcntxt_cs NTcntxt_cs NTcntxt_cs NTcntxt_cs NTcntxt_0 NTcntxt_0 NTcntxt_0];
  NI=NI;
  NH=NH;

  
function ReplotFrom_Callback(hObject, eventdata, handles)
%  str2double(get(hObject,'String')) returns contents of ReplotFrom as a double
clear global replotFrom
global replotFrom
replotFrom=str2double(get(hObject,'String'));

function Replotto_Callback(hObject, eventdata, handles)
% str2double(get(hObject,'String')) returns contents of Replotto as a double
clear global replotTo
global replotTo
replotTo=str2double(get(hObject,'String'));

function ReplotApYmax_Callback(hObject, eventdata, handles)
% Hints: get(hObject,'String') returns contents of ReplotApYmax as text
%        str2double(get(hObject,'String')) returns contents of ReplotApYmax as a double

function SchedFname_Callback(hObject, eventdata, handles)
global SchedFname hSchedFnameBox
SchedFname=get(hObject,'String');
hSchedFnameBox=hObject;

function shockIntensity_Callback(hObject, eventdata, handles)
global Ishk
Ishk= str2double(get(hObject,'String'));

%In order to pre-familiarize FRAT to contexts A, B, and C without writing 
%this explicitly into schedules for experiments, the following GUI-called
%functions are available. The first sets a flag that causes all new calle
%of Run/Continue to set il values (but not ilHx values) to unity.  The
%other two explicitly set set either il or ilHx values to one.  All il
%values are reset to zero when New Fraidy is requested.

%Sets flag so ilA,B,&C set to 1 at start of each new call to Run/Continue
%routine. il ABC reset to zero when New Fraidy (Reset) called.
function prfmcntxts_Callback(hObject, eventdata, handles)
global FamAllCntxts
FamAllCntxts=get(hObject,'Value');

% --- Executes on button press in ilABCto1. Sets ilA,B,C to 1 for current frat only.
function ilABCto1_Callback(hObject, eventdata, handles)
global il ilA ilB ilC hilABCto1Button
hilABCto1Button=hObject;
set(hilABCto1Button,'BackgroundColor','red')
ilA=1;il(1)=1;
ilB=1;il(2)=1;
ilC=1;il(3)=1;

% --- Executes on button press in ilHxABCto1. Sets ilHxA,B,C to 1 for current frat only.
function ilHxABCto1_Callback(hObject, eventdata, handles)
global ilHx ilHxA ilHxB ilHxC hilHxABCto1Button
hilHxABCto1Button=hObject;
set(hilHxABCto1Button,'BackgroundColor','red')
ilHxA=1;ilHx(1)=1;
ilHxB=1;ilHx(2)=1;
ilHxC=1;ilHx(3)=1;

function pcentHs_Callback(hObject, eventdata, handles)
global pcentHs
pcentHs=str2double(get(hObject,'String'));

%/////////////////////////////////////////////////////////////////////////
%     Create function entries and possibly some obsolete stuff
%///////////////////////////////////////////////////////////////////////

% --- Executes during object creation, after setting all properties.
function pcentHs_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes during object creation, after setting all properties.
function Type_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes during object creation, after setting all properties.
function edit13_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes during object creation, after setting all properties.
function edit14_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function edit13_Callback(hObject, eventdata, handles)

function edit14_Callback(hObject, eventdata, handles)

% --- Executes during object creation, after setting all properties.
function shockIntensity_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes during object creation, after setting all properties.
function Replotto_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function SchedFname_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end  

% --- Executes during object creation, after setting all properties.
function ReplotFrom_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function ReplotApYmax_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end