changeset 38:c2204b18f4a2 tip

End nov big change
author Ray Meddis <rmeddis@essex.ac.uk>
date Mon, 28 Nov 2011 13:34:28 +0000
parents 771a643d5c29
children
files Documentation Manuals Presentations etc/Hearing dummy Talk.ppt Documentation Manuals Presentations etc/Lecluyse, Meddis (2009).pdf Documentation Manuals Presentations etc/MAP 1_14 Model description.doc Documentation Manuals Presentations etc/MAP1_14 quick reference.doc Documentation Manuals Presentations etc/Meddis and Lopez-Poveda (Springer).pdf Documentation Manuals Presentations etc/MultiThreshold manual.doc Documentation Manuals Presentations etc/Surrey Meddis 2010.ppt Documentation Manuals Presentations etc/forward masking figures.ppt Documentation Manuals Presentations etc/multiThreshold quickStart instructions.doc Documentation Manuals Presentations etc/old model talk 2010.ppt Documentation/MAP 1_14 Model description.docx Documentation/MAP1_14 quick reference .doc Documentation/MultiThreshold ManualCT.doc Documentation/MultiThreshold manual.doc Documentation/multiThreshold quickStart instructions.doc Documentation/multiThreshold quickStartCT.doc MAP/MAP 1_14 Model description.docx - Shortcut.lnk MAP/MAP1_14.m MAP/MAPrunner.m MAP/documentation/Hearing dummy Talk.ppt MAP/documentation/MAP1_14 quick reference.doc MAP/documentation/Model description.doc MAP/documentation/MultiThreshold manual.doc MAP/documentation/Surrey Meddis 2010.ppt MAP/documentation/The multiThreshold guide to getting started.doc MAP/documentation/old model talk 2010.ppt MAP/filteredSACF.m MAP/old MAP files/MAP1_14AP.m MAP/old MAP files/MAP1_14parallel.m MAP/old MAP files/MAPrunner.m ReadMe MAP14.doc ReadMe MAP1_14.doc multiThreshold 1.46/OHIOtest.m multiThreshold 1.46/hs_err_pid8684.log multiThreshold 1.46/old files/MTprofile.m multiThreshold 1.46/old files/profile.mat multiThreshold 1.46/paradigms/paradigmBase.m multiThreshold 1.46/paradigms/paradigm_OHIOabs.m multiThreshold 1.46/paradigms/paradigm_OHIOrand.m multiThreshold 1.46/paradigms/paradigm_OHIOspect.m multiThreshold 1.46/paradigms/paradigm_OHIOspectemp.m multiThreshold 1.46/paradigms/paradigm_OHIOtemp.m multiThreshold 1.46/savedData/Meddis/Meddis 26-Sep-2011 08_46_01.mat multiThreshold 1.46/savedData/Normal/Normal 04-Oct-2011 15_23_57.mat multiThreshold 1.46/savedData/statsModel/statsModel 26-Sep-2011 08_44_18.mat multiThreshold 1.46/savedData/statsModel/statsModel 26-Sep-2011 08_44_28.mat multiThreshold 1.46/ten.wav multithreshold 1.46/MTprofile.m multithreshold 1.46/documentation/MultiThreshold manual.doc multithreshold 1.46/documentation/The multiThreshold guide to getting started.doc multithreshold 1.46/forward masking figures.ppt multithreshold 1.46/multiThreshold.fig multithreshold 1.46/multiThreshold.m multithreshold 1.46/nextStimulus.m multithreshold 1.46/old files/MAPmodel.m multithreshold 1.46/paradigms/paradigm_IFMC.m multithreshold 1.46/paradigms/paradigm_TENtest.m multithreshold 1.46/paradigms/paradigm_TMC.m multithreshold 1.46/paradigms/paradigm_absThreshold.m multithreshold 1.46/paradigms/paradigm_absThreshold_16.m multithreshold 1.46/paradigms/paradigm_discomfort.m multithreshold 1.46/paradigms/paradigm_forwardMasking.m multithreshold 1.46/paradigms/paradigm_overShoot.m multithreshold 1.46/paradigms/paradigm_profile.m multithreshold 1.46/paradigms/paradigm_psychometric.m multithreshold 1.46/paradigms/paradigm_threshold_duration.m multithreshold 1.46/paradigms/paradigm_training.m multithreshold 1.46/paradigms/paradigm_trainingIFMC.m multithreshold 1.46/plotProfile.m multithreshold 1.46/printReport.m multithreshold 1.46/profile.mat multithreshold 1.46/savedData/mostRecentResults.mat multithreshold 1.46/subjGUI_MT.m parameterStore/MAPparamsNormal.m parameterStore/MAPparamsOHCloss.m parameterStore/MAPparamsPL.m profiles/MTprofile11_5hr05_Oct_2011.m profiles/MTprofile12_26hr05_Oct_2011.m profiles/MTprofile12_41hr04_Oct_2011.m profiles/MTprofile13_25hr04_Oct_2011.m profiles/MTprofile14_39hr04_Oct_2011.m profiles/MTprofile14_59hr10_Nov_2011.m profiles/MTprofile14_9hr20_Sep_2011.m profiles/MTprofile15_22hr04_Oct_2011.m profiles/MTprofile16_0hr04_Oct_2011.m profiles/MTprofile16_31hr04_Oct_2011.m profiles/MTprofile16_43hr14_Nov_2011.m profiles/MTprofile19_7hr09_Oct_2011.m profiles/MTprofile20_5hr09_Oct_2011.m profiles/MTprofile23_35hr09_Oct_2011.m profiles/MTprofile9_34hr18_Nov_2011.m testPrograms/LiebermanMOCdata.m testPrograms/LiebermanMOCtest.m testPrograms/MAPtwoToneDemo.m testPrograms/demoTwisterProbability.m testPrograms/demoTwisterSpikes.m testPrograms/oldTestPrograms/LiebermanMOCdata.m testPrograms/oldTestPrograms/MAPtwoToneDemo1D.m testPrograms/openGlobals.m testPrograms/repeatTester.m testPrograms/runMAP1_14.m testPrograms/temp.m testPrograms/tempPL.m testPrograms/termp.m testPrograms/test2toneMovie.m testPrograms/test2toneSuppression.m testPrograms/test2toneSuppressionHold.m testPrograms/testACF.m testPrograms/testAN.m testPrograms/testANprob.m testPrograms/testBM.m testPrograms/testDPOAE.m testPrograms/testEfferent.m testPrograms/testFM.m testPrograms/testLibermanMOC_DPOAE.m testPrograms/testOME.m testPrograms/testPhaseLocking.m testPrograms/testPhysiology.m testPrograms/testPhysiologyProb.m testPrograms/testRF.m testPrograms/testRP.m testPrograms/testRP2.m testPrograms/testSynapse.m testPrograms/test_DRNL_Ruggero97.m testPrograms/test_MAP1_14.m testPrograms/test_speechInNoise.m userPrograms/Pavel_MAP1_14.m userPrograms/pitchModel_RM.m userPrograms/runMAP1_14.m userProgramsASRforDummies/ASR_suite_for_dummies.pdf userProgramsASRforDummies/EssexAid_DEMO.pdf userProgramsASRforDummies/Exp_Ray_1.m userProgramsASRforDummies/Exp_Tutorial_1.m userProgramsASRforDummies/Exp_Tutorial_2.m userProgramsASRforDummies/MAPwrap.m userProgramsASRforDummies/cEssexAid.m userProgramsASRforDummies/cHMM.m userProgramsASRforDummies/cJob.m userProgramsASRforDummies/def/Grammar_digit/noSevenZeroDict userProgramsASRforDummies/def/Grammar_digit/wdnetNRCnoSP.txt userProgramsASRforDummies/def/Grammar_digit/wdnetNoSP.slf userProgramsASRforDummies/def/Grammar_digit/words3 userProgramsASRforDummies/def/Grammar_digit/wordsNoSevenZero userProgramsASRforDummies/def/HERest_digit/mix2_16.hed userProgramsASRforDummies/def/HERest_digit/mix3_16.hed userProgramsASRforDummies/def/HERest_digit/mix5_16.hed userProgramsASRforDummies/def/HERest_digit/mix7_16.hed userProgramsASRforDummies/def/HERest_digit/sil1.hed userProgramsASRforDummies/def/config_STANDARD userProgramsASRforDummies/demo_wavs/TrainingData-Clean/MNC_1359A.wav userProgramsASRforDummies/demo_wavs/TrainingData-Clean/MNC_2468A.wav userProgramsASRforDummies/demo_wavs/TrainingData-Clean/MNC_312OA.wav userProgramsASRforDummies/demo_wavs/TrainingData-Clean/MNC_4321OA.wav userProgramsASRforDummies/demo_wavs/TrainingData-Clean/MNC_46598A.wav userProgramsASRforDummies/demo_wavs/TrainingData-Clean/MNC_5689OA.wav userProgramsASRforDummies/demo_wavs/TrainingData-Clean/MNC_8642A.wav userProgramsASRforDummies/demo_wavs/TrainingData-Clean/MNC_9531A.wav userProgramsASRforDummies/demo_wavs/TrainingData-Clean/MNC_98564A.wav userProgramsASRforDummies/demo_wavs/TrainingData-Clean/MNC_O1234A.wav userProgramsASRforDummies/demo_wavs/TrainingData-Clean/MNC_O213A.wav userProgramsASRforDummies/demo_wavs/TrainingData-Clean/MNC_O9865A.wav userProgramsASRforDummies/demo_wavs/TripletTestData/MNC_132A.wav userProgramsASRforDummies/demo_wavs/TripletTestData/MNC_148A.wav userProgramsASRforDummies/demo_wavs/TripletTestData/MNC_36OA.wav userProgramsASRforDummies/demo_wavs/TripletTestData/MNC_465A.wav userProgramsASRforDummies/demo_wavs/TripletTestData/MNC_592A.wav userProgramsASRforDummies/demo_wavs/TripletTestData/MNC_8O9A.wav userProgramsASRforDummies/demo_wavs/noises/pink_demo.wav userProgramsASRforDummies/worker.m userProgramsDomenika/test_IC_DominikaTones.m userProgramsMathiasDietz/test_binaural.m userProgramsMikaelDeroche/runMAP1_14.m userProgramsMikaelDeroche/testACF.m userProgramsRM/MAPdemoMultiChOAE.m userProgramsRM/Pavel_MAP1_14.m userProgramsRM/pitchModel_RM.m userProgramsRM/temp.m userProgramsRM/testACF.m userProgramsRM/testDPOAE.m userProgramsRM/test_Dolan_and_Nuttall.m userProgramsRM/test_MAP1_14Hopkins.m userProgramsRM/test_MAP1_14RAM.m userProgramsRM/test_MAP1_14RAMworks.m userProgramsRM/test_speechInNoise.m userProgramsRM/test_speechInNoiseDelmanhorst.m userProgramsRM/test_toneInNoise.m userProgramsTim/IPIHextract.m userProgramsTim/MAP1_14_olde_version_dont_use.m userProgramsTim/Pavel_MAP1_14.m userProgramsTim/cutsignal.m userProgramsTim/enframe.m userProgramsTim/fourier_analyse.m userProgramsTim/fourierautocorrelationhistogram.m userProgramsTim/fourierautocorrelationhistogram_direct.m userProgramsTim/iloga2sloga.m userProgramsTim/map_iih_onto_log.m userProgramsTim/mellin_trafo.m userProgramsTim/pitchModel_RM.m userProgramsTim/plotIFRAN.m userProgramsTim/poolIPI_across_channels.m userProgramsTim/runningACF.m userProgramsTim/sloga2iloga.m userProgramsTim/speech_stimuli_check.m userProgramsTim/speechmanipulation.fig userProgramsTim/speechmanipulation.m userProgramsTim/test_autocorr.m userProgramsTim/track_formants_from_IPI_guy.m userProgramsTim/track_formants_from_IPI_guy_olde.m utilities/UTIL_Butterworth.m utilities/UTIL_CAPgenerator.m utilities/UTIL_FFT.m utilities/UTIL_cascadePlot.m utilities/UTIL_plotMatrix.m utilities/UTIL_printTabTable.m utilities/UTIL_showMAP.m utilities/stimulusCreate.m utilities/temp.m wavFileStore/1o7a_44kHz.wav wavFileStore/1z67931a_44kHz.wav wavFileStore/Oh No.wav wavFileStore/ten.wav wavFileStore/white noise.wav
diffstat 222 files changed, 16502 insertions(+), 4507 deletions(-) [+]
line wrap: on
line diff
Binary file Documentation Manuals Presentations etc/Hearing dummy Talk.ppt has changed
Binary file Documentation Manuals Presentations etc/Lecluyse, Meddis (2009).pdf has changed
Binary file Documentation Manuals Presentations etc/MAP 1_14 Model description.doc has changed
Binary file Documentation Manuals Presentations etc/MAP1_14 quick reference.doc has changed
Binary file Documentation Manuals Presentations etc/Meddis and Lopez-Poveda (Springer).pdf has changed
Binary file Documentation Manuals Presentations etc/MultiThreshold manual.doc has changed
Binary file Documentation Manuals Presentations etc/Surrey Meddis 2010.ppt has changed
Binary file Documentation Manuals Presentations etc/forward masking figures.ppt has changed
Binary file Documentation Manuals Presentations etc/multiThreshold quickStart instructions.doc has changed
Binary file Documentation Manuals Presentations etc/old model talk 2010.ppt has changed
Binary file Documentation/MAP 1_14 Model description.docx has changed
Binary file Documentation/MAP1_14 quick reference .doc has changed
Binary file Documentation/MultiThreshold ManualCT.doc has changed
Binary file Documentation/MultiThreshold manual.doc has changed
Binary file Documentation/multiThreshold quickStart instructions.doc has changed
Binary file Documentation/multiThreshold quickStartCT.doc has changed
Binary file MAP/MAP 1_14 Model description.docx - Shortcut.lnk has changed
--- a/MAP/MAP1_14.m	Thu Oct 06 15:43:20 2011 +0100
+++ b/MAP/MAP1_14.m	Mon Nov 28 13:34:28 2011 +0000
@@ -23,35 +23,27 @@
 restorePath=path;
 addpath (['..' filesep 'parameterStore'])
 
-% clear global -regexp OMEParams DRNLParams IHC_cilia_RPParams IHCpreSynapseParams
-% clear global -regexp  AN_IHCsynapseParams MacGregorParams MacGregorMultiParams
-% clear global -regexp dt ANdt  savedBFlist saveAN_spikesOrProbability saveMAPparamsName...
-%     savedInputSignal OMEextEarPressure TMoutput OMEoutput ARattenuation ...
-%     DRNLoutput IHC_cilia_output IHCrestingCiliaCond IHCrestingV...
-%     IHCoutput ANprobRateOutput ANoutput savePavailable ANtauCas  ...
-%     CNtauGk CNoutput  ICoutput ICmembraneOutput ICfiberTypeRates ...
-%     MOCattenuation
-
 global OMEParams DRNLParams IHC_cilia_RPParams IHCpreSynapseParams
 global AN_IHCsynapseParams MacGregorParams MacGregorMultiParams
 
 % All of the results of this function are stored as global
-global dt ANdt  savedBFlist saveAN_spikesOrProbability saveMAPparamsName...
-    savedInputSignal OMEextEarPressure TMoutput OMEoutput ARattenuation ...
-    DRNLoutput IHC_cilia_output IHCrestingCiliaCond IHCrestingV...
-    IHCoutput ANprobRateOutput ANoutput savePavailable ANtauCas  ...
-    CNtauGk CNoutput  ICoutput ICmembraneOutput ICfiberTypeRates ...
-    MOCattenuation 
+global  savedParamChanges savedBFlist saveAN_spikesOrProbability ...
+    saveMAPparamsName savedInputSignal dt dtSpikes ...
+    OMEextEarPressure TMoutput OMEoutput DRNLoutput...
+    IHC_cilia_output IHCrestingCiliaCond IHCrestingV...
+    IHCoutput ANprobRateOutput ANoutput savePavailable saveNavailable ...
+    ANtauCas CNtauGk CNoutput ICoutput ICmembraneOutput ICfiberTypeRates...
+    MOCattenuation ARattenuation 
 
 
 % Normally only ICoutput(logical spike matrix) or ANprobRateOutput will be
 % needed by the user; so the following will suffice
-%   global ANdt ICoutput ANprobRateOutput
+%   global dtSpikes ICoutput ANprobRateOutput
 
 % Note that sampleRate has not changed from the original function call and
 %  ANprobRateOutput is sampled at this rate
 % However ANoutput, CNoutput and IC output are stored as logical
-%  'spike' matrices using a lower sample rate (see ANdt).
+%  'spike' matrices using a lower sample rate (see dtSpikes).
 
 % When AN_spikesOrProbability is set to probability,
 %  no spike matrices are computed.
@@ -60,7 +52,7 @@
 
 % Efferent control variables are ARattenuation and MOCattenuation
 %  These are scalars between 1 (no attenuation) and 0.
-%  They are represented with dt=1/sampleRate (not ANdt)
+%  They are represented with dt=1/sampleRate (not dtSpikes)
 %  They are computed using either AN probability rate output
 %   or IC (spikes) output as approrpriate.
 % AR is computed using across channel activity
@@ -85,6 +77,7 @@
 savedBFlist=BFlist;
 saveAN_spikesOrProbability=AN_spikesOrProbability;
 saveMAPparamsName=MAPparamsName;
+savedParamChanges=paramChanges;
 
 dt=1/sampleRate;
 duration=length(inputSignal)/sampleRate;
@@ -94,7 +87,8 @@
 segmentTime=dt*(1:segmentLength); % used in debugging plots
 
 % all spiking activity is computed using longer epochs
-ANspeedUpFactor=AN_IHCsynapseParams.ANspeedUpFactor;  % e.g.5 times
+ANspeedUpFactor=ceil(sampleRate/AN_IHCsynapseParams.spikesTargetSampleRate);
+% ANspeedUpFactor=AN_IHCsynapseParams.ANspeedUpFactor;  % e.g.5 times
 
 % inputSignal must be  row vector
 [r c]=size(inputSignal);
@@ -115,10 +109,10 @@
 inputSignal=[inputSignal pad];
 [ignore signalLength]=size(inputSignal);
 
-% AN (spikes) is computed at a lower sample rate when spikes required
-%  so it has a reduced segment length (see 'ANspeeUpFactor' above)
+% spiking activity is computed at longer sampling intervals (dtSpikes)
+%  so it has a smaller number of epochs per segment(see 'ANspeeUpFactor' above)
 % AN CN and IC all use this sample interval
-ANdt=dt*ANspeedUpFactor;
+dtSpikes=dt*ANspeedUpFactor;
 reducedSegmentLength=round(segmentLength/ANspeedUpFactor);
 reducedSignalLength= round(signalLength/ANspeedUpFactor);
 
@@ -163,7 +157,7 @@
 OME_TMdisplacementBndry=[];
 
 % OME high pass (simulates poor low frequency stapes response)
-OMEhighPassHighCutOff=OMEParams.OMEstapesLPcutoff;
+OMEhighPassHighCutOff=OMEParams.OMEstapesHPcutoff;
 Nyquist=sampleRate/2;
 [stapesDisp_b,stapesDisp_a] = butter(1, OMEhighPassHighCutOff/Nyquist, 'high');
 % figure(10), freqz(stapesDisp_b, stapesDisp_a)
@@ -236,8 +230,8 @@
 % DRNLb=DRNLParams.b;
 DRNLc=DRNLParams.c;
 linGAIN=DRNLParams.g;
-CtBM=10e-9*10^(DRNLParams.CtBMdB/20);
-CtS=CtBM/DRNLa;
+ctBM=10e-9*10^(DRNLParams.ctBMdB/20);
+CtS=ctBM/DRNLa;
 %
 % gammatone filter coefficients for linear pathway
 bw=DRNLParams.linBWs';
@@ -299,6 +293,7 @@
 b0=1+ a1;
 % high pass (i.e. low pass reversed)
 IHCciliaFilter_b=[a0 a1]; IHCciliaFilter_a=b0;
+% i.e. b= [1  dt/tc-1]  and a= dt/IHC_cilia_RPParams.tc
 % figure(9), freqz(IHCciliaFilter_b, IHCciliaFilter_a)
 
 IHCciliaBndry=cell(nBFs,1);
@@ -405,14 +400,17 @@
 % special variables for monitoring synaptic cleft (specialists only)
 savePavailableSeg=zeros(nANchannels,segmentLength);
 savePavailable=zeros(nANchannels,signalLength);
+% only one stream of available transmitter will be saved
+saveNavailableSeg=zeros(1,reducedSegmentLength);
+saveNavailable=zeros(1,reducedSignalLength);
 
 % spikes     % !  !  !    ! !        !   !  !
-lengthAbsRefractory= round(AN_refractory_period/ANdt);
+lengthAbsRefractory= round(AN_refractory_period/dtSpikes);
 
-AN_ydt= repmat(AN_IHCsynapseParams.y*ANdt, nANfibers,1);
-AN_ldt= repmat(AN_IHCsynapseParams.l*ANdt, nANfibers,1);
-AN_xdt= repmat(AN_IHCsynapseParams.x*ANdt, nANfibers,1);
-AN_rdt= repmat(AN_IHCsynapseParams.r*ANdt, nANfibers,1);
+AN_ydt= repmat(AN_IHCsynapseParams.y*dtSpikes, nANfibers,1);
+AN_ldt= repmat(AN_IHCsynapseParams.l*dtSpikes, nANfibers,1);
+AN_xdt= repmat(AN_IHCsynapseParams.x*dtSpikes, nANfibers,1);
+AN_rdt= repmat(AN_IHCsynapseParams.r*dtSpikes, nANfibers,1);
 AN_rdt_plus_ldt= AN_rdt + AN_ldt;
 AN_M= round(AN_IHCsynapseParams.M);
 
@@ -480,12 +478,12 @@
 CNdendriteLPfreq= MacGregorMultiParams.dendriteLPfreq;
 CNcurrentPerSpike=MacGregorMultiParams.currentPerSpike;
 CNspikeToCurrentTau=1/(2*pi*CNdendriteLPfreq);
-t=ANdt:ANdt:5*CNspikeToCurrentTau;
+t=dtSpikes:dtSpikes:5*CNspikeToCurrentTau;
 CNalphaFunction= (1 / ...
     CNspikeToCurrentTau)*t.*exp(-t /CNspikeToCurrentTau);
 CNalphaFunction=CNalphaFunction*CNcurrentPerSpike;
 
-% figure(98), plot(t,CNalphaFunction)
+% figure(98), plot(t,CNalphaFunction), xlim([0 .020]), xlabel('time (s)'), ylabel('I')
 % working memory for implementing convolution
 
 CNcurrentTemp=...
@@ -520,7 +518,7 @@
 CN_PSTH=zeros(nICcells ,reducedSegmentLength);
 
 % ICspikeWidth=0.00015;   % this may need revisiting
-% epochsPerSpike=round(ICspikeWidth/ANdt);
+% epochsPerSpike=round(ICspikeWidth/dtSpikes);
 % if epochsPerSpike<1
 %     error(['MacGregorMulti: sample rate too low to support ' ...
 %         num2str(ICspikeWidth*1e6) '  microsec spikes']);
@@ -546,7 +544,7 @@
 ICdendriteLPfreq= MacGregorParams.dendriteLPfreq;
 ICcurrentPerSpike=MacGregorParams.currentPerSpike;
 ICspikeToCurrentTau=1/(2*pi*ICdendriteLPfreq);
-t=ANdt:ANdt:3*ICspikeToCurrentTau;
+t=dtSpikes:dtSpikes:3*ICspikeToCurrentTau;
 IC_CNalphaFunction= (ICcurrentPerSpike / ...
     ICspikeToCurrentTau)*t.*exp(-t / ICspikeToCurrentTau);
 % figure(98), plot(t,IC_CNalphaFunction)
@@ -661,12 +659,16 @@
                 nonlinOutput, GTnonlinBdry1{BFno,order});
         end
         
+        
         % Nick's compression algorithm
-        abs_x = abs(nonlinOutput);
-        y(abs_x<CtS)   = DRNLa * nonlinOutput(abs_x<CtS);
-        y(abs_x>=CtS)  = sign(nonlinOutput(abs_x>=CtS)) * DRNLa * CtS .* ...
-            exp(   DRNLc * log(  abs_x(abs_x>=CtS)/CtS  )   );
-        nonlinOutput=y;
+        abs_x= abs(nonlinOutput);
+        signs= sign(nonlinOutput);
+        belowThreshold= abs_x<CtS;
+        nonlinOutput(belowThreshold)= DRNLa *nonlinOutput(belowThreshold);
+        aboveThreshold=~belowThreshold;
+        nonlinOutput(aboveThreshold)= signs(aboveThreshold) *ctBM .* ...
+            exp(DRNLc *log( DRNLa*abs_x(aboveThreshold)/ctBM ));
+                       
         
 %         %    original   broken stick instantaneous compression
 %         holdY=nonlinOutput;
@@ -688,24 +690,16 @@
 %         end
 %         nonlinOutput=y;
 
-        % % Boltzmann compression function
-        % y=(nonlinOutput * DRNLa*100000);
-        % holdY=y;
-        % y=abs(y);
-        % s=10; u=0.0;
-        % x=1./(1+exp(-(y-u)/s))-0.5;
-        % nonlinOutput=sign(nonlinOutput).*x/10000;
 
+% if segmentStartPTR==10*segmentLength+1
+%     figure(90)
+%     plot(holdY,'b'), hold on
+%     plot(nonlinOutput, 'r'), hold off
+%     ylim([-1e-5 1e-5])
+%     pause(1)
+% end
 
-        % if segmentStartPTR==10*segmentLength+1
-        %     figure(90)
-        %     plot(holdY,'b'), hold on
-        %     plot(nonlinOutput, 'r'), hold off
-        %     ylim([-1e-5 1e-5])
-        %     pause(1)
-        % end
-
-        %       second filter removes distortion products
+%       second filter removes distortion products
         for order = 1 : GTnonlinOrder
             [ nonlinOutput GTnonlinBdry2{BFno,order}] = ...
                 filter(GTnonlin_b(BFno,:), GTnonlin_a(BFno,:), ...
@@ -839,7 +833,8 @@
                % the probability of a spike's occurring in the preceding
                %  refractory window: t= (tnow-refractory period) :dt: tnow
                %    pFired= 1 - II(1-p(t)),
-               % we need a running account of cumProb=II(1-p(t))
+               % we need a running account of cumProb=II(1-p(t)) in order
+               % not to have to recompute this for each value of t
                %   cumProb(t)= cumProb(t-1)*(1-p(t))/(1-p(t-refracPeriod))
                %   cumProb(0)=0
                %   pFired(t)= 1-cumProb(t)
@@ -869,8 +864,7 @@
 %                 figure(88), plot(cumANnotFireProb'), title('cumNotFire')
 %                 figure(89), plot(ANprobRateOutput'), title('ANprobRateOutput')
 
-            %% Estimate efferent effect:  0 < ARattenuation > 1
-            %  acoustic reflex
+            %% Estimate acoustic reflex efferent effect:  0 < ARattenuation > 1
             [r c]=size(ANrate);
             if r>nBFs % Only if LSR fibers are computed
                 ARAttSeg=mean(ANrate(1:nBFs,:),1); %LSR channels are 1:nBF
@@ -893,31 +887,6 @@
                     ones(size(rates))* -rateToAttenuationFactorProb;
             else
 
-                % Nick's new code
-%                 for idx=1:nBFs
-%                     [smoothedRates, MOCprobBoundary{idx}] = ...
-%                         filter(MOCfilt_b, MOCfilt_a, rates(idx,:), ...
-%                         MOCprobBoundary{idx});
-% %                     smoothedRates=smoothedRates-MOCrateThresholdProb;
-% %                     smoothedRates(smoothedRates<0)=0;
-% %                     x =  (1- smoothedRates* rateToAttenuationFactorProb); %ORIGINAL 
-%  
-%                     %NEW !!!
-%                     x = -20*log10(  max(smoothedRates/MOCrateThresholdProb,1)  )*rateToAttenuationFactorProb; %dB attenuation
-%                     x = 10.^(x/20);
-%                     x = max(x,10^(-35/20));    
-% %                     %ALSO - filter at the end - this will stop rapid attack
-% %                     %and slow decay
-% %                     [x, MOCprobBoundary{idx}] = ...
-% %                         filter(MOCfilt_b, MOCfilt_a, x, ...
-% %                         MOCprobBoundary{idx});
-%                     
-%                                         
-%                     MOCattenuation(idx,segmentStartPTR:segmentEndPTR)= ...
-%                         x;                                                            
-%                 end
-                
-
                 for idx=1:nBFs
                     [smoothedRates, MOCprobBoundary{idx}] = ...
                         filter(MOCfiltProb_b, MOCfiltProb_a, rates(idx,:), ...
@@ -940,7 +909,7 @@
             for t = ANspeedUpFactor:ANspeedUpFactor:segmentLength;
                 ANtimeCount=ANtimeCount+1;
                 % convert release rate to probabilities
-                releaseProb=vesicleReleaseRate(:,t)*ANdt;
+                releaseProb=vesicleReleaseRate(:,t)*dtSpikes;
                 % releaseProb is the release probability per channel
                 %  but each channel has many synapses
                 releaseProb=repmat(releaseProb',nFibersPerChannel,1);
@@ -968,6 +937,8 @@
 
                 AN_available = AN_available + replenish - ejected ...
                     + reprocessed;
+                saveNavailableSeg(:,ANtimeCount)=AN_available(end,:); % only last channel
+
                 AN_cleft = AN_cleft + ejected - reuptakeandlost;
                 AN_reprocess = AN_reprocess + reuptake - reprocessed;
 
@@ -1003,17 +974,20 @@
 
             % segment debugging
             % plotInstructions.figureNo=98;
-            % plotInstructions.displaydt=ANdt;
+            % plotInstructions.displaydt=dtSpikes;
             %  plotInstructions.numPlots=1;
             %  plotInstructions.subPlotNo=1;
             % UTIL_plotMatrix(ANspikes, plotInstructions);
 
             % and save it. NB, AN is now on 'speedUp' time
             ANoutput(:, reducedSegmentPTR: shorterSegmentEndPTR)=ANspikes;
+            % monitor synapse contents (only sometimes used)
+            saveNavailable(reducedSegmentPTR:reducedSegmentPTR+reducedSegmentLength-1)=...
+                saveNavailableSeg;
 
 
             %% CN Macgregor first neucleus -------------------------------
-            % input is from AN so ANdt is used throughout
+            % input is from AN so dtSpikes is used throughout
             % Each CNneuron has a unique set of input fibers selected
             %  at random from the available AN fibers (CNinputfiberLists)
 
@@ -1024,7 +998,7 @@
                 for idx=1:nCNneuronsPerChannel
                     % determine candidate fibers for this unit
                     fibersUsed=CNinputfiberLists(synapseNo,:);
-                    % ANpsth has a bin width of ANdt
+                    % ANpsth has a bin width of dtSpikes
                     %  (just a simple sum across fibers)
                     AN_PSTH(synapseNo,:) = ...
                         sum(ANspikes(fibersUsed,:), 1);
@@ -1056,14 +1030,14 @@
             if CN_c>0
                 % variable threshold condition (slow)
                 for t=1:reducedSegmentLength
-                    CNtimeSinceLastSpike=CNtimeSinceLastSpike-ANdt;
+                    CNtimeSinceLastSpike=CNtimeSinceLastSpike-dtSpikes;
                     s=CN_E>CN_Th & CNtimeSinceLastSpike<0 ;
                     CNtimeSinceLastSpike(s)=0.0005;         % 0.5 ms for sodium spike
                     dE =(-CN_E/CN_tauM + ...
                         CNcurrentInput(:,t)/CN_cap+(...
-                        CN_Gk/CN_cap).*(CN_Ek-CN_E))*ANdt;
-                    dGk=-CN_Gk*ANdt./tauGk + CN_b*s;
-                    dTh=-(CN_Th-CN_Th0)*ANdt/CN_tauTh + CN_c*s;
+                        CN_Gk/CN_cap).*(CN_Ek-CN_E))*dtSpikes;
+                    dGk=-CN_Gk*dtSpikes./tauGk + CN_b*s;
+                    dTh=-(CN_Th-CN_Th0)*dtSpikes/CN_tauTh + CN_c*s;
                     CN_E=CN_E+dE;
                     CN_Gk=CN_Gk+dGk;
                     CN_Th=CN_Th+dTh;
@@ -1076,7 +1050,7 @@
                 ss=zeros(1,reducedSegmentLength);
                 for t=1:reducedSegmentLength
                     % time of previous spike moves back in time
-                    CNtimeSinceLastSpike=CNtimeSinceLastSpike-ANdt;
+                    CNtimeSinceLastSpike=CNtimeSinceLastSpike-dtSpikes;
                     % action potential if E>threshold
                     %  allow time for s to reset between events
                     s=CN_E>CN_Th0 & CNtimeSinceLastSpike<0 ;  
@@ -1084,8 +1058,8 @@
                     CNtimeSinceLastSpike(s)=0.0005; % 0.5 ms for sodium spike
                     dE = (-CN_E/CN_tauM + ...
                         CNcurrentInput(:,t)/CN_cap +...
-                        (CN_Gk/CN_cap).*(CN_Ek-CN_E))*ANdt;
-                    dGk=-CN_Gk*ANdt./tauGk +CN_b*s;
+                        (CN_Gk/CN_cap).*(CN_Ek-CN_E))*dtSpikes;
+                    dGk=-CN_Gk*dtSpikes./tauGk +CN_b*s;
                     CN_E=CN_E+dE;
                     CN_Gk=CN_Gk+dGk;
                     E(t)=CN_E(1);
@@ -1116,7 +1090,7 @@
 
             % segment debugging
             % plotInstructions.figureNo=98;
-            % plotInstructions.displaydt=ANdt;
+            % plotInstructions.displaydt=dtSpikes;
             %  plotInstructions.numPlots=1;
             %  plotInstructions.subPlotNo=1;
             % UTIL_plotMatrix(CN_spikes, plotInstructions);
@@ -1158,8 +1132,8 @@
                     for t=1:reducedSegmentLength
                         s=IC_E>IC_Th0;
                         dE = (-IC_E/IC_tauM + inputCurrent(:,t)/IC_cap +...
-                            (IC_Gk/IC_cap).*(IC_Ek-IC_E))*ANdt;
-                        dGk=-IC_Gk*ANdt/IC_tauGk +IC_b*s;
+                            (IC_Gk/IC_cap).*(IC_Ek-IC_E))*dtSpikes;
+                        dGk=-IC_Gk*dtSpikes/IC_tauGk +IC_b*s;
                         IC_E=IC_E+dE;
                         IC_Gk=IC_Gk+dGk;
                         ICmembranePotential(:,t)=IC_E+s.*(IC_Eb-IC_E)+IC_Er;
@@ -1169,16 +1143,16 @@
                     for t=1:reducedSegmentLength
                         dE = (-IC_E/IC_tauM + ...
                             inputCurrent(:,t)/IC_cap + (IC_Gk/IC_cap)...
-                            .*(IC_Ek-IC_E))*ANdt;
+                            .*(IC_Ek-IC_E))*dtSpikes;
                         IC_E=IC_E+dE;
                         s=IC_E>IC_Th;
                         ICmembranePotential(:,t)=IC_E+s.*(IC_Eb-IC_E)+IC_Er;
-                        dGk=-IC_Gk*ANdt/IC_tauGk +IC_b*s;
+                        dGk=-IC_Gk*dtSpikes/IC_tauGk +IC_b*s;
                         IC_Gk=IC_Gk+dGk;
 
                         % After a spike, the threshold is raised
                         % otherwise it settles to its baseline
-                        dTh=-(IC_Th-Th0)*ANdt/IC_tauTh +s*IC_c;
+                        dTh=-(IC_Th-Th0)*dtSpikes/IC_tauTh +s*IC_c;
                         IC_Th=IC_Th+dTh;
                     end
                 end
@@ -1202,7 +1176,7 @@
                     ICfiberTypeRates(tauCount, ...
                         reducedSegmentPTR:shorterSegmentEndPTR)=...
                         sum(ICspikes(firstCell:lastCell, :))...
-                        /(nCellsPerTau*ANdt);
+                        /(nCellsPerTau*dtSpikes);
                     firstCell=firstCell+nCellsPerTau;
                     lastCell=lastCell+nCellsPerTau;
                 end
@@ -1230,19 +1204,19 @@
                 % figure(4),plot(ICmembraneOutput(2,:))
 
                 % estimate efferent effects.
-                % ARis based on LSR units. LSR channels are 1:nBF
+                % AR is based on LSR units. LSR channels are 1:nBF
                 if nANfiberTypes>1  % use only if model is multi-fiber
-                    ARAttSeg=mean(ICspikes(1:nBFs,:),1)/ANdt;
+                    ARAttSeg=mean(ICspikes(1:nBFs,:),1)/dtSpikes;
                     [ARAttSeg, ARboundary] = ...
                         filter(ARfilt_b, ARfilt_a, ARAttSeg, ARboundary);
-%                     ARAttSeg(ARAttSeg<0)=0;   % prevent negative strengths
-                    % scale up to dt from ANdt
+%                    ARAttSeg(ARAttSeg<0)=0;   % prevent negative strengths
+                    % scale up to dt from dtSpikes
                     x= repmat(ARAttSeg, ANspeedUpFactor,1);
                     x= reshape(x,1,segmentLength);
                     ARattenuation(segmentStartPTR:segmentEndPTR)=...
                         (1-ARrateToAttenuationFactor* x);
                     % max 60 dB attenuation
-                    ARattenuation(ARattenuation<0)=0.001;
+                    ARattenuation(ARattenuation<0)=0.01;
                 else
                     % single fiber type; disable AR because no LSR fibers
                     ARattenuation(segmentStartPTR:segmentEndPTR)=...
@@ -1253,7 +1227,7 @@
                 %  separate MOC effect for each BF
                 %  there is only one unit per channel
                 HSRbegins=nBFs*(nANfiberTypes-1)+1;
-                rates=ICspikes(HSRbegins:end,:)/ANdt;
+                rates=ICspikes(HSRbegins:end,:)/dtSpikes;
                 % figure(4),plot(rates(1,:))
 
                 for idx=1:nBFs
@@ -1262,7 +1236,7 @@
                         MOCboundary{idx});
                     % spont 'rates' is zero for IC
                     MOCattSegment(idx,:)=smoothedRates;
-                    % expand timescale back to model dt from ANdt
+                    % expand timescale back to model dt from dtSpikes
                     x= repmat(MOCattSegment(idx,:), ANspeedUpFactor,1);
                     x= reshape(x,1,segmentLength);
                     MOCattenuation(idx,segmentStartPTR:segmentEndPTR)= ...
@@ -1276,7 +1250,7 @@
                 
                 % segment debugging
                 % plotInstructions.figureNo=98;
-                % plotInstructions.displaydt=ANdt;
+                % plotInstructions.displaydt=dtSpikes;
                 %  plotInstructions.numPlots=1;
                 %  plotInstructions.subPlotNo=1;
                 % UTIL_plotMatrix(ICspikes, plotInstructions);
--- a/MAP/MAPrunner.m	Thu Oct 06 15:43:20 2011 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,71 +0,0 @@
-function MAPrunner(MAPparamsName, AN_spikesOrProbability, ...
-    signalCharacteristics, paramChanges, showMapOptions)
-
-dbstop if error
-restorePath=path;
-addpath (['..' filesep 'MAP'],    ['..' filesep 'wavFileStore'], ...
-    ['..' filesep 'utilities'])
-
-
-%% #3 pure tone, harmonic sequence or speech file input
-signalType= signalCharacteristics.type;
-sampleRate= signalCharacteristics.sampleRate;
-duration=signalCharacteristics.duration;                 % seconds
-rampDuration=signalCharacteristics.rampDuration;              % raised cosine ramp (seconds)
-beginSilence=signalCharacteristics.beginSilence;               
-endSilence=signalCharacteristics.endSilence;                  
-toneFrequency= signalCharacteristics.toneFrequency;            % or a pure tone (Hz)
-leveldBSPL=signalCharacteristics.leveldBSPL;
-
-BFlist=-1;
-
-
-%% Generate stimuli
-
-switch signalType
-    case 'tones'
-        % Create pure tone stimulus
-        dt=1/sampleRate; % seconds
-        time=dt: dt: duration;
-        inputSignal=sum(sin(2*pi*toneFrequency'*time), 1);
-        amp=10^(leveldBSPL/20)*28e-6;   % converts to Pascals (peak)
-        inputSignal=amp*inputSignal;
-        % apply ramps
-        % catch rampTime error
-        if rampDuration>0.5*duration, rampDuration=duration/2; end
-        rampTime=dt:dt:rampDuration;
-        ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ...
-            ones(1,length(time)-length(rampTime))];
-        inputSignal=inputSignal.*ramp;
-        ramp=fliplr(ramp);
-        inputSignal=inputSignal.*ramp;
-        % add silence
-        intialSilence= zeros(1,round(beginSilence/dt));
-        finalSilence= zeros(1,round(endSilence/dt));
-        inputSignal= [intialSilence inputSignal finalSilence];
-
-    case 'file'
-        %% file input simple or mixed
-        [inputSignal sampleRate]=wavread(fileName);
-        dt=1/sampleRate;
-        inputSignal=inputSignal(:,1);
-        targetRMS=20e-6*10^(leveldBSPL/20);
-        rms=(mean(inputSignal.^2))^0.5;
-        amp=targetRMS/rms;
-        inputSignal=inputSignal*amp;
-        intialSilence= zeros(1,round(0.1/dt));
-        finalSilence= zeros(1,round(0.2/dt));
-        inputSignal= [intialSilence inputSignal' finalSilence];
-end
-
-
-%% run the model
-
-MAP1_14(inputSignal, sampleRate, BFlist, ...
-    MAPparamsName, AN_spikesOrProbability, paramChanges);
-
-%% the model run is now complete. Now display the results
-UTIL_showMAP(showMapOptions, paramChanges)
-
-path(restorePath)
-
Binary file MAP/documentation/Hearing dummy Talk.ppt has changed
Binary file MAP/documentation/MAP1_14 quick reference.doc has changed
Binary file MAP/documentation/Model description.doc has changed
Binary file MAP/documentation/MultiThreshold manual.doc has changed
Binary file MAP/documentation/Surrey Meddis 2010.ppt has changed
Binary file MAP/documentation/The multiThreshold guide to getting started.doc has changed
Binary file MAP/documentation/old model talk 2010.ppt has changed
--- a/MAP/filteredSACF.m	Thu Oct 06 15:43:20 2011 +0100
+++ b/MAP/filteredSACF.m	Mon Nov 28 13:34:28 2011 +0000
@@ -1,53 +1,52 @@
-function [P, BFlist, sacf, boundaryValue] = ...
-    filteredSACF(inputSignalMatrix, method, params)
-% UTIL_filteredSACF computes within-channel, running autocorrelations (acfs)
-%  and finds the sum across channels (sacf).
-%  The SACF is smoothed to give the 'p function' (P).
+function [LP_SACF, BFlist, SACF, ACFboundaryValue] = ...
+    filteredSACF(inputSignalMatrix, dt, BFlist, params)
+% UTIL_filteredSACF computes within-channel, running autocorrelations (ACFs)
+%  and finds the running sum across channels (SACF).
+%  The SACF is smoothed to give the 'p function' (LP_SACF).
+%  (Balaguer-Ballestera, E. Denham, S.L. and Meddis, R. (2008))
+%
 %
 % INPUT
 %  	inputSignalMatrix: a matrix (channel x time) of AN activity
-%  	method.dt:			the signal sampling interval in seconds
-%   method.segmentNo:
-%   method.nonlinCF
-%   
+%  	dt:		the signal sampling interval in seconds
+%   BFlist: channel BFs
+%
 % params: 	a list of parmeters to guide the computation:
-%   filteredSACFParams.lags: an array of lags to be computed (seconds)
-%   filteredSACFParams.acfTau: time constant (sec) of the running acf calculations
-%     if acfTau>1 it is assumed that Wiegrebe'sacf method
+%   params.lags: an array of lags to be computed (seconds)
+%   params.acfTau: time constant (sec) of the running ACF
+%     if acfTau>1 it is assumed that Wiegrebe'SACF method
 %   	for calculating tau is to be used (see below)
-%   filteredSACFParams.Lambda: time constant  for smoothing thsacf to make P
-%   filteredSACFParams.lagsProcedure identifies a strategy for omitting some lags.
-%    Options are: 'useAllLags', 'omitShortLags', or 'useBernsteinLagWeights'
-%   filteredSACFParams.usePressnitzer applies lower weights longer lags
-%   parafilteredSACFParamsms.plotACFs (=1) creates movie of acf matrix (optional)
-%
+%   params.Lambda: smoothing factor for the SACF
+%   params.lagsProcedure: strategies for omitting some lags.
+%    (Options: 'useAllLags' or 'omitShortLags')
+%   params.usePressnitzer applies lower weights longer lags
+%   params.plotACFs (=1) creates movie of ACF matrix (optional)
 %
 % OUTPUT
-%  	P:	P function 	(time x lags), a low pass filtered version of sacf.
-%  method: updated version of input method (to include lags used)
-%   sacf:  	(time x lags)
+%  	LP_SACF:	LP_SACF function 	(time x lags), a low pass filtered version of SACF.
+%  method: updated version of input 'method' (to include lags used)
+%   SACF:  	(time x lags)
+%
+% Notes:
+% ACFboundaryValue refers to segmented evaluation and is currently not
+%  supported. However the code may be useful later when this function
+%  is incorporated into MAP1_14.
 
 %%
-boundaryValue=[];
+global savedInputSignal
+
+ACFboundaryValue=[];
+
 [nChannels inputLength]= size(inputSignalMatrix);
-% list of BFs must be repeated is many fiber types used
-BFlist=method.nonlinCF;
-nfibertypes=nChannels/length(BFlist);
-BFlist=repmat(BFlist',2,1)';
 
-dt=method.dt;
-% adjust sample rate, if required
-if isfield(params,'dt')
-    [inputSignalMatrix dt]=UTIL_adjustDT(params.dt, method.dt, inputSignalMatrix);
-    method.dt=dt;
-end
-
-% create acf movie
+% create ACF movie
 if isfield(params, 'plotACFs') && params.plotACFs==1
     plotACF=1;
+    signalTime=dt:dt:dt*length(savedInputSignal);
 else
     plotACF=0;  % default
 end
+params.plotACFsInterval=round(params.plotACFsInterval/dt);
 
 if isfield(params,'lags')
     lags=params.lags;
@@ -64,11 +63,11 @@
 else
     lagsProcedure='useAllLags';  % default
 end
-% disp(['lag procedure= ''' lagsProcedure ''''])
+
 lagWeights=ones(nChannels,nLags);
 switch lagsProcedure
     case 'useAllLags'
-       % no action required lagWeights set above
+        % no action required lagWeights set above
     case 'omitShortLags'
         % remove lags that are short relative to CF
         allLags=repmat(lags,nChannels,1);
@@ -76,14 +75,12 @@
         criterionForOmittingLags=1./(params.criterionForOmittingLags*allCFs);
         idx= allLags < criterionForOmittingLags;	% ignore these lags
         lagWeights(idx)=0;
-    case 'useBernsteinLagWeights'
-        lagWeights=BernsteinLags(BFlist, lags)';
     otherwise
-        error ('acf: params.lagProcedure not recognised')
+        error ('ACF: params.lagProcedure not recognised')
 end
 
 
-% Establish matrix of lag time constants 
+% Establish matrix of lag time constants
 %   these are all the same if tau<1
 % if acfTau>1, it is assumed that we are using the Wiegrebe method
 %   and a different decay factor is applied to each lag
@@ -92,7 +89,7 @@
 if acfTau<1          % all taus are the same
     acfTaus=repmat(acfTau, 1, nLags);
     acfDecayFactors=ones(size(lags)).*exp(-dt/acfTau);
-else                      % use Wiegrebe method: tau= 2*lag (for example)
+else                  % use Wiegrebe method: tau= 2*lag (for example)
     WiegrebeFactor=acfTau;
     acfTaus=WiegrebeFactor*lags;
     idx= acfTaus<0.0025; acfTaus(idx)=0.0025;
@@ -101,7 +98,7 @@
 % make acfDecayFactors into a (channels x lags) matrix for speedy computation
 acfDecayFactors=repmat(acfDecayFactors,nChannels, 1);
 
-% P function lowpass filter decay (only one value needed)
+% LP_SACF function lowpass filter decay (only one value needed)
 pDecayFactor=exp(-dt/params.lambda);
 
 % ACF
@@ -112,124 +109,93 @@
 end
 
 
-P=zeros(nLags,inputLength+1);   % P must match segment length +1
-sacf=zeros(nLags,inputLength);
+LP_SACF=zeros(nLags,inputLength+1);   % LP_SACF must match segment length +1
+SACF=zeros(nLags,inputLength);
+method=[];  % legacy programming
 if   ~isfield(method,'segmentNumber') || method.segmentNumber==1
-    acf=zeros(nChannels,nLags);
+    ACF=zeros(nChannels,nLags);
     % create a runup buffer of signal
     buffer= zeros(nChannels, max(lagPointers));
 else
-    % boundaryValue picks up from a previous calculation
-    acf=params.boundaryValue{1};
-    P(: , 1)=params.boundaryValue{2}; % NB first value is last value of previous segment
-    buffer=params.boundaryValue{3};
+    % ACFboundaryValue picks up from a previous calculation
+    ACF=params.ACFboundaryValue{1};
+    % NB first value is last value of previous segment
+    LP_SACF(: , 1)=params.ACFboundaryValue{2};
+    buffer=params.ACFboundaryValue{3};
 end
 inputSignalMatrix=[buffer inputSignalMatrix];
 [nChannels inputLength]= size(inputSignalMatrix);
 
 timeCounter=0; biggestSACF=0;
 for timePointer= max(lagPointers)+1:inputLength
-    % acf is a continuously changing channels x lags matrix
+    % ACF is a continuously changing channels x lags matrix
     %   Only the current value is stored
-    % sacf is the vertical summary of acf ( a vector) and all values are kept and returned
-    % P is the smoothed version of sacf and all values are kept and returned
+    % SACF is the vertical sum of ACFs; all values are kept and returned
+    % LP_SACF is the smoothed version of SACF:all values are kept and returned
     % lagWeights emphasise some BF/lag combinations and ignore others
     % NB time now begins at the longest lag.
-    % E.g. if max(lags) is .04 then this is when the ACf will begin.
-    %            AN                                       AN delayed                             weights               filtering
-    
+    % E.g. if max(lags) is .04 then this is when the ACf will begin (?).
+
     % This is the ACF calculation
     timeCounter=timeCounter+1;
-    acf= (repmat(inputSignalMatrix(:, timePointer), 1, nLags) .* inputSignalMatrix(:, timePointer-lagPointers)).*lagWeights *dt + acf.* acfDecayFactors;
-    x=(mean(acf,1)./acfTaus)';
-%     disp(num2str(x'))
-    sacf(:,timeCounter)=x;
-    P(:,timeCounter+1)=sacf(:,timeCounter)*(1-pDecayFactor)+P(:,timeCounter)*pDecayFactor;
+    ACF= (repmat(inputSignalMatrix(:, timePointer), 1, nLags) .* ...
+        inputSignalMatrix(:, timePointer-lagPointers)).*...
+        lagWeights *dt + ACF.* acfDecayFactors;
+    x=(mean(ACF,1)./acfTaus)';
+    SACF(:,timeCounter)=x;
     
-    % plot at intervals of 200 points
-    if plotACF && ~mod(timePointer,params.plotACFsInterval)
-        %       mark cursor on chart to signal progress
-        % this assumes that the user has already plotted
-        % the signal in subplot(2,1,1) of figure (13)
-        figure(13)
-        hold on
-        subplot(4,1,1)
+    % smoothed version of SACF
+    LP_SACF(:,timeCounter+1)=SACF(:,timeCounter)* (1-pDecayFactor) + ...
+        LP_SACF(:,timeCounter)* pDecayFactor;
+
+    % plot ACF at intervals if requested to do so
+    if plotACF && ~mod(timePointer,params.plotACFsInterval) && ...
+            timePointer*dt>3*max(lags)
+        figure(89), clf
+        %           plot ACFs one per channel
+        subplot(2,1,1)
+        UTIL_cascadePlot(ACF, lags)
+        title(['running ACF  at ' num2str(dt*timePointer,'%5.3f') ' s'])
+        ylabel('channel BF'), xlabel('period (lag, ms)')
+        set(gca,'ytickLabel',[])
+
+        %           plot SACF
+        subplot(4,1,3), cla
+        plotSACF=SACF(:,timeCounter)-min(SACF(:,timeCounter));
+        plot(lags*1000, plotSACF, 'k')
+        biggestSACF=max(biggestSACF, max(plotSACF));
+        if biggestSACF>0, ylim([0 biggestSACF]), else ylim([0 1]), end
+        ylabel('SACF'), set(gca,'ytickLabel',[])
+%         xlim([min(lags*1000) max(lags*1000)])
+
+        %           plot signal
+        subplot(4,1,4)
+        plot(signalTime, savedInputSignal, 'k'), hold on
+        xlim([0 max(signalTime)])
+        a= ylim;
+        %       mark cursor on chart to indicate progress
         time=timePointer*dt;
-        a =ylim;
-        plot([time time], [a(1) a(1)+(a(2)-a(1))/4]) % current signal point marker
-        
-        %         plot ACFs one per channel
-        subplot(2,1,2), cla
-        cascadePlot(acf, lags, BFlist)
-        xlim([min(lags) max(lags)])
-        %         set(gca,'xscale','log')
-        title(num2str(method.dt*timePointer))
-        ylabel('BF'), xlabel('period (lag)')
-        
-        %         plot SACF
-        subplot(4,1,2), hold off
-        plot(lags,sacf(:,timeCounter)-min(sacf(:,timeCounter)))
-        biggestSACF=max(biggestSACF, max(sacf(:,timeCounter)));
-        if biggestSACF>0, ylim([0 biggestSACF]), end
-        %         set(gca,'xscale','log')
-        title('SACF')
+        plot([time time], [a(1) a(1)+(a(2)-a(1))/4], 'r', 'linewidth', 5)
         pause(params.plotMoviePauses)
     end
 end
-P=P(:,1:end-1);  % correction for speed up above
+LP_SACF=LP_SACF(:,1:end-1);  % correction for speed up above
 
 % Pressnitzer weights
 if ~isfield(params, 'usePressnitzer'),     params.usePressnitzer=0; end
 if params.usePressnitzer
-    [a nTimePoints]=size(P);
+    [a nTimePoints]=size(LP_SACF);
     % higher pitches get higher weights
     %     PressnitzerWeights=repmat(min(lags)./lags,nTimePoints,1);
     % weaker weighting
     PressnitzerWeights=repmat((min(lags)./lags).^0.5, nTimePoints,1);
-    P=P.*PressnitzerWeights';
-    sacf=sacf.*PressnitzerWeights';
+    LP_SACF=LP_SACF.*PressnitzerWeights';
+    SACF=SACF.*PressnitzerWeights';
 end
 
 % wrap up
-method.acfLags=lags;
-method.filteredSACFdt=dt;
-
-boundaryValue{1}=acf(:,end-nLags+1:end);
-boundaryValue{2}=P(:,end);
+% BoundaryValue is legacy programming used in segmented model (keep)
+ACFboundaryValue{1}=ACF(:,end-nLags+1:end);
+ACFboundaryValue{2}=LP_SACF(:,end);
 % save signal buffer for next segment
-boundaryValue{3} = inputSignalMatrix(:, end-max(lagPointers)+1 : end);
-
-method.displaydt=method.filteredSACFdt;
-
-% if ~isfield(params, 'plotUnflteredSACF'), params.plotUnflteredSACF=0; end
-% if method.plotGraphs
-%     method.plotUnflteredSACF=params.plotUnflteredSACF;
-%     if ~method.plotUnflteredSACF
-%         method=filteredSACFPlot(P,method);
-%     else
-%         method=filteredSACFPlot(SACF,method);
-%     end
-% end
-
-
-% ------------------------------------------------  plotting ACFs
-function cascadePlot(toPlot, lags, BFs)
-% % useful code
-[nChannels nLags]=size(toPlot);
-
-% cunning code to represent channels as parallel lines
-[nRows nCols]=size(toPlot);
-if nChannels>1
-    % max(toPlot) defines the spacing between lines
-    a=max(max(toPlot))*(0:nRows-1)';
-    % a is the height to be added to each channel
-    peakGain=10;
-    % peakGain emphasises the peak height
-    x=peakGain*toPlot+repmat(a,1,nCols);
-    x=nRows*x/max(max(x));
-else
-    x=toPlot;                            % used when only the stimulus is returned
-end
-plot(lags, x','k')
-ylim([0 nRows])
-
+ACFboundaryValue{3} = inputSignalMatrix(:, end-max(lagPointers)+1 : end);
--- a/MAP/old MAP files/MAP1_14AP.m	Thu Oct 06 15:43:20 2011 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,1254 +0,0 @@
-
-function  MAP1_14AP(inputSignal, sampleRate, BFlist, MAPparamsName, ...
-    AN_spikesOrProbability, paramChanges)
-% To test this function use test_MAP1_14 in this folder
-%
-% All arguments are mandatory.
-%
-%  BFlist is a vector of BFs but can be '-1' to allow MAPparams to choose
-%  MAPparamsName='Normal';          % source of model parameters
-%  AN_spikesOrProbability='spikes'; % or 'probability'
-%  paramChanges is a cell array of strings that can be used to make last
-%   minute parameter changes, e.g., to simulate OHC loss
-%  e.g.  paramChanges{1}= 'DRNLParams.a=0;'; % disable OHCs
-%  e.g.  paramchanges={};                    % no changes
-% The model parameters are established in the MAPparams<***> file
-%  and stored as global
-
-restorePath=path;
-addpath (['..' filesep 'parameterStore'])
-
-
-CONVOLUTION_CHANGE_TEST = 0; %for debug
-
-
-global OMEParams DRNLParams IHC_cilia_RPParams IHCpreSynapseParams
-global AN_IHCsynapseParams MacGregorParams MacGregorMultiParams
-
-% All of the results of this function are stored as global
-global dt ANdt  savedBFlist saveAN_spikesOrProbability saveMAPparamsName...
-    savedInputSignal OMEextEarPressure TMoutput OMEoutput ARattenuation ...
-    DRNLoutput IHC_cilia_output IHCrestingCiliaCond IHCrestingV...
-    IHCoutput ANprobRateOutput ANoutput savePavailable tauCas  ...
-    CNoutput  ICoutput ICmembraneOutput ICfiberTypeRates MOCattenuation
-
-% Normally only ICoutput(logical spike matrix) or ANprobRateOutput will be
-% needed by the user; so the following will suffice
-%   global ANdt ICoutput ANprobRateOutput
-
-% Note that sampleRate has not changed from the original function call and
-%  ANprobRateOutput is sampled at this rate
-% However ANoutput, CNoutput and IC output are stored as logical
-%  'spike' matrices using a lower sample rate (see ANdt).
-
-% When AN_spikesOrProbability is set to probability,
-%  no spike matrices are computed.
-% When AN_spikesOrProbability is set to 'spikes',
-%  no probability output is computed
-
-% Efferent control variables are ARattenuation and MOCattenuation
-%  These are scalars between 1 (no attenuation) and 0.
-%  They are represented with dt=1/sampleRate (not ANdt)
-%  They are computed using either AN probability rate output
-%   or IC (spikes) output as approrpriate.
-% AR is computed using across channel activity
-% MOC is computed on a within-channel basis.
-
-if nargin<1
-    error(' MAP1_14 is not a script but a function that must be called')
-end
-
-if nargin<6
-    paramChanges=[];
-end
-% Read parameters from MAPparams<***> file in 'parameterStore' folder
-% Beware, 'BFlist=-1' is a legitimate argument for MAPparams<>
-%  It means that the calling program allows MAPparams to specify the list
-cmd=['method=MAPparams' MAPparamsName ...
-    '(BFlist, sampleRate, 0, paramChanges);'];
-eval(cmd);
-BFlist=DRNLParams.nonlinCFs;
-
-% save as global for later plotting if required
-savedBFlist=BFlist;
-saveAN_spikesOrProbability=AN_spikesOrProbability;
-saveMAPparamsName=MAPparamsName;
-
-dt=1/sampleRate;
-duration=length(inputSignal)/sampleRate;
-% segmentDuration is specified in parameter file (must be >efferent delay)
-segmentDuration=method.segmentDuration;
-segmentLength=round(segmentDuration/ dt);
-segmentTime=dt*(1:segmentLength); % used in debugging plots
-
-% all spiking activity is computed using longer epochs
-ANspeedUpFactor=AN_IHCsynapseParams.ANspeedUpFactor;  % e.g.5 times
-
-% inputSignal must be  row vector
-[r c]=size(inputSignal);
-if r>c, inputSignal=inputSignal'; end       % transpose
-% ignore stereo signals
-inputSignal=inputSignal(1,:);               % drop any second channel
-savedInputSignal=inputSignal;
-
-% Segment the signal
-% The sgment length is given but the signal length must be adjusted to be a
-% multiple of both the segment length and the reduced segmentlength
-[nSignalRows signalLength]=size(inputSignal);
-segmentLength=ceil(segmentLength/ANspeedUpFactor)*ANspeedUpFactor;
-% Make the signal length a whole multiple of the segment length
-nSignalSegments=ceil(signalLength/segmentLength);
-padSize=nSignalSegments*segmentLength-signalLength;
-pad=zeros(nSignalRows,padSize);
-inputSignal=[inputSignal pad];
-[ignore signalLength]=size(inputSignal);
-
-% AN (spikes) is computed at a lower sample rate when spikes required
-%  so it has a reduced segment length (see 'ANspeeUpFactor' above)
-% AN CN and IC all use this sample interval
-ANdt=dt*ANspeedUpFactor;
-reducedSegmentLength=round(segmentLength/ANspeedUpFactor);
-reducedSignalLength= round(signalLength/ANspeedUpFactor);
-
-%% Initialise with respect to each stage before computing
-%  by allocating memory,
-%  by computing constants
-%  by establishing easy to read variable names
-% The computations are made in segments and boundary conditions must
-%  be established and stored. These are found in variables with
-%  'boundary' or 'bndry' in the name
-
-%% OME ---
-% external ear resonances
-OMEexternalResonanceFilters=OMEParams.externalResonanceFilters;
-[nOMEExtFilters c]=size(OMEexternalResonanceFilters);
-% details of external (outer ear) resonances
-OMEgaindBs=OMEexternalResonanceFilters(:,1);
-OMEgainScalars=10.^(OMEgaindBs/20);
-OMEfilterOrder=OMEexternalResonanceFilters(:,2);
-OMElowerCutOff=OMEexternalResonanceFilters(:,3);
-OMEupperCutOff=OMEexternalResonanceFilters(:,4);
-% external resonance coefficients
-ExtFilter_b=cell(nOMEExtFilters,1);
-ExtFilter_a=cell(nOMEExtFilters,1);
-for idx=1:nOMEExtFilters
-    Nyquist=sampleRate/2;
-    [b, a] = butter(OMEfilterOrder(idx), ...
-        [OMElowerCutOff(idx) OMEupperCutOff(idx)]...
-        /Nyquist);
-    ExtFilter_b{idx}=b;
-    ExtFilter_a{idx}=a;
-end
-OMEExtFilterBndry=cell(2,1);
-OMEextEarPressure=zeros(1,signalLength); % pressure at tympanic membrane
-
-% pressure to velocity conversion using smoothing filter (50 Hz cutoff)
-tau=1/(2*pi*50);
-a1=dt/tau-1; a0=1;
-b0=1+ a1;
-TMdisp_b=b0; TMdisp_a=[a0 a1];
-% figure(9), freqz(TMdisp_b, TMdisp_a)
-OME_TMdisplacementBndry=[];
-
-% OME high pass (simulates poor low frequency stapes response)
-OMEhighPassHighCutOff=OMEParams.OMEstapesLPcutoff;
-Nyquist=sampleRate/2;
-[stapesDisp_b,stapesDisp_a] = butter(1, OMEhighPassHighCutOff/Nyquist, 'high');
-% figure(10), freqz(stapesDisp_b, stapesDisp_a)
-
-OMEhighPassBndry=[];
-
-% OMEampStapes might be reducdant (use OMEParams.stapesScalar)
-stapesScalar= OMEParams.stapesScalar;
-
-% Acoustic reflex
-efferentDelayPts=round(OMEParams.ARdelay/dt);
-% smoothing filter
-a1=dt/OMEParams.ARtau-1; a0=1;
-b0=1+ a1;
-ARfilt_b=b0; ARfilt_a=[a0 a1];
-
-ARattenuation=ones(1,signalLength);
-ARrateThreshold=OMEParams.ARrateThreshold; % may not be used
-ARrateToAttenuationFactor=OMEParams.rateToAttenuationFactor;
-ARrateToAttenuationFactorProb=OMEParams.rateToAttenuationFactorProb;
-ARboundary=[];
-ARboundaryProb=0;
-
-% save complete OME record (stapes displacement)
-OMEoutput=zeros(1,signalLength);
-TMoutput=zeros(1,signalLength);
-
-%% BM ---
-% BM is represented as a list of locations identified by BF
-DRNL_BFs=BFlist;
-nBFs= length(DRNL_BFs);
-
-% DRNLchannelParameters=DRNLParams.channelParameters;
-DRNLresponse= zeros(nBFs, segmentLength);
-
-MOCrateToAttenuationFactor=DRNLParams.rateToAttenuationFactor;
-rateToAttenuationFactorProb=DRNLParams.rateToAttenuationFactorProb;
-MOCrateThresholdProb=DRNLParams.MOCrateThresholdProb;
-
-% smoothing filter for MOC
-a1=dt/DRNLParams.MOCtau-1; a0=1;
-b0=1+ a1;
-MOCfilt_b=b0; MOCfilt_a=[a0 a1];
-% figure(9), freqz(stapesDisp_b, stapesDisp_a)
-MOCboundary=cell(nBFs,1);
-MOCprobBoundary=cell(nBFs,1);
-
-MOCattSegment=zeros(nBFs,reducedSegmentLength);
-MOCattenuation=ones(nBFs,signalLength);
-
-if DRNLParams.a>0
-    DRNLcompressionThreshold=10^((1/(1-DRNLParams.c))* ...
-    log10(DRNLParams.b/DRNLParams.a));
-else
-    DRNLcompressionThreshold=inf;
-end
-
-DRNLlinearOrder= DRNLParams.linOrder;
-DRNLnonlinearOrder= DRNLParams.nonlinOrder;
-
-DRNLa=DRNLParams.a;
-DRNLb=DRNLParams.b;
-DRNLc=DRNLParams.c;
-linGAIN=DRNLParams.g;
-%
-% gammatone filter coefficients for linear pathway
-bw=DRNLParams.linBWs';
-phi = 2 * pi * bw * dt;
-cf=DRNLParams.linCFs';
-theta = 2 * pi * cf * dt;
-cos_theta = cos(theta);
-sin_theta = sin(theta);
-alpha = -exp(-phi).* cos_theta;
-b0 = ones(nBFs,1);
-b1 = 2 * alpha;
-b2 = exp(-2 * phi);
-z1 = (1 + alpha .* cos_theta) - (alpha .* sin_theta) * i;
-z2 = (1 + b1 .* cos_theta) - (b1 .* sin_theta) * i;
-z3 = (b2 .* cos(2 * theta)) - (b2 .* sin(2 * theta)) * i;
-tf = (z2 + z3) ./ z1;
-a0 = abs(tf);
-a1 = alpha .* a0;
-GTlin_a = [b0, b1, b2];
-GTlin_b = [a0, a1];
-GTlinOrder=DRNLlinearOrder;
-GTlinBdry=cell(nBFs,GTlinOrder);
-
-% nonlinear gammatone filter coefficients 
-bw=DRNLParams.nlBWs';
-phi = 2 * pi * bw * dt;
-cf=DRNLParams.nonlinCFs';
-theta = 2 * pi * cf * dt;
-cos_theta = cos(theta);
-sin_theta = sin(theta);
-alpha = -exp(-phi).* cos_theta;
-b0 = ones(nBFs,1);
-b1 = 2 * alpha;
-b2 = exp(-2 * phi);
-z1 = (1 + alpha .* cos_theta) - (alpha .* sin_theta) * i;
-z2 = (1 + b1 .* cos_theta) - (b1 .* sin_theta) * i;
-z3 = (b2 .* cos(2 * theta)) - (b2 .* sin(2 * theta)) * i;
-tf = (z2 + z3) ./ z1;
-a0 = abs(tf);
-a1 = alpha .* a0;
-GTnonlin_a = [b0, b1, b2];
-GTnonlin_b = [a0, a1];
-GTnonlinOrder=DRNLnonlinearOrder;
-GTnonlinBdry1=cell(nBFs, GTnonlinOrder);
-GTnonlinBdry2=cell(nBFs, GTnonlinOrder);
-
-% complete BM record (BM displacement)
-DRNLoutput=zeros(nBFs, signalLength);
-
-
-%% IHC ---
-% IHC cilia activity and receptor potential
-% viscous coupling between BM and stereocilia displacement
-% Nyquist=sampleRate/2;
-% IHCcutoff=1/(2*pi*IHC_cilia_RPParams.tc);
-% [IHCciliaFilter_b,IHCciliaFilter_a]=...
-%     butter(1, IHCcutoff/Nyquist, 'high');
-a1=dt/IHC_cilia_RPParams.tc-1; a0=1;
-b0=1+ a1;
-% high pass (i.e. low pass reversed)
-IHCciliaFilter_b=[a0 a1]; IHCciliaFilter_a=b0;
-% figure(9), freqz(IHCciliaFilter_b, IHCciliaFilter_a)
-
-IHCciliaBndry=cell(nBFs,1);
-
-% IHC apical conductance (Boltzman function)
-IHC_C= IHC_cilia_RPParams.C;
-IHCu0= IHC_cilia_RPParams.u0;
-IHCu1= IHC_cilia_RPParams.u1;
-IHCs0= IHC_cilia_RPParams.s0;
-IHCs1= IHC_cilia_RPParams.s1;
-IHCGmax= IHC_cilia_RPParams.Gmax;
-IHCGa= IHC_cilia_RPParams.Ga; % (leakage)
-
-IHCGu0 = IHCGa+IHCGmax./(1+exp(IHCu0/IHCs0).*(1+exp(IHCu1/IHCs1)));
-IHCrestingCiliaCond=IHCGu0;
-
-% Receptor potential
-IHC_Cab= IHC_cilia_RPParams.Cab;
-IHC_Gk= IHC_cilia_RPParams.Gk;
-IHC_Et= IHC_cilia_RPParams.Et;
-IHC_Ek= IHC_cilia_RPParams.Ek;
-IHC_Ekp= IHC_Ek+IHC_Et*IHC_cilia_RPParams.Rpc;
-
-IHCrestingV= (IHC_Gk*IHC_Ekp+IHCGu0*IHC_Et)/(IHCGu0+IHC_Gk);
-
-IHC_Vnow= IHCrestingV*ones(nBFs,1); % initial voltage
-IHC_RP= zeros(nBFs,segmentLength);
-
-% complete record of IHC receptor potential (V)
-IHCciliaDisplacement= zeros(nBFs,segmentLength);
-IHCoutput= zeros(nBFs,signalLength);
-IHC_cilia_output= zeros(nBFs,signalLength);
-
-
-%% pre-synapse ---
-% Each BF is replicated using a different fiber type to make a 'channel'
-% The number of channels is nBFs x nANfiberTypes
-% Fiber types are specified in terms of tauCa
-nANfiberTypes= length(IHCpreSynapseParams.tauCa);
-tauCas= IHCpreSynapseParams.tauCa;
-nANchannels= nANfiberTypes*nBFs;
-synapticCa= zeros(nANchannels,segmentLength);
-
-% Calcium control (more calcium, greater release rate)
-ECa=IHCpreSynapseParams.ECa;
-gamma=IHCpreSynapseParams.gamma;
-beta=IHCpreSynapseParams.beta;
-tauM=IHCpreSynapseParams.tauM;
-mICa=zeros(nANchannels,segmentLength);
-GmaxCa=IHCpreSynapseParams.GmaxCa;
-synapse_z= IHCpreSynapseParams.z;
-synapse_power=IHCpreSynapseParams.power;
-
-% tauCa vector is established across channels to allow vectorization
-%  (one tauCa per channel). Do not confuse with tauCas (one pre fiber type)
-tauCa=repmat(tauCas, nBFs,1);
-tauCa=reshape(tauCa, nANchannels, 1);
-
-% presynapse startup values (vectors, length:nANchannels)
-% proportion (0 - 1) of Ca channels open at IHCrestingV
-mICaCurrent=((1+beta^-1 * exp(-gamma*IHCrestingV))^-1)...
-    *ones(nBFs*nANfiberTypes,1);
-% corresponding startup currents
-ICaCurrent= (GmaxCa*mICaCurrent.^3) * (IHCrestingV-ECa);
-CaCurrent= ICaCurrent.*tauCa;
-
-% vesicle release rate at startup (one per channel)
-% kt0 is used only at initialisation
-kt0= -synapse_z * CaCurrent.^synapse_power;
-
-
-%% AN ---
-% each row of the AN matrices represents one AN fiber
-% The results computed either for probabiities *or* for spikes (not both)
-% Spikes are necessary if CN and IC are to be computed
-nFibersPerChannel= AN_IHCsynapseParams.numFibers;
-nANfibers= nANchannels*nFibersPerChannel;
-AN_refractory_period= AN_IHCsynapseParams.refractory_period;
-
-y=AN_IHCsynapseParams.y;
-l=AN_IHCsynapseParams.l;
-x=AN_IHCsynapseParams.x;
-r=AN_IHCsynapseParams.r;
-M=round(AN_IHCsynapseParams.M);
-
-% probability            (NB initial 'P' on everything)
-PAN_ydt = repmat(AN_IHCsynapseParams.y*dt, nANchannels,1);
-PAN_ldt = repmat(AN_IHCsynapseParams.l*dt, nANchannels,1);
-PAN_xdt = repmat(AN_IHCsynapseParams.x*dt, nANchannels,1);
-PAN_rdt = repmat(AN_IHCsynapseParams.r*dt, nANchannels,1);
-PAN_rdt_plus_ldt = PAN_rdt + PAN_ldt;
-PAN_M=round(AN_IHCsynapseParams.M);
-
-% compute starting values
-Pcleft    = kt0* y* M ./ (y*(l+r)+ kt0* l);
-Pavailable    = Pcleft*(l+r)./kt0;
-Preprocess    = Pcleft*r/x; % canbe fractional
-
-ANprobability=zeros(nANchannels,segmentLength);
-ANprobRateOutput=zeros(nANchannels,signalLength);
-lengthAbsRefractoryP= round(AN_refractory_period/dt);
-% special variables for monitoring synaptic cleft (specialists only)
-savePavailableSeg=zeros(nANchannels,segmentLength);
-savePavailable=zeros(nANchannels,signalLength);
-
-% spikes     % !  !  !    ! !        !   !  !
-lengthAbsRefractory= round(AN_refractory_period/ANdt);
-
-AN_ydt= repmat(AN_IHCsynapseParams.y*ANdt, nANfibers,1);
-AN_ldt= repmat(AN_IHCsynapseParams.l*ANdt, nANfibers,1);
-AN_xdt= repmat(AN_IHCsynapseParams.x*ANdt, nANfibers,1);
-AN_rdt= repmat(AN_IHCsynapseParams.r*ANdt, nANfibers,1);
-AN_rdt_plus_ldt= AN_rdt + AN_ldt;
-AN_M= round(AN_IHCsynapseParams.M);
-
-% kt0  is initial release rate
-% Establish as a vector (length=channel x number of fibers)
-kt0= repmat(kt0', nFibersPerChannel, 1);
-kt0=reshape(kt0, nANfibers,1);
-
-% starting values for reservoirs
-AN_cleft    = kt0* y* M ./ (y*(l+r)+ kt0* l);
-AN_available    = round(AN_cleft*(l+r)./kt0); %must be integer
-AN_reprocess    = AN_cleft*r/x;
-
-% output is in a logical array spikes = 1/ 0.
-ANspikes= false(nANfibers,reducedSegmentLength);
-ANoutput= false(nANfibers,reducedSignalLength);
-
-
-%% CN (first brain stem nucleus - could be any subdivision of CN)
-% Input to a CN neuorn is a random selection of AN fibers within a channel
-%  The number of AN fibers used is ANfibersFanInToCN
-% CNtauGk (Potassium time constant) determines the rate of firing of
-%  the unit when driven hard by a DC input (not normally >350 sp/s)
-% If there is more than one value, everything is replicated accordingly
-
-ANavailableFibersPerChan=AN_IHCsynapseParams.numFibers;
-ANfibersFanInToCN=MacGregorMultiParams.fibersPerNeuron;
-
-CNtauGk=MacGregorMultiParams.tauGk; % row vector of CN types (by tauGk)
-nCNtauGk=length(CNtauGk);
-
-% the total number of 'channels' is now greater
-nCNchannels=nANchannels*nCNtauGk;
-
-nCNneuronsPerChannel=MacGregorMultiParams.nNeuronsPerBF;
-tauGk=repmat(CNtauGk, nCNneuronsPerChannel,1);
-tauGk=reshape(tauGk,nCNneuronsPerChannel*nCNtauGk,1);
-
-% Now the number of neurons has been increased
-nCNneurons=nCNneuronsPerChannel*nCNchannels;
-CNmembranePotential=zeros(nCNneurons,reducedSegmentLength);
-
-% establish which ANfibers (by name) feed into which CN nuerons
-CNinputfiberLists=zeros(nANchannels*nCNneuronsPerChannel, ANfibersFanInToCN);
-unitNo=1;
-for ch=1:nANchannels
-    % Each channel contains a number of units =length(listOfFanInValues)
-    for idx=1:nCNneuronsPerChannel
-        for idx2=1:nCNtauGk
-            fibersUsed=(ch-1)*ANavailableFibersPerChan + ...
-                ceil(rand(1,ANfibersFanInToCN)* ANavailableFibersPerChan);
-            CNinputfiberLists(unitNo,:)=fibersUsed;
-            unitNo=unitNo+1;
-        end
-    end
-end
-
-% input to CN units
-AN_PSTH=zeros(nCNneurons,reducedSegmentLength);
-
-% Generate CNalphaFunction function
-%  by which spikes are converted to post-synaptic currents
-CNdendriteLPfreq= MacGregorMultiParams.dendriteLPfreq;
-CNcurrentPerSpike=MacGregorMultiParams.currentPerSpike;
-CNspikeToCurrentTau=1/(2*pi*CNdendriteLPfreq);
-t=ANdt:ANdt:5*CNspikeToCurrentTau;
-CNalphaFunction= (1 / ...
-    CNspikeToCurrentTau)*t.*exp(-t /CNspikeToCurrentTau);
-CNalphaFunction=CNalphaFunction*CNcurrentPerSpike;
-
-% figure(98), plot(t,CNalphaFunction)
-% working memory for implementing convolution
-
-CNcurrentTemp=...
-    zeros(nCNneurons,reducedSegmentLength+length(CNalphaFunction)-1);
-% trailing alphas are parts of humps carried forward to the next segment
-CNtrailingAlphas=zeros(nCNneurons,length(CNalphaFunction));
-
-CN_tauM=MacGregorMultiParams.tauM;
-CN_tauTh=MacGregorMultiParams.tauTh;
-CN_cap=MacGregorMultiParams.Cap;
-CN_c=MacGregorMultiParams.c;
-CN_b=MacGregorMultiParams.dGkSpike;
-CN_Ek=MacGregorMultiParams.Ek;
-CN_Eb= MacGregorMultiParams.Eb;
-CN_Er=MacGregorMultiParams.Er;
-CN_Th0= MacGregorMultiParams.Th0;
-CN_E= zeros(nCNneurons,1);
-CN_Gk= zeros(nCNneurons,1);
-CN_Th= MacGregorMultiParams.Th0*ones(nCNneurons,1);
-CN_Eb=CN_Eb.*ones(nCNneurons,1);
-CN_Er=CN_Er.*ones(nCNneurons,1);
-CNtimeSinceLastSpike=zeros(nCNneurons,1);
-% tauGk is the main distinction between neurons
-%  in fact they are all the same in the standard model
-tauGk=repmat(tauGk,nANchannels,1);
-
-CNoutput=false(nCNneurons,reducedSignalLength);
-
-
-%% MacGregor (IC - second nucleus) --------
-nICcells=nANchannels*nCNtauGk;  % one cell per channel
-CN_PSTH=zeros(nICcells ,reducedSegmentLength);
-
-ICspikeWidth=0.00015;   % this may need revisiting
-epochsPerSpike=round(ICspikeWidth/ANdt);
-if epochsPerSpike<1
-    error(['MacGregorMulti: sample rate too low to support ' ...
-        num2str(ICspikeWidth*1e6) '  microsec spikes']);
-end
-
-% short names
-IC_tauM=MacGregorParams.tauM;
-IC_tauGk=MacGregorParams.tauGk;
-IC_tauTh=MacGregorParams.tauTh;
-IC_cap=MacGregorParams.Cap;
-IC_c=MacGregorParams.c;
-IC_b=MacGregorParams.dGkSpike;
-IC_Th0=MacGregorParams.Th0;
-IC_Ek=MacGregorParams.Ek;
-IC_Eb= MacGregorParams.Eb;
-IC_Er=MacGregorParams.Er;
-
-IC_E=zeros(nICcells,1);
-IC_Gk=zeros(nICcells,1);
-IC_Th=IC_Th0*ones(nICcells,1);
-
-% Dendritic filtering, all spikes are replaced by CNalphaFunction functions
-ICdendriteLPfreq= MacGregorParams.dendriteLPfreq;
-ICcurrentPerSpike=MacGregorParams.currentPerSpike;
-ICspikeToCurrentTau=1/(2*pi*ICdendriteLPfreq);
-t=ANdt:ANdt:3*ICspikeToCurrentTau;
-IC_CNalphaFunction= (ICcurrentPerSpike / ...
-    ICspikeToCurrentTau)*t.*exp(-t / ICspikeToCurrentTau);
-% figure(98), plot(t,IC_CNalphaFunction)
-
-% working space for implementing alpha function
-ICcurrentTemp=...
-    zeros(nICcells,reducedSegmentLength+length(IC_CNalphaFunction)-1);
-ICtrailingAlphas=zeros(nICcells, length(IC_CNalphaFunction));
-
-ICfiberTypeRates=zeros(nANfiberTypes,reducedSignalLength);
-ICoutput=false(nICcells,reducedSignalLength);
-
-ICmembranePotential=zeros(nICcells,reducedSegmentLength);
-ICmembraneOutput=zeros(nICcells,signalLength);
-
-
-%% Main program %%  %%  %%  %%  %%  %%  %%  %%  %%  %%  %%  %%  %%  %%
-
-%  Compute the entire model for each segment
-segmentStartPTR=1;
-reducedSegmentPTR=1; % when sampling rate is reduced
-while segmentStartPTR<signalLength
-    segmentEndPTR=segmentStartPTR+segmentLength-1;
-    % shorter segments after speed up.
-    shorterSegmentEndPTR=reducedSegmentPTR+reducedSegmentLength-1;
-
-    inputPressureSegment=inputSignal...
-        (:,segmentStartPTR:segmentStartPTR+segmentLength-1);
-
-    % segment debugging plots
-    % figure(98)
-    % plot(segmentTime,inputPressureSegment), title('signalSegment')
-
-
-    % OME ----------------------
-
-    % OME Stage 1: external resonances. Add to inputSignal pressure wave
-    y=inputPressureSegment;
-    for n=1:nOMEExtFilters
-        % any number of resonances can be used
-        [x  OMEExtFilterBndry{n}] = ...
-            filter(ExtFilter_b{n},ExtFilter_a{n},...
-            inputPressureSegment, OMEExtFilterBndry{n});
-        x= x* OMEgainScalars(n);
-        % This is a parallel resonance so add it
-        y=y+x;
-    end
-    inputPressureSegment=y;
-    OMEextEarPressure(segmentStartPTR:segmentEndPTR)= inputPressureSegment;
-    
-    % OME stage 2: convert input pressure (velocity) to
-    %  tympanic membrane(TM) displacement using low pass filter
-    [TMdisplacementSegment  OME_TMdisplacementBndry] = ...
-        filter(TMdisp_b,TMdisp_a,inputPressureSegment, ...
-        OME_TMdisplacementBndry);
-    % and save it
-    TMoutput(segmentStartPTR:segmentEndPTR)= TMdisplacementSegment;
-
-    % OME stage 3: middle ear high pass effect to simulate stapes inertia
-    [stapesDisplacement  OMEhighPassBndry] = ...
-        filter(stapesDisp_b,stapesDisp_a,TMdisplacementSegment, ...
-        OMEhighPassBndry);
-
-    % OME stage 4:  apply stapes scalar
-    stapesDisplacement=stapesDisplacement*stapesScalar;
-
-    % OME stage 5:    acoustic reflex stapes attenuation
-    %  Attenuate the TM response using feedback from LSR fiber activity
-    if segmentStartPTR>efferentDelayPts
-        stapesDisplacement= stapesDisplacement.*...
-            ARattenuation(segmentStartPTR-efferentDelayPts:...
-            segmentEndPTR-efferentDelayPts);
-    end
-
-    % segment debugging plots
-    % figure(98)
-    % plot(segmentTime, stapesDisplacement), title ('stapesDisplacement')
-
-    % and save
-    OMEoutput(segmentStartPTR:segmentEndPTR)= stapesDisplacement;
-
-
-    %% BM ------------------------------
-    % Each location is computed separately
-    for BFno=1:nBFs
-
-        %            *linear* path
-        linOutput = stapesDisplacement * linGAIN;  % linear gain
-        for order = 1 : GTlinOrder
-            [linOutput GTlinBdry{BFno,order}] = ...
-                filter(GTlin_b(BFno,:), GTlin_a(BFno,:), linOutput, GTlinBdry{BFno,order});
-        end
-
-        %           *nonLinear* path
-        % efferent attenuation (0 <> 1)
-        if segmentStartPTR>efferentDelayPts
-            MOC=MOCattenuation(BFno, segmentStartPTR-efferentDelayPts:...
-                segmentEndPTR-efferentDelayPts);
-        else    % no MOC available yet
-            MOC=ones(1, segmentLength);
-        end
-        % apply MOC to nonlinear input function       
-        nonlinOutput=stapesDisplacement.* MOC;
-
-        %       first gammatone filter (nonlin path)
-        for order = 1 : GTnonlinOrder
-            [nonlinOutput GTnonlinBdry1{BFno,order}] = ...
-                filter(GTnonlin_b(BFno,:), GTnonlin_a(BFno,:), ...
-                nonlinOutput, GTnonlinBdry1{BFno,order});
-        end
-        %       broken stick instantaneous compression
-        y= nonlinOutput.* DRNLa;  % linear section.
-        % compress parts of the signal above the compression threshold
-        abs_x = abs(nonlinOutput);
-        idx=find(abs_x>DRNLcompressionThreshold);
-        if ~isempty(idx)>0
-            y(idx)=sign(y(idx)).* (DRNLb*abs_x(idx).^DRNLc);
-        end
-        nonlinOutput=y;
-
-        %       second filter removes distortion products
-        for order = 1 : GTnonlinOrder
-            [ nonlinOutput GTnonlinBdry2{BFno,order}] = ...
-                filter(GTnonlin_b(BFno,:), GTnonlin_a(BFno,:), ...
-                nonlinOutput, GTnonlinBdry2{BFno,order});
-        end
-
-        %  combine the two paths to give the DRNL displacement
-        DRNLresponse(BFno,:)=linOutput+nonlinOutput;
-    end % BF
-
-    % segment debugging plots
-    % figure(98)
-    %     if size(DRNLresponse,1)>3
-    %         imagesc(DRNLresponse)  % matrix display
-    %         title('DRNLresponse'); % single or double channel response
-    %     else
-    %         plot(segmentTime, DRNLresponse)
-    %     end
-
-    % and save it
-    DRNLoutput(:, segmentStartPTR:segmentEndPTR)= DRNLresponse;
-
-
-    %% IHC ------------------------------------
-    %  BM displacement to IHCciliaDisplacement is  a high-pass filter
-    %   because of viscous coupling
-    for idx=1:nBFs
-        [IHCciliaDisplacement(idx,:)  IHCciliaBndry{idx}] = ...
-            filter(IHCciliaFilter_b,IHCciliaFilter_a, ...
-            DRNLresponse(idx,:), IHCciliaBndry{idx});
-    end
-    
-    % apply scalar
-    IHCciliaDisplacement=IHCciliaDisplacement* IHC_C;
-
-    % and save it
-    IHC_cilia_output(:,segmentStartPTR:segmentStartPTR+segmentLength-1)=...
-        IHCciliaDisplacement;
-
-    % compute apical conductance
-    G=IHCGmax./(1+exp(-(IHCciliaDisplacement-IHCu0)/IHCs0).*...
-        (1+exp(-(IHCciliaDisplacement-IHCu1)/IHCs1)));
-    Gu=G + IHCGa;
-
-    % Compute receptor potential
-    for idx=1:segmentLength
-        IHC_Vnow=IHC_Vnow+ (-Gu(:, idx).*(IHC_Vnow-IHC_Et)-...
-            IHC_Gk*(IHC_Vnow-IHC_Ekp))*  dt/IHC_Cab;
-        IHC_RP(:,idx)=IHC_Vnow;
-    end
-
-    % segment debugging plots
-    %     if size(IHC_RP,1)>3
-    %         surf(IHC_RP), shading interp, title('IHC_RP')
-    %     else
-    %         plot(segmentTime, IHC_RP)
-    %     end
-
-    % and save it
-    IHCoutput(:, segmentStartPTR:segmentStartPTR+segmentLength-1)=IHC_RP;
-
-
-    %% synapse -----------------------------
-    % Compute the vesicle release rate for each fiber type at each BF
-    % replicate IHC_RP for each fiber type
-    Vsynapse=repmat(IHC_RP, nANfiberTypes,1);
-
-    % look-up table of target fraction channels open for a given IHC_RP
-    mICaINF=    1./( 1 + exp(-gamma  * Vsynapse)  /beta);
-    % fraction of channel open - apply time constant
-    for idx=1:segmentLength
-        % mICaINF is the current 'target' value of mICa
-        mICaCurrent=mICaCurrent+(mICaINF(:,idx)-mICaCurrent)*dt./tauM;
-        mICa(:,idx)=mICaCurrent;
-    end
-
-    ICa=   (GmaxCa* mICa.^3) .* (Vsynapse- ECa);
-
-    for idx=1:segmentLength
-        CaCurrent=CaCurrent +  ICa(:,idx)*dt - CaCurrent*dt./tauCa;
-        synapticCa(:,idx)=CaCurrent;
-    end
-    synapticCa=-synapticCa; % treat IHCpreSynapseParams as positive substance
-
-    % NB vesicleReleaseRate is /s and is independent of dt
-    vesicleReleaseRate = synapse_z * synapticCa.^synapse_power; % rate
-
-    % segment debugging plots
-    %     if size(vesicleReleaseRate,1)>3
-    %         surf(vesicleReleaseRate), shading interp, title('vesicleReleaseRate')
-    %     else
-    %         plot(segmentTime, vesicleReleaseRate)
-    %     end
-
-
-    %% AN
-    switch AN_spikesOrProbability
-        case 'probability'
-            % No refractory effect is applied
-            for t = 1:segmentLength;
-                M_Pq=PAN_M-Pavailable;
-                M_Pq(M_Pq<0)=0;
-                Preplenish = M_Pq .* PAN_ydt;
-                Pejected = Pavailable.* vesicleReleaseRate(:,t)*dt;
-                Preprocessed = M_Pq.*Preprocess.* PAN_xdt;
-
-                ANprobability(:,t)= min(Pejected,1);
-                reuptakeandlost= PAN_rdt_plus_ldt .* Pcleft;
-                reuptake= PAN_rdt.* Pcleft;
-
-                Pavailable= Pavailable+ Preplenish- Pejected+ Preprocessed;
-                Pcleft= Pcleft + Pejected - reuptakeandlost;
-                Preprocess= Preprocess + reuptake - Preprocessed;
-                Pavailable(Pavailable<0)=0;
-                savePavailableSeg(:,t)=Pavailable;    % synapse tracking
-            end
-            % and save it as *rate*
-            ANrate=ANprobability/dt;
-            ANprobRateOutput(:, segmentStartPTR:...
-                segmentStartPTR+segmentLength-1)=  ANrate;
-            % monitor synapse contents (only sometimes used)
-            savePavailable(:, segmentStartPTR:segmentStartPTR+segmentLength-1)=...
-                savePavailableSeg;
-
-            % Estimate efferent effects. ARattenuation (0 <> 1)
-            %  acoustic reflex
-            [r c]=size(ANrate);
-            if r>nBFs % Only if LSR fibers are computed
-                ARAttSeg=mean(ANrate(1:nBFs,:),1); %LSR channels are 1:nBF
-                % smooth
-                [ARAttSeg, ARboundaryProb] = ...
-                    filter(ARfilt_b, ARfilt_a, ARAttSeg, ARboundaryProb);
-                ARAttSeg=ARAttSeg-ARrateThreshold;
-                ARAttSeg(ARAttSeg<0)=0;   % prevent negative strengths
-                ARattenuation(segmentStartPTR:segmentEndPTR)=...
-                    (1-ARrateToAttenuationFactorProb.* ARAttSeg);
-            end
-            %             plot(ARattenuation)
-
-            % MOC attenuation
-            % within-channel HSR response only
-            HSRbegins=nBFs*(nANfiberTypes-1)+1;
-            rates=ANrate(HSRbegins:end,:);
-            if rateToAttenuationFactorProb<0
-                % negative factor implies a fixed attenuation
-                MOCattenuation(:,segmentStartPTR:segmentEndPTR)= ...
-                    ones(size(rates))* -rateToAttenuationFactorProb;
-            else
-                for idx=1:nBFs
-                    [smoothedRates, MOCprobBoundary{idx}] = ...
-                        filter(MOCfilt_b, MOCfilt_a, rates(idx,:), ...
-                        MOCprobBoundary{idx});
-                    smoothedRates=smoothedRates-MOCrateThresholdProb;
-                    smoothedRates(smoothedRates<0)=0;
-                    MOCattenuation(idx,segmentStartPTR:segmentEndPTR)= ...
-                        (1- smoothedRates* rateToAttenuationFactorProb);
-                end
-            end
-            MOCattenuation(MOCattenuation<0)=0.001;
-
-            %             plot(MOCattenuation)
-
-
-        case 'spikes'
-            ANtimeCount=0;
-            % implement speed upt
-            for t = ANspeedUpFactor:ANspeedUpFactor:segmentLength;
-                ANtimeCount=ANtimeCount+1;
-                % convert release rate to probabilities
-                releaseProb=vesicleReleaseRate(:,t)*ANdt;
-                % releaseProb is the release probability per channel
-                %  but each channel has many synapses
-                releaseProb=repmat(releaseProb',nFibersPerChannel,1);
-                releaseProb=reshape(releaseProb, nFibersPerChannel*nANchannels,1);
-
-                % AN_available=round(AN_available); % vesicles must be integer, (?needed)
-                M_q=AN_M- AN_available;     % number of missing vesicles
-                M_q(M_q<0)= 0;              % cannot be less than 0
-
-                % AN_N1 converts probability to discrete events
-                %   it considers each event that might occur
-                %   (how many vesicles might be released)
-                %   and returns a count of how many were released
-
-                % slow line
-%                 probabilities= 1-(1-releaseProb).^AN_available;
-                probabilities= 1-intpow((1-releaseProb), AN_available);
-                ejected= probabilities> rand(length(AN_available),1);
-
-                reuptakeandlost = AN_rdt_plus_ldt .* AN_cleft;
-                reuptake = AN_rdt.* AN_cleft;
-
-                % slow line
-%                 probabilities= 1-(1-AN_reprocess.*AN_xdt).^M_q;
-                probabilities= 1-intpow((1-AN_reprocess.*AN_xdt), M_q);
-                reprocessed= probabilities>rand(length(M_q),1);
-
-                % slow line
-%                 probabilities= 1-(1-AN_ydt).^M_q;
-                 probabilities= 1-intpow((1-AN_ydt), M_q);
-
-                replenish= probabilities>rand(length(M_q),1);
-
-                AN_available = AN_available + replenish - ejected ...
-                    + reprocessed;
-                AN_cleft = AN_cleft + ejected - reuptakeandlost;
-                AN_reprocess = AN_reprocess + reuptake - reprocessed;
-
-                % ANspikes is logical record of vesicle release events>0
-                ANspikes(:, ANtimeCount)= ejected;
-            end % t
-
-            % zero any events that are preceded by release events ...
-            %  within the refractory period
-            % The refractory period consist of two periods
-            %  1) the absolute period where no spikes occur
-            %  2) a relative period where a spike may occur. This relative
-            %     period is realised as a variable length interval
-            %     where the length is chosen at random
-            %     (esentially a linear ramp up)
-
-            % Andreas has a fix for this
-            for t = 1:ANtimeCount-2*lengthAbsRefractory;
-                % identify all spikes across fiber array at time (t)
-                % idx is a list of channels where spikes occurred
-                % ?? try sparse matrices?
-                idx=find(ANspikes(:,t));
-                for j=idx  % consider each spike
-                    % specify variable refractory period
-                    %  between abs and 2*abs refractory period
-                    nPointsRefractory=lengthAbsRefractory+...
-                        round(rand*lengthAbsRefractory);
-                    % disable spike potential for refractory period
-                    % set all values in this range to 0
-                    ANspikes(j,t+1:t+nPointsRefractory)=0;
-                end
-            end  %t
-
-            % segment debugging
-            % plotInstructions.figureNo=98;
-            % plotInstructions.displaydt=ANdt;
-            %  plotInstructions.numPlots=1;
-            %  plotInstructions.subPlotNo=1;
-            % UTIL_plotMatrix(ANspikes, plotInstructions);
-
-            % and save it. NB, AN is now on 'speedUp' time
-            ANoutput(:, reducedSegmentPTR: shorterSegmentEndPTR)=ANspikes;
-
-
-            %% CN Macgregor first neucleus -------------------------------
-            % input is from AN so ANdt is used throughout
-            % Each CNneuron has a unique set of input fibers selected
-            %  at random from the available AN fibers (CNinputfiberLists)
-
-            % Create the dendritic current for that neuron
-            % First get input spikes to this neuron
-            synapseNo=1;
-            for ch=1:nCNchannels
-                for idx=1:nCNneuronsPerChannel
-                    % determine candidate fibers for this unit
-                    fibersUsed=CNinputfiberLists(synapseNo,:);
-                    % ANpsth has a bin width of ANdt
-                    %  (just a simple sum across fibers)
-                    AN_PSTH(synapseNo,:) = ...
-                        sum(ANspikes(fibersUsed,:), 1);
-                    synapseNo=synapseNo+1;
-                end
-            end
-            
-
-
-%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-
-                        
-            
-            % One alpha function per spike
-            [alphaRows alphaCols]=size(CNtrailingAlphas);
-
-           for unitNo=1:nCNneurons 
-
-%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-
-                 CNcurrentTemp0(unitNo,:)= ...
-                      conv(AN_PSTH(unitNo,:),CNalphaFunction);
-              
-
-                 
-                 CNcurrentTemp(unitNo,:)= ...
-                      conv2(AN_PSTH(unitNo,:),CNalphaFunction);
-            % Changed conv to conv2 because it runs faster. (Andreas)   
-
-
-%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-
-% 
-%              
-%                 f = CNalphaFunction;
-%                 g = AN_PSTH(unitNo,:);
-% 
-% 
-%                 g = [g zeros(1,length(f)-1)];
-% 
-%                 spikePos = find(g)';
-% 
-%                 result = zeros(1,length(g));
-% 
-%                 for index = 1:length(spikePos)
-%                     k = spikePos(index);
-%                     result(k:(k+length(f)-1)) = result(k:(k+length(f)-1)) + g(k)*f;
-%                 end
-%              
-%                 CNcurrentTemp2(unitNo,:) = result;    
-
-
-            end
-            
-
-%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%            
-
-
-         
-            
-            f = CNalphaFunction;
-            g = AN_PSTH;
-
-            g = [g zeros(size(g,1),length(f)-1)];
-
-            [r c] = find(g);
-
-            CNcurrentTemp2 = zeros(size(g));
-
-            for index = 1:length(r)
-
-                row = r(index);
-                col = c(index);
-
-               CNcurrentTemp2(row,col:col+length(f)-1) =  CNcurrentTemp2(row,col:col+length(f)-1) + f*g(row,col);
-
-            end
-
-
-
-CONVOLUTION_CHANGE_TEST =  CONVOLUTION_CHANGE_TEST + sum(abs(CNcurrentTemp2 - CNcurrentTemp))+ sum(abs(CNcurrentTemp0 - CNcurrentTemp));
-
-
-%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-
-
-
-
-%             disp(['sum(AN_PSTH)= ' num2str(sum(AN_PSTH(1,:)))])
-            % add post-synaptic current  left over from previous segment
-            CNcurrentTemp(:,1:alphaCols)=...
-                CNcurrentTemp(:,1:alphaCols)+ CNtrailingAlphas;
-
-            % take post-synaptic current for this segment
-            CNcurrentInput= CNcurrentTemp(:, 1:reducedSegmentLength);
-%                 disp(['mean(CNcurrentInput)= ' num2str(mean(CNcurrentInput(1,:)))])
-
-            % trailingalphas are the ends of the alpha functions that
-            % spill over into the next segment
-            CNtrailingAlphas= ...
-                CNcurrentTemp(:, reducedSegmentLength+1:end);
-
-            if CN_c>0
-                % variable threshold condition (slow)
-                for t=1:reducedSegmentLength
-                    CNtimeSinceLastSpike=CNtimeSinceLastSpike-ANdt;
-                    s=CN_E>CN_Th & CNtimeSinceLastSpike<0 ;
-                    CNtimeSinceLastSpike(s)=0.0005;         % 0.5 ms for sodium spike
-                    dE =(-CN_E/CN_tauM + ...
-                        CNcurrentInput(:,t)/CN_cap+(...
-                        CN_Gk/CN_cap).*(CN_Ek-CN_E))*ANdt;
-                    dGk=-CN_Gk*ANdt./tauGk + CN_b*s;
-                    dTh=-(CN_Th-CN_Th0)*ANdt/CN_tauTh + CN_c*s;
-                    CN_E=CN_E+dE;
-                    CN_Gk=CN_Gk+dGk;
-                    CN_Th=CN_Th+dTh;
-                    CNmembranePotential(:,t)=CN_E+s.*(CN_Eb-CN_E)+CN_Er;
-                end
-            else
-                % static threshold (faster)
-                E=zeros(1,reducedSegmentLength);
-                Gk=zeros(1,reducedSegmentLength);
-                ss=zeros(1,reducedSegmentLength);
-                for t=1:reducedSegmentLength
-                    % time of previous spike moves back in time
-                    CNtimeSinceLastSpike=CNtimeSinceLastSpike-ANdt;
-                    % action potential if E>threshold
-                    %  allow time for s to reset between events
-                    s=CN_E>CN_Th0 & CNtimeSinceLastSpike<0 ;  
-                    ss(t)=s(1);
-                    CNtimeSinceLastSpike(s)=0.0005; % 0.5 ms for sodium spike
-                    dE = (-CN_E/CN_tauM + ...
-                        CNcurrentInput(:,t)/CN_cap +...
-                        (CN_Gk/CN_cap).*(CN_Ek-CN_E))*ANdt;
-                    dGk=-CN_Gk*ANdt./tauGk +CN_b*s;
-                    CN_E=CN_E+dE;
-                    CN_Gk=CN_Gk+dGk;
-                    E(t)=CN_E(1);
-                    Gk(t)=CN_Gk(1);
-                    % add spike to CN_E and add resting potential (-60 mV)
-                    CNmembranePotential(:,t)=CN_E +s.*(CN_Eb-CN_E)+CN_Er;
-                end
-            end
-%             disp(['CN_E= ' num2str(sum(CN_E(1,:)))])
-%             disp(['CN_Gk= ' num2str(sum(CN_Gk(1,:)))])
-%             disp(['CNmembranePotential= ' num2str(sum(CNmembranePotential(1,:)))])
-%             plot(CNmembranePotential(1,:))
-
-
-            % extract spikes.  A spike is a substantial upswing in voltage
-            CN_spikes=CNmembranePotential> -0.02;
-%             disp(['CNspikesbefore= ' num2str(sum(sum(CN_spikes)))])
-
-            % now remove any spike that is immediately followed by a spike
-            % NB 'find' works on columns (whence the transposing)
-            % for each spike put a zero in the next epoch
-            CN_spikes=CN_spikes';
-            idx=find(CN_spikes);
-            idx=idx(1:end-1);
-            CN_spikes(idx+1)=0;
-            CN_spikes=CN_spikes';
-%             disp(['CNspikes= ' num2str(sum(sum(CN_spikes)))])
-
-            % segment debugging
-            % plotInstructions.figureNo=98;
-            % plotInstructions.displaydt=ANdt;
-            %  plotInstructions.numPlots=1;
-            %  plotInstructions.subPlotNo=1;
-            % UTIL_plotMatrix(CN_spikes, plotInstructions);
-
-            % and save it
-            CNoutput(:, reducedSegmentPTR:shorterSegmentEndPTR)=...
-                CN_spikes;
-
-
-            %% IC ----------------------------------------------
-                %  MacGregor or some other second order neurons
-
-                % combine CN neurons in same channel, 
-                %  i.e. same BF & same tauCa
-                %  to generate inputs to single IC unit
-                channelNo=0;
-                for idx=1:nCNneuronsPerChannel:nCNneurons-nCNneuronsPerChannel+1;
-                    channelNo=channelNo+1;
-                    CN_PSTH(channelNo,:)=...
-                        sum(CN_spikes(idx:idx+nCNneuronsPerChannel-1,:));
-                end
-
-                [alphaRows alphaCols]=size(ICtrailingAlphas);
-                for ICneuronNo=1:nICcells
-                    ICcurrentTemp(ICneuronNo,:)= ...
-                        conv2(CN_PSTH(ICneuronNo,:),  IC_CNalphaFunction);
-                % Changed conv to conv2 because it runs faster. (Andreas)
-                end
-
-                % add the unused current from the previous convolution
-                ICcurrentTemp(:,1:alphaCols)=ICcurrentTemp(:,1:alphaCols)...
-                    + ICtrailingAlphas;
-                % take what is required and keep the trailing part for next time
-                inputCurrent=ICcurrentTemp(:, 1:reducedSegmentLength);
-                ICtrailingAlphas=ICcurrentTemp(:, reducedSegmentLength+1:end);
-
-                if IC_c==0
-                    % faster computation when threshold is stable (C==0)
-                    for t=1:reducedSegmentLength
-                        s=IC_E>IC_Th0;
-                        dE = (-IC_E/IC_tauM + inputCurrent(:,t)/IC_cap +...
-                            (IC_Gk/IC_cap).*(IC_Ek-IC_E))*ANdt;
-                        dGk=-IC_Gk*ANdt/IC_tauGk +IC_b*s;
-                        IC_E=IC_E+dE;
-                        IC_Gk=IC_Gk+dGk;
-                        ICmembranePotential(:,t)=IC_E+s.*(IC_Eb-IC_E)+IC_Er;
-                    end
-                else
-                    %  threshold is changing (IC_c>0; e.g. bushy cell)
-                    for t=1:reducedSegmentLength
-                        dE = (-IC_E/IC_tauM + ...
-                            inputCurrent(:,t)/IC_cap + (IC_Gk/IC_cap)...
-                            .*(IC_Ek-IC_E))*ANdt;
-                        IC_E=IC_E+dE;
-                        s=IC_E>IC_Th;
-                        ICmembranePotential(:,t)=IC_E+s.*(IC_Eb-IC_E)+IC_Er;
-                        dGk=-IC_Gk*ANdt/IC_tauGk +IC_b*s;
-                        IC_Gk=IC_Gk+dGk;
-
-                        % After a spike, the threshold is raised
-                        % otherwise it settles to its baseline
-                        dTh=-(IC_Th-Th0)*ANdt/IC_tauTh +s*IC_c;
-                        IC_Th=IC_Th+dTh;
-                    end
-                end
-
-                ICspikes=ICmembranePotential> -0.01;
-                % now remove any spike that is immediately followed by a spike
-                % NB 'find' works on columns (whence the transposing)
-                ICspikes=ICspikes';
-                idx=find(ICspikes);
-                idx=idx(1:end-1);
-                ICspikes(idx+1)=0;
-                ICspikes=ICspikes';
-
-                nCellsPerTau= nICcells/nANfiberTypes;
-                firstCell=1;
-                lastCell=nCellsPerTau;
-                for tauCount=1:nANfiberTypes
-                    % separate rates according to fiber types
-                    % currently only the last segment is saved
-                    ICfiberTypeRates(tauCount, ...
-                        reducedSegmentPTR:shorterSegmentEndPTR)=...
-                        sum(ICspikes(firstCell:lastCell, :))...
-                        /(nCellsPerTau*ANdt);
-                    firstCell=firstCell+nCellsPerTau;
-                    lastCell=lastCell+nCellsPerTau;
-                end
-                
-                ICoutput(:,reducedSegmentPTR:shorterSegmentEndPTR)=ICspikes;
-                
-                % store membrane output on original dt scale
-                if nBFs==1  % single channel
-                    x= repmat(ICmembranePotential(1,:), ANspeedUpFactor,1);
-                    x= reshape(x,1,segmentLength);
-                    if nANfiberTypes>1  % save HSR and LSR
-                        y=repmat(ICmembranePotential(end,:),...
-                            ANspeedUpFactor,1);
-                        y= reshape(y,1,segmentLength);
-                        x=[x; y];
-                    end
-                    ICmembraneOutput(:, segmentStartPTR:segmentEndPTR)= x;
-                end
-
-                % estimate efferent effects.
-                % ARis based on LSR units. LSR channels are 1:nBF
-                if nANfiberTypes>1  % AR is multi-channel only
-                    ARAttSeg=sum(ICspikes(1:nBFs,:),1)/ANdt;
-                    [ARAttSeg, ARboundary] = ...
-                        filter(ARfilt_b, ARfilt_a, ARAttSeg, ARboundary);
-                    ARAttSeg=ARAttSeg-ARrateThreshold;
-                    ARAttSeg(ARAttSeg<0)=0;   % prevent negative strengths
-                    % scale up to dt from ANdt
-                    x=    repmat(ARAttSeg, ANspeedUpFactor,1);
-                    x=reshape(x,1,segmentLength);
-                    ARattenuation(segmentStartPTR:segmentEndPTR)=...
-                        (1-ARrateToAttenuationFactor* x);
-                    ARattenuation(ARattenuation<0)=0.001;
-                else
-                    % single channel model; disable AR
-                    ARattenuation(segmentStartPTR:segmentEndPTR)=...
-                        ones(1,segmentLength);
-                end
-
-                % MOC attenuation using HSR response only
-                % Separate MOC effect for each BF
-                HSRbegins=nBFs*(nANfiberTypes-1)+1;
-                rates=ICspikes(HSRbegins:end,:)/ANdt;
-                for idx=1:nBFs
-                    [smoothedRates, MOCboundary{idx}] = ...
-                        filter(MOCfilt_b, MOCfilt_a, rates(idx,:), ...
-                        MOCboundary{idx});
-                    % spont 'rates' is zero for IC
-                    MOCattSegment(idx,:)=smoothedRates;
-                    % expand timescale back to model dt from ANdt
-                    x= repmat(MOCattSegment(idx,:), ANspeedUpFactor,1);
-                    x= reshape(x,1,segmentLength);
-                    MOCattenuation(idx,segmentStartPTR:segmentEndPTR)= ...
-                        (1- MOCrateToAttenuationFactor*  x);
-                end
-                MOCattenuation(MOCattenuation<0)=0.04;
-                % segment debugging
-                % plotInstructions.figureNo=98;
-                % plotInstructions.displaydt=ANdt;
-                %  plotInstructions.numPlots=1;
-                %  plotInstructions.subPlotNo=1;
-                % UTIL_plotMatrix(ICspikes, plotInstructions);
-
-    end     % AN_spikesOrProbability
-    segmentStartPTR=segmentStartPTR+segmentLength;
-    reducedSegmentPTR=reducedSegmentPTR+reducedSegmentLength;
-
-
-end  % segment
-
-disp('CONVOLUTION_CHANGE_TEST (if followed by zero all is good)')
-disp(max(CONVOLUTION_CHANGE_TEST)) %% for debugging
-
-
-%% apply refractory correction to spike probabilities
-
-% switch AN_spikesOrProbability
-%     case 'probability'
-%         ANprobOutput=ANprobRateOutput*dt;
-%         [r nEpochs]=size(ANprobOutput);
-%         % find probability of no spikes in refractory period
-%         pNoSpikesInRefrac=ones(size(ANprobOutput));
-%         pSpike=zeros(size(ANprobOutput));
-%         for epochNo=lengthAbsRefractoryP+2:nEpochs
-%             pNoSpikesInRefrac(:,epochNo)=...
-%                 pNoSpikesInRefrac(:,epochNo-2)...
-%                 .*(1-pSpike(:,epochNo-1))...
-%                 ./(1-pSpike(:,epochNo-lengthAbsRefractoryP-1));
-%             pSpike(:,epochNo)= ANprobOutput(:,epochNo)...
-%                 .*pNoSpikesInRefrac(:,epochNo);
-%         end
-%         ANprobRateOutput=pSpike/dt;
-% end
-
-path(restorePath)
--- a/MAP/old MAP files/MAP1_14parallel.m	Thu Oct 06 15:43:20 2011 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,1148 +0,0 @@
-
-function  MAP1_14parallel(inputSignal, sampleRate, BFlist, MAPparamsName, ...
-    AN_spikesOrProbability, paramChanges)
-% To test this function use test_MAP1_14 in this folder
-%
-% All arguments are mandatory.
-%
-% BFlist is a list of BFs but can be '-1' to allow MAPparams to choose
-%
-
-%  MAPparamsName='Normal'; % source of model parameters
-%  AN_spikesOrProbability='spikes'; % or 'probability'
-%  paramChanges is a cell array of strings that can be used to make last
-%   minute parameter changes, e.g., to simulate OHC loss
-%   paramChanges{1}= 'DRNLParams.a=0;';
-
-% The model parameters are established in the MAPparams<***> file
-%  and stored as global
-
-restorePath=path;
-addpath (['..' filesep 'parameterStore'])
-
-global OMEParams DRNLParams IHC_cilia_RPParams IHCpreSynapseParams
-global AN_IHCsynapseParams MacGregorParams MacGregorMultiParams
-
-% All of the results of this function are stored as global
-global dt ANdt  savedBFlist saveAN_spikesOrProbability saveMAPparamsName...
-    savedInputSignal OMEextEarPressure TMoutput OMEoutput ARattenuation ...
-    DRNLoutput IHC_cilia_output IHCrestingCiliaCond IHCrestingV...
-    IHCoutput ANprobRateOutput ANoutput savePavailable tauCas  ...
-    CNoutput  ICoutput ICmembraneOutput ICfiberTypeRates MOCattenuation
-
-% Normally only ICoutput(logical spike matrix) or ANprobRateOutput will be
-% needed by the user; so the following will suffice
-%   global ANdt ICoutput ANprobRateOutput
-
-% Note that sampleRate has not changed from the original function call and
-%  ANprobRateOutput is sampled at this rate
-% However ANoutput, CNoutput and IC output are stored as logical
-%  'spike' matrices using a lower sample rate (see ANdt).
-
-% When AN_spikesOrProbability is set to probability,
-%  no spike matrices are computed.
-% When AN_spikesOrProbability is set to 'spikes',
-%  no probability output is computed
-
-% Efferent control variables are ARattenuation and MOCattenuation
-%  These are scalars between 1 (no attenuation) and 0.
-%  They are represented with dt=1/sampleRate (not ANdt)
-%  They are computed using either AN probability rate output
-%   or IC (spikes) output as approrpriate.
-% AR is computed using across channel activity
-% MOC is computed on a within-channel basis.
-
-
-% save as global for later plotting if required
-savedBFlist=BFlist;
-saveAN_spikesOrProbability=AN_spikesOrProbability;
-saveMAPparamsName=MAPparamsName;
-
-% Read parameters from MAPparams<***> file in 'parameterStore' folder
-cmd=['method=MAPparams' MAPparamsName ...
-    '(BFlist, sampleRate, 0);'];
-eval(cmd);
-
-% Beware, 'BFlist=-1' is a legitimate argument for MAPparams<>
-%  if the calling program allows MAPparams to specify the list
-BFlist=DRNLParams.nonlinCFs;
-
-% now accept last mintue parameter changes required by the calling program
-if nargin>5 && ~isempty(paramChanges)
-    nChanges=length(paramChanges);
-    for idx=1:nChanges
-        eval(paramChanges{idx})
-    end
-end
-
-dt=1/sampleRate;
-duration=length(inputSignal)/sampleRate;
-% segmentDuration is specified in parameter file (must be >efferent delay)
-segmentDuration=method.segmentDuration;
-segmentLength=round(segmentDuration/ dt);
-segmentTime=dt*(1:segmentLength); % used in debugging plots
-
-% all spiking activity is computed using longer epochs
-ANspeedUpFactor=5;  % 5 times longer
-
-% inputSignal must be  row vector
-[r c]=size(inputSignal);
-if r>c, inputSignal=inputSignal'; end       % transpose
-% ignore stereo signals
-inputSignal=inputSignal(1,:);               % drop any second channel
-savedInputSignal=inputSignal;
-
-% Segment the signal
-% The sgment length is given but the signal length must be adjusted to be a
-% multiple of both the segment length and the reduced segmentlength
-[nSignalRows signalLength]=size(inputSignal);
-segmentLength=ceil(segmentLength/ANspeedUpFactor)*ANspeedUpFactor;
-% Make the signal length a whole multiple of the segment length
-nSignalSegments=ceil(signalLength/segmentLength);
-padSize=nSignalSegments*segmentLength-signalLength;
-pad=zeros(nSignalRows,padSize);
-inputSignal=[inputSignal pad];
-[ignore signalLength]=size(inputSignal);
-
-% AN (spikes) is computed at a lower sample rate when spikes required
-%  so it has a reduced segment length (see 'ANspeeUpFactor' above)
-% AN CN and IC all use this sample interval
-ANdt=dt*ANspeedUpFactor;
-reducedSegmentLength=round(segmentLength/ANspeedUpFactor);
-reducedSignalLength= round(signalLength/ANspeedUpFactor);
-
-%% Initialise with respect to each stage before computing
-%  by allocating memory,
-%  by computing constants
-%  by establishing easy to read variable names
-% The computations are made in segments and boundary conditions must
-%  be established and stored. These are found in variables with
-%  'boundary' or 'bndry' in the name
-
-%% OME ---
-% external ear resonances
-OMEexternalResonanceFilters=OMEParams.externalResonanceFilters;
-[nOMEExtFilters c]=size(OMEexternalResonanceFilters);
-% details of external (outer ear) resonances
-OMEgaindBs=OMEexternalResonanceFilters(:,1);
-OMEgainScalars=10.^(OMEgaindBs/20);
-OMEfilterOrder=OMEexternalResonanceFilters(:,2);
-OMElowerCutOff=OMEexternalResonanceFilters(:,3);
-OMEupperCutOff=OMEexternalResonanceFilters(:,4);
-% external resonance coefficients
-ExtFilter_b=cell(nOMEExtFilters,1);
-ExtFilter_a=cell(nOMEExtFilters,1);
-for idx=1:nOMEExtFilters
-    Nyquist=sampleRate/2;
-    [b, a] = butter(OMEfilterOrder(idx), ...
-        [OMElowerCutOff(idx) OMEupperCutOff(idx)]...
-        /Nyquist);
-    ExtFilter_b{idx}=b;
-    ExtFilter_a{idx}=a;
-end
-OMEExtFilterBndry=cell(2,1);
-OMEextEarPressure=zeros(1,signalLength); % pressure at tympanic membrane
-
-% pressure to velocity conversion using smoothing filter (50 Hz cutoff)
-tau=1/(2*pi*50);
-a1=dt/tau-1; a0=1;
-b0=1+ a1;
-TMdisp_b=b0; TMdisp_a=[a0 a1];
-% figure(9), freqz(TMdisp_b, TMdisp_a)
-OME_TMdisplacementBndry=[];
-
-% OME high pass (simulates poor low frequency stapes response)
-OMEhighPassHighCutOff=OMEParams.OMEstapesLPcutoff;
-Nyquist=sampleRate/2;
-[stapesDisp_b,stapesDisp_a] = butter(1, OMEhighPassHighCutOff/Nyquist, 'high');
-% figure(10), freqz(stapesDisp_b, stapesDisp_a)
-
-OMEhighPassBndry=[];
-
-% OMEampStapes might be reducdant (use OMEParams.stapesScalar)
-stapesScalar= OMEParams.stapesScalar;
-
-% Acoustic reflex
-efferentDelayPts=round(OMEParams.ARdelay/dt);
-% smoothing filter
-% Nyquist=(1/ANdt)/2;
-% [ARfilt_b,ARfilt_a] = butter(1, (1/(2*pi*OMEParams.ARtau))/Nyquist, 'low');
-a1=dt/OMEParams.ARtau-1; a0=1;
-b0=1+ a1;
-ARfilt_b=b0; ARfilt_a=[a0 a1];
-
-ARattenuation=ones(1,signalLength);
-ARrateThreshold=OMEParams.ARrateThreshold; % may not be used
-ARrateToAttenuationFactor=OMEParams.rateToAttenuationFactor;
-ARrateToAttenuationFactorProb=OMEParams.rateToAttenuationFactorProb;
-ARboundary=[];
-ARboundaryProb=0;
-
-% save complete OME record (stapes displacement)
-OMEoutput=zeros(1,signalLength);
-TMoutput=zeros(1,signalLength);
-
-%% BM ---
-% BM is represented as a list of locations identified by BF
-DRNL_BFs=BFlist;
-nBFs= length(DRNL_BFs);
-
-% DRNLchannelParameters=DRNLParams.channelParameters;
-DRNLresponse= zeros(nBFs, segmentLength);
-
-MOCrateToAttenuationFactor=DRNLParams.rateToAttenuationFactor;
-rateToAttenuationFactorProb=DRNLParams.rateToAttenuationFactorProb;
-MOCrateThresholdProb=DRNLParams.MOCrateThresholdProb;
-
-% smoothing filter for MOC
-% Nyquist=(1/ANdt)/2;
-% [MOCfilt_b,MOCfilt_a] = ...
-%     butter(1, (1/(2*pi*DRNLParams.MOCtau))/Nyquist, 'low');
-% figure(10), freqz(stapesDisp_b, stapesDisp_a)
-a1=dt/DRNLParams.MOCtau-1; a0=1;
-b0=1+ a1;
-MOCfilt_b=b0; MOCfilt_a=[a0 a1];
-% figure(9), freqz(stapesDisp_b, stapesDisp_a)
-MOCboundary=cell(nBFs,1);
-MOCprobBoundary=cell(nBFs,1);
-
-MOCattSegment=zeros(nBFs,reducedSegmentLength);
-MOCattenuation=ones(nBFs,signalLength);
-
-if DRNLParams.a>0
-    DRNLcompressionThreshold=10^((1/(1-DRNLParams.c))* ...
-    log10(DRNLParams.b/DRNLParams.a));
-else
-    DRNLcompressionThreshold=inf;
-end
-
-DRNLlinearOrder= DRNLParams.linOrder;
-DRNLnonlinearOrder= DRNLParams.nonlinOrder;
-
-DRNLa=DRNLParams.a;
-DRNLb=DRNLParams.b;
-DRNLc=DRNLParams.c;
-linGAIN=DRNLParams.g;
-%
-% gammatone filter coefficients for linear pathway
-bw=DRNLParams.linBWs';
-phi = 2 * pi * bw * dt;
-cf=DRNLParams.linCFs';
-theta = 2 * pi * cf * dt;
-cos_theta = cos(theta);
-sin_theta = sin(theta);
-alpha = -exp(-phi).* cos_theta;
-b0 = ones(nBFs,1);
-b1 = 2 * alpha;
-b2 = exp(-2 * phi);
-z1 = (1 + alpha .* cos_theta) - (alpha .* sin_theta) * i;
-z2 = (1 + b1 .* cos_theta) - (b1 .* sin_theta) * i;
-z3 = (b2 .* cos(2 * theta)) - (b2 .* sin(2 * theta)) * i;
-tf = (z2 + z3) ./ z1;
-a0 = abs(tf);
-a1 = alpha .* a0;
-GTlin_a = [b0, b1, b2];
-GTlin_b = [a0, a1];
-GTlinOrder=DRNLlinearOrder;
-GTlinBdry1=cell(nBFs);
-GTlinBdry2=cell(nBFs);
-GTlinBdry3=cell(nBFs);
-GTlinBdry1out=cell(nBFs);
-GTlinBdry2out=cell(nBFs);
-GTlinBdry3out=cell(nBFs);
-
-% nonlinear gammatone filter coefficients 
-bw=DRNLParams.nlBWs';
-phi = 2 * pi * bw * dt;
-cf=DRNLParams.nonlinCFs';
-theta = 2 * pi * cf * dt;
-cos_theta = cos(theta);
-sin_theta = sin(theta);
-alpha = -exp(-phi).* cos_theta;
-b0 = ones(nBFs,1);
-b1 = 2 * alpha;
-b2 = exp(-2 * phi);
-z1 = (1 + alpha .* cos_theta) - (alpha .* sin_theta) * i;
-z2 = (1 + b1 .* cos_theta) - (b1 .* sin_theta) * i;
-z3 = (b2 .* cos(2 * theta)) - (b2 .* sin(2 * theta)) * i;
-tf = (z2 + z3) ./ z1;
-a0 = abs(tf);
-a1 = alpha .* a0;
-GTnonlin_a = [b0, b1, b2];
-GTnonlin_b = [a0, a1];
-GTnonlinOrder=DRNLnonlinearOrder;
-firstGTnonlinBdry1=cell(nBFs);
-firstGTnonlinBdry2=cell(nBFs);
-firstGTnonlinBdry3=cell(nBFs);
-firstGTnonlinBdry1out=cell(nBFs);
-firstGTnonlinBdry2out=cell(nBFs);
-firstGTnonlinBdry3out=cell(nBFs);
-
-secondGTnonlinBdry1=cell(nBFs);
-secondGTnonlinBdry2=cell(nBFs);
-secondGTnonlinBdry3=cell(nBFs);
-secondGTnonlinBdry1out=cell(nBFs);
-secondGTnonlinBdry2out=cell(nBFs);
-secondGTnonlinBdry3out=cell(nBFs);
-
-% complete BM record (BM displacement)
-DRNLoutput=zeros(nBFs, signalLength);
-
-
-%% IHC ---
-% IHC cilia activity and receptor potential
-% viscous coupling between BM and stereocilia displacement
-% Nyquist=sampleRate/2;
-% IHCcutoff=1/(2*pi*IHC_cilia_RPParams.tc);
-% [IHCciliaFilter_b,IHCciliaFilter_a]=...
-%     butter(1, IHCcutoff/Nyquist, 'high');
-a1=dt/IHC_cilia_RPParams.tc-1; a0=1;
-b0=1+ a1;
-% high pass (i.e. low pass reversed)
-IHCciliaFilter_b=[a0 a1]; IHCciliaFilter_a=b0;
-% figure(9), freqz(IHCciliaFilter_b, IHCciliaFilter_a)
-
-IHCciliaBndry=cell(nBFs,1);
-
-% IHC apical conductance (Boltzman function)
-IHC_C= IHC_cilia_RPParams.C;
-IHCu0= IHC_cilia_RPParams.u0;
-IHCu1= IHC_cilia_RPParams.u1;
-IHCs0= IHC_cilia_RPParams.s0;
-IHCs1= IHC_cilia_RPParams.s1;
-IHCGmax= IHC_cilia_RPParams.Gmax;
-IHCGa= IHC_cilia_RPParams.Ga; % (leakage)
-
-IHCGu0 = IHCGa+IHCGmax./(1+exp(IHCu0/IHCs0).*(1+exp(IHCu1/IHCs1)));
-
-% Receptor potential
-IHC_Cab= IHC_cilia_RPParams.Cab;
-IHC_Gk= IHC_cilia_RPParams.Gk;
-IHC_Et= IHC_cilia_RPParams.Et;
-IHC_Ek= IHC_cilia_RPParams.Ek;
-IHC_Ekp= IHC_Ek+IHC_Et*IHC_cilia_RPParams.Rpc;
-
-IHCrestingV= (IHC_Gk*IHC_Ekp+IHCGu0*IHC_Et)/(IHCGu0+IHC_Gk);
-
-IHC_Vnow= IHCrestingV*ones(nBFs,1); % initial voltage
-IHC_RP= zeros(nBFs,segmentLength);
-
-% complete record of IHC receptor potential (V)
-IHCciliaDisplacement= zeros(nBFs,segmentLength);
-IHCoutput= zeros(nBFs,signalLength);
-IHC_cilia_output= zeros(nBFs,signalLength);
-
-
-%% pre-synapse ---
-% Each BF is replicated using a different fiber type to make a 'channel'
-% The number of channels is nBFs x nANfiberTypes
-% Fiber types are specified in terms of tauCa
-nANfiberTypes= length(IHCpreSynapseParams.tauCa);
-tauCas= IHCpreSynapseParams.tauCa;
-nChannels= nANfiberTypes*nBFs;
-synapticCa= zeros(nChannels,segmentLength);
-
-% Calcium control (more calcium, greater release rate)
-ECa=IHCpreSynapseParams.ECa;
-gamma=IHCpreSynapseParams.gamma;
-beta=IHCpreSynapseParams.beta;
-tauM=IHCpreSynapseParams.tauM;
-mICa=zeros(nChannels,segmentLength);
-GmaxCa=IHCpreSynapseParams.GmaxCa;
-synapse_z= IHCpreSynapseParams.z;
-synapse_power=IHCpreSynapseParams.power;
-
-% tauCa vector is established across channels to allow vectorization
-%  (one tauCa per channel). Do not confuse with tauCas (one pre fiber type)
-tauCa=repmat(tauCas, nBFs,1);
-tauCa=reshape(tauCa, nChannels, 1);
-
-% presynapse startup values (vectors, length:nChannels)
-% proportion (0 - 1) of Ca channels open at IHCrestingV
-mICaCurrent=((1+beta^-1 * exp(-gamma*IHCrestingV))^-1)...
-    *ones(nBFs*nANfiberTypes,1);
-% corresponding startup currents
-ICaCurrent= (GmaxCa*mICaCurrent.^3) * (IHCrestingV-ECa);
-CaCurrent= ICaCurrent.*tauCa;
-
-% vesicle release rate at startup (one per channel)
-% kt0 is used only at initialisation
-kt0= -synapse_z * CaCurrent.^synapse_power;
-
-
-%% AN ---
-% each row of the AN matrices represents one AN fiber
-% The results computed either for probabiities *or* for spikes (not both)
-% Spikes are necessary if CN and IC are to be computed
-nFibersPerChannel= AN_IHCsynapseParams.numFibers;
-nANfibers= nChannels*nFibersPerChannel;
-
-y=AN_IHCsynapseParams.y;
-l=AN_IHCsynapseParams.l;
-x=AN_IHCsynapseParams.x;
-r=AN_IHCsynapseParams.r;
-M=round(AN_IHCsynapseParams.M);
-
-% probability            (NB initial 'P' on everything)
-PAN_ydt = repmat(AN_IHCsynapseParams.y*dt, nChannels,1);
-PAN_ldt = repmat(AN_IHCsynapseParams.l*dt, nChannels,1);
-PAN_xdt = repmat(AN_IHCsynapseParams.x*dt, nChannels,1);
-PAN_rdt = repmat(AN_IHCsynapseParams.r*dt, nChannels,1);
-PAN_rdt_plus_ldt = PAN_rdt + PAN_ldt;
-PAN_M=round(AN_IHCsynapseParams.M);
-
-% compute starting values
-Pcleft    = kt0* y* M ./ (y*(l+r)+ kt0* l);
-Pavailable    = Pcleft*(l+r)./kt0;
-Preprocess    = Pcleft*r/x; % canbe fractional
-
-ANprobability=zeros(nChannels,segmentLength);
-ANprobRateOutput=zeros(nChannels,signalLength);
-% special variables for monitoring synaptic cleft (specialists only)
-savePavailableSeg=zeros(nChannels,segmentLength);
-savePavailable=zeros(nChannels,signalLength);
-
-% spikes     % !  !  !    ! !        !   !  !
-AN_refractory_period= AN_IHCsynapseParams.refractory_period;
-lengthAbsRefractory= round(AN_refractory_period/ANdt);
-
-AN_ydt= repmat(AN_IHCsynapseParams.y*ANdt, nANfibers,1);
-AN_ldt= repmat(AN_IHCsynapseParams.l*ANdt, nANfibers,1);
-AN_xdt= repmat(AN_IHCsynapseParams.x*ANdt, nANfibers,1);
-AN_rdt= repmat(AN_IHCsynapseParams.r*ANdt, nANfibers,1);
-AN_rdt_plus_ldt= AN_rdt + AN_ldt;
-AN_M= round(AN_IHCsynapseParams.M);
-
-% kt0  is initial release rate
-% Establish as a vector (length=channel x number of fibers)
-kt0= repmat(kt0', nFibersPerChannel, 1);
-kt0=reshape(kt0, nANfibers,1);
-
-% starting values for reservoirs
-AN_cleft    = kt0* y* M ./ (y*(l+r)+ kt0* l);
-AN_available    = round(AN_cleft*(l+r)./kt0); %must be integer
-AN_reprocess    = AN_cleft*r/x;
-
-% output is in a logical array spikes = 1/ 0.
-ANspikes= false(nANfibers,reducedSegmentLength);
-ANoutput= false(nANfibers,reducedSignalLength);
-
-
-%% CN (first brain stem nucleus - could be any subdivision of CN)
-% Input to a CN neuorn is a random selection of AN fibers within a channel
-%  The number of AN fibers used is ANfibersFanInToCN
-ANfibersFanInToCN=MacGregorMultiParams.fibersPerNeuron;
-nCNneuronsPerChannel=MacGregorMultiParams.nNeuronsPerBF;
-% CNtauGk (Potassium time constant) determines the rate of firing of
-%  the unit when driven hard by a DC input (not normally >350 sp/s)
-CNtauGk=MacGregorMultiParams.tauGk;
-ANavailableFibersPerChan=AN_IHCsynapseParams.numFibers;
-nCNneurons=nCNneuronsPerChannel*nChannels;
-% nCNneuronsPerFiberType= nCNneurons/nANfiberTypes;
-
-CNmembranePotential=zeros(nCNneurons,reducedSegmentLength);
-
-% establish which ANfibers (by name) feed into which CN nuerons
-CNinputfiberLists=zeros(nChannels*nCNneuronsPerChannel, ANfibersFanInToCN);
-unitNo=1;
-for ch=1:nChannels
-    % Each channel contains a number of units =length(listOfFanInValues)
-    for idx=1:nCNneuronsPerChannel
-        fibersUsed=(ch-1)*ANavailableFibersPerChan + ...
-            ceil(rand(1,ANfibersFanInToCN)* ANavailableFibersPerChan);
-        CNinputfiberLists(unitNo,:)=fibersUsed;
-        unitNo=unitNo+1;
-    end
-end
-
-% input to CN units
-AN_PSTH=zeros(nCNneurons,reducedSegmentLength);
-
-% Generate CNalphaFunction function
-%  by which spikes are converted to post-synaptic currents
-CNdendriteLPfreq= MacGregorMultiParams.dendriteLPfreq;
-CNcurrentPerSpike=MacGregorMultiParams.currentPerSpike;
-CNspikeToCurrentTau=1/(2*pi*CNdendriteLPfreq);
-t=ANdt:ANdt:5*CNspikeToCurrentTau;
-CNalphaFunction=...
-    (CNcurrentPerSpike/CNspikeToCurrentTau)*t.*exp(-t/CNspikeToCurrentTau);
-% figure(98), plot(t,CNalphaFunction)
-% working memory for implementing convolution
-CNcurrentTemp=...
-    zeros(nCNneurons,reducedSegmentLength+length(CNalphaFunction)-1);
-% trailing alphas are parts of humps carried forward to the next segment
-CNtrailingAlphas=zeros(nCNneurons,length(CNalphaFunction));
-
-CN_tauM=MacGregorMultiParams.tauM;
-CN_tauTh=MacGregorMultiParams.tauTh;
-CN_cap=MacGregorMultiParams.Cap;
-CN_c=MacGregorMultiParams.c;
-CN_b=MacGregorMultiParams.dGkSpike;
-CN_Ek=MacGregorMultiParams.Ek;
-CN_Eb= MacGregorMultiParams.Eb;
-CN_Er=MacGregorMultiParams.Er;
-CN_Th0= MacGregorMultiParams.Th0;
-CN_E= zeros(nCNneurons,1);
-CN_Gk= zeros(nCNneurons,1);
-CN_Th= MacGregorMultiParams.Th0*ones(nCNneurons,1);
-CN_Eb=CN_Eb.*ones(nCNneurons,1);
-CN_Er=CN_Er.*ones(nCNneurons,1);
-CNtimeSinceLastSpike=zeros(nCNneurons,1);
-% tauGk is the main distinction between neurons
-%  in fact they are all the same in the standard model
-tauGk=repmat(CNtauGk,nChannels*nCNneuronsPerChannel,1);
-
-CN_PSTH=zeros(nChannels,reducedSegmentLength);
-CNoutput=false(nCNneurons,reducedSignalLength);
-
-
-%% MacGregor (IC - second nucleus) --------
-nICcells=nChannels;  % one cell per channel
-
-ICspikeWidth=0.00015;   % this may need revisiting
-epochsPerSpike=round(ICspikeWidth/ANdt);
-if epochsPerSpike<1
-    error(['MacGregorMulti: sample rate too low to support ' ...
-        num2str(ICspikeWidth*1e6) '  microsec spikes']);
-end
-
-% short names
-IC_tauM=MacGregorParams.tauM;
-IC_tauGk=MacGregorParams.tauGk;
-IC_tauTh=MacGregorParams.tauTh;
-IC_cap=MacGregorParams.Cap;
-IC_c=MacGregorParams.c;
-IC_b=MacGregorParams.dGkSpike;
-IC_Th0=MacGregorParams.Th0;
-IC_Ek=MacGregorParams.Ek;
-IC_Eb= MacGregorParams.Eb;
-IC_Er=MacGregorParams.Er;
-
-IC_E=zeros(nICcells,1);
-IC_Gk=zeros(nICcells,1);
-IC_Th=IC_Th0*ones(nICcells,1);
-
-% Dendritic filtering, all spikes are replaced by CNalphaFunction functions
-ICdendriteLPfreq= MacGregorParams.dendriteLPfreq;
-ICcurrentPerSpike=MacGregorParams.currentPerSpike;
-ICspikeToCurrentTau=1/(2*pi*ICdendriteLPfreq);
-t=ANdt:ANdt:3*ICspikeToCurrentTau;
-IC_CNalphaFunction= (ICcurrentPerSpike / ...
-    ICspikeToCurrentTau)*t.*exp(-t / ICspikeToCurrentTau);
-% figure(98), plot(t,IC_CNalphaFunction)
-
-% working space for implementing alpha function
-ICcurrentTemp=...
-    zeros(nICcells,reducedSegmentLength+length(IC_CNalphaFunction)-1);
-ICtrailingAlphas=zeros(nICcells, length(IC_CNalphaFunction));
-
-ICfiberTypeRates=zeros(nANfiberTypes,reducedSignalLength);
-ICoutput=false(nChannels,reducedSignalLength);
-
-ICmembranePotential=zeros(nICcells,reducedSegmentLength);
-ICmembraneOutput=zeros(nICcells,signalLength);
-
-
-%% Main program %%  %%  %%  %%  %%  %%  %%  %%  %%  %%  %%  %%  %%  %%
-
-%  Compute the entire model for each segment
-segmentStartPTR=1;
-reducedSegmentPTR=1; % when sampling rate is reduced
-while segmentStartPTR<signalLength
-    segmentEndPTR=segmentStartPTR+segmentLength-1;
-    % shorter segments after speed up.
-    shorterSegmentEndPTR=reducedSegmentPTR+reducedSegmentLength-1;
-
-    iputPressureSegment=inputSignal...
-        (:,segmentStartPTR:segmentStartPTR+segmentLength-1);
-
-    % segment debugging plots
-    % figure(98)
-    % plot(segmentTime,iputPressureSegment), title('signalSegment')
-
-
-    % OME ----------------------
-
-    % OME Stage 1: external resonances. Add to inputSignal pressure wave
-    y=iputPressureSegment;
-    for n=1:nOMEExtFilters
-        % any number of resonances can be used
-        [x  OMEExtFilterBndry{n}] = ...
-            filter(ExtFilter_b{n},ExtFilter_a{n},...
-            iputPressureSegment, OMEExtFilterBndry{n});
-        x= x* OMEgainScalars(n);
-        % This is a parallel resonance so add it
-        y=y+x;
-    end
-    iputPressureSegment=y;
-    OMEextEarPressure(segmentStartPTR:segmentEndPTR)= iputPressureSegment;
-    
-    % OME stage 2: convert input pressure (velocity) to
-    %  tympanic membrane(TM) displacement using low pass filter
-    [TMdisplacementSegment  OME_TMdisplacementBndry] = ...
-        filter(TMdisp_b,TMdisp_a,iputPressureSegment, ...
-        OME_TMdisplacementBndry);
-    % and save it
-    TMoutput(segmentStartPTR:segmentEndPTR)= TMdisplacementSegment;
-
-    % OME stage 3: middle ear high pass effect to simulate stapes inertia
-    [stapesDisplacement  OMEhighPassBndry] = ...
-        filter(stapesDisp_b,stapesDisp_a,TMdisplacementSegment, ...
-        OMEhighPassBndry);
-
-    % OME stage 4:  apply stapes scalar
-    stapesDisplacement=stapesDisplacement*stapesScalar;
-
-    % OME stage 5:    acoustic reflex stapes attenuation
-    %  Attenuate the TM response using feedback from LSR fiber activity
-    if segmentStartPTR>efferentDelayPts
-        stapesDisplacement= stapesDisplacement.*...
-            ARattenuation(segmentStartPTR-efferentDelayPts:...
-            segmentEndPTR-efferentDelayPts);
-    end
-
-    % segment debugging plots
-    % figure(98)
-    % plot(segmentTime, stapesDisplacement), title ('stapesDisplacement')
-
-    % and save
-    OMEoutput(segmentStartPTR:segmentEndPTR)= stapesDisplacement;
-
-    % needed for parallel processing
-    if segmentStartPTR>efferentDelayPts
-        MOCatt=MOCattenuation(:, segmentStartPTR-efferentDelayPts:...
-            segmentEndPTR-efferentDelayPts);
-    else    % no MOC available yet
-        MOCatt=ones(nBFs, segmentLength);
-    end
-    %% BM ------------------------------
-    % Each BM location is computed separately
-    parfor BFno=1:nBFs
-
-        %            *linear* path
-        % repeats used to avoid parallel processin problems
-        linOutput = stapesDisplacement * linGAIN;  % linear gain
-        [linOutput GTlinBdry1out{BFno}] = ...
-            filter(GTlin_b(BFno,:), GTlin_a(BFno,:), linOutput, GTlinBdry1{BFno});
-        [linOutput GTlinBdry2out{BFno}] = ...
-            filter(GTlin_b(BFno,:), GTlin_a(BFno,:), linOutput, GTlinBdry2{BFno});
-        [linOutput GTlinBdry3out{BFno}] = ...
-            filter(GTlin_b(BFno,:), GTlin_a(BFno,:), linOutput, GTlinBdry3{BFno});
-
-        %           *nonLinear* path
-        % efferent attenuation (0 <> 1)
-        MOC=MOCatt(BFno);
-
-
-        %       first gammatone filter
-        [nonlinOutput firstGTnonlinBdry1out{BFno}] = ...
-            filter(GTnonlin_b(BFno,:), GTnonlin_a(BFno,:), ...
-            stapesDisplacement, firstGTnonlinBdry1{BFno});
-
-        [nonlinOutput firstGTnonlinBdry2out{BFno}] = ...
-            filter(GTnonlin_b(BFno,:), GTnonlin_a(BFno,:), ...
-            stapesDisplacement, firstGTnonlinBdry2{BFno});
-
-        [nonlinOutput firstGTnonlinBdry3out{BFno}] = ...
-            filter(GTnonlin_b(BFno,:), GTnonlin_a(BFno,:), ...
-            stapesDisplacement, firstGTnonlinBdry3{BFno});
-
-        %       broken stick instantaneous compression
-        % nonlinear gain is weakend by MOC before applied to BM response
-        y= nonlinOutput.*(MOC* DRNLa);  % linear section.
-        % compress those parts of the signal above the compression
-        % threshold
-        abs_x = abs(nonlinOutput);
-        idx=find(abs_x>DRNLcompressionThreshold);
-        if ~isempty(idx)>0
-            y(idx)=sign(nonlinOutput(idx)).*...
-                (DRNLb*abs_x(idx).^DRNLc);
-        end
-        nonlinOutput=y;
-
-        %       second filter removes distortion products
-        [nonlinOutput secondGTnonlinBdry1out{BFno}] = ...
-            filter(GTnonlin_b(BFno,:), GTnonlin_a(BFno,:), ...
-            nonlinOutput, secondGTnonlinBdry1{BFno});
-
-        [nonlinOutput secondGTnonlinBdry2out{BFno}] = ...
-            filter(GTnonlin_b(BFno,:), GTnonlin_a(BFno,:), ...
-            nonlinOutput, secondGTnonlinBdry2{BFno});
-
-        [nonlinOutput secondGTnonlinBdry3out{BFno}] = ...
-            filter(GTnonlin_b(BFno,:), GTnonlin_a(BFno,:), ...
-            nonlinOutput, secondGTnonlinBdry3{BFno});
-
-
-        %  combine the two paths to give the DRNL displacement
-        DRNLresponse(BFno,:)=linOutput+nonlinOutput;
-    end % BF
-    GTlinBdry1=GTlinBdry1out;
-    GTlinBdry2=GTlinBdry2out;
-    GTlinBdry3=GTlinBdry3out;
-    firstGTnonlinBdry1=firstGTnonlinBdry1out;
-    firstGTnonlinBdry2=firstGTnonlinBdry2out;
-    firstGTnonlinBdry3=firstGTnonlinBdry3out;
-    secondGTnonlinBdry1=secondGTnonlinBdry1out;
-    secondGTnonlinBdry2=secondGTnonlinBdry2out;
-    secondGTnonlinBdry3=secondGTnonlinBdry3out;
-    % segment debugging plots
-    % figure(98)
-    %     if size(DRNLresponse,1)>3
-    %         imagesc(DRNLresponse)  % matrix display
-    %         title('DRNLresponse'); % single or double channel response
-    %     else
-    %         plot(segmentTime, DRNLresponse)
-    %     end
-
-    % and save it
-    DRNLoutput(:, segmentStartPTR:segmentEndPTR)= DRNLresponse;
-
-
-    %% IHC ------------------------------------
-    %  BM displacement to IHCciliaDisplacement is  a high-pass filter
-    %   because of viscous coupling
-    for idx=1:nBFs
-        [IHCciliaDisplacement(idx,:)  IHCciliaBndry{idx}] = ...
-            filter(IHCciliaFilter_b,IHCciliaFilter_a, ...
-            DRNLresponse(idx,:), IHCciliaBndry{idx});
-    end
-    
-    % apply scalar
-    IHCciliaDisplacement=IHCciliaDisplacement* IHC_C;
-
-    % and save it
-    IHC_cilia_output(:,segmentStartPTR:segmentStartPTR+segmentLength-1)=...
-        IHCciliaDisplacement;
-
-    % compute apical conductance
-    G=IHCGmax./(1+exp(-(IHCciliaDisplacement-IHCu0)/IHCs0).*...
-        (1+exp(-(IHCciliaDisplacement-IHCu1)/IHCs1)));
-    Gu=G + IHCGa;
-
-    % Compute receptor potential
-    for idx=1:segmentLength
-        IHC_Vnow=IHC_Vnow+ (-Gu(:, idx).*(IHC_Vnow-IHC_Et)-...
-            IHC_Gk*(IHC_Vnow-IHC_Ekp))*  dt/IHC_Cab;
-        IHC_RP(:,idx)=IHC_Vnow;
-    end
-
-    % segment debugging plots
-    %     if size(IHC_RP,1)>3
-    %         surf(IHC_RP), shading interp, title('IHC_RP')
-    %     else
-    %         plot(segmentTime, IHC_RP)
-    %     end
-
-    % and save it
-    IHCoutput(:, segmentStartPTR:segmentStartPTR+segmentLength-1)=IHC_RP;
-
-
-    %% synapse -----------------------------
-    % Compute the vesicle release rate for each fiber type at each BF
-    % replicate IHC_RP for each fiber type
-    Vsynapse=repmat(IHC_RP, nANfiberTypes,1);
-
-    % look-up table of target fraction channels open for a given IHC_RP
-    mICaINF=    1./( 1 + exp(-gamma  * Vsynapse)  /beta);
-    % fraction of channel open - apply time constant
-    for idx=1:segmentLength
-        % mICaINF is the current 'target' value of mICa
-        mICaCurrent=mICaCurrent+(mICaINF(:,idx)-mICaCurrent)*dt./tauM;
-        mICa(:,idx)=mICaCurrent;
-    end
-
-    ICa=   (GmaxCa* mICa.^3) .* (Vsynapse- ECa);
-
-    for idx=1:segmentLength
-        CaCurrent=CaCurrent +  ICa(:,idx)*dt - CaCurrent*dt./tauCa;
-        synapticCa(:,idx)=CaCurrent;
-    end
-    synapticCa=-synapticCa; % treat IHCpreSynapseParams as positive substance
-
-    % NB vesicleReleaseRate is /s and is independent of dt
-    vesicleReleaseRate = synapse_z * synapticCa.^synapse_power; % rate
-
-    % segment debugging plots
-    %     if size(vesicleReleaseRate,1)>3
-    %         surf(vesicleReleaseRate), shading interp, title('vesicleReleaseRate')
-    %     else
-    %         plot(segmentTime, vesicleReleaseRate)
-    %     end
-
-
-    %% AN
-    switch AN_spikesOrProbability
-        case 'probability'
-            % No refractory effect is applied
-            for t = 1:segmentLength;
-                M_Pq=PAN_M-Pavailable;
-                M_Pq(M_Pq<0)=0;
-                Preplenish = M_Pq .* PAN_ydt;
-                Pejected = Pavailable.* vesicleReleaseRate(:,t)*dt;
-                Preprocessed = M_Pq.*Preprocess.* PAN_xdt;
-
-                ANprobability(:,t)= min(Pejected,1);
-                reuptakeandlost= PAN_rdt_plus_ldt .* Pcleft;
-                reuptake= PAN_rdt.* Pcleft;
-
-                Pavailable= Pavailable+ Preplenish- Pejected+ Preprocessed;
-                Pcleft= Pcleft + Pejected - reuptakeandlost;
-                Preprocess= Preprocess + reuptake - Preprocessed;
-                Pavailable(Pavailable<0)=0;
-                savePavailableSeg(:,t)=Pavailable;    % synapse tracking
-            end
-            % and save it as *rate*
-            ANrate=ANprobability/dt;
-            ANprobRateOutput(:, segmentStartPTR:...
-                segmentStartPTR+segmentLength-1)=  ANrate;
-            % monitor synapse contents (only sometimes used)
-            savePavailable(:, segmentStartPTR:segmentStartPTR+segmentLength-1)=...
-                savePavailableSeg;
-
-            % Estimate efferent effects. ARattenuation (0 <> 1)
-            %  acoustic reflex
-            ARAttSeg=mean(ANrate(1:nBFs,:),1); %LSR channels are 1:nBF
-            % smooth
-            [ARAttSeg, ARboundaryProb] = ...
-                filter(ARfilt_b, ARfilt_a, ARAttSeg, ARboundaryProb);
-            ARAttSeg=ARAttSeg-ARrateThreshold;
-            ARAttSeg(ARAttSeg<0)=0;   % prevent negative strengths
-            ARattenuation(segmentStartPTR:segmentEndPTR)=...
-                (1-ARrateToAttenuationFactorProb.* ARAttSeg);
-
-            % MOC attenuation
-            % within-channel HSR response only
-            HSRbegins=nBFs*(nANfiberTypes-1)+1;
-            rates=ANrate(HSRbegins:end,:);
-            for idx=1:nBFs
-                [smoothedRates, MOCprobBoundary{idx}] = ...
-                    filter(MOCfilt_b, MOCfilt_a, rates(idx,:), ...
-                    MOCprobBoundary{idx});
-                smoothedRates=smoothedRates-MOCrateThresholdProb;
-                smoothedRates(smoothedRates<0)=0;
-                MOCattenuation(idx,segmentStartPTR:segmentEndPTR)= ...
-                    (1- smoothedRates* rateToAttenuationFactorProb);
-            end
-            MOCattenuation(MOCattenuation<0)=0.001;
-
-
-        case 'spikes'
-            ANtimeCount=0;
-            % implement speed upt
-            for t = ANspeedUpFactor:ANspeedUpFactor:segmentLength;
-                ANtimeCount=ANtimeCount+1;
-                % convert release rate to probabilities
-                releaseProb=vesicleReleaseRate(:,t)*ANdt;
-                % releaseProb is the release probability per channel
-                %  but each channel has many synapses
-                releaseProb=repmat(releaseProb',nFibersPerChannel,1);
-                releaseProb=reshape(releaseProb, nFibersPerChannel*nChannels,1);
-
-                % AN_available=round(AN_available); % vesicles must be integer, (?needed)
-                M_q=AN_M- AN_available;     % number of missing vesicles
-                M_q(M_q<0)= 0;              % cannot be less than 0
-
-                % AN_N1 converts probability to discrete events
-                %   it considers each event that might occur
-                %   (how many vesicles might be released)
-                %   and returns a count of how many were released
-
-                % slow line
-%                 probabilities= 1-(1-releaseProb).^AN_available;
-                probabilities= 1-intpow((1-releaseProb), AN_available);
-                ejected= probabilities> rand(length(AN_available),1);
-
-                reuptakeandlost = AN_rdt_plus_ldt .* AN_cleft;
-                reuptake = AN_rdt.* AN_cleft;
-
-                % slow line
-%                 probabilities= 1-(1-AN_reprocess.*AN_xdt).^M_q;
-                probabilities= 1-intpow((1-AN_reprocess.*AN_xdt), M_q);
-                reprocessed= probabilities>rand(length(M_q),1);
-
-                % slow line
-%                 probabilities= 1-(1-AN_ydt).^M_q;
-                 probabilities= 1-intpow((1-AN_ydt), M_q);
-
-                replenish= probabilities>rand(length(M_q),1);
-
-                AN_available = AN_available + replenish - ejected ...
-                    + reprocessed;
-                AN_cleft = AN_cleft + ejected - reuptakeandlost;
-                AN_reprocess = AN_reprocess + reuptake - reprocessed;
-
-                % ANspikes is logical record of vesicle release events>0
-                ANspikes(:, ANtimeCount)= ejected;
-            end % t
-
-            % zero any events that are preceded by release events ...
-            %  within the refractory period
-            % The refractory period consist of two periods
-            %  1) the absolute period where no spikes occur
-            %  2) a relative period where a spike may occur. This relative
-            %     period is realised as a variable length interval
-            %     where the length is chosen at random
-            %     (esentially a linear ramp up)
-
-            % Andreas has a fix for this
-            for t = 1:ANtimeCount-2*lengthAbsRefractory;
-                % identify all spikes across fiber array at time (t)
-                % idx is a list of channels where spikes occurred
-                % ?? try sparse matrices?
-                idx=find(ANspikes(:,t));
-                for j=idx  % consider each spike
-                    % specify variable refractory period
-                    %  between abs and 2*abs refractory period
-                    nPointsRefractory=lengthAbsRefractory+...
-                        round(rand*lengthAbsRefractory);
-                    % disable spike potential for refractory period
-                    % set all values in this range to 0
-                    ANspikes(j,t+1:t+nPointsRefractory)=0;
-                end
-            end  %t
-
-            % segment debugging
-            % plotInstructions.figureNo=98;
-            % plotInstructions.displaydt=ANdt;
-            %  plotInstructions.numPlots=1;
-            %  plotInstructions.subPlotNo=1;
-            % UTIL_plotMatrix(ANspikes, plotInstructions);
-
-            % and save it. NB, AN is now on 'speedUp' time
-            ANoutput(:, reducedSegmentPTR: shorterSegmentEndPTR)=ANspikes;
-
-
-            %% CN Macgregor first neucleus -------------------------------
-            % input is from AN so ANdt is used throughout
-            % Each CNneuron has a unique set of input fibers selected
-            %  at random from the available AN fibers (CNinputfiberLists)
-
-            % Create the dendritic current for that neuron
-            % First get input spikes to this neuron
-            synapseNo=1;
-            for ch=1:nChannels
-                for idx=1:nCNneuronsPerChannel
-                    % determine candidate fibers for this unit
-                    fibersUsed=CNinputfiberLists(synapseNo,:);
-                    % ANpsth has a bin width of dt
-                    %  (just a simple sum across fibers)
-                    AN_PSTH(synapseNo,:) = ...
-                        sum(ANspikes(fibersUsed,:), 1);
-                    synapseNo=synapseNo+1;
-                end
-            end
-
-            % One alpha function per spike
-            [alphaRows alphaCols]=size(CNtrailingAlphas);
-
-            for unitNo=1:nCNneurons
-                CNcurrentTemp(unitNo,:)= ...
-                    conv(AN_PSTH(unitNo,:),CNalphaFunction);
-            end
-            % add post-synaptic current  left over from previous segment
-            CNcurrentTemp(:,1:alphaCols)=...
-                CNcurrentTemp(:,1:alphaCols)+ CNtrailingAlphas;
-
-            % take post-synaptic current for this segment
-            CNcurrentInput= CNcurrentTemp(:, 1:reducedSegmentLength);
-
-            % trailingalphas are the ends of the alpha functions that
-            % spill over into the next segment
-            CNtrailingAlphas= ...
-                CNcurrentTemp(:, reducedSegmentLength+1:end);
-
-            if CN_c>0
-                % variable threshold condition (slow)
-                for t=1:reducedSegmentLength
-                    CNtimeSinceLastSpike=CNtimeSinceLastSpike-dts;
-                    s=CN_E>CN_Th & CNtimeSinceLastSpike<0 ;
-                    CNtimeSinceLastSpike(s)=0.0005;         % 0.5 ms for sodium spike
-                    dE =(-CN_E/CN_tauM + ...
-                        CNcurrentInput(:,t)/CN_cap+(CN_Gk/CN_cap).*(CN_Ek-CN_E))*dt;
-                    dGk=-CN_Gk*dt./tauGk + CN_b*s;
-                    dTh=-(CN_Th-CN_Th0)*dt/CN_tauTh + CN_c*s;
-                    CN_E=CN_E+dE;
-                    CN_Gk=CN_Gk+dGk;
-                    CN_Th=CN_Th+dTh;
-                    CNmembranePotential(:,t)=CN_E+s.*(CN_Eb-CN_E)+CN_Er;
-                end
-            else
-                % static threshold (faster)
-                for t=1:reducedSegmentLength
-                    CNtimeSinceLastSpike=CNtimeSinceLastSpike-dt;
-                    s=CN_E>CN_Th0 & CNtimeSinceLastSpike<0 ;  % =1 if both conditions met
-                    CNtimeSinceLastSpike(s)=0.0005;          % 0.5 ms for sodium spike
-                    dE = (-CN_E/CN_tauM + ...
-                        CNcurrentInput(:,t)/CN_cap+(CN_Gk/CN_cap).*(CN_Ek-CN_E))*dt;
-                    dGk=-CN_Gk*dt./tauGk +CN_b*s;
-                    CN_E=CN_E+dE;
-                    CN_Gk=CN_Gk+dGk;
-                    % add spike to CN_E and add resting potential (-60 mV)
-                    CNmembranePotential(:,t)=CN_E+s.*(CN_Eb-CN_E)+CN_Er;
-                end
-            end
-
-            % extract spikes.  A spike is a substantial upswing in voltage
-            CN_spikes=CNmembranePotential> -0.01;
-
-            % now remove any spike that is immediately followed by a spike
-            % NB 'find' works on columns (whence the transposing)
-            CN_spikes=CN_spikes';
-            idx=find(CN_spikes);
-            idx=idx(1:end-1);
-            CN_spikes(idx+1)=0;
-            CN_spikes=CN_spikes';
-
-            % segment debugging
-            % plotInstructions.figureNo=98;
-            % plotInstructions.displaydt=ANdt;
-            %  plotInstructions.numPlots=1;
-            %  plotInstructions.subPlotNo=1;
-            % UTIL_plotMatrix(CN_spikes, plotInstructions);
-
-            % and save it
-            CNoutput(:, reducedSegmentPTR:shorterSegmentEndPTR)=...
-                CN_spikes;
-
-
-            %% IC ----------------------------------------------
-                %  MacGregor or some other second order neurons
-
-                % combine CN neurons in same channel, i.e. same BF & same tauCa
-                %  to generate inputs to single IC unit
-                channelNo=0;
-                for idx=1:nCNneuronsPerChannel:nCNneurons-nCNneuronsPerChannel+1;
-                    channelNo=channelNo+1;
-                    CN_PSTH(channelNo,:)=...
-                        sum(CN_spikes(idx:idx+nCNneuronsPerChannel-1,:));
-                end
-
-                [alphaRows alphaCols]=size(ICtrailingAlphas);
-                for ICneuronNo=1:nICcells
-                    ICcurrentTemp(ICneuronNo,:)= ...
-                        conv(CN_PSTH(ICneuronNo,:),  IC_CNalphaFunction);
-                end
-
-                % add the unused current from the previous convolution
-                ICcurrentTemp(:,1:alphaCols)=ICcurrentTemp(:,1:alphaCols)...
-                    + ICtrailingAlphas;
-                % take what is required and keep the trailing part for next time
-                inputCurrent=ICcurrentTemp(:, 1:reducedSegmentLength);
-                ICtrailingAlphas=ICcurrentTemp(:, reducedSegmentLength+1:end);
-
-                if IC_c==0
-                    % faster computation when threshold is stable (C==0)
-                    for t=1:reducedSegmentLength
-                        s=IC_E>IC_Th0;
-                        dE = (-IC_E/IC_tauM + inputCurrent(:,t)/IC_cap +...
-                            (IC_Gk/IC_cap).*(IC_Ek-IC_E))*dt;
-                        dGk=-IC_Gk*dt/IC_tauGk +IC_b*s;
-                        IC_E=IC_E+dE;
-                        IC_Gk=IC_Gk+dGk;
-                        ICmembranePotential(:,t)=IC_E+s.*(IC_Eb-IC_E)+IC_Er;
-                    end
-                else
-                    %  threshold is changing (IC_c>0; e.g. bushy cell)
-                    for t=1:reducedSegmentLength
-                        dE = (-IC_E/IC_tauM + ...
-                            inputCurrent(:,t)/IC_cap + (IC_Gk/IC_cap)...
-                            .*(IC_Ek-IC_E))*dt;
-                        IC_E=IC_E+dE;
-                        s=IC_E>IC_Th;
-                        ICmembranePotential(:,t)=IC_E+s.*(IC_Eb-IC_E)+IC_Er;
-                        dGk=-IC_Gk*dt/IC_tauGk +IC_b*s;
-                        IC_Gk=IC_Gk+dGk;
-
-                        % After a spike, the threshold is raised
-                        % otherwise it settles to its baseline
-                        dTh=-(IC_Th-Th0)*dt/IC_tauTh +s*IC_c;
-                        IC_Th=IC_Th+dTh;
-                    end
-                end
-
-                ICspikes=ICmembranePotential> -0.01;
-                % now remove any spike that is immediately followed by a spike
-                % NB 'find' works on columns (whence the transposing)
-                ICspikes=ICspikes';
-                idx=find(ICspikes);
-                idx=idx(1:end-1);
-                ICspikes(idx+1)=0;
-                ICspikes=ICspikes';
-
-                nCellsPerTau= nICcells/nANfiberTypes;
-                firstCell=1;
-                lastCell=nCellsPerTau;
-                for tauCount=1:nANfiberTypes
-                    % separate rates according to fiber types
-                    ICfiberTypeRates(tauCount, ...
-                        reducedSegmentPTR:shorterSegmentEndPTR)=...
-                        sum(ICspikes(firstCell:lastCell, :))...
-                        /(nCellsPerTau*ANdt);
-                    firstCell=firstCell+nCellsPerTau;
-                    lastCell=lastCell+nCellsPerTau;
-                end
-                ICoutput(:, reducedSegmentPTR:shorterSegmentEndPTR)=ICspikes;
-
-                if nBFs==1  % single channel
-                    x= repmat(ICmembranePotential(1,:), ANspeedUpFactor,1);
-                    x= reshape(x,1,segmentLength);
-                    if nANfiberTypes>1  % save HSR and LSR
-                        y= repmat(ICmembranePotential(end,:), ANspeedUpFactor,1);
-                        y= reshape(y,1,segmentLength);
-                        x=[x; y];
-                    end
-                    ICmembraneOutput(:, segmentStartPTR:segmentEndPTR)= x;
-                end
-
-                % estimate efferent effects.
-                % ARis based on LSR units. LSR channels are 1:nBF
-                if nANfiberTypes>1  % AR is multi-channel only
-                    ARAttSeg=sum(ICspikes(1:nBFs,:),1)/ANdt;
-                    [ARAttSeg, ARboundary] = ...
-                        filter(ARfilt_b, ARfilt_a, ARAttSeg, ARboundary);
-                    ARAttSeg=ARAttSeg-ARrateThreshold;
-                    ARAttSeg(ARAttSeg<0)=0;   % prevent negative strengths
-                    % scale up to dt from ANdt
-                    x=    repmat(ARAttSeg, ANspeedUpFactor,1);
-                    x=reshape(x,1,segmentLength);
-                    ARattenuation(segmentStartPTR:segmentEndPTR)=...
-                        (1-ARrateToAttenuationFactor* x);
-                    ARattenuation(ARattenuation<0)=0.001;
-                else
-                    % single channel model; disable AR
-                    ARattenuation(segmentStartPTR:segmentEndPTR)=...
-                        ones(1,segmentLength);
-                end
-
-                % MOC attenuation using HSR response only
-                % Separate MOC effect for each BF
-                HSRbegins=nBFs*(nANfiberTypes-1)+1;
-                rates=ICspikes(HSRbegins:end,:)/ANdt;
-                for idx=1:nBFs
-                    [smoothedRates, MOCboundary{idx}] = ...
-                        filter(MOCfilt_b, MOCfilt_a, rates(idx,:), ...
-                        MOCboundary{idx});
-                    MOCattSegment(idx,:)=smoothedRates;
-                    % expand timescale back to model dt from ANdt
-                    x= repmat(MOCattSegment(idx,:), ANspeedUpFactor,1);
-                    x= reshape(x,1,segmentLength);
-                    MOCattenuation(idx,segmentStartPTR:segmentEndPTR)= ...
-                        (1- MOCrateToAttenuationFactor*  x);
-                end
-                MOCattenuation(MOCattenuation<0)=0.04;
-                % segment debugging
-                % plotInstructions.figureNo=98;
-                % plotInstructions.displaydt=ANdt;
-                %  plotInstructions.numPlots=1;
-                %  plotInstructions.subPlotNo=1;
-                % UTIL_plotMatrix(ICspikes, plotInstructions);
-
-    end     % AN_spikesOrProbability
-    segmentStartPTR=segmentStartPTR+segmentLength;
-    reducedSegmentPTR=reducedSegmentPTR+reducedSegmentLength;
-
-
-end  % segment
-
-path(restorePath)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/MAP/old MAP files/MAPrunner.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,71 @@
+function MAPrunner(MAPparamsName, AN_spikesOrProbability, ...
+    signalCharacteristics, paramChanges, showMapOptions)
+
+dbstop if error
+restorePath=path;
+addpath (['..' filesep 'MAP'],    ['..' filesep 'wavFileStore'], ...
+    ['..' filesep 'utilities'])
+
+
+%% #3 pure tone, harmonic sequence or speech file input
+signalType= signalCharacteristics.type;
+sampleRate= signalCharacteristics.sampleRate;
+duration=signalCharacteristics.duration;                 % seconds
+rampDuration=signalCharacteristics.rampDuration;              % raised cosine ramp (seconds)
+beginSilence=signalCharacteristics.beginSilence;               
+endSilence=signalCharacteristics.endSilence;                  
+toneFrequency= signalCharacteristics.toneFrequency;            % or a pure tone (Hz)
+leveldBSPL=signalCharacteristics.leveldBSPL;
+
+BFlist=-1;
+
+
+%% Generate stimuli
+
+switch signalType
+    case 'tones'
+        % Create pure tone stimulus
+        dt=1/sampleRate; % seconds
+        time=dt: dt: duration;
+        inputSignal=sum(sin(2*pi*toneFrequency'*time), 1);
+        amp=10^(leveldBSPL/20)*28e-6;   % converts to Pascals (peak)
+        inputSignal=amp*inputSignal;
+        % apply ramps
+        % catch rampTime error
+        if rampDuration>0.5*duration, rampDuration=duration/2; end
+        rampTime=dt:dt:rampDuration;
+        ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ...
+            ones(1,length(time)-length(rampTime))];
+        inputSignal=inputSignal.*ramp;
+        ramp=fliplr(ramp);
+        inputSignal=inputSignal.*ramp;
+        % add silence
+        intialSilence= zeros(1,round(beginSilence/dt));
+        finalSilence= zeros(1,round(endSilence/dt));
+        inputSignal= [intialSilence inputSignal finalSilence];
+
+    case 'file'
+        %% file input simple or mixed
+        [inputSignal sampleRate]=wavread(fileName);
+        dt=1/sampleRate;
+        inputSignal=inputSignal(:,1);
+        targetRMS=20e-6*10^(leveldBSPL/20);
+        rms=(mean(inputSignal.^2))^0.5;
+        amp=targetRMS/rms;
+        inputSignal=inputSignal*amp;
+        intialSilence= zeros(1,round(0.1/dt));
+        finalSilence= zeros(1,round(0.2/dt));
+        inputSignal= [intialSilence inputSignal' finalSilence];
+end
+
+
+%% run the model
+
+MAP1_14(inputSignal, sampleRate, BFlist, ...
+    MAPparamsName, AN_spikesOrProbability, paramChanges);
+
+%% the model run is now complete. Now display the results
+UTIL_showMAP(showMapOptions, paramChanges)
+
+path(restorePath)
+
Binary file ReadMe MAP14.doc has changed
Binary file ReadMe MAP1_14.doc has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/multiThreshold 1.46/OHIOtest.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,99 @@
+dbstop if error
+path=pathdef;
+restorePath=path;
+addpath (['..' filesep 'utilities']) % model physiology tests
+
+globalStimParams.FS=100000;
+doPlot=0;
+
+stim.type='OHIO';
+stim.OHIOtype='OHIOrand';
+stim.phases='sin';
+stim.beginSilence=0;
+stim.endSilence=-1;
+stim.rampOnDur=.002;
+stim.rampOffDur=-1;
+
+% 1. ‘OHIOabs’ paradigm is a baseline procedure for measuring absolute
+% thresholds (in dB SPL) of the single tone with 12 frequencies:
+%    1   2    3     4    5     6     7     8     9     10     11    12
+% 494, 663, 870, 1125, 1442, 1838, 2338, 2957, 3725, 4689, 5866, 7334
+
+% 2. ‘OHIOtemp’ is for measuring thresholds for temporally integrated
+% combinations of 2, 4, 8, and 12 tones presented simultaneously.
+% In our experiment, we used 4680Hz frequency.
+
+% 3. ‘OHIOspec’ is for measuring thresholds for spectrally integrated
+% combinations of 2(7335 and 5866Hz), 4(7334, 5866, 4680, and 3725Hz),
+% 8(7334, 5866, 4680, 3725, 2957, 2338, 1838, and
+% 1442Hz), and
+% 12(all 12 frequencies) tones presented simultaneously.
+
+% 4. ‘OHIOspectemp’ is for measuring thresholds for patterned signals
+% differing in both the spectral and temporal domains.
+% The frequency conditions are the same as that of ‘OHIOspec’.
+
+% 5. ‘OHIOrand’ is for measuring thresholds for spectrotemporally varying
+% signals with random frequency presentation.
+
+nTonesList=[2 4 8 12];
+allFreqs=[494, 663, 870, 1125, 1442, 1838, 2338, 2957, 3725, 4689, 5866, 7334];
+absThresholds= 50*ones(1,12);   % protem
+
+for nTones=nTonesList
+    switch stim.OHIOtype
+        case ' OHIOabs'
+            % one tone frequency at a time
+            stim.frequencies=allFreqs(1);
+            stim.amplitudesdB=0;    
+
+        case 'OHIOrand'
+            % chose nTones frequencies at random
+            x=rand(1,12);
+            [sorted idx]=sort(x);
+            stim.frequencies=allFreqs(idx(1:nTones));
+            stim.amplitudesdB=absThresholds(idx);
+
+        case 'OHIOtemp'
+            % 4680 Hz repeated nTones times
+            stim.frequencies=4680*ones(1,nTones);
+            stim.amplitudesdB=repmat(absThresholds(10),1,nTones);   
+
+        case {'OHIOspect',  'OHIOspectemp'}
+            % nTones frequencies either simulataneously or sequentially
+            switch nTones
+                case 2
+                    stim.frequencies=[7335 5866];
+                    idx=[12 11];
+                    stim.amplitudesdB=absThresholds(idx);    
+                case 4
+                    stim.frequencies=[7334, 5866, 4680, 3725];
+                    idx=[12:-1:9 ];
+                    stim.amplitudesdB=absThresholds(idx);    
+                case 8
+                    stim.frequencies=...
+                        [7334, 5866, 4680, 3725, 2957, 2338, 1838, 1442];
+                    idx=[12:-1:5 ];
+                    stim.amplitudesdB=absThresholds(idx);    
+                case 12
+                    stim.frequencies=allFreqs;
+                    idx=[12:-1:1 ];
+                    stim.amplitudesdB=absThresholds(idx);    
+            end
+    end
+
+    switch stim.OHIOtype
+        case {'OHIOabs', 'OHIOspect'}
+            stim.toneDuration=.02;
+            globalStimParams.overallDuration=stim.toneDuration;
+        otherwise
+            stim.toneDuration=nTones*0.02;
+            globalStimParams.overallDuration=stim.toneDuration;
+    end
+
+    disp(num2str(stim.frequencies))
+
+    [audio, msg]=stimulusCreate(globalStimParams, stim, doPlot);
+    wavplay(audio,globalStimParams.FS)
+end
+path=restorePath;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/multiThreshold 1.46/hs_err_pid8684.log	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,290 @@
+#
+# An unexpected error has been detected by Java Runtime Environment:
+#
+#  EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x0000000031425110, pid=8684, tid=6796
+#
+# Java VM: Java HotSpot(TM) 64-Bit Server VM (1.6.0-b105 mixed mode)
+# Problematic frame:
+# C  [awt.dll+0x185110]
+#
+# If you would like to submit a bug report, please visit:
+#   http://java.sun.com/webapps/bugreport/crash.jsp
+#
+
+---------------  T H R E A D  ---------------
+
+Current thread (0x0000000030ebc400):  JavaThread "AWT-EventQueue-0" [_thread_in_native, id=6796]
+
+siginfo: ExceptionCode=0xc0000005, reading address 0xffffffffffffffff
+
+Registers:
+EAX=0x8000008463a878df, EBX=0x0000000000000001, ECX=0x000000003099f710, EDX=0x00000000308c01b0
+ESP=0x0000000031a7e520, EBP=0x0000000030dbd350, ESI=0x0000000030ebc590, EDI=0x0000000000000000
+EIP=0x0000000031425110, EFLAGS=0x0000000000010202
+
+Top of Stack: (sp=0x0000000031a7e520)
+0x0000000031a7e520:   0000000030ebc400 0000000000000000
+0x0000000031a7e530:   0000000031a7e670 0000000015dfcd98
+0x0000000031a7e540:   0000000000000001 0000000031426dd3
+0x0000000031a7e550:   0000000000000001 0000000030dbd350
+0x0000000031a7e560:   0000000030ebc590 0000000000000000
+0x0000000031a7e570:   00000000308c01b0 0000000016a0e600
+0x0000000031a7e580:   0000000000000004 00000000152cd810
+0x0000000031a7e590:   0000000000000000 0000000000000000
+0x0000000031a7e5a0:   0000000000000001 0000000000000102
+0x0000000031a7e5b0:   00000000122a308e 0000000000000001
+0x0000000031a7e5c0:   0000000031a7e648 00000000122afc24
+0x0000000031a7e5d0:   0000000000000000 0000000026b4b368
+0x0000000031a7e5e0:   0000000000000000 0000000015dfcd98
+0x0000000031a7e5f0:   0000000000000001 0000000000000000
+0x0000000031a7e600:   0000000031a7e5f0 0000000031a7e608
+0x0000000031a7e610:   0000000000000000 0000000031a7e670 
+
+Instructions: (pc=0x0000000031425110)
+0x0000000031425100:   e8 5b 72 f9 ff 48 8b 0d 04 9a 08 00 48 8b 04 d8
+0x0000000031425110:   48 8b 58 30 e8 67 72 f9 ff 48 8b c3 48 83 c4 20 
+
+
+Stack: [0x0000000031a00000,0x0000000031a80000),  sp=0x0000000031a7e520,  free space=505k
+Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)
+C  [awt.dll+0x185110]
+
+Java frames: (J=compiled Java code, j=interpreted, Vv=VM code)
+j  sun.awt.Win32GraphicsConfig.getBounds(I)Ljava/awt/Rectangle;+0
+j  sun.awt.Win32GraphicsConfig.getBounds()Ljava/awt/Rectangle;+8
+j  com.mathworks.mwswing.WindowUtils.getVirtualScreenBounds()Ljava/awt/Rectangle;+98
+j  com.mathworks.mwswing.MJUtilities.getVirtualScreenBounds()Ljava/awt/Rectangle;+0
+j  com.mathworks.widgets.tokenmatch.TokenMatchPopup.outOfScreenBounds(Ljava/awt/Rectangle;ZZ)Z+0
+j  com.mathworks.widgets.tokenmatch.TokenMatchPopup.startTimerAndShowPopupIfNecessary(Ljavax/swing/text/JTextComponent;[IZILcom/mathworks/widgets/tokenmatch/TokenMatchPopup$TokenMatchListener;Lcom/mathworks/widgets/tokenmatch/TokenMatchPopup$Language;)V+380
+j  com.mathworks.widgets.text.MWCaret$DelimiterMatchingImpl.startTimerAndShowPopupIfNecessary(Ljavax/swing/text/JTextComponent;[IZILcom/mathworks/widgets/tokenmatch/TokenMatchPopup$TokenMatchListener;Lcom/mathworks/widgets/tokenmatch/TokenMatchPopup$Language;)V+12
+j  com.mathworks.widgets.text.MWCaret.doTokenMatchPopup([IZI)V+59
+j  com.mathworks.widgets.text.MWCaret.drawNewMarks(ZZ[II)V+76
+j  com.mathworks.widgets.text.MWCaret.updateMatchBrace(ZI)V+359
+j  com.mathworks.widgets.text.MWKit.doBraceMatch(Ljavax/swing/text/JTextComponent;Z)V+60
+j  com.mathworks.widgets.text.MWKit.access$400(Ljavax/swing/text/JTextComponent;Z)V+2
+j  com.mathworks.widgets.text.MWKit$MWUpAction.actionPerformed(Ljava/awt/event/ActionEvent;Ljavax/swing/text/JTextComponent;)V+8
+j  org.netbeans.editor.BaseAction.actionPerformed(Ljava/awt/event/ActionEvent;)V+229
+j  javax.swing.SwingUtilities.notifyAction(Ljavax/swing/Action;Ljavax/swing/KeyStroke;Ljava/awt/event/KeyEvent;Ljava/lang/Object;I)Z+132
+J  javax.swing.JComponent.processKeyBinding(Ljavax/swing/KeyStroke;Ljava/awt/event/KeyEvent;IZ)Z
+J  javax.swing.JComponent.processKeyBindings(Ljava/awt/event/KeyEvent;Z)Z
+j  javax.swing.JComponent.processKeyEvent(Ljava/awt/event/KeyEvent;)V+51
+J  com.mathworks.widgets.SyntaxTextPaneBase.processKeyEvent(Ljava/awt/event/KeyEvent;)V
+j  java.awt.Component.processEvent(Ljava/awt/AWTEvent;)V+121
+j  java.awt.Container.processEvent(Ljava/awt/AWTEvent;)V+18
+j  java.awt.Component.dispatchEventImpl(Ljava/awt/AWTEvent;)V+562
+j  java.awt.Container.dispatchEventImpl(Ljava/awt/AWTEvent;)V+42
+J  java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(Ljava/awt/event/KeyEvent;)Z
+j  java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(Ljava/awt/Component;Ljava/awt/AWTEvent;)Z+157
+j  java.awt.DefaultKeyboardFocusManager.dispatchEvent(Ljava/awt/AWTEvent;)Z+1455
+j  java.awt.Component.dispatchEventImpl(Ljava/awt/AWTEvent;)V+128
+j  java.awt.Container.dispatchEventImpl(Ljava/awt/AWTEvent;)V+42
+j  java.awt.Window.dispatchEventImpl(Ljava/awt/AWTEvent;)V+19
+J  java.awt.EventDispatchThread.pumpOneEventForFilters(I)Z
+J  java.awt.EventDispatchThread.pumpEventsForFilter(ILjava/awt/Conditional;Ljava/awt/EventFilter;)V
+j  java.awt.EventDispatchThread.pumpEventsForHierarchy(ILjava/awt/Conditional;Ljava/awt/Component;)V+11
+j  java.awt.EventDispatchThread.pumpEvents(ILjava/awt/Conditional;)V+4
+j  java.awt.EventDispatchThread.pumpEvents(Ljava/awt/Conditional;)V+3
+j  java.awt.EventDispatchThread.run()V+9
+v  ~StubRoutines::call_stub
+
+---------------  P R O C E S S  ---------------
+
+Java Threads: ( => current thread )
+  0x000000003118d800 JavaThread "Thread-585" [_thread_blocked, id=7968]
+  0x0000000032494400 JavaThread "Timer-9" [_thread_blocked, id=7196]
+  0x0000000032496400 JavaThread "Thread-486" [_thread_blocked, id=6792]
+  0x0000000032497c00 JavaThread "Prefs Updater" [_thread_blocked, id=7836]
+  0x0000000032495800 JavaThread "Thread-17" [_thread_blocked, id=8688]
+  0x0000000032495000 JavaThread "Thread-16" [_thread_blocked, id=4192]
+  0x0000000030fb2000 JavaThread "Thread-10" [_thread_blocked, id=6964]
+  0x0000000030fb1c00 JavaThread "Thread-9" [_thread_blocked, id=860]
+  0x0000000030fb1400 JavaThread "Thread-8" [_thread_blocked, id=4756]
+  0x0000000030fb0c00 JavaThread "Active Reference Queue Daemon" daemon [_thread_blocked, id=4000]
+  0x0000000030fb0400 JavaThread "Timer-3" daemon [_thread_blocked, id=9188]
+  0x0000000030fafc00 JavaThread "Timer-2" daemon [_thread_blocked, id=1888]
+  0x0000000030db4000 JavaThread "TimerQueue" daemon [_thread_blocked, id=8140]
+=>0x0000000030ebc400 JavaThread "AWT-EventQueue-0" [_thread_in_native, id=6796]
+  0x0000000030d5a800 JavaThread "AWT-Windows" daemon [_thread_in_native, id=8608]
+  0x0000000030d58000 JavaThread "AWT-Shutdown" [_thread_blocked, id=8820]
+  0x0000000030d57c00 JavaThread "Java2D Disposer" daemon [_thread_blocked, id=2432]
+  0x0000000011de1c00 JavaThread "Timer-0" [_thread_blocked, id=1136]
+  0x0000000011d82400 JavaThread "Low Memory Detector" daemon [_thread_blocked, id=6404]
+  0x0000000011d80400 JavaThread "CompilerThread1" daemon [_thread_blocked, id=8664]
+  0x0000000011d78400 JavaThread "CompilerThread0" daemon [_thread_blocked, id=7624]
+  0x0000000011d77800 JavaThread "Attach Listener" daemon [_thread_blocked, id=7480]
+  0x0000000011d5f400 JavaThread "Finalizer" daemon [_thread_blocked, id=2340]
+  0x0000000011d59c00 JavaThread "Reference Handler" daemon [_thread_blocked, id=5252]
+  0x0000000003d2fc00 JavaThread "main" [_thread_in_native, id=8136]
+
+Other Threads:
+  0x0000000011d56400 VMThread [id=6160]
+  0x0000000003d35800 WatcherThread [id=7524]
+
+VM state:not at safepoint (normal execution)
+
+VM Mutex/Monitor currently owned by a thread: None
+
+Heap
+ PSYoungGen      total 9536K, used 6541K [0x00000000265a0000, 0x0000000027110000, 0x00000000296a0000)
+  eden space 8896K, 66% used [0x00000000265a0000,0x0000000026b6b5d8,0x0000000026e50000)
+  from space 640K, 95% used [0x0000000026ee0000,0x0000000026f78000,0x0000000026f80000)
+  to   space 1280K, 0% used [0x0000000026fd0000,0x0000000026fd0000,0x0000000027110000)
+ PSOldGen        total 75392K, used 55116K [0x000000001d2a0000, 0x0000000021c40000, 0x00000000265a0000)
+  object space 75392K, 73% used [0x000000001d2a0000,0x0000000020873098,0x0000000021c40000)
+ PSPermGen       total 66688K, used 44568K [0x00000000152a0000, 0x00000000193c0000, 0x000000001d2a0000)
+  object space 66688K, 66% used [0x00000000152a0000,0x0000000017e26168,0x00000000193c0000)
+
+Dynamic libraries:
+0x0000000140000000 - 0x0000000140138000 	C:\Program Files\MATLAB\R2008a\bin\win64\MATLAB.exe
+0x0000000077c80000 - 0x0000000077e29000 	C:\Windows\SYSTEM32\ntdll.dll
+0x0000000077b60000 - 0x0000000077c7f000 	C:\Windows\system32\kernel32.dll
+0x000007fefdda0000 - 0x000007fefde0b000 	C:\Windows\system32\KERNELBASE.dll
+0x0000000180000000 - 0x0000000180401000 	C:\Program Files\MATLAB\R2008a\bin\win64\libut.dll
+0x000007fefe410000 - 0x000007fefe427000 	C:\Windows\system32\imagehlp.dll
+0x000007feff1d0000 - 0x000007feff26f000 	C:\Windows\system32\msvcrt.dll
+0x0000000077e40000 - 0x0000000077e47000 	C:\Windows\system32\PSAPI.DLL
+0x00000000010d0000 - 0x00000000010f8000 	C:\Program Files\MATLAB\R2008a\bin\win64\LIBEXPAT.dll
+0x0000000074240000 - 0x0000000074309000 	C:\Windows\WinSxS\amd64_microsoft.vc80.crt_1fc8b3b9a1e18e3b_8.0.50727.5592_none_88e45feb2faab9ce\MSVCR80.dll
+0x000000004a800000 - 0x000000004a917000 	C:\Program Files\MATLAB\R2008a\bin\win64\icuuc36.dll
+0x000007feffb90000 - 0x000007feffc6b000 	C:\Windows\system32\ADVAPI32.dll
+0x000007fefe2e0000 - 0x000007fefe2ff000 	C:\Windows\SYSTEM32\sechost.dll
+0x000007feff8e0000 - 0x000007feffa0d000 	C:\Windows\system32\RPCRT4.dll
+0x0000000001120000 - 0x0000000001123000 	C:\Program Files\MATLAB\R2008a\bin\win64\icudt36.dll
+0x000000004ab00000 - 0x000000004ab0f000 	C:\Program Files\MATLAB\R2008a\bin\win64\icuio36.dll
+0x0000000001250000 - 0x0000000001356000 	C:\Program Files\MATLAB\R2008a\bin\win64\icuin36.dll
+0x0000000072aa0000 - 0x0000000072ba9000 	C:\Windows\WinSxS\amd64_microsoft.vc80.crt_1fc8b3b9a1e18e3b_8.0.50727.5592_none_88e45feb2faab9ce\MSVCP80.dll
+0x0000000077a60000 - 0x0000000077b5a000 	C:\Windows\system32\USER32.dll
+0x000007fefe300000 - 0x000007fefe367000 	C:\Windows\system32\GDI32.dll
+0x000007feff4b0000 - 0x000007feff4be000 	C:\Windows\system32\LPK.dll
+0x000007feffdd0000 - 0x000007feffe99000 	C:\Windows\system32\USP10.dll
+0x0000000001370000 - 0x00000000014e4000 	C:\Program Files\MATLAB\R2008a\bin\win64\libmwservices.dll
+0x0000000001500000 - 0x0000000001570000 	C:\Program Files\MATLAB\R2008a\bin\win64\libmx.dll
+0x0000000001580000 - 0x0000000001597000 	C:\Program Files\MATLAB\R2008a\bin\win64\zlib1.dll
+0x00000000015a0000 - 0x0000000001648000 	C:\Program Files\MATLAB\R2008a\bin\win64\libmwmathutil.dll
+0x0000000001660000 - 0x00000000016b5000 	C:\Program Files\MATLAB\R2008a\bin\win64\mpath.dll
+0x00000000016d0000 - 0x00000000016f1000 	C:\Program Files\MATLAB\R2008a\bin\win64\mlutil.dll
+0x000007fefa0d0000 - 0x000007fefa170000 	C:\Windows\WinSxS\amd64_microsoft.windows.common-controls_6595b64144ccf1df_5.82.7601.17514_none_a4d6a923711520a9\COMCTL32.dll
+0x000007feffea0000 - 0x000007fefff37000 	C:\Windows\system32\comdlg32.dll
+0x000007feffc70000 - 0x000007feffce1000 	C:\Windows\system32\SHLWAPI.dll
+0x000007fefe430000 - 0x000007feff1b8000 	C:\Windows\system32\SHELL32.dll
+0x000007fefd190000 - 0x000007fefd1a6000 	C:\Windows\system32\NETAPI32.dll
+0x000007fefd120000 - 0x000007fefd12c000 	C:\Windows\system32\netutils.dll
+0x000007fefd720000 - 0x000007fefd743000 	C:\Windows\system32\srvcli.dll
+0x000007fefd070000 - 0x000007fefd085000 	C:\Windows\system32\wkscli.dll
+0x000007fefff40000 - 0x000007fefff8d000 	C:\Windows\system32\WS2_32.dll
+0x000007feff1c0000 - 0x000007feff1c8000 	C:\Windows\system32\NSI.dll
+0x0000000001710000 - 0x0000000001765000 	C:\Program Files\MATLAB\R2008a\bin\win64\mcr.dll
+0x0000000001780000 - 0x00000000017a5000 	C:\Program Files\MATLAB\R2008a\bin\win64\iqm.dll
+0x00000000017c0000 - 0x00000000017e1000 	C:\Program Files\MATLAB\R2008a\bin\win64\bridge.dll
+0x0000000001800000 - 0x0000000001811000 	C:\Program Files\MATLAB\R2008a\bin\win64\libmex.dll
+0x0000000001830000 - 0x00000000018bc000 	C:\Program Files\MATLAB\R2008a\bin\win64\m_dispatcher.dll
+0x00000000018d0000 - 0x00000000018f5000 	C:\Program Files\MATLAB\R2008a\bin\win64\datasvcs.dll
+0x0000000012000000 - 0x0000000012295000 	C:\Program Files\MATLAB\R2008a\bin\win64\xerces-c_2_7.dll
+0x0000000001920000 - 0x00000000021b1000 	C:\Program Files\MATLAB\R2008a\bin\win64\m_interpreter.dll
+0x00000000021d0000 - 0x0000000002201000 	C:\Program Files\MATLAB\R2008a\bin\win64\libmat.dll
+0x0000000002220000 - 0x0000000002325000 	C:\Program Files\MATLAB\R2008a\bin\win64\libhdf5.dll
+0x0000000002330000 - 0x000000000239f000 	C:\Program Files\MATLAB\R2008a\bin\win64\profiler.dll
+0x00000000023b0000 - 0x00000000023ba000 	C:\Program Files\MATLAB\R2008a\bin\win64\libmwmathrng.dll
+0x00000000023d0000 - 0x00000000023ea000 	C:\Program Files\MATLAB\R2008a\bin\win64\m_pcodeio.dll
+0x0000000002400000 - 0x000000000244a000 	C:\Program Files\MATLAB\R2008a\bin\win64\m_ir.dll
+0x0000000002460000 - 0x0000000002a1b000 	C:\Program Files\MATLAB\R2008a\bin\win64\m_parser.dll
+0x0000000002a30000 - 0x0000000002a42000 	C:\Program Files\MATLAB\R2008a\bin\win64\ir_xfmr.dll
+0x0000000002a60000 - 0x0000000002c7b000 	C:\Program Files\MATLAB\R2008a\bin\win64\mcos.dll
+0x0000000002c90000 - 0x0000000002c9c000 	C:\Program Files\MATLAB\R2008a\bin\win64\mtok.dll
+0x0000000002cb0000 - 0x0000000002cd0000 	C:\Program Files\MATLAB\R2008a\bin\win64\m_pcodegen.dll
+0x000007fef49f0000 - 0x000007fef4b15000 	C:\Windows\system32\dbghelp.dll
+0x0000000002ce0000 - 0x0000000002cf0000 	C:\Program Files\MATLAB\R2008a\bin\win64\boost_thread-vc80-mt-1_34_1.dll
+0x0000000002d00000 - 0x0000000002dc0000 	C:\Program Files\MATLAB\R2008a\bin\win64\udd.dll
+0x0000000002dd0000 - 0x0000000002f12000 	C:\Program Files\MATLAB\R2008a\bin\win64\libmwgui.dll
+0x0000000002f30000 - 0x000000000316a000 	C:\Program Files\MATLAB\R2008a\bin\win64\hg.dll
+0x0000000003180000 - 0x00000000031d6000 	C:\Program Files\MATLAB\R2008a\bin\win64\jmi.dll
+0x00000000031f0000 - 0x000000000322e000 	C:\Program Files\MATLAB\R2008a\bin\win64\libmwhardcopy.dll
+0x0000000003240000 - 0x000000000329c000 	C:\Program Files\MATLAB\R2008a\bin\win64\libuij.dll
+0x00000000032b0000 - 0x000000000353c000 	C:\Program Files\MATLAB\R2008a\bin\win64\numerics.dll
+0x0000000003550000 - 0x000000000355c000 	C:\Program Files\MATLAB\R2008a\bin\win64\libmwblas.dll
+0x0000000003570000 - 0x000000000357f000 	C:\Program Files\MATLAB\R2008a\bin\win64\libmwbinder.dll
+0x0000000003590000 - 0x00000000035b4000 	C:\Program Files\MATLAB\R2008a\bin\win64\libmwlapack.dll
+0x00000000035d0000 - 0x00000000035db000 	C:\Program Files\MATLAB\R2008a\bin\win64\libmwfftw.dll
+0x00000000035f0000 - 0x0000000003625000 	C:\Program Files\MATLAB\R2008a\bin\win64\libmwrookfastbp.dll
+0x0000000003640000 - 0x000000000366e000 	C:\Program Files\MATLAB\R2008a\bin\win64\libmwma57.dll
+0x0000000010000000 - 0x00000000100d3000 	C:\Program Files\MATLAB\R2008a\bin\win64\libifcoremd.dll
+0x0000000003680000 - 0x000000000389d000 	C:\Program Files\MATLAB\R2008a\bin\win64\libmmd.dll
+0x00000000038a0000 - 0x00000000038a9000 	C:\Program Files\MATLAB\R2008a\bin\win64\libmwcsparse.dll
+0x00000000038c0000 - 0x000000000398a000 	C:\Program Files\MATLAB\R2008a\bin\win64\libmwumfpack.dll
+0x00000000039a0000 - 0x00000000039ad000 	C:\Program Files\MATLAB\R2008a\bin\win64\libmwamd.dll
+0x00000000039c0000 - 0x0000000003a52000 	C:\Program Files\MATLAB\R2008a\bin\win64\libmwcholmod.dll
+0x0000000003a70000 - 0x0000000003a7c000 	C:\Program Files\MATLAB\R2008a\bin\win64\libmwcolamd.dll
+0x0000000003a90000 - 0x0000000003b49000 	C:\Program Files\MATLAB\R2008a\bin\win64\uiw.dll
+0x0000000003b60000 - 0x0000000003b6a000 	C:\Program Files\MATLAB\R2008a\bin\win64\uinone.dll
+0x00000000723a0000 - 0x000000007253c000 	C:\Windows\WinSxS\amd64_microsoft.vc80.mfc_1fc8b3b9a1e18e3b_8.0.50727.5592_none_8448f49f328da8c3\MFC80.DLL
+0x000007fefbef0000 - 0x000007fefbf61000 	C:\Windows\system32\WINSPOOL.DRV
+0x000007feff6d0000 - 0x000007feff8d3000 	C:\Windows\system32\ole32.dll
+0x000007feffcf0000 - 0x000007feffdc7000 	C:\Windows\system32\OLEAUT32.dll
+0x0000000003b80000 - 0x0000000003c10000 	C:\Program Files\MATLAB\R2008a\bin\win64\udd_mi.dll
+0x0000000003c20000 - 0x0000000003c38000 	C:\Program Files\MATLAB\R2008a\bin\win64\mwoles05.DLL
+0x0000000003c50000 - 0x0000000003cb9000 	C:\Program Files\MATLAB\R2008a\bin\win64\comcli.dll
+0x0000000072a80000 - 0x0000000072aa0000 	C:\Windows\WinSxS\amd64_microsoft.vc80.atl_1fc8b3b9a1e18e3b_8.0.50727.5592_none_8a1e1b372ed7b012\ATL80.DLL
+0x0000000003cd0000 - 0x0000000003cde000 	C:\Program Files\MATLAB\R2008a\bin\win64\mlautoregister.dll
+0x000007feff4c0000 - 0x000007feff4ee000 	C:\Windows\system32\IMM32.DLL
+0x000007feff270000 - 0x000007feff379000 	C:\Windows\system32\MSCTF.dll
+0x000000006fa00000 - 0x000000006fa3f000 	C:\PROGRA~2\Sophos\SOPHOS~1\SOPHOS~2.DLL
+0x0000000007880000 - 0x000000000824e000 	C:\Program Files\MATLAB\R2008a\bin\win64\mkl.dll
+0x0000000003e70000 - 0x0000000003ebb000 	C:\Program Files\MATLAB\R2008a\bin\win64\libguide40.dll
+0x0000000003ed0000 - 0x0000000003ed8000 	C:\Program Files\MATLAB\R2008a\bin\win64\mklcompat.dll
+0x0000000008250000 - 0x00000000087f7000 	C:\Program Files\MATLAB\R2008a\bin\win64\mllapack.dll
+0x0000000007270000 - 0x0000000007364000 	C:\Program Files\MATLAB\R2008a\bin\win64\libfftw3i.dll
+0x0000000007370000 - 0x000000000745e000 	C:\Program Files\MATLAB\R2008a\bin\win64\libfftw3f.dll
+0x000007fefdbd0000 - 0x000007fefdbdf000 	C:\Windows\system32\profapi.dll
+0x000007fefdb00000 - 0x000007fefdb0f000 	C:\Windows\system32\CRYPTBASE.dll
+0x000007fefc6f0000 - 0x000007fefc8e4000 	C:\Windows\WinSxS\amd64_microsoft.windows.common-controls_6595b64144ccf1df_6.0.7601.17514_none_fa396087175ac9ac\comctl32.dll
+0x000007feff4f0000 - 0x000007feff6c7000 	C:\Windows\system32\SETUPAPI.dll
+0x000007fefdc80000 - 0x000007fefdcb6000 	C:\Windows\system32\CFGMGR32.dll
+0x000007fefdf80000 - 0x000007fefdf9a000 	C:\Windows\system32\DEVOBJ.dll
+0x000007fefe370000 - 0x000007fefe409000 	C:\Windows\system32\CLBCatQ.DLL
+0x000007fefc150000 - 0x000007fefc27c000 	C:\Windows\system32\propsys.dll
+0x000007fefb740000 - 0x000007fefb76d000 	C:\Windows\system32\ntmarta.dll
+0x000007fefe280000 - 0x000007fefe2d2000 	C:\Windows\system32\WLDAP32.dll
+0x000007fefaa10000 - 0x000007fefaa37000 	C:\Windows\system32\iphlpapi.dll
+0x000007fefaa00000 - 0x000007fefaa0b000 	C:\Windows\system32\WINNSI.DLL
+0x000007fefd290000 - 0x000007fefd2eb000 	C:\Windows\system32\DNSAPI.dll
+0x000007fefa810000 - 0x000007fefa828000 	C:\Windows\system32\dhcpcsvc.DLL
+0x000007fefa7f0000 - 0x000007fefa801000 	C:\Windows\system32\dhcpcsvc6.DLL
+0x000007fefda70000 - 0x000007fefda95000 	C:\Windows\system32\SspiCli.dll
+0x00000000722f0000 - 0x00000000722f3000 	C:\Windows\system32\icmp.Dll
+0x00000000100e0000 - 0x0000000010631000 	C:\Program Files\MATLAB\R2008a\sys\java\jre\win64\jre1.6.0\bin\server\jvm.dll
+0x000007fefb6f0000 - 0x000007fefb72b000 	C:\Windows\system32\WINMM.dll
+0x0000000006a10000 - 0x0000000006a1a000 	C:\Program Files\MATLAB\R2008a\sys\java\jre\win64\jre1.6.0\bin\hpi.dll
+0x0000000006c80000 - 0x0000000006ce5000 	C:\Program Files\WIDCOMM\Bluetooth Software\btmmhook.dll
+0x0000000007160000 - 0x000000000716e000 	C:\Program Files\MATLAB\R2008a\sys\java\jre\win64\jre1.6.0\bin\verify.dll
+0x0000000007170000 - 0x0000000007197000 	C:\Program Files\MATLAB\R2008a\sys\java\jre\win64\jre1.6.0\bin\java.dll
+0x0000000007560000 - 0x0000000007572000 	C:\Program Files\MATLAB\R2008a\sys\java\jre\win64\jre1.6.0\bin\zip.dll
+0x0000000007660000 - 0x0000000007676000 	C:\Program Files\MATLAB\R2008a\bin\win64\nativejava.dll
+0x000000000beb0000 - 0x000000000bec6000 	C:\Program Files\MATLAB\R2008a\bin\win64\nativejmi.dll
+0x00000000071e0000 - 0x00000000071e7000 	C:\Program Files\MATLAB\R2008a\bin\win64\nativeservices.dll
+0x00000000312a0000 - 0x00000000314f0000 	C:\Program Files\MATLAB\R2008a\sys\java\jre\win64\jre1.6.0\bin\awt.dll
+0x00000000315f0000 - 0x0000000031659000 	C:\Program Files\MATLAB\R2008a\sys\java\jre\win64\jre1.6.0\bin\fontmanager.dll
+
+VM Arguments:
+jvm_args: -Xss512k -XX:PermSize=32M -Xms64m -XX:NewRatio=3 -XX:MaxPermSize=128M -Xmx196m -XX:MaxDirectMemorySize=2147400000 -Dsun.java2d.noddraw=true -Dsun.awt.nopixfmt=true -Xshare:off -Xrs -Djava.library.path=C:\Program Files\MATLAB\R2008a\bin\win64 vfprintf abort
+java_command: <unknown>
+Launcher Type: generic
+
+Environment Variables:
+CLASSPATH=.;C:\Program Files (x86)\Java\jre6\lib\ext\QTJava.zip
+PATH=C:\Program Files (x86)\Nokia\PC Connectivity Solution\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files\Intel\DMIX;C:\Program Files (x86)\NTRU Cryptosystems\NTRU TCG Software Stack\bin\;C:\Program Files\NTRU Cryptosystems\NTRU TCG Software Stack\bin\;C:\Program Files\Wave Systems Corp\Gemalto\Access Client\v5\;c:\Program Files\WIDCOMM\Bluetooth Software\;c:\Program Files\WIDCOMM\Bluetooth Software\syswow64;C:\Program Files (x86)\Common Files\Roxio Shared\DLLShared\;C:\Program Files (x86)\Common Files\Roxio Shared\10.0\DLLShared\;C:\Program Files (x86)\Common Files\Adobe\AGL;C:\Program Files\MATLAB\R2010b\bin;C:\Program Files\MATLAB\R2010a\bin;C:\Program Files\MATLAB\R2008a\bin;C:\Program Files\MATLAB\R2008a\bin\win64;C:\Program Files (x86)\QuickTime\QTSystem\;C:\Program Files\Microsoft Windows Performance Toolkit\
+USERNAME=rmeddis
+OS=Windows_NT
+PROCESSOR_IDENTIFIER=Intel64 Family 6 Model 37 Stepping 2, GenuineIntel
+
+
+
+---------------  S Y S T E M  ---------------
+
+OS: Windows NT 6.1 Build 7601 Service Pack 1
+
+CPU:total 4 em64t ht
+
+Memory: 4k page, physical 8181592k(5048892k free), swap 16361336k(13057292k free)
+
+vm_info: Java HotSpot(TM) 64-Bit Server VM (1.6.0-b105) for windows-amd64, built on Nov 29 2006 00:38:01 by "java_re" with unknown MS VC++:1400
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/multiThreshold 1.46/old files/MTprofile.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,31 @@
+function x = MTprofile
+%created: 17_20hr18_Aug_2011
+
+x.BFs = [250   500  1000  2000  4000  8000];
+
+x.LongTone = [16.4      13.1      8.77      9.38      15.8      21.4];
+x.ShortTone = [18.8      15.1      11.9      13.3      20.7        25];
+
+x.Gaps = [0.01      0.03      0.05      0.07      0.09];
+x.TMCFreq = [250   500  1000  2000  4000  8000];
+x.TMC = [
+37.8	32.6	28.6	40.8	41.7	38	 
+41.5	36.3	40.1	44.5	44.6	37.5	 
+48.7	42.6	43	49.4	49.7	41.2	 
+55.4	45.6	52.2	52.9	52.3	43.2	 
+62.7	55.5	62.5	52.3	58	45.9	 
+];
+x.TMC = x.TMC';
+
+x.MaskerRatio = [0.5      0.7      0.9        1      1.1      1.3      1.6];
+x.IFMCFreq = [250   500  1000  2000  4000  8000];
+x.IFMCs = [
+44.3	58.4	66.1	73.5	81.9	82.9	 
+39.6	46.8	49.9	54	66.5	67.6	 
+36.8	36	35.1	42.8	49.9	38	 
+37	32.9	33.1	40.8	41.7	37.3	 
+34.6	30.6	30.6	41.9	42	38.3	 
+35.3	31.8	42.7	52.4	61	56.7	 
+40.5	45.3	61	75.5	85.3	90.5	 
+];
+x.IFMCs = x.IFMCs';
Binary file multiThreshold 1.46/old files/profile.mat has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/multiThreshold 1.46/paradigms/paradigmBase.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,73 @@
+function paradigmBase(handles)
+global stimulusParameters experiment betweenRuns
+
+stimulusParameters.subjectSampleRate=44100; % compatible with file input
+% stimulusParameters.subjectSampleRate=128000; % compatible with file input
+
+%  assessment method
+% {'oneIntervalUpDown', 'MaxLikelihood', '2I2AFC++', '2I2AFC+++'}
+experiment.threshEstMethod='oneIntervalUpDown';
+% {'cued', 'noCue'};
+stimulusParameters.includeCue=1;
+stimulusParameters.cueTestDifference=10;
+
+experiment.singleIntervalMaxTrials=10;
+experiment.maxTrials=10;
+experiment.allowCatchTrials= 1;
+
+% {'tone','noise', 'pinkNoise','whiteNoise','OHIO'}
+stimulusParameters.WRVname='targetLevel';
+stimulusParameters.WRVstartValues=30 ;
+stimulusParameters.WRVsteps=[10 2];
+stimulusParameters.WRVlimits=[-30 110];
+
+% target variable: slope=1, start going down.
+experiment.psyFunSlope=1;
+withinRuns.direction='down';
+
+betweenRuns.variableName1='targetFrequency';
+betweenRuns.variableList1=1000;
+betweenRuns.variableName2='targetDuration';
+betweenRuns.variableList2=0.1 ;
+% 'randomize within blocks', 'fixed sequence', 'randomize across blocks'
+betweenRuns.randomizeSequence='randomize within blocks'; 
+
+% delay > masker > gap > target
+
+stimulusParameters.stimulusDelay=0.3;
+
+% maskerTypes={'tone','noise', 'pinkNoise','TEN','whiteNoise'};
+experiment.maskerInUse=0;
+stimulusParameters.maskerType='tone';
+stimulusParameters.maskerPhase='cos';
+stimulusParameters.maskerDuration=0.0;
+stimulusParameters.maskerLevel= -50;
+stimulusParameters.maskerRelativeFrequency= 1 ; 
+
+stimulusParameters.gapDuration=0.0;
+
+% targetTypes={'tone','noise', 'pinkNoise','whiteNoise','OHIO'};
+stimulusParameters.targetType='tone';
+stimulusParameters.targetPhase='cos'; %{'sin','cos','alt','rand'}
+stimulusParameters.targetFrequency=1000;
+stimulusParameters.targetDuration=0.1;
+stimulusParameters.OHIOnTones=1;
+stimulusParameters.targetLevel=stimulusParameters.WRVstartValues(1);
+
+stimulusParameters.rampDuration=0.004;
+
+% forced choice window interval
+stimulusParameters.AFCsilenceDuration=0.5;
+
+% {'none','noise', 'pinkNoise', 'TEN','noiseDich', 'pinkNoiseDich','whiteNoise'}
+stimulusParameters.backgroundType='none'; 
+stimulusParameters.backgroundLevel=-100;
+
+% instructions to user
+%   single interval up/down no cue
+stimulusParameters.instructions{1}= [{'YES if you hear the tone clearly'}, { }, { 'NO if not (or you are uncertain'}];
+%   single interval up/down with cue
+stimulusParameters.instructions{2}= [{'count the tones you hear clearly'}, { }, { 'ignore indistinct tones'}];
+
+stimulusParameters.numOHIOtones=1;
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/multiThreshold 1.46/paradigms/paradigm_OHIOabs.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,31 @@
+function paradigm_OHIOabs(handles)
+global stimulusParameters experiment betweenRuns
+
+paradigmBase(handles) % default
+
+betweenRuns.variableName1='targetFrequency';
+betweenRuns.variableList1=...
+[494, 663, 870, 1125, 1442, 1838, 2338, 2957, 3725, 4689, 5866, 7334];
+betweenRuns.variableName2='targetDuration';
+betweenRuns.variableList2= 0.01;
+
+experiment.maskerInUse=0;
+
+stimulusParameters.targetFrequency=betweenRuns.variableList1;
+stimulusParameters.targetDuration=betweenRuns.variableList2;
+stimulusParameters.targetLevel=stimulusParameters.WRVstartValues(1);
+
+stimulusParameters.WRVstartValues=30;
+experiment.singleIntervalMaxTrials=20;
+
+% forced choice window interval
+stimulusParameters.AFCsilenceDuration=0.5;
+
+
+% instructions to user
+%   single interval up/down no cue
+stimulusParameters.instructions{1}=[{'YES if you hear the added click'}, { }, { 'NO if not (or you are uncertain'}];
+%   single interval up/down with cue
+stimulusParameters.instructions{2}=[{'count how many distinct clicks you hear'},{'ignore the tones'},{' '},...
+    {'The clicks must be **clearly distinct** to count'}];
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/multiThreshold 1.46/paradigms/paradigm_OHIOrand.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,33 @@
+function paradigm_OHIOrand(handles)
+global stimulusParameters experiment betweenRuns
+
+paradigmBase(handles) % default
+
+betweenRuns.variableName1='OHIOnTones';
+betweenRuns.variableList1=...
+[2 4 8 12];
+betweenRuns.variableName2='targetDuration';
+betweenRuns.variableList2= 0.01;
+
+experiment.maskerInUse=0;
+
+stimulusParameters.OHIOnTones=betweenRuns.variableList1;
+stimulusParameters.targetDuration=betweenRuns.variableList2;
+stimulusParameters.targetLevel=stimulusParameters.WRVstartValues(1);
+
+
+stimulusParameters.WRVstartValues=30;
+experiment.singleIntervalMaxTrials=20;
+
+
+% forced choice window interval
+stimulusParameters.AFCsilenceDuration=0.5;
+
+
+% instructions to user
+%   single interval up/down no cue
+stimulusParameters.instructions{1}=[{'YES if you hear the added click'}, { }, { 'NO if not (or you are uncertain'}];
+%   single interval up/down with cue
+stimulusParameters.instructions{2}=[{'count how many distinct clicks you hear'},{'ignore the tones'},{' '},...
+    {'The clicks must be **clearly distinct** to count'}];
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/multiThreshold 1.46/paradigms/paradigm_OHIOspect.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,33 @@
+function paradigm_OHIOspect(handles)
+global stimulusParameters experiment betweenRuns
+
+paradigmBase(handles) % default
+
+betweenRuns.variableName1='OHIOnTones';
+betweenRuns.variableList1=...
+[2 4 8 12];
+betweenRuns.variableName2='targetDuration';
+betweenRuns.variableList2= 0.01;
+
+experiment.maskerInUse=0;
+
+stimulusParameters.OHIOnTones=betweenRuns.variableList1;
+stimulusParameters.targetDuration=betweenRuns.variableList2;
+stimulusParameters.targetLevel=stimulusParameters.WRVstartValues(1);
+
+
+stimulusParameters.WRVstartValues=30;
+experiment.singleIntervalMaxTrials=20;
+
+
+% forced choice window interval
+stimulusParameters.AFCsilenceDuration=0.5;
+
+
+% instructions to user
+%   single interval up/down no cue
+stimulusParameters.instructions{1}=[{'YES if you hear the added click'}, { }, { 'NO if not (or you are uncertain'}];
+%   single interval up/down with cue
+stimulusParameters.instructions{2}=[{'count how many distinct clicks you hear'},{'ignore the tones'},{' '},...
+    {'The clicks must be **clearly distinct** to count'}];
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/multiThreshold 1.46/paradigms/paradigm_OHIOspectemp.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,33 @@
+function paradigm_OHIOspectemp(handles)
+global stimulusParameters experiment betweenRuns
+
+paradigmBase(handles) % default
+
+betweenRuns.variableName1='OHIOnTones';
+betweenRuns.variableList1=...
+[2 4 8 12];
+betweenRuns.variableName2='targetDuration';
+betweenRuns.variableList2= 0.01;
+
+experiment.maskerInUse=0;
+
+stimulusParameters.OHIOnTones=betweenRuns.variableList1;
+stimulusParameters.targetDuration=betweenRuns.variableList2;
+stimulusParameters.targetLevel=stimulusParameters.WRVstartValues(1);
+
+
+stimulusParameters.WRVstartValues=30;
+experiment.singleIntervalMaxTrials=20;
+
+
+% forced choice window interval
+stimulusParameters.AFCsilenceDuration=0.5;
+
+
+% instructions to user
+%   single interval up/down no cue
+stimulusParameters.instructions{1}=[{'YES if you hear the added click'}, { }, { 'NO if not (or you are uncertain'}];
+%   single interval up/down with cue
+stimulusParameters.instructions{2}=[{'count how many distinct clicks you hear'},{'ignore the tones'},{' '},...
+    {'The clicks must be **clearly distinct** to count'}];
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/multiThreshold 1.46/paradigms/paradigm_OHIOtemp.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,33 @@
+function paradigm_OHIOtemp(handles)
+global stimulusParameters experiment betweenRuns
+
+paradigmBase(handles) % default
+
+betweenRuns.variableName1='OHIOnTones';
+betweenRuns.variableList1=...
+[2 4 8 12];
+betweenRuns.variableName2='targetDuration';
+betweenRuns.variableList2= 0.01;
+
+experiment.maskerInUse=0;
+
+stimulusParameters.OHIOnTones=betweenRuns.variableList1;
+stimulusParameters.targetDuration=betweenRuns.variableList2;
+stimulusParameters.targetLevel=stimulusParameters.WRVstartValues(1);
+
+
+stimulusParameters.WRVstartValues=30;
+experiment.singleIntervalMaxTrials=20;
+
+
+% forced choice window interval
+stimulusParameters.AFCsilenceDuration=0.5;
+
+
+% instructions to user
+%   single interval up/down no cue
+stimulusParameters.instructions{1}=[{'YES if you hear the added click'}, { }, { 'NO if not (or you are uncertain'}];
+%   single interval up/down with cue
+stimulusParameters.instructions{2}=[{'count how many distinct clicks you hear'},{'ignore the tones'},{' '},...
+    {'The clicks must be **clearly distinct** to count'}];
+
Binary file multiThreshold 1.46/savedData/Meddis/Meddis 26-Sep-2011 08_46_01.mat has changed
Binary file multiThreshold 1.46/savedData/Normal/Normal 04-Oct-2011 15_23_57.mat has changed
Binary file multiThreshold 1.46/savedData/statsModel/statsModel 26-Sep-2011 08_44_18.mat has changed
Binary file multiThreshold 1.46/savedData/statsModel/statsModel 26-Sep-2011 08_44_28.mat has changed
Binary file multiThreshold 1.46/ten.wav has changed
--- a/multithreshold 1.46/MTprofile.m	Thu Oct 06 15:43:20 2011 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,31 +0,0 @@
-function x = MTprofile
-%created: 17_20hr18_Aug_2011
-
-x.BFs = [250   500  1000  2000  4000  8000];
-
-x.LongTone = [16.4      13.1      8.77      9.38      15.8      21.4];
-x.ShortTone = [18.8      15.1      11.9      13.3      20.7        25];
-
-x.Gaps = [0.01      0.03      0.05      0.07      0.09];
-x.TMCFreq = [250   500  1000  2000  4000  8000];
-x.TMC = [
-37.8	32.6	28.6	40.8	41.7	38	 
-41.5	36.3	40.1	44.5	44.6	37.5	 
-48.7	42.6	43	49.4	49.7	41.2	 
-55.4	45.6	52.2	52.9	52.3	43.2	 
-62.7	55.5	62.5	52.3	58	45.9	 
-];
-x.TMC = x.TMC';
-
-x.MaskerRatio = [0.5      0.7      0.9        1      1.1      1.3      1.6];
-x.IFMCFreq = [250   500  1000  2000  4000  8000];
-x.IFMCs = [
-44.3	58.4	66.1	73.5	81.9	82.9	 
-39.6	46.8	49.9	54	66.5	67.6	 
-36.8	36	35.1	42.8	49.9	38	 
-37	32.9	33.1	40.8	41.7	37.3	 
-34.6	30.6	30.6	41.9	42	38.3	 
-35.3	31.8	42.7	52.4	61	56.7	 
-40.5	45.3	61	75.5	85.3	90.5	 
-];
-x.IFMCs = x.IFMCs';
Binary file multithreshold 1.46/documentation/MultiThreshold manual.doc has changed
Binary file multithreshold 1.46/documentation/The multiThreshold guide to getting started.doc has changed
Binary file multithreshold 1.46/forward masking figures.ppt has changed
Binary file multithreshold 1.46/multiThreshold.fig has changed
--- a/multithreshold 1.46/multiThreshold.m	Thu Oct 06 15:43:20 2011 +0100
+++ b/multithreshold 1.46/multiThreshold.m	Mon Nov 28 13:34:28 2011 +0000
@@ -46,7 +46,7 @@
 
 % Edit the above text to modify the response to help multiThreshold
 
-% Last Modified by GUIDE v2.5 20-Sep-2011 11:47:22
+% Last Modified by GUIDE v2.5 25-Oct-2011 07:51:14
 
 % Begin initialization code - DO NOT EDIT
 gui_Singleton = 1;
@@ -93,7 +93,7 @@
 % Then wait for user action
 global stimulusParameters experiment betweenRuns
 global targetTypes maskerTypes backgroundTypes
-global variableNames paradigmNames threshEstNames  cueNames
+global variableNames paradigmNames threshEstNames  cueNames betweenRunsVariables
 
 % Specify order of fields in main structures
 % identify as empty values or empty strings only
@@ -106,13 +106,14 @@
 variableNames={'stimulusDelay','maskerDuration','maskerLevel',...
     'maskerRelativeFrequency', 'targetFrequency', 'gapDuration',...
     'targetDuration','targetLevel','rampDuration',...
-    'cueTestDifference', 'WRVstartValues', 'WRVsteps', 'WRVlimits'};
+    'cueTestDifference', 'WRVstartValues', 'WRVsteps', 'WRVlimits',...
+    'OHIOnTones'};
 
 % Variable variables
 %  (names of variable that can changed between runs)
 betweenRunsVariables={'stimulusDelay','maskerDuration','maskerLevel',...
     'maskerRelativeFrequency','targetFrequency', 'gapDuration',...
-    'targetDuration','targetLevel','numOHIOtones'};
+    'targetDuration','targetLevel','OHIOnTones'};
 % populate the 'between runs variable' menus
 set(handles.popupmenuVaryParameter1,'string',betweenRunsVariables)
 set(handles.popupmenuVaryParameter2,'string',betweenRunsVariables)
@@ -143,6 +144,8 @@
 % Establish available paradigms by scanning paradigms folder
 paradigmNames= what('paradigms');
 paradigmNames= paradigmNames.m; % select m files only
+idx=strmatch('paradigm_', paradigmNames); % with 'paradigm_'
+paradigmNames=paradigmNames(idx);
 for i=1:length(paradigmNames)   % strip off file extension
     paradigmNames{i}=paradigmNames{i}(10:end-2); 
 end
@@ -183,7 +186,7 @@
     '2I2AFC++', '2I2AFC+++'};
 set(handles.popupmenuThreshEst, 'string', threshEstNames);
 experiment.stopCriteria2IFC=[75 3 5];
-experiment.stopCriteriaSI=[20];
+experiment.stopCriteriaSI=20;
 
 % ** editBoxes that are only set by hand
 % music (relative) level, 'tada!' (manual setting only)
@@ -191,7 +194,7 @@
 set(handles.editMusicLevel,'string','0')
 
 % Catch Trial Rate
-set(handles.editCatchTrialRate,'string','0.2   0.1  2 ');
+set(handles.editCatchTrialRate,'string','0.2   0.1  ');
 
 % calibration
 stimulusParameters.restoreCalibration=7;
@@ -205,6 +208,7 @@
 % saveData
 experiment.saveData=1;
 set(handles.editSaveData,'string',num2str(experiment.saveData))
+set(handles.pushbuttonSave,'visible','off')
 
 % printTracks
 experiment.printTracks=0;
@@ -336,6 +340,25 @@
 set(handles.editBackgroundLevel,'string', num2str...
     (stimulusParameters.backgroundLevel))
 
+% values related to assessment method
+switch experiment.threshEstMethod
+    case {'MaxLikelihood','oneIntervalUpDown'}
+        set(handles.editstopCriteriaBox, 'string', ...
+            num2str(experiment.singleIntervalMaxTrials))
+    case {'2I2AFC++','2I2AFC+++'}
+        set(handles.editstopCriteriaBox, 'string', ...
+            num2str(experiment.stopCriteria2IFC))
+    otherwise
+        error([' aResetPopupMenus:  threshEstMethod not recognised -> ' ...
+            experiment.threshEstMethod])
+end
+% assessment method popup may be changed between paradigms
+%  e.g. SRT must be one interval
+x=get(handles.popupmenuThreshEst, 'string');
+set(handles.popupmenuThreshEst, 'value', ...
+    strmatch(experiment.threshEstMethod, x));
+
+
 % on RUN the sample rate will be picked from the text box
 % However, MAP overrules the sample rate and sets its own
 aSetSampleRate(stimulusParameters.subjectSampleRate, handles);
@@ -352,7 +375,7 @@
 % ------------------------------------------------------ aResetPopupMenus
 function aResetPopupMenus(handles)
 global   stimulusParameters betweenRuns variableNames
-global targetTypes maskerTypes experiment backgroundTypes
+global targetTypes maskerTypes experiment backgroundTypes betweenRunsVariables
 
 switch experiment.threshEstMethod
     case {'MaxLikelihood','oneIntervalUpDown'}
@@ -375,11 +398,11 @@
 
 %set variables popupmenus as specified in betweenRuns
 variableParameter1ID=0; variableParameter2ID=0;
-for i=1:length(variableNames)
-    if strcmp(variableNames{i},betweenRuns.variableName1)
+for i=1:length(betweenRunsVariables) %  variableNames
+    if strcmp(betweenRunsVariables{i},betweenRuns.variableName1)
         variableParameter1ID=i;
     end
-    if strcmp(variableNames{i},betweenRuns.variableName2)
+    if strcmp(betweenRunsVariables{i},betweenRuns.variableName2)
         variableParameter2ID=i;
     end
 end
@@ -416,6 +439,15 @@
 set(handles.edittargetDuration, 'visible', 'on')
 set(handles.edittargetFrequency, 'visible', 'on')
 
+switch experiment.paradigm(1:3)
+    case 'OHI'
+        set(handles.editOHIOnTones, 'visible', 'on')
+        set(handles.textOHIOnTones, 'visible', 'on')
+    otherwise
+        set(handles.editOHIOnTones, 'visible', 'off')
+        set(handles.textOHIOnTones, 'visible', 'off')
+end
+
 switch experiment.ear
     case {'statsModelLogistic', 'statsModelRareEvent'}
         set(handles.editStatsModel, 'visible', 'on')
@@ -688,6 +720,8 @@
 global experiment expGUIhandles stimulusParameters
 tic
 expGUIhandles=handles;
+set(handles.pushbuttonSave,'visible','off')
+
 set(handles.pushbuttonStop, 'backgroundColor', [.941 .941 .941])
 % set(handles.editparamChanges,'visible','off')
 
@@ -718,9 +752,15 @@
 
 % --- Executes on button press in pushbuttonSingleShot.
 function pushbuttonSingleShot_Callback(hObject, eventdata, handles)
-global experiment
+global experiment paradigmNames
 experiment.singleShot=1;
 
+% startup paradigm, 'training' (could be anywhere on the list)
+startupParadigm='training';
+idx= find(strcmp(paradigmNames,startupParadigm));
+set(handles.popupmenuParadigm,'value', idx)
+aParadigmSelection(handles);
+
 % special test for spontaneous activity
 x=get(handles.editWRVstartValues, 'string');
 y=get(handles.edittargetDuration, 'string');
@@ -740,7 +780,7 @@
 % ------------------------------------------aReadAndCheckParameterBoxes
 function errorMsg=aReadAndCheckParameterBoxes(handles)
 global experiment  stimulusParameters betweenRuns  statsModel
-global variableNames  LevittControl paramChanges
+global variableNames  LevittControl paramChanges betweenRunsVariables
 % When the program sets the parameters all should be well
 % But when the user changes them...
 
@@ -801,7 +841,7 @@
 end
 
 chosenOption=get(handles.popupmenuVaryParameter1,'value');
-betweenRuns.variableName1=variableNames{chosenOption};
+betweenRuns.variableName1=betweenRunsVariables{chosenOption};
 eval(['betweenRuns.variableList1 = stimulusParameters.' ...
     betweenRuns.variableName1 ';']);
 
@@ -891,6 +931,9 @@
         'catch trial base rates must be less than catch trial start rate';
     return,
 end
+% force the decay rate for catchTrialRate
+%  to avoid having to explain it to the user
+stimulusParameters.catchTrialRates(3)=2;
 
 % sample rate
 % The sample rate is set in the paradigm file.
@@ -1040,7 +1083,12 @@
 % identify model parameter changes if any
 paramChanges=get(handles.editparamChanges,'string');
 if ~strcmp(paramChanges, ';'), paramChanges=[paramChanges ';']; end
+try
 eval(paramChanges);
+catch
+    error('Problems with suggested parameter changes')
+end
+
 
 % -------------------------------------------- aSetSampleRate
 function aSetSampleRate(sampleRate, handles)
@@ -1099,7 +1147,7 @@
         stimulusParameters.includeCue=0;						 % no cue
         set(handles.popupmenuCueNoCue,'value', 2)
 
-        set(handles.editCatchTrialRate,'string','0 0  2 ');%no catch trials
+        set(handles.editCatchTrialRate,'string','0 0');%no catch trials
         set(handles.editName,'string', 'Normal')			% force name
         experiment.name=get(handles.editName,'string');	% read name back
         set(handles.editcalibrationdB,'string','0')
@@ -1110,6 +1158,9 @@
         set(handles.editSaveData,'string', '0')
         set(handles.editSubjectFont,'string', '10');
         experiment.MacGThreshold=0; % num MacG spikes to exceed threshold
+    otherwise
+        set(handles.editCatchTrialRate,'string','0.2 0.1');%no catch trials
+
 end
 aResetPopupMenus(handles)
 
@@ -1119,19 +1170,22 @@
 
 % ------------------------------------------------------------- cueSetUp
 function cueSetUp(handles)
-global stimulusParameters
+global stimulusParameters experiment
 
-chosenOption=get(handles.popupmenuCueNoCue,'value');
-if chosenOption==1
-    stimulusParameters.includeCue=1;
-    set(handles.editcueTestDifference,'visible', 'on')
-    set(handles.textcueTestDifference,'visible', 'on')
-    stimulusParameters.subjectText=stimulusParameters.instructions{2};
-else
-    stimulusParameters.includeCue=0;
-    set(handles.editcueTestDifference,'visible', 'off')
-    set(handles.textcueTestDifference,'visible', 'off')
-    stimulusParameters.subjectText= stimulusParameters.instructions{1};
+switch experiment.threshEstMethod
+    case {'oneIntervalUpDown', 'MaxLikelihood'}
+        chosenOption=get(handles.popupmenuCueNoCue,'value');
+        if chosenOption==1
+            stimulusParameters.includeCue=1;
+            set(handles.editcueTestDifference,'visible', 'on')
+            set(handles.textcueTestDifference,'visible', 'on')
+            stimulusParameters.subjectText=stimulusParameters.instructions{2};
+        else
+            stimulusParameters.includeCue=0;
+            set(handles.editcueTestDifference,'visible', 'off')
+            set(handles.textcueTestDifference,'visible', 'off')
+            stimulusParameters.subjectText= stimulusParameters.instructions{1};
+        end
 end
 
 % -------------------------------------------- popupmenuThreshEst_Callback
@@ -1761,3 +1815,34 @@
 end
 
 
+
+
+function pushbuttonSave_Callback(hObject, eventdata, handles)
+global experiment
+
+subjectName=experiment.name;
+if ~isdir(['savedData' filesep subjectName ])
+    mkdir(['savedData' filesep subjectName ])
+end
+
+% date and time and replace ':' with '_'
+date=datestr(now);idx=findstr(':',date);date(idx)='_';
+fileName=[subjectName ' ' date '.mat'];
+movefile(['savedData' filesep 'mostRecentResults.mat'], ...
+    ['savedData' filesep subjectName filesep fileName])
+set(handles.pushbuttonSave,'visible','off')
+
+
+
+function editOHIOnTones_Callback(hObject, eventdata, handles)
+
+
+function editOHIOnTones_CreateFcn(hObject, eventdata, handles)
+
+% Hint: edit controls usually have a white background on Windows.
+%       See ISPC and COMPUTER.
+if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
+    set(hObject,'BackgroundColor','white');
+end
+
+
--- a/multithreshold 1.46/nextStimulus.m	Thu Oct 06 15:43:20 2011 +0100
+++ b/multithreshold 1.46/nextStimulus.m	Mon Nov 28 13:34:28 2011 +0000
@@ -2,7 +2,7 @@
 % Handles everything concerned with the stimulus presentation
 %  called from startNewRun in subjGUI
 
-global experiment stimulusParameters withinRuns  
+global experiment stimulusParameters withinRuns  betweenRuns
 experiment.status='presentingStimulus';
 errormsg='';
 
@@ -234,16 +234,133 @@
             case {'training','absThreshold', 'absThreshold_8',  ...
                     'TENtest', 'threshold_duration','discomfort',...
                     'overShoot','overShootB','overShootMB1', ...
-                    'overShootMB2', 'OHIO','OHIOabs','OHIOspect'}
+                    'overShootMB2', 'OHIO','OHIOabs','OHIOspect'...
+                    'OHIOrand', 'OHIOtemp', 'OHIOspectemp'}
                 cueTargetLevel=targetLevel+cueTestDifference;
                 
             case {'forwardMasking','forwardMaskingD','trainingIFMC', ...
-                    'TMC','TMC_16ms', 'TMC - ELP', 'IFMC','IFMC_8ms', 'FMreProbe'}
+                    'TMC','TMC_16ms', 'TMC - ELP', 'IFMC','IFMC_8ms', ...
+                    'FMreProbe'}
                 % cue masker is weaker to make target more audible
                 cueMaskerLevel=maskerLevel-cueTestDifference;
         end
 end
 
+% thresholds (in dB SPL) of the single tone with 12 frequencies:
+%    1   2    3     4    5     6     7     8     9     10     11    12
+% 494, 663, 870, 1125, 1442, 1838, 2338, 2957, 3725, 4689, 5866, 7334
+
+% 2. ‘OHIOtemp’ is for measuring thresholds for temporally integrated
+% combinations of 2, 4, 8, and 12 tones presented simultaneously.
+% In our experiment, we used 4680Hz frequency.
+
+% 3. ‘OHIOspec’ is for measuring thresholds for spectrally integrated
+% combinations of 2(7335 and 5866Hz), 4(7334, 5866, 4680, and 3725Hz),
+% 8(7334, 5866, 4680, 3725, 2957, 2338, 1838, and
+% 1442Hz), and
+% 12(all 12 frequencies) tones presented simultaneously.
+
+% 4. ‘OHIOspectemp’ is for measuring thresholds for patterned signals
+% differing in both the spectral and temporal domains.
+% The frequency conditions are the same as that of ‘OHIOspec’.
+
+% 5. ‘OHIOrand’ is for measuring thresholds for spectrotemporally varying
+% signals with random frequency presentation.
+
+switch experiment.paradigm(1:3)
+    case 'OHI'
+        targetType='OHIO';
+        OHIOtype=experiment.paradigm;
+        % 1. ‘OHIOabs’ paradigm is a baseline procedure for measuring absolute
+
+        nTones=betweenRuns.var1Sequence(betweenRuns.runNumber);
+        allFreqs=[494, 663, 870, 1125, 1442, 1838, 2338, 2957, 3725, 4689, 5866, 7334];
+        toneLevelBoost= ...
+            [1	0	0	1	1	4	8	12	12	14	17	19 ];
+
+
+        % for nTones=nTonesList
+        switch experiment.paradigm
+            %         case ' OHIOabs'
+            %             % one tone frequency at a time
+            %             stim.frequencies=allFreqs(1);
+            %             stim.amplitudesdB=0;
+
+            case 'OHIOrand'
+                % chose nTones frequencies at random
+                x=rand(1,12);
+                [sorted idx]=sort(x);
+                cueTargetFrequency=allFreqs(idx(1:nTones));
+                cueTargetLevel=toneLevelBoost(idx)+...
+                    targetLevel + cueTestDifference;
+                targetFrequency=allFreqs(idx(1:nTones));
+                targetLevel=targetLevel + toneLevelBoost(idx);
+
+            case 'OHIOtemp'
+                % 4680 Hz repeated nTones times
+                cueTargetFrequency=4680*ones(1,nTones);
+                cueTargetLevel=repmat(toneLevelBoost(10),1,nTones)+...
+                    targetLevel + cueTestDifference;
+                targetFrequency=4680*ones(1,nTones);
+                targetLevel= targetLevel+repmat(toneLevelBoost(10),1,nTones);
+
+            case {'OHIOspect',  'OHIOspectemp'}
+                % nTones frequencies either simulataneously or sequentially
+                switch nTones
+                    case 2
+                        cueTargetFrequency=[7335 5866];
+                        targetFrequency=[7335 5866];
+                        idx=[12 11];
+                        cueTargetLevel=targetLevel + toneLevelBoost(idx)+cueTestDifference;
+                        targetLevel=targetLevel + toneLevelBoost(idx);
+                    case 4
+                        cueTargetFrequency=[7334, 5866, 4680, 3725];
+                        targetFrequency=[7334, 5866, 4680, 3725];
+                        idx=[12:-1:9 ];
+                        cueTargetLevel=targetLevel + toneLevelBoost(idx)+cueTestDifference;
+                        targetLevel=targetLevel + toneLevelBoost(idx);
+                    case 8
+                        cueTargetFrequency=...
+                            [7334, 5866, 4680, 3725, 2957, 2338, 1838, 1442];
+                        targetFrequency=...
+                            [7334, 5866, 4680, 3725, 2957, 2338, 1838, 1442];
+                        idx=[12:-1:5 ];
+                        cueTargetLevel=targetLevel + toneLevelBoost(idx)+cueTestDifference;
+                        targetLevel=targetLevel + toneLevelBoost(idx);
+                    case 12
+                        cueTargetFrequency=allFreqs;
+                        targetFrequency=allFreqs;
+                        cueTargetLevel=targetLevel + toneLevelBoost(1:12)+cueTestDifference;
+                        targetLevel=targetLevel + toneLevelBoost(1:12);
+                end
+        end
+
+    otherwise
+        OHIOtype='none';
+end
+
+switch experiment.paradigm(1:3)
+    case 'OHI'
+
+        switch experiment.threshEstMethod
+            case {'2I2AFC++', '2I2AFC+++'}
+                % the cue stimulus (masker + probe) is the 'no' window
+                % the target stimulus (masker+probe) is the 'yes' window
+                % the order of presentation is decided at the last minute.
+                cueTargetLevel=-100; 
+        end
+
+
+        switch experiment.paradigm
+            case {'OHIOabs', 'OHIOspect'}
+                OHIOtoneDuration=.02+stimulusParameters.stimulusDelay;
+                globalStimParams.overallDuration=OHIOtoneDuration;
+            otherwise
+                OHIOtoneDuration=nTones*0.02+stimulusParameters.stimulusDelay;
+                globalStimParams.overallDuration=OHIOtoneDuration;
+        end
+end
+
 % ----------------------------- catch trial
 if withinRuns.catchTrial
     targetLevel=-100;	% no target
@@ -370,8 +487,8 @@
             return
         end
         
+    case 'gapDuration'
         % legacy programming
-    case 'gapDuration'
         if gapDuration<0
             errormsg=['gapDuration (' num2str(gapDuration) ...
                 ') is less than zero  ***'];
@@ -497,6 +614,20 @@
 globalStimParams.nSignalPoints=...
     round(globalStimParams.overallDuration*globalStimParams.FS);
 
+% special case
+switch experiment.paradigm(1:3)
+    case 'OHI'
+        switch experiment.paradigm
+            case {'OHIOabs', 'OHIOspect'}
+                OHIOtoneDuration=.02+stimulusParameters.stimulusDelay;
+                globalStimParams.overallDuration=OHIOtoneDuration;
+            otherwise
+                OHIOtoneDuration=nTones*0.02+stimulusParameters.stimulusDelay;
+                globalStimParams.overallDuration=OHIOtoneDuration;
+        end
+end
+
+
 %           ----------------------------------------------cue stimulus
 % cue masker
 componentNo=1;
@@ -527,6 +658,7 @@
 componentNo=2;
 precedingSilence=precedingSilence + maskerDuration+cueGapDuration;
 stimComponents(targetEar,componentNo).type=targetType;
+stimComponents(targetEar,componentNo).OHIOtype=OHIOtype;
 stimComponents(targetEar,componentNo).toneDuration=targetDuration;
 stimComponents(targetEar,componentNo).frequencies=cueTargetFrequency;
 stimComponents(targetEar,componentNo).amplitudesdB=cueTargetLevel;
@@ -605,6 +737,7 @@
 componentNo=2;
 targetDelay=precedingSilence+ maskerDuration+ gapDuration;
 stimComponents(targetEar,componentNo).type=targetType;
+stimComponents(targetEar,componentNo).OHIOtype=OHIOtype;
 stimComponents(targetEar,componentNo).toneDuration=targetDuration;
 stimComponents(targetEar,componentNo).frequencies=targetFrequency;
 stimComponents(targetEar,componentNo).amplitudesdB=targetLevel;
@@ -661,8 +794,14 @@
         %     case 'SRT'
         %         set(handles.editdigitInput,'visible','off')
     otherwise
-        stimulusParameters.testTargetBegins=targetDelay;
-        stimulusParameters.testTargetEnds=targetDelay+targetDuration;
+        switch experiment.paradigm(1:3)
+            case 'OHI'
+                stimulusParameters.testTargetBegins=0;
+                stimulusParameters.testTargetEnds=OHIOtoneDuration;
+            otherwise
+                stimulusParameters.testTargetBegins=targetDelay;
+                stimulusParameters.testTargetEnds=targetDelay+targetDuration;
+        end
 end
 
 % ------------------------------------------------------------- play!
--- a/multithreshold 1.46/old files/MAPmodel.m	Thu Oct 06 15:43:20 2011 +0100
+++ b/multithreshold 1.46/old files/MAPmodel.m	Mon Nov 28 13:34:28 2011 +0000
@@ -20,7 +20,7 @@
 AN_spikesOrProbability='spikes';
 
 % [response, method]=MAPsequenceSeg(audio, method, 1:8);
-global ICoutput ANdt
+global ICoutput dtSpikes
     MAP1_14(audio, 1/method.dt, method.nonlinCF,...
         MAPparamsName, AN_spikesOrProbability);
     
@@ -29,7 +29,7 @@
     options.showModelOutput=1;
     options.printFiringRates=1;
     options.showACF=0;
-    options.showEfferent=1;
+    options.showEfferent=0;
     UTIL_showMAP(options)
 end
 
@@ -41,7 +41,7 @@
 
 % ---------------------------------------------------------- end model run
 
-dt=ANdt;
+dt=dtSpikes;
 time=dt:dt:dt*length(MacGregorResponse);
 
 % group delay on unit response
--- a/multithreshold 1.46/paradigms/paradigm_IFMC.m	Thu Oct 06 15:43:20 2011 +0100
+++ b/multithreshold 1.46/paradigms/paradigm_IFMC.m	Mon Nov 28 13:34:28 2011 +0000
@@ -1,7 +1,7 @@
 function paradigm_IFMC(handles)
 global stimulusParameters experiment betweenRuns
 
-paradigm_training(handles) % default
+paradigmBase(handles) % default
 
 stimulusParameters.WRVname='maskerLevel';
 stimulusParameters.WRVstartValues=10;
--- a/multithreshold 1.46/paradigms/paradigm_TENtest.m	Thu Oct 06 15:43:20 2011 +0100
+++ b/multithreshold 1.46/paradigms/paradigm_TENtest.m	Mon Nov 28 13:34:28 2011 +0000
@@ -1,7 +1,7 @@
 function paradigm_TENtest(handles)
 global stimulusParameters experiment betweenRuns
 
-paradigm_training(handles) % default
+paradigmBase(handles) % default
 
 stimulusParameters.WRVname='targetLevel';
 stimulusParameters.WRVstartValues=40;
@@ -29,6 +29,6 @@
 %   single interval up/down no cue
 stimulusParameters.instructions{1}=[{'YES if you hear the added click'}, { }, { 'NO if not (or you are uncertain'}];
 %   single interval up/down with cue
-stimulusParameters.instructions{2}=[{'count how many distinct clicks you hear'},{'ignore the tones'},{' '},...
+stimulusParameters.instructions{2}=[{'count how many distinct clicks you hear'},{'ignore the noise'},{' '},...
     {'The clicks must be **clearly distinct** to count'}];
 
--- a/multithreshold 1.46/paradigms/paradigm_TMC.m	Thu Oct 06 15:43:20 2011 +0100
+++ b/multithreshold 1.46/paradigms/paradigm_TMC.m	Mon Nov 28 13:34:28 2011 +0000
@@ -1,7 +1,7 @@
 function paradigm_TMC(handles)
 global stimulusParameters experiment betweenRuns
 
-paradigm_training(handles) % default
+paradigmBase(handles) % default
 
 stimulusParameters.WRVname='maskerLevel';
 stimulusParameters.WRVstartValues=50;
--- a/multithreshold 1.46/paradigms/paradigm_absThreshold.m	Thu Oct 06 15:43:20 2011 +0100
+++ b/multithreshold 1.46/paradigms/paradigm_absThreshold.m	Mon Nov 28 13:34:28 2011 +0000
@@ -1,7 +1,7 @@
 function paradigm_absThreshold(handles)
 global stimulusParameters experiment betweenRuns
 
-paradigm_training(handles) % default
+paradigmBase(handles) % default
 
 betweenRuns.variableName1='targetFrequency';
 betweenRuns.variableList1=[250 500 1000 2000 4000 8000 ];
--- a/multithreshold 1.46/paradigms/paradigm_absThreshold_16.m	Thu Oct 06 15:43:20 2011 +0100
+++ b/multithreshold 1.46/paradigms/paradigm_absThreshold_16.m	Mon Nov 28 13:34:28 2011 +0000
@@ -1,7 +1,7 @@
 function paradigm_absThreshold16(handles)
 global stimulusParameters experiment betweenRuns
 
-paradigm_training(handles) % default
+paradigmBase(handles) % default
 
 betweenRuns.variableName1='targetFrequency';
 betweenRuns.variableList1=1000;
--- a/multithreshold 1.46/paradigms/paradigm_discomfort.m	Thu Oct 06 15:43:20 2011 +0100
+++ b/multithreshold 1.46/paradigms/paradigm_discomfort.m	Mon Nov 28 13:34:28 2011 +0000
@@ -1,7 +1,7 @@
 function paradigm_discomfort(handles)
 global stimulusParameters experiment betweenRuns
 
-paradigm_training(handles) % default
+paradigmBase(handles) % default
 
 stimulusParameters.WRVname='targetLevel';
 stimulusParameters.WRVstartValues=75 ;
--- a/multithreshold 1.46/paradigms/paradigm_forwardMasking.m	Thu Oct 06 15:43:20 2011 +0100
+++ b/multithreshold 1.46/paradigms/paradigm_forwardMasking.m	Mon Nov 28 13:34:28 2011 +0000
@@ -1,7 +1,7 @@
 function paradigm_forwardMasking(handles)
 global stimulusParameters experiment betweenRuns
 
-paradigm_training(handles) % default
+paradigmBase(handles) % default
 
 stimulusParameters.WRVname='targetLevel';
 stimulusParameters.WRVstartValues=50;
--- a/multithreshold 1.46/paradigms/paradigm_overShoot.m	Thu Oct 06 15:43:20 2011 +0100
+++ b/multithreshold 1.46/paradigms/paradigm_overShoot.m	Mon Nov 28 13:34:28 2011 +0000
@@ -1,7 +1,7 @@
 function paradigm_overShoot(handles)
 global stimulusParameters  betweenRuns experiment
 
-paradigm_training(handles) % default
+paradigmBase(handles) % default
 
 stimulusParameters.WRVname='targetLevel';
 stimulusParameters.WRVstartValues=50;
--- a/multithreshold 1.46/paradigms/paradigm_profile.m	Thu Oct 06 15:43:20 2011 +0100
+++ b/multithreshold 1.46/paradigms/paradigm_profile.m	Mon Nov 28 13:34:28 2011 +0000
@@ -1,7 +1,7 @@
 function paradigm_profile(handles)
 global stimulusParameters experiment betweenRuns
 
-paradigm_training(handles) % default
+paradigmBase(handles) % default
 
 betweenRuns.variableName1='targetFrequency';
 betweenRuns.variableList1=[250 500 1000 2000 4000 8000 ];
--- a/multithreshold 1.46/paradigms/paradigm_psychometric.m	Thu Oct 06 15:43:20 2011 +0100
+++ b/multithreshold 1.46/paradigms/paradigm_psychometric.m	Mon Nov 28 13:34:28 2011 +0000
@@ -1,7 +1,7 @@
 function paradigm_psychometric(handles)
 global stimulusParameters experiment betweenRuns
 
-paradigm_training(handles) % default
+paradigmBase(handles) % default
 
 experiment.printTracks=1;
 experiment.maxTrials=30;
--- a/multithreshold 1.46/paradigms/paradigm_threshold_duration.m	Thu Oct 06 15:43:20 2011 +0100
+++ b/multithreshold 1.46/paradigms/paradigm_threshold_duration.m	Mon Nov 28 13:34:28 2011 +0000
@@ -1,7 +1,7 @@
 function paradigm_threshold_duration(handles)
 global stimulusParameters experiment betweenRuns
 
-paradigm_training(handles) % default
+paradigmBase(handles) % default
 
 stimulusParameters.WRVname='targetLevel';
 stimulusParameters.WRVstartValues=40;
--- a/multithreshold 1.46/paradigms/paradigm_training.m	Thu Oct 06 15:43:20 2011 +0100
+++ b/multithreshold 1.46/paradigms/paradigm_training.m	Mon Nov 28 13:34:28 2011 +0000
@@ -1,8 +1,10 @@
 function paradigm_training(handles)
 global stimulusParameters experiment betweenRuns
 
-stimulusParameters.subjectSampleRate=44100; % compatible with file input
-stimulusParameters.subjectSampleRate=64000; % compatible with file input
+paradigmBase(handles) % default
+
+% rest may be unnecessary
+
 % stimulusParameters.subjectSampleRate=128000; % compatible with file input
 
 %  assessment method
--- a/multithreshold 1.46/paradigms/paradigm_trainingIFMC.m	Thu Oct 06 15:43:20 2011 +0100
+++ b/multithreshold 1.46/paradigms/paradigm_trainingIFMC.m	Mon Nov 28 13:34:28 2011 +0000
@@ -1,7 +1,7 @@
-function paradigm_trainingIFMC(handles)
+function paradigmBaseIFMC(handles)
 global stimulusParameters experiment betweenRuns
 
-paradigm_training(handles) % default
+paradigmBase(handles) % default
 
 stimulusParameters.WRVname='maskerLevel';
 stimulusParameters.WRVstartValues=-10;
@@ -16,7 +16,7 @@
 betweenRuns.variableList1=[ 0.5       .9 .7   1.3 ];
 betweenRuns.variableName2='targetFrequency';
 % keep old list of target frequencies
-betweenRuns.variableList2=str2num(get(handles.edittargetFrequency,'string'));
+betweenRuns.variableList2=[ 2000 ];
 
 experiment.maskerInUse=1;
 stimulusParameters.maskerType='tone';
--- a/multithreshold 1.46/plotProfile.m	Thu Oct 06 15:43:20 2011 +0100
+++ b/multithreshold 1.46/plotProfile.m	Mon Nov 28 13:34:28 2011 +0000
@@ -4,7 +4,7 @@
 
 %% plot profile
 if nargin<1
-    fgName = myFile;
+    fgName = 'profile_JSAN_R';
     bgName = '';
 end
 
@@ -68,13 +68,14 @@
     freq=foreground.MaskerRatio'*foreground.IFMCFreq(BFno);
     subplot(2,1,2)
     semilogx(freq,foreground.IFMCs(BFno,:),'r','lineWidth',3), hold on
-    ylim([0 100])
+    ylim([-20 100])
     xlim([100 12000])
 %     grid on
 end
 xlabel('frequency (Hz)')
 ylabel('masker dB / probe dB')
 set(gca,'XTick',foreground.IFMCFreq)
+set(gca,'Ytick', [-20 0 50 100])
 
 if ~isempty(bgName)
     for BFno=1:length(background.IFMCFreq)
--- a/multithreshold 1.46/printReport.m	Thu Oct 06 15:43:20 2011 +0100
+++ b/multithreshold 1.46/printReport.m	Mon Nov 28 13:34:28 2011 +0000
@@ -19,6 +19,7 @@
 printReportGuide.showPsychometric=0;
 printReportGuide.HorizontalTracks=1;
 
+
 if nargin==0
     % print new report
     printReportGuide.showTracks=experiment.printTracks;
@@ -180,9 +181,14 @@
     disp('Psychometric function')
     fprintf(' level  \tfreq\tprob\n')
     fprintf('%6.0f\t%6.2f\t%6.0f\n',[levelsBinVector; binFrequencies; psy])
-    fprintf('\n')
-    fprintf('k \t %6.2f\n',logistic.bestK)
-    fprintf('g  \t%7.5f\n',rareEvent.bestGain)
+
+    switch experiment.threshEstMethod
+        % only one value required for level change
+        case {'MaxLikelihood',  'oneIntervalUpDown'};
+%             fprintf('\n')
+%             fprintf('k \t %6.2f\n',logistic.bestK)
+%             fprintf('g  \t%7.5f\n',rareEvent.bestGain)
+    end
     fprintf('\n')
 
 end
Binary file multithreshold 1.46/profile.mat has changed
Binary file multithreshold 1.46/savedData/mostRecentResults.mat has changed
--- a/multithreshold 1.46/subjGUI_MT.m	Thu Oct 06 15:43:20 2011 +0100
+++ b/multithreshold 1.46/subjGUI_MT.m	Mon Nov 28 13:34:28 2011 +0000
@@ -986,11 +986,12 @@
         otherwise
             title([stimulusParameters.WRVname ' = ' ...
                 num2str(withinRuns.variableValue, '%5.1f') ...
-                ';    TH= ' num2str(estThresh, '%5.1f')])
+                ';    TH= ' num2str(estThresh, '%5.1f') ' dB'])
     end
 end
 xlim([0 experiment.maxTrials+withinRuns.beginningOfPhase2]);
 ylim(stimulusParameters.WRVlimits)
+ylabel ('dB SPL')
 grid on
 
 % Panel 4: Summary of threshold estimates (not used here)
@@ -1275,7 +1276,7 @@
 end
 xlimRM([ min(betweenRuns.variableList1) max(betweenRuns.variableList1) ])
 ylim(stimulusParameters.WRVlimits)
-ylabel('thresholds')
+ylabel('thresholds (dB)')
 xlabel(betweenRuns.variableName1)
 set(gca,'ytick', [0 20 40 60 80 100])
 try
@@ -1305,6 +1306,7 @@
     % update experimenter GUI
     addToMsg('Experiment completed.',1)
 
+    set(expGUIhandles.pushbuttonSave,'visible','on')
     printReport
     experiment.status='endOfExperiment';
     return
@@ -1433,7 +1435,7 @@
 
 global experiment stimulusParameters audio withinRuns
 % global outerMiddleEarParams DRNLParams AN_IHCsynapseParams
-global ICoutput ANdt dt savedBFlist ANprobRateOutput expGUIhandles
+global ICoutput dtSpikes dt savedBFlist ANprobRateOutput expGUIhandles
 global paramChanges
 
 savePath=path;
@@ -1479,7 +1481,7 @@
     options.showModelOutput=1;
     options.printFiringRates=1;
     options.showACF=0;
-    options.showEfferent=1;
+    options.showEfferent=0;
     options.surfProbability=0;
     showMapOptions.surfSpikes=0;
     UTIL_showMAP(options)
@@ -1493,7 +1495,7 @@
 
 if strcmp(AN_spikesOrProbability,'spikes')
     MacGregorResponse= sum(ICoutput,1);                 % use IC
-    dt=ANdt;
+    dt=dtSpikes;
     time=dt:dt:dt*length(MacGregorResponse);
 else
     % for one channel, ANprobResponse=ANprobRateOutput
@@ -1508,7 +1510,8 @@
 windowOnsetDelay= 0.004;
 windowOffsetDelay= 0.022; % long ringing time
 
-% now find the response of the MacGregor model during the target presentation + group delay
+% now find the response of the MacGregor model during 
+%  the target presentation + group delay
 switch experiment.threshEstMethod
     case {'2I2AFC++', '2I2AFC+++'}
         idx= time>stimulusParameters.testTargetBegins+windowOnsetDelay ...
@@ -1550,7 +1553,8 @@
             num2str([withinRuns.variableValue nSpikesTrueWindow ...
             nSpikesFalseWindow  nSpikesDuringTarget], '%4.0f') ] )
     otherwise
-        % single interval
+        
+        % single interval up/down
         idx=find(time>stimulusParameters.testTargetBegins +windowOnsetDelay...
             & time<stimulusParameters.testTargetEnds+windowOffsetDelay);
         if strcmp(AN_spikesOrProbability,'spikes')
@@ -1747,7 +1751,9 @@
 end
 
 try
-    serobj = serial('COM4') ;           	% Creating serial port object now its connected to COM4 !!! button boxes in booths are connected to COM2
+    % !!! button boxes in booths are connected to COM2. User beware of
+    % connection port.
+    serobj = serial('COM2') ;           	% Creating serial port object
     serobj.Baudrate = 9600;           		% Set the baud rate at the specific value
     set(serobj, 'Parity', 'none') ;     	% Set parity as none
     set(serobj, 'Databits', 8) ;          	% set the number of data bits
--- a/parameterStore/MAPparamsNormal.m	Thu Oct 06 15:43:20 2011 +0100
+++ b/parameterStore/MAPparamsNormal.m	Mon Nov 28 13:34:28 2011 +0000
@@ -25,7 +25,7 @@
 method.segmentDuration=efferentDelay;
 
 if nargin<3, showParams=0; end
-if nargin<2, sampleRate=50000; end
+if nargin<2, sampleRate=44100; end
 if nargin<1 || BFlist(1)<0 % if BFlist= -1, set BFlist to default
     lowestBF=250; 	highestBF= 8000; 	numChannels=21;
     % 21 chs (250-8k)includes BFs at 250 500 1000 2000 4000 8000
@@ -52,18 +52,15 @@
                                        
 % highpass stapes filter  
 %  Huber gives 2e-9 m at 80 dB and 1 kHz (2e-13 at 0 dB SPL)
-OMEParams.OMEstapesLPcutoff= 1000;
+OMEParams.OMEstapesHPcutoff= 1000;
 OMEParams.stapesScalar=	     45e-9;
 
 % Acoustic reflex: maximum attenuation should be around 25 dB (Price, 1966)
 % i.e. a minimum ratio of 0.056.
 % 'spikes' model: AR based on brainstem spiking activity (LSR)
-OMEParams.rateToAttenuationFactor=0.008;  % * N(all ICspikes)
-% OMEParams.rateToAttenuationFactor=0;  % i.e. no AR
-
+OMEParams.rateToAttenuationFactor=0.05; % * N(all ICspikes)
 % 'probability model': Ar based on AN firing probabilities (LSR)
-OMEParams.rateToAttenuationFactorProb=0.006;    % * N(all ANrates)
-% OMEParams.rateToAttenuationFactorProb=0;      % i.e. no AR
+OMEParams.rateToAttenuationFactorProb=0.02;    % * N(all ANrates)
 
 % asymptote should be around 100-200 ms
 OMEParams.ARtau=.250; % AR smoothing function 250 ms fits Hung and Dallos
@@ -77,19 +74,19 @@
 
 %   *** DRNL nonlinear path
 % broken stick compression
-DRNLParams.a=5e4;       % DRNL.a=0 means no OHCs (no nonlinear path)
+DRNLParams.a=2e4;       % DRNL.a=0 means no OHCs (no nonlinear path)
 DRNLParams.c=.2;        % compression exponent
-DRNLParams.CtBMdB = 10; %Compression threshold dB re 10e-9 m displacement
+DRNLParams.ctBMdB = 10; %Compression threshold dB re 10e-9 m displacement
 
 % filters
 DRNLParams.nonlinOrder=	3;  % order of nonlinear gammatone filters
 DRNLParams.nonlinCFs=BFlist;
-p=0.2895;   q=250;      % human  (% p=0.14;   q=366;  % cat)
-DRNLParams.nlBWs=  p * BFlist + q;
-DRNLParams.p=p;   DRNLParams.q=q;   % save p and q for printing only
+DRNLParams.p=0.2895;   DRNLParams.q=250;   % save p and q for printing only
+% p=0.2895;   q=250;      % human  (% p=0.14;   q=366;  % cat)
+DRNLParams.nlBWs=  DRNLParams.p * BFlist + DRNLParams.q;
 
 %   *** DRNL linear path:
-DRNLParams.g=200;       % linear path gain factor
+DRNLParams.g=100;       % linear path gain factor
 DRNLParams.linOrder=3;  % order of linear gammatone filters
 % linCF is not necessarily the same as nonlinCF
 minLinCF=153.13; coeffLinCF=0.7341;   % linCF>nonlinBF for BF < 1 kHz
@@ -100,23 +97,22 @@
 
 %   *** DRNL MOC efferents
 DRNLParams.MOCdelay = efferentDelay;            % must be < segment length!
-DRNLParams.minMOCattenuationdB=-30;
+DRNLParams.minMOCattenuationdB=-35;
 
 % 'spikes' model: MOC based on brainstem spiking activity (HSR)
-DRNLParams.MOCtau =.025;                         % smoothing for MOC
-DRNLParams.rateToAttenuationFactor = .00635;  % strength of MOC
-% DRNLParams.rateToAttenuationFactor = 0;  % strength of MOC
+DRNLParams.MOCtau =.0285;                         % smoothing for MOC
+DRNLParams.rateToAttenuationFactor = .03;  % strength of MOC
+DRNLParams.rateToAttenuationFactor = .0055;  % strength of MOC
 
-% 'probability' model: MOC based on AN spiking activity (HSR)
+% 'probability' model: MOC based on AN probability (HSR)
 DRNLParams.MOCtauProb =.285;                         % smoothing for MOC
-DRNLParams.rateToAttenuationFactorProb = 0.0075;  % strength of MOC
-% DRNLParams.rateToAttenuationFactorProb = .0;  % strength of MOC
-DRNLParams.MOCrateThresholdProb =50;                % spikes/s probability only
+DRNLParams.rateToAttenuationFactorProb = 0.007;  % strength of MOC
+DRNLParams.MOCrateThresholdProb =67;                % spikes/s probability only
 
 
 %% #4 IHC_cilia_RPParams
-IHC_cilia_RPParams.tc=	0.0003;   % 0.0003 filter time simulates viscocity
-IHC_cilia_RPParams.C=	0.03;      % 0.1 scalar (C_cilia ) 
+IHC_cilia_RPParams.tc=	0.00012;   % 0.0003 Shamma
+IHC_cilia_RPParams.C=	0.08;       % 0.1 scalar (C_cilia ) 
 IHC_cilia_RPParams.u0=	5e-9;       
 IHC_cilia_RPParams.s0=	30e-9;
 IHC_cilia_RPParams.u1=	1e-9;
@@ -148,7 +144,8 @@
 % reminder: changing z has a strong effect on HF thresholds (like Et)
 IHCpreSynapseParams.z=	    2e42;   % scalar Ca -> vesicle release rate
 
-LSRtauCa=40e-6;            HSRtauCa=80e-6;            % seconds
+LSRtauCa=30e-6;            HSRtauCa=80e-6;            % seconds
+% LSRtauCa=40e-6;            HSRtauCa=90e-6;            % seconds
 % IHCpreSynapseParams.tauCa= [15e-6 80e-6]; %LSR and HSR fiber
 IHCpreSynapseParams.tauCa= [LSRtauCa HSRtauCa]; %LSR and HSR fiber
 
@@ -159,7 +156,8 @@
 % absolute refractory period. Relative refractory period is the same. 
 AN_IHCsynapseParams.refractory_period=	0.00075;
 AN_IHCsynapseParams.TWdelay=0.004;  % ?delay before stimulus first spike
-AN_IHCsynapseParams.ANspeedUpFactor=5; % longer epochs for computing spikes.
+AN_IHCsynapseParams.spikesTargetSampleRate=10000;
+% AN_IHCsynapseParams.ANspeedUpFactor=5; % longer epochs for computing spikes.
 
 % c=kym/(y(l+r)+kl)	(spontaneous rate)
 % c=(approx)  ym/l  (saturated rate)
@@ -205,7 +203,7 @@
         MacGregorMultiParams.fibersPerNeuron=10;  % N input fibers
 
         MacGregorMultiParams.dendriteLPfreq=50;   % dendritic filter
-        MacGregorMultiParams.currentPerSpike=35e-9; % *per spike
+        MacGregorMultiParams.currentPerSpike=28e-9; % *per spike
 %         MacGregorMultiParams.currentPerSpike=30e-9; % *per spike
         
         MacGregorMultiParams.Cap=1.67e-8; % ??cell capacitance (Siemens)
@@ -226,7 +224,6 @@
 MacGregorParams.type = 'chopper cell';
 MacGregorParams.fibersPerNeuron=10; % N input fibers
 MacGregorParams.dendriteLPfreq=100; % dendritic filter
-MacGregorParams.currentPerSpike=120e-9;% *(A) per spike
 MacGregorParams.currentPerSpike=40e-9;% *(A) per spike
 
 MacGregorParams.Cap=16.7e-9;        % cell capacitance (Siemens)
@@ -246,18 +243,26 @@
 % MacGregorParams.saveAllData=0;
 
 %%  #9 filteredSACF
-minPitch=	300; maxPitch=	3000; numPitches=60;    % specify lags
-pitches=100*log10(logspace(minPitch/100, maxPitch/100, numPitches));
-filteredSACFParams.lags=1./pitches;     % autocorrelation lags vector
-filteredSACFParams.acfTau=	.003;       % time constant of running ACF
-filteredSACFParams.lambda=	0.12;       % slower filter to smooth ACF
-filteredSACFParams.plotFilteredSACF=1;  % 0 plots unfiltered ACFs
-filteredSACFParams.plotACFs=0;          % special plot (see code)
-%  filteredSACFParams.usePressnitzer=0; % attenuates ACF at  long lags
-filteredSACFParams.lagsProcedure=  'useAllLags';
-% filteredSACFParams.lagsProcedure=  'useBernsteinLagWeights';
-% filteredSACFParams.lagsProcedure=  'omitShortLags';
-filteredSACFParams.criterionForOmittingLags=3;
+% identify periodicities to be logged
+    minPitch=	80; maxPitch=	500; numPitches=50;  
+    maxLag=1/minPitch; minLag=1/maxPitch;
+    lags= linspace(minLag, maxLag, numPitches);
+    pitches=10.^ linspace(log10(minPitch), log10(maxPitch),numPitches);
+    pitches=fliplr(pitches);
+    % convert to lags for ACF
+    filteredSACFParams.lags=lags;     % autocorrelation lags vector
+    filteredSACFParams.acfTau=	.003;       % time constant of running ACF
+    filteredSACFParams.lambda=	0.12;       % slower filter to smooth ACF
+    % request plot of within-channel ACFs at fixed intervals in time
+    filteredSACFParams.plotACFs=1;          
+    filteredSACFParams.plotACFsInterval=0.002;
+    filteredSACFParams.plotMoviePauses=.1;  
+
+    filteredSACFParams.usePressnitzer=0; % attenuates ACF at  long lags
+    filteredSACFParams.lagsProcedure=  'useAllLags';
+    %  'useAllLags' or 'omitShortLags'
+    filteredSACFParams.criterionForOmittingLags=3;
+
 
 % checks
 if AN_IHCsynapseParams.numFibers<MacGregorMultiParams.fibersPerNeuron
@@ -269,7 +274,7 @@
 % paramChanges
 if nargin>3 && ~isempty(paramChanges)
     if ~iscellstr(paramChanges)
-        error(['paramChanges error: paramChanges not a cell array'])
+        error('paramChanges error: paramChanges not a cell array')
     end
     
     nChanges=length(paramChanges);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/parameterStore/MAPparamsOHCloss.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,328 @@
+function method=MAPparamsOHCloss ...
+    (BFlist, sampleRate, showParams, paramChanges)
+% MAPparamsOHCloss.m is a parameter file, similar in all respects to
+% MAPparamsNormal except that the parameter 'DRNLParams.a' is set to zero.
+%
+% MAPparams<> establishes a complete set of MAP parameters
+% Parameter file names must be of the form <MAPparams><name>
+%
+% Input arguments
+%  BFlist     (optional) specifies the desired list of channel BFs
+%    otherwise defaults set below
+%  sampleRate (optional), default is 50000.
+%  showParams (optional) =1 prints out the complete set of parameters
+% Output argument
+%  method passes a miscelleny of values
+%  the use of 'method' is being phased out. use globals
+
+global inputStimulusParams OMEParams DRNLParams IHC_cilia_RPParams
+global IHCpreSynapseParams  AN_IHCsynapseParams
+global MacGregorParams MacGregorMultiParams  filteredSACFParams
+global experiment % used only by calls from multiThreshold
+% global IHC_VResp_VivoParams
+
+currentFile=mfilename;                      % i.e. the name of this mfile
+method.parameterSource=currentFile(10:end); % for the record
+
+efferentDelay=0.010;
+method.segmentDuration=efferentDelay;
+
+if nargin<3, showParams=0; end
+if nargin<2, sampleRate=44100; end
+if nargin<1 || BFlist(1)<0 % if BFlist= -1, set BFlist to default
+    lowestBF=250; 	highestBF= 8000; 	numChannels=21;
+    % 21 chs (250-8k)includes BFs at 250 500 1000 2000 4000 8000
+    BFlist=round(logspace(log10(lowestBF),log10(highestBF),numChannels));
+end
+% BFlist=1000;  % single channel option
+
+% preserve for backward campatibility
+method.nonlinCF=BFlist; 
+method.dt=1/sampleRate; 
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% set  model parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%%  #1 inputStimulus
+inputStimulusParams=[];
+inputStimulusParams.sampleRate= sampleRate; 
+
+%%  #2 outerMiddleEar
+OMEParams=[];  % clear the structure first
+% outer ear resonances band pass filter  [gain lp order  hp]
+OMEParams.externalResonanceFilters=      [ 10 1 1000 4000];
+                                       
+% highpass stapes filter  
+%  Huber gives 2e-9 m at 80 dB and 1 kHz (2e-13 at 0 dB SPL)
+OMEParams.OMEstapesHPcutoff= 1000;
+OMEParams.stapesScalar=	     45e-9;
+
+% Acoustic reflex: maximum attenuation should be around 25 dB (Price, 1966)
+% i.e. a minimum ratio of 0.056.
+% 'spikes' model: AR based on brainstem spiking activity (LSR)
+OMEParams.rateToAttenuationFactor=0.05; % * N(all ICspikes)
+% 'probability model': Ar based on AN firing probabilities (LSR)
+OMEParams.rateToAttenuationFactorProb=0.02;    % * N(all ANrates)
+
+% asymptote should be around 100-200 ms
+OMEParams.ARtau=.250; % AR smoothing function 250 ms fits Hung and Dallos
+% delay must be longer than the segment length
+OMEParams.ARdelay=efferentDelay;  %Moss gives 8.5 ms latency
+OMEParams.ARrateThreshold=40;
+
+%%  #3 DRNL
+DRNLParams=[];  % clear the structure first
+% DRNLParams.BFlist=BFlist;
+
+%   *** DRNL nonlinear path
+% broken stick compression
+% DRNLParams.a=2e4;     % normal value (commented out)
+DRNLParams.a=0;         % DRNL.a=0 means no OHCs (no nonlinear path)
+DRNLParams.c=.2;        % compression exponent
+DRNLParams.ctBMdB = 10; %Compression threshold dB re 10e-9 m displacement
+
+% filters
+DRNLParams.nonlinOrder=	3;  % order of nonlinear gammatone filters
+DRNLParams.nonlinCFs=BFlist;
+DRNLParams.p=0.2895;   DRNLParams.q=250;   % save p and q for printing only
+% p=0.2895;   q=250;      % human  (% p=0.14;   q=366;  % cat)
+DRNLParams.nlBWs=  DRNLParams.p * BFlist + DRNLParams.q;
+
+%   *** DRNL linear path:
+DRNLParams.g=100;       % linear path gain factor
+DRNLParams.linOrder=3;  % order of linear gammatone filters
+% linCF is not necessarily the same as nonlinCF
+minLinCF=153.13; coeffLinCF=0.7341;   % linCF>nonlinBF for BF < 1 kHz
+DRNLParams.linCFs=minLinCF+coeffLinCF*BFlist;
+% bandwidths (linear)
+minLinBW=100; coeffLinBW=0.6531;
+DRNLParams.linBWs=minLinBW + coeffLinBW*BFlist; % bandwidths of linear  filters
+
+%   *** DRNL MOC efferents
+DRNLParams.MOCdelay = efferentDelay;            % must be < segment length!
+DRNLParams.minMOCattenuationdB=-35;
+
+% 'spikes' model: MOC based on brainstem spiking activity (HSR)
+DRNLParams.MOCtau =.0285;                         % smoothing for MOC
+DRNLParams.rateToAttenuationFactor = .03;  % strength of MOC
+DRNLParams.rateToAttenuationFactor = .0055;  % strength of MOC
+
+% 'probability' model: MOC based on AN probability (HSR)
+DRNLParams.MOCtauProb =.285;                         % smoothing for MOC
+DRNLParams.rateToAttenuationFactorProb = 0.007;  % strength of MOC
+DRNLParams.MOCrateThresholdProb =67;                % spikes/s probability only
+
+
+%% #4 IHC_cilia_RPParams
+IHC_cilia_RPParams.tc=	0.00012;   % 0.0003 Shamma
+IHC_cilia_RPParams.C=	0.08;       % 0.1 scalar (C_cilia ) 
+IHC_cilia_RPParams.u0=	5e-9;       
+IHC_cilia_RPParams.s0=	30e-9;
+IHC_cilia_RPParams.u1=	1e-9;
+IHC_cilia_RPParams.s1=	1e-9;
+
+IHC_cilia_RPParams.Gmax= 6e-9;    % 2.5e-9 maximum conductance (Siemens)
+IHC_cilia_RPParams.Ga=	1e-9;  % 4.3e-9 fixed apical membrane conductance
+IHC_cilia_RPParams.Ga=	.8e-9;  % 4.3e-9 fixed apical membrane conductance
+
+%  #5 IHC_RP
+IHC_cilia_RPParams.Cab=	4e-012;         % IHC capacitance (F)
+% IHC_cilia_RPParams.Cab=	1e-012;         % IHC capacitance (F)
+IHC_cilia_RPParams.Et=	0.100;          % endocochlear potential (V)
+
+IHC_cilia_RPParams.Gk=	2e-008;         % 1e-8 potassium conductance (S)
+IHC_cilia_RPParams.Ek=	-0.08;          % -0.084 K equilibrium potential
+IHC_cilia_RPParams.Rpc=	0.04;           % combined resistances
+
+
+%%  #5 IHCpreSynapse
+IHCpreSynapseParams=[];
+IHCpreSynapseParams.GmaxCa=	14e-9;% maximum calcium conductance
+% IHCpreSynapseParams.GmaxCa=	12e-9;% maximum calcium conductance
+IHCpreSynapseParams.ECa=	0.066;  % calcium equilibrium potential
+IHCpreSynapseParams.beta=	400;	% determine Ca channel opening
+IHCpreSynapseParams.gamma=	100;	% determine Ca channel opening
+IHCpreSynapseParams.tauM=	0.00005;	% membrane time constant ?0.1ms
+IHCpreSynapseParams.power=	3;
+% reminder: changing z has a strong effect on HF thresholds (like Et)
+IHCpreSynapseParams.z=	    2e42;   % scalar Ca -> vesicle release rate
+
+LSRtauCa=30e-6;            HSRtauCa=80e-6;            % seconds
+% LSRtauCa=40e-6;            HSRtauCa=90e-6;            % seconds
+% IHCpreSynapseParams.tauCa= [15e-6 80e-6]; %LSR and HSR fiber
+IHCpreSynapseParams.tauCa= [LSRtauCa HSRtauCa]; %LSR and HSR fiber
+
+%%  #6 AN_IHCsynapse
+AN_IHCsynapseParams=[];             % clear the structure first
+% number of AN fibers at each BF (used only for spike generation)
+AN_IHCsynapseParams.numFibers=	100; 
+% absolute refractory period. Relative refractory period is the same. 
+AN_IHCsynapseParams.refractory_period=	0.00075;
+AN_IHCsynapseParams.TWdelay=0.004;  % ?delay before stimulus first spike
+AN_IHCsynapseParams.spikesTargetSampleRate=10000;
+% AN_IHCsynapseParams.ANspeedUpFactor=5; % longer epochs for computing spikes.
+
+% c=kym/(y(l+r)+kl)	(spontaneous rate)
+% c=(approx)  ym/l  (saturated rate)
+AN_IHCsynapseParams.M=	12;         % maximum vesicles at synapse
+AN_IHCsynapseParams.y=	4;          % depleted vesicle replacement rate
+AN_IHCsynapseParams.y=	6;          % depleted vesicle replacement rate
+
+AN_IHCsynapseParams.x=	30;         % replenishment from re-uptake store
+AN_IHCsynapseParams.x=	60;         % replenishment from re-uptake store
+
+% reduce l to increase saturated rate
+AN_IHCsynapseParams.l=	100; % *loss rate of vesicles from the cleft
+AN_IHCsynapseParams.l=	250; % *loss rate of vesicles from the cleft
+
+AN_IHCsynapseParams.r=	500; % *reuptake rate from cleft into cell
+% AN_IHCsynapseParams.r=	300; % *reuptake rate from cleft into cell
+
+
+%%  #7 MacGregorMulti (first order brainstem neurons)
+MacGregorMultiParams=[];
+MacGregorMultiType='chopper'; % MacGregorMultiType='primary-like'; %choose
+switch MacGregorMultiType
+    case 'primary-like'
+        MacGregorMultiParams.nNeuronsPerBF=	10;   % N neurons per BF
+        MacGregorMultiParams.type = 'primary-like cell';
+        MacGregorMultiParams.fibersPerNeuron=4;   % N input fibers
+        MacGregorMultiParams.dendriteLPfreq=200;  % dendritic filter
+        MacGregorMultiParams.currentPerSpike=0.11e-6; % (A) per spike
+        MacGregorMultiParams.Cap=4.55e-9;   % cell capacitance (Siemens)
+        MacGregorMultiParams.tauM=5e-4;     % membrane time constant (s)
+        MacGregorMultiParams.Ek=-0.01;      % K+ eq. potential (V)
+        MacGregorMultiParams.dGkSpike=3.64e-5; % K+ cond.shift on spike,S
+        MacGregorMultiParams.tauGk=	0.0012; % K+ conductance tau (s)
+        MacGregorMultiParams.Th0=	0.01;   % equilibrium threshold (V)
+        MacGregorMultiParams.c=	0.01;       % threshold shift on spike, (V)
+        MacGregorMultiParams.tauTh=	0.015;  % variable threshold tau
+        MacGregorMultiParams.Er=-0.06;      % resting potential (V)
+        MacGregorMultiParams.Eb=0.06;       % spike height (V)
+
+    case 'chopper'
+        MacGregorMultiParams.nNeuronsPerBF=	10;   % N neurons per BF
+        MacGregorMultiParams.type = 'chopper cell';
+        MacGregorMultiParams.fibersPerNeuron=10;  % N input fibers
+
+        MacGregorMultiParams.dendriteLPfreq=50;   % dendritic filter
+        MacGregorMultiParams.currentPerSpike=28e-9; % *per spike
+%         MacGregorMultiParams.currentPerSpike=30e-9; % *per spike
+        
+        MacGregorMultiParams.Cap=1.67e-8; % ??cell capacitance (Siemens)
+        MacGregorMultiParams.tauM=0.002;  % membrane time constant (s)
+        MacGregorMultiParams.Ek=-0.01;    % K+ eq. potential (V)
+        MacGregorMultiParams.dGkSpike=1.33e-4; % K+ cond.shift on spike,S
+        MacGregorMultiParams.tauGk=	0.0005;% K+ conductance tau (s)
+        MacGregorMultiParams.Th0=	0.01; % equilibrium threshold (V)
+        MacGregorMultiParams.c=	0;        % threshold shift on spike, (V)
+        MacGregorMultiParams.tauTh=	0.02; % variable threshold tau
+        MacGregorMultiParams.Er=-0.06;    % resting potential (V)
+        MacGregorMultiParams.Eb=0.06;     % spike height (V)
+        MacGregorMultiParams.PSTHbinWidth=	1e-4;
+end
+
+%%  #8 MacGregor (second-order neuron). Only one per channel
+MacGregorParams=[];                 % clear the structure first
+MacGregorParams.type = 'chopper cell';
+MacGregorParams.fibersPerNeuron=10; % N input fibers
+MacGregorParams.dendriteLPfreq=100; % dendritic filter
+MacGregorParams.currentPerSpike=40e-9;% *(A) per spike
+
+MacGregorParams.Cap=16.7e-9;        % cell capacitance (Siemens)
+MacGregorParams.tauM=0.002;         % membrane time constant (s)
+MacGregorParams.Ek=-0.01;           % K+ eq. potential (V)
+MacGregorParams.dGkSpike=1.33e-4;   % K+ cond.shift on spike,S
+MacGregorParams.tauGk=	0.0012;     % K+ conductance tau (s)
+MacGregorParams.Th0=	0.01;       % equilibrium threshold (V)
+MacGregorParams.c=	0;              % threshold shift on spike, (V)
+MacGregorParams.tauTh=	0.02;       % variable threshold tau
+MacGregorParams.Er=-0.06;           % resting potential (V)
+MacGregorParams.Eb=0.06;            % spike height (V)
+MacGregorParams.debugging=0;        % (special)
+% wideband accepts input from all channels (of same fiber type)
+% use wideband to create inhibitory units
+MacGregorParams.wideband=0;         % special for wideband units
+% MacGregorParams.saveAllData=0;
+
+%%  #9 filteredSACF
+minPitch=	300; maxPitch=	3000; numPitches=60;    % specify lags
+pitches=100*log10(logspace(minPitch/100, maxPitch/100, numPitches));
+filteredSACFParams.lags=1./pitches;     % autocorrelation lags vector
+filteredSACFParams.acfTau=	.003;       % time constant of running ACF
+filteredSACFParams.lambda=	0.12;       % slower filter to smooth ACF
+filteredSACFParams.plotFilteredSACF=1;  % 0 plots unfiltered ACFs
+filteredSACFParams.plotACFs=0;          % special plot (see code)
+%  filteredSACFParams.usePressnitzer=0; % attenuates ACF at  long lags
+filteredSACFParams.lagsProcedure=  'useAllLags';
+% filteredSACFParams.lagsProcedure=  'omitShortLags';
+filteredSACFParams.criterionForOmittingLags=3;
+
+% checks
+if AN_IHCsynapseParams.numFibers<MacGregorMultiParams.fibersPerNeuron
+    error('MacGregorMulti: too few input fibers for input to MacG unit')
+end
+
+
+%% now accept last minute parameter changes required by the calling program
+% paramChanges
+if nargin>3 && ~isempty(paramChanges)
+    if ~iscellstr(paramChanges)
+        error('paramChanges error: paramChanges not a cell array')
+    end
+    
+    nChanges=length(paramChanges);
+    for idx=1:nChanges
+        x=paramChanges{idx};
+        x=deblank(x);
+        if ~isempty(x)
+            if ~strcmp(x(end),';')
+                error(['paramChanges error (terminate with semicolon) ' x])
+            end
+            st=strtrim(x(1:strfind(x,'.')-1));
+            fld=strtrim(x(strfind(x,'.')+1:strfind(x,'=')-1));
+            value=x(strfind(x,'=')+1:end);
+            if isempty(st) || isempty(fld) || isempty(value)
+                error(['paramChanges error:' x])
+            end
+            
+            x1=eval(['isstruct(' st ')']);
+            cmd=['isfield(' st ',''' fld ''')'];
+            x2=eval(cmd);
+            if ~(x1*x2)
+                error(['paramChanges error:' x])
+            end
+        end
+        
+        % no problems so go ahead
+        eval(paramChanges{idx})
+    end
+end
+
+
+%% write all parameters to the command window
+% showParams is currently set at the top of htis function
+if showParams
+    fprintf('\n %%%%%%%%\n')
+    fprintf('\n%s\n', method.parameterSource)
+    fprintf('\n')
+    nm=UTIL_paramsList(whos);
+    for i=1:length(nm)
+        %         eval(['UTIL_showStruct(' nm{i} ', ''' nm{i} ''')'])
+        if ~strcmp(nm(i), 'method')
+            eval(['UTIL_showStructureSummary(' nm{i} ', ''' nm{i} ''', 10)'])
+        end
+    end
+
+    % highlight parameter changes made locally
+    if nargin>3 && ~isempty(paramChanges)
+        fprintf('\n Local parameter changes:\n')
+        for i=1:length(paramChanges)
+            disp(paramChanges{i})
+        end
+    end
+end
+
+% for backward compatibility
+experiment.comparisonData=[];
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/parameterStore/MAPparamsPL.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,329 @@
+function method=MAPparamsPL ...
+    (BFlist, sampleRate, showParams, paramChanges)
+% MAPparamsPL.m is a parameter file, similar in all respects to
+%  MAPparamsNormal except that a primary-like' neuron is used at the 
+%  level of the cochlear nuclues (rather than a chopper cell).
+%
+% MAPparams<> establishes a complete set of MAP parameters
+% Parameter file names must be of the form <MAPparams><name>
+%
+% Input arguments
+%  BFlist     (optional) specifies the desired list of channel BFs
+%    otherwise defaults set below
+%  sampleRate (optional), default is 50000.
+%  showParams (optional) =1 prints out the complete set of parameters
+% Output argument
+%  method passes a miscelleny of values
+%  the use of 'method' is being phased out. use globals
+
+global inputStimulusParams OMEParams DRNLParams IHC_cilia_RPParams
+global IHCpreSynapseParams  AN_IHCsynapseParams
+global MacGregorParams MacGregorMultiParams  filteredSACFParams
+global experiment % used only by calls from multiThreshold
+% global IHC_VResp_VivoParams
+
+currentFile=mfilename;                      % i.e. the name of this mfile
+method.parameterSource=currentFile(10:end); % for the record
+
+efferentDelay=0.010;
+method.segmentDuration=efferentDelay;
+
+if nargin<3, showParams=0; end
+if nargin<2, sampleRate=50000; end
+if nargin<1 || BFlist(1)<0 % if BFlist= -1, set BFlist to default
+    lowestBF=250; 	highestBF= 8000; 	numChannels=21;
+    % 21 chs (250-8k)includes BFs at 250 500 1000 2000 4000 8000
+    BFlist=round(logspace(log10(lowestBF),log10(highestBF),numChannels));
+end
+% BFlist=1000;  % single channel option
+
+% preserve for backward campatibility
+method.nonlinCF=BFlist; 
+method.dt=1/sampleRate; 
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% set  model parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%%  #1 inputStimulus
+inputStimulusParams=[];
+inputStimulusParams.sampleRate= sampleRate; 
+
+%%  #2 outerMiddleEar
+OMEParams=[];  % clear the structure first
+% outer ear resonances band pass filter  [gain lp order  hp]
+OMEParams.externalResonanceFilters=      [ 10 1 1000 4000];
+                                       
+% highpass stapes filter  
+%  Huber gives 2e-9 m at 80 dB and 1 kHz (2e-13 at 0 dB SPL)
+OMEParams.OMEstapesHPcutoff= 1000;
+OMEParams.stapesScalar=	     45e-9;
+
+% Acoustic reflex: maximum attenuation should be around 25 dB (Price, 1966)
+% i.e. a minimum ratio of 0.056.
+% 'spikes' model: AR based on brainstem spiking activity (LSR)
+OMEParams.rateToAttenuationFactor=0.05; % * N(all ICspikes)
+% 'probability model': Ar based on AN firing probabilities (LSR)
+OMEParams.rateToAttenuationFactorProb=0.02;    % * N(all ANrates)
+
+% asymptote should be around 100-200 ms
+OMEParams.ARtau=.250; % AR smoothing function 250 ms fits Hung and Dallos
+% delay must be longer than the segment length
+OMEParams.ARdelay=efferentDelay;  %Moss gives 8.5 ms latency
+OMEParams.ARrateThreshold=40;
+
+%%  #3 DRNL
+DRNLParams=[];  % clear the structure first
+% DRNLParams.BFlist=BFlist;
+
+%   *** DRNL nonlinear path
+% broken stick compression
+DRNLParams.a=2e4;       % DRNL.a=0 means no OHCs (no nonlinear path)
+DRNLParams.c=.2;        % compression exponent
+DRNLParams.ctBMdB = 10; %Compression threshold dB re 10e-9 m displacement
+
+% filters
+DRNLParams.nonlinOrder=	3;  % order of nonlinear gammatone filters
+DRNLParams.nonlinCFs=BFlist;
+DRNLParams.p=0.2895;   DRNLParams.q=250;   % save p and q for printing only
+% p=0.2895;   q=250;      % human  (% p=0.14;   q=366;  % cat)
+DRNLParams.nlBWs=  DRNLParams.p * BFlist + DRNLParams.q;
+
+%   *** DRNL linear path:
+DRNLParams.g=100;       % linear path gain factor
+DRNLParams.linOrder=3;  % order of linear gammatone filters
+% linCF is not necessarily the same as nonlinCF
+minLinCF=153.13; coeffLinCF=0.7341;   % linCF>nonlinBF for BF < 1 kHz
+DRNLParams.linCFs=minLinCF+coeffLinCF*BFlist;
+% bandwidths (linear)
+minLinBW=100; coeffLinBW=0.6531;
+DRNLParams.linBWs=minLinBW + coeffLinBW*BFlist; % bandwidths of linear  filters
+
+%   *** DRNL MOC efferents
+DRNLParams.MOCdelay = efferentDelay;            % must be < segment length!
+DRNLParams.minMOCattenuationdB=-35;
+
+% 'spikes' model: MOC based on brainstem spiking activity (HSR)
+DRNLParams.MOCtau =.0285;                         % smoothing for MOC
+DRNLParams.rateToAttenuationFactor = .03;  % strength of MOC
+DRNLParams.rateToAttenuationFactor = .0055;  % strength of MOC
+
+% 'probability' model: MOC based on AN probability (HSR)
+DRNLParams.MOCtauProb =.285;                         % smoothing for MOC
+DRNLParams.rateToAttenuationFactorProb = 0.007;  % strength of MOC
+DRNLParams.MOCrateThresholdProb =67;                % spikes/s probability only
+
+
+%% #4 IHC_cilia_RPParams
+IHC_cilia_RPParams.tc=	0.00012;   % 0.0003 Shamma
+IHC_cilia_RPParams.C=	0.08;       % 0.1 scalar (C_cilia ) 
+IHC_cilia_RPParams.u0=	5e-9;       
+IHC_cilia_RPParams.s0=	30e-9;
+IHC_cilia_RPParams.u1=	1e-9;
+IHC_cilia_RPParams.s1=	1e-9;
+
+IHC_cilia_RPParams.Gmax= 6e-9;    % 2.5e-9 maximum conductance (Siemens)
+IHC_cilia_RPParams.Ga=	1e-9;  % 4.3e-9 fixed apical membrane conductance
+IHC_cilia_RPParams.Ga=	.8e-9;  % 4.3e-9 fixed apical membrane conductance
+
+%  #5 IHC_RP
+IHC_cilia_RPParams.Cab=	4e-012;         % IHC capacitance (F)
+% IHC_cilia_RPParams.Cab=	1e-012;         % IHC capacitance (F)
+IHC_cilia_RPParams.Et=	0.100;          % endocochlear potential (V)
+
+IHC_cilia_RPParams.Gk=	2e-008;         % 1e-8 potassium conductance (S)
+IHC_cilia_RPParams.Ek=	-0.08;          % -0.084 K equilibrium potential
+IHC_cilia_RPParams.Rpc=	0.04;           % combined resistances
+
+
+%%  #5 IHCpreSynapse
+IHCpreSynapseParams=[];
+IHCpreSynapseParams.GmaxCa=	14e-9;% maximum calcium conductance
+% IHCpreSynapseParams.GmaxCa=	12e-9;% maximum calcium conductance
+IHCpreSynapseParams.ECa=	0.066;  % calcium equilibrium potential
+IHCpreSynapseParams.beta=	400;	% determine Ca channel opening
+IHCpreSynapseParams.gamma=	100;	% determine Ca channel opening
+IHCpreSynapseParams.tauM=	0.00005;	% membrane time constant ?0.1ms
+IHCpreSynapseParams.power=	3;
+% reminder: changing z has a strong effect on HF thresholds (like Et)
+IHCpreSynapseParams.z=	    2e42;   % scalar Ca -> vesicle release rate
+
+LSRtauCa=30e-6;            HSRtauCa=80e-6;            % seconds
+% LSRtauCa=40e-6;            HSRtauCa=90e-6;            % seconds
+% IHCpreSynapseParams.tauCa= [15e-6 80e-6]; %LSR and HSR fiber
+IHCpreSynapseParams.tauCa= [LSRtauCa HSRtauCa]; %LSR and HSR fiber
+
+%%  #6 AN_IHCsynapse
+AN_IHCsynapseParams=[];             % clear the structure first
+% number of AN fibers at each BF (used only for spike generation)
+AN_IHCsynapseParams.numFibers=	100; 
+% absolute refractory period. Relative refractory period is the same. 
+AN_IHCsynapseParams.refractory_period=	0.00075;
+AN_IHCsynapseParams.TWdelay=0.004;  % ?delay before stimulus first spike
+AN_IHCsynapseParams.spikesTargetSampleRate=sampleRate;
+% AN_IHCsynapseParams.ANspeedUpFactor=5; % longer epochs for computing spikes.
+
+% c=kym/(y(l+r)+kl)	(spontaneous rate)
+% c=(approx)  ym/l  (saturated rate)
+AN_IHCsynapseParams.M=	12;         % maximum vesicles at synapse
+AN_IHCsynapseParams.y=	4;          % depleted vesicle replacement rate
+AN_IHCsynapseParams.y=	6;          % depleted vesicle replacement rate
+
+AN_IHCsynapseParams.x=	30;         % replenishment from re-uptake store
+AN_IHCsynapseParams.x=	60;         % replenishment from re-uptake store
+
+% reduce l to increase saturated rate
+AN_IHCsynapseParams.l=	100; % *loss rate of vesicles from the cleft
+AN_IHCsynapseParams.l=	250; % *loss rate of vesicles from the cleft
+
+AN_IHCsynapseParams.r=	500; % *reuptake rate from cleft into cell
+% AN_IHCsynapseParams.r=	300; % *reuptake rate from cleft into cell
+
+
+%%  #7 MacGregorMulti (first order brainstem neurons)
+MacGregorMultiParams=[];
+% MacGregorMultiType='chopper'; % MacGregorMultiType='primary-like'; %choose
+MacGregorMultiType='primary-like'; % MacGregorMultiType='primary-like'; %choose
+switch MacGregorMultiType
+    case 'primary-like'
+        MacGregorMultiParams.nNeuronsPerBF=	10;   % N neurons per BF
+        MacGregorMultiParams.type = 'primary-like cell';
+        MacGregorMultiParams.fibersPerNeuron=4;   % N input fibers
+        MacGregorMultiParams.dendriteLPfreq=500;  % dendritic filter
+        MacGregorMultiParams.currentPerSpike=0.11e-6; % (A) per spike
+        MacGregorMultiParams.Cap=4.55e-9;   % cell capacitance (Siemens)
+        MacGregorMultiParams.tauM=5e-4;     % membrane time constant (s)
+        MacGregorMultiParams.Ek=-0.01;      % K+ eq. potential (V)
+        MacGregorMultiParams.dGkSpike=3.64e-5; % K+ cond.shift on spike,S
+        MacGregorMultiParams.tauGk=	0.0005; % K+ conductance tau (s)
+        MacGregorMultiParams.Th0=	0.01;   % equilibrium threshold (V)
+        MacGregorMultiParams.c=	0.01;       % threshold shift on spike, (V)
+        MacGregorMultiParams.tauTh=	0.015;  % variable threshold tau
+        MacGregorMultiParams.Er=-0.06;      % resting potential (V)
+        MacGregorMultiParams.Eb=0.06;       % spike height (V)
+
+    case 'chopper'
+        MacGregorMultiParams.nNeuronsPerBF=	10;   % N neurons per BF
+        MacGregorMultiParams.type = 'chopper cell';
+        MacGregorMultiParams.fibersPerNeuron=10;  % N input fibers
+
+        MacGregorMultiParams.dendriteLPfreq=50;   % dendritic filter
+        MacGregorMultiParams.currentPerSpike=28e-9; % *per spike
+%         MacGregorMultiParams.currentPerSpike=30e-9; % *per spike
+        
+        MacGregorMultiParams.Cap=1.67e-8; % ??cell capacitance (Siemens)
+        MacGregorMultiParams.tauM=0.002;  % membrane time constant (s)
+        MacGregorMultiParams.Ek=-0.01;    % K+ eq. potential (V)
+        MacGregorMultiParams.dGkSpike=1.33e-4; % K+ cond.shift on spike,S
+        MacGregorMultiParams.tauGk=	0.0005;% K+ conductance tau (s)
+        MacGregorMultiParams.Th0=	0.01; % equilibrium threshold (V)
+        MacGregorMultiParams.c=	0;        % threshold shift on spike, (V)
+        MacGregorMultiParams.tauTh=	0.02; % variable threshold tau
+        MacGregorMultiParams.Er=-0.06;    % resting potential (V)
+        MacGregorMultiParams.Eb=0.06;     % spike height (V)
+        MacGregorMultiParams.PSTHbinWidth=	1e-4;
+end
+
+%%  #8 MacGregor (second-order neuron). Only one per channel
+MacGregorParams=[];                 % clear the structure first
+MacGregorParams.type = 'chopper cell';
+MacGregorParams.fibersPerNeuron=10; % N input fibers
+MacGregorParams.dendriteLPfreq=100; % dendritic filter
+MacGregorParams.currentPerSpike=40e-9;% *(A) per spike
+
+MacGregorParams.Cap=16.7e-9;        % cell capacitance (Siemens)
+MacGregorParams.tauM=0.002;         % membrane time constant (s)
+MacGregorParams.Ek=-0.01;           % K+ eq. potential (V)
+MacGregorParams.dGkSpike=1.33e-4;   % K+ cond.shift on spike,S
+MacGregorParams.tauGk=	0.0012;     % K+ conductance tau (s)
+MacGregorParams.Th0=	0.01;       % equilibrium threshold (V)
+MacGregorParams.c=	0;              % threshold shift on spike, (V)
+MacGregorParams.tauTh=	0.02;       % variable threshold tau
+MacGregorParams.Er=-0.06;           % resting potential (V)
+MacGregorParams.Eb=0.06;            % spike height (V)
+MacGregorParams.debugging=0;        % (special)
+% wideband accepts input from all channels (of same fiber type)
+% use wideband to create inhibitory units
+MacGregorParams.wideband=0;         % special for wideband units
+% MacGregorParams.saveAllData=0;
+
+%%  #9 filteredSACF
+minPitch=	300; maxPitch=	3000; numPitches=60;    % specify lags
+pitches=100*log10(logspace(minPitch/100, maxPitch/100, numPitches));
+filteredSACFParams.lags=1./pitches;     % autocorrelation lags vector
+filteredSACFParams.acfTau=	.003;       % time constant of running ACF
+filteredSACFParams.lambda=	0.12;       % slower filter to smooth ACF
+filteredSACFParams.plotFilteredSACF=1;  % 0 plots unfiltered ACFs
+filteredSACFParams.plotACFs=0;          % special plot (see code)
+%  filteredSACFParams.usePressnitzer=0; % attenuates ACF at  long lags
+filteredSACFParams.lagsProcedure=  'useAllLags';
+% filteredSACFParams.lagsProcedure=  'omitShortLags';
+filteredSACFParams.criterionForOmittingLags=3;
+
+% checks
+if AN_IHCsynapseParams.numFibers<MacGregorMultiParams.fibersPerNeuron
+    error('MacGregorMulti: too few input fibers for input to MacG unit')
+end
+
+
+%% now accept last minute parameter changes required by the calling program
+% paramChanges
+if nargin>3 && ~isempty(paramChanges)
+    if ~iscellstr(paramChanges)
+        error('paramChanges error: paramChanges not a cell array')
+    end
+    
+    nChanges=length(paramChanges);
+    for idx=1:nChanges
+        x=paramChanges{idx};
+        x=deblank(x);
+        if ~isempty(x)
+            if ~strcmp(x(end),';')
+                error(['paramChanges error (terminate with semicolon) ' x])
+            end
+            st=strtrim(x(1:strfind(x,'.')-1));
+            fld=strtrim(x(strfind(x,'.')+1:strfind(x,'=')-1));
+            value=x(strfind(x,'=')+1:end);
+            if isempty(st) || isempty(fld) || isempty(value)
+                error(['paramChanges error:' x])
+            end
+            
+            x1=eval(['isstruct(' st ')']);
+            cmd=['isfield(' st ',''' fld ''')'];
+            x2=eval(cmd);
+            if ~(x1*x2)
+                error(['paramChanges error:' x])
+            end
+        end
+        
+        % no problems so go ahead
+        eval(paramChanges{idx})
+    end
+end
+
+
+%% write all parameters to the command window
+% showParams is currently set at the top of htis function
+if showParams
+    fprintf('\n %%%%%%%%\n')
+    fprintf('\n%s\n', method.parameterSource)
+    fprintf('\n')
+    nm=UTIL_paramsList(whos);
+    for i=1:length(nm)
+        %         eval(['UTIL_showStruct(' nm{i} ', ''' nm{i} ''')'])
+        if ~strcmp(nm(i), 'method')
+            eval(['UTIL_showStructureSummary(' nm{i} ', ''' nm{i} ''', 10)'])
+        end
+    end
+
+    % highlight parameter changes made locally
+    if nargin>3 && ~isempty(paramChanges)
+        fprintf('\n Local parameter changes:\n')
+        for i=1:length(paramChanges)
+            disp(paramChanges{i})
+        end
+    end
+end
+
+% for backward compatibility
+experiment.comparisonData=[];
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/profiles/MTprofile11_5hr05_Oct_2011.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,31 @@
+function x = MTprofile11_5hr05_Oct_2011
+%created: 11_5hr05_Oct_2011
+
+x.BFs = [250   500  1000  2000  4000  8000];
+
+x.LongTone = [26.6      23.8      29.1      47.2      62.9      48.4];
+x.ShortTone = [34.1      33.4      37.6      64.3      78.1      62.4];
+
+x.Gaps = [0.01      0.03      0.05      0.07      0.09];
+x.TMCFreq = [250   500  1000  2000  4000  8000];
+x.TMC = [
+49.9	55.5	47.3	70.7	94.5	54.2	 
+52.3	55.4	42.6	69.4	95.2	56.7	 
+55.1	67.5	49.6	73.5	96.6	84	 
+60.3	72.2	53.5	85.4	99	70.2	 
+64.3	78.7	61.3	83.2	102	66.8	 
+];
+x.TMC = x.TMC';
+
+x.MaskerRatio = [0.5      0.7      0.9        1      1.1      1.3      1.6];
+x.IFMCFreq = [250   500  1000  2000  4000  8000];
+x.IFMCs = [
+54.7	74.2	79.9	80.4	93.4	85.4	 
+46.7	66	69.3	83.6	96.7	96.1	 
+49.7	55.1	42.4	82.6	97.3	82.5	 
+52.8	52.4	42.4	79.2	92.4	46.1	 
+54.8	48.2	43.7	79	97.7	56.4	 
+47.9	64.8	63.7	92.9	NaN	69.8	 
+68.6	87.1	87	98	NaN	107	 
+];
+x.IFMCs = x.IFMCs';
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/profiles/MTprofile12_26hr05_Oct_2011.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,31 @@
+function x = MTprofile12_26hr05_Oct_2011
+%created: 12_26hr05_Oct_2011
+
+x.BFs = [250   500  1000  2000  4000  8000];
+
+x.LongTone = [10.5      7.64      6.56      10.1      13.2      18.6];
+x.ShortTone = [15.4      14.1      12.5        16      21.7      27.4];
+
+x.Gaps = [0.01      0.03      0.05      0.07      0.09];
+x.TMCFreq = [250   500  1000  2000  4000  8000];
+x.TMC = [
+39.6	46.7	37.8	47.4	51	67.9	 
+47.7	49.6	47.2	44.2	63	83.5	 
+54	53.8	59.9	53.4	74.5	89.8	 
+61.2	63.7	58.8	58.2	80	97.5	 
+65.2	67.3	69.3	72.2	91.3	95.9	 
+];
+x.TMC = x.TMC';
+
+x.MaskerRatio = [0.5      0.7      0.9        1      1.1      1.3      1.6];
+x.IFMCFreq = [250   500  1000  2000  4000  8000];
+x.IFMCs = [
+47.8	70.6	76.5	77.2	78.5	94.9	 
+42.3	59.2	63.2	74.8	84.1	97.2	 
+36.9	47.3	43.8	45.5	65	85.5	 
+38.7	44.6	40.5	53	49.8	71.2	 
+39	38.5	39.6	27.3	41.3	68.5	 
+41.6	47.9	56.7	55.8	93.4	NaN	 
+54.8	84.6	87	92.2	103	NaN	 
+];
+x.IFMCs = x.IFMCs';
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/profiles/MTprofile12_41hr04_Oct_2011.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,31 @@
+function x = MTprofile12_41hr04_Oct_2011
+%created: 12_41hr04_Oct_2011
+
+x.BFs = [250   500  1000  2000  4000  8000];
+
+x.LongTone = [40.1      42.7      53.1      81.2      92.3      82.3];
+x.ShortTone = [49.6      48.3      64.4        89      95.5      92.3];
+
+x.Gaps = [0.01      0.03      0.05      0.07      0.09];
+x.TMCFreq = [250   500  1000  2000  4000  8000];
+x.TMC = [
+60.6	58.5	77.7	NaN	NaN	NaN	 
+62.8	56	85.2	NaN	NaN	NaN	 
+60.8	60.2	81.6	NaN	NaN	NaN	 
+75.2	67.5	85.4	NaN	NaN	NaN	 
+83.9	77.4	93.2	NaN	NaN	NaN	 
+];
+x.TMC = x.TMC';
+
+x.MaskerRatio = [0.5      0.7      0.9        1      1.1      1.3      1.6];
+x.IFMCFreq = [250   500  1000  2000  4000  8000];
+x.IFMCs = [
+60.9	81.2	89.1	105	NaN	NaN	 
+57.6	69	85.4	105	NaN	NaN	 
+52.4	56.4	77.2	106	NaN	NaN	 
+52.8	57.7	78.3	105	NaN	NaN	 
+51.8	57.2	78.6	NaN	NaN	NaN	 
+57.2	62.1	89.3	NaN	NaN	NaN	 
+66.8	93.5	103	NaN	NaN	NaN	 
+];
+x.IFMCs = x.IFMCs';
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/profiles/MTprofile13_25hr04_Oct_2011.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,31 @@
+function x = MTprofile13_25hr04_Oct_2011
+%created: 13_25hr04_Oct_2011
+
+x.BFs = [250   500  1000  2000  4000  8000];
+
+x.LongTone = [33.8      32.5      44.1      68.4      84.1        69];
+x.ShortTone = [41.7      40.6      51.1      79.1      90.3      79.7];
+
+x.Gaps = [0.01      0.03      0.05      0.07      0.09];
+x.TMCFreq = [250   500  1000  2000  4000  8000];
+x.TMC = [
+48	48.4	66.2	91.1	NaN	82.4	 
+55.1	53.6	60.7	92	NaN	91.5	 
+57.3	55	71.1	95.7	NaN	89.7	 
+64.4	65.8	64.6	98.8	NaN	82.3	 
+59.8	70.9	80.1	96	NaN	90.3	 
+];
+x.TMC = x.TMC';
+
+x.MaskerRatio = [0.5      0.7      0.9        1      1.1      1.3      1.6];
+x.IFMCFreq = [250   500  1000  2000  4000  8000];
+x.IFMCs = [
+56.3	76.4	86.4	91.5	104	102	 
+52.2	64.1	74.6	95.1	NaN	NaN	 
+48.8	52.8	59.2	92.9	NaN	98	 
+49.4	52	58.3	92.5	NaN	79	 
+49.7	47.7	61.2	95.5	NaN	87.8	 
+50.7	56.8	74.9	NaN	NaN	94.9	 
+56.4	91.5	99.3	NaN	NaN	NaN	 
+];
+x.IFMCs = x.IFMCs';
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/profiles/MTprofile14_39hr04_Oct_2011.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,31 @@
+function x = MTprofile14_39hr04_Oct_2011
+%created: 14_39hr04_Oct_2011
+
+x.BFs = [250   500  1000  2000  4000  8000];
+
+x.LongTone = [27.1      24.1      32.5      52.6      63.4      51.3];
+x.ShortTone = [33.6      33.9      43.7      67.7      80.9      62.8];
+
+x.Gaps = [0.01      0.03      0.05      0.07      0.09];
+x.TMCFreq = [250   500  1000  2000  4000  8000];
+x.TMC = [
+42	40.4	59.7	73.9	88.2	51.5	 
+44.1	47.7	57.7	77.6	93.8	40.2	 
+47.2	49.3	68	85.9	97.6	44.6	 
+55.2	54.9	72.4	86.1	96.6	55.8	 
+66.4	64	83.3	87.1	101	58	 
+];
+x.TMC = x.TMC';
+
+x.MaskerRatio = [0.5      0.7      0.9        1      1.1      1.3      1.6];
+x.IFMCFreq = [250   500  1000  2000  4000  8000];
+x.IFMCs = [
+44.5	73.9	86.4	84.9	94.8	81.2	 
+43.2	58.5	77	86.7	98.3	102	 
+43.9	50.9	61.4	72	99.3	51.3	 
+39.9	46.8	57.6	56	92.4	50.7	 
+40.3	44	62	78.2	88.7	40.3	 
+36.9	51.8	78.3	99.2	NaN	73.2	 
+51.2	89.5	98.1	NaN	NaN	NaN	 
+];
+x.IFMCs = x.IFMCs';
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/profiles/MTprofile14_59hr10_Nov_2011.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,31 @@
+function x = MTprofile14_59hr10_Nov_2011
+%created: 14_59hr10_Nov_2011
+
+x.BFs = [250   500  1000  2000  4000  8000];
+
+x.LongTone = [16.6        14      12.6      15.5      20.3      27.6];
+x.ShortTone = [17.9      16.5      15.4      18.5      26.3      32.9];
+
+x.Gaps = [0.01      0.03      0.05      0.07      0.09];
+x.TMCFreq = [250   500  1000  2000  4000  8000];
+x.TMC = [
+28.7	30.7	34.8	46	40.9	52.4	 
+36.3	45.1	49.3	54.1	55	49.5	 
+73.5	82.5	80.2	59.8	54.7	68.4	 
+94.1	88.7	85.5	78.1	71.5	76.8	 
+97.9	91.6	89.2	78.5	75.2	91.1	 
+];
+x.TMC = x.TMC';
+
+x.MaskerRatio = [0.5      0.7      0.9        1      1.1      1.3      1.6];
+x.IFMCFreq = [250   500  1000  2000  4000  8000];
+x.IFMCs = [
+32.7	57.1	72.5	71.7	72	83.3	 
+30.7	39.3	50.9	69.7	81.3	89.2	 
+28.8	32.2	35.2	42.3	57.6	53	 
+28.4	30.6	32.2	38.7	39.2	46.7	 
+28.2	30.2	38.4	40.9	44.5	49.8	 
+28.3	34.2	55.6	79.7	71.3	88.7	 
+30.3	55.6	86.3	91.5	97.1	103	 
+];
+x.IFMCs = x.IFMCs';
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/profiles/MTprofile14_9hr20_Sep_2011.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,31 @@
+function x = MTprofile14_9hr20_Sep_2011
+%created: 14_9hr20_Sep_2011
+
+x.BFs = [250   500  1000  2000  4000  8000];
+
+x.LongTone = [10.7      6.17      2.35      2.12      4.94      10.6];
+x.ShortTone = [15.2      11.4       7.7      8.55      12.3      17.7];
+
+x.Gaps = [0.01      0.03      0.05      0.07      0.09];
+x.TMCFreq = [250   500  1000  2000  4000  8000];
+x.TMC = [
+27.9	23.1	19	28.7	25.7	26.5	 
+36.7	30.3	26.8	34.1	33.3	34.8	 
+44.8	41.1	47.5	61.2	38.3	38.1	 
+54.8	59.5	66.4	65.4	51	51.4	 
+79.2	80.3	75.1	80.5	63	41.3	 
+];
+x.TMC = x.TMC';
+
+x.MaskerRatio = [0.5      0.7      0.9        1      1.1      1.3      1.6];
+x.IFMCFreq = [250   500  1000  2000  4000  8000];
+x.IFMCs = [
+34.3	57.9	67.5	67.7	65.3	72.2	 
+31.7	41.5	47.6	66.9	72.1	79.7	 
+29.2	27.3	22.1	24.9	27.6	30.3	 
+27.8	22.3	19.4	24.3	24.5	28.7	 
+27.8	22.6	18.4	23.3	25.2	30.9	 
+28.8	23.7	24.7	43.5	36.1	45.8	 
+32.7	39.1	76.1	82.8	88.1	94.8	 
+];
+x.IFMCs = x.IFMCs';
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/profiles/MTprofile15_22hr04_Oct_2011.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,31 @@
+function x = MTprofile15_22hr04_Oct_2011
+%created: 15_22hr04_Oct_2011
+
+x.BFs = [250   500  1000  2000  4000  8000];
+
+x.LongTone = [11.1      7.48      8.71      8.55      14.3      18.4];
+x.ShortTone = [16.1      13.6      14.2      15.1        21      27.3];
+
+x.Gaps = [0.01      0.03      0.05      0.07      0.09];
+x.TMCFreq = [250   500  1000  2000  4000  8000];
+x.TMC = [
+26.7	30.8	33.1	28.5	37.3	50.4	 
+35.1	33.5	41.6	34.8	44.2	57.1	 
+44.6	41.8	49.8	39.5	75.1	80.9	 
+53.8	57.8	61	37.2	71	89.3	 
+64.7	62.9	63.4	52.2	81.5	97.9	 
+];
+x.TMC = x.TMC';
+
+x.MaskerRatio = [0.5      0.7      0.9        1      1.1      1.3      1.6];
+x.IFMCFreq = [250   500  1000  2000  4000  8000];
+x.IFMCs = [
+34.9	62.4	79.4	80.7	83.6	94.1	 
+32.8	42	61.6	78.3	87.9	99.3	 
+29.2	28	34.4	27.3	46.9	58.5	 
+29.5	28.1	31	36	41	42.8	 
+29.6	28.1	37.1	23.2	32.3	50.2	 
+32.4	35.1	46.5	52.2	59.4	88.7	 
+37.7	52.5	92.7	97	107	NaN	 
+];
+x.IFMCs = x.IFMCs';
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/profiles/MTprofile16_0hr04_Oct_2011.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,31 @@
+function x = MTprofile16_0hr04_Oct_2011
+%created: 16_0hr04_Oct_2011
+
+x.BFs = [250   500  1000  2000  4000  8000];
+
+x.LongTone = [70        68      66.5      70.6      75.7      81.9];
+x.ShortTone = [78.6      73.9      72.5      75.7        82      88.8];
+
+x.Gaps = [0.01      0.03      0.05      0.07      0.09];
+x.TMCFreq = [250   500  1000  2000  4000  8000];
+x.TMC = [
+92.4	89.6	91.5	94.6	101	NaN	 
+95.1	90.6	92.8	99.3	NaN	NaN	 
+95.2	90.7	94.2	99.5	NaN	NaN	 
+95	91.4	94.6	102	NaN	NaN	 
+96.7	91.9	97.2	NaN	NaN	NaN	 
+];
+x.TMC = x.TMC';
+
+x.MaskerRatio = [0.5      0.7      0.9        1      1.1      1.3      1.6];
+x.IFMCFreq = [250   500  1000  2000  4000  8000];
+x.IFMCs = [
+99.7	95.7	91.8	91.5	94.5	103	 
+97.4	93.3	90	93.1	97.9	104	 
+94.4	90	89.9	96.5	99.8	NaN	 
+93	89.4	90.7	97.2	103	NaN	 
+92.1	88.6	92.3	98	102	NaN	 
+90.1	89.5	96.1	103	NaN	NaN	 
+89	92.6	103	NaN	NaN	NaN	 
+];
+x.IFMCs = x.IFMCs';
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/profiles/MTprofile16_31hr04_Oct_2011.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,31 @@
+function x = MTprofile16_31hr04_Oct_2011
+%created: 16_31hr04_Oct_2011
+
+x.BFs = [250   500  1000  2000  4000  8000];
+
+x.LongTone = [65.9      64.4      61.8        65      67.5        69];
+x.ShortTone = [71.9      68.3      65.8      69.7      75.3      81.6];
+
+x.Gaps = [0.01      0.03      0.05      0.07      0.09];
+x.TMCFreq = [250   500  1000  2000  4000  8000];
+x.TMC = [
+86	84.2	84.7	91	95.8	99.8	 
+88.1	84.1	85.6	92.4	97.4	103	 
+88.7	86.6	87.4	95.1	98.7	103	 
+89.1	87.2	88.1	95.4	101	NaN	 
+90.5	88	89.6	96.8	103	NaN	 
+];
+x.TMC = x.TMC';
+
+x.MaskerRatio = [0.5      0.7      0.9        1      1.1      1.3      1.6];
+x.IFMCFreq = [250   500  1000  2000  4000  8000];
+x.IFMCs = [
+94.4	91.1	86	83.8	86.1	95.9	 
+90.8	87.7	82.7	87.7	90.8	95.9	 
+87.3	84.6	83	89.1	92	97.9	 
+86.4	84	84.5	90.4	94.3	99.6	 
+85.4	82.7	85.3	92	96	102	 
+83.2	83.1	89.5	96.8	100	NaN	 
+83.2	86.9	95.4	103	NaN	103	 
+];
+x.IFMCs = x.IFMCs';
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/profiles/MTprofile16_43hr14_Nov_2011.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,31 @@
+function x = MTprofile16_43hr14_Nov_2011
+%created: 16_43hr14_Nov_2011
+
+x.BFs = [250   500  1000  2000  4000  8000];
+
+x.LongTone = [64.1      57.3      57.3      60.1      66.1      74.9];
+x.ShortTone = [66.6      60.3      60.2      62.6      68.7      78.1];
+
+x.Gaps = [0.01      0.03      0.05      0.07      0.09];
+x.TMCFreq = [250   500  1000  2000  4000  8000];
+x.TMC = [
+92.8	84.9	83.6	83.9	85.4	94.1	 
+100	93.4	93.2	88.2	87.6	96.8	 
+NaN	96.3	96.1	91.8	89.8	98.7	 
+NaN	97.9	102	97.1	95.4	101	 
+NaN	101	NaN	NaN	97.5	NaN	 
+];
+x.TMC = x.TMC';
+
+x.MaskerRatio = [0.5      0.7      0.9        1      1.1      1.3      1.6];
+x.IFMCFreq = [250   500  1000  2000  4000  8000];
+x.IFMCs = [
+98	89.5	83.2	76.7	78.1	87.8	 
+96.1	86.3	83.1	80.2	81.6	89.3	 
+94.4	85.1	82.8	82.8	84.9	91.3	 
+92.1	83.9	83.2	82.4	85.9	94.4	 
+90.7	85.6	84.7	84.9	86	94.7	 
+90.5	86.6	88.7	88.3	91	101	 
+90.1	91.3	94.3	95.6	95.9	106	 
+];
+x.IFMCs = x.IFMCs';
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/profiles/MTprofile19_7hr09_Oct_2011.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,31 @@
+function x = MTprofile19_7hr09_Oct_2011
+%created: 19_7hr09_Oct_2011
+
+x.BFs = [250   500  1000  2000  4000  8000];
+
+x.LongTone = [4.55    -0.275     -0.15      2.09      5.95      9.32];
+x.ShortTone = [7.73      5.16      3.75      6.61      13.1      17.1];
+
+x.Gaps = [0.01      0.03      0.05      0.07      0.09];
+x.TMCFreq = [250   500  1000  2000  4000  8000];
+x.TMC = [
+18	16.2	16.3	25.8	36.3	32.3	 
+20.9	20.2	17.6	45.2	42.5	32.3	 
+22.8	24	29.6	44.6	39.6	34.7	 
+33.8	35.2	24.5	58	55.3	33.3	 
+54.1	47.6	47.9	66.9	68.1	37.1	 
+];
+x.TMC = x.TMC';
+
+x.MaskerRatio = [0.5      0.7      0.9        1      1.1      1.3      1.6];
+x.IFMCFreq = [250   500  1000  2000  4000  8000];
+x.IFMCs = [
+23.3	39.5	60.5	72.1	74.4	80.8	 
+21	24.9	33.6	69	80.3	85.8	 
+19.1	18.1	18.4	31.7	44.9	36.1	 
+19.2	16.4	15.4	24	32.9	29.5	 
+17.9	16.8	15.4	36	28.9	31.1	 
+18.7	17.1	28.9	46.9	50.3	45.9	 
+21.4	29.1	84.2	91.8	97	80.8	 
+];
+x.IFMCs = x.IFMCs';
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/profiles/MTprofile20_5hr09_Oct_2011.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,31 @@
+function x = MTprofile20_5hr09_Oct_2011
+%created: 20_5hr09_Oct_2011
+
+x.BFs = [250   500  1000  2000  4000  8000];
+
+x.LongTone = [1.84    -0.775     -3.26     -1.62      5.65      10.4];
+x.ShortTone = [7.18      5.31      3.18       6.1      13.2      18.4];
+
+x.Gaps = [0.01      0.03      0.05      0.07      0.09];
+x.TMCFreq = [250   500  1000  2000  4000  8000];
+x.TMC = [
+17.2	16.5	14	21	25.8	30.2	 
+17.8	16.4	15	27.9	33.8	31.8	 
+18.9	18.7	15.4	31.8	36.6	35.7	 
+21.1	19.2	19	42.3	58.1	34.4	 
+21.5	21.9	22.6	57.3	61.3	45.6	 
+];
+x.TMC = x.TMC';
+
+x.MaskerRatio = [0.5      0.7      0.9        1      1.1      1.3      1.6];
+x.IFMCFreq = [250   500  1000  2000  4000  8000];
+x.IFMCs = [
+21	34.6	57.7	70.4	73.1	81.7	 
+18.8	22.7	26.9	51	78.6	87.6	 
+17.8	17.7	15.7	19.5	35.1	33.1	 
+17.2	14.7	13.6	26.7	27.2	31.1	 
+16.7	14.9	13.1	22	30.7	32.9	 
+16.6	15.7	20.5	41.3	60	50.2	 
+19.4	24.2	82.7	89	97.6	103	 
+];
+x.IFMCs = x.IFMCs';
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/profiles/MTprofile23_35hr09_Oct_2011.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,31 @@
+function x = MTprofile23_35hr09_Oct_2011
+%created: 23_35hr09_Oct_2011
+
+x.BFs = [250   500  1000  2000  4000  8000];
+
+x.LongTone = [4.82    -0.118     -1.64     0.904      6.77      12.7];
+x.ShortTone = [7.33      5.53      4.97      7.39      11.8      18.9];
+
+x.Gaps = [0.01      0.03      0.05      0.07      0.09];
+x.TMCFreq = [250   500  1000  2000  4000  8000];
+x.TMC = [
+23.5	26.3	46.9	58.2	32.4	40.6	 
+35.6	56.1	69.3	67.7	49.3	47	 
+70.6	68.1	77.9	67.6	54.4	58.9	 
+77.3	78.5	81.6	79.9	65.9	64.6	 
+84.5	80.5	82.7	86.5	62.4	72.7	 
+];
+x.TMC = x.TMC';
+
+x.MaskerRatio = [0.5      0.7      0.9        1      1.1      1.3      1.6];
+x.IFMCFreq = [250   500  1000  2000  4000  8000];
+x.IFMCs = [
+28.5	64.5	78.3	75.4	75.4	86.9	 
+26.1	42.3	64.9	76.9	81.3	90.9	 
+22.3	31	50.4	60.2	47.5	53.9	 
+24	28.2	52	59.8	45.9	37.2	 
+23.1	32.1	51.2	56.6	45.7	42.5	 
+23.9	34.1	75.1	85.1	57.1	66	 
+32.3	79.1	91.2	95.8	96.7	105	 
+];
+x.IFMCs = x.IFMCs';
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/profiles/MTprofile9_34hr18_Nov_2011.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,31 @@
+function x = MTprofile9_34hr18_Nov_2011
+%created: 9_34hr18_Nov_2011
+
+x.BFs = [250   500  1000  2000  4000  8000];
+
+x.LongTone = [23.4        22      22.6      52.7      66.9      55.7];
+x.ShortTone = [25.5      23.5      27.6      64.8      72.3      65.7];
+
+x.Gaps = [0.01      0.03      0.05      0.07      0.09];
+x.TMCFreq = [250   500  1000  2000  4000  8000];
+x.TMC = [
+40.2	47	31.2	76.5	82.6	72.6	 
+51.3	57.9	39.4	78	86.9	79.3	 
+69.4	70.4	40.8	81.1	88.6	83.8	 
+81.4	79	45.4	85.1	91.4	86.7	 
+93.9	90.7	59.8	85.1	95.3	84.5	 
+];
+x.TMC = x.TMC';
+
+x.MaskerRatio = [0.5      0.7      0.9        1      1.1      1.3      1.6];
+x.IFMCFreq = [250   500  1000  2000  4000  8000];
+x.IFMCs = [
+49.7	68.2	66.7	77.6	87.9	90.1	 
+47.1	56.2	51	82.5	90.5	94.2	 
+41.4	46.5	28.9	75.9	89.1	85.4	 
+39	45.2	27.4	75.5	84.3	73.2	 
+40.8	47.6	35.4	82.2	87.6	69.6	 
+41.4	80.6	77.9	93.1	99.9	102	 
+48	85.7	87.7	98.5	NaN	NaN	 
+];
+x.IFMCs = x.IFMCs';
--- a/testPrograms/LiebermanMOCdata.m	Thu Oct 06 15:43:20 2011 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,79 +0,0 @@
-function LibermanData= LiebermanMOCdata
-
-LibermanData=[
-    2	0.2;
-2.1	0.19;
-2.2	0.18;
-2.3	0.18;
-2.4	0.16;
-2.5	0.15;
-2.6	0.15;
-2.7	0.15;
-2.8	0.12;
-2.9	0.12;
-3	0.1;
-3.1	0.1;
-3.2	0.05;
-3.3	0.05;
-3.4	0;
-3.5	-0.1;
-3.6	-0.4;
-3.7	-1.2;
-3.8	-1.6;
-3.9	-1.8;
-4	-1.85;
-4.1	-2;
-4.2	-2.05;
-4.3	-2.05;
-4.4	-2.15;
-4.5	-2.2;
-4.6	-2.15;
-4.7	-2.1;
-4.8	-2.15;
-4.9	-2.2;
-5	-2.1;
-5.1	-2.1;
-5.2	-2.25;
-5.3	-2.1;
-5.4	-2.15;
-5.5	-2.1;
-5.6	-2.15;
-5.7	-2.1;
-5.8	-2.2;
-5.9	-2.05;
-6	-2.15;
-6.1	-2.05;
-6.2	-2;
-6.3	-2.2;
-6.4	-2.1;
-6.5	-2.05;
-6.6	-2.05;
-6.7	-2.05;
-6.8	-2.2;
-6.9	-2.1;
-7	-2.05;
-7.1	-2.05;
-7.2	-0.7;
-7.3	-0.1;
-7.4	0;
-7.5	0.1;
-7.6	0.2;
-7.7	0.35;
-7.8	0.2;
-7.9	0.15;
-8	0.2;
-8.1	0.15;
-8.2	0.15;
-8.3	0.15;
-8.4	0.12;
-8.5	0.1;
-8.6	0.09;
-8.7	0.08;
-8.8	0.07;
-8.9	0.06;
-9	0.05;
-];
-figure(98), subplot(2,1,2), hold on
-scalar=-15;
-plot(LibermanData(:,1)-2.5,scalar*LibermanData(:,2))
-
--- a/testPrograms/LiebermanMOCtest.m	Thu Oct 06 15:43:20 2011 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,155 +0,0 @@
-function LiebermanMOCtest
-
-% In test_MAP1_14.m set these parameters
-
-% AN_spikesOrProbability='spikes';
-
-% global dt ANdt  savedBFlist saveAN_spikesOrProbability saveMAPparamsName...
-%     savedInputSignal OMEextEarPressure TMoutput OMEoutput ARattenuation ...
-%     DRNLoutput IHC_cilia_output IHCrestingCiliaCond IHCrestingV...
-%     IHCoutput ANprobRateOutput ANoutput savePavailable ANtauCas  ...
-%     CNtauGk CNoutput  ICoutput ICmembraneOutput ICfiberTypeRates ...
-%     MOCattenuation
-global dt ANdt   saveAN_spikesOrProbability ANprobRateOutput ICoutput    
-
-global DRNLParams
-
-LibermanData=[
-    2	0.2;
-2.1	0.19;2.2	0.18;2.3	0.18;2.4	0.16;2.5	0.15;2.6	0.15;2.7 0.15;
-2.8	0.12;2.9	0.12;3	0.1;3.1	0.1;3.2	0.05;3.3	0.05;3.4	0;3.5	-0.1;
-3.6	-0.4;3.7	-1.2;3.8	-1.6;3.9	-1.8;4	-1.85;4.1	-2;4.2	-2.05;
-4.3	-2.05;4.4	-2.15;4.5	-2.2;4.6	-2.15;4.7	-2.1;4.8	-2.15;4.9 -2.2;
-5	-2.1;5.1	-2.1;5.2	-2.25;5.3	-2.1;5.4	-2.15;5.5	-2.1;5.6 -2.15;
-5.7	-2.1;5.8	-2.2;5.9	-2.05;6	-2.15;6.1	-2.05;6.2 -2;6.3 -2.2;6.4 -2.1;
-6.5	-2.05;6.6	-2.05;6.7	-2.05;6.8 -2.2;6.9 -2.1;7	-2.05;7.1 -2.05;7.2	-0.7;
-7.3	-0.1;7.4	0;7.5	0.1;7.6	0.2;7.7	0.35;7.8	0.2;7.9	0.15;8	0.2;8.1	0.15;8.2	0.15;
-8.3	0.15;8.4	0.12;8.5	0.1;8.6	0.09;8.7	0.08;8.8	0.07;8.9	0.06;9	0.05;
-];
-
-restorePath=path;
-addpath (['..' filesep 'MAP'],    ['..' filesep 'wavFileStore'], ...
-    ['..' filesep 'utilities'])
-
-%%  #1 parameter file name
-MAPparamsName='Normal';
-
-
-%% #2 probability (fast) or spikes (slow) representation
-AN_spikesOrProbability='spikes';
-%   or
-% AN_spikesOrProbability='probability';
-
-
-%% #3 pure tone, harmonic sequence or speech file input
-signalType= 'tones';
-sampleRate= 50000;
-rampDuration=.005;              % raised cosine ramp (seconds)
-toneFrequency= 1000;            % or a pure tone (Hz)
-duration=3.6;                   % Lieberman test
-beginSilence=1;                 % 1 for Lieberman
-endSilence=1;                   % 1 for Lieberman
-
-%% #4 rms level
-% signal details
-leveldBSPL= 80;                  % dB SPL (80 for Lieberman)
-
-
-%% #5 number of channels in the model
-
-numChannels=1;
-BFlist=toneFrequency;
-
-
-%% #6 change model parameters
-paramChanges={};
-
-%% delare 'showMap' options to control graphical output
-showMapOptions.printModelParameters=1;   % prints all parameters
-showMapOptions.showModelOutput=1;       % plot of all stages
-showMapOptions.printFiringRates=1;      % prints stage activity levels
-showMapOptions.showACF=0;               % shows SACF (probability only)
-showMapOptions.showEfferent=1;          % tracks of AR and MOC
-showMapOptions.surfProbability=1;       % 2D plot of HSR response 
-showMapOptions.surfSpikes=0;            % 2D plot of spikes histogram
-showMapOptions.ICrates=0;               % IC rates by CNtauGk
-
-%% Generate stimuli
-
-        % Create pure tone stimulus
-        dt=1/sampleRate; % seconds
-        time=dt: dt: duration;
-        inputSignal=sum(sin(2*pi*toneFrequency'*time), 1);
-        amp=10^(leveldBSPL/20)*28e-6;   % converts to Pascals (peak)
-        inputSignal=amp*inputSignal;
-        % apply ramps
-        % catch rampTime error
-        if rampDuration>0.5*duration, rampDuration=duration/2; end
-        rampTime=dt:dt:rampDuration;
-        ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ...
-            ones(1,length(time)-length(rampTime))];
-        inputSignal=inputSignal.*ramp;
-        ramp=fliplr(ramp);
-        inputSignal=inputSignal.*ramp;
-        % add silence
-        intialSilence= zeros(1,round(beginSilence/dt));
-        finalSilence= zeros(1,round(endSilence/dt));
-        inputSignal= [intialSilence inputSignal finalSilence];
-
-%% run the model
-tic
-fprintf('\n')
-disp(['Signal duration= ' num2str(length(inputSignal)/sampleRate)])
-disp([num2str(numChannels) ' channel model: ' AN_spikesOrProbability])
-disp('Computing ...')
-
-MAP1_14(inputSignal, sampleRate, BFlist, ...
-    MAPparamsName, AN_spikesOrProbability, paramChanges);
-
-
-%% the model run is now complete. Now display the results
-UTIL_showMAP(showMapOptions, paramChanges)
-
-if strcmp(signalType,'tones')
-    disp(['duration=' num2str(duration)])
-    disp(['level=' num2str(leveldBSPL)])
-    disp(['toneFrequency=' num2str(toneFrequency)])
-    disp(['attenuation factor =' ...
-        num2str(DRNLParams.rateToAttenuationFactor, '%5.3f') ])
-    disp(['attenuation factor (probability)=' ...
-        num2str(DRNLParams.rateToAttenuationFactorProb, '%5.3f') ])
-    disp(AN_spikesOrProbability)
-end
-disp(paramChanges)
-
-
-
-%% superimpose Lieberman data
-
-global DRNLParams
-% scale up DPOAE results to a maximum of whatever MAP_14 uses as its
-% maximum
-scalar=-DRNLParams.minMOCattenuationdB/min(LibermanData(:,2));
-
-figure(98), subplot(2,1,2), hold on
-plot(LibermanData(:,1)-2.5,scalar*LibermanData(:,2),'r:')
-
-PSTHbinwidth=0.001;
-
-if strcmp(saveAN_spikesOrProbability,'probability')
-    PSTH=UTIL_PSTHmaker...
-        (ANprobRateOutput(2,:), ANdt, PSTHbinwidth)*ANdt/PSTHbinwidth;
-else
-    PSTH=UTIL_PSTHmaker(ICoutput(2,:), dt, PSTHbinwidth)*dt/PSTHbinwidth;
-end
-
-time=PSTHbinwidth:PSTHbinwidth:PSTHbinwidth*length(PSTH);
-figure(89)
-plot(time, PSTH)
-set(gcf,'name', 'Lieberman')
-title(saveAN_spikesOrProbability)
-
-toc
-path(restorePath)
-
-% figure(88), plot(MOCattenuation)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/testPrograms/MAPtwoToneDemo.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,152 @@
+% function MAPtwoToneDemo
+%
+% Demonstration of two-tone suppression in the AN using a
+%   F1 tone suppressed by a 1.5*F1 kHz tone
+%
+
+global  ANprobRateOutput DRNLoutput
+dbstop if error
+restorePath=path;
+addpath (['..' filesep 'MAP'],    ['..' filesep 'wavFileStore'], ...
+    ['..' filesep 'utilities'])
+figure(5), clf
+
+disp('')
+primaryToneFrequency=2000;
+
+probedBs=[-100 20 :20: 90];
+nProbeLevels=length(probedBs);
+
+% disp(['F1 F1 level= ' num2str([primaryToneFrequency probedB])])
+
+suppressorLevels=0:10:80;
+suppressorLevels=0:10:80;
+
+lowestBF=250; 	highestBF= 8000; 	numChannels=21;
+BFlist=round(logspace(log10(lowestBF), log10(highestBF), numChannels));
+
+suppressorFrequencies=BFlist;
+BFchannel=find(BFlist==primaryToneFrequency);
+
+sampleRate= 40000; % Hz (higher sample rate needed for BF>8000 Hz)
+dt=1/sampleRate; % seconds
+
+duration=.050;		      % seconds
+tone2Duration=duration/2; % s
+startSilenceDuration=0.010;
+startSilence=...
+    zeros(1,startSilenceDuration*sampleRate);
+suppressorStartsPTR=...
+    round((startSilenceDuration+duration/2)*sampleRate);
+
+probedBCount=0;
+for probedB=probedBs
+    probedBCount=probedBCount+1;
+    
+    peakResponse= zeros(length(suppressorLevels),length(suppressorFrequencies));
+    suppFreqCount=0;
+    for suppressorFrequency=suppressorFrequencies
+        suppFreqCount=suppFreqCount+1;
+        
+        suppressorLevelCount=0;
+        for suppressorDB=suppressorLevels
+            suppressorLevelCount=suppressorLevelCount+1;
+            
+            % primary + suppressor
+            primaryLevelDB=probedB;
+            suppressorLevelDB=suppressorDB;
+            
+            
+            % primary BF tone
+            time1=dt: dt: duration;
+            amp=10^(primaryLevelDB/20)*28e-6;
+            inputSignal=amp*sin(2*pi*primaryToneFrequency*time1);
+            rampDuration=.005; rampTime=dt:dt:rampDuration;
+            ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ones(1,length(time1)-length(rampTime))];
+            inputSignal=inputSignal.*ramp;
+            inputSignal=inputSignal.*fliplr(ramp);
+            
+            % suppressor
+            time2= dt: dt: tone2Duration;
+            % B: tone on
+            amp=10^(suppressorLevelDB/20)*28e-6;
+            inputSignal2=amp*sin(2*pi*suppressorFrequency*time2);
+            rampDuration=.005; rampTime=dt:dt:rampDuration;
+            ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ones(1,length(time2)-length(rampTime))];
+            inputSignal2=inputSignal2.*ramp;
+            inputSignal2=inputSignal2.*fliplr(ramp);
+            % A: initial silence (delay to suppressor)
+            silence=zeros(1,length(time2));
+            inputSignal2=[silence inputSignal2];
+            
+            % add tone and suppressor components
+            inputSignal=inputSignal+inputSignal2;
+            
+            inputSignal=...
+                [startSilence inputSignal ];
+            
+            % run MAP
+            MAPparamsName='Normal';
+            AN_spikesOrProbability='probability';
+            paramChanges={'IHCpreSynapseParams.tauCa=80e-6;'};
+            MAP1_14(inputSignal, sampleRate, BFlist, ...
+                MAPparamsName, AN_spikesOrProbability, paramChanges);
+            
+            response=ANprobRateOutput;
+            peakResponse(suppressorLevelCount,suppFreqCount)=...
+                mean(response(BFchannel,suppressorStartsPTR:end));
+            disp(['F2 level= ', num2str([suppressorFrequency suppressorDB ...
+                peakResponse(suppressorLevelCount,suppFreqCount)])])
+            
+            
+            %% make movie
+            figure(6), subplot(4,1,2)
+            axis tight
+            set(gca,'nextplot','replacechildren');
+            plot(dt:dt:dt*length(inputSignal), inputSignal, 'k')
+            title('probe                 -                        suppressor')
+            ylim([-.5 .5])
+            
+            figure(6), subplot(2,1,2)
+            PSTHbinWidth=0.010;
+            PSTH= UTIL_PSTHmakerb(...
+                response, dt, PSTHbinWidth);
+            [nY nX]=size(PSTH);
+            time=PSTHbinWidth*(0:nX-1);
+            surf(time, BFlist, PSTH)
+            zlim([0 500]),
+            caxis([0 500])
+            shading interp
+            colormap(jet)
+            set(gca, 'yScale','log')
+            xlim([0 max(time)+dt])
+            ylim([0 max(BFlist)])
+            view([0 90]) % view([-8 68])
+            title('probe                 -                        suppressor')
+            pause(0.05)
+        end
+    end
+    
+    %% plot matrix
+    
+    peakResponse=peakResponse/peakResponse(1,1);
+    
+    figure(5), subplot(2,nProbeLevels, probedBCount)
+    surf(suppressorFrequencies,suppressorLevels,peakResponse)
+    shading interp
+    view([0 90])
+    set(gca,'Xscale','log')
+    xlim([min(suppressorFrequencies) max(suppressorFrequencies)])
+    set(gca,'Xtick', [1000  4000],'xticklabel',{'1000', '4000'})
+    ylim([min(suppressorLevels) max(suppressorLevels)])
+    
+    subplot(2,nProbeLevels,nProbeLevels+probedBCount)
+    contour(suppressorFrequencies,suppressorLevels,peakResponse, ...
+        [.1:.1:.9 1.1] )
+    set(gca,'Xscale','log')
+    set(gca,'Xtick', [1000  4000],'xticklabel',{'1000', '4000'})
+    set(gcf, 'name',['primaryToneFrequency= ' num2str(primaryToneFrequency)])
+    title([num2str(probedB) ' dB'])
+end
+
+path=restorePath;
--- a/testPrograms/demoTwisterProbability.m	Thu Oct 06 15:43:20 2011 +0100
+++ b/testPrograms/demoTwisterProbability.m	Mon Nov 28 13:34:28 2011 +0000
@@ -63,9 +63,12 @@
 showMapOptions.printFiringRates=1;
 showMapOptions.showACF=0;
 showMapOptions.showEfferent=0;
-showMapOptions.surfProbability=1;       % 2D plot of HSR response 
+showMapOptions.surfAN=1;       % 3D plot of HSR response 
+showMapOptions.PSTHbinwidth=0.002;      % 3D plot of HSR response 
+showMapOptions.view=[-14 76];           % 3D plot of HSR response
 
-UTIL_showMAP(showMapOptions, paramChanges)
+
+UTIL_showMAP(showMapOptions)
 
 toc
 path(restorePath)
--- a/testPrograms/demoTwisterSpikes.m	Thu Oct 06 15:43:20 2011 +0100
+++ b/testPrograms/demoTwisterSpikes.m	Mon Nov 28 13:34:28 2011 +0000
@@ -27,13 +27,13 @@
 
 %% #5 number of channels in the model
 %   21-channel model (log spacing)
-numChannels=21;
+numChannels=11;
 lowestBF=250; 	highestBF= 8000;
 BFlist=round(logspace(log10(lowestBF), log10(highestBF), numChannels));
 
 
 %% #6 change model parameters
-paramChanges=[];
+paramChanges={};
 
 %% delare showMap options
 showMapOptions=[];  % use defaults
@@ -45,7 +45,7 @@
 showMapOptions.showACF=0;
 showMapOptions.showEfferent=0;
 showMapOptions.surfSpikes=0;
-showMapOptions.surfProbability=0;       % 2D plot of HSR response
+showMapOptions.surfAN=0;       % 2D plot of HSR response
 
 %% Generate stimuli
 [inputSignal sampleRate]=wavread(fileName);
@@ -69,7 +69,7 @@
 
 
 % the model run is now complete. Now display the results
-UTIL_showMAP(showMapOptions, paramChanges)
+UTIL_showMAP(showMapOptions)
 
 toc
 path(restorePath)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/testPrograms/oldTestPrograms/LiebermanMOCdata.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,79 @@
+function LibermanData= LiebermanMOCdata
+
+LibermanData=[
+    2	0.2;
+2.1	0.19;
+2.2	0.18;
+2.3	0.18;
+2.4	0.16;
+2.5	0.15;
+2.6	0.15;
+2.7	0.15;
+2.8	0.12;
+2.9	0.12;
+3	0.1;
+3.1	0.1;
+3.2	0.05;
+3.3	0.05;
+3.4	0;
+3.5	-0.1;
+3.6	-0.4;
+3.7	-1.2;
+3.8	-1.6;
+3.9	-1.8;
+4	-1.85;
+4.1	-2;
+4.2	-2.05;
+4.3	-2.05;
+4.4	-2.15;
+4.5	-2.2;
+4.6	-2.15;
+4.7	-2.1;
+4.8	-2.15;
+4.9	-2.2;
+5	-2.1;
+5.1	-2.1;
+5.2	-2.25;
+5.3	-2.1;
+5.4	-2.15;
+5.5	-2.1;
+5.6	-2.15;
+5.7	-2.1;
+5.8	-2.2;
+5.9	-2.05;
+6	-2.15;
+6.1	-2.05;
+6.2	-2;
+6.3	-2.2;
+6.4	-2.1;
+6.5	-2.05;
+6.6	-2.05;
+6.7	-2.05;
+6.8	-2.2;
+6.9	-2.1;
+7	-2.05;
+7.1	-2.05;
+7.2	-0.7;
+7.3	-0.1;
+7.4	0;
+7.5	0.1;
+7.6	0.2;
+7.7	0.35;
+7.8	0.2;
+7.9	0.15;
+8	0.2;
+8.1	0.15;
+8.2	0.15;
+8.3	0.15;
+8.4	0.12;
+8.5	0.1;
+8.6	0.09;
+8.7	0.08;
+8.8	0.07;
+8.9	0.06;
+9	0.05;
+];
+figure(98), subplot(2,1,2), hold on
+scalar=-15;
+plot(LibermanData(:,1)-2.5,scalar*LibermanData(:,2))
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/testPrograms/oldTestPrograms/MAPtwoToneDemo1D.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,126 @@
+% function MAPtwoToneDemo
+% Not for distribution but code worth keeping
+% Demonstration of two-tone suppression in the AN using a
+%   single channel
+%
+
+dbstop if error
+% create access to all MAP 1_8 facilities
+% addpath ('..\modules', '..\utilities',  '..\parameterStore',  '..\wavFileStore' , '..\testPrograms')
+addpath (['..' filesep 'modules'], ['..' filesep 'utilities'],  ['..' filesep 'parameterStore'],  ['..' filesep 'wavFileStore'] , ['..' filesep 'testPrograms'])
+
+moduleSequence= 1:7;  	% up to the AN
+figure(3), clf
+primaryToneFrequency=2000;
+suppressorFrequency=primaryToneFrequency*1.5;
+
+primaryDB=30;
+suppressors=20:10:80;
+frameCount=0;
+for suppressorDB=suppressors
+    frameCount=frameCount+1;
+    lowestBF=1000; 	highestBF= 5000; 	numChannels=30;
+    BFlist=round(logspace(log10(lowestBF), log10(highestBF), numChannels));
+    BFlist=2000;
+    duration=.020;		      % seconds
+    sampleRate= 40000; % Hz (higher sample rate needed for BF>8000 Hz)
+    dt=1/sampleRate; % seconds
+    
+    % for conditionNo=1:3  % probe alone/ suppressor alone/ combined
+    for conditionNo=1:3  % probe alone/ suppressor alone/ combined
+        switch conditionNo
+            case 1
+                primaryLevelDB=primaryDB;
+                suppressorLevelDB= -100;
+                plotGuide.subPlotNo=	1;     % initialize subplot count
+                figureTitle=['probe alone:  ' num2str(primaryToneFrequency) ' Hz;   ' num2str(primaryLevelDB) ' dB SPL'];
+                
+            case 2
+                primaryLevelDB=-100;
+                suppressorLevelDB=suppressorDB;
+                plotGuide.subPlotNo=	2;     % initialize subplot count
+                figureTitle=['suppressor alone:  ' num2str(suppressorFrequency) ' Hz;   ' num2str(suppressorLevelDB) ' dB SPL'];
+            case 3
+                primaryLevelDB=primaryDB;
+                suppressorLevelDB=suppressorDB;
+                plotGuide.subPlotNo=	3;     % initialize subplot count
+                figureTitle=['probe + suppressor'];
+        end
+        
+        % primary BF tone
+        time1=dt: dt: duration;
+        amp=10^(primaryLevelDB/20)*28e-6;
+        inputSignal=amp*sin(2*pi*primaryToneFrequency*time1);
+        rampDuration=.005; rampTime=dt:dt:rampDuration;
+        ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ones(1,length(time1)-length(rampTime))];
+        inputSignal=inputSignal.*ramp;
+        inputSignal=inputSignal.*fliplr(ramp);
+        
+        % suppressor
+        tone2Duration=duration/2; % s
+        time2= dt: dt: tone2Duration;
+        % B: tone on
+        amp=10^(suppressorLevelDB/20)*28e-6;
+        inputSignal2=amp*sin(2*pi*suppressorFrequency*time2);
+        rampDuration=.005; rampTime=dt:dt:rampDuration;
+        ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ones(1,length(time2)-length(rampTime))];
+        inputSignal2=inputSignal2.*ramp;
+        % A: initial silence (delay to suppressor)
+        silence=zeros(1,length(time2));
+        inputSignal2=[silence inputSignal2];
+        
+        % add tone and suppressor components
+        inputSignal=inputSignal+inputSignal2;
+        
+        % specify model parameters
+        method=MAPparamsDEMO(BFlist, sampleRate);
+        % parameter change (must be global to take effect)
+        global   AN_IHCsynapseParams
+        AN_IHCsynapseParams.mode=	'probability';
+%         method.useEfferent=0;
+        
+        method.plotGraphs=	1;	   % please plot
+        
+        figure(4), subplot(3,1,conditionNo)
+        plot(time1, inputSignal, 'k')% *************
+        
+        [ANresponse, method, A]=MAPsequenceSeg(inputSignal, method, moduleSequence);
+        response{conditionNo}=ANresponse;
+% 	F(frameCount) = getframe(gcf);
+    end
+    
+%     peakResponse=max(max([response{1} response{2} response{3}]));
+%     figure(3), subplot(4,1,1)
+%     mesh((response{1}), [0 peakResponse])
+%     title(['primary: ' num2str(primaryDB) ' dB SPL'])
+%     zlim([0 5000]), view([-28 36])
+%     
+%     figure(3), subplot(4,1,2)
+%     mesh((response{2}), [0 peakResponse])
+%     title(['suppressor: ' num2str(suppressorDB) ' dB SPL'])
+%     zlim([0 5000]),  view([-28 36])
+%     
+%     figure(3), subplot(4,1,3)
+%     mesh((response{3}), [0 peakResponse])
+%     title([' primary + suppressor '])
+%     zlim([0 5000]), view([-28 36])
+%     
+%     figure(3), subplot(4,1,4)
+%     sum= response{3}-response{1}-response{2};
+%     mesh(sum)
+%     zlim([-2000 2000])
+%     title(' difference matrix (combined - primary - suppressor)')
+%     view([-28 20])
+%     disp( [num2str([ suppressorDB primaryDB max(max(sum))])] )
+%     
+%     colormap(jet)
+    pause(1)
+end
+
+figure(4)
+xlabel('time (s)')
+figure(3)
+xlabel('time (s)')
+
+%  figure(99), movie(F, 1, 1)
+% UTIL_showAllMAPStructures
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/testPrograms/openGlobals.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,12 @@
+global OMEParams DRNLParams IHC_cilia_RPParams IHCpreSynapseParams
+global AN_IHCsynapseParams MacGregorParams MacGregorMultiParams
+
+% All of the results of this function are stored as global
+global  savedParamChanges savedBFlist saveAN_spikesOrProbability ...
+    saveMAPparamsName savedInputSignal dt dtSpikes ...
+    OMEextEarPressure TMoutput OMEoutput DRNLoutput...
+    IHC_cilia_output IHCrestingCiliaCond IHCrestingV...
+    IHCoutput ANprobRateOutput ANoutput savePavailable saveNavailable ...
+    ANtauCas CNtauGk CNoutput ICoutput ICmembraneOutput ICfiberTypeRates...
+    MOCattenuation ARattenuation 
+
--- a/testPrograms/repeatTester.m	Thu Oct 06 15:43:20 2011 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,52 +0,0 @@
-restorePath=path;
-addpath (['..' filesep 'MAP'],    ['..' filesep 'wavFileStore'], ...
-    ['..' filesep 'utilities'])
-
-global OMEParams DRNLParams IHC_cilia_RPParams IHCpreSynapseParams
-global AN_IHCsynapseParams MacGregorParams MacGregorMultiParams
-global dt ANdt  savedBFlist saveAN_spikesOrProbability saveMAPparamsName...
-    savedInputSignal OMEextEarPressure TMoutput OMEoutput ARattenuation ...
-    DRNLoutput IHC_cilia_output IHCrestingCiliaCond IHCrestingV...
-    IHCoutput ANprobRateOutput ANoutput savePavailable ANtauCas  ...
-    CNtauGk CNoutput  ICoutput ICmembraneOutput ICfiberTypeRates ...
-    MOCattenuation 
-
-signalCharacteristics.type='tones';
-signalCharacteristicssignalCharacteristics.sampleRate=50000;
-signalCharacteristics.duration= 1;
-signalCharacteristics.rampDuration=0.05;     
-signalCharacteristics.beginSilence=0.05;
-signalCharacteristics.endSilence=0.05;                  
-signalCharacteristics.toneFrequency=1000; 
-signalCharacteristics.leveldBSPL=50;
-
-showMapOptions.printModelParameters=0;   % prints all parameters
-showMapOptions.showModelOutput=0;       % plot of all stages
-showMapOptions.printFiringRates=0;      % prints stage activity levels
-showMapOptions.showACF=0;               % shows SACF (probability only)
-showMapOptions.showEfferent=0;          % tracks of AR and MOC
-showMapOptions.surfProbability=0;       % 2D plot of HSR response 
-showMapOptions.surfSpikes=0;            % 2D plot of spikes histogram
-showMapOptions.ICrates=0;               % IC rates by CNtauGk
-
-tic
-fprintf('\n')
-disp('Computing ...')
-
-levels=80:10:100;
-    figure(10), clf
-    
-for level=levels
-signalCharacteristics.leveldBSPL=level;
-% MAPrunner(MAPparamsName, AN_spikesOrProbability, ...
-%     signalCharacteristics, paramChanges, showMapOptions)
-MAPrunner('Normal', 'spikes', ...
-    signalCharacteristics, {}, showMapOptions)
-ARmin=min(ARattenuation);
-disp([num2str(level) ':' num2str(ARmin)])
-time=dt:dt:dt*length(ARattenuation);
-hold on, plot(time,(1-ARattenuation)/(1-min(ARattenuation)))
-pause(0.1)
-end
-
-path(restorePath)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/testPrograms/runMAP1_14.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,190 @@
+function runMAP1_14
+% runMAP1_14 is a general purpose test routine that can be adjusted to
+% explore different applications of MAP1_14
+%
+% It is also designed as 'starter' code for building new applications.
+%
+% A range of options are supplied in the early part of the program
+%
+% #1
+% Identify the file (in 'MAPparamsName') containing the model parameters
+%
+% #2
+% Identify the kind of model required (in 'AN_spikesOrProbability').
+%  A full brainstem model ('spikes') can be computed or a shorter model
+%  ('probability') that computes only so far as the auditory nerve
+%
+% #3
+% Choose between a tone signal or file input (in 'signalType')
+%
+% #4
+% Set the signal rms level (in leveldBSPL)
+%
+% #5
+% Identify the channels in terms of their best frequencies in the vector
+%  BFlist.
+%
+% #6
+% Last minute changes to the model parameters can be made using
+%  a cell array of strings, 'paramChanges'.
+
+dbstop if error
+restorePath=path;
+addpath (['..' filesep 'MAP'],    ['..' filesep 'wavFileStore'], ...
+    ['..' filesep 'utilities'])
+
+%%  #1 parameter file name
+MAPparamsName='Normal';
+
+
+%% #2 probability (fast) or spikes (slow) representation: select one
+% AN_spikesOrProbability='spikes';
+%   or
+AN_spikesOrProbability='probability';
+
+
+%% #3 A. pure tone, B. harmonic sequence or C. speech file input
+% comment out unwanted code
+
+% A. tone
+sampleRate= 95000;
+signalType= 'tones';
+toneFrequency= 1000;            % or a pure tone (Hz)
+duration=0.500;                 % seconds
+beginSilence=0.010;
+endSilence=0.020;
+rampDuration=.005;              % raised cosine ramp (seconds)
+
+%   or
+% B. harmonic tone (Hz) - useful to demonstrate a broadband sound
+% sampleRate= 44100;
+% signalType= 'tones';
+% toneFrequency= F0:F0:8000;
+% duration=0.500;                 % seconds
+% beginSilence=0.250;
+% endSilence=0.250;
+% F0=210;
+% rampDuration=.005;              % raised cosine ramp (seconds)
+
+%   or
+% C. signalType= 'file';
+% fileName='twister_44kHz';
+
+%% #4 rms level
+% signal details
+leveldBSPL= 80;                  % dB SPL (80 for Lieberman)
+
+%% #5 number of channels in the model
+%   21-channel model (log spacing)
+numChannels=21;
+lowestBF=100; 	highestBF= 6000;
+BFlist=round(logspace(log10(lowestBF), log10(highestBF), numChannels));
+
+%   or specify your own channel BFs
+% numChannels=1;
+% BFlist=toneFrequency;
+
+
+%% #6 change model parameters
+
+paramChanges={};    % no changes
+
+% Parameter changes can be used to change one or more model parameters
+%  *after* the MAPparams file has been read
+%  Each string must have the same format as the corresponding line in the
+%   file identified in 'MAPparamsName'
+% This example declares only one fiber type with a calcium clearance time
+% constant of 80e-6 s (HSR fiber) when the probability option is selected.
+%   paramChanges={'AN_IHCsynapseParams.ANspeedUpFactor=5;', ...
+%     'IHCpreSynapseParams.tauCa=86e-6; '};
+paramChanges={ 'IHCpreSynapseParams.tauCa=86e-6; ',...
+    'DRNLParams.rateToAttenuationFactorProb = 0;'};
+
+
+
+%% delare 'showMap' options to control graphical output
+% see UTIL_showMAP for more options
+showMapOptions.printModelParameters=1;   % prints all parameters
+showMapOptions.showModelOutput=0;       % plot of all stages
+showMapOptions.printFiringRates=1;      % prints stage activity levels
+showMapOptions.showEfferent=0;          % tracks of AR and MOC
+showMapOptions.surfAN=1;       % 2D plot of HSR response
+
+if strcmp(signalType, 'file')
+    % needed for labeling plot
+    showMapOptions.fileName=fileName;
+else
+    showMapOptions.fileName=[];
+end
+
+%% Generate stimuli
+switch signalType
+    case 'tones'
+        % Create pure tone stimulus
+        dt=1/sampleRate; % seconds
+        time=dt: dt: duration;
+        inputSignal=sum(sin(2*pi*toneFrequency'*time), 1);
+        amp=10^(leveldBSPL/20)*28e-6;   % converts to Pascals (peak)
+        inputSignal=amp*inputSignal;
+        % apply ramps
+        % catch rampTime error
+        if rampDuration>0.5*duration, rampDuration=duration/2; end
+        rampTime=dt:dt:rampDuration;
+        ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ...
+            ones(1,length(time)-length(rampTime))];
+        inputSignal=inputSignal.*ramp;
+        ramp=fliplr(ramp);
+        inputSignal=inputSignal.*ramp;
+        % add silence
+        intialSilence= zeros(1,round(beginSilence/dt));
+        finalSilence= zeros(1,round(endSilence/dt));
+        inputSignal= [intialSilence inputSignal finalSilence];
+
+    case 'file'
+        %% file input simple or mixed
+        [inputSignal sampleRate]=wavread(fileName);
+        dt=1/sampleRate;
+        inputSignal=inputSignal(:,1);
+        targetRMS=20e-6*10^(leveldBSPL/20);
+        rms=(mean(inputSignal.^2))^0.5;
+        amp=targetRMS/rms;
+        inputSignal=inputSignal*amp;
+        intialSilence= zeros(1,round(0.1/dt));
+        finalSilence= zeros(1,round(0.2/dt));
+        inputSignal= [intialSilence inputSignal' finalSilence];
+end
+
+
+%% run the model
+tic
+fprintf('\n')
+disp(['Signal duration= ' num2str(length(inputSignal)/sampleRate)])
+disp([num2str(numChannels) ' channel model: ' AN_spikesOrProbability])
+disp('Computing ...')
+
+MAP1_14(inputSignal, sampleRate, BFlist, ...
+    MAPparamsName, AN_spikesOrProbability, paramChanges);
+
+
+%% the model run is now complete. Now display the results
+UTIL_showMAP(showMapOptions)
+
+if strcmp(signalType,'tones')
+    disp(['duration=' num2str(duration)])
+    disp(['level=' num2str(leveldBSPL)])
+    disp(['toneFrequency=' num2str(toneFrequency)])
+    global DRNLParams
+    disp(['attenuation factor =' ...
+        num2str(DRNLParams.rateToAttenuationFactor, '%5.3f') ])
+    disp(['attenuation factor (probability)=' ...
+        num2str(DRNLParams.rateToAttenuationFactorProb, '%5.3f') ])
+    disp(AN_spikesOrProbability)
+end
+disp('paramChanges')
+for i=1:length(paramChanges)
+    disp(paramChanges{i})
+end
+
+toc
+path(restorePath)
+
--- a/testPrograms/temp.m	Thu Oct 06 15:43:20 2011 +0100
+++ b/testPrograms/temp.m	Mon Nov 28 13:34:28 2011 +0000
@@ -1,190 +1,332 @@
-function test_MAP1_14
-% test_MAP1_14 is a general purpose test routine that can be adjusted to
-% test a number of different applications of MAP1_14
-%
-% A range of options are supplied in the early part of the program
-%
-% One use of the function is to create demonstrations; filenames <demoxx>
-%  to illustrate particular features
-%
-% #1
-% Identify the file (in 'MAPparamsName') containing the model parameters
-%
-% #2
-% Identify the kind of model required (in 'AN_spikesOrProbability').
-%  A full brainstem model (spikes) can be computed or a shorter model
-%  (probability) that computes only so far as the auditory nerve
-%
-% #3
-% Choose between a tone signal or file input (in 'signalType')
-%
-% #4
-% Set the signal rms level (in leveldBSPL)
-%
-% #5
-% Identify the channels in terms of their best frequencies in the vector
-%  BFlist.
-%
-% Last minute changes to the parameters fetched earlier can be made using
-%  the cell array of strings 'paramChanges'.
-%  Each string must have the same format as the corresponding line in the
-%  file identified in 'MAPparamsName'
-%
-% When the demonstration is satisfactory, freeze it by renaming it <demoxx>
+function vectorStrength=testAN(probeFrequency,BFlist, levels, ...
+    paramsName,paramChanges)
+% testAN generates rate/level functions for AN and brainstem units.
+%  also other information like PSTHs, MOC efferent activity levels.
+% Vector strength calculations require the computation of period
+% histograms. for this reason the sample rate must always be an integer
+% multiple of the tone frequency. This applies to both the sampleRate and
+% the spikes sampling rate.
+% A full 'spikes' model is used.
+% paramChanges is a cell array of strings containing MATLAB statements that
+% change model parameters. See MAPparamsNormal for examples.
+% e.g.
+% testAN(1000,1000, -10:10:80,'Normal',{});
 
+
+global IHC_VResp_VivoParams  IHC_cilia_RPParams IHCpreSynapseParams
+global AN_IHCsynapseParams
+global ANoutput dtSpikes CNoutput ICoutput ICmembraneOutput ANtauCas
+global ARattenuation MOCattenuation
+tic
 dbstop if error
 restorePath=path;
-addpath (['..' filesep 'MAP'],    ['..' filesep 'wavFileStore'], ...
-    ['..' filesep 'utilities'])
+addpath (['..' filesep 'MAP'], ['..' filesep 'utilities'], ...
+    ['..' filesep 'parameterStore'],  ['..' filesep 'wavFileStore'],...
+    ['..' filesep 'testPrograms'])
 
-%%  #1 parameter file name
-MAPparamsName='Normal';
+if nargin<5, paramChanges={'IHCpreSynapseParams.tauCa= [30e-6 90e-6];'}; end
+if nargin<4, paramsName='PL'; end
+if nargin<3, levels=-10:10:80; end
+if nargin==0, probeFrequency=1000; BFlist=1000; end
+nLevels=length(levels);
 
+toneDuration=.2;   rampDuration=0.005;   silenceDuration=.02;
+localPSTHbinwidth=0.001;
 
-%% #2 probability (fast) or spikes (slow) representation
-AN_spikesOrProbability='spikes';
-%   or
-AN_spikesOrProbability='probability';
+%% guarantee that the sample rate is an interger multiple 
+%   of the probe frequency
+% we want 5 bins per period for spikes
+spikesSampleRate=5*probeFrequency;
+% model sample rate must be an integer multiple of this and in the region
+% of 50000
+sampleRate=spikesSampleRate*round(50000/spikesSampleRate);
+dt=1/sampleRate;
+% avoid very slow spikes sampling rate
+spikesSampleRate=spikesSampleRate*ceil(10000/spikesSampleRate);
 
+%% pre-allocate storage
+AN_HSRonset=zeros(nLevels,1);
+AN_HSRsaturated=zeros(nLevels,1);
+AN_LSRonset=zeros(nLevels,1);
+AN_LSRsaturated=zeros(nLevels,1);
+CNLSRrate=zeros(nLevels,1);
+CNHSRsaturated=zeros(nLevels,1);
+ICHSRsaturated=zeros(nLevels,1);
+ICLSRsaturated=zeros(nLevels,1);
+vectorStrength=zeros(nLevels,1);
 
-%% #3 pure tone, harmonic sequence or speech file input
-signalType= 'tones';
-sampleRate= 50000;
-duration=0.500;                 % seconds
-rampDuration=.005;              % raised cosine ramp (seconds)
-beginSilence=0.250;               
-endSilence=0.250;                  
-toneFrequency= 1000;            % or a pure tone (Hz)
+AR=zeros(nLevels,1);
+MOC=zeros(nLevels,1);
 
-%   or
-% harmonic sequence (Hz)
-% F0=210;
-% toneFrequency= F0:F0:8000;    
+figure(15), clf
+set(gcf,'position',[980   356   401   321])
+figure(5), clf
+set(gcf,'position', [980 34 400 295])
+drawnow
 
-%   or
-signalType= 'file';
-fileName='twister_44kHz';
 
+%% main computational loop (vary level)
+levelNo=0;
+for leveldB=levels
+    levelNo=levelNo+1;
+    amp=28e-6*10^(leveldB/20);
+    fprintf('%4.0f\t', leveldB)
 
+    %% generate tone and silences
+    time=dt:dt:toneDuration;
+    rampTime=dt:dt:rampDuration;
+    ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ...
+        ones(1,length(time)-length(rampTime))];
+    ramp=ramp.*fliplr(ramp);
+    
+    silence=zeros(1,round(silenceDuration/dt));
+    
+    inputSignal=amp*sin(2*pi*probeFrequency'*time);
+    inputSignal= ramp.*inputSignal;
+    inputSignal=[silence inputSignal];
+    
+    %% run the model
+    AN_spikesOrProbability='spikes';  
+    nExistingParamChanges=length(paramChanges);
+    paramChanges{nExistingParamChanges+1}=...
+        ['AN_IHCsynapseParams.spikesTargetSampleRate=' ...
+        num2str(spikesSampleRate) ';'];
 
-%% #4 rms level
-% signal details
-leveldBSPL= 70;                  % dB SPL (80 for Lieberman)
+    MAP1_14(inputSignal, 1/dt, BFlist, ...
+        paramsName, AN_spikesOrProbability, paramChanges);
+    
+    nTaus=length(ANtauCas);
+    
+    %% Auditory nerve evaluate and display (Fig. 5)
+    %LSR (same as HSR if no LSR fibers present)
+    [nANFibers nTimePoints]=size(ANoutput);
+    numLSRfibers=nANFibers/nTaus;
+    numHSRfibers=numLSRfibers;
+    
+    LSRspikes=ANoutput(1:numLSRfibers,:);
+    PSTH=UTIL_PSTHmaker(LSRspikes, dtSpikes, localPSTHbinwidth);
+    PSTHLSR=mean(PSTH,1)/localPSTHbinwidth;  % across fibers rates
+    PSTHtime=localPSTHbinwidth:localPSTHbinwidth:...
+        localPSTHbinwidth*length(PSTH);
+    AN_LSRonset(levelNo)= max(PSTHLSR); % peak in 5 ms window
+    AN_LSRsaturated(levelNo)= mean(PSTHLSR(round(length(PSTH)/2):end));
+    
+    % AN HSR
+    HSRspikes= ANoutput(end- numHSRfibers+1:end, :);
+    PSTH=UTIL_PSTHmaker(HSRspikes, dtSpikes, localPSTHbinwidth);
+    PSTH=mean(PSTH,1)/localPSTHbinwidth; % sum across fibers (HSR only)
+    AN_HSRonset(levelNo)= max(PSTH);
+    AN_HSRsaturated(levelNo)= mean(PSTH(round(length(PSTH)/2): end));
+    
+    figure(5), subplot(2,2,2)
+    hold off, bar(PSTHtime,PSTH, 'b')
+    hold on,  bar(PSTHtime,PSTHLSR,'r')
+    ylim([0 1000])
+    xlim([0 length(PSTH)*localPSTHbinwidth])
+    grid on
+    set(gcf,'name',['PSTH: ' num2str(BFlist), ' Hz: ' num2str(leveldB) ' dB']);
+    
+    % AN - CV
+    %  CV is computed 5 times. Use the middle one (3) as most typical
+    cvANHSR=  UTIL_CV(HSRspikes, dtSpikes);
+    
+    % AN - vector strength
+    PSTH=sum(CNoutput (11:20,:));
+    [PH, binTimes]=UTIL_periodHistogram...
+        (PSTH, dtSpikes, probeFrequency);
+    VS=UTIL_vectorStrength(PH);
+    vectorStrength(levelNo)=VS;
+    disp(['sat rate= ' num2str(AN_HSRsaturated(levelNo)) ...
+        ';   phase-locking VS = ' num2str(VS)])
+    title(['AN HSR: CV=' num2str(cvANHSR(3),'%5.2f') ...
+        'VS=' num2str(VS,'%5.2f')])
+    
+    %% CN - first-order neurons
+    
+    % CN driven by LSR fibers
+    [nCNneurons c]=size(CNoutput);
+    nLSRneurons=round(nCNneurons/nTaus);
+    CNLSRspikes=CNoutput(1:nLSRneurons,:);
+    PSTH=UTIL_PSTHmaker(CNLSRspikes, dtSpikes, localPSTHbinwidth);
+    PSTH=sum(PSTH)/nLSRneurons;
+%     CNLSRrate(levelNo)=mean(PSTH(round(length(PSTH)/2):end))/localPSTHbinwidth;
+    CNLSRrate(levelNo)=mean(PSTH)/localPSTHbinwidth;
+    
+    %CN HSR
+    MacGregorMultiHSRspikes=...
+        CNoutput(end-nLSRneurons+1:end,:);
+    PSTH=UTIL_PSTHmaker(MacGregorMultiHSRspikes, dtSpikes, localPSTHbinwidth);
+    PSTH=sum(PSTH)/nLSRneurons;
+    PSTH=mean(PSTH,1)/localPSTHbinwidth; % sum across fibers (HSR only)
+    
+%     CNHSRsaturated(levelNo)=mean(PSTH(length(PSTH)/2:end));
+    CNHSRsaturated(levelNo)=mean(PSTH);
+    
+    figure(5), subplot(2,2,3)
+    bar(PSTHtime,PSTH)
+    ylim([0 1000])
+    xlim([0 length(PSTH)*localPSTHbinwidth])
+    cvMMHSR= UTIL_CV(MacGregorMultiHSRspikes, dtSpikes);
+    title(['CN    CV= ' num2str(cvMMHSR(3),'%5.2f')])
+    
+    %% IC LSR
+    [nICneurons c]=size(ICoutput);
+    nLSRneurons=round(nICneurons/nTaus);
+    ICLSRspikes=ICoutput(1:nLSRneurons,:);
+    PSTH=UTIL_PSTHmaker(ICLSRspikes, dtSpikes, localPSTHbinwidth);
+%     ICLSRsaturated(levelNo)=mean(PSTH(round(length(PSTH)/2):end))/localPSTHbinwidth;
+    ICLSRsaturated(levelNo)=mean(PSTH)/localPSTHbinwidth;
+    
+    %IC HSR
+    MacGregorMultiHSRspikes=...
+        ICoutput(end-nLSRneurons+1:end,:);
+    PSTH=UTIL_PSTHmaker(MacGregorMultiHSRspikes, dtSpikes, localPSTHbinwidth);
+    ICHSRsaturated(levelNo)= (sum(PSTH)/nLSRneurons)/toneDuration;
 
+    AR(levelNo)=min(ARattenuation);
+    MOC(levelNo)=min(MOCattenuation(length(MOCattenuation)/2:end));
+    
+    time=dt:dt:dt*size(ICmembraneOutput,2);
+    figure(5), subplot(2,2,4)
+    % plot HSR (last of two)
+    plot(time,ICmembraneOutput(end-nLSRneurons+1, 1:end),'k')
+    ylim([-0.07 0])
+    xlim([0 max(time)])
+    title(['IC  ' num2str(leveldB,'%4.0f') 'dB'])
+    drawnow
+    
+    figure(5), subplot(2,2,1)
+    plot(20*log10(MOC), 'k'), hold on
+    plot(20*log10(AR), 'r'), hold off
+    title(' MOC'), ylabel('dB attenuation')
+    ylim([-30 0])
+    
+%     x=input('prompt')
+end % level
 
-%% #5 number of channels in the model
-%   21-channel model (log spacing)
-numChannels=21;
-lowestBF=250; 	highestBF= 6000;
-BFlist=round(logspace(log10(lowestBF), log10(highestBF), numChannels));
+%% plot with levels on x-axis
+figure(5), subplot(2,2,1)
+plot(levels,20*log10(MOC), 'k'),hold on
+plot(levels,20*log10(AR), 'r'), hold off
+title(' MOC'), ylabel('dB attenuation')
+ylim([-30 0])
+xlim([0 max(levels)])
 
-%   or specify your own channel BFs
-numChannels=1;
-BFlist=toneFrequency;
+fprintf('\n')
+toneDuration=2;
+rampDuration=0.004;
+silenceDuration=.02;
+nRepeats=200;   % no. of AN fibers
+fprintf('toneDuration  %6.3f\n', toneDuration)
+fprintf(' %6.0f  AN fibers (repeats)\n', nRepeats)
+fprintf('levels')
+fprintf('%6.2f\t', levels)
+fprintf('\n')
 
+%% ---------------------- display summary results (Fig 15)
+figure(15), clf
+nRows=2; nCols=2;
 
-%% #6 change model parameters
-
-paramChanges={};
-
-% Parameter changes can be used to change one or more model parameters
-%  *after* the MAPparams file has been read
-% This example declares only one fiber type with a calcium clearance time
-% constant of 80e-6 s (HSR fiber) when the probability option is selected.
-paramChanges={'AN_IHCsynapseParams.ANspeedUpFactor=5;', ...
-    'IHCpreSynapseParams.tauCa=86e-6; '};
-
-
-
-%% delare 'showMap' options to control graphical output
-showMapOptions.printModelParameters=1;   % prints all parameters
-showMapOptions.showModelOutput=1;       % plot of all stages
-showMapOptions.printFiringRates=1;      % prints stage activity levels
-showMapOptions.showACF=1;               % shows SACF (probability only)
-showMapOptions.showEfferent=1;          % tracks of AR and MOC
-showMapOptions.surfProbability=1;       % 2D plot of HSR response 
-showMapOptions.surfSpikes=1;            % 2D plot of spikes histogram
-showMapOptions.ICrates=0;               % IC rates by CNtauGk
-
-% disable certain silly options
-if strcmp(AN_spikesOrProbability, 'spikes')
-    % avoid nonsensical options
-    showMapOptions.surfProbability=0;
-    showMapOptions.showACF=0;
+% AN rate - level ONSET functions
+subplot(nRows,nCols,1)
+plot(levels,AN_LSRonset,'ro'), hold on
+plot(levels,AN_HSRonset,'ko'), hold off
+ylim([0 1000])
+if length(levels)>1
+    xlim([min(levels) max(levels)])
 end
 
-if strcmp(signalType, 'file')
-    % needed for labeling plot
-    showMapOptions.fileName=fileName;
-else
-    showMapOptions.fileName=[];
+ttl=['tauCa= ' num2str(IHCpreSynapseParams.tauCa)];
+title( ttl)
+xlabel('level dB SPL'), ylabel('peak rate (sp/s)'), grid on
+text(0, 800, 'AN onset', 'fontsize', 14)
+
+% AN rate - level ADAPTED function
+subplot(nRows,nCols,2)
+plot(levels,AN_LSRsaturated, 'ro'), hold on
+plot(levels,AN_HSRsaturated, 'ko'), hold off
+ylim([0 400])
+set(gca,'ytick',0:50:300)
+if length(levels)>1
+xlim([min(levels) max(levels)])
 end
+set(gca,'xtick',[levels(1):20:levels(end)])
+%     grid on
+ttl=[   'spont=' num2str(mean(AN_HSRsaturated(1,:)),'%4.0f')...
+    '  sat=' num2str(mean(AN_HSRsaturated(end,1)),'%4.0f')];
+title( ttl)
+xlabel('level dB SPL'), ylabel ('adapted rate (sp/s)')
+text(0, 340, 'AN adapted', 'fontsize', 14), grid on
 
-%% Generate stimuli
+% CN rate - level function
+subplot(nRows,nCols,3)
+plot(levels,CNLSRrate, 'ro'), hold on
+plot(levels,CNHSRsaturated, 'ko'), hold off
+ylim([0 400])
+set(gca,'ytick',0:50:300)
+if length(levels)>1
+xlim([min(levels) max(levels)])
+end
+set(gca,'xtick',[levels(1):20:levels(end)])
+%     grid on
+ttl=[   'spont=' num2str(mean(CNHSRsaturated(1,:)),'%4.0f') '  sat=' ...
+    num2str(mean(CNHSRsaturated(end,1)),'%4.0f')];
+title( ttl)
+xlabel('level dB SPL'), ylabel ('adapted rate (sp/s)')
+text(0, 350, 'CN', 'fontsize', 14), grid on
 
-switch signalType
-    case 'tones'
-        % Create pure tone stimulus
-        dt=1/sampleRate; % seconds
-        time=dt: dt: duration;
-        inputSignal=sum(sin(2*pi*toneFrequency'*time), 1);
-        amp=10^(leveldBSPL/20)*28e-6;   % converts to Pascals (peak)
-        inputSignal=amp*inputSignal;
-        % apply ramps
-        % catch rampTime error
-        if rampDuration>0.5*duration, rampDuration=duration/2; end
-        rampTime=dt:dt:rampDuration;
-        ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ...
-            ones(1,length(time)-length(rampTime))];
-        inputSignal=inputSignal.*ramp;
-        ramp=fliplr(ramp);
-        inputSignal=inputSignal.*ramp;
-        % add silence
-        intialSilence= zeros(1,round(beginSilence/dt));
-        finalSilence= zeros(1,round(endSilence/dt));
-        inputSignal= [intialSilence inputSignal finalSilence];
+% IC rate - level function
+subplot(nRows,nCols,4)
+plot(levels,ICLSRsaturated, 'ro'), hold on
+plot(levels,ICHSRsaturated, 'ko'), hold off
+ylim([0 400])
+set(gca,'ytick',0:50:300)
+if length(levels)>1
+xlim([min(levels) max(levels)])
+end
+set(gca,'xtick',[levels(1):20:levels(end)]), grid on
+ttl=['spont=' num2str(mean(ICHSRsaturated(1,:)),'%4.0f') ...
+    '  sat=' num2str(mean(ICHSRsaturated(end,1)),'%4.0f')];
+title( ttl)
+xlabel('level dB SPL'), ylabel ('adapted rate (sp/s)')
+text(0, 350, 'IC', 'fontsize', 14)
+set(gcf,'name',' AN CN IC rate/level')
 
-    case 'file'
-        %% file input simple or mixed
-        [inputSignal sampleRate]=wavread(fileName);
-        dt=1/sampleRate;
-        inputSignal=inputSignal(:,1);
-        targetRMS=20e-6*10^(leveldBSPL/20);
-        rms=(mean(inputSignal.^2))^0.5;
-        amp=targetRMS/rms;
-        inputSignal=inputSignal*amp;
-        intialSilence= zeros(1,round(0.1/dt));
-        finalSilence= zeros(1,round(0.2/dt));
-        inputSignal= [intialSilence inputSignal' finalSilence];
-end
+fprintf('\n')
+disp('levels vectorStrength')
+fprintf('%3.0f \t %6.4f \n', [levels; vectorStrength'])
+fprintf('\n')
+fprintf('Phase locking, max vector strength=\t %6.4f\n\n',...
+    max(vectorStrength))
 
+allData=[ levels'  AN_HSRonset AN_HSRsaturated...
+    AN_LSRonset AN_LSRsaturated ...
+    CNHSRsaturated CNLSRrate...
+    ICHSRsaturated ICLSRsaturated];
+fprintf('\n levels \tANHSR Onset \tANHSR adapted\tANLSR Onset \tANLSR adapted\tCNHSR\tCNLSR\tICHSR  \tICLSR \n');
+UTIL_printTabTable(round(allData))
+fprintf('VS (phase locking)= \t%6.4f\n\n',...
+    max(vectorStrength))
 
-%% run the model
-tic
+UTIL_showStruct(IHC_cilia_RPParams, 'IHC_cilia_RPParams')
+UTIL_showStruct(IHCpreSynapseParams, 'IHCpreSynapseParams')
+UTIL_showStruct(AN_IHCsynapseParams, 'AN_IHCsynapseParams')
+
 fprintf('\n')
-disp(['Signal duration= ' num2str(length(inputSignal)/sampleRate)])
-disp([num2str(numChannels) ' channel model: ' AN_spikesOrProbability])
-disp('Computing ...')
+disp('levels vectorStrength')
+fprintf('%3.0f \t %6.4f \n', [levels; vectorStrength'])
+fprintf('\n')
+fprintf('Phase locking, max vector strength= \t%6.4f\n\n',...
+    max(vectorStrength))
 
-MAP1_14(inputSignal, sampleRate, BFlist, ...
-    MAPparamsName, AN_spikesOrProbability, paramChanges);
+allData=[ levels'  AN_HSRonset AN_HSRsaturated...
+    AN_LSRonset AN_LSRsaturated ...
+    CNHSRsaturated CNLSRrate...
+    ICHSRsaturated ICLSRsaturated];
+fprintf('\n levels \tANHSR Onset \tANHSR adapted\tANLSR Onset \tANLSR adapted\tCNHSR\tCNLSR\tICHSR  \tICLSR \n');
+UTIL_printTabTable(round(allData))
+fprintf('VS (phase locking)= \t%6.4f\n\n',...
+    max(vectorStrength))
 
-
-%% the model run is now complete. Now display the results
-UTIL_showMAP(showMapOptions, paramChanges)
-
-if strcmp(signalType,'tones')
-    disp(['duration=' num2str(duration)])
-    disp(['level=' num2str(leveldBSPL)])
-    disp(['toneFrequency=' num2str(toneFrequency)])
-    global DRNLParams
-    disp(['attenuation factor =' ...
-        num2str(DRNLParams.rateToAttenuationFactor, '%5.3f') ])
-    disp(['attenuation factor (probability)=' ...
-        num2str(DRNLParams.rateToAttenuationFactorProb, '%5.3f') ])
-    disp(AN_spikesOrProbability)
-end
-disp(paramChanges)
+path(restorePath)
 toc
-path(restorePath)
-
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/testPrograms/tempPL.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,58 @@
+function testPhaseLocking(paramsName, paramChanges)
+
+if nargin<2
+    paramChanges=[];
+end
+
+if nargin<1
+    paramsName='PL';
+end
+
+testFrequencies=[250 500 1000 2000];
+levels=0:10:100;
+
+figure(14), clf
+set(gcf,'position', [980    36   383   321])
+set(gcf,'name', 'phase locking')
+
+allStrengths=zeros(length(testFrequencies), length(levels));
+peakVectorStrength=zeros(1,length(testFrequencies));
+
+freqCount=0;
+for targetFrequency=testFrequencies;
+    %single test
+    freqCount=freqCount+1;
+    vectorStrength=...
+        temp(targetFrequency,targetFrequency, levels,...
+        paramsName, paramChanges);
+    allStrengths(freqCount,:)=vectorStrength';
+    peakVectorStrength(freqCount)=max(vectorStrength');
+end
+%% plot results
+figure(14)
+subplot(2,1,2)
+plot(levels,allStrengths, '+')
+xlabel('levels')
+ylabel('vector strength')
+legend (num2str(testFrequencies'),'location','eastOutside')
+
+subplot(2,1,1)
+semilogx(testFrequencies,peakVectorStrength)
+grid on
+title ('peak vector strength')
+xlabel('frequency')
+ylabel('vector strength')
+
+johnson=[250	0.79
+500	0.82
+1000	0.8
+2000	0.7
+4000	0.25
+5500	0.05
+];
+hold on
+plot(johnson(:,1),johnson(:,2),'o')
+legend({'model','Johnson 80'},'location','eastOutside')
+hold off
+
+
--- a/testPrograms/termp.m	Thu Oct 06 15:43:20 2011 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,13 +0,0 @@
-
-DRNLParams.a=10;
-paramChanges={'DRNL.a=2;'}
-for idx=1:length(paramChanges)
-x=paramChanges{idx};
-st=x(1:strfind(x,'.')-1);
-fld=x(strfind(x,'.')+1:strfind(x,'=')-1);
-x1=eval(['isstruct(' st ')']);
-x2=eval(['isfield(' st ',''' fld ''')']);
-if ~x1*x2
-    disp([' paramChange is faulty: ' x])
-end
-end
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/testPrograms/test2toneMovie.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,151 @@
+% function test2toneMovie
+%
+% Demonstration of two-tone suppression in the AN using a
+%   F1 tone suppressed by a 1.5*F1 kHz tone
+%
+
+global  ANprobRateOutput DRNLoutput
+dbstop if error
+restorePath=path;
+addpath (['..' filesep 'MAP'],    ['..' filesep 'wavFileStore'], ...
+    ['..' filesep 'utilities'])
+figure(5), clf
+
+disp('')
+primaryToneFrequency=8000;
+
+probedBs=10 :10: 50;
+nProbeLevels=length(probedBs);
+
+% disp(['F1 F1 level= ' num2str([primaryToneFrequency probedB])])
+
+suppressorLevels=0:10:80;
+
+lowestBF=250; 	highestBF= 8000; 	numChannels=21;
+BFlist=round(logspace(log10(lowestBF), log10(highestBF), numChannels));
+% fix so that probe is middle range and is at a BF
+BFlist=BFlist*primaryToneFrequency/2000;
+suppressorFrequencies=BFlist;
+BFchannel=find(round(BFlist)==round(primaryToneFrequency));
+
+sampleRate= 100000; % Hz (higher sample rate needed for BF>8000 Hz)
+dt=1/sampleRate; % seconds
+
+duration=.050;		      % seconds
+    tone2Duration=duration/2; % s
+startSilenceDuration=0.010;
+startSilence=...
+    zeros(1,startSilenceDuration*sampleRate);
+suppressorStartsPTR=...
+    round((startSilenceDuration+duration/2)*sampleRate);
+
+probedBCount=0;
+for probedB=probedBs
+    probedBCount=probedBCount+1;
+    
+peakResponse= zeros(length(suppressorLevels),length(suppressorFrequencies));
+suppFreqCount=0;
+for suppressorFrequency=suppressorFrequencies
+    suppFreqCount=suppFreqCount+1;
+    
+    suppressorLevelCount=0;
+for suppressorDB=suppressorLevels
+suppressorLevelCount=suppressorLevelCount+1;
+
+    % primary + suppressor
+    primaryLevelDB=probedB;
+    suppressorLevelDB=suppressorDB;
+
+
+% primary BF tone
+    time1=dt: dt: duration;
+    amp=10^(primaryLevelDB/20)*28e-6;
+    inputSignal=amp*sin(2*pi*primaryToneFrequency*time1);
+    rampDuration=.005; rampTime=dt:dt:rampDuration;
+    ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ones(1,length(time1)-length(rampTime))];
+    inputSignal=inputSignal.*ramp;
+    inputSignal=inputSignal.*fliplr(ramp);
+
+    % suppressor
+    time2= dt: dt: tone2Duration;
+    % B: tone on
+    amp=10^(suppressorLevelDB/20)*28e-6;
+    inputSignal2=amp*sin(2*pi*suppressorFrequency*time2);
+    rampDuration=.005; rampTime=dt:dt:rampDuration;
+    ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ones(1,length(time2)-length(rampTime))];
+    inputSignal2=inputSignal2.*ramp;
+    inputSignal2=inputSignal2.*fliplr(ramp);
+    % A: initial silence (delay to suppressor)
+    silence=zeros(1,length(time2));
+    inputSignal2=[silence inputSignal2];
+
+    % add tone and suppressor components
+    inputSignal=inputSignal+inputSignal2;
+
+    inputSignal=...
+        [startSilence inputSignal ];
+
+    % run MAP
+    MAPparamsName='Normal';
+    AN_spikesOrProbability='probability';
+    paramChanges={'IHCpreSynapseParams.tauCa=80e-6;'};
+    MAP1_14(inputSignal, sampleRate, BFlist, ...
+        MAPparamsName, AN_spikesOrProbability, paramChanges);
+
+    response=ANprobRateOutput;
+peakResponse(suppressorLevelCount,suppFreqCount)=...
+    mean(response(BFchannel,suppressorStartsPTR:end));
+disp(['F2 level= ', num2str([suppressorFrequency suppressorDB ...
+    peakResponse(suppressorLevelCount,suppFreqCount)])])
+
+
+%% make movie
+    figure(6), subplot(4,1,2)
+    axis tight
+    set(gca,'nextplot','replacechildren');
+    plot(dt:dt:dt*length(inputSignal), inputSignal, 'k')
+    ylim([-.5 .5])
+
+    figure(6), subplot(2,1,2)
+    PSTHbinWidth=0.010;
+    PSTH= UTIL_PSTHmakerb(...
+        response, dt, PSTHbinWidth);
+    [nY nX]=size(PSTH);
+    time=PSTHbinWidth*(0:nX-1);
+    surf(time, BFlist, PSTH)
+    zlim([0 500]),
+    caxis([0 500])
+    shading interp
+    colormap(jet)
+    set(gca, 'yScale','log')
+    xlim([0 max(time)+dt])
+    ylim([0 max(BFlist)])
+    view([0 90]) % view([-8 68])
+    title([' primary + suppressor '])
+
+end
+end
+
+%% plot matrix
+
+peakResponse=peakResponse/peakResponse(1,1);
+
+figure(5), subplot(2,nProbeLevels, probedBCount)
+surf(suppressorFrequencies,suppressorLevels,peakResponse)
+shading interp
+view([0 90])
+set(gca,'Xscale','log')
+xlim([min(suppressorFrequencies) max(suppressorFrequencies)])
+set(gca,'Xtick', [1000  4000],'xticklabel',{'1000', '4000'})
+title([num2str(primaryToneFrequency) ' Hz'])
+
+subplot(2,nProbeLevels,nProbeLevels+probedBCount)
+contourf(suppressorFrequencies,suppressorLevels,peakResponse, ...
+    [.1:.1:.9 0.99] )
+set(gca,'Xscale','log')
+set(gca,'Xtick', [1000  4000],'xticklabel',{'1000', '4000'})
+set(gcf, 'name',['primaryToneFrequency= ' num2str(primaryToneFrequency)])
+title([num2str(probedB) ' dB'])
+end
+
+path=restorePath;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/testPrograms/test2toneSuppression.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,216 @@
+% function test2toneSuppression
+%
+% Demonstration of two-tone suppression
+%
+% A probe tone is played at a fixed level and a second tone is introduced
+%  half way through the presentation. The response to the combined signal
+%  is recorded and analysed.
+%
+% The second tone called the seeep tone is presented at a reange of
+%  frequencies and levels. In a linear system we might expect the addition
+%  of a second tone to increase the magnitude of the output. 
+%  In fact, it often results in a reduction in the response. 
+%  This is called two-tone suppression.
+%
+% The effect of the sweep tone is represented in a countour plot showing
+%  both reductions and increases in response.
+% The background colour in this plot is the response to the 
+%  fixed tone alone
+
+
+% Ruggero et al 1992 (Fig 2)
+fixedToneFrequency=8600;
+fixedToneLevelsdB=[45 :5: 90];
+% fixedToneLevelsdB=[30];
+fixedToneDuration=.050;		      % seconds
+sweeptoneLevelsdB=[ 0 : 10:90];
+nSweepToneFrequencies=21;
+sampleSweepFrequency=10600;
+
+global  ANprobRateOutput DRNLoutput
+dbstop if error
+restorePath=path;
+addpath (['..' filesep 'MAP'],    ['..' filesep 'wavFileStore'], ...
+    ['..' filesep 'utilities'])
+figure(5), clf
+figure(87), clf
+
+nFixedToneLevels=length(fixedToneLevelsdB);
+
+lowestSweepFrequency=fixedToneFrequency/6;
+highestSweepFrequency=fixedToneFrequency*3;
+sweepToneFrequencies=round(logspace(log10(lowestSweepFrequency), ...
+    log10(highestSweepFrequency), nSweepToneFrequencies));
+
+% key channels for snapshots
+[a BFchannel]=min((sweepToneFrequencies-fixedToneFrequency).^2);
+[a sampleChannel]=min((sweepToneFrequencies-sampleSweepFrequency).^2);
+
+sampleRate= max(44100, 4*highestSweepFrequency);
+dt=1/sampleRate; % seconds
+
+startSilenceDuration=0.010;
+startSilence= zeros(1,startSilenceDuration*sampleRate);
+
+sweepStartPTR=...
+    round((startSilenceDuration + fixedToneDuration/2)*sampleRate);
+
+BF_BMresponse=zeros(length(sweepToneFrequencies), ...
+    length(fixedToneLevelsdB), length(sweeptoneLevelsdB));
+
+fixedTonedBCount=0;
+for fixedTonedB=fixedToneLevelsdB
+    fixedTonedBCount=fixedTonedBCount+1;
+
+    BMpeakResponse= zeros(length(sweeptoneLevelsdB),length(sweepToneFrequencies));
+    ANpeakResponse= zeros(length(sweeptoneLevelsdB),length(sweepToneFrequencies));
+    sweepToneLevelCount=0;
+    for sweepToneDB=sweeptoneLevelsdB
+        sweepToneLevelCount=sweepToneLevelCount+1;
+        suppFreqCount=0;
+        for sweepToneFrequency=sweepToneFrequencies
+            suppFreqCount=suppFreqCount+1;
+
+            % fixedTone tone
+            time1=dt: dt: fixedToneDuration;
+            amp=10^(fixedTonedB/20)*28e-6;
+            inputSignal=amp*sin(2*pi*fixedToneFrequency*time1);
+            rampDuration=.005; rampTime=dt:dt:rampDuration;
+            ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ones(1,length(time1)-length(rampTime))];
+            inputSignal=inputSignal.*ramp;
+            inputSignal=inputSignal.*fliplr(ramp);
+            nsignalPoints=length(inputSignal);
+            sweepStart=round(nsignalPoints/2);
+            nSweepPoints=nsignalPoints-sweepStart;
+
+            % sweepTone
+            time2= dt: dt: dt*nSweepPoints;
+            % B: tone on
+            amp=10^(sweepToneDB/20)*28e-6;
+            inputSignal2=amp*sin(2*pi*sweepToneFrequency*time2);
+            rampDuration=.005; rampTime=dt:dt:rampDuration;
+            ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ones(1,length(time2)-length(rampTime))];
+            inputSignal2=inputSignal2.*ramp;
+            inputSignal2=inputSignal2.*fliplr(ramp);
+            % add tone and sweepTone components
+            inputSignal(sweepStart+1:end)= inputSignal(sweepStart+1:end)+inputSignal2;
+
+            inputSignal=...
+                [startSilence inputSignal ];
+
+            %% run MAP
+                MAPparamsName='Normal';
+                AN_spikesOrProbability='probability';
+                % only use HSR fibers (NB no acoustic reflex)
+                paramChanges={'IHCpreSynapseParams.tauCa=80e-6;'};
+                paramChanges={'IHCpreSynapseParams.tauCa=80e-6;',...
+                                'DRNLParams.g=0;'};
+                MAP1_14(inputSignal, sampleRate, fixedToneFrequency, ...
+                    MAPparamsName, AN_spikesOrProbability, paramChanges);
+
+                % find toneAlone response
+                if sweepToneLevelCount==1 && suppFreqCount==1
+                    BMfixedToneAloneRate=...
+                        mean(abs(DRNLoutput(sweepStartPTR:end)));
+                    ANfixedToneAloneRate=...
+                        mean(abs(ANprobRateOutput(sweepStartPTR:end)));
+                end
+                
+                   BF_BMresponse(suppFreqCount,fixedTonedBCount, ...
+                       sweepToneLevelCount)=...
+                        mean(abs(DRNLoutput(sweepStartPTR:end)));
+
+                BMpeakResponse(sweepToneLevelCount,suppFreqCount)=...
+                    mean(abs(DRNLoutput(sweepStartPTR:end)))...
+                    /BMfixedToneAloneRate;
+                ANpeakResponse(sweepToneLevelCount,suppFreqCount)=...
+                    mean(abs(ANprobRateOutput(sweepStartPTR:end)))...
+                    /ANfixedToneAloneRate;
+                disp(['F2: ', num2str([sweepToneFrequency sweepToneDB ...
+                    BMpeakResponse(sweepToneLevelCount,suppFreqCount)...
+                    ANpeakResponse(sweepToneLevelCount,suppFreqCount)])...
+                    ' dB'])
+
+                figure(5)
+                time=dt:dt:dt*length(inputSignal);
+                subplot(3,1,1), plot(time, inputSignal)
+                title(['stimulus: Suppressor=' ...
+                    num2str([sweepToneFrequency, sweepToneDB]) ' Hz/ dB'])
+
+                time=dt:dt:dt*length(DRNLoutput);
+                subplot(3,1,2), plot(time, DRNLoutput)
+                xlim([0 fixedToneDuration])
+                        ylim([0 inf])
+
+                time=dt:dt:dt*length(ANprobRateOutput);
+                subplot(3,1,2), plot(time, ANprobRateOutput)
+                xlim([0 fixedToneDuration])
+                        ylim([0 500])
+                title(['ANresponse: fixedTone' num2str([fixedToneFrequency, fixedTonedB]) ' Hz/ dB'])
+
+                subplot(3,2,5)
+                contourf(sweepToneFrequencies,sweeptoneLevelsdB,BMpeakResponse, ...
+                    [.1:.1:.9 1.05] )
+                set(gca,'Xscale','log')
+                set(gca,'Xtick', [1000  4000],'xticklabel',{'1000', '4000'})
+                set(gcf, 'name',['fixedToneFrequency= ' num2str(fixedToneFrequency)])
+                title(['BM' num2str(fixedTonedB) ' dB'])
+
+                subplot(3,2,6)
+                contourf(sweepToneFrequencies,sweeptoneLevelsdB,ANpeakResponse, ...
+                    [.1:.1:.9 1.05] )
+                set(gca,'Xscale','log')
+                set(gca,'Xtick', [1000  4000],'xticklabel',{'1000', '4000'})
+                set(gcf, 'name',['fixedToneFrequency= ' num2str(fixedToneFrequency)])
+                title(['AN:' num2str(fixedTonedB) ' dB'])
+                drawnow
+        end
+    end
+
+    %% plot matrix
+
+    figure (87)
+    subplot(3, nFixedToneLevels, fixedTonedBCount)
+    surf(sweepToneFrequencies,sweeptoneLevelsdB,BMpeakResponse)
+    set(gca,'Xscale','log')
+    zlabel('gain')
+    xlim([lowestSweepFrequency highestSweepFrequency])
+    ylim([min(sweeptoneLevelsdB) max(sweeptoneLevelsdB)])
+    title('BM response')
+    view([-11 52])
+
+    subplot(3, nFixedToneLevels, nFixedToneLevels+fixedTonedBCount)
+    contourf(sweepToneFrequencies,sweeptoneLevelsdB,BMpeakResponse, ...
+        [.1:.5:.9 0.99 1.05] )
+    hold on
+    plot(fixedToneFrequency, fixedTonedB, 'or', 'markerfacecolor','w')
+    set(gca,'Xscale','log')
+    set(gca,'Xtick', [1000  5000],'xticklabel',{'1000', '5000'})
+    ylabel('(BM) sweep level')
+    xlabel('(BM) sweep freq')
+    title(['fixed tone level=' num2str(fixedTonedB) ' dB'])
+%     colorbar
+
+    subplot(3, nFixedToneLevels, 2*nFixedToneLevels+fixedTonedBCount)
+    contourf(sweepToneFrequencies,sweeptoneLevelsdB,ANpeakResponse, ...
+        [.1:.5:.9 0.99 1.05] )
+    hold on
+    plot(fixedToneFrequency, fixedTonedB, 'or', 'markerfacecolor','w')
+    set(gca,'Xscale','log')
+    set(gca,'Xtick', [1000  5000],'xticklabel',{'1000', '5000'})
+    ylabel('(AN) sweep level')
+    xlabel('(AN) sweep freq')
+    title(['fixed tone level=' num2str(fixedTonedB) ' dB'])
+%     colorbar
+    
+end
+
+% Ruggero fig 2 (probe tone level is x-axis, sweep tone level is y-axis
+figure(1),semilogy(fixedToneLevelsdB,squeeze(BF_BMresponse(sampleChannel,:,:)))
+ylim([-inf inf])
+legend(num2str(sweeptoneLevelsdB'),'location','southeast')
+xlabel('probe SPL')
+ylabel ('displacement (m)')
+title(['Probe ' num2str(fixedToneFrequency) ' Hz. Sweep ' ...
+    num2str(sweepToneFrequencies(sampleChannel)) ' Hz.'])
+path=restorePath;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/testPrograms/test2toneSuppressionHold.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,151 @@
+% function test2toneSuppression
+%
+% Demonstration of two-tone suppression in the AN using a
+%   F1 tone suppressed by a 1.5*F1 kHz tone
+%
+
+global  ANprobRateOutput DRNLoutput
+dbstop if error
+restorePath=path;
+addpath (['..' filesep 'MAP'],    ['..' filesep 'wavFileStore'], ...
+    ['..' filesep 'utilities'])
+figure(5), clf
+
+disp('')
+primaryToneFrequency=8000;
+
+probedBs=10 :10: 50;
+nProbeLevels=length(probedBs);
+
+% disp(['F1 F1 level= ' num2str([primaryToneFrequency probedB])])
+
+suppressorLevels=0:10:80;
+
+lowestBF=250; 	highestBF= 8000; 	numChannels=21;
+BFlist=round(logspace(log10(lowestBF), log10(highestBF), numChannels));
+% fix so that probe is middle range and is at a BF
+BFlist=BFlist*primaryToneFrequency/2000;
+suppressorFrequencies=BFlist;
+BFchannel=find(round(BFlist)==round(primaryToneFrequency));
+
+sampleRate= 100000; % Hz (higher sample rate needed for BF>8000 Hz)
+dt=1/sampleRate; % seconds
+
+duration=.050;		      % seconds
+    tone2Duration=duration/2; % s
+startSilenceDuration=0.010;
+startSilence=...
+    zeros(1,startSilenceDuration*sampleRate);
+suppressorStartsPTR=...
+    round((startSilenceDuration+duration/2)*sampleRate);
+
+probedBCount=0;
+for probedB=probedBs
+    probedBCount=probedBCount+1;
+    
+peakResponse= zeros(length(suppressorLevels),length(suppressorFrequencies));
+suppFreqCount=0;
+for suppressorFrequency=suppressorFrequencies
+    suppFreqCount=suppFreqCount+1;
+    
+    suppressorLevelCount=0;
+for suppressorDB=suppressorLevels
+suppressorLevelCount=suppressorLevelCount+1;
+
+    % primary + suppressor
+    primaryLevelDB=probedB;
+    suppressorLevelDB=suppressorDB;
+
+
+% primary BF tone
+    time1=dt: dt: duration;
+    amp=10^(primaryLevelDB/20)*28e-6;
+    inputSignal=amp*sin(2*pi*primaryToneFrequency*time1);
+    rampDuration=.005; rampTime=dt:dt:rampDuration;
+    ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ones(1,length(time1)-length(rampTime))];
+    inputSignal=inputSignal.*ramp;
+    inputSignal=inputSignal.*fliplr(ramp);
+
+    % suppressor
+    time2= dt: dt: tone2Duration;
+    % B: tone on
+    amp=10^(suppressorLevelDB/20)*28e-6;
+    inputSignal2=amp*sin(2*pi*suppressorFrequency*time2);
+    rampDuration=.005; rampTime=dt:dt:rampDuration;
+    ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ones(1,length(time2)-length(rampTime))];
+    inputSignal2=inputSignal2.*ramp;
+    inputSignal2=inputSignal2.*fliplr(ramp);
+    % A: initial silence (delay to suppressor)
+    silence=zeros(1,length(time2));
+    inputSignal2=[silence inputSignal2];
+
+    % add tone and suppressor components
+    inputSignal=inputSignal+inputSignal2;
+
+    inputSignal=...
+        [startSilence inputSignal ];
+
+    % run MAP
+    MAPparamsName='Normal';
+    AN_spikesOrProbability='probability';
+    paramChanges={'IHCpreSynapseParams.tauCa=80e-6;'};
+    MAP1_14(inputSignal, sampleRate, BFlist, ...
+        MAPparamsName, AN_spikesOrProbability, paramChanges);
+
+    response=ANprobRateOutput;
+peakResponse(suppressorLevelCount,suppFreqCount)=...
+    mean(response(BFchannel,suppressorStartsPTR:end));
+disp(['F2 level= ', num2str([suppressorFrequency suppressorDB ...
+    peakResponse(suppressorLevelCount,suppFreqCount)])])
+
+
+%% make movie
+    figure(6), subplot(4,1,2)
+    axis tight
+    set(gca,'nextplot','replacechildren');
+    plot(dt:dt:dt*length(inputSignal), inputSignal, 'k')
+    ylim([-.5 .5])
+
+    figure(6), subplot(2,1,2)
+    PSTHbinWidth=0.010;
+    PSTH= UTIL_PSTHmakerb(...
+        response, dt, PSTHbinWidth);
+    [nY nX]=size(PSTH);
+    time=PSTHbinWidth*(0:nX-1);
+    surf(time, BFlist, PSTH)
+    zlim([0 500]),
+    caxis([0 500])
+    shading interp
+    colormap(jet)
+    set(gca, 'yScale','log')
+    xlim([0 max(time)+dt])
+    ylim([0 max(BFlist)])
+    view([0 90]) % view([-8 68])
+    title([' primary + suppressor '])
+
+end
+end
+
+%% plot matrix
+
+peakResponse=peakResponse/peakResponse(1,1);
+
+figure(5), subplot(2,nProbeLevels, probedBCount)
+surf(suppressorFrequencies,suppressorLevels,peakResponse)
+shading interp
+view([0 90])
+set(gca,'Xscale','log')
+xlim([min(suppressorFrequencies) max(suppressorFrequencies)])
+set(gca,'Xtick', [1000  4000],'xticklabel',{'1000', '4000'})
+title([num2str(primaryToneFrequency) ' Hz'])
+
+subplot(2,nProbeLevels,nProbeLevels+probedBCount)
+contourf(suppressorFrequencies,suppressorLevels,peakResponse, ...
+    [.1:.1:.9 0.99] )
+set(gca,'Xscale','log')
+set(gca,'Xtick', [1000  4000],'xticklabel',{'1000', '4000'})
+set(gcf, 'name',['primaryToneFrequency= ' num2str(primaryToneFrequency)])
+title([num2str(probedB) ' dB'])
+end
+
+path=restorePath;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/testPrograms/testACF.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,263 @@
+% function [P dt lags SACF]= testACF
+% testACF is a *script* to demonstrate the smoothed ACF of 
+% Balaguer-Ballestera, E. Denham, S.L. and Meddis, R. (2008). 
+%
+% Convert this to a *function* by uncommenting the first line
+%  The function returns the P matrix plotted in Figure 96.
+%  If a function is used, the following outputs are returned:
+%   P:  smoothed SACF (lags x time matrix)
+%   dt: time interval between successive columns of P
+%   lags: lags used in computing P
+%   SACF: unsmoothed SACFs
+%  
+% A range of options are supplied in the early part of the program
+%
+% #1
+% Identify the model parameter file (in 'MAPparamsName') 
+%
+% #2
+% Identify the kind of model required (in 'AN_spikesOrProbability')
+%  'probability' is recommended for ACF work
+%
+% #3
+% Choose between a harmonic complex or file input
+%  by commenting out unwanted code
+%
+% #4
+% Set the signal rms level (in leveldBSPL)
+%
+% #5
+% Identify the model channel BFs in the vector 'BFlist'.
+%
+% #6
+% Last minute changes to the model parameters can be made using
+%  the cell array of strings 'paramChanges'.
+%  This is used here to control the details of the ACF computations
+%  Read the notes in this section for more information
+%
+% displays:
+% Figure 97 shows the AN response to the stimulus. this is a channel x time
+%  display. The z-axis (and colour) is the AN fiber firing rate
+%
+% Figure 96 shows the P-matrix, the smoothed SACF.
+%
+% Figure 89 shows a summary of the evolution of the unsmoothed SACF 
+%  over time. If you wish to take a snapshot of the P-matrix at a
+%  particular time, this figure can help identify when to take it. 
+%  The index on the y-axis, identifies the required row numbers 
+%    of the P or SACF matrix, e.g. P(:,2000)
+%
+%  On request, (filteredSACFParams.plotACFs=1) Figure 89 shows the channel 
+%   by channel ACFs at intervals during the computation as a movie.
+%  The number of ACF displays is controlled by 'plotACFsInterval'
+%   and the movie can be slowed or speeded up using 'plotMoviePauses' 
+%   (see paramChanges section below).
+
+% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
+% This global will find results from MAP1_14
+global savedInputSignal ANprobRateOutput ANoutput dt dtSpikes savedBFlist 
+ % This global,from model parameter file
+global filteredSACFParams                      
+
+dbstop if error
+restorePath=path;
+addpath (['..' filesep 'MAP'],    ['..' filesep 'wavFileStore'], ...
+    ['..' filesep 'utilities'])
+
+% User sets up requirements
+%%  #1 parameter file name
+MAPparamsName='Normal';                 % recommended
+
+
+%% #2 probability (fast) or spikes (slow) representation: select one
+% AN_spikesOrProbability='spikes';
+%   or
+AN_spikesOrProbability='probability';   % recommended
+
+%% #3 A. harmonic sequence or B. speech file input
+% Comment out unwanted code
+% A. harmonic tone (Hz) - useful to demonstrate a broadband sound
+sampleRate= 44100;              % recommended 44100
+signalType= 'tones';
+duration=0.100;                 % seconds
+beginSilence=0.020;
+endSilence=0.020;
+rampDuration=.005;              % raised cosine ramp (seconds)
+
+% toneFrequency is a vector of component frequencies
+F0=120;
+toneFrequency= [3*F0 4*F0 5*F0];
+
+%   or
+% B. file input
+signalType= 'file';
+fileName='Oh No';
+fileName='1z67931a_44kHz';
+
+
+%% #4 rms level
+leveldBSPL= 60;                  % dB SPL (80 for Lieberman)
+
+%% #5 number of channels in the model
+%   21-channel model (log spacing of BFs)
+numChannels=21;
+lowestBF=150; 	highestBF= 6000;
+BFlist=round(logspace(log10(lowestBF), log10(highestBF), numChannels));
+
+%% #6 change model parameters
+% Parameter changes can be used to change one or more model parameters
+%  *after* the MAPparams file has been read (see manual)
+
+% Take control of ACF parameters
+%  The filteredACF parameters are set in the MAPparamsNormal file
+%  However, it is convenient to change them here leving the file intacta
+    minPitch=	80; maxPitch=	500; numPitches=50;  
+    minPitch=	200; maxPitch=	4000; numPitches=40;  
+    maxLag=1/minPitch; minLag=1/maxPitch;
+    lags= linspace(minLag, maxLag, numPitches);
+    
+paramChanges={...
+    'filteredSACFParams.lags=lags;     % autocorrelation lags vector;',...
+    'filteredSACFParams.acfTau=	2;     % (Wiegrebe) time constant ACF;',...
+    'filteredSACFParams.lambda=	0.12;  % slower filter to smooth ACF;',...
+    'filteredSACFParams.plotACFs=1;    % plot ACFs while computing;',...
+    'filteredSACFParams.plotACFsInterval=0.01;',...
+    'filteredSACFParams.plotMoviePauses=.1;  ',...
+    'filteredSACFParams.usePressnitzer=0; % attenuates ACF at  long lags;',...
+    'filteredSACFParams.lagsProcedure=  ''useAllLags'';',...
+    };
+
+% Notes:
+% acfTau:   time constant of unsmoothed ACF
+% lambda:   time constant of smoothed ACFS
+% plotACFs: plot ACFs during computation (0 to switch off, for speed)
+% plotACFsInterval: sampling interval for plots
+% plotMoviePauses:  pause duration between frames to allow viewing
+% usePressnitzer:   gives low weights to long lags
+% lagsProcedure:    used to fiddle with output (ignore)
+
+%% delare 'showMap' options to control graphical output
+% see UTIL_showMAP for more options
+showMapOptions=[];
+% showMapOptions.showModelOutput=0;     % plot of all stages
+showMapOptions.surfAN=1;                % surface plot of HSR response
+showMapOptions.PSTHbinwidth=0.001;      % smoothing for PSTH
+
+if exist('fileName','var')
+    % needed for labeling plot
+    showMapOptions.fileName=fileName;
+end
+
+%% Generate stimuli
+switch signalType
+    case 'tones'
+        % Create tone stimulus
+        dt=1/sampleRate; % seconds
+        time=dt: dt: duration;
+        inputSignal=sum(sin(2*pi*toneFrequency'*time), 1);
+        amp=10^(leveldBSPL/20)*28e-6;   % converts to Pascals (peak)
+        inputSignal=amp*inputSignal;
+        % apply ramps
+        % catch rampTime error
+        if rampDuration>0.5*duration, rampDuration=duration/2; end
+        rampTime=dt:dt:rampDuration;
+        ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ...
+            ones(1,length(time)-length(rampTime))];
+        inputSignal=inputSignal.*ramp;
+        ramp=fliplr(ramp);
+        inputSignal=inputSignal.*ramp;
+        % add silence
+        intialSilence= zeros(1,round(beginSilence/dt));
+        finalSilence= zeros(1,round(endSilence/dt));
+        inputSignal= [intialSilence inputSignal finalSilence];
+
+    case 'file'
+        %% file input simple or mixed
+        [inputSignal sampleRate]=wavread(fileName);
+        dt=1/sampleRate;
+        inputSignal=inputSignal(:,1);
+        targetRMS=20e-6*10^(leveldBSPL/20);
+        rms=(mean(inputSignal.^2))^0.5;
+        amp=targetRMS/rms;
+        inputSignal=inputSignal*amp;
+end
+
+wavplay(inputSignal, sampleRate)
+
+%% run the model
+
+fprintf('\n')
+disp(['Signal duration= ' num2str(length(inputSignal)/sampleRate)])
+disp([num2str(numChannels) ' channel model: ' AN_spikesOrProbability])
+disp('Computing ...')
+
+MAP1_14(inputSignal, sampleRate, BFlist, ...
+    MAPparamsName, AN_spikesOrProbability, paramChanges);
+
+
+%% The model run is now complete. Now display the results
+% display the AN response
+UTIL_showMAP(showMapOptions)
+
+% compute ACF
+switch AN_spikesOrProbability
+    case 'probability'
+        % use only HSR fibers
+        inputToACF=ANprobRateOutput(end-length(savedBFlist)+1:end,:);
+    otherwise
+        inputToACF=ANoutput;
+        dt=dtSpikes;
+end
+
+disp ('computing ACF...')
+
+% read paramChanges to get new filteredSACFParams
+for i=1:length(paramChanges)
+eval(paramChanges{i});
+end
+
+[P BFlist SACF]= filteredSACF(inputToACF, dt, savedBFlist, filteredSACFParams);
+disp(' ACF done.')
+
+%% plot original waveform on summary/smoothed ACF plot
+figure(96), clf
+subplot(3,1,3)
+t=dt*(1:length(savedInputSignal));
+plot(t,savedInputSignal, 'k')
+xlim([0 t(end)])
+title(['stimulus: ' num2str(leveldBSPL, '%4.0f') ' dB SPL']);
+
+% plot SACF
+figure(96)
+subplot(2,1,1)
+imagesc(P.^2)
+colormap bone
+ylabel('periodicities (Hz)'), xlabel('time (s)')
+title('smoothed SACF. (periodicity x time)')
+% y-axis specifies pitches (1/lags)
+% Force MATLAB to show the lowest pitch
+postedYvalues=[1 get(gca,'ytick')]; set(gca,'ytick',postedYvalues)
+pitches=1./filteredSACFParams.lags;
+set(gca,'ytickLabel', round(pitches(postedYvalues)))
+% x-axis is time at which P is samples
+[nCH nTimes]=size(P);
+t=dt:dt:dt*nTimes;
+tt=get(gca,'xtick');
+set(gca,'xtickLabel', round(100*t(tt))/100)
+
+%% On a new figure show a cascade of SACFs
+figure(89), clf
+% select 100 samples;
+[r c]=size(SACF);
+step=round(c/100);
+idx=step:step:c;
+
+UTIL_cascadePlot(SACF(:,idx)', 1./pitches)
+
+xlabel('lag (s)'), ylabel('time pointer -->')
+title(' SACF summary over time')
+yValues=get(gca,'yTick');
+set(gca,'yTickLabel', num2str(yValues'*100))
+
+path(restorePath)
+
--- a/testPrograms/testAN.m	Thu Oct 06 15:43:20 2011 +0100
+++ b/testPrograms/testAN.m	Mon Nov 28 13:34:28 2011 +0000
@@ -1,13 +1,21 @@
 function vectorStrength=testAN(probeFrequency,BFlist, levels, ...
     paramsName,paramChanges)
-% generates rate/level functions for AN and brainstem units.
+% testAN generates rate/level functions for AN and brainstem units.
 %  also other information like PSTHs, MOC efferent activity levels.
+% Vector strength calculations require the computation of period
+% histograms. for this reason the sample rate must always be an integer
+% multiple of the tone frequency. This applies to both the sampleRate and
+% the spikes sampling rate.
+% A full 'spikes' model is used.
+% paramChanges is a cell array of strings containing MATLAB statements that
+% change model parameters. See MAPparamsNormal for examples.
 % e.g.
-% testAN(1000,1000, -10:10:80,'Normal',[]);
+% testAN(1000,1000, -10:10:80,'Normal',{});
+
 
 global IHC_VResp_VivoParams  IHC_cilia_RPParams IHCpreSynapseParams
 global AN_IHCsynapseParams
-global ANoutput ANdt CNoutput ICoutput ICmembraneOutput ANtauCas
+global ANoutput dtSpikes CNoutput ICoutput ICmembraneOutput ANtauCas
 global ARattenuation MOCattenuation
 tic
 dbstop if error
@@ -23,23 +31,18 @@
 nLevels=length(levels);
 
 toneDuration=.2;   rampDuration=0.002;   silenceDuration=.02;
-localPSTHbinwidth=0.001;
+localPSTHbinwidth=0.0005;
 
-%% guarantee that the sample rate is at least 10 times the frequency
-sampleRate=50000;
-while sampleRate< 10* probeFrequency
-    sampleRate=sampleRate+10000;
-end
-
-%% adjust sample rate so that the pure tone stimulus has an integer
-%% numver of epochs in a period
+%% guarantee that the sample rate is an interger multiple 
+%   of the probe frequency
+% we want 5 bins per period for spikes
+spikesSampleRate=5*probeFrequency;
+% model sample rate must be an integer multiple of this and in the region
+% of 50000
+sampleRate=spikesSampleRate*round(50000/spikesSampleRate);
 dt=1/sampleRate;
-period=1/probeFrequency;
-ANspeedUpFactor=5;  %anticipating MAP (needs clearing up)
-ANdt=dt*ANspeedUpFactor;
-ANdt=period/round(period/ANdt);
-dt=ANdt/ANspeedUpFactor;
-sampleRate=1/dt;
+% avoid very slow spikes sampling rate
+spikesSampleRate=spikesSampleRate*ceil(10000/spikesSampleRate);
 
 %% pre-allocate storage
 AN_HSRonset=zeros(nLevels,1);
@@ -83,7 +86,12 @@
     inputSignal=[silence inputSignal];
     
     %% run the model
-    AN_spikesOrProbability='spikes';   
+    AN_spikesOrProbability='spikes';  
+    nExistingParamChanges=length(paramChanges);
+    paramChanges{nExistingParamChanges+1}=...
+        ['AN_IHCsynapseParams.spikesTargetSampleRate=' ...
+        num2str(spikesSampleRate) ';'];
+
     MAP1_14(inputSignal, 1/dt, BFlist, ...
         paramsName, AN_spikesOrProbability, paramChanges);
     
@@ -96,16 +104,16 @@
     numHSRfibers=numLSRfibers;
     
     LSRspikes=ANoutput(1:numLSRfibers,:);
-    PSTH=UTIL_PSTHmaker(LSRspikes, ANdt, localPSTHbinwidth);
+    PSTH=UTIL_PSTHmaker(LSRspikes, dtSpikes, localPSTHbinwidth);
     PSTHLSR=mean(PSTH,1)/localPSTHbinwidth;  % across fibers rates
     PSTHtime=localPSTHbinwidth:localPSTHbinwidth:...
         localPSTHbinwidth*length(PSTH);
     AN_LSRonset(levelNo)= max(PSTHLSR); % peak in 5 ms window
     AN_LSRsaturated(levelNo)= mean(PSTHLSR(round(length(PSTH)/2):end));
     
-    % HSR
+    % AN HSR
     HSRspikes= ANoutput(end- numHSRfibers+1:end, :);
-    PSTH=UTIL_PSTHmaker(HSRspikes, ANdt, localPSTHbinwidth);
+    PSTH=UTIL_PSTHmaker(HSRspikes, dtSpikes, localPSTHbinwidth);
     PSTH=mean(PSTH,1)/localPSTHbinwidth; % sum across fibers (HSR only)
     AN_HSRonset(levelNo)= max(PSTH);
     AN_HSRsaturated(levelNo)= mean(PSTH(round(length(PSTH)/2): end));
@@ -120,12 +128,12 @@
     
     % AN - CV
     %  CV is computed 5 times. Use the middle one (3) as most typical
-    cvANHSR=  UTIL_CV(HSRspikes, ANdt);
+    cvANHSR=  UTIL_CV(HSRspikes, dtSpikes);
     
     % AN - vector strength
     PSTH=sum(HSRspikes);
     [PH, binTimes]=UTIL_periodHistogram...
-        (PSTH, ANdt, probeFrequency);
+        (PSTH, dtSpikes, probeFrequency);
     VS=UTIL_vectorStrength(PH);
     vectorStrength(levelNo)=VS;
     disp(['sat rate= ' num2str(AN_HSRsaturated(levelNo)) ...
@@ -139,37 +147,40 @@
     [nCNneurons c]=size(CNoutput);
     nLSRneurons=round(nCNneurons/nTaus);
     CNLSRspikes=CNoutput(1:nLSRneurons,:);
-    PSTH=UTIL_PSTHmaker(CNLSRspikes, ANdt, localPSTHbinwidth);
+    PSTH=UTIL_PSTHmaker(CNLSRspikes, dtSpikes, localPSTHbinwidth);
     PSTH=sum(PSTH)/nLSRneurons;
-    CNLSRrate(levelNo)=mean(PSTH(round(length(PSTH)/2):end))/localPSTHbinwidth;
+%     CNLSRrate(levelNo)=mean(PSTH(round(length(PSTH)/2):end))/localPSTHbinwidth;
+    CNLSRrate(levelNo)=mean(PSTH)/localPSTHbinwidth;
     
     %CN HSR
     MacGregorMultiHSRspikes=...
         CNoutput(end-nLSRneurons+1:end,:);
-    PSTH=UTIL_PSTHmaker(MacGregorMultiHSRspikes, ANdt, localPSTHbinwidth);
+    PSTH=UTIL_PSTHmaker(MacGregorMultiHSRspikes, dtSpikes, localPSTHbinwidth);
     PSTH=sum(PSTH)/nLSRneurons;
     PSTH=mean(PSTH,1)/localPSTHbinwidth; % sum across fibers (HSR only)
     
-    CNHSRsaturated(levelNo)=mean(PSTH(length(PSTH)/2:end));
+%     CNHSRsaturated(levelNo)=mean(PSTH(length(PSTH)/2:end));
+    CNHSRsaturated(levelNo)=mean(PSTH);
     
     figure(5), subplot(2,2,3)
     bar(PSTHtime,PSTH)
     ylim([0 1000])
     xlim([0 length(PSTH)*localPSTHbinwidth])
-    cvMMHSR= UTIL_CV(MacGregorMultiHSRspikes, ANdt);
+    cvMMHSR= UTIL_CV(MacGregorMultiHSRspikes, dtSpikes);
     title(['CN    CV= ' num2str(cvMMHSR(3),'%5.2f')])
     
     %% IC LSR
     [nICneurons c]=size(ICoutput);
     nLSRneurons=round(nICneurons/nTaus);
     ICLSRspikes=ICoutput(1:nLSRneurons,:);
-    PSTH=UTIL_PSTHmaker(ICLSRspikes, ANdt, localPSTHbinwidth);
-    ICLSRsaturated(levelNo)=mean(PSTH(round(length(PSTH)/2):end))/localPSTHbinwidth;
+    PSTH=UTIL_PSTHmaker(ICLSRspikes, dtSpikes, localPSTHbinwidth);
+%     ICLSRsaturated(levelNo)=mean(PSTH(round(length(PSTH)/2):end))/localPSTHbinwidth;
+    ICLSRsaturated(levelNo)=mean(PSTH)/localPSTHbinwidth;
     
     %IC HSR
     MacGregorMultiHSRspikes=...
         ICoutput(end-nLSRneurons+1:end,:);
-    PSTH=UTIL_PSTHmaker(MacGregorMultiHSRspikes, ANdt, localPSTHbinwidth);
+    PSTH=UTIL_PSTHmaker(MacGregorMultiHSRspikes, dtSpikes, localPSTHbinwidth);
     ICHSRsaturated(levelNo)= (sum(PSTH)/nLSRneurons)/toneDuration;
 
     AR(levelNo)=min(ARattenuation);
@@ -190,7 +201,7 @@
     title(' MOC'), ylabel('dB attenuation')
     ylim([-30 0])
     
-    
+%     x=input('prompt')
 end % level
 
 %% plot with levels on x-axis
@@ -219,8 +230,12 @@
 % AN rate - level ONSET functions
 subplot(nRows,nCols,1)
 plot(levels,AN_LSRonset,'ro'), hold on
-plot(levels,AN_HSRonset,'ko'), hold off
-ylim([0 1000]),  xlim([min(levels) max(levels)])
+plot(levels,AN_HSRonset,'ko', 'MarkerEdgeColor','k', 'markerFaceColor','k'), hold off
+ylim([0 1000])
+if length(levels)>1
+    xlim([min(levels) max(levels)])
+end
+
 ttl=['tauCa= ' num2str(IHCpreSynapseParams.tauCa)];
 title( ttl)
 xlabel('level dB SPL'), ylabel('peak rate (sp/s)'), grid on
@@ -229,10 +244,12 @@
 % AN rate - level ADAPTED function
 subplot(nRows,nCols,2)
 plot(levels,AN_LSRsaturated, 'ro'), hold on
-plot(levels,AN_HSRsaturated, 'ko'), hold off
+plot(levels,AN_HSRsaturated, 'ko', 'MarkerEdgeColor','k', 'markerFaceColor','k'), hold off
 ylim([0 400])
 set(gca,'ytick',0:50:300)
+if length(levels)>1
 xlim([min(levels) max(levels)])
+end
 set(gca,'xtick',[levels(1):20:levels(end)])
 %     grid on
 ttl=[   'spont=' num2str(mean(AN_HSRsaturated(1,:)),'%4.0f')...
@@ -241,13 +258,15 @@
 xlabel('level dB SPL'), ylabel ('adapted rate (sp/s)')
 text(0, 340, 'AN adapted', 'fontsize', 14), grid on
 
-% CN rate - level ADAPTED function
+% CN rate - level function
 subplot(nRows,nCols,3)
 plot(levels,CNLSRrate, 'ro'), hold on
-plot(levels,CNHSRsaturated, 'ko'), hold off
+plot(levels,CNHSRsaturated, 'ko', 'MarkerEdgeColor','k', 'markerFaceColor','k'), hold off
 ylim([0 400])
 set(gca,'ytick',0:50:300)
+if length(levels)>1
 xlim([min(levels) max(levels)])
+end
 set(gca,'xtick',[levels(1):20:levels(end)])
 %     grid on
 ttl=[   'spont=' num2str(mean(CNHSRsaturated(1,:)),'%4.0f') '  sat=' ...
@@ -256,13 +275,15 @@
 xlabel('level dB SPL'), ylabel ('adapted rate (sp/s)')
 text(0, 350, 'CN', 'fontsize', 14), grid on
 
-% IC rate - level ADAPTED function
+% IC rate - level function
 subplot(nRows,nCols,4)
 plot(levels,ICLSRsaturated, 'ro'), hold on
-plot(levels,ICHSRsaturated, 'ko'), hold off
+plot(levels,ICHSRsaturated, 'ko', 'MarkerEdgeColor','k', 'markerFaceColor','k'), hold off
 ylim([0 400])
 set(gca,'ytick',0:50:300)
+if length(levels)>1
 xlim([min(levels) max(levels)])
+end
 set(gca,'xtick',[levels(1):20:levels(end)]), grid on
 ttl=['spont=' num2str(mean(ICHSRsaturated(1,:)),'%4.0f') ...
     '  sat=' num2str(mean(ICHSRsaturated(end,1)),'%4.0f')];
--- a/testPrograms/testANprob.m	Thu Oct 06 15:43:20 2011 +0100
+++ b/testPrograms/testANprob.m	Mon Nov 28 13:34:28 2011 +0000
@@ -1,6 +1,9 @@
 function testANprob(targetFrequency,BFlist, levels, ...
     paramsName, paramChanges)
-
+% testANprob generates rate/level functions for AN and brainstem units.
+%  also other information like PSTHs, MOC efferent activity levels.
+% A 'probability' model is used.
+% e.g.
 % testANprob(1000,1000, -10:10:80, 'Normal')
 
 global IHC_VResp_VivoParams  IHC_cilia_RPParams IHCpreSynapseParams
@@ -151,7 +154,7 @@
 % AN rate - level ONSET functions
 subplot(nRows,nCols,1)
 plot(levels,AN_LSRonset,'ro'), hold on
-plot(levels,AN_HSRonset,'ko'), hold off
+plot(levels,AN_HSRonset,'ko', 'MarkerEdgeColor','k', 'markerFaceColor','k'), hold off
 ylim([0 1000]),  xlim([min(levels) max(levels)])
 ttl=['tauCa= ' num2str(IHCpreSynapseParams.tauCa)];
 title( ttl)
@@ -161,7 +164,7 @@
 % AN rate - level ADAPTED function
 subplot(nRows,nCols,2)
 plot(levels,AN_LSRsaturated, 'ro'), hold on
-plot(levels,AN_HSRsaturated, 'ko'), hold off
+plot(levels,AN_HSRsaturated, 'ko', 'MarkerEdgeColor','k', 'markerFaceColor','k'), hold off
 maxYlim=340;
 ylim([0 maxYlim])
 set(gca,'ytick',0:50:300)
--- a/testPrograms/testBM.m	Thu Oct 06 15:43:20 2011 +0100
+++ b/testPrograms/testBM.m	Mon Nov 28 13:34:28 2011 +0000
@@ -1,15 +1,20 @@
 function testBM (BFlist, paramsName,...
     relativeFrequencies, AN_spikesOrProbability, paramChanges)
 % testBM generates input output functions for DRNL model for any number
-% of locations.
-% Computations are bast on a single channel model (channelBFs=BF)
-% peak displacement (peakAmp) is measured.
-%  if DRNLParams.useMOC is chosen, the full model is run (slow)
-%  otherwise only DRNL is computed.
-% Tuning curves are generated based on a range of frequencies reletove to
-% the BF of the location.
+% of locations (BFlist).
+% Each BF is evaluated using a single channel model
+%
+% Peak displacement as a function of pure tone level(peakAmp) is displayed
+%
+% If relative Frequencies is set to a range of values, tuning curves will
+%   be computed using these stimulus frequencie.
+%
+% If AN_spikesOrProbability is set to 'spikes' the full model is run (slow)
+%  otherwise efferent activity is based on AN pspiking probabilities.
 %
 % testBM (1000, 'Normal', 1, 'probability', [])
+%   for tuning curves at 6 locations:
+% testBM ([250 500 1000 2000 4000 8000], 'Normal', [.5 .75 .9 1 1.1 1.25 1.5], 'probability', [])
 
 global    DRNLParams
 
@@ -20,8 +25,9 @@
 
 savePath=path;
 addpath (['..' filesep 'utilities'],['..' filesep 'MAP'])
+tic
 
-levels=-10:10:90;   nLevels=length(levels);
+levels=-10:10:100;   nLevels=length(levels);
 % levels= 50;   nLevels=length(levels);
 
 % refBMdisplacement is the displacement of the BM at threshold
@@ -124,17 +130,21 @@
     set(gca,'ytick',[-10 0 10 20 40])
     grid on
     %     legend({num2str(stimulusFrequencies')}, 'location', 'EastOutside')
-    UTIL_printTabTable([levels' peakAmpBMdB], ...
+    UTIL_printTabTable([levels' peakAmpBMdB peakAmpBM*1e9], ...
         num2str([0 stimulusFrequencies]','%5.0f'), '%5.0f')
     finalSummary=[finalSummary peakAmpBMdB];
 
     % Tuning curve
     if length(relativeFrequencies)>2
         figure(3), subplot(maxRows,nBFs, 2*nBFs+BFno)
-        %         contour(stimulusFrequencies,levels,peakAmpBM,...
-        %             [refBMdisplacement refBMdisplacement],'r')
-        contour(stimulusFrequencies,levels,peakAmpBM,...
-            refBMdisplacement.*[1 5 10 50 100])
+                contour(stimulusFrequencies,levels,peakAmpBM,...
+                    [refBMdisplacement refBMdisplacement],'r','linewidth',4)
+                ylim([-10 40])
+                
+%         contour(stimulusFrequencies,levels,peakAmpBM,...
+%             refBMdisplacement.*[1 5 10 50 100])
+%         ylim([-10 90])
+
         title(['tuning curve at ' num2str(refBMdisplacement) 'm']);
         ylabel('level (dB) at reference')
         xlim([100 10000])
@@ -148,7 +158,7 @@
     figure(3)
     subplot(maxRows,nBFs,nBFs+BFno), cla
     plot(levels,20*log10(peakEfferent), 'linewidth',2)
-    ylabel('MOC (dB attenuation)'), xlabel('level')
+    ylabel('MOC (dB attenuation)'), xlabel('level (dB SPL)')
     title(['MOC: (' AN_spikesOrProbability ') duration= ' ...
         num2str(1000*toneDuration,'%5.0f') ' ms'])
     grid on
@@ -161,6 +171,7 @@
 
 end % best frequency
 
+
 UTIL_showStructureSummary(DRNLParams, 'DRNLParams', 10)
 
     UTIL_printTabTable([levels' finalSummary], ...
@@ -170,5 +181,5 @@
         disp(paramChanges)
     end
     
-
+toc
 path(savePath);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/testPrograms/testDPOAE.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,105 @@
+function [frequencies fft_ampdB]= ...
+    testDPOAE (leveldBSPL, toneFrequencies)
+% MAPdemo runs the MATLAB auditory periphery model
+%
+% The OAE is simulated by combining the output from all DRNL channels
+%
+% arguments leveldBSPL and toneFrequencies are optional
+%  defaults are 70 and [5000 6000]
+%
+% e.g. 
+%  MAPdemoMultiChOAE (60, [3000 4000])
+
+
+global dt DRNLoutput
+dbstop if error
+restorePath=path;
+addpath (['..' filesep 'MAP'], ['..' filesep 'utilities'], ...
+    ['..' filesep 'parameterStore'],  ['..' filesep 'wavFileStore'],...
+    ['..' filesep 'testPrograms'])
+
+% set parameter file here
+paramsName='Normal';
+% choose probability because spikes not used to evaluate BM
+AN_spikesOrProbability='probability';
+% add parameter changes here. paramchanges is a cell array of command
+% strings
+paramChanges={};
+
+% DRNL channels
+lowestBF=1000; 	highestBF= 8000; 	numChannels=41;
+% includes BFs at 250 500 1000 2000 4000 8000 (for 11, 21, 31 BFs)
+%  the output from all these filters will be combined to form the OAE
+BFlist=round(logspace(log10(lowestBF), log10(highestBF), numChannels));
+
+if nargin<2
+    toneFrequencies= 2000;            % single pure tone test
+    toneFrequencies=[ 2000 3000]; 	%  F1 F2 for DPOAEs
+    toneFrequencies=[ 5000 6000]; 	%  F1 F2
+end
+duration=0.05;                  % seconds
+duration=0.05;                  % seconds
+rampDuration=.005;
+
+if nargin<1
+    leveldBSPL=70;                  % dB SPL
+end
+amp=10^(leveldBSPL/20)*28e-6;   % converts to Pascals (peak level)
+
+% Create pure stimulus
+sampleRate= 100000;
+dt=1/sampleRate;
+time=dt: dt: duration;
+inputSignal=sum(sin(2*pi*toneFrequencies'*time), 1);
+inputSignal=amp*inputSignal;
+
+% apply ramps
+if rampDuration>0.5*duration, rampDuration=duration/2; end
+rampTime=dt:dt:rampDuration;
+ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ...
+    ones(1,length(time)-length(rampTime))];
+inputSignal=inputSignal.*ramp;  % at the beginning
+ramp=fliplr(ramp);
+inputSignal=inputSignal.*ramp;  % and at the end
+
+% add 10 ms silence
+silenceDuration=0.01;
+silence= zeros(1,round(silenceDuration/dt));
+inputSignal= [silence inputSignal silence];
+time=dt: dt: dt*length(inputSignal);
+
+%% delare 'showMap' options to control graphical output
+showMapOptions.printModelParameters=0;   % prints all parameters
+showMapOptions.showModelOutput=1;       % plot of all stages
+showMapOptions.printFiringRates=1;      % prints stage activity levels
+showMapOptions.showACF=0;               % shows SACF (probability only)
+showMapOptions.showEfferent=0;          % tracks of AR and MOC
+showMapOptions.surfAN=0;       % 2D plot of HSR response
+showMapOptions.surfSpikes=0;            % 2D plot of spikes histogram
+showMapOptions.ICrates=0;               % IC rates by CNtauGk
+
+
+MAP1_14(inputSignal, 1/dt, BFlist, ...
+    paramsName, AN_spikesOrProbability, paramChanges);
+
+UTIL_showMAP(showMapOptions)
+pause(0.1)
+
+% use this to produce a comnplete record of model parameters
+% UTIL_showAllMAPStructures
+
+OAE=sum(DRNLoutput);
+figure(5),subplot(2,1,1)
+plot(time,OAE)
+title(['F=' num2str(toneFrequencies)])
+[fft_powerdB, fft_phase, frequencies, fft_ampdB]= UTIL_FFT(OAE, dt, 1e-15);
+idx=find(frequencies<1e4);
+
+figure(5),subplot(2,1,2)
+plot(frequencies(idx),fft_ampdB(idx))
+title ('FFT of OAE')
+ylabel('dB')
+ylim([0 100])
+grid on
+
+path(restorePath);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/testPrograms/testEfferent.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,118 @@
+function testEfferent(probeFrequency,BFlist, levels, ...
+    paramsName,paramChanges)
+% generates rate/level functions for AAR and MOC
+%
+% e.g.
+% testEfferent(1000,1000, -10:10:80,'Normal',[]);
+
+global dtSpikes MOCattenuation ANtauCas
+
+tic
+dbstop if error
+restorePath=path;
+addpath (['..' filesep 'MAP'], ['..' filesep 'utilities'], ...
+    ['..' filesep 'parameterStore'],  ['..' filesep 'wavFileStore'],...
+    ['..' filesep 'testPrograms'])
+
+if nargin<5, paramChanges=[]; end
+if nargin<4, paramsName='Normal'; end
+if nargin<3, levels=-10:10:100; end
+if nargin==0,
+    probeFrequency=1000;
+    probeFrequency=100:100:8000;
+        lowestBF=250; 	highestBF= 8000; 	numChannels=21;
+    % 21 chs (250-8k)includes BFs at 250 500 1000 2000 4000 8000
+    BFlist=round(logspace(log10(lowestBF),log10(highestBF),numChannels));
+    keyChannel=round(numChannels/2);
+%     BFlist=1000;
+end
+nLevels=length(levels);
+
+toneDuration=.2;   rampDuration=0.002;   silenceDuration=.02;
+localPSTHbinwidth=0.001;
+
+
+sampleRate=64000; dt=1/sampleRate;
+
+%% delare 'showMap' options to control graphical output
+showMapOptions.printModelParameters=0;   % prints all parameters
+showMapOptions.showModelOutput=0;       % plot of all stages
+showMapOptions.printFiringRates=1;      % prints stage activity levels
+showMapOptions.showACF=0;               % shows SACF (probability only)
+showMapOptions.showEfferent=1;          % tracks of AR and MOC
+showMapOptions.surfAN=0;       % 2D plot of HSR response
+showMapOptions.surfSpikes=0;            % 2D plot of spikes histogram
+showMapOptions.ICrates=0;               % IC rates by CNtauGk
+
+
+%% pre-allocate storage
+AN_HSRonset=zeros(nLevels,1);
+AN_HSRsaturated=zeros(nLevels,1);
+AN_LSRonset=zeros(nLevels,1);
+AN_LSRsaturated=zeros(nLevels,1);
+CNLSRrate=zeros(nLevels,1);
+CNHSRsaturated=zeros(nLevels,1);
+ICHSRsaturated=zeros(nLevels,1);
+ICLSRsaturated=zeros(nLevels,1);
+vectorStrength=zeros(nLevels,1);
+
+AR=zeros(nLevels,1);
+MOC=zeros(nLevels,1);
+maxMOC=[];
+
+%% main computational loop (vary level)
+levelNo=0;
+for leveldB=levels
+    levelNo=levelNo+1;
+    amp=28e-6*10^(leveldB/20);
+    fprintf('%4.0f\t', leveldB)
+
+    %% generate tone and silences
+    time=dt:dt:toneDuration;
+    rampTime=dt:dt:rampDuration;
+    ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ...
+        ones(1,length(time)-length(rampTime))];
+    ramp=ramp.*fliplr(ramp);
+
+    silence=zeros(1,round(silenceDuration/dt));
+
+    inputSignal=amp*sin(2*pi*probeFrequency'*time);
+    inputSignal=sum(inputSignal);
+    inputSignal= ramp.*inputSignal;
+    inputSignal=[silence inputSignal];
+
+    %% run the model
+    AN_spikesOrProbability='spikes';
+%     nExistingParamChanges=length(paramChanges);
+%     paramChanges{nExistingParamChanges+1}=...
+%         ['AN_IHCsynapseParams.spikesTargetSampleRate=' ...
+%         num2str(spikesSampleRate) ';'];
+
+    MAP1_14(inputSignal, 1/dt, BFlist, ...
+        paramsName, AN_spikesOrProbability, paramChanges);
+    
+maxMOC=[maxMOC min(MOCattenuation(keyChannel,:))];
+    UTIL_showMAP(showMapOptions)
+    pause(0.1)
+
+    %% Auditory nerve evaluate and display (Fig. 5)
+    %LSR (same as HSR if no LSR fibers present)
+    nTaus=length(ANtauCas);
+
+
+end % level
+
+%% MOC atten/ level function
+figure(21), subplot(2,1,2)
+plot(levels, 20*log10(maxMOC), 'k'), hold off
+title(' MOC dB attenuation'), ylabel('dB attenuation')
+ylim([-30 0])
+figure(21), subplot(2,1,1)
+plot(levels, maxMOC, 'k'), hold off
+title(' MOC attenuation (scalar)'), ylabel('attenuation (scalar)')
+ylim([0 1])
+
+set(gcf,'name','MOC atten/level')
+
+path(restorePath)
+toc
--- a/testPrograms/testFM.m	Thu Oct 06 15:43:20 2011 +0100
+++ b/testPrograms/testFM.m	Mon Nov 28 13:34:28 2011 +0000
@@ -12,7 +12,7 @@
 
 global inputStimulusParams outerMiddleEarParams DRNLParams
 global IHC_VResp_VivoParams IHCpreSynapseParams  AN_IHCsynapseParams
-global  ANprobRateOutput  ANoutput ANtauCas  ANdt
+global  ANprobRateOutput  ANoutput ANtauCas  dtSpikes
 dbstop if error
 restorePath=path;
 addpath (['..' filesep 'MAP'], ['..' filesep 'utilities'], ...
@@ -26,7 +26,7 @@
     paramChanges=[];
 else
     if nargin<3
-    paramChanges=[];
+        paramChanges=[];
     end
 end
 
@@ -144,13 +144,13 @@
 
         inputSignal=...
             [initialSilence maskerPa gap probe finalSilence];
-%         time=dt:dt:length(inputSignal)*dt;
-%         figure(99), plot(time,inputSignal)
+        %         time=dt:dt:length(inputSignal)*dt;
+        %         figure(99), plot(time,inputSignal)
 
         % **********************************  run MAP model
-%         showPlotsAndDetails=0;
-nChanges=length(paramChanges);
-paramChanges{nChanges+1}='AN_IHCsynapseParams.numFibers=	500;'; 
+        %         showPlotsAndDetails=0;
+        nChanges=length(paramChanges);
+        paramChanges{nChanges+1}='AN_IHCsynapseParams.numFibers=	500;';
         MAP1_14(inputSignal, 1/dt, targetFrequency, ...
             paramsName, AN_spikesOrProbability, paramChanges);
 
@@ -158,7 +158,7 @@
             [nFibers c]=size(ANprobRateOutput);
             nLSRfibers=nFibers/length(ANtauCas);
             ANresponse=ANprobRateOutput(end-nLSRfibers:end,:);
-            ANdt=dt; % no adjustment for spikes speedup
+            dtSpikes=dt; % no adjustment for spikes speedup
         else
             [nFibers c]=size(ANoutput);
             nLSRfibers=nFibers/length(ANtauCas);
@@ -166,12 +166,12 @@
         end
 
         ANresponse=sum(ANresponse);
-%         ANresponseTimes=ANdt:ANdt:length(ANresponse)*ANdt;
-%         figure(99), plot(ANresponseTimes,ANresponse)
+        %         ANresponseTimes=dtSpikes:dtSpikes:length(ANresponse)*dtSpikes;
+        %         figure(99), plot(ANresponseTimes,ANresponse)
 
         % analyse results
         probeStart=initialSilenceDuration+maskerDuration+gapDuration;
-        PSTHbinWidth=ANdt;
+        PSTHbinWidth=dtSpikes;
         responseDelay=0.005;
         probeTimes=probeStart+responseDelay:...
             PSTHbinWidth:probeStart+probeDuration+responseDelay;
@@ -189,20 +189,20 @@
             nDurations=length(gapDurations);
             figure(8)
             PSTHbinWidth=1e-3;
-            PSTH=UTIL_PSTHmaker(ANresponse, ANdt, PSTHbinWidth);
-            PSTH=PSTH*ANdt/PSTHbinWidth;
+            PSTH=UTIL_PSTHmaker(ANresponse, dtSpikes, PSTHbinWidth);
+            PSTH=PSTH*dtSpikes/PSTHbinWidth;
             PSTHplotCount=PSTHplotCount+1;
             subplot(nLevels,nDurations,PSTHplotCount)
             PSTHtime=PSTHbinWidth:PSTHbinWidth:...
                 PSTHbinWidth*length(PSTH);
             if strcmp(AN_spikesOrProbability, 'spikes')
-            bar(PSTHtime, PSTH/PSTHbinWidth/nFibers)
-%                 ylim([0 500])
+                bar(PSTHtime, PSTH/PSTHbinWidth/nFibers)
+                %                 ylim([0 500])
             else
-            bar(PSTHtime, PSTH)
+                bar(PSTHtime, PSTH)
                 ylim([0 500])
             end
-%             xlim([0 longestSignalDuration])
+            xlim([0 longestSignalDuration])
             grid on
 
             if PSTHplotCount< (nLevels-1) * nDurations+1
@@ -220,7 +220,7 @@
                 title([num2str(1000*gapDurations(PSTHplotCount)) 'ms'])
             end
 
-%         figure(99),            bar(PSTHtime, PSTH)
+            %         figure(99),            bar(PSTHtime, PSTH)
 
         end % showPSTHs
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/testPrograms/testLibermanMOC_DPOAE.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,189 @@
+function testLibermanMOC_DPOAE
+
+% compares MOC response to LIberman's 1996 data for DPOAE reduction with
+%  contralateral tone stimulation.
+% This program is used mainly as a check on the time constants involved.
+%
+% NB very different time constants are required for 'spikes' and
+% 'probability'
+
+% global dt ANdt  savedBFlist saveAN_spikesOrProbability saveMAPparamsName...
+%     savedInputSignal OMEextEarPressure TMoutput OMEoutput ARattenuation ...
+%     DRNLoutput IHC_cilia_output IHCrestingCiliaCond IHCrestingV...
+%     IHCoutput ANprobRateOutput ANoutput savePavailable ANtauCas  ...
+%     CNtauGk CNoutput  ICoutput ICmembraneOutput ICfiberTypeRates ...
+%     MOCattenuation
+global dt dtSpikes   saveAN_spikesOrProbability ANprobRateOutput ICoutput    
+
+global DRNLParams
+
+LibermanData=[
+    2	0.2;
+2.1	0.19;2.2	0.18;2.3	0.18;2.4	0.16;2.5	0.15;2.6	0.15;2.7 0.15;
+2.8	0.12;2.9	0.12;3	0.1;3.1	0.1;3.2	0.05;3.3	0.05;3.4	0;3.5	-0.1;
+3.6	-0.4;3.7	-1.2;3.8	-1.6;3.9	-1.8;4	-1.85;4.1	-2;4.2	-2.05;
+4.3	-2.05;4.4	-2.15;4.5	-2.2;4.6	-2.15;4.7	-2.1;4.8	-2.15;4.9 -2.2;
+5	-2.1;5.1	-2.1;5.2	-2.25;5.3	-2.1;5.4	-2.15;5.5	-2.1;5.6 -2.15;
+5.7	-2.1;5.8	-2.2;5.9	-2.05;6	-2.15;6.1	-2.05;6.2 -2;6.3 -2.2;6.4 -2.1;
+6.5	-2.05;6.6	-2.05;6.7	-2.05;6.8 -2.2;6.9 -2.1;7	-2.05;7.1 -2.05;7.2	-0.7;
+7.3	-0.1;7.4	0;7.5	0.1;7.6	0.2;7.7	0.35;7.8	0.2;7.9	0.15;8	0.2;8.1	0.15;8.2	0.15;
+8.3	0.15;8.4	0.12;8.5	0.1;8.6	0.09;8.7	0.08;8.8	0.07;8.9	0.06;9	0.05;
+];
+
+% Backus2006Data: time	bilateral	contralateral	ipsilateral
+% all % max microPascals
+Backus2006Data=[
+    100	20	15	10;
+    200	36	24	14;
+    300	44	30	18;
+    400	46	32	20;
+    500	48	34	22;
+    1000	50	36	24;
+    1500	52	37	25;
+    2000	54	38	27
+    ];
+
+steadyMinimum=mean(LibermanData(LibermanData(:,1)>4 & LibermanData(:,1)<7,2));
+
+restorePath=path;
+addpath (['..' filesep 'MAP'],    ['..' filesep 'wavFileStore'], ...
+    ['..' filesep 'utilities'])
+
+%%  #1 parameter file name
+MAPparamsName='Normal';
+
+
+%% #2 probability (fast) or spikes (slow) representation
+AN_spikesOrProbability='spikes';
+%   or
+AN_spikesOrProbability='probability';
+
+
+%% #3 pure tone, harmonic sequence or speech file input
+signalType= 'tones';
+sampleRate= 50000;
+rampDuration=.005;              % raised cosine ramp (seconds)
+toneFrequency= 1000;            % or a pure tone (Hz)
+duration=3.6;                   % Lieberman test
+beginSilence=1;                 % 1 for Lieberman
+endSilence=1;                   % 1 for Lieberman
+
+%% #4 rms level
+% signal details
+leveldBSPL= 80;                  % dB SPL (80 for Lieberman)
+
+
+%% #5 number of channels in the model
+
+numChannels=1;
+BFlist=toneFrequency;
+
+
+%% #6 change model parameters
+paramChanges={};
+
+%% delare 'showMap' options to control graphical output
+showMapOptions.printModelParameters=1;   % prints all parameters
+showMapOptions.showModelOutput=1;       % plot of all stages
+showMapOptions.printFiringRates=1;      % prints stage activity levels
+showMapOptions.showACF=0;               % shows SACF (probability only)
+showMapOptions.showEfferent=1;          % tracks of AR and MOC
+showMapOptions.surfAN=1;                % 2D plot of HSR response 
+showMapOptions.surfSpikes=0;            % 2D plot of spikes histogram
+showMapOptions.ICrates=0;               % IC rates by CNtauGk
+
+%% Generate stimuli
+
+        % Create pure tone stimulus
+        dt=1/sampleRate; % seconds
+        time=dt: dt: duration;
+        inputSignal=sum(sin(2*pi*toneFrequency'*time), 1);
+        amp=10^(leveldBSPL/20)*28e-6;   % converts to Pascals (peak)
+        inputSignal=amp*inputSignal;
+        % apply ramps
+        % catch rampTime error
+        if rampDuration>0.5*duration, rampDuration=duration/2; end
+        rampTime=dt:dt:rampDuration;
+        ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ...
+            ones(1,length(time)-length(rampTime))];
+        inputSignal=inputSignal.*ramp;
+        ramp=fliplr(ramp);
+        inputSignal=inputSignal.*ramp;
+        % add silence
+        intialSilence= zeros(1,round(beginSilence/dt));
+        finalSilence= zeros(1,round(endSilence/dt));
+        inputSignal= [intialSilence inputSignal finalSilence];
+
+%% run the model
+tic
+fprintf('\n')
+disp(['Signal duration= ' num2str(length(inputSignal)/sampleRate)])
+disp([num2str(numChannels) ' channel model: ' AN_spikesOrProbability])
+disp('Computing ...')
+
+MAP1_14(inputSignal, sampleRate, BFlist, ...
+    MAPparamsName, AN_spikesOrProbability, paramChanges);
+
+
+%% the model run is now complete. Now display the results
+UTIL_showMAP(showMapOptions)
+
+if strcmp(signalType,'tones')
+    disp(['duration=' num2str(duration)])
+    disp(['level=' num2str(leveldBSPL)])
+    disp(['toneFrequency=' num2str(toneFrequency)])
+    disp(['attenuation factor =' ...
+        num2str(DRNLParams.rateToAttenuationFactor, '%5.3f') ])
+    disp(['attenuation factor (probability)=' ...
+        num2str(DRNLParams.rateToAttenuationFactorProb, '%5.3f') ])
+    disp(AN_spikesOrProbability)
+end
+disp(paramChanges)
+
+
+
+%% superimpose Lieberman (1996) data
+
+global  MOCattenuation
+MOCdB=20*log10(MOCattenuation);
+MOCtime=dt:dt:dt*length(MOCdB);
+
+% scale up DPOAE results to the running maximum MOC dB
+steadyMOCminimum=mean(MOCdB(MOCtime>2 & MOCtime<4.5));
+scalar=steadyMOCminimum/steadyMinimum;
+
+figure(90), clf
+plot(MOCtime,MOCdB), hold on
+plot(LibermanData(:,1)-2.5,scalar*LibermanData(:,2),'r:','linewidth',4)
+legend({'MAP', 'DPOAE'},'location', 'east')
+title('Compare Liberman (1996) DPOAE data with MAP MOC')
+xlabel('time (s)'), ylabel('MOC attenuation/ DPOAE reduction')
+if strcmp(saveAN_spikesOrProbability,'probability')
+text(0,2,['MOCtau= ' num2str(DRNLParams.MOCtauProb)])
+else
+text(0,2,['MOCtau= ' num2str(DRNLParams.MOCtau)])
+end
+set(gcf, 'name', 'Liberman compare')
+
+PSTHbinwidth=0.001;
+
+% show the source of the MOC activity
+figure(89)
+if strcmp(saveAN_spikesOrProbability,'probability')
+    % brainstem activity
+    PSTH=UTIL_PSTHmaker...
+        (ANprobRateOutput(2,:), dt, PSTHbinwidth)*dt/PSTHbinwidth;
+else
+    % AN probability
+    PSTH=UTIL_PSTHmaker(ICoutput(2,:), dtSpikes, PSTHbinwidth)*dt/PSTHbinwidth;
+end
+
+time=PSTHbinwidth:PSTHbinwidth:PSTHbinwidth*length(PSTH);
+plot(time, PSTH)
+set(gcf,'name', 'Lieberman')
+title(saveAN_spikesOrProbability)
+
+toc
+path(restorePath)
+
+% figure(88), plot(MOCattenuation)
--- a/testPrograms/testOME.m	Thu Oct 06 15:43:20 2011 +0100
+++ b/testPrograms/testOME.m	Mon Nov 28 13:34:28 2011 +0000
@@ -1,16 +1,24 @@
 function testOME(paramsName, paramChanges)
-% testOME compute the stapes response at a number of frequencies
-%  and compares the stapes displacement with in vivo data
+% testOME compute the external resonance and 
+%  stapes response at a number of frequencies
+% It compares the stapes displacement against human in vivo data
 %  collected by Huber et al.2001.
-% e.g.
+% paramsName: name of file in parameterStore containing model parameters
+% paramchanges: string array of changes to parameters. 
+%    this can be omitted or {} is acceptable argument
+% 
 % testOME('Normal',{})
 
 savePath=path;
 addpath (['..' filesep 'utilities'],['..' filesep 'MAP'])
 
+% default arguments
 if nargin<2
     paramChanges=[];
 end
+if nargin<1
+    paramsName='Normal';
+end
 
 sampleRate=50000;
 
--- a/testPrograms/testPhaseLocking.m	Thu Oct 06 15:43:20 2011 +0100
+++ b/testPrograms/testPhaseLocking.m	Mon Nov 28 13:34:28 2011 +0000
@@ -4,13 +4,20 @@
     paramChanges=[];
 end
 
+if nargin<1
+    paramsName='Normal';
+end
+
 testFrequencies=[250 500 1000 2000 4000 8000];
-levels=50:10:80;
+levels=0:10:100;
+
 figure(14), clf
 set(gcf,'position', [980    36   383   321])
 set(gcf,'name', 'phase locking')
+
 allStrengths=zeros(length(testFrequencies), length(levels));
 peakVectorStrength=zeros(1,length(testFrequencies));
+
 freqCount=0;
 for targetFrequency=testFrequencies;
     %single test
@@ -24,7 +31,7 @@
 %% plot results
 figure(14)
 subplot(2,1,2)
-plot(levels,allStrengths)
+plot(levels,allStrengths, '+')
 xlabel('levels')
 ylabel('vector strength')
 legend (num2str(testFrequencies'),'location','eastOutside')
--- a/testPrograms/testPhysiology.m	Thu Oct 06 15:43:20 2011 +0100
+++ b/testPrograms/testPhysiology.m	Mon Nov 28 13:34:28 2011 +0000
@@ -1,22 +1,40 @@
 function testPhysiology(BF,paramsName, paramChanges)
 % e.g.
-% testPhysiology(1000,'Normal', [])
+% testPhysiology(1000,'Normal', {})
 
 restorePath=path;
 addpath (['..' filesep 'MAP'])
 
-if nargin<3
-    paramChanges=[];
-end
+if nargin<3,  paramChanges=[]; end
 
+if nargin<2, paramsName='Normal'; end
+
+if nargin<1, BF=1000; end
+
+disp('testPhysiology...........computing')
+disp('testOME...........computing')
 testOME(paramsName,paramChanges)
+
 relativeFrequencies=[0.25    .5   .75  1  1.25 1.5    2];
+disp('testBM...........computing')
 testBM (BF, paramsName,relativeFrequencies,'spikes', paramChanges)
-testRP(BF,paramsName,paramChanges)
-testSynapse(BF,paramsName,paramChanges)
+
+disp('testRP...........computing')
+testRP2(paramsName,paramChanges)
+
+disp('testSynapse...........computing')
+testSynapse(BF,paramsName, 'spikes', paramChanges)
+
+disp('testFM...........computing')
 testFM(BF,paramsName,'spikes', paramChanges)
+
+disp('testPhaseLocking...........computing')
 testPhaseLocking(paramsName,paramChanges)
+
+disp('testAN...........computing')
 testAN(BF,BF, -10:10:80,paramsName,paramChanges);
+
+% put these figures on top
 figure(14)
 figure(15)
 
--- a/testPrograms/testPhysiologyProb.m	Thu Oct 06 15:43:20 2011 +0100
+++ b/testPrograms/testPhysiologyProb.m	Mon Nov 28 13:34:28 2011 +0000
@@ -9,12 +9,30 @@
     paramChanges=[];
 end
 
+if nargin==0
+    error('testPhysiologyProb must be called from the command line')
+end
+
+
+disp('testPhysiologyProb...........computing')
+
+disp('testOME...........computing')
 testOME(paramsName, paramChanges)
+
+disp('testBM...........computing')
 relativeFrequencies=[0.25    .5   .75  1  1.25 1.5    2];
 testBM (BF, paramsName,relativeFrequencies,'probability', paramChanges)
-testRP(BF,paramsName, paramChanges)
-testSynapse(BF,paramsName, paramChanges)
+
+disp('testRP...........computing')
+testRP2(paramsName,paramChanges)
+
+disp('testSynapse...........computing')
+testSynapse(BF,paramsName, 'probability', paramChanges)
+
+disp('testFM...........computing')
 testFM(BF,paramsName,'probability', paramChanges)
+
+disp('testANprob...........computing')
 testANprob(BF,BF, -10:10:80,paramsName, paramChanges);
 
 figure(4)
--- a/testPrograms/testRF.m	Thu Oct 06 15:43:20 2011 +0100
+++ b/testPrograms/testRF.m	Mon Nov 28 13:34:28 2011 +0000
@@ -113,7 +113,7 @@
               
         moduleSequence=[1:8];       
 
-        global ANdt ARAttenuation TMoutput OMEoutput ...
+        global dtSpikes ARAttenuation TMoutput OMEoutput ...
     DRNLoutput IHC_cilia_output IHCrestingCiliaCond IHCrestingV...
     IHCoutput ANprobRateOutput ANoutput savePavailable ANtauCas  ...
     CNoutput  ICoutput ICmembraneOutput ICfiberTypeRates MOCattenuation
--- a/testPrograms/testRP.m	Thu Oct 06 15:43:20 2011 +0100
+++ b/testPrograms/testRP.m	Mon Nov 28 13:34:28 2011 +0000
@@ -1,5 +1,5 @@
 function testRP(BFs,MAPparamsName,paramChanges)
-% testIHC used for IHC I/O function
+% testIHC evaluates IHC I/O function
 % multiple BFs can be used but only one is easier to interpret.
 % e.g. testRP(1000,'Normal',{});
 
@@ -18,6 +18,12 @@
 if nargin<3
     paramChanges=[]; 
 end
+if nargin<2
+    MAPparamsName='Normal';
+end
+if nargin<3
+    BFs=800; 
+end
 
 levels=-20:10:100;
 nLevels=length(levels);
@@ -133,10 +139,10 @@
     subplot(2,2,2)
     restingIHC_cilia=IHCrestingCiliaCond;
     plot(levels, IHC_cilia_peak,'k', 'linewidth',2), hold on
-    plot(levels, IHC_cilia_min,'r', 'linewidth',2)
-    hold on,
-    plot([min(levels) max(levels)], ...
-        [restingIHC_cilia restingIHC_cilia], 'g')
+%     plot(levels, IHC_cilia_min,'r', 'linewidth',2)
+%     hold on,
+%     plot([min(levels) max(levels)], ...
+%         [restingIHC_cilia restingIHC_cilia], 'g')
     title(' IHC apical cond.')
     ylabel ('IHCcilia(conductance)'), xlabel('dB SPL')
     xlim([min(levels) max(levels)])
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/testPrograms/testRP2.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,295 @@
+function testRP2(MAPparamsName,paramChanges)
+% testIHC evaluates IHC I/O function
+% multiple BF can be used but only one is easier to interpret.
+% e.g. testRP(1000,'Normal',{});
+
+global experiment method inputStimulusParams
+global stimulusParameters IHC_VResp_VivoParams IHC_cilia_RPParams
+savePath=path;
+addpath (['..' filesep 'utilities'],['..' filesep 'MAP'])
+dbstop if error
+
+figure(4), clf,
+set (gcf, 'name', ['IHC'])
+set(gcf,'position',[613   354   360   322])
+drawColors='rgbkmcy';
+drawnow
+
+if nargin<3
+    paramChanges=[];
+end
+if nargin<2
+    MAPparamsName='Normal';
+end
+if nargin<3
+    BF=800;
+end
+
+levels=-20:10:100;
+nLevels=length(levels);
+toneDuration=.05;
+silenceDuration=.01;
+sampleRate=50000;
+dt=1/sampleRate;
+
+allIHC_RP_peak=[];
+allIHC_RP_dc=[];
+
+%% Ruggero
+%%Ruggero data
+RuggeroData=[
+    0	2.00E-10;
+    10	5.00E-10;
+    20	1.50E-09;
+    30	2.50E-09;
+    40	5.30E-09;
+    50	1.00E-08;
+    60	1.70E-08;
+    70	2.50E-08;
+    80	4.00E-08;
+    90	6.00E-08;
+    100	1.50E-07;
+    110	3.00E-07;
+    ];
+
+
+BF=10000;
+targetFrequency=BF;
+
+IHC_RP_peak=zeros(nLevels,1);
+IHC_RP_min=zeros(nLevels,1);
+IHC_RP_dc=zeros(nLevels,1);
+
+time=dt:dt:toneDuration;
+
+rampDuration=0.004;
+rampTime=dt:dt:rampDuration;
+ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ...
+    ones(1,length(time)-length(rampTime))];
+ramp=ramp.*fliplr(ramp);
+
+silence=zeros(1,round(silenceDuration/dt));
+
+toneStartptr=length(silence)+1;
+toneMidptr=toneStartptr+round(toneDuration/(2*dt)) -1;
+toneEndptr=toneStartptr+round(toneDuration/dt) -1;
+
+levelNo=0;
+for leveldB=levels
+    levelNo=levelNo+1;
+    % replicate at all levels
+    amp=28e-6*10^(leveldB/20);
+    
+    %% create signal (leveldB/ frequency)
+    inputSignal=amp*sin(2*pi*targetFrequency'*time);
+    inputSignal= ramp.*inputSignal;
+    inputSignal=[silence inputSignal silence];
+    inputStimulusParams.sampleRate=1/dt;
+    %         global IHC_ciliaParams
+    
+    %% disable efferent for fast processing
+    
+    %% run the model
+    global  DRNLoutput IHC_cilia_output IHCrestingCiliaCond IHCrestingV...
+        IHCoutput
+    AN_spikesOrProbability='probability';
+    
+    MAP1_14(inputSignal, sampleRate, BF, ...
+        MAPparamsName, AN_spikesOrProbability, paramChanges);
+    
+    % DRNL
+    DRNLoutput=DRNLoutput;
+    DRNL_peak(levelNo,1)=max(DRNLoutput(toneMidptr:toneEndptr));
+    DRNL_min(levelNo,1)=min(DRNLoutput(toneMidptr:toneEndptr));
+    DRNL_dc(levelNo,1)=mean(DRNLoutput(toneMidptr:toneEndptr));
+    
+end
+%% plot DRNL
+subplot(2,2,1)
+referenceDisp=10e-9;
+semilogy(levels,DRNL_peak, 'linewidth',2), hold on
+semilogy(RuggeroData(:,1),RuggeroData(:,2),'o')
+title(['BM: Ruggero ' num2str(BF) ' Hz'])
+ylabel ('displacement(m)'), xlabel('dB SPL')
+xlim([min(levels) max(levels)]), ylim([1e-10 1e-7])
+grid on
+
+
+%% Dallos
+BF=800;
+targetFrequency=BF;
+
+IHC_RP_peak=zeros(nLevels,1);
+IHC_RP_min=zeros(nLevels,1);
+IHC_RP_dc=zeros(nLevels,1);
+
+time=dt:dt:toneDuration;
+
+rampDuration=0.004;
+rampTime=dt:dt:rampDuration;
+ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ...
+    ones(1,length(time)-length(rampTime))];
+ramp=ramp.*fliplr(ramp);
+
+silence=zeros(1,round(silenceDuration/dt));
+
+toneStartptr=length(silence)+1;
+toneMidptr=toneStartptr+round(toneDuration/(2*dt)) -1;
+toneEndptr=toneStartptr+round(toneDuration/dt) -1;
+
+levelNo=0;
+for leveldB=levels
+    levelNo=levelNo+1;
+    % replicate at all levels
+    amp=28e-6*10^(leveldB/20);
+    
+    %% create signal (leveldB/ frequency)
+    inputSignal=amp*sin(2*pi*targetFrequency'*time);
+    inputSignal= ramp.*inputSignal;
+    inputSignal=[silence inputSignal silence];
+    inputStimulusParams.sampleRate=1/dt;
+    %         global IHC_ciliaParams
+    
+    %% disable efferent for fast processing
+    method.DRNLSave=1;
+    method.IHC_cilia_RPSave=1;
+    method.IHCpreSynapseSave=1;
+    method.IHC_cilia_RPSave=1;
+    method.segmentDuration=-1;
+    moduleSequence=1:4;
+    
+    %% run the model
+    global  DRNLoutput IHC_cilia_output IHCrestingCiliaCond IHCrestingV...
+        IHCoutput
+    AN_spikesOrProbability='probability';
+    
+    MAP1_14(inputSignal, sampleRate, BF, ...
+        MAPparamsName, AN_spikesOrProbability, paramChanges);
+    
+    % DRNL
+    DRNLoutput=DRNLoutput;
+    DRNL_peak(levelNo,1)=max(DRNLoutput(toneMidptr:toneEndptr));
+    DRNL_min(levelNo,1)=min(DRNLoutput(toneMidptr:toneEndptr));
+    DRNL_dc(levelNo,1)=mean(DRNLoutput(toneMidptr:toneEndptr));
+    
+    % cilia
+    IHC_ciliaData=IHC_cilia_output;
+    IHC_ciliaData=IHC_ciliaData;
+    IHC_cilia_peak(levelNo,1)=...
+        max(IHC_ciliaData(toneMidptr:toneEndptr));
+    IHC_cilia_min(levelNo,1)=...
+        min(IHC_ciliaData(toneMidptr:toneEndptr));
+    IHC_cilia_dc(levelNo,1)=...
+        mean(IHC_ciliaData(toneMidptr:toneEndptr));
+    
+    % RP
+    IHC_RPData=IHCoutput;
+    IHC_RPData=IHC_RPData;
+    IHC_RP_peak(levelNo,1)=...
+        max(IHC_RPData(toneMidptr:toneEndptr));
+    IHC_RP_min(levelNo,1)=...
+        min(IHC_RPData(toneMidptr:toneEndptr));
+    IHC_RP_dc(levelNo,1)=...
+        mean(IHC_RPData(toneMidptr:toneEndptr));
+    
+end
+
+%% Dallos and Harris data
+%% plot receptor potentials
+figure(4)
+subplot(2,2,3)
+% RP I/O function min and max
+restingRP=IHC_RP_peak(1);
+toPlot= [fliplr(IHC_RP_min(:,1)') IHC_RP_peak(:,1)'];
+microPa=   28e-6*10.^(levels/20);
+microPa=[-fliplr(microPa) microPa];
+plot(microPa,toPlot, 'linewidth',2)
+
+dallosx=[-0.9	-0.1	-0.001	0.001	0.01	0.9];
+dallosy=[-8	-7.8	-6.5	11	16.5	22]/1000 + restingRP;
+subplot(2,2,3)
+hold on, plot(dallosx,dallosy, 'o')
+plot([-1 1], [restingRP restingRP], 'r')
+title(' Dallos(86) data at 800 Hz')
+ylabel ('receptor potential(V)'), xlabel('Pa')
+ylim([-0.08 -0.02]), xlim([-1 1])
+grid on
+
+
+%% Patuzzi
+BF=7000;
+targetFrequency=BF;
+
+IHC_RP_peak=zeros(nLevels,1);
+IHC_RP_min=zeros(nLevels,1);
+IHC_RP_dc=zeros(nLevels,1);
+
+time=dt:dt:toneDuration;
+
+rampDuration=0.004;
+rampTime=dt:dt:rampDuration;
+ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ...
+    ones(1,length(time)-length(rampTime))];
+ramp=ramp.*fliplr(ramp);
+
+silence=zeros(1,round(silenceDuration/dt));
+
+toneStartptr=length(silence)+1;
+toneMidptr=toneStartptr+round(toneDuration/(2*dt)) -1;
+toneEndptr=toneStartptr+round(toneDuration/dt) -1;
+
+levelNo=0;
+for leveldB=levels
+    levelNo=levelNo+1;
+    % replicate at all levels
+    amp=28e-6*10^(leveldB/20);
+    
+    %% create signal (leveldB/ frequency)
+    inputSignal=amp*sin(2*pi*targetFrequency'*time);
+    inputSignal= ramp.*inputSignal;
+    inputSignal=[silence inputSignal silence];
+    inputStimulusParams.sampleRate=1/dt;
+    %         global IHC_ciliaParams
+    
+    %% run the model
+    global  DRNLoutput IHC_cilia_output IHCrestingCiliaCond IHCrestingV...
+        IHCoutput
+    AN_spikesOrProbability='probability';
+    
+    MAP1_14(inputSignal, sampleRate, BF, ...
+        MAPparamsName, AN_spikesOrProbability, paramChanges);
+    
+    % RP
+    IHC_RPData=IHCoutput;
+    IHC_RP_peak(levelNo,1)=...
+        max(IHC_RPData(toneMidptr:toneEndptr));
+    IHC_RP_min(levelNo,1)=...
+        min(IHC_RPData(toneMidptr:toneEndptr));
+    IHC_RP_dc(levelNo,1)=...
+        mean(IHC_RPData(toneMidptr:toneEndptr));
+end
+
+
+%% RP I/O function min and max
+figure(4)
+subplot(2,2,4)
+restingRP=IHC_RP_peak(1);
+peakRP=max(IHC_RP_peak);
+plot(levels, IHC_RP_peak, 'linewidth',2)
+hold on
+plot(levels, IHC_RP_dc, ':', 'linewidth',2)
+plot([min(levels) max(levels)], [restingRP restingRP], 'r')
+xlim([min(levels) max(levels)])
+% animal data
+sndLevel=[5	15	25	35	45	55	65	75];
+RPanimal=restingRP+[0.5	2	4.6	5.8	6.4	7.2	8	10.2]/1000;
+% could be misleading when restingRP changes
+RPanimal=-0.060+[0.5	2	4.6	5.8	6.4	7.2	8	10.2]/1000;
+hold on, plot(sndLevel,RPanimal,'o')
+
+grid on
+title(' 7 kHz Patuzzi')
+ylabel ('RP(V) peak and DC'), xlabel('dB SPL')
+ylim([-0.07 -0.04])
+path(savePath);
+disp(paramChanges)
--- a/testPrograms/testSynapse.m	Thu Oct 06 15:43:20 2011 +0100
+++ b/testPrograms/testSynapse.m	Mon Nov 28 13:34:28 2011 +0000
@@ -1,12 +1,14 @@
-function testSynapse(BFlist,paramsName, paramChanges)
+function testSynapse(BF,paramsName, AN_spikesOrProbability, paramChanges)
 % testSynapse tracks the quantity of available transmitter vesicles
 %  the computations are single channel using the first frequency
 %  in the targetFrequency box of the expGUI.
-% For, speed this function uses only probability and HSR fibers.
-% This cannot be changed because of the way AN_IHCsynapse is coded.This).
+% This function uses only probability and HSR fibers.
+% testSynapse(1000,'Normal',[])
 
-global experiment  method IHCpreSynapseParams
+global experiment  IHCpreSynapseParams
 global  AN_IHCsynapseParams  stimulusParameters
+global savePavailable saveNavailable
+
 savePath=path;
 addpath (['..' filesep 'utilities'],['..' filesep 'MAP'])
 
@@ -14,15 +16,27 @@
     paramChanges=[];
 end
 
+if length(BF)>1
+    error('Only one value allowed for BF')
+end
+% AN_spikesOrProbability='probability';
+% AN_spikesOrProbability='spikes';
+% showPlotsAndDetails=0;
+
 figure(6),clf
 plotColors='rbgkrbgkrbgkrbgkrbgkrbgk';
 set(gcf,'position',[5    32   264   243])
 
 sampleRate=5e4; dt=1/sampleRate;
 
-maskerLevels=-0:10:100;
+switch AN_spikesOrProbability
+    case 'probability'
+        maskerLevels=-0:20:100;
+    case 'spikes'
+        maskerLevels=80;
+end
 
-targetFrequency=BFlist;
+targetFrequency=BF;
 
 silenceDuration=0.015;
 maskerDuration=0.1;
@@ -51,17 +65,16 @@
     amp=28e-6*10^(leveldB/20);
     inputSignal=amp*signal;
 
-    AN_spikesOrProbability='probability';
-    showPlotsAndDetails=0;
-
-    global savePavailable
-   
-        MAP1_14(inputSignal, 1/dt, targetFrequency, ...
-            paramsName, AN_spikesOrProbability, paramChanges);
+    MAP1_14(inputSignal, 1/dt, targetFrequency, ...
+        paramsName, AN_spikesOrProbability, paramChanges);
 
     % ignore LSR channels (if any) at the top of the matrix
-    qt=savePavailable(end, :);
-
+    switch AN_spikesOrProbability
+        case 'probability'
+            qt=savePavailable(end, :);
+        case 'spikes'
+            qt=saveNavailable;
+    end
     synapsedt=dt;
     time=synapsedt:synapsedt:synapsedt*length(qt);
 
@@ -71,17 +84,22 @@
     hold on
     xlim([0 max(time)])
     ylim([0 AN_IHCsynapseParams.M])
+    xlabel ('time')
 end
 
 set(gcf,'name','pre-synaptic available transmitter')
-title(['q - available vesicles:' num2str(BFlist) ' Hz'])
+title(['pre-synaptic transmitter:' num2str(BF) ' Hz'])
+ylabel(['q - available vesicles'])
 legend(strvcat(num2str(maskerLevels')),'location','southeast')
 legend boxoff
 grid on
 
-figure(88), [c,H]=contour(time, maskerLevels,qtMatrix,1:12); clabel(c, H);
-set(gcf,'position',[ 276    31   328   246])
-xlabel('time'), ylabel('maskerLevels')
-title('contour plot of available transmitter')
-grid on
+switch AN_spikesOrProbability
+    case 'probability'
+        figure(88), [c,H]=contour(time, maskerLevels,qtMatrix,1:12); clabel(c, H);
+        set(gcf,'position',[ 276    31   328   246])
+        xlabel('time'), ylabel('maskerLevels')
+        title('contour plot of available transmitter')
+        grid on
+end
 path(savePath);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/testPrograms/test_DRNL_Ruggero97.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,172 @@
+function test_DRNL_Ruggero97
+% test_DRNL_Ruggero97 attempts to match Ruggero's (1992 and 1997)
+%  iso-intensity data by fiddling with the parameters
+
+% # BF is the BF of the filter to be assessed
+BF=9000;
+
+% # test frequencies. check that BF is one of them
+%    copy Ruggero's test tones as fara as possible
+numFs=6; lowestF=4000; 	highestF= 11030;
+toneFrequencyList=round(logspace(log10(lowestF), log10(highestF), numFs));
+
+%  # parameter file name. this is the base set of parameters
+MAPparamsName='Normal';
+
+% # probability representation (not directly relevant here as only
+%    the DRNL output is used
+AN_spikesOrProbability='probability';
+
+% # tone characteristics
+sampleRate= 100000;
+duration=0.0200;                % Ruggero uses 5, 10, 25 ms tones
+rampDuration=0.0015;              % raised cosine ramp (seconds)
+beginSilence=0.050;
+endSilence=0.020;
+
+% # levels
+levels=[3 10:10:80];
+
+%% # change model parameters
+% Parameter changes can be used to change one or more model parameters
+%  *after* the MAPparams file has been read
+
+paramChanges={};
+
+paramChanges={...
+    'DRNLParams.ctBMdB = -20;'...
+    'DRNLParams.g=1000;'...
+    };
+
+% delare 'showMap' options to control graphical output
+% (not needed but might be useful
+% showMapOptions.printModelParameters=0;   % prints all parameters
+% showMapOptions.showModelOutput=1;       % plot of all stages
+% showMapOptions.printFiringRates=0;      % prints stage activity levels
+% showMapOptions.showACF=0;               % shows SACF (probability only)
+% showMapOptions.showEfferent=0;          % tracks of AR and MOC
+% showMapOptions.surfAN=0;       % 2D plot of HSR response
+% showMapOptions.surfSpikes=0;            % 2D plot of spikes histogram
+% showMapOptions.ICrates=0;               % IC rates by CNtauGk
+% showMapOptions.fileName=[];
+
+% run the program
+global dt  DRNLoutput DRNLParams TMoutput
+dbstop if error
+restorePath=path; 
+addpath (['..' filesep 'MAP'],    ['..' filesep 'wavFileStore'], ...
+    ['..' filesep 'utilities'])
+figure(2), clf,figure(3), clf,figure(4), clf,
+
+peakOutputDisp=zeros(length(levels),length(toneFrequencyList));
+peakStapesDisp=zeros(length(levels),length(toneFrequencyList));
+
+%% now vary level and frequency while measuring the response
+levelNo=0;
+for leveldBSPL=levels
+    levelNo=levelNo+1;
+    disp(['level: ' num2str(leveldBSPL)])
+
+    freqNo=0;
+    for toneFrequency=toneFrequencyList
+        freqNo=freqNo+1;
+
+        %% Generate stimuli
+        dt=1/sampleRate;
+        time=dt: dt: duration;
+        inputSignal=sum(sin(2*pi*toneFrequency'*time), 1);
+        amp=10^(leveldBSPL/20)*28e-6;   % converts to Pascals (peak)
+        inputSignal=amp*inputSignal;
+        % apply ramps
+        if rampDuration>0.5*duration, rampDuration=duration/2; end
+        rampTime=dt:dt:rampDuration;
+        ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ...
+            ones(1,length(time)-length(rampTime))];
+        inputSignal=inputSignal.*ramp;
+        ramp=fliplr(ramp);
+        inputSignal=inputSignal.*ramp;
+        % add silence
+        intialSilence= zeros(1,round(beginSilence/dt));
+        finalSilence= zeros(1,round(endSilence/dt));
+        inputSignal= [intialSilence inputSignal finalSilence];
+
+        %% run the model
+    
+        MAP1_14(inputSignal, sampleRate, BF, ...
+            MAPparamsName, AN_spikesOrProbability, paramChanges);
+
+        peakOutputDisp(levelNo,freqNo)=max(DRNLoutput);
+        peakStapesDisp(levelNo,freqNo)=max(TMoutput);
+
+        % the model run is complete. Now display the results if debugging
+        % UTIL_showMAP(showMapOptions)
+    end % probe frequencies
+    
+    % monitor progress
+    figure(2), loglog(toneFrequencyList, peakOutputDisp), hold on
+    xlabel('frequency')
+    ylabel('peak DRNL displacement (m)')
+    title ('DRNL uncorrected displacement')
+end  % levels
+figure(2),legend(num2str(toneFrequencyList'),'location','northwest')
+
+% convert from model BM displacement to Ruggero's velocity
+DRNLvelocity= peakOutputDisp ...
+    .*repmat(2*pi*toneFrequencyList,length(levels),1);
+% convert from model stapes displacement to Ruggero's velocity
+stapesVelocity= peakStapesDisp ...
+    .*repmat(2*pi*toneFrequencyList,length(levels),1);
+% velocity gain is increased velocity attributable to the DRNL
+DRNLvelocityGain = DRNLvelocity./stapesVelocity;
+DRNLvelocityGain_dB= 20*log10(DRNLvelocityGain );
+% iso-intensity equates all functions at the same outpu for the lowest
+%  velocity tested
+isoIntensityDRNLvel_dB= DRNLvelocityGain_dB- ...
+    repmat(DRNLvelocityGain_dB(:,1),1,length(toneFrequencyList));
+
+% displays
+% iso-velocity function (nrmalised by stapes velocity)
+figure(3), clf, semilogx(toneFrequencyList, isoIntensityDRNLvel_dB)
+ylim([-10 50])
+xlim([3000 20000])
+xlabel('frequency (Hz)')
+set(gca,'Xtick', [1000 ],'xticklabel',{'1000'})
+
+ylabel('peak DRNL velocity gain (dB)')
+title(['CF= ' num2str(BF) ' Hz'])
+legend(num2str(levels'),'location','northwest')
+
+% velocity I/O function
+figure(4), clf, semilogy(levels, (DRNLvelocity*1e6)'), hold on
+ylim([5e0 1.2e4])
+xlim([0 80])
+xlabel('level')
+ylabel(' velocity (microm/ s)')
+title(['CF= ' num2str(BF) ' Hz'])
+legend(num2str(toneFrequencyList'),'location','northwest')
+
+% command window reports
+disp(''), disp('***')
+disp(AN_spikesOrProbability)
+
+% DRNL parameter set
+UTIL_showStructureSummary(DRNLParams, 'DRNLParams', 10)
+
+% stimulus characteristics
+disp(['CF=' num2str(BF)])
+disp(['tone Duration=' num2str(rampDuration)])
+disp(['ramp Duration=' num2str(duration)])
+
+% particular parameter changes used on this run
+for i=1:length(paramChanges)
+    disp(paramChanges{i})
+end
+
+% if required dump one or more matrices in tab spaced format
+%  (suitable for pasting directly into EXCEL.
+%     UTIL_printTabTable([toneFrequencyList' peakOutputDisp'])
+
+% leave the path as you found it
+path(restorePath)
+
+
--- a/testPrograms/test_MAP1_14.m	Thu Oct 06 15:43:20 2011 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,190 +0,0 @@
-function test_MAP1_14
-% test_MAP1_14 is a general purpose test routine that can be adjusted to
-% test a number of different applications of MAP1_14
-%
-% A range of options are supplied in the early part of the program
-%
-% One use of the function is to create demonstrations; filenames <demoxx>
-%  to illustrate particular features
-%
-% #1
-% Identify the file (in 'MAPparamsName') containing the model parameters
-%
-% #2
-% Identify the kind of model required (in 'AN_spikesOrProbability').
-%  A full brainstem model (spikes) can be computed or a shorter model
-%  (probability) that computes only so far as the auditory nerve
-%
-% #3
-% Choose between a tone signal or file input (in 'signalType')
-%
-% #4
-% Set the signal rms level (in leveldBSPL)
-%
-% #5
-% Identify the channels in terms of their best frequencies in the vector
-%  BFlist.
-%
-% Last minute changes to the parameters fetched earlier can be made using
-%  the cell array of strings 'paramChanges'.
-%  Each string must have the same format as the corresponding line in the
-%  file identified in 'MAPparamsName'
-%
-% When the demonstration is satisfactory, freeze it by renaming it <demoxx>
-
-dbstop if error
-restorePath=path;
-addpath (['..' filesep 'MAP'],    ['..' filesep 'wavFileStore'], ...
-    ['..' filesep 'utilities'])
-
-%%  #1 parameter file name
-MAPparamsName='Normal';
-
-
-%% #2 probability (fast) or spikes (slow) representation
-AN_spikesOrProbability='spikes';
-%   or
-AN_spikesOrProbability='probability';
-
-
-%% #3 pure tone, harmonic sequence or speech file input
-signalType= 'tones';
-sampleRate= 50000;
-duration=0.500;                 % seconds
-rampDuration=.005;              % raised cosine ramp (seconds)
-beginSilence=0.250;               
-endSilence=0.250;                  
-toneFrequency= 1000;            % or a pure tone (Hz)
-
-%   or
-% harmonic sequence (Hz)
-% F0=210;
-% toneFrequency= F0:F0:8000;    
-
-%   or
-signalType= 'file';
-fileName='twister_44kHz';
-
-
-
-%% #4 rms level
-% signal details
-leveldBSPL= 70;                  % dB SPL (80 for Lieberman)
-
-
-%% #5 number of channels in the model
-%   21-channel model (log spacing)
-numChannels=21;
-lowestBF=250; 	highestBF= 6000;
-BFlist=round(logspace(log10(lowestBF), log10(highestBF), numChannels));
-
-%   or specify your own channel BFs
-% numChannels=1;
-% BFlist=toneFrequency;
-
-
-%% #6 change model parameters
-
-paramChanges={};
-
-% Parameter changes can be used to change one or more model parameters
-%  *after* the MAPparams file has been read
-% This example declares only one fiber type with a calcium clearance time
-% constant of 80e-6 s (HSR fiber) when the probability option is selected.
-paramChanges={'AN_IHCsynapseParams.ANspeedUpFactor=5;', ...
-    'IHCpreSynapseParams.tauCa=86e-6; '};
-
-
-
-%% delare 'showMap' options to control graphical output
-showMapOptions.printModelParameters=1;   % prints all parameters
-showMapOptions.showModelOutput=1;       % plot of all stages
-showMapOptions.printFiringRates=1;      % prints stage activity levels
-showMapOptions.showACF=0;               % shows SACF (probability only)
-showMapOptions.showEfferent=1;          % tracks of AR and MOC
-showMapOptions.surfProbability=1;       % 2D plot of HSR response 
-showMapOptions.surfSpikes=1;            % 2D plot of spikes histogram
-showMapOptions.ICrates=0;               % IC rates by CNtauGk
-
-% disable certain silly options
-if strcmp(AN_spikesOrProbability, 'spikes')
-    % avoid nonsensical options
-    showMapOptions.surfProbability=0;
-    showMapOptions.showACF=0;
-end
-
-if strcmp(signalType, 'file')
-    % needed for labeling plot
-    showMapOptions.fileName=fileName;
-else
-    showMapOptions.fileName=[];
-end
-
-%% Generate stimuli
-
-switch signalType
-    case 'tones'
-        % Create pure tone stimulus
-        dt=1/sampleRate; % seconds
-        time=dt: dt: duration;
-        inputSignal=sum(sin(2*pi*toneFrequency'*time), 1);
-        amp=10^(leveldBSPL/20)*28e-6;   % converts to Pascals (peak)
-        inputSignal=amp*inputSignal;
-        % apply ramps
-        % catch rampTime error
-        if rampDuration>0.5*duration, rampDuration=duration/2; end
-        rampTime=dt:dt:rampDuration;
-        ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ...
-            ones(1,length(time)-length(rampTime))];
-        inputSignal=inputSignal.*ramp;
-        ramp=fliplr(ramp);
-        inputSignal=inputSignal.*ramp;
-        % add silence
-        intialSilence= zeros(1,round(beginSilence/dt));
-        finalSilence= zeros(1,round(endSilence/dt));
-        inputSignal= [intialSilence inputSignal finalSilence];
-
-    case 'file'
-        %% file input simple or mixed
-        [inputSignal sampleRate]=wavread(fileName);
-        dt=1/sampleRate;
-        inputSignal=inputSignal(:,1);
-        targetRMS=20e-6*10^(leveldBSPL/20);
-        rms=(mean(inputSignal.^2))^0.5;
-        amp=targetRMS/rms;
-        inputSignal=inputSignal*amp;
-        intialSilence= zeros(1,round(0.1/dt));
-        finalSilence= zeros(1,round(0.2/dt));
-        inputSignal= [intialSilence inputSignal' finalSilence];
-end
-
-
-%% run the model
-tic
-fprintf('\n')
-disp(['Signal duration= ' num2str(length(inputSignal)/sampleRate)])
-disp([num2str(numChannels) ' channel model: ' AN_spikesOrProbability])
-disp('Computing ...')
-
-MAP1_14(inputSignal, sampleRate, BFlist, ...
-    MAPparamsName, AN_spikesOrProbability, paramChanges);
-
-
-%% the model run is now complete. Now display the results
-UTIL_showMAP(showMapOptions, paramChanges)
-
-if strcmp(signalType,'tones')
-    disp(['duration=' num2str(duration)])
-    disp(['level=' num2str(leveldBSPL)])
-    disp(['toneFrequency=' num2str(toneFrequency)])
-    global DRNLParams
-    disp(['attenuation factor =' ...
-        num2str(DRNLParams.rateToAttenuationFactor, '%5.3f') ])
-    disp(['attenuation factor (probability)=' ...
-        num2str(DRNLParams.rateToAttenuationFactorProb, '%5.3f') ])
-    disp(AN_spikesOrProbability)
-end
-disp(paramChanges)
-toc
-path(restorePath)
-
--- a/testPrograms/test_speechInNoise.m	Thu Oct 06 15:43:20 2011 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,215 +0,0 @@
-function test_speechInNoise
-% test_MAP1_14 is a general purpose test routine that can be adjusted to
-% test a number of different applications of MAP1_14
-%
-% A range of options are supplied in the early part of the program
-%
-% One use of the function is to create demonstrations; filenames <demoxx>
-%  to illustrate particular features
-%
-% #1
-% Identify the file (in 'MAPparamsName') containing the model parameters
-%
-% #2
-% Identify the kind of model required (in 'AN_spikesOrProbability').
-%  A full brainstem model (spikes) can be computed or a shorter model
-%  (probability) that computes only so far as the auditory nerve
-%
-% #3
-% Choose between a tone signal or file input (in 'signalType')
-%
-% #4
-% Set the signal rms level (in leveldBSPL)
-%
-% #5
-% Identify the channels in terms of their best frequencies in the vector
-%  BFlist.
-%
-% Last minute changes to the parameters fetched earlier can be made using
-%  the cell array of strings 'paramChanges'.
-%  Each string must have the same format as the corresponding line in the
-%  file identified in 'MAPparamsName'
-%
-% When the demonstration is satisfactory, freeze it by renaming it <demoxx>
-
-dbstop if error
-restorePath=path;
-addpath (['..' filesep 'MAP'],    ['..' filesep 'wavFileStore'], ...
-    ['..' filesep 'utilities'])
-
-%%  #1 parameter file name
-MAPparamsName='Normal';
-
-
-%% #2 probability (fast) or spikes (slow) representation
-AN_spikesOrProbability='spikes';
-%   or
-% AN_spikesOrProbability='probability';
-
-
-%% #3 pure tone, harmonic sequence or speech file input
-% signalType= 'tones';
-% sampleRate= 50000;
-% toneFrequency= 1000;            % or a pure tone (Hz8
-% duration=.5;                   % seconds
-% beginSilence=.2;
-% endSilence=0.5;
-
-% F0=210;
-% toneFrequency= F0:F0:8000;    % harmonic sequence (Hz)
-
-rampDuration=.005;              % raised cosine ramp (seconds)
-
-%   or
-signalType= 'file';
-fileName='twister_44kHz';
-beginSilence=1;
-endSilence=0.5;
-
-%% #4 rms level
-% signal details
-leveldBSPL= 60;                  % dB SPL
-
-% leveldBSPLNoise=leveldBSPL;
-leveldBSPLNoise=0;
-
-%% #5 number of channels in the model
-%   21-channel model (log spacing)
-numChannels=21;
-lowestBF=300; 	highestBF= 6000;
-BFlist=round(logspace(log10(lowestBF), log10(highestBF), numChannels));
-
-%   or specify your own channel BFs
-% numChannels=1;
-% BFlist=toneFrequency;
-
-
-%% #6 change model parameters
-% Parameter changes can be used to change one or more model parameters
-%  *after* the MAPparams file has been read
-% This example declares only one fiber type with a calcium clearance time
-% constant of 80e-6 s (HSR fiber) when the probability option is selected.
-% paramChanges={'AN_IHCsynapseParams.ANspeedUpFactor=5;', ...
-%     'IHCpreSynapseParams.tauCa=86e-6;'};
-
-% paramChanges={};
-
-paramChanges{1}='DRNLParams.MOCtau =.3;';
-paramChanges{2}='IHCpreSynapseParams.tauCa= IHCpreSynapseParams.tauCa(2);';
-paramChanges{3}='DRNLParams.rateToAttenuationFactorProb = 0.05;';
-paramChanges{3}='DRNLParams.rateToAttenuationFactorProb = 0;';
-
-% paramChanges={...
-%     'DRNLParams.MOCtau =.055;DRNLParams.rateToAttenuationFactor = 002;'};
-% paramChanges=...
-%     {'DRNLParams.MOCtau =.3; DRNLParams.rateToAttenuationFactor=0.0123;'};
-
-%% delare 'showMap' options to control graphical output
-showMapOptions.printModelParameters=1;   % prints all parameters
-showMapOptions.showModelOutput=1;       % plot of all stages
-showMapOptions.printFiringRates=1;      % prints stage activity levels
-showMapOptions.showACF=0;               % shows SACF (probability only)
-showMapOptions.showEfferent=1;          % tracks of AR and MOC
-showMapOptions.surfProbability=0;       % 2D plot of HSR response
-showMapOptions.surfSpikes=0;            % 2D plot of spikes histogram
-showMapOptions.ICrates=0;               % IC rates by CNtauGk
-
-% disable certain silly options
-if strcmp(AN_spikesOrProbability, 'spikes')
-    % avoid nonsensical options
-    showMapOptions.surfProbability=0;
-    showMapOptions.showACF=0;
-else
-    showMapOptions.surfSpikes=0;
-end
-if strcmp(signalType, 'file')
-    % needed for labeling plot
-    showMapOptions.fileName=fileName;
-else
-    showMapOptions.fileName=[];
-end
-
-%% Generate stimuli
-
-switch signalType
-    case 'tones'
-        %         inputSignal=createMultiTone(sampleRate, toneFrequency, ...
-        %             leveldBSPL, duration, rampDuration);
-        % Create pure tone stimulus
-        dt=1/sampleRate; % seconds
-        time=dt: dt: duration;
-        inputSignal=sum(sin(2*pi*toneFrequency'*time), 1);
-        amp=10^(leveldBSPL/20)*28e-6;   % converts to Pascals (peak)
-        inputSignal=amp*inputSignal;
-        
-        % apply ramps
-        % catch rampTime error
-        if rampDuration>0.5*duration, rampDuration=duration/2; end
-        rampTime=dt:dt:rampDuration;
-        ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ...
-            ones(1,length(time)-length(rampTime))];
-        inputSignal=inputSignal.*ramp;
-        ramp=fliplr(ramp);
-        inputSignal=inputSignal.*ramp;
-        
-        % add silences
-        intialSilence= zeros(1,round(beginSilence/dt));
-        finalSilence= zeros(1,round(endSilence/dt));
-        inputSignal= [intialSilence inputSignal finalSilence];
-        
-    case 'file'
-        %% file input simple or mixed
-        [inputSignal sampleRate]=wavread(fileName);
-        dt=1/sampleRate;
-        inputSignal=inputSignal(:,1);
-        targetRMS=20e-6*10^(leveldBSPL/20);
-        rms=(mean(inputSignal.^2))^0.5;
-        amp=targetRMS/rms;
-        inputSignal=inputSignal*amp;
-        
-        % add silences
-        intialSilence= zeros(1,round(beginSilence*sampleRate));
-        finalSilence= zeros(1,round(endSilence*sampleRate));
-        inputSignal= [intialSilence inputSignal' finalSilence];
-        
-        [inputNoise sampleRateN]=wavread('babble');
-        inputNoise=inputNoise(1:length(inputSignal));
-       inputNoise=inputNoise(:,1);
-        targetRMS=20e-6*10^(leveldBSPLNoise/20);
-        rms=(mean(inputNoise.^2))^0.5;
-        amp=targetRMS/rms;
-        inputNoise=inputNoise*amp;
-        inputSignal=inputSignal+inputNoise';
-        
-end
-
-
-%% run the model
-tic
-
-fprintf('\n')
-disp(['Signal duration= ' num2str(length(inputSignal)/sampleRate)])
-disp([num2str(numChannels) ' channel model'])
-disp('Computing ...')
-
-MAP1_14(inputSignal, sampleRate, BFlist, ...
-    MAPparamsName, AN_spikesOrProbability, paramChanges);
-
-
-%% the model run is now complete. Now display the results
-UTIL_showMAP(showMapOptions, paramChanges)
-disp(['duration=' num2str(duration)])
-disp(['level=' num2str(leveldBSPL)])
-disp(['noise level=' num2str(leveldBSPLNoise)])
-
-disp(['toneFrequency=' num2str(toneFrequency)])
-global DRNLParams
-disp(['attenuation factor =' ...
-    num2str(DRNLParams.rateToAttenuationFactor, '%5.3f') ])
-disp(['attenuation factor (probability)=' ...
-    num2str(DRNLParams.rateToAttenuationFactorProb, '%5.3f') ])
-disp(AN_spikesOrProbability)
-disp(paramChanges)
-toc
-path(restorePath)
-
--- a/userPrograms/Pavel_MAP1_14.m	Thu Oct 06 15:43:20 2011 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,189 +0,0 @@
-function Pavel_MAP1_14
-% test_MAP1_14 is a general purpose test routine that can be adjusted to
-% test a number of different applications of MAP1_14
-%
-% A range of options are supplied in the early part of the program
-%
-% One use of the function is to create demonstrations; filenames <demoxx>
-%  to illustrate particular features
-%
-% #1
-% Identify the file (in 'MAPparamsName') containing the model parameters
-%
-% #2
-% Identify the kind of model required (in 'AN_spikesOrProbability').
-%  A full brainstem model (spikes) can be computed or a shorter model
-%  (probability) that computes only so far as the auditory nerve
-%
-% #3
-% Choose between a tone signal or file input (in 'signalType')
-%
-% #4
-% Set the signal rms level (in leveldBSPL)
-%
-% #5
-% Identify the channels in terms of their best frequencies in the vector
-%  BFlist.
-%
-% Last minute changes to the parameters fetched earlier can be made using
-%  the cell array of strings 'paramChanges'.
-%  Each string must have the same format as the corresponding line in the
-%  file identified in 'MAPparamsName'
-%
-% When the demonstration is satisfactory, freeze it by renaming it <demoxx>
-
-restorePath=path;
-addpath (['..' filesep 'MAP'],    ['..' filesep 'wavFileStore'], ...
-    ['..' filesep 'utilities'])
-
-%%  #1 parameter file name
-MAPparamsName='Normal';
-
-
-%% #2 probability (fast) or spikes (slow) representation
-AN_spikesOrProbability='spikes';
-
-% or
-% AN_spikesOrProbability='probability';
-% NB probabilities are not corrected for refractory effects
-
-
-%% #3 pure tone, harmonic sequence or speech file input
-signalType= 'tones';
-sampleRate= 100000;
-duration=0.1;                 % seconds
-% toneFrequency= 250:250:8000;    % harmonic sequence (Hz)
-toneFrequency= 1000;            % or a pure tone (Hz8
-rampDuration=.005;              % seconds
-
-% or
-% signalType= 'file';
-% fileName='twister_44kHz';
-
-
-%% #4 rms level
-% signal details
-leveldBSPL= 30;                  % dB SPL
-
-
-%% #5 number of channels in the model
-%   21-channel model (log spacing)
-% numChannels=21;
-% lowestBF=250; 	highestBF= 8000;
-% BFlist=round(logspace(log10(lowestBF), log10(highestBF), numChannels));
-
-%   or specify your own channel BFs
-numChannels=1;
-BFlist=toneFrequency;
-
-
-%% #6 change model parameters
-paramChanges=[];
-
-% or
-% Parameter changes can be used to change one or more model parameters
-%  *after* the MAPparams file has been read
-% This example declares only one fiber type with a calcium clearance time
-% constant of 80e-6 s (HSR fiber) when the probability option is selected.
-% It also removes the speed up that normally takes place for AN spikes
-% It also increases the number of AN fibers computed to 500.
-paramChanges={...
-    'AN_IHCsynapseParams.ANspeedUpFactor=1;', ...
-    'IHCpreSynapseParams.tauCa=86e-6;',...
-    'AN_IHCsynapseParams.numFibers=	500;' };
-
-
-%% delare 'showMap' options to control graphical output
-global showMapOptions
-
-% or (example: show everything including an smoothed SACF output
-showMapOptions.printModelParameters=1;   % prints all parameters
-showMapOptions.showModelOutput=1;       % plot of all stages
-showMapOptions.printFiringRates=1;      % prints stage activity levels
-showMapOptions.showACF=0;               % shows SACF (probability only)
-showMapOptions.showEfferent=0;          % tracks of AR and MOC
-showMapOptions.surfProbability=0;       % 2D plot of HSR response 
-if strcmp(AN_spikesOrProbability, 'spikes')
-    % avoid nonsensical options
-    showMapOptions.surfProbability=0;
-    showMapOptions.showACF=0;
-end
-if strcmp(signalType, 'file')
-    % needed for labeling plot
-    showMapOptions.fileName=fileName;
-else
-    showMapOptions.fileName=[];
-end
-
-%% Generate stimuli
-
-dbstop if error
-restorePath=path;
-addpath (['..' filesep 'MAP'],    ['..' filesep 'wavFileStore'])
-switch signalType
-    case 'tones'
-        inputSignal=createMultiTone(sampleRate, toneFrequency, ...
-            leveldBSPL, duration, rampDuration);
-
-    case 'file'
-        %% file input simple or mixed
-        [inputSignal sampleRate]=wavread(fileName);
-        dt=1/sampleRate;
-        inputSignal=inputSignal(:,1);
-        targetRMS=20e-6*10^(leveldBSPL/20);
-        rms=(mean(inputSignal.^2))^0.5;
-        amp=targetRMS/rms;
-        inputSignal=inputSignal*amp;
-        silence= zeros(1,round(0.1/dt));
-        inputSignal= [silence inputSignal' silence];
-end
-
-
-%% run the model
-tic
-
-fprintf('\n')
-disp(['Signal duration= ' num2str(length(inputSignal)/sampleRate)])
-disp([num2str(numChannels) ' channel model'])
-disp('Computing ...')
-
-
-MAP1_14(inputSignal, sampleRate, BFlist, ...
-    MAPparamsName, AN_spikesOrProbability, paramChanges);
-toc
-
-% the model run is now complete. Now display the results
-% the model run is now complete. Now display the results
-disp(' param changes to list of parameters below')
-for i=1:length(paramChanges)
-    disp(paramChanges{i})
-end
-UTIL_showMAP(showMapOptions)
-
-toc
-path(restorePath)
-
-
-function inputSignal=createMultiTone(sampleRate, toneFrequency, ...
-    leveldBSPL, duration, rampDuration)
-% Create pure tone stimulus
-dt=1/sampleRate; % seconds
-time=dt: dt: duration;
-inputSignal=sum(sin(2*pi*toneFrequency'*time), 1);
-amp=10^(leveldBSPL/20)*28e-6;   % converts to Pascals (peak)
-inputSignal=amp*inputSignal;
-
-% apply ramps
-% catch rampTime error
-if rampDuration>0.5*duration, rampDuration=duration/2; end
-rampTime=dt:dt:rampDuration;
-ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ...
-    ones(1,length(time)-length(rampTime))];
-inputSignal=inputSignal.*ramp;
-ramp=fliplr(ramp);
-inputSignal=inputSignal.*ramp;
-
-% add 10 ms silence
-silence= zeros(1,round(0.03/dt));
-inputSignal= [silence inputSignal silence];
-
--- a/userPrograms/pitchModel_RM.m	Thu Oct 06 15:43:20 2011 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,242 +0,0 @@
-function pitchModel_RM
-% Modification of testMAP_14 to replicate the pitch model published
-%  in JASA 2006.
-%
-% test_MAP1_14 is a general purpose test routine that can be adjusted to
-% test a number of different applications of MAP1_14
-%
-% A range of options are supplied in the early part of the program
-%
-% One use of the function is to create demonstrations; filenames <demoxx>
-%  to illustrate particular features
-%
-% #1
-% Identify the file (in 'MAPparamsName') containing the model parameters
-%
-% #2
-% Identify the kind of model required (in 'AN_spikesOrProbability').
-%  A full brainstem model (spikes) can be computed or a shorter model
-%  (probability) that computes only so far as the auditory nerve
-%
-% #3
-% Choose between a tone signal or file input (in 'signalType')
-%
-% #4
-% Set the signal rms level (in leveldBSPL)
-%
-% #5
-% Identify the channels in terms of their best frequencies in the vector
-%  BFlist.
-%
-% Last minute changes to the parameters fetched earlier can be made using
-%  the cell array of strings 'paramChanges'.
-%  Each string must have the same format as the corresponding line in the
-%  file identified in 'MAPparamsName'
-%
-% When the demonstration is satisfactory, freeze it by renaming it <demoxx>
-
-dbstop if error
-restorePath=path;
-addpath (['..' filesep 'MAP'],    ['..' filesep 'wavFileStore'], ...
-    ['..' filesep 'utilities'])
-
-% Pitch model modification here
-global ICrate           % used to collect rate profile from showMAP temporary
-rates=[]; F0count=0;
-
-% F0s=[150 200 250];          % fundamental frequency
-% harmonics= 3:5;
-
-% F0s=[3000];          % fundamental frequency
-F0s=50:5:1000;
-harmonics= 1;
-% F0s=150;
-for F0=F0s
-    F0count=F0count+1;
-    
-
-%%  #1 parameter file name
-MAPparamsName='Normal';
-
-
-%% #2 probability (fast) or spikes (slow) representation
-AN_spikesOrProbability='spikes';
-
-% or
-% NB probabilities are not corrected for refractory effects
-% AN_spikesOrProbability='probability';
-
-
-%% #3 pure tone, harmonic sequence or speech file input
-signalType= 'tones';
-sampleRate= 50000;
-duration=0.50;                 % seconds
-% toneFrequency= 1000;            % or a pure tone (Hz8
-
-% F0=210;
-toneFrequency= F0*harmonics;  % harmonic sequence (Hz)
-
-rampDuration=.005;              % raised cosine ramp (seconds)
-
-% or
-
-% signalType= 'file';
-% fileName='twister_44kHz';
-
-
-%% #4 rms level
-% signal details
-leveldBSPL= 50;                  % dB SPL
-
-
-%% #5 number of channels in the model
-%   21-channel model (log spacing)
-numChannels=21;
-lowestBF=250; 	highestBF= 8000;
-BFlist=round(logspace(log10(lowestBF), log10(highestBF), numChannels));
-
-%   or specify your own channel BFs
-% numChannels=1;
-BFlist=toneFrequency;
-% BFlist=500;
-
-
-%% #6 change model parameters
-paramChanges=[];
-
-% or
-% Parameter changes can be used to change one or more model parameters
-%  *after* the MAPparams file has been read
-% This example declares only one fiber type with a calcium clearance time
-% constant of 80e-6 s (HSR fiber) when the probability option is selected.
-
-% paramChanges={'AN_IHCsynapseParams.ANspeedUpFactor=5;', ...
-%     'IHCpreSynapseParams.tauCa=86e-6;'};
-
-% paramChanges={'DRNLParams.rateToAttenuationFactorProb = 0;'};
-
-% paramChanges={'IHCpreSynapseParams.tauCa=86e-6;',
-%     'AN_IHCsynapseParams.numFibers=	1000;'};
-
-% fixed MOC attenuation(using negative factor)
-% paramChanges={'DRNLParams.rateToAttenuationFactorProb=-0.005;'};
-
-% slow the CN chopping rate
-% paramChanges={'IHCpreSynapseParams.tauCa= 70e-6;'...'
-%     'MacGregorMultiParams.tauGk=	[0.75e-3:.0001 : 3e-3];'...
-%     ' MacGregorParams.dendriteLPfreq=4000;'...
-%     'MacGregorParams.tauGk=	1e-4;'...
-%     'MacGregorParams.currentPerSpike=220e-8;'...
-% };
-paramChanges={...
-    'MacGregorMultiParams.currentPerSpike=25e-9;'...
-    'MacGregorMultiParams.tauGk=	[0.1e-3:.00005 : 1e-3];'...
-'MacGregorParams.currentPerSpike=40e-9;'...
-};
-
-%% delare 'showMap' options to control graphical output
-
-showMapOptions.printModelParameters=0;   % prints all parameters
-showMapOptions.showModelOutput=1;       % plot of all stages
-showMapOptions.printFiringRates=1;      % prints stage activity levels
-showMapOptions.showACF=0;               % shows SACF (probability only)
-showMapOptions.showEfferent=0;          % tracks of AR and MOC
-showMapOptions.surfProbability=0;       % 2D plot of HSR response 
-showMapOptions.surfSpikes=0;            % 2D plot of spikes histogram
-showMapOptions.ICrates=1;               % IC rates by CNtauGk
-
-% disable certain silly options
-if strcmp(AN_spikesOrProbability, 'spikes')
-    % avoid nonsensical options
-    showMapOptions.surfProbability=0;
-    showMapOptions.showACF=0;
-else
-    showMapOptions.surfSpikes=0;
-end
-if strcmp(signalType, 'file')
-    % needed for labeling plot
-    showMapOptions.fileName=fileName;
-else
-    showMapOptions.fileName=[];
-end
-
-%% Generate stimuli
-
-switch signalType
-    case 'tones'
-        inputSignal=createMultiTone(sampleRate, toneFrequency, ...
-            leveldBSPL, duration, rampDuration);
-
-    case 'file'
-        %% file input simple or mixed
-        [inputSignal sampleRate]=wavread(fileName);
-        dt=1/sampleRate;
-        inputSignal=inputSignal(:,1);
-        targetRMS=20e-6*10^(leveldBSPL/20);
-        rms=(mean(inputSignal.^2))^0.5;
-        amp=targetRMS/rms;
-        inputSignal=inputSignal*amp;
-        silence= zeros(1,round(0.1/dt));
-        inputSignal= [silence inputSignal' silence];
-end
-
-
-%% run the model
-tic
-
-fprintf('\n')
-disp(['Signal duration= ' num2str(length(inputSignal)/sampleRate)])
-disp([num2str(numChannels) ' channel model'])
-disp([num2str(F0) ' F0'])
-disp('Computing ...')
-
-MAP1_14(inputSignal, sampleRate, BFlist, ...
-    MAPparamsName, AN_spikesOrProbability, paramChanges);
-
-
-% the model run is now complete. Now display the results
-UTIL_showMAP(showMapOptions, paramChanges)
-
-%% pitch model Collect and analyse data
-% ICrate is global and computed in showMAP
-%  a vector of 'stage4' rates; one value for each tauCNGk
-rates=[rates; ICrate];
-figure(92), imagesc(rates)
-ylabel ('F0 no'), xlabel('tauGk')
-% figure(92), plot(rates), ylim([0 inf])
-
-h=figure(99); CNmovie(F0count)=getframe(h);
-figure(91), plot(rates'),ylim([0 inf])
-pause (0.1)
-path(restorePath)
-
-end
-%% show results
-toc
-figure(91), plot(F0s,rates'), xlabel('F0'), ylabel('rate'),ylim([0 inf])
-% figure(99),clf,movie(CNmovie,1,4)
-
-
-function inputSignal=createMultiTone(sampleRate, toneFrequency, ...
-    leveldBSPL, duration, rampDuration)
-% Create pure tone stimulus
-dt=1/sampleRate; % seconds
-time=dt: dt: duration;
-inputSignal=sum(sin(2*pi*toneFrequency'*time), 1);
-amp=10^(leveldBSPL/20)*28e-6;   % converts to Pascals (peak)
-inputSignal=amp*inputSignal;
-
-% apply ramps
-% catch rampTime error
-if rampDuration>0.5*duration, rampDuration=duration/2; end
-rampTime=dt:dt:rampDuration;
-ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ...
-    ones(1,length(time)-length(rampTime))];
-inputSignal=inputSignal.*ramp;
-ramp=fliplr(ramp);
-inputSignal=inputSignal.*ramp;
-
-% add 10 ms silence
-silence= zeros(1,round(0.005/dt));
-inputSignal= [silence inputSignal silence];
-
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userPrograms/runMAP1_14.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,181 @@
+function runMAP1_14
+% runMAP1_14 is a general purpose test routine that can be adjusted to
+% test a number of different applications of MAP1_14
+%
+% A range of options are supplied in the early part of the program
+%
+% #1
+% Identify the file (in 'MAPparamsName') containing the model parameters
+%
+% #2
+% Identify the kind of model required (in 'AN_spikesOrProbability').
+%  A full brainstem model ('spikes') can be computed or a shorter model
+%  ('probability') that computes only so far as the auditory nerve
+%
+% #3
+% Choose between a tone signal or file input (in 'signalType')
+%
+% #4
+% Set the signal rms level (in leveldBSPL)
+%
+% #5
+% Identify the channels in terms of their best frequencies in the vector
+%  BFlist.
+%
+% Last minute changes to the parameters can be made using
+%  the cell array of strings 'paramChanges'.
+%  Each string must have the same format as the corresponding line in the
+%  file identified in 'MAPparamsName'
+
+dbstop if error
+restorePath=path;
+addpath (['..' filesep 'MAP'],    ['..' filesep 'wavFileStore'], ...
+    ['..' filesep 'utilities'])
+
+%%  #1 parameter file name
+MAPparamsName='Normal';
+
+
+%% #2 probability (fast) or spikes (slow) representation: select one
+% AN_spikesOrProbability='spikes';
+%   or
+AN_spikesOrProbability='probability';
+
+
+%% #3 A. pure tone, B. harmonic sequence or C. speech file input
+% comment out unwanted code
+
+% A. tone
+sampleRate= 441000;
+signalType= 'tones';
+toneFrequency= 5000;            % or a pure tone (Hz)
+duration=0.500;                 % seconds
+beginSilence=0.050;               
+endSilence=0.050;                  
+rampDuration=.005;              % raised cosine ramp (seconds)
+
+%   or
+% B. harmonic tone (Hz) - useful to demonstrate a broadband sound
+% sampleRate= 44100;
+% signalType= 'tones';
+% toneFrequency= F0:F0:8000;    
+% duration=0.500;                 % seconds
+% beginSilence=0.250;               
+% endSilence=0.250;                  
+% F0=210;
+% rampDuration=.005;              % raised cosine ramp (seconds)
+
+%   or
+% C. signalType= 'file';
+% fileName='twister_44kHz';
+
+%% #4 rms level
+% signal details
+leveldBSPL= 70;                  % dB SPL (80 for Lieberman)
+
+%% #5 number of channels in the model
+%   21-channel model (log spacing)
+numChannels=21;
+lowestBF=250; 	highestBF= 6000;
+BFlist=round(logspace(log10(lowestBF), log10(highestBF), numChannels));
+
+%   or specify your own channel BFs
+% numChannels=1;
+% BFlist=toneFrequency;
+
+
+%% #6 change model parameters
+
+paramChanges={};
+
+% Parameter changes can be used to change one or more model parameters
+%  *after* the MAPparams file has been read
+% This example declares only one fiber type with a calcium clearance time
+% constant of 80e-6 s (HSR fiber) when the probability option is selected.
+% paramChanges={'AN_IHCsynapseParams.ANspeedUpFactor=5;', ...
+%     'IHCpreSynapseParams.tauCa=86e-6; '};
+
+
+
+%% delare 'showMap' options to control graphical output
+% see UTIL_showMAP for more options
+showMapOptions.printModelParameters=1;   % prints all parameters
+showMapOptions.showModelOutput=1;       % plot of all stages
+showMapOptions.printFiringRates=1;      % prints stage activity levels
+showMapOptions.showEfferent=1;          % tracks of AR and MOC
+showMapOptions.surfProbability=1;       % 2D plot of HSR response 
+
+if strcmp(signalType, 'file')
+    % needed for labeling plot
+    showMapOptions.fileName=fileName;
+else
+    showMapOptions.fileName=[];
+end
+
+%% Generate stimuli
+switch signalType
+    case 'tones'
+        % Create pure tone stimulus
+        dt=1/sampleRate; % seconds
+        time=dt: dt: duration;
+        inputSignal=sum(sin(2*pi*toneFrequency'*time), 1);
+        amp=10^(leveldBSPL/20)*28e-6;   % converts to Pascals (peak)
+        inputSignal=amp*inputSignal;
+        % apply ramps
+        % catch rampTime error
+        if rampDuration>0.5*duration, rampDuration=duration/2; end
+        rampTime=dt:dt:rampDuration;
+        ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ...
+            ones(1,length(time)-length(rampTime))];
+        inputSignal=inputSignal.*ramp;
+        ramp=fliplr(ramp);
+        inputSignal=inputSignal.*ramp;
+        % add silence
+        intialSilence= zeros(1,round(beginSilence/dt));
+        finalSilence= zeros(1,round(endSilence/dt));
+        inputSignal= [intialSilence inputSignal finalSilence];
+
+    case 'file'
+        %% file input simple or mixed
+        [inputSignal sampleRate]=wavread(fileName);
+        dt=1/sampleRate;
+        inputSignal=inputSignal(:,1);
+        targetRMS=20e-6*10^(leveldBSPL/20);
+        rms=(mean(inputSignal.^2))^0.5;
+        amp=targetRMS/rms;
+        inputSignal=inputSignal*amp;
+        intialSilence= zeros(1,round(0.1/dt));
+        finalSilence= zeros(1,round(0.2/dt));
+        inputSignal= [intialSilence inputSignal' finalSilence];
+end
+
+
+%% run the model
+tic
+fprintf('\n')
+disp(['Signal duration= ' num2str(length(inputSignal)/sampleRate)])
+disp([num2str(numChannels) ' channel model: ' AN_spikesOrProbability])
+disp('Computing ...')
+
+MAP1_14(inputSignal, sampleRate, BFlist, ...
+    MAPparamsName, AN_spikesOrProbability, paramChanges);
+
+
+%% the model run is now complete. Now display the results
+UTIL_showMAP(showMapOptions, paramChanges)
+
+if strcmp(signalType,'tones')
+    disp(['duration=' num2str(duration)])
+    disp(['level=' num2str(leveldBSPL)])
+    disp(['toneFrequency=' num2str(toneFrequency)])
+    global DRNLParams
+    disp(['attenuation factor =' ...
+        num2str(DRNLParams.rateToAttenuationFactor, '%5.3f') ])
+    disp(['attenuation factor (probability)=' ...
+        num2str(DRNLParams.rateToAttenuationFactorProb, '%5.3f') ])
+    disp(AN_spikesOrProbability)
+end
+disp(paramChanges)
+toc
+path(restorePath)
+
Binary file userProgramsASRforDummies/ASR_suite_for_dummies.pdf has changed
Binary file userProgramsASRforDummies/EssexAid_DEMO.pdf has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsASRforDummies/Exp_Ray_1.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,167 @@
+function Exp_Ray_1(isMasterNode)
+
+% Some description of the experiment goes here
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Set up the basic folders
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+expName = 'scrap6_with_eff';
+dataFolderPrefix = 'featR';
+if isunix
+    expFolderPrefix = '/scratch/nrclark/exps/';
+else
+    expFolderPrefix = 'D:\Exps';
+end
+
+expFolder = fullfile(expFolderPrefix,expName);
+hmmFolder = fullfile(expFolder,'hmm');
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Sort out the training (LEARNING) condition
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+learnFolder = fullfile(expFolder,'featL');
+
+xL = cJob('L', learnFolder);
+
+xL.participant = 'Normal';
+xL.MAPparamChanges= {'DRNLParams.rateToAttenuationFactorProb=0;', 'OMEParams.rateToAttenuationFactorProb=0;' };
+xL.MAPparamChanges= {};
+
+xL.noiseLevToUse   =  -200;
+xL.noiseLevToUse   =  20;
+xL.speechLevToUse  =  50;
+
+xL.MAPopHSR = 1;
+xL.MAPopMSR = 0;
+xL.MAPopLSR = 0;
+
+
+xL.numCoeff = 14;
+xL.removeEnergyStatic = 0;
+
+%%%%% Group of params that will influence simulation run time %%%%%%%
+xL.numWavs = 512; %MAX=8440
+testWavs = 48; %MAX = 358
+nzLevel = [-200 40 60];
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+xL.noisePreDur = 1;
+xL.noisePostDur = 0.1;
+xL.truncateDur  = xL.noisePreDur-0.1; 
+
+xL.noiseName = '20TalkerBabble';
+
+if isMasterNode && ~isdir(xL.opFolder)
+    mkdir(xL.opFolder);
+    xL = xL.assignFiles;
+    xL.storeSelf; % This is a call to a member function and is not a pointless line of code!
+end
+
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Sort out the testing (RECOGNITION) conditions
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+recConditions = numel(nzLevel);
+
+tmpIdx=0;
+for nn = 0*recConditions+1:1*recConditions    
+    tmpIdx=tmpIdx+1;
+    xR{nn} = xL; %simply copy the "Learn" object and change it a bit below
+    recFolder = fullfile(expFolder,[dataFolderPrefix num2str(nn)]);
+    xR{nn}.opFolder = recFolder;    
+    
+    %These are the interesting differences between training and testing
+    xR{nn}.numWavs = testWavs; %MAX = 358
+    xR{nn}.noiseLevToUse = nzLevel(tmpIdx);
+    %xR{nn}.MAPparamChanges= {'DRNLParams.rateToAttenuationFactorProb=0;'};
+        
+    %Now just to wrap it up ready for processing
+    if isMasterNode && ~isdir(xR{nn}.opFolder)
+        mkdir(xR{nn}.opFolder);
+        xR{nn} = xR{nn}.assignWavPaths('R');
+        xR{nn} = xR{nn}.assignFiles;
+        xR{nn}.storeSelf;
+    end
+end
+
+% tmpIdx=0;
+% for nn = 1*recConditions+1:2*recConditions    
+%     tmpIdx=tmpIdx+1;
+%     xR{nn} = xL; %simply copy the "Learn" object and change it a bit below
+%     recFolder = fullfile(expFolder,[dataFolderPrefix num2str(nn)]);
+%     xR{nn}.opFolder = recFolder;    
+%     
+%     %These are the interesting differences between training and testing
+%     xR{nn}.numWavs = testWavs; %MAX = 358
+%     xR{nn}.noiseLevToUse = nzLevel(tmpIdx);
+%     xR{nn}.MAPparamChanges= {'DRNLParams.rateToAttenuationFactorProb=-10^(-10/20);'};
+%     
+%     
+%     %Now just to wrap it up ready for processing
+%     if isMasterNode && ~isdir(xR{nn}.opFolder)
+%         mkdir(xR{nn}.opFolder);
+%         xR{nn} = xR{nn}.assignWavPaths('R');
+%         xR{nn} = xR{nn}.assignFiles;
+%         xR{nn}.storeSelf;
+%     end
+% end
+
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% ** Generate features **
+% This is the time consuming, processing intensive portion of the program.
+% Nodes that are not the master node are only interested in the opFolder
+% member of the jobjects.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+worker(xL.opFolder);
+maxConds = nn;
+if ~isMasterNode %dont bother wasting master node effort on generating testing features (for now)
+    for nn = 1:maxConds
+        worker(xR{nn}.opFolder);
+    end
+end
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Train and test the recogniser - a job for the master node only
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isMasterNode    
+    while(~all(xL.todoStatus==2))        
+        disp('Waiting on straggler nodes to complete their jobs before HMM is trained . . .')
+        pause(30); %Wait for 30 seconds before looking again
+        xL.lockJobList;
+        xL = xL.loadSelf; %Reload incase changed
+        xL.unlockJobList;
+    end
+    y = cHMM(hmmFolder);    
+    y.numCoeff = (xL.numCoeff-logical(xL.removeEnergyStatic)) * 3;
+    y.createSCP(xL.opFolder)
+    y.createMLF(xL.opFolder)
+    y.train(xL.opFolder) %This node can be busy training, even if other jobs are being processed for testing
+    
+    % ALLOW MASTER NODE TO MUCK IN WITH GENERATING TESTING FEATURES ONCE
+    % HMM HAS BEEN TRAINED
+    for nn = 1:maxConds
+        worker(xR{nn}.opFolder);
+    end    
+    
+    xR{end}.lockJobList;
+    xR{end} = xR{end}.loadSelf; %Reload changes
+    xR{end}.unlockJobList;
+    while(~all(xR{end}.todoStatus==2))        
+        disp('Waiting on straggler nodes to complete their jobs before HMM is tested . . .')
+        pause(30); %Wait for 30 seconds before looking again
+        xR{end}.lockJobList;
+        xR{end} = xR{end}.loadSelf; %Reload incase changed
+        xR{end}.unlockJobList;
+    end
+      
+    for nn = 1:maxConds
+        y.createSCP(xR{nn}.opFolder);
+        y.test(xR{nn}.opFolder);
+    end
+    
+    %Show all of the scores in the command window at the end
+    for nn = 1:maxConds
+        y.score(xR{nn}.opFolder);
+    end
+end
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsASRforDummies/Exp_Tutorial_1.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,165 @@
+function Exp_Tutorial_1(isMasterNode)
+
+% Some description of the experiment goes here
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Set up the basic folders
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+expName = 'Tutorial';
+dataFolderPrefix = 'featR';
+if isunix
+    expFolderPrefix = '/scratch/nrclark/exps/';
+else
+    expFolderPrefix = 'D:\Exps';
+end
+
+expFolder = fullfile(expFolderPrefix,expName);
+hmmFolder = fullfile(expFolder,'hmm');
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Sort out the training (LEARNING) condition
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+learnFolder = fullfile(expFolder,'featL');
+
+xL = cJob('L', learnFolder);
+
+xL.participant = 'Normal';
+xL.MAPparamChanges= {'DRNLParams.rateToAttenuationFactorProb=0;', 'OMEParams.rateToAttenuationFactorProb=0;' };
+
+xL.noiseLevToUse   =  -200;
+xL.speechLevToUse  =  60;
+
+xL.MAPopHSR = 1;
+xL.MAPopMSR = 0;
+xL.MAPopLSR = 0;
+
+
+xL.numCoeff = 14;
+xL.removeEnergyStatic = 0;
+
+%%%%% Group of params that will influence simulation run time %%%%%%%
+xL.numWavs = 12; %MAX=8440
+testWavs = 6; %MAX = 358
+nzLevel = [-200 40:10:70];
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+xL.noisePreDur = 1;
+xL.noisePostDur = 0.1;
+xL.truncateDur  = xL.noisePreDur-0.1; 
+
+xL.noiseName = 'pink_demo';
+
+if isMasterNode && ~isdir(xL.opFolder)
+    mkdir(xL.opFolder);
+    xL = xL.assignFiles;
+    xL.storeSelf; % This is a call to a member function and is not a pointless line of code!
+end
+
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Sort out the testing (RECOGNITION) conditions
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+recConditions = numel(nzLevel);
+
+tmpIdx=0;
+for nn = 0*recConditions+1:1*recConditions    
+    tmpIdx=tmpIdx+1;
+    xR{nn} = xL; %simply copy the "Learn" object and change it a bit below
+    recFolder = fullfile(expFolder,[dataFolderPrefix num2str(nn)]);
+    xR{nn}.opFolder = recFolder;    
+    
+    %These are the interesting differences between training and testing
+    xR{nn}.numWavs = testWavs; %MAX = 358
+    xR{nn}.noiseLevToUse = nzLevel(tmpIdx);
+    xR{nn}.MAPparamChanges= {'DRNLParams.rateToAttenuationFactorProb=0;'};
+        
+    %Now just to wrap it up ready for processing
+    if isMasterNode && ~isdir(xR{nn}.opFolder)
+        mkdir(xR{nn}.opFolder);
+        xR{nn} = xR{nn}.assignWavPaths('R');
+        xR{nn} = xR{nn}.assignFiles;
+        xR{nn}.storeSelf;
+    end
+end
+
+tmpIdx=0;
+for nn = 1*recConditions+1:2*recConditions    
+    tmpIdx=tmpIdx+1;
+    xR{nn} = xL; %simply copy the "Learn" object and change it a bit below
+    recFolder = fullfile(expFolder,[dataFolderPrefix num2str(nn)]);
+    xR{nn}.opFolder = recFolder;    
+    
+    %These are the interesting differences between training and testing
+    xR{nn}.numWavs = testWavs; %MAX = 358
+    xR{nn}.noiseLevToUse = nzLevel(tmpIdx);
+    xR{nn}.MAPparamChanges= {'DRNLParams.rateToAttenuationFactorProb=-10^(-10/20);'};
+    
+    
+    %Now just to wrap it up ready for processing
+    if isMasterNode && ~isdir(xR{nn}.opFolder)
+        mkdir(xR{nn}.opFolder);
+        xR{nn} = xR{nn}.assignWavPaths('R');
+        xR{nn} = xR{nn}.assignFiles;
+        xR{nn}.storeSelf;
+    end
+end
+
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% ** Generate features **
+% This is the time consuming, processing intensive portion of the program.
+% Nodes that are not the master node are only interested in the opFolder
+% member of the jobjects.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+worker(xL.opFolder);
+maxConds = nn;
+if ~isMasterNode %dont bother wasting master node effort on generating testing features (for now)
+    for nn = 1:maxConds
+        worker(xR{nn}.opFolder);
+    end
+end
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Train and test the recogniser - a job for the master node only
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isMasterNode    
+    while(~all(xL.todoStatus==2))        
+        disp('Waiting on straggler nodes to complete their jobs before HMM is trained . . .')
+        pause(30); %Wait for 30 seconds before looking again
+        xL.lockJobList;
+        xL = xL.loadSelf; %Reload incase changed
+        xL.unlockJobList;
+    end
+    y = cHMM(hmmFolder);    
+    y.numCoeff = (xL.numCoeff-logical(xL.removeEnergyStatic)) * 3;
+    y.createSCP(xL.opFolder)
+    y.createMLF(xL.opFolder)
+    y.train(xL.opFolder) %This node can be busy training, even if other jobs are being processed for testing
+    
+    % ALLOW MASTER NODE TO MUCK IN WITH GENERATING TESTING FEATURES ONCE
+    % HMM HAS BEEN TRAINED
+    for nn = 1:maxConds
+        worker(xR{nn}.opFolder);
+    end    
+    
+    xR{end}.lockJobList;
+    xR{end} = xR{end}.loadSelf; %Reload changes
+    xR{end}.unlockJobList;
+    while(~all(xR{end}.todoStatus==2))        
+        disp('Waiting on straggler nodes to complete their jobs before HMM is tested . . .')
+        pause(30); %Wait for 30 seconds before looking again
+        xR{end}.lockJobList;
+        xR{end} = xR{end}.loadSelf; %Reload incase changed
+        xR{end}.unlockJobList;
+    end
+      
+    for nn = 1:maxConds
+        y.createSCP(xR{nn}.opFolder);
+        y.test(xR{nn}.opFolder);
+    end
+    
+    %Show all of the scores in the command window at the end
+    for nn = 1:maxConds
+        y.score(xR{nn}.opFolder);
+    end
+end
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsASRforDummies/Exp_Tutorial_2.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,173 @@
+function Exp_Tutorial_2(isMasterNode)
+
+% This tutorial recycles a HMM
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Set up the basic experiment parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+expName = 'Tutorial';
+dataFolderPrefix = 'recycle_featR';
+if isunix
+    expFolderPrefix = '/scratch/nrclark/exps/';
+else
+    expFolderPrefix = 'D:\Exps';
+end
+
+% expFolderPrefix = pwd;
+expFolder = fullfile(expFolderPrefix,expName);
+hmmFolder = fullfile(expFolder,'hmm');
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Sort out the training (LEARNING) condition
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+learnFolder = fullfile(expFolder,'featL');
+
+xL = cJob('L', learnFolder);
+
+xL.participant = 'Normal';
+xL.MAPparamChanges= {'DRNLParams.rateToAttenuationFactorProb=0;', 'OMEParams.rateToAttenuationFactorProb=0;' };
+
+xL.noiseLevToUse   =  -200;
+xL.speechLevToUse  =  60;
+
+xL.MAPopHSR = 1;
+xL.MAPopMSR = 0;
+xL.MAPopLSR = 0;
+
+
+xL.numCoeff = 14;
+xL.removeEnergyStatic = 0;
+
+%%%%% Group of params that will influence simulation run time %%%%%%%
+xL.numWavs = 12; %MAX=8440
+testWavs = 6; %MAX = 358
+nzLevel = [-200 40:10:70];
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+xL.noisePreDur = 1;
+xL.noisePostDur = 0.1;
+xL.truncateDur  = xL.noisePreDur-0.1; 
+xL.noiseName = 'pink_demo';
+
+
+% if isMasterNode && ~isdir(xL.opFolder)
+%     mkdir(xL.opFolder);
+%     xL = xL.assignFiles;
+%     xL.storeSelf;
+% end
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Sort out the testing (RECOGNITION) conditions
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+recConditions = numel(nzLevel);
+
+tmpIdx=0;
+for nn = 0*recConditions+1:1*recConditions    
+    tmpIdx=tmpIdx+1;
+    xR{nn} = xL; %simply copy the "Learn" object and change it a bit below
+    recFolder = fullfile(expFolder,[dataFolderPrefix num2str(nn)]);
+    xR{nn}.opFolder = recFolder;    
+    
+    %These are the interesting differences between training and testing
+    xR{nn}.numWavs = testWavs; %MAX = 358
+    xR{nn}.noiseLevToUse = nzLevel(tmpIdx); 
+    xR{nn}.MAPparamChanges= {'DRNLParams.a=400;'};
+
+    
+    %Now just to wrap it up ready for processing
+    if isMasterNode && ~isdir(xR{nn}.opFolder)
+        mkdir(xR{nn}.opFolder);
+        xR{nn} = xR{nn}.assignWavPaths('R');
+        xR{nn} = xR{nn}.assignFiles;
+        xR{nn}.storeSelf;
+    end
+end
+
+tmpIdx=0;
+for nn = 1*recConditions+1:2*recConditions    
+    tmpIdx=tmpIdx+1;
+    xR{nn} = xL; %simply copy the "Learn" object and change it a bit below
+    recFolder = fullfile(expFolder,[dataFolderPrefix num2str(nn)]);
+    xR{nn}.opFolder = recFolder;    
+    
+    %These are the interesting differences between training and testing
+    xR{nn}.numWavs = testWavs; %MAX = 358
+    xR{nn}.noiseLevToUse = nzLevel(tmpIdx); 
+    xR{nn}.MAPparamChanges= {'DRNLParams.a=400;'};
+    
+    xR{nn}.mainGain = [27.2013;   26.0797;   26.0939;   26.7997;   26.0520];  
+    xR{nn}.TCdBO    = [37;   37;   37;   37;   37];      %Compression thresholds (in dB OUTPUT from 2nd filt)
+    xR{nn}.TMdBO    = [20;   20;   20;   20;   20];      %MOC thresholds (in dB OUTPUT from 2nd filt)
+    xR{nn}.ARthresholddB = 85;       % dB SPL (input signal level) =>200 to disable
+    xR{nn}.MOCtau = 1;
+    xR{nn}.useAid = 1;
+    
+    %Now just to wrap it up ready for processing
+    if isMasterNode && ~isdir(xR{nn}.opFolder)
+        mkdir(xR{nn}.opFolder);
+        xR{nn} = xR{nn}.assignWavPaths('R');
+        xR{nn} = xR{nn}.assignFiles;
+        xR{nn}.storeSelf;
+    end
+end
+
+
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% ** Generate features **
+% This is the time consuming, processing intensive portion of the program.
+% Nodes that are not the master node are only interested in the opFolder
+% member of the jobjects.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% worker(xL.opFolder);
+maxConds = nn;
+if ~isMasterNode %dont bother wasting master node effort on generating testing features (for now)
+    for nn = 1:maxConds
+        worker(xR{nn}.opFolder);
+    end
+end
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Train and test the recogniser - a job for the master node only
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isMasterNode    
+%     while(~all(xL.todoStatus==2))        
+%         disp('Waiting on straggler nodes to complete their jobs before HMM is trained . . .')
+%         pause(30); %Wait for 30 seconds before looking again
+%         xL.lockJobList;
+%         xL = xL.loadSelf; %Reload incase changed
+%         xL.unlockJobList;
+%     end
+    y = cHMM(hmmFolder);    
+    y.numCoeff = 14*3;
+%     y.createSCP(xL.opFolder)
+%     y.createMLF(xL.opFolder)
+%     y.train(xL.opFolder) %This node can be busy training, even if other jobs are being processed for testing
+    
+    % ALLOW MASTER NODE TO MUCK IN WITH GENERATING TESTING FEATURES ONCE
+    % HMM HAS BEEN TRAINED
+    for nn = 1:maxConds
+        worker(xR{nn}.opFolder);
+    end    
+    
+    xR{end}.lockJobList;
+    xR{end} = xR{end}.loadSelf; %Reload changes
+    xR{end}.unlockJobList;
+    while(~all(xR{end}.todoStatus==2))        
+        disp('Waiting on straggler nodes to complete their jobs before HMM is tested . . .')
+        pause(30); %Wait for 30 seconds before looking again
+        xR{end}.lockJobList;
+        xR{end} = xR{end}.loadSelf; %Reload incase changed
+        xR{end}.unlockJobList;
+    end
+      
+    for nn = 1:maxConds
+        y.createSCP(xR{nn}.opFolder);
+        y.test(xR{nn}.opFolder);
+    end
+    
+    %Show all of the scores in the command window at the end
+    for nn = 1:maxConds
+        y.score(xR{nn}.opFolder);
+    end
+end
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsASRforDummies/MAPwrap.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,14 @@
+% This function wraps up whatever version of MAP I want to call. It is
+% implemented partly because I want to avoid messing with jobject too much
+% and mostly because I dont want to declare globals in my class.
+
+function [myANprobRateOutput, mydt, myBF] = MAPwrap(stimulus, sampleRate, BFlist, participant, AN_spikesOrProbability, paramChanges)
+
+
+global ANprobRateOutput  dt BFlist
+% disp(20*log10(sqrt(mean(stimulus.^2))/20e-6))
+MAP1_14(stimulus, sampleRate, BFlist, participant, AN_spikesOrProbability, paramChanges);
+% disp(20*log10(sqrt(mean(stimulus.^2))/20e-6))
+myANprobRateOutput   = ANprobRateOutput;
+mydt = dt;
+myBF = BFlist;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsASRforDummies/cEssexAid.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,651 @@
+classdef cEssexAid
+    %ESSEXAID_WRAPCLASS Wrapper for the EssexAid - Nick Clark July 2011
+    %   This class wraps up the EssexAid algorithm function that processes
+    %   each block of samples. This wrapper closely emulates the GUI used
+    %   in the lab and runs stimuli through the exact same algorithm used
+    %   in the lab. It even includes a helper function to generate C code
+    %   from the algorithm for use in a real-time framework.
+
+    
+    %% *********************************************************
+    %  properties                      _   _
+    %                                 | | (_)
+    %  _ __  _ __ ___  _ __   ___ _ __| |_ _  ___  ___
+    % | '_ \| '__/ _ \| '_ \ / _ \ '__| __| |/ _ \/ __|
+    % | |_) | | | (_) | |_) |  __/ |  | |_| |  __/\__ \
+    % | .__/|_|  \___/| .__/ \___|_|   \__|_|\___||___/
+    % | |             | |
+    % |_|             |_|
+    %************************************************************
+    
+    %% **********************************************************
+    % Public properties - can be set by user
+    %************************************************************
+    properties(Access = public)
+        sr         = 48e3;
+        numSamples = 1024; %MAX=6912, LAB_USE=48
+        stimulusUSER                   
+        
+        %------------------------------------------------------------------
+        % Params for audiometric freqs 250, 500, 1000, 2000, 4000, 8000 Hz
+        %------------------------------------------------------------------
+        audiometry_dB= [ 0;    0;    0;    0;    0;   0];   %Pure tone threshold in dB SPL
+        mainGain_dB  = [ 0;    0;    0;    0;    0;   0];   %Gain applied at audiometric frequencies
+        TC_dBHL      = [40;   40;   40;   40;   40;  40];   %Compression thresholds (in dB HL from 2nd filt)
+        TM_dBHL      = [10;   10;   10;   10;   10;  10];   %MOC thresholds (in dB OUTPUT from 2nd filt)
+        DRNLc        = [ 0.2;  0.2;  0.2;  0.2;  0.2; 0.2]; %Compression exponent at audiometric frequencies
+        
+        %------------------------------------------------------------------
+        % Dynamic compression properties
+        %------------------------------------------------------------------
+        ARtau = 60e-3;       %decay time constant
+        ARthreshold_dB = 85; %dB SPL (input signal level) =>200 to disable
+        MOCtau = 450e-3;     %Time constant in Seconds
+        MOCfactor = 0.5;     %dB attenuation applied to the input per dB exceeding output threshold
+        
+        %------------------------------------------------------------------
+        % Band filtering properties
+        %------------------------------------------------------------------
+        bwOct = 1/2; %1/1, 1/2, 1/3, 1/4, 1/5
+        filterOrder = 2 %BUTTER=2, GTF=3
+        useGTF = false; %If false, revert to butterworth
+    end
+    
+    %% **********************************************************
+    % Read only properties that are not dependent
+    %************************************************************
+    properties(SetAccess = private)          
+        MOCrecord
+    end
+    
+    %% **********************************************************
+    % Constant properties 
+    %************************************************************
+    properties(Constant = true, Hidden = true)  
+        numAudiometricFreqs = 6;
+    end
+    
+    %% **********************************************************
+    % Dependent visable properties - calculated at runtime
+    %************************************************************
+    properties(Dependent = true, Hidden = false)
+        channelBFs %= 250 * 2.^((0:fNmax)'*params.bwOct);        
+        numChannels %= numel(channelBFs);        
+        aidOPnice %aid output reformatted to be exactly the same dimensions as the input stimulus                               
+    end
+    
+    %% **********************************************************
+    % Dependent invisable properties - calculated at runtime
+    %************************************************************
+    properties(Dependent = true, Hidden = true)
+        TC_dBO_INTERP % Compression threshold in terms of 2nd filter o/p in dB SPL
+        TM_dBO_INTERP % MOC threshold in terms of 2nd filter o/p in dB SPL                    
+        bwOct_INTERP
+        DRNLb_INTERP %=  ( 2e-5 .* 10.^(TCdBO/20)) .^ (1-DRNLc)  ; 
+        DRNLc_INTERP               
+        mainGain_INTERP %Interp'd and in linear units 
+        
+        ARthresholdPa %=  20e-6*10^(ARthreshold_dB/20);% Pa thresh for triggering AR        
+        stimulusINTERNAL %input stimulus in correct format for the Aid algo
+    end
+    
+    %% **********************************************************
+    % Protected properties - The user never needs to set
+    %************************************************************
+    properties(Access = protected)  
+        aidOP
+        emlc_z
+        
+        %--------------------------------------------------------------
+        % ENUMERATIONS USED IN THE FRAME PROCESSOR
+        %--------------------------------------------------------------
+        enumC_ARb  = 0;
+        enumC_ARa  = 2;
+        enumC_MOCb = 4;
+        enumC_MOCa = 6;
+        
+        % enumC_BPb1 = 8;
+        % enumC_BPa1 = 13;
+        % enumC_BPb2 = 18;
+        % enumC_BPa2 = 23;
+        % enumC_BPb3 = 28;
+        % enumC_BPa3 = 33;
+        % enumC_BPb4 = 38;
+        % enumC_BPa4 = 43;
+        
+        enumS_AR  = 0;
+        
+        % enumS_MOC1  = 1;
+        % enumS_BPin_1_1 = 2;
+        % enumS_BPin_2_1 = 6;
+        % enumS_BPout_1_1 = 10;
+        % enumS_BPout_2_1 = 14;
+        %
+        % enumS_MOC2 = 18;
+        % enumS_BPin_1_2 = 19;
+        % enumS_BPin_2_2 = 23;
+        % enumS_BPout_1_2 = 27;
+        % enumS_BPout_2_2 = 31;
+        % ...
+    end
+        
+    %% **********************************************************
+    % methods        _   _               _
+    %               | | | |             | |
+    % _ __ ___   ___| |_| |__   ___   __| |___
+    %| '_ ` _ \ / _ \ __| '_ \ / _ \ / _` / __|
+    %| | | | | |  __/ |_| | | | (_) | (_| \__ \
+    %|_| |_| |_|\___|\__|_| |_|\___/ \__,_|___/
+    %************************************************************
+    
+    methods
+        %% **********************************************************
+        % Constructor
+        %************************************************************
+        function obj = EssexAid_WrapClass(sr, stimulus)          
+            
+            if nargin > 0
+                obj.sr = sr;
+            end
+            
+            if nargin > 1
+                obj.stimulusUSER = stimulus;
+            else         
+                obj.stimulusUSER = obj.pipSequence(obj.sr);
+            end
+        end
+        
+        %% **********************************************************
+        % Get method for channelBFs 
+        %************************************************************
+        function value = get.channelBFs(obj)
+            fNmax = 5/obj.bwOct;
+            value = 250 * 2.^((0:fNmax)'*obj.bwOct);
+        end
+        
+        %% **********************************************************
+        % Get method for numChannels 
+        %************************************************************
+        function value = get.numChannels(obj)
+            value = numel(obj.channelBFs);
+        end
+        
+        %% **********************************************************
+        % Get method for ARthresholdPa 
+        %************************************************************
+        function value = get.ARthresholdPa(obj)
+            value = 20e-6*10^(obj.ARthreshold_dB/20);% Pa thresh for triggering AR
+        end
+        
+        %% **********************************************************
+        % Get method for TC_dBO_INTERP
+        %************************************************************
+        function value = get.TC_dBO_INTERP(obj)
+            TC_dBO = obj.audiometry_dB - obj.mainGain_dB + obj.TC_dBHL;
+            value  = obj.interpPars(TC_dBO, obj.numChannels);
+        end
+        
+        %% **********************************************************
+        % Get method for TM_dBO_INTERP
+        %************************************************************
+        function value = get.TM_dBO_INTERP(obj)
+            TM_dBO = obj.audiometry_dB - obj.mainGain_dB + obj.TM_dBHL;
+            value  = obj.interpPars(TM_dBO, obj.numChannels);
+        end
+        
+        %% **********************************************************
+        % Get method for bwOct_INTERP 
+        %************************************************************
+        function value = get.bwOct_INTERP(obj)
+            value = repmat(obj.bwOct, 1, obj.numChannels);
+        end
+        
+        %% **********************************************************
+        % Get method for DRNLb_INTERP 
+        %************************************************************
+        function value = get.DRNLb_INTERP(obj)
+            value = ( 2e-5 .* 10.^(obj.TC_dBO_INTERP/20)) .^ (1-obj.DRNLc_INTERP); 
+        end
+        
+        %% **********************************************************
+        % Get method for DRNLc_INTERP 
+        %************************************************************
+        function value = get.DRNLc_INTERP(obj)
+            value  = obj.interpPars(obj.DRNLc, obj.numChannels);
+        end
+        
+        %% **********************************************************
+        % Get method for mainGain_INTERP 
+        %************************************************************
+        function value = get.mainGain_INTERP(obj)
+            mainGainLin = 10.^(obj.mainGain_dB/20); %lin units
+            value  = obj.interpPars(mainGainLin, obj.numChannels);
+        end                
+        
+        %% ***********************************************************
+        % Get method for stimulus
+        % -----------------------
+        % The hearing aid expects a stereo signal, as the MOC control is
+        % linked for left and right channels. It would be more efficient to
+        % use a mono version of the aid for simulation in Matlab. However,
+        % I always want to use the exact same code for the hardware in the
+        % lab and current simulations. This code will make a mono signal
+        % stereo if needs be and/or rotate to 2xN array.
+        %*************************************************************
+        function value = get.stimulusINTERNAL(obj)            
+            [nRows, nCols] = size(obj.stimulusUSER);
+            
+            % Assume that the stimulus duration is greater than 2 samples.
+            % Therefore the number of channels is the min dim.            
+            [nChans, I] = min([nRows nCols]);                                                
+            
+            if nChans == 2
+                if I == 2
+                    value = obj.stimulusUSER;
+                else
+                    value = obj.stimulusUSER';
+                end
+            elseif nChans == 1 %Just to be explicit
+                if I == 2
+                    value = [obj.stimulusUSER obj.stimulusUSER];   
+                else
+                    value = [obj.stimulusUSER; obj.stimulusUSER]';
+                end
+            end
+        end
+        
+        %% ***********************************************************
+        % Get method for aid output
+        % -----------------------
+        % This get method is linked to the above internal stimulus method
+        % and allows the user to extract the hearing aid output in exactly
+        % the same shape and size as the original input stimulus. This is
+        % very useful for the speech recognition work and presumably
+        % for multithreshold also.
+        %*************************************************************
+        function value = get.aidOPnice(obj)
+            if ~isempty(obj.aidOP)
+                [nRows, nCols] = size(obj.stimulusUSER);
+                
+                % Assume that the stimulus duration is greater than 2 samples.
+                % Therefore the number of channels is the min dim.
+                [nChans, I] = min([nRows nCols]);
+                
+                %** The aid output will ALWAYS be a 2xN array **
+                %The fist job is to remove trailing zeros that may have been
+                %introduced by the framing process
+                aidOPtruncated = obj.aidOP(:, 1:max([nRows nCols]));
+                
+                %The next task is to arrange the op like the ip
+                if nChans == 2
+                    if I == 1
+                        value = aidOPtruncated;
+                    else
+                        value = aidOPtruncated';
+                    end
+                elseif nChans == 1 %Just to be explicit
+                    if I == 1
+                        value = aidOPtruncated(1,:);
+                    else
+                        value = aidOPtruncated(1,:)';
+                    end
+                end
+            else % ---- of if isempty statement
+                value = [];
+            end
+        end
+        
+        %% ***********************************************************
+        % *** Set methods ***
+        % -----------------------
+        % This is a bunch of unexciting error hunting functions. They also
+        % flush the aid output if any parameters change. Therefore,
+        % processStim will have to be called explicity by the user once
+        % again. 
+        %*************************************************************
+        function obj = set.stimulusUSER(obj,value)
+            [nRows, nCols] = size(value);
+            
+            % Assume that the stimulus duration is greater than 2 samples.
+            % Therefore the number of channels is the min dim.            
+            nChans = min([nRows nCols]);            
+            assert(nChans<3 && nChans, 'Number of stimulus channels must be 1 or 2')
+            
+            obj = obj.flushAidData; %flush any previous hearing aid data if the input stimulus changes
+            obj.stimulusUSER = value;
+        end                     
+        function obj = set.sr(obj,value)
+            assert(value>=20e3 && value<=192e3, 'sr must be between 20 and 192 kHz')            
+            obj = obj.flushAidData;
+            obj.sr = value;
+        end
+        function obj = set.numSamples(obj,value)
+            assert(value>=48 && value<=6912, 'must be between 48 and 6912 samples')            
+            obj = obj.flushAidData;
+            obj.numSamples = value;
+        end
+        function obj = set.audiometry_dB(obj,value)
+            [nRows,nCols] = size(value);
+            assert(nRows==obj.numAudiometricFreqs && nCols==1, 'must be 6x1 column vector') %#ok<MCSUP>
+            obj = obj.flushAidData;
+            obj.audiometry_dB = value;
+        end
+        function obj = set.mainGain_dB(obj,value)
+            [nRows,nCols] = size(value);
+            assert(nRows==obj.numAudiometricFreqs && nCols==1, 'must be 6x1 column vector') %#ok<MCSUP>
+            obj = obj.flushAidData;
+            obj.mainGain_dB = value;
+        end
+        function obj = set.TC_dBHL(obj,value)
+            [nRows,nCols] = size(value);
+            assert(nRows==obj.numAudiometricFreqs && nCols==1, 'must be 6x1 column vector') %#ok<MCSUP>
+            obj = obj.flushAidData;
+            obj.TC_dBHL = value;
+        end
+        function obj = set.TM_dBHL(obj,value)
+            [nRows,nCols] = size(value);
+            assert(nRows==obj.numAudiometricFreqs && nCols==1, 'must be 6x1 column vector') %#ok<MCSUP>
+            obj = obj.flushAidData;
+            obj.TM_dBHL = value;
+        end
+        function obj = set.DRNLc(obj,value)
+            [nRows,nCols] = size(value);
+            assert(nRows==obj.numAudiometricFreqs && nCols==1, 'must be 6x1 column vector') %#ok<MCSUP>
+            assert(all(value)>=0 && all(value)<=1, 'all DRNLc values must be between 0 and 1')
+            obj = obj.flushAidData;
+            obj.DRNLc = value;
+        end
+        function obj = set.ARtau(obj,value)
+            assert(value>=1e-3 && value<=1, 'must be between 1e-3 and 1s')            
+            obj = obj.flushAidData;
+            obj.ARtau = value;
+        end
+        function obj = set.ARthreshold_dB(obj,value)
+            assert(value>0, 'set AR to a high value to disable it')            
+            obj = obj.flushAidData;
+            obj.ARthreshold_dB = value;
+        end
+        function obj = set.MOCtau(obj,value)
+            assert(value>=1e-3 && value<=2, 'must be between 1e-3 and 2s')            
+            obj = obj.flushAidData;
+            obj.MOCtau = value;
+        end
+        function obj = set.MOCfactor(obj,value)
+            assert(value>=0 && value<=1, 'must be between 0 and 1')
+            obj = obj.flushAidData;
+            obj.MOCfactor = value;
+        end
+        function obj = set.bwOct(obj,value)
+            assert(value==1/1 || value==1/2 || value==1/3 || value==1/4 || value==1/5, 'must be one of 1./(1:5)')
+            obj = obj.flushAidData;
+            obj.bwOct = value;
+        end
+        function obj = set.filterOrder(obj,value)
+            assert(value>0 && value<5, 'must be one of 1:4')
+            obj = obj.flushAidData;
+            obj.filterOrder = value;
+        end
+        function obj = set.useGTF(obj,value)
+            obj = obj.flushAidData;
+            obj.useGTF = value;
+        end                    
+        
+        %% **********************************************************
+        % flushAidData        
+        % This second function is a workaround allowing a set method to
+        % change another property value.
+        %************************************************************
+        function obj = flushAidData(obj) 
+            obj.aidOP = [];
+            obj.MOCrecord = [];
+        end 
+        
+        
+        %% **********************************************************
+        % OVERLOADED plot method 
+        %************************************************************
+        function plot(obj)
+            clf
+            sig2dBSPL = @(sig)20*log10(abs(sig/20e-6)+(1/(2^32)));
+            dt = 1/obj.sr;
+            tAxis = dt:dt:dt*size(obj.stimulusINTERNAL,1);
+            
+            subplot(2,1,1)
+            plot(tAxis(1:length(obj.stimulusUSER)), sig2dBSPL(obj.stimulusUSER), 'k')
+            if ~isempty(obj.aidOPnice)
+                hold on
+                plot(tAxis(1:length(obj.stimulusUSER)), sig2dBSPL(obj.aidOPnice), 'r')
+            end                                   
+            ylim([0 100])
+            xlim([0 tAxis(length(obj.stimulusUSER))])
+            title('Level response')
+            xlabel('Time in seconds')
+            ylabel('Level in dB SPL')
+            
+            subplot(2,1,2) 
+            if ~isempty(obj.MOCrecord)
+                imagesc(tAxis, 1:obj.numChannels, flipud(-20*log10(obj.MOCrecord)))
+                colorbar                               
+            end         
+            title('MOC attenuation')
+            xlabel('Time in seconds')
+            ylabel('Band frequency in Hz')
+            numSpacers = 1 + (obj.numChannels-numel(obj.DRNLc)) / (numel(obj.DRNLc)-1);
+            set(gca, 'YTick', 1:numSpacers:obj.numChannels);
+            set(gca, 'YTickLabel', num2str(flipud([250; 500; 1000; 2000; 4000; 8000])));
+        end% ------ OVERLOADED plot method
+        
+        %% **********************************************************
+        % OVERLOADED soundsc method 
+        %************************************************************
+        function soundsc(obj)
+            soundsc(obj.aidOPnice, obj.sr)
+        end                 
+        
+        %% **********************************************************
+        % processStim
+        %************************************************************
+        function obj = processStim(obj)
+            %--------------------------------------------------------------
+            % EMULATION OF THE GUI PARAMETER CONVERSIONS
+            %--------------------------------------------------------------
+            biggestNumSamples = obj.numSamples; 
+            
+            filterStatesL = (zeros(3000,1));
+            filterStatesR = filterStatesL;
+            filterCoeffs = (zeros(5000,1));
+            
+            %filter coefficients
+            ARcutOff=1/(2*pi*obj.ARtau);
+            [b,a] = butter(1,ARcutOff/(obj.sr/2));
+            filterCoeffs(obj.enumC_ARb+1:obj.enumC_ARb+2) = b;
+            filterCoeffs(obj.enumC_ARa+1:obj.enumC_ARa+2) = a;
+            
+            MOCcutOff=1/(2*pi*obj.MOCtau);
+            [bMOC,aMOC] = butter(1,MOCcutOff/(obj.sr/2));
+            filterCoeffs(obj.enumC_MOCb+1:obj.enumC_MOCb+2) = bMOC;
+            filterCoeffs(obj.enumC_MOCa+1:obj.enumC_MOCa+2) = aMOC;
+            
+            
+            for filterCount = 1:obj.numChannels
+                %-----------------------------------
+                % nonlinear path - filter bws
+                %-----------------------------------
+                lowerCutOff=obj.channelBFs(filterCount)*2^(-obj.bwOct_INTERP(filterCount)/2);
+                upperCutOff=obj.channelBFs(filterCount)*2^( obj.bwOct_INTERP(filterCount)/2);
+                
+                if obj.useGTF
+                    bwHz = upperCutOff - lowerCutOff;
+                    [b_DRNL,a_DRNL] = obj.gammatone(bwHz, obj.channelBFs(filterCount), 1/obj.sr);
+                    filterCoeffs(10*(filterCount-1)+9 :10*(filterCount-1)+10) = b_DRNL;
+                    filterCoeffs(10*(filterCount-1)+14:10*(filterCount-1)+16) = a_DRNL;
+                else                                             
+                    [b_DRNL,a_DRNL] = butter(2,[lowerCutOff upperCutOff]/(obj.sr/2));
+                    filterCoeffs(10*(filterCount-1)+9 :10*(filterCount-1)+13) = b_DRNL;
+                    filterCoeffs(10*(filterCount-1)+14:10*(filterCount-1)+18) = a_DRNL;
+                end
+            end
+            
+            %--------------------------------------------------------------
+            % EMULATION OF THE IO CALLBACK THREAD
+            %--------------------------------------------------------------
+            frameBufferL = buffer(obj.stimulusINTERNAL(:,1), obj.numSamples);
+            frameBufferR = buffer(obj.stimulusINTERNAL(:,2), obj.numSamples);
+            nFrames = size(frameBufferL,2);
+            
+            pad = zeros(1,biggestNumSamples-obj.numSamples);
+            ARampL=ones(1,biggestNumSamples);
+            ARampR = ARampL;
+            MOCcontrol = ones(obj.numChannels, biggestNumSamples);
+            
+            peakIPL = zeros(5,1);
+            peakOPL = peakIPL;
+            rmsIPL  = peakIPL;
+            rmsOPL  = peakIPL;
+            
+            peakIPR = peakIPL;
+            peakOPR = peakIPL;
+            rmsIPR  = peakIPL;
+            rmsOPR  = peakIPL;
+            
+            MOCend = zeros(obj.numChannels,1);
+            
+            op = [];
+            moc= [];
+            for nn = 1:nFrames
+                frameBufferPadL = [frameBufferL(:,nn)' pad];
+                frameBufferPadR = [frameBufferR(:,nn)' pad];
+                
+                [ outBufferL, outBufferR, filterStatesL, filterStatesR,  ARampL, ARampR, MOCend, peakIPL, peakOPL, rmsIPL, rmsOPL, peakIPR, peakOPR, rmsIPR, rmsOPR, MOCcontrol ] =...
+                    EssexAidProcessVFrameSwitchable( ...
+                    frameBufferPadL,...
+                    frameBufferPadR,...
+                    filterStatesL,...
+                    filterStatesR,...
+                    filterCoeffs,...
+                    obj.numChannels,...
+                    obj.numSamples,...
+                    ARampL,...
+                    ARampR,...
+                    obj.ARthresholdPa,...
+                    obj.filterOrder,...
+                    obj.DRNLb_INTERP,...
+                    obj.DRNLc_INTERP,...
+                    obj.TM_dBO_INTERP,...
+                    obj.MOCfactor,...
+                    peakIPL,...
+                    peakOPL,...
+                    rmsIPL,...
+                    rmsOPL,...
+                    peakIPR,...
+                    peakOPR,...
+                    rmsIPR,...
+                    rmsOPR,...
+                    MOCend,...
+                    MOCcontrol,...
+                    obj.mainGain_INTERP,...
+                    obj.useGTF);
+                                
+                
+                outBuffer = ( [outBufferL(:, 1:obj.numSamples); outBufferR(:, 1:obj.numSamples)] );                
+                op = [op outBuffer]; %#ok<AGROW>   
+                moc= [moc MOCcontrol]; %#ok<AGROW>
+                
+            end %End of frame processing emulation loop
+            obj.aidOP = op;
+            obj.MOCrecord=moc;
+                       
+            
+        end %End of process stim method          
+        
+    end %End of methods block
+    
+    %%  *********************************************************
+    %      _        _   _                       _   _               _
+    %     | |      | | (_)                     | | | |             | |
+    %  ___| |_ __ _| |_ _  ___   _ __ ___   ___| |_| |__   ___   __| |___
+    % / __| __/ _` | __| |/ __| | '_ ` _ \ / _ \ __| '_ \ / _ \ / _` / __|
+    % \__ \ || (_| | |_| | (__  | | | | | |  __/ |_| | | | (_) | (_| \__ \
+    % |___/\__\__,_|\__|_|\___| |_| |_| |_|\___|\__|_| |_|\___/ \__,_|___/
+    %************************************************************
+    
+    methods(Static)        
+        %% ********************************************************
+        % pipOut - sequence of tone pips at various levels
+        %**********************************************************        
+        function pipOut = pipSequence(sampleRate, freq, dBlevs, pulseDur, silDur)
+            if nargin < 5
+                silDur = 0.3;
+            end
+            if nargin < 4
+                pulseDur = 0.1;
+            end
+            if nargin < 3
+                dBlevs = 20:20:100;
+            end
+            if nargin < 2
+                freq = 500;
+            end
+            if nargin < 1
+                sampleRate = 48e3;
+            end
+            
+            dt = 1/sampleRate;
+            tAxis = dt:dt:pulseDur;
+            sPulse = sin(2*pi*freq*tAxis);
+            sPulse = sPulse./sqrt(mean(sPulse.^2));
+            rms2dBspl = @(dBspl)20e-6*10^(dBspl/20); %sneaky short-hand function by (ab)using function handles
+            zPad = zeros(1,ceil(sampleRate*silDur));
+            
+            pipOut = [];
+            for nn = 1:numel(dBlevs)                
+                pipOut = [ pipOut sPulse*rms2dBspl(dBlevs(nn))  zPad]; %#ok<AGROW>
+            end
+
+        end% ------ OF pipSequence
+        
+        %% ********************************************************
+        % interpPars - Linear interpolation of given parameter to mimic GUI
+        % fitting functionality.
+        %**********************************************************        
+        function fullArray = interpPars(shortArray, numBands)
+            nGUIbands = numel(shortArray);
+            if numBands == nGUIbands
+                fullArray = shortArray;
+            else
+                numSpacers = (numBands-nGUIbands) / (nGUIbands-1);
+                fullArray = shortArray(1);
+                for nn = 2:nGUIbands
+                    fullArray = [fullArray,...
+                        repmat(mean([shortArray(nn) shortArray(nn-1)]),1,numSpacers),...
+                        shortArray(nn)]; %#ok<AGROW>
+                end                    
+            end                        
+        end% ----- OF interpPars
+        
+        %% ********************************************************
+        % gammatone - get filter coefficients
+        %********************************************************** 
+        function [b,a] = gammatone(bw, cf, dt)
+            phi = 2 * pi * bw * dt;
+            theta = 2 * pi * cf * dt;
+            cos_theta = cos(theta);
+            sin_theta = sin(theta);
+            alpha = -exp(-phi) * cos_theta;
+            b0 = 1.0;
+            b1 = 2 * alpha;
+            b2 = exp(-2 * phi);
+            z1 = (1 + alpha * cos_theta) - (alpha * sin_theta) * 1i;
+            z2 = (1 + b1 * cos_theta) - (b1 * sin_theta) * 1i;
+            z3 = (b2 * cos(2 * theta)) - (b2 * sin(2 * theta)) * 1i;
+            tf = (z2 + z3) / z1;
+            a0 = abs(tf);
+            a1 = alpha * a0;
+            
+            a = [b0, b1, b2];
+            b = [a0, a1];
+        end% ------ OF gammatone
+    end% ------ OF static methods
+    
+end %End of classdef
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsASRforDummies/cHMM.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,718 @@
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%   This program 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 2 of the License, or
+%   (at your option) any later version.
+%
+%   This program 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 can obtain a copy of the GNU General Public License from
+%   http://www.gnu.org/copyleft/gpl.html or by writing to
+%   Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+classdef cHMM
+    %HMMCLASS Handles all of the HTK related gubbins
+    %   Please see the documentation located in a separate file for further
+    %   information.     
+    
+    %%  *********************************************************
+    %  properties                      _   _
+    %                                 | | (_)
+    %  _ __  _ __ ___  _ __   ___ _ __| |_ _  ___  ___
+    % | '_ \| '__/ _ \| '_ \ / _ \ '__| __| |/ _ \/ __|
+    % | |_) | | | (_) | |_) |  __/ |  | |_| |  __/\__ \
+    % | .__/|_|  \___/| .__/ \___|_|   \__|_|\___||___/
+    % | |             | |
+    % |_|             |_|
+    %************************************************************
+    
+    %% **********************************************************
+    % Public properties - can be set by user
+    %************************************************************
+    properties(Access = public)
+        hmmFolder
+        paramType               = 'USER_D_A'; %DELTAS and ACCELERATIONS
+        numCoeff                = 27; %9*3 THIS IS FOR PROBABILITY MODEL (not high spont+low spont which would be 18*3=54)
+                
+        HERestDataPath      = fullfile(pwd, 'def', 'HERest_digit');
+        binPath             = fullfile(pwd, 'def', 'bin');
+        configFile          = fullfile(pwd, 'def', 'config_STANDARD');
+        trainWordListFile   = fullfile(pwd, 'def', 'Grammar_digit', 'words3');
+        testWordListFile    = fullfile(pwd, 'def', 'Grammar_digit', 'wordsNoSevenZero');
+        wordNetFile         = fullfile(pwd, 'def', 'Grammar_digit', 'wdnetNoSP.slf');
+        dictFile            = fullfile(pwd, 'def', 'Grammar_digit', 'noSevenZeroDict');
+    end
+    
+    %% **********************************************************
+    % Dependent - never set by user. Only calculated when needed
+    %************************************************************
+    properties(Dependent = true)
+        protoFile              % = fullfile(pwd, 'def', 'proto_RobANonly_9'); %probability only
+    end
+    
+    %%  *********************************************************
+    % methods        _   _               _
+    %               | | | |             | |
+    % _ __ ___   ___| |_| |__   ___   __| |___
+    %| '_ ` _ \ / _ \ __| '_ \ / _ \ / _` / __|
+    %| | | | | |  __/ |_| | | | (_) | (_| \__ \
+    %|_| |_| |_|\___|\__|_| |_|\___/ \__,_|___/
+    %************************************************************
+    
+    methods
+        %% **********************************************************
+        % Constructor
+        %************************************************************
+        function obj = cHMM(hmmFolder)
+            if nargin > 0
+                obj.hmmFolder = hmmFolder;
+            end
+        end % ------ OF CONSTRUCTOR
+        
+        %% **********************************************************
+        % genProto - generate task specific prototype
+        %************************************************************
+        function genProto(obj)
+            % models_1mixsil.exe - takes input (hmmdef) and copies it making a
+            % basis of one, two three etc. etc.
+            obj.models_1mixsilMat(fullfile(obj.hmmFolder,'hmm0','hmmdef'), fullfile(obj.hmmFolder,'hmm0','models'));            
+        end % ------ OF GENPROTO
+        
+        %% **********************************************************
+        % istrained
+        %************************************************************
+        function boolans = istrained(obj)
+            boolans = numel(dir(fullfile(obj.hmmFolder,'hmm36','models')));
+        end
+        
+        %% **********************************************************
+        % Train
+        %************************************************************
+        function train(obj, trainFeatureFolder)
+                       
+            % Most of the following code block can be replaced by doing a
+            % find and replace across the  code below. I didn't
+            % want to mess with the working code too much, so I just
+            % copied the object properties needed into the variable names
+            % expected.
+            
+            ED_CMDFILE1 = fullfile(obj.HERestDataPath, 'sil1.hed');
+            ED_CMDFILE2 = fullfile(obj.HERestDataPath, 'mix2_16.hed');
+            ED_CMDFILE3 = fullfile(obj.HERestDataPath, 'mix3_16.hed');
+            ED_CMDFILE4 = fullfile(obj.HERestDataPath, 'mix5_16.hed');
+            ED_CMDFILE5 = fullfile(obj.HERestDataPath, 'mix7_16.hed');
+            
+            NUM_COEF        = obj.numCoeff;
+            PAR_TYPE        = obj.paramType;
+            LIST_FILE       = fullfile(obj.hmmFolder, 'tmp.list');
+            
+            word_list       = obj.trainWordListFile;%fullfile(obj.grammarPath, 'words');
+            word_listSP     = word_list; % for use in hmm4 onwards - UGLY HACK NOW SP ABANDONED
+            proto           = obj.protoFile;%Does not exist on disk just yet probably - see a few lines down
+            config          = obj.configFile;
+            train_list      = fullfile(trainFeatureFolder, 'list.scp');
+            labels          = fullfile(trainFeatureFolder, 'labels.mlf');
+            labelssp        = labels; % for use in hmm4 onwards - UGLY HACK NOW SP ABANDONED
+            hmm_dir         = obj.hmmFolder;
+            
+            FEAT_ROOT       = trainFeatureFolder;
+            
+            % Now for the actual HMM training code
+            mkdir(hmm_dir)
+            for I = 0:36
+                h = fullfile(hmm_dir,['hmm' num2str(I)]);
+                mkdir(h);
+            end
+            obj.makeProtoHmm(proto, obj.paramType, obj.numCoeff, 18);
+            
+            fid = fopen(train_list,'r');
+            disp(train_list)
+            S = textscan(fid,'%s','Delimiter','\n');
+            fclose(fid);
+            
+            fid = fopen(LIST_FILE,'w');
+            
+            for I = 1:size(S{1},1)
+                str  = fullfile(FEAT_ROOT,S{1}{I});
+                fprintf(fid,'%s\n',str);
+            end;
+            fclose(fid);
+            
+            % HCompV just gets the vfloor stuff out so we can begin approximating
+            cmd = ['"HCompV" -T 2 -D -C "' config '" -o hmmdef -f 0.01 -m -S "' LIST_FILE '" -M "' hmm_dir filesep 'hmm0" "' proto '"'];
+            system(cmd);                        
+            
+            %cmd = [BINDIR filesep 'macro' binExt ' ' num2str(NUM_COEF) ' ' PAR_TYPE ' ' '"' hmm_dir filesep 'hmm0' filesep 'vFloors' '" "' hmm_dir filesep 'hmm0' filesep 'macros' '"'];
+            %system(cmd);            
+            obj.macroMat(NUM_COEF,PAR_TYPE, fullfile(hmm_dir, 'hmm0', 'vFloors'), fullfile(hmm_dir, 'hmm0', 'macros'));
+            
+            %MAKE THE INITIAL MODEL PROTOTYPE
+            genProto(obj);
+                        
+            disp('Seed HMM successfully Produced.....');
+            
+            %Training
+            for I = 1:3
+                disp(I)
+                j = I-1;
+                cmd = ['HERest -D -C ' config ' -I ' labels ' -t 250.0 150.0 1000.0 -S ' LIST_FILE  ' -H ' hmm_dir filesep 'hmm' num2str(j)  filesep 'macros -H ' hmm_dir filesep 'hmm' num2str(j) filesep 'models -M ' hmm_dir filesep 'hmm' num2str(I) ' ' word_list];
+                %                 disp(cmd)
+                system(cmd);
+            end
+            
+            disp('3 iterations complete');
+            
+            rmdir ([hmm_dir filesep 'hmm4'],'s')
+            copyfile ([hmm_dir filesep 'hmm3'], [hmm_dir filesep 'hmm4'])                                                
+            
+            % The following command takes state 3 from the silence model
+            % and appends it to the end of the model as state 2 of the
+            % short pause model.
+            % Original:
+            % cmd = [BINDIR filesep 'spmodel_gen' binExt ' ' hmm_dir filesep 'hmm3' filesep 'models ' hmm_dir filesep 'hmm4' filesep 'models'];
+            % system(cmd);
+            % New:
+            obj.spmodel_genMat(fullfile(hmm_dir,'hmm3','models'), fullfile(hmm_dir,'hmm4','models'));                                     
+            
+            cmd = ['HHEd  -T 2 -H ' hmm_dir filesep 'hmm4' filesep 'macros -H ' hmm_dir filesep 'hmm4' filesep 'models -M ' hmm_dir filesep 'hmm5 ' ED_CMDFILE1 ' ' word_listSP ];
+            system(cmd);
+            disp ('SP model fixed')
+            
+            % after the spmodel_gen command - the word_list is changed to
+            % word_listSP. The sp model is just ignored currently
+            
+            for I = 6:8
+                disp(I)
+                j = I-1;
+                cmd = ['HERest -C ' config ' -I ' labelssp ' -S ' LIST_FILE  ' -H ' hmm_dir filesep 'hmm' num2str(j)  filesep 'macros -H ' hmm_dir filesep 'hmm' num2str(j) filesep 'models -M ' hmm_dir filesep 'hmm' num2str(I) ' ' word_listSP];
+                system(cmd);
+            end
+            
+            disp('6 iterations complete');
+            
+            cmd = ['HHEd  -T 2 -H ' hmm_dir filesep 'hmm8' filesep 'macros -H ' hmm_dir filesep 'hmm8' filesep 'models -M ' hmm_dir filesep 'hmm9 ' ED_CMDFILE2 ' ' word_listSP ];
+            system(cmd);
+            disp ('2 gaussians per mixture')
+            
+            for I = 10:12
+                disp(I)
+                j = I-1;
+                cmd = ['HERest -C ' config ' -I ' labelssp ' -S ' LIST_FILE  ' -H ' hmm_dir filesep 'hmm' num2str(j)  filesep 'macros -H ' hmm_dir filesep 'hmm' num2str(j) filesep 'models -M ' hmm_dir filesep 'hmm' num2str(I) ' ' word_listSP];
+                system(cmd);
+            end
+            
+            disp ('9 iterations completed')
+            
+            cmd = ['HHEd  -T 2 -H ' hmm_dir filesep 'hmm12'  filesep 'macros -H ' hmm_dir filesep 'hmm12' filesep 'models -M ' hmm_dir filesep 'hmm13 ' ED_CMDFILE3 ' ' word_listSP ];
+            system(cmd);
+            disp ('3 gaussians per mixture')
+            
+            for I = 14:20
+                disp(I)
+                j = I-1;
+                cmd = ['HERest -C ' config ' -I ' labelssp ' -S ' LIST_FILE  ' -H ' hmm_dir filesep 'hmm' num2str(j)  filesep 'macros -H ' hmm_dir filesep 'hmm' num2str(j) filesep 'models -M ' hmm_dir filesep 'hmm' num2str(I) ' ' word_listSP];
+                system(cmd);
+            end
+            
+            disp ('16 iterations completed')
+            
+            cmd = ['HHEd  -T 2 -H ' hmm_dir filesep 'hmm20'  filesep 'macros -H ' hmm_dir filesep 'hmm20' filesep 'models -M ' hmm_dir filesep 'hmm21 ' ED_CMDFILE4 ' ' word_listSP ];
+            system(cmd);
+            disp ('5 gaussians per mixture')
+            
+            for I = 22:28
+                disp(I)
+                j = I-1;
+                cmd = ['HERest -C ' config ' -I ' labelssp ' -S ' LIST_FILE  ' -H ' hmm_dir filesep 'hmm' num2str(j)  filesep 'macros -H ' hmm_dir filesep 'hmm' num2str(j) filesep 'models -M ' hmm_dir filesep 'hmm' num2str(I) ' ' word_listSP];
+                system(cmd);
+            end
+            
+            disp ('23 iterations completed')
+            
+            cmd = ['HHEd  -T 2 -H ' hmm_dir filesep 'hmm28'  filesep 'macros -H ' hmm_dir filesep 'hmm28' filesep 'models -M ' hmm_dir filesep 'hmm29 ' ED_CMDFILE5 ' ' word_listSP ];
+            system(cmd);
+            disp ('7 gaussians per mixture')
+            
+            for I = 30:36
+                disp(I)
+                j = I-1;
+                cmd = ['HERest -C ' config ' -I ' labelssp ' -S ' LIST_FILE  ' -H ' hmm_dir filesep 'hmm' num2str(j)  filesep 'macros -H ' hmm_dir filesep 'hmm' num2str(j) filesep 'models -M ' hmm_dir filesep 'hmm' num2str(I) ' ' word_listSP];
+                system(cmd);
+            end
+            
+            disp ('30 iterations completed')
+            
+        end % ------ OF TRAIN
+        
+        %% **********************************************************
+        % Test
+        %************************************************************
+        function test(obj, testFeatureFolder)
+            flags = '-p 0.0 -s 0.0';
+            test_word_list = obj.testWordListFile;
+            
+            net = obj.wordNetFile;
+            dict = obj.dictFile;
+            
+            LIST_FILE       = fullfile(testFeatureFolder, 'tmp.list');
+            config          = obj.configFile;
+            
+            disp ('Now testing with 7 mixture HMMs')
+            mod_file = fullfile(obj.hmmFolder, 'hmm36', 'models');
+            mac_file = fullfile(obj.hmmFolder, 'hmm36', 'macros');
+            
+            
+            RESULTS_DIR = testFeatureFolder;
+            TEST_FEAT_ROOT  = testFeatureFolder;
+            
+            N1list =  fullfile(testFeatureFolder, 'list.scp');
+            
+            ftest = fopen(N1list,'r');
+            S = textscan(ftest,'%s','Delimiter','\n');
+            fclose(ftest);
+            
+            flist = fopen(LIST_FILE,'w');
+            for I = 1:size(S{1},1)
+                str  = fullfile(TEST_FEAT_ROOT,S{1}{I});
+                fprintf(flist,'%s\n',str);
+            end;
+            fclose(flist);
+            
+            cmd = ['HVite -D -H ' mac_file ' -H ' mod_file ' -S ' LIST_FILE ' -C ' config ' -w ' net ' -l ''*'' -i ' RESULTS_DIR filesep 'result.mlf ' flags ' ' dict ' ' test_word_list];
+            system(cmd);
+        end % ------ OF TEST
+        
+        %% **********************************************************
+        % Get methods determining feature vector related gubbins
+        %************************************************************
+        function value = get.protoFile(obj)
+            value = fullfile(obj.hmmFolder, 'proto_AutoGen');
+        end
+        
+    end % ------ OF METHODS
+    
+    %%  *********************************************************
+    %      _        _   _                       _   _               _
+    %     | |      | | (_)                     | | | |             | |
+    %  ___| |_ __ _| |_ _  ___   _ __ ___   ___| |_| |__   ___   __| |___
+    % / __| __/ _` | __| |/ __| | '_ ` _ \ / _ \ __| '_ \ / _ \ / _` / __|
+    % \__ \ || (_| | |_| | (__  | | | | | |  __/ |_| | | | (_) | (_| \__ \
+    % |___/\__\__,_|\__|_|\___| |_| |_| |_|\___|\__|_| |_|\___/ \__,_|___/
+    %************************************************************
+    
+    methods(Static)        
+        %% **********************************************************
+        % macroMat (matlab port of macro C code)
+        % ported by NC - Nov 2011
+        %************************************************************
+        function macroMat(VECSIZE, PARAMETER_TYPE, infile, outfile)
+          % This function takes the vFloors file that is created after
+          % invoking HCompV and generates a Macro file required for further  
+          % HMM training 
+            
+            ofp = fopen(outfile,'w');
+                        
+            fprintf(ofp, '~o\n<STREAMINFO> 1 %d\n', VECSIZE);
+            fprintf(ofp, '<VECSIZE> %d\n', VECSIZE);
+            fprintf(ofp, '<NULLD>\n<%s>\n', PARAMETER_TYPE);
+            
+            fp = fopen(infile);            
+            tline = fgets(fp);
+            while ischar(tline)
+                fprintf(ofp,tline);
+                tline = fgets(fp);
+            end
+            fclose(fp);
+            fclose(ofp);
+        end %---- of MACROMAT
+        
+        %% **********************************************************
+        % spmodel_genMat (matlab port of spmodel_gen C code)
+        % ported by NC - Nov 2011
+        %************************************************************
+        function spmodel_genMat(infile, outfile)
+          % This function copies the middle state (3) from the silence model
+          % and makes a sp model out of it by copying it to state 2 of the sp model.
+          
+          % From: http://www.voxforge.org/home/dev/acousticmodels/linux/create/htkjulius/tutorial/monophones/step-7
+            %  In the last step you created HMM models that did not include an "sp"
+            %  (short pause) silence model - which refers to the types of short pauses
+            %  that occur between words in normal speech.  However, you did create a
+            %  "sil" silence model - sil silence models are typically of longer
+            %  duration, and refer to the pauses occur at the end of a sentence.
+            %
+            % The HTK book says that the sp model needs to have its "emitting state
+            % tied to the centre state of the silence model".  What this means is that
+            % you need to create a new sp model in your hmmdefs, that it will use the
+            % centre state of sil, and then they both need to be 'tied' together.  For
+            % a bit of background on HMMs and states, see this example.
+            %
+            % This can be done by copying the centre state from the sil model in your
+            % hmmdefs file and adding it to the sp model, and then running a special
+            % tool called HHED to 'tie' the sp model to the sil model so that they
+            % share the same centre state.  The HTK book provides some background on
+            % what this means, but you need an understanding of the basics of Hidden
+            % Markov Modelling before tackling the HTK Book explanations 
+            
+            ofp = fopen(outfile,'a+'); % we append this time
+            
+            fprintf(ofp,'~h "sp"\n');
+            fprintf(ofp,'<BEGINHMM>\n<NUMSTATES> 3\n<STATE> 2\n');
+            
+            %-- This block gets the hmmdef file to the MODEL
+            lNow = [];
+            fp = fopen(infile);
+            while ~(strcmpi(lNow, '~h "sil"'))
+                lNow = fgetl(fp);
+            end
+            %------------------------------
+            
+            %-- This block gets the hmmdef file to the STATE
+            lNow = [];
+            fp = fopen(infile);
+            while ~(strcmpi(lNow, ['<STATE> ' num2str(3)]))
+                lNow = fgetl(fp);
+            end
+            %------------------------------
+            
+            %%% This block puts a copy of the hmmdef file in from the
+            %%% correct line as found above
+            tline = fgetl(fp);
+            while ~(strcmpi(tline, ['<STATE> ' num2str(4)]))
+                fprintf(ofp,'%s\n', tline);
+                tline = fgetl(fp);
+            end
+            fclose(fp);
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+            
+            fprintf(ofp,'<TRANSP> 3\n0.000000e+00 1.000000e+00 0.000000e+00\n');
+            fprintf(ofp,'0.000000e+00 5.000000e-01 5.000000e-01\n');
+            fprintf(ofp,'0.000000e+00 0.000000e+00 0.000000e+00\n<ENDHMM>\n');                        
+
+            fclose(ofp);
+        end %---- of spmodel_genMat
+        
+        %% **********************************************************
+        % models_1mixsilMat (matlab port of models_1mixsil C code)
+        % ported by NC - Nov 2011
+        %************************************************************
+        function models_1mixsilMat(infile, outfile)
+            % This function takes the hmmdef file and      
+            % generates a HMM Model file       
+            
+            ofp = fopen(outfile,'w');
+            for ii = 1:11
+                
+                %%% This block gets the hmmdef file to the correct line
+                lNow = [];                                
+                fp = fopen(infile);
+                while ~(strcmpi(lNow, '~h "hmmdef"'))
+                    lNow = fgetl(fp);
+                end
+                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+                
+                %%% This block puts a numbered header
+                if ii==1;  fprintf(ofp,'~h "one"\n'); end
+                if ii==2;  fprintf(ofp,'~h "two"\n'); end
+                if ii==3;  fprintf(ofp,'~h "three"\n'); end
+                if ii==4;  fprintf(ofp,'~h "four"\n'); end
+                if ii==5;  fprintf(ofp,'~h "five"\n'); end
+                if ii==6;  fprintf(ofp,'~h "six"\n'); end
+                if ii==7;  fprintf(ofp,'~h "seven"\n'); end
+                if ii==8;  fprintf(ofp,'~h "eight"\n'); end
+                if ii==9;  fprintf(ofp,'~h "nine"\n'); end
+                if ii==10; fprintf(ofp,'~h "oh"\n'); end
+                if ii==11; fprintf(ofp,'~h "zero"\n'); end
+                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+                
+                %%% This block puts a copy of the hmmdef file in from the
+                %%% correct line as found above
+                tline = fgets(fp);
+                while ischar(tline)
+                    fprintf(ofp,tline);
+                    tline = fgets(fp);
+                end                
+                fclose(fp); %close it as we reached EOF
+                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+            end
+            
+            %%% THIS IS THE SILENCE MODEL @ THE END
+            fprintf(ofp,'~h "sil"\n');
+            fprintf(ofp,'<BEGINHMM>\n<NUMSTATES> 5\n');
+            for kk = 2:4
+                fprintf(ofp,'<STATE> %d\n<NUMMIXES> 1\n', kk);
+                %-- This block gets the hmmdef file to the correct line
+                lNow = [];                                
+                fp = fopen(infile);
+                while ~(strcmpi(lNow, ['<STATE> ' num2str(kk)]))
+                    lNow = fgetl(fp);
+                end
+                %------------------------------
+                
+                %%% This block puts a copy of the hmmdef file in from the
+                %%% correct line as found above
+                tline = fgetl(fp);
+                while ~(strcmpi(tline, ['<STATE> ' num2str(kk+1)]))
+                    fprintf(ofp,'%s\n', tline);
+                    tline = fgetl(fp);
+                end                 
+                fclose(fp);
+                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+            end
+            
+            fprintf(ofp,'<TRANSP> 5\n0.000000e+00 1.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00\n');
+            fprintf(ofp,'0.000000e+00 6.000000e-01 4.000000e-01 0.000000e+00 0.000000e+00\n');
+            fprintf(ofp,'0.000000e+00 0.000000e+00 6.000000e-01 4.000000e-01 0.000000e+00\n');
+            fprintf(ofp,'0.000000e+00 0.000000e+00 0.000000e+00 7.000000e-01 3.000000e-01\n');
+            fprintf(ofp,'0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00\n<ENDHMM>\n');
+            
+            fclose(ofp);
+        end %---- of models_1mixsilMat
+        
+        %% **********************************************************
+        % makeProtoHmm (Make a prototype HMM)
+        %************************************************************
+        function makeProtoHmm(filename,featureType,numFeatures,numStates)
+            % filename is obvious
+            % featureType is usually USER_D_A
+            % numFeatures is number of features (including differences if used)
+            % numStates is usually 18
+            
+            ofp = fopen(filename,'w');
+            
+            fprintf(ofp,'<BeginHMM>\n');
+            fprintf(ofp,' <NumStates> %d <VecSize> %d <%s> <nullD> <diagC>\n',numStates,numFeatures,featureType');
+            fprintf(ofp,' <StreamInfo> 1 %d\n',numFeatures);
+            for state=2:numStates-1,
+                fprintf(ofp,' <State> %d <NumMixes> 1\n',state);
+                fprintf(ofp,'  <Stream> 1\n');
+                fprintf(ofp,'  <Mixture> 1 1.0\n');
+                fprintf(ofp,'    <Mean> %d\n',numFeatures);
+                fprintf(ofp,'      ');
+                fprintf(ofp,'%1.1f ',zeros(1,numFeatures));
+                fprintf(ofp,'\n');
+                fprintf(ofp,'   <Variance> %d\n',numFeatures);
+                fprintf(ofp,'      ');
+                fprintf(ofp,'%1.1f ',ones(1,numFeatures));
+                fprintf(ofp,'\n');
+            end
+            fprintf(ofp,'<TransP> %d\n',numStates);
+            transp = zeros(numFeatures);
+            transp(1,2)=1;
+            for state=2:numStates-2,
+                transp(state,state)=0.6;
+                transp(state,state+1)=0.4;
+            end
+            transp(numStates-1,numStates-1)=0.9;
+            transp(numStates-1,numStates)=0.1;
+            for state=1:numStates,
+                fprintf(ofp,'%1.3e  ',transp(state,1:numStates));
+                fprintf(ofp,'\n');
+            end
+            fprintf(ofp,'<EndHMM>\n');                      
+            fclose(ofp);
+        end %---- of MAKEPROTOHMM
+        
+        %% **********************************************************
+        % createMLF - master label file - belongs with hmm class
+        %************************************************************
+        function createMLF(mapFileFolder)
+            mlfFileName = 'labels';
+            d = dir(fullfile(mapFileFolder, '*.map'));
+            fid = fopen([fullfile(mapFileFolder,mlfFileName) '.mlf'],'w');
+            fprintf(fid,'#!MLF!#\n');
+            
+            for I = 1:size(d,1)
+                fprintf(fid,['"*/' d(I).name(1:end-3) 'lab"\n']);
+                fprintf(fid,'sil\n');
+                labels = d(I).name(5:end-5);
+                for J = 1:length(labels);
+                    switch labels(J)
+                        case 'O'
+                            S = 'oh';
+                        case '1'
+                            S = 'one';
+                        case '2'
+                            S = 'two';
+                        case '3'
+                            S = 'three';
+                        case '4'
+                            S = 'four';
+                        case '5'
+                            S = 'five';
+                        case '6'
+                            S = 'six';
+                        case '7'
+                            S = 'seven';
+                        case '8'
+                            S = 'eight';
+                        case '9'
+                            S = 'nine';
+                        case 'Z'
+                            S = 'zero';
+                    end
+                    fprintf(fid,S);
+                    fprintf(fid,'\n');
+                end;
+                fprintf(fid,'sil\n.\n');
+            end;
+            fclose(fid);
+        end % ------ OF CREATEMLF
+        
+        %% **********************************************************
+        % createSCP - Just a file list
+        %************************************************************
+        function createSCP(mapFileFolder)
+            scpFileName = 'list';
+            d = dir(fullfile(mapFileFolder, '*.map'));
+            fid = fopen([fullfile(mapFileFolder,scpFileName) '.scp'],'w');
+            
+            for I = 1:size(d,1)
+                fprintf(fid,[d(I).name(1:end-3) 'map\n']);
+            end;
+            
+            fclose(fid);
+        end% ------ OF createSCP
+        
+        %% **********************************************************
+        % score - Simple non-dynamic scoring
+        %************************************************************
+        function score(testMLFpath)            
+            % First get the test result files and store the file locations
+            testIdx = 1;
+            temp = dir(testMLFpath);
+            for nn = 1:numel(temp)
+                if length(temp(nn).name) > 3
+                    if strcmp(temp(nn).name(end-3:end), '.mlf')
+                        testMLFfiles{testIdx} = temp(nn).name;
+                        testIdx = testIdx+1;
+                    end
+                end
+            end
+            
+            for fileIdx = 1:numel(testMLFfiles)
+                % Extract file name and regonised words as strings -> store in recResults.
+                % This code block is Matt Robertson's
+                fmlf = fopen(fullfile(testMLFpath , testMLFfiles{fileIdx}),'r');
+                
+                MLF = textscan(fmlf,'%s','delimiter','\n');
+                replaceDownPattern = '[0-9\-\.\s]';
+                
+                for I  = 1:size(MLF{1},1);
+                    if strfind(MLF{1}{I},'.rec') >0
+                        M{I} = MLF{1}{I};
+                    else
+                        if strfind(MLF{1}{I},'MLF') >0;
+                            M{I} = MLF{1}{I};
+                        else
+                            M{I} = regexprep(MLF{1}{I},replaceDownPattern,'');
+                        end
+                    end;
+                end;
+                
+                fclose(fmlf);
+                
+                A = 1;
+                for I = 1:size(M,2)
+                    if not(strcmpi(M{I},'sp')) && not(strcmpi(M{I},'sil')) && not(strcmpi(M{I},''));
+                        M2{A} = M{I};
+                        A = A + 1;
+                    end;
+                end;
+                
+                recResults = [];
+                X=0;
+                for I = 1:length(M2)
+                    if strfind(M2{I},'MLF')
+                    else
+                        if strfind(M2{I},'.rec')
+                            X = X+1;
+                            
+                            % found FileName
+                            recResults(X).fileName = M2{I};
+                            recResults(X).utterance = {};
+                        else
+                            recResults(X).utterance = [recResults(X).utterance M2{I}];
+                        end;
+                    end;
+                end;
+                
+                % Make separate 2D arrays of input and output digits
+                inputDigits  = zeros(numel(recResults),3);
+                outputDigits = zeros(numel(recResults),3);
+                for nn = 1:numel(recResults)
+                    ipStr = recResults(nn).fileName(end-8:end-6);
+                    
+                    for kk = 1:3
+                        inputDigits(nn,kk)  = cHMM.htk_str2num(ipStr(kk)); %see local function @ bottom of script
+                        opStr = recResults(nn).utterance(kk);
+                        outputDigits(nn,kk) = cHMM.htk_str2num(opStr{:}); %bit of a hack to do cell2str as it were
+                    end
+                end
+                
+                % Now do the scoring (simple whan data in the right format)
+                % :D
+                scoreArray = (inputDigits == outputDigits);
+                pcSent(fileIdx) = 100*sum(all(scoreArray,2)) / numel(recResults);
+                pcWord(fileIdx) = 100*sum(scoreArray(:)) / numel(scoreArray);
+            end
+            
+            %will output table to console if used on *nix
+            xlsdataFull = [{'-- File Name --', '%Sent', '%Word'}; testMLFfiles' num2cell(pcSent') num2cell(pcWord')];
+            disp(xlsdataFull)
+            fid = fopen(fullfile(testMLFpath,['score__' num2str(pcWord(1), '%0.1f') '__.txt']),'w');            
+            fclose(fid);
+        end% ------ OF SCORE
+        
+        %% **********************************************************
+        % scoreWhole folder - make my life easier @ command line
+        %************************************************************
+        function scoreWholeFolder(folderToScore, searchString)
+            if nargin < 2
+                searchString = '*featR*';
+            end            
+            dirInfo = dir(fullfile(folderToScore, searchString));
+            numFolders = numel(dirInfo);
+            for nn = 1:numFolders;
+                currentScoring = fullfile(folderToScore, dirInfo(nn).name);
+                disp('');
+                disp(currentScoring);
+                cHMM.score(currentScoring);
+            end
+        end                        
+        
+        %**************************************************************************
+        % htk_str2num - Convert strings to integers
+        %**************************************************************************
+        function opNum = htk_str2num(ipString)            
+            switch ipString
+                case {'oh' , 'O'}
+                    opNum = 0;
+                case {'one' , '1'}
+                    opNum = 1;
+                case {'two' , '2'}
+                    opNum = 2;
+                case {'three' , '3'}
+                    opNum = 3;
+                case {'four' , '4'}
+                    opNum = 4;
+                case {'five' , '5'}
+                    opNum = 5;
+                case {'six' , '6'}
+                    opNum = 6;
+                case {'eight' , '8'}
+                    opNum = 8;
+                case {'nine' , '9'}
+                    opNum = 9;
+                otherwise
+                    assert(0) % throw error
+            end
+        end % ------ OF htk_str2num                      
+        
+    end % ------ OF STATIC METHODS
+    
+end % ------ OF CLASS
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsASRforDummies/cJob.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,941 @@
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%   This program 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 2 of the License, or
+%   (at your option) any later version.
+%
+%   This program 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 can obtain a copy of the GNU General Public License from
+%   http://www.gnu.org/copyleft/gpl.html or by writing to
+%   Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+classdef cJob
+    %CJOB Responsible for conversion of wav files into recogniser features
+    %   Please see the documentation located in a separate file for further
+    %   information.
+    
+    %%  *********************************************************
+    %  properties                      _   _
+    %                                 | | (_)
+    %  _ __  _ __ ___  _ __   ___ _ __| |_ _  ___  ___
+    % | '_ \| '__/ _ \| '_ \ / _ \ '__| __| |/ _ \/ __|
+    % | |_) | | | (_) | |_) |  __/ |  | |_| |  __/\__ \
+    % | .__/|_|  \___/| .__/ \___|_|   \__|_|\___||___/
+    % | |             | |
+    % |_|             |_|
+    %************************************************************
+    
+    %% **********************************************************
+    % Public properties - can be set by user
+    %************************************************************
+    properties(Access = public)
+        wavFolder
+        opFolder
+        noiseFolder
+        
+        wavList
+        todoStatus
+        
+        
+        participant        = 'Normal';%'DEMO2_multiSpont';
+        noiseName          = '8TalkerBabble';
+        numWavs            =  5;
+        noiseLevToUse      = -200;
+        speechLevToUse     =  50;
+        
+        speechLevStd       = 0;
+        noiseLevStd        = 0;
+        freezeNoise        = 0;
+        meanSNR            = 20;
+        speechDist         = 'None';
+        noiseDist          = 'None';
+        
+        noisePreDur        = 0.0;
+        noisePostDur       = 0.0;
+        truncateDur        = 0.0; %Dr. RF used 0.550
+        
+        currentSpeechLevel
+        currentNoiseLevel
+        
+        
+        useSpectrogram = false;
+        numCoeff = 9;
+        
+        %************************************************************
+        % plotting handles
+        %************************************************************
+        probHaxes   = [];
+        probHaxesSM = [];
+        sacfHaxes   = [];
+        sacfHaxesSM = [];
+        featHaxes   = [];
+        reconHaxes  = [];
+        
+        %************************************************************
+        % SACF params
+        %************************************************************
+        useSACF             = false;
+        SACFacfTau          = 2; % > 1 = Wiegrebe mode
+        SACFnBins           = 128;
+        SACFminLag          = 1 / 4000;
+        SACFmaxLag          = 1 / 50;
+        SACFlambda          = 10e-3;
+        
+        %************************************************************
+        % MAP params
+        %************************************************************
+        MAProot                 = fullfile('..');
+        MAPplotGraphs           = 0;
+        MAPDRNLSave             = 0;
+        
+        MAPopLSR                = 0;
+        MAPopMSR                = 0;
+        MAPopHSR                = 1;
+        
+        MAPparamChanges = {};
+        
+        %************************************************************
+        % HTK stuff - writing to HTK recogniser format
+        %************************************************************
+        frameshift              = 10;       % shift between frames (ms)
+        sampPeriodFromMsFactor  = 10000;    % appropriate for 10ms frame rate
+        paramKind               = 9;        % HTK USER format for user-defined features (p73 of HTK book)
+        
+        removeEnergyStatic      = false;
+        doCMN                   = false; % Cepstral mean normalisation
+        
+        %************************************************************
+        % Portable EssexAid params
+        %************************************************************
+        bwOct = 1/1;
+        filterOrder  = 2;
+        
+        mainGain = [ 1;    1;    1;    1;    1];     % gain in linear units
+        TCdBO    = [40;   40;   40;   40;   40];      %Compression thresholds (in dB OUTPUT from 2nd filt)
+        TMdBO    = [10;   10;   10;   10;   10];      %MOC thresholds (in dB OUTPUT from 2nd filt)
+        DRNLc    = [ 0.2;  0.2;  0.2;  0.2;  0.2;]
+        
+        ARtau  = 0.03;            % decay time constant
+        ARthresholddB = 85;       % dB SPL (input signal level) =>200 to disable
+        MOCtau = 0.3;
+        MOCfactor = 0.5;   %dB per dB OUTPUT
+        
+        numSamples = 1024; %MAX=6912
+        useAid = 0;
+    end
+    
+    %%  *********************************************************
+    % Protected properties - inter/ra class communication
+    %************************************************************
+    properties(Access = protected)
+        jobLockFid % File identifier for mutex
+        
+        %Nick C comment on this:
+        %OK. The big-endian thing used to work because in the config file
+        %'config_tr_zcpa12' there was a flag called NATURALREADORDER that was set to
+        %FALSE and thus appeared to override x86 standard:
+        %little-endian. Endianess has **!nothing!** to do with win vs *nix
+        byteOrder = 'le';  % byte order is big endian
+    end
+    properties(Dependent = true)
+        jobLockTxtFile
+    end
+    
+    %%  *********************************************************
+    % methods        _   _               _
+    %               | | | |             | |
+    % _ __ ___   ___| |_| |__   ___   __| |___
+    %| '_ ` _ \ / _ \ __| '_ \ / _ \ / _` / __|
+    %| | | | | |  __/ |_| | | | (_) | (_| \__ \
+    %|_| |_| |_|\___|\__|_| |_|\___/ \__,_|___/
+    %************************************************************
+    
+    methods
+        %% **********************************************************
+        % Constructor
+        %************************************************************
+        function obj = cJob(LearnOrRecWavs, jobFolder)
+            if nargin < 1
+                warning('job:ambiguouscorpus',...
+                    'We need to know whether the (L)earning or (R)ecognition corpus is being used, assuming ''L''');
+                LearnOrRecWavs = 'L';
+            end
+            if nargin > 1
+                obj.opFolder = jobFolder;
+            else
+                if isunix
+                    if ismac
+                        obj.opFolder = '~/ASR/exps/_foo';
+                    else
+                        obj.opFolder = '/scratch/nrclark/exps/_foo';
+                    end
+                else
+                    obj.opFolder = 'D:\exps\_foo';
+                end
+            end
+            
+            obj = obj.assignWavPaths(LearnOrRecWavs);
+            obj = obj.initMAP;
+            
+            
+        end % ------ OF CONSTRUCTOR
+        
+        %% **********************************************************
+        % Set Wav Paths
+        %************************************************************
+        function obj = assignWavPaths(obj, LearnOrRecWavs)
+            if isunix
+                if ismac
+                    lWAVpath = fullfile('demo_wavs', 'TrainingData-Clean');
+                    rWAVpath = fullfile('demo_wavs', 'TripletTestData');
+                    obj.noiseFolder = fullfile('demo_wavs', 'noises');
+                else
+                    lWAVpath = fullfile('demo_wavs', 'TrainingData-Clean');
+                    rWAVpath = fullfile('demo_wavs', 'TripletTestData');
+                    obj.noiseFolder = fullfile('demo_wavs', 'noises');
+                end
+            else
+                lWAVpath = 'D:\AURORA digits (wav)\TrainingData-Clean';
+                rWAVpath = 'D:\AURORA digits (wav)\TripletTestData';
+                obj.noiseFolder = 'D:\AURORA digits (wav)\noises';
+            end
+            
+            if strcmpi(LearnOrRecWavs, 'l')
+                obj.wavFolder = lWAVpath;
+            elseif strcmpi(LearnOrRecWavs, 'r')
+                obj.wavFolder = rWAVpath;
+            else
+                error('First argument to constructor must be ''L'' or ''R''');
+            end
+        end
+        
+        %% **********************************************************
+        % mutex related    _
+        %                 | |
+        %  _ __ ___  _   _| |_ _____  __
+        % | '_ ` _ \| | | | __/ _ \ \/ /
+        % | | | | | | |_| | ||  __/>  <
+        % |_| |_| |_|\__,_|\__\___/_/\_\
+        %************************************************************
+        
+        %% **********************************************************
+        % lockJobList - File mutex protecting from race conditions
+        %************************************************************
+        function obj = lockJobList(obj)
+            lockON = false;
+            while (~lockON)
+                if numel(dir(obj.jobLockTxtFile)) %Check to see if lock already in place
+                    wTime = randi(750)+250; %3,000-10,000 ms
+                    disp(['File mutex in place. Retrying in ' num2str(wTime) ' ms'])
+                    pause(wTime/1000);
+                else
+                    obj.jobLockFid = fopen(obj.jobLockTxtFile,'w');
+                    disp('Job locked');
+                    pause(50/1000);
+                    lockON = true;
+                end
+            end
+            fclose(obj.jobLockFid);
+        end% ------ OF LOCKJOBLIST
+        
+        %% **********************************************************
+        % unlockJobList - unlocks for other workers
+        %************************************************************
+        function obj = unlockJobList(obj)
+            lockON = logical(numel(dir(obj.jobLockTxtFile)));
+            while(lockON)
+                try
+                    delete(obj.jobLockTxtFile);
+                    disp('Job unlocked');
+                    pause(50/1000);
+                    lockON = false;
+                catch %#ok<CTCH>
+                    disp('Unjamming lock - retrying immediately')
+                    pause(200/1000)
+                end
+            end
+        end% ------ OF UNLOCKJOBLIST
+        
+        %% **********************************************************
+        % storeSelf - save a copy of this object in opFolder
+        %************************************************************
+        function storeSelf(obj)
+            doneSaving = false;
+            while(~doneSaving)
+                try
+                    save(fullfile(obj.opFolder, 'jobObject'), 'obj');
+                    doneSaving = true;
+                catch  %#ok<CTCH>
+                    wTime = randi(3800)+200; %200-4000 ms
+                    disp(['Save collision (THIS IS VERY VERY BAD - have you not used the mutex?). Retrying in ' num2str(wTime) ' ms']);
+                    pause(wTime/1000);
+                end
+            end
+        end % ------ OF STORESELF
+        
+        %% **********************************************************
+        % loadSelf - load a copy of this object from opFolder
+        %************************************************************
+        function obj = loadSelf(obj)
+            doneLoading = false;
+            while(~doneLoading)
+                try
+                    load(fullfile(obj.opFolder,'jobObject'));
+                    doneLoading = true;
+                catch  %#ok<CTCH>
+                    wTime = randi(3800)+200; %200-4000 ms
+                    disp(['Load collision (THIS IS VERY VERY BAD - have you not used the mutex?). Retrying in ' num2str(wTime) ' ms'])
+                    pause(wTime/1000);
+                end
+            end
+        end% ------ OF LOADSELF
+        
+        
+        %%  *********************************************************
+        %  _                          _                   _
+        % | |                        | |                 (_)
+        % | |__   ___  _   _ ___  ___| | _____  ___ _ __  _ _ __   __ _
+        % | '_ \ / _ \| | | / __|/ _ \ |/ / _ \/ _ \ '_ \| | '_ \ / _` |
+        % | | | | (_) | |_| \__ \  __/   <  __/  __/ |_) | | | | | (_| |
+        % |_| |_|\___/ \__,_|___/\___|_|\_\___|\___| .__/|_|_| |_|\__, |
+        %                                          | |             __/ |
+        %                                          |_|            |___/
+        %************************************************************
+        
+        %% **********************************************************
+        % get method for dependtent var jobLockTxtFile
+        %************************************************************
+        function value = get.jobLockTxtFile(obj)
+            %Name the MUTEX file here
+            value = [fullfile(obj.opFolder, 'jobLock') '.txt'];
+        end
+        
+        %% **********************************************************
+        % checkStatus - see how much of the current job is complete
+        %************************************************************
+        function checkStatus(obj)
+            NOWopen = sum(obj.todoStatus==0); %Starting from R2010b, Matlab supports enumerations. For now, we resort to integers for compatibility.
+            NOWpend = sum(obj.todoStatus==1);
+            NOWdone = sum(obj.todoStatus==2);
+            
+            zz = clock;
+            disp([num2str(zz(3)) '-' num2str(zz(2)) '-' num2str(zz(1)) '   ' num2str(zz(4)) ':' num2str(zz(5))])
+            disp(['CURRENT JOB:' obj.opFolder]);
+            disp(' ')
+            disp(['open - ' num2str(NOWopen) ' || pending - ' num2str(NOWpend) ' || complete - ' num2str(NOWdone)])
+            
+            % ---- PROGRESS BAR ----
+            pcDone = 100*NOWdone/obj.numWavs;
+            progBarLength = 40;
+            charBars = repmat('=',1,floor(pcDone/100 * progBarLength));
+            charWhiteSpace = repmat(' ',1, progBarLength - numel(charBars));
+            disp(' ')
+            disp([' -[' charBars charWhiteSpace ']-  ' num2str(pcDone, '%0.1f') '%'])
+            disp(' ')
+            disp(' ')
+            % -- END PROGRESS BAR ---
+        end% ------ OF CHECKSTATUS
+        
+        %% **********************************************************
+        % initMAP - add MAP stuff to path
+        %************************************************************
+        function obj = initMAP(obj)
+            addpath(...fullfile(obj.MAProot, 'modules'),...
+                fullfile(obj.MAProot, 'utilities'),...
+                fullfile(obj.MAProot, 'MAP'),...
+                fullfile(obj.MAProot, 'parameterStore'));
+        end % ------ OF INIT MAP
+        
+        %% **********************************************************
+        % assign files to testing and training sets
+        %************************************************************
+        function obj = assignFiles(obj)
+            speechWavs  = dir(fullfile(obj.wavFolder, '*.wav'));
+            assert(obj.numWavs <= size(speechWavs, 1) ,...
+                'not enough files available in the corpus');  % make sure we have enough wavs
+            
+            randomWavs = rand(1, size(speechWavs, 1));
+            [~,b] = sort(randomWavs);
+            trainFileIdx = b(1:obj.numWavs);
+            
+            obj.wavList  = speechWavs(trainFileIdx); %This is a record of all of the wavs that should be done
+            
+            %Starting from R2010b, Matlab should support enumerated types. For now we
+            %use integers for compatibility.
+            %0=open, 1=processing, 2=done
+            obj.todoStatus = zeros(numel(obj.wavList), 1);
+            
+        end % ------ OF ASSIGN FILES
+        
+        %% **********************************************************
+        % generate  feature
+        %************************************************************
+        function obj = genFeat(obj, currentWav)
+            fprintf(1,'Processing: %s \n', currentWav);
+            if strcmpi(obj.speechDist,'Gaussian')
+                tempSpeechLev = obj.speechLevToUse + obj.speechLevStd*randn;
+            elseif strcmpi(obj.speechDist,'Uniform')
+                % for a uniform distribution, the standard deviation is
+                % range/sqrt(12)
+                % http://mathforum.org/library/drmath/view/52066.html
+                tempSpeechLev = obj.speechLevToUse - obj.speechLevStd*sqrt(12)/2 + obj.speechLevStd*sqrt(12)*rand;
+            elseif strcmpi(obj.speechDist,'None')
+                tempSpeechLev = obj.speechLevToUse;
+            end
+            
+            if strcmpi(obj.noiseDist,'Gaussian')
+                tempNoiseLev  = speechLev - obj.meanSNR  + obj.noiseLevStd*randn;
+            elseif strcmpi(obj.noiseDist,'Uniform')
+                tempNoiseLev  = tempSpeechLev - obj.meanSNR - obj.noiseLevStd*sqrt(12)/2 + obj.noiseLevStd*sqrt(12)*rand;
+            elseif strcmpi(obj.noiseDist,'None')
+                tempNoiseLev  = obj.noiseLevToUse;
+            end
+            
+            disp(['Current speech level = ' num2str(tempSpeechLev)]);
+            disp(['Current noise level  = ' num2str(tempNoiseLev)]);
+            
+            obj.currentSpeechLevel = tempSpeechLev;
+            obj.currentNoiseLevel = tempNoiseLev;
+            [finalFeatures, ~] = processWavs(obj, currentWav); %discard the output from ANprobabilityResponse and method using ~
+            opForHTK(obj, currentWav, finalFeatures);
+        end % ------ OF GENFEAT
+        
+        %% **********************************************************
+        % write o/p in HTK friendly format
+        %************************************************************
+        function obj = opForHTK(obj, currentWav, featureData)
+            
+            featureName = strrep(currentWav, '.wav','.map');
+            targetFilename = fullfile(obj.opFolder, featureName);
+            
+            % write in a format HTK compliant for the recogniser to use
+            obj.writeHTK(...
+                targetFilename,...
+                featureData,...
+                size(featureData,2),...
+                obj.frameshift*obj.sampPeriodFromMsFactor,...
+                size(featureData,1)*4,...
+                obj.paramKind,...
+                obj.byteOrder);            
+        end % ------ OF opForHTK
+        
+        
+        %% **********************************************************
+        %      _                   _                                     _
+        %     (_)                 | |                                   (_)
+        %  ___ _  __ _ _ __   __ _| |  _ __  _ __ ___   ___ ___  ___ ___ _ _ __   __ _
+        % / __| |/ _` | '_ \ / _` | | | '_ \| '__/ _ \ / __/ _ \/ __/ __| | '_ \ / _` |
+        % \__ \ | (_| | | | | (_| | | | |_) | | | (_) | (_|  __/\__ \__ \ | | | | (_| |
+        % |___/_|\__, |_| |_|\__,_|_| | .__/|_|  \___/ \___\___||___/___/_|_| |_|\__, |
+        %         __/ |               | |                                         __/ |
+        %        |___/                |_|                                        |___/
+        %************************************************************
+        
+        %% **********************************************************
+        % getStimulus - what it says on the tin
+        %************************************************************
+        function [stimulus, sampleRate] = getStimulus(obj, currentWav)
+            
+            % getStimulus.m - NC Aug 2010
+            % Modified version of Rob's script to include:
+            %
+            % 1)Signal and noise samples with different sample rate. The component with
+            % lower sample rate is upsampled to the rate of that with the
+            % higher rate.
+            % 2) Clearer level setting
+            % 3) Parameter to change noise intro duration
+            % 4) Noise padding at end of stimulus
+            %
+            % ORIGINAL HEADER:
+            % getStimulus.m
+            %
+            % Robert T. Ferry
+            % 13th May 2009
+            
+            % Set levels
+            [speech speechSampleRate] = wavread(fullfile(obj.wavFolder, currentWav ));
+            speech = speech./sqrt(mean(speech.^2)); %Normalize RMS to 1
+            speech = speech * 20e-6 * 10^(obj.currentSpeechLevel/20); %Convert RMS to pascals at desired level
+            %disp(20*log10(sqrt(mean(speech.^2))/20e-6))
+            
+            [noise noiseSampleRate] = wavread(fullfile(obj.noiseFolder, obj.noiseName ));
+            noise = noise./sqrt(mean(noise.^2)); %Normalize RMS to 1
+            noise = noise * 20e-6*10^(obj.currentNoiseLevel/20); %Convert RMS to pascals at desired level
+            %disp(20*log10(sqrt(mean(noise.^2))/20e-6))
+                        
+            % Do sample rate conversion if needed
+            % Will always convert stimulus component with lower rate up to that with
+            % higher rate.
+            if speechSampleRate > noiseSampleRate
+                %     disp('S>N')
+                [p,q] = rat(speechSampleRate/noiseSampleRate,0.0001);
+                noise = resample(noise, p, q);
+                noiseSampleRate = speechSampleRate;
+            elseif noiseSampleRate > speechSampleRate
+                %     disp('N>S')
+                [p,q] = rat(noiseSampleRate/speechSampleRate,0.0001);
+                speech = resample(speech, p, q);
+                speechSampleRate = noiseSampleRate; %#ok<NASGU>
+            else
+                %DO NOTHING BUT ASSERT
+                assert(speechSampleRate == noiseSampleRate);
+            end
+            sampleRate = noiseSampleRate;
+            dt = 1/sampleRate;
+            
+            % mix stimuli
+            % Everything from here down (mostly) is RTF's original
+            silenceStart = floor(obj.noisePreDur*sampleRate);
+            silenceEnd = floor(obj.noisePostDur*sampleRate);
+            
+            silencePointsStart = zeros(silenceStart,1);
+            silencePointsEnd = zeros(silenceEnd,1);
+            
+            speech = [silencePointsStart; speech; silencePointsEnd];
+            
+            stimLength = length(speech);
+            noiseLength = length(noise);
+            if obj.freezeNoise
+                idx = 1;
+            else
+                idx = ceil(rand*(noiseLength-stimLength));
+            end
+            noise = noise(idx:idx+stimLength-1);
+            
+            stimulus = speech+noise;
+            
+            % add ramps to noise
+            stimInNoiseTime = dt:dt:dt*length(stimulus);
+            rampDuration = 0.100;
+            rampTime = dt : dt : rampDuration;
+            ramp = [0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ones(1,length(stimInNoiseTime)-length(rampTime))];
+            stimulus = stimulus'.*ramp;
+            ramp = fliplr(ramp);
+            stimulus = stimulus.*ramp;
+            stimulus = stimulus';
+            %disp(20*log10(sqrt(mean(stimulus.^2))/20e-6))
+            
+            % add additional silent period to start of stimulus for model to 'settle down'
+            additionalSilenceLength = round(0.050*sampleRate);
+            additionalSilencePoints = zeros(additionalSilenceLength,1);
+            stimulus = [additionalSilencePoints; stimulus]'; %now rotated.
+            %disp(20*log10(sqrt(mean(stimulus.^2))/20e-6))
+        end% ------ OF GETSTIMULUS
+                
+        
+        %% **********************************************************
+        % processWavs - do all of the MAP signal processing
+        %************************************************************
+        function [finalFeatures, ANprobabilityResponse] = processWavs(obj, currentWav)
+            
+            %**********************************************************
+            % FIRST GET THE STIMULUS
+            %**********************************************************
+            [stimulus, sampleRate] = obj.getStimulus(currentWav);
+            
+            %**********************************************************
+            % NOW TO LOAD IN THE HEARING AID
+            %**********************************************************
+            if obj.useAid
+                stimulus = [stimulus; stimulus]'; %EsxAid requires stereo stim
+                stimulus = EssexAid_guiEmulatorWrapper(stimulus, sampleRate, obj);
+                stimulus = stimulus(1,:); %convert back to mono
+            end
+            
+            AN_spikesOrProbability = 'probability';
+            
+            if obj.useSpectrogram
+                lowestBF=100; 	highestBF= 4500; 	numChannels=30;
+                F=round(logspace(log10(lowestBF),log10(highestBF),numChannels));
+                
+                nfft = 1024;
+                hopSamples = 64;
+                noverlap = nfft - hopSamples;
+                dt = hopSamples/sampleRate;
+                [~,~,~,P] = spectrogram(stimulus,nfft,noverlap,F,sampleRate);
+                
+                ANprobabilityResponse = 10*log10(  abs(P) /  ((20e-6)^2)  ); %now correct [(a^2)/(b^2) = (a/b)^2]
+                
+            else
+                [ANprobabilityResponse, dt, myBFlist] = MAPwrap(stimulus, sampleRate, -1, obj.participant, AN_spikesOrProbability, obj.MAPparamChanges);
+            end
+            nChannels = numel(myBFlist);
+            
+            
+            time_ANresponse = dt:dt:dt*size(ANprobabilityResponse,2);
+            idx = time_ANresponse > obj.truncateDur; %RTF had this @ 0.550
+            ANprobabilityResponse = ANprobabilityResponse(:, idx);
+            
+            
+            if ~obj.useSpectrogram
+                if obj.MAPopLSR && ~obj.MAPopHSR
+                    ANprobabilityResponse = ANprobabilityResponse(1:nChannels, :); %use LSR
+                end
+                if ~obj.MAPopLSR && obj.MAPopHSR
+                    ANprobabilityResponse = ANprobabilityResponse(end-nChannels+1:end, :); %or use HSR
+                end
+                if obj.MAPopMSR
+                    assert(0,'Not working with MSR at the mo')
+                end
+            end
+            
+            % OPTIONAL PLOTTING
+            YTickIdx = 1:floor(numel(myBFlist)/6):numel(myBFlist);
+            YTickIdxRev = numel(myBFlist)+1-YTickIdx;
+            if ~isempty(obj.probHaxes)
+                axes(obj.probHaxes);  %#ok<MAXES>
+                imagesc(ANprobabilityResponse); colorbar('peer', obj.probHaxes)
+                set(obj.probHaxes, 'YTick', YTickIdx);
+                set(obj.probHaxes, 'YTickLabel', num2str(    myBFlist(YTickIdxRev)'     ));
+                ylabel('cf in Hz')
+            end
+            
+            % OPTIONAL PLOTTING SMOOTHED
+            if ~isempty(obj.probHaxesSM)
+                axes(obj.probHaxesSM); %#ok<MAXES>
+                anSM=flipud(obj.makeANsmooth(ANprobabilityResponse, 1/dt));
+                imagesc((1:size(anSM,2))./100,1:size(ANprobabilityResponse,1),anSM);
+                set(obj.probHaxesSM, 'YTick', YTickIdx);
+                set(obj.probHaxesSM, 'YTickLabel', num2str(    myBFlist(YTickIdxRev)'     ));
+                shading(obj.probHaxesSM, 'flat'); colorbar('peer', obj.probHaxesSM)
+                ylabel('cf (Hz)')
+                xlabel('Time (s)')
+            end
+            
+            
+            %**********************************************************
+            % optional SACF stage
+            %**********************************************************
+            if obj.useSACF
+                
+                % A slightly ugly copying is needed
+                SACFparams.lambda = obj.SACFlambda;
+                SACFparams.acfTau = obj.SACFacfTau;
+                SACFparams.lags = logspace(log10(obj.SACFminLag),log10(obj.SACFmaxLag),obj.SACFnBins);
+                SACFparams.lags = linspace(obj.SACFminLag, obj.SACFmaxLag,obj.SACFnBins );
+                
+                SACFmethod.dt = dt;
+                SACFmethod.nonlinCF = myBFlist;
+                
+                %This is slightly misleading as the ANprob is now a SACF
+                [ANprobabilityResponse, ~, ~, ~] = filteredSACF(ANprobabilityResponse, SACFmethod, SACFparams);
+                
+                % OPTIONAL PLOTTING
+                YTickIdx = 1:floor(obj.SACFnBins/6):obj.SACFnBins;
+                %YTickIdxRev = obj.SACFnBins+1-YTickIdx;
+                if ~isempty(obj.sacfHaxes)
+                    axes(obj.sacfHaxes);  %#ok<MAXES>
+                    imagesc(flipud(ANprobabilityResponse)); shading(obj.sacfHaxes, 'flat'); colorbar('peer', obj.sacfHaxes)
+                    set(obj.sacfHaxes, 'YTick', YTickIdx);
+                    set(obj.sacfHaxes, 'YTickLabel', num2str(    1./SACFparams.lags(YTickIdx)'    ,'%0.1f' ));
+                    ylabel('Pitch in Hz')
+                end
+                
+                % OPTIONAL PLOTTING SMOOTHED
+                if ~isempty(obj.sacfHaxesSM)
+                    axes(obj.sacfHaxesSM);  %#ok<MAXES>
+                    imagesc(flipud(obj.makeANsmooth(ANprobabilityResponse, 1/dt))); shading(obj.sacfHaxesSM, 'flat'); colorbar('peer', obj.sacfHaxesSM)
+                    set(obj.sacfHaxesSM, 'YTick', YTickIdx);
+                    set(obj.sacfHaxesSM, 'YTickLabel', num2str(    1./SACFparams.lags(YTickIdx)'    ,'%0.1f' ));
+                    ylabel('Pitch in Hz')
+                end
+                
+            end
+            
+            
+            finalFeatures = obj.makeANfeatures(  ...
+                obj.makeANsmooth(ANprobabilityResponse, 1/dt), obj.numCoeff  );
+            
+            if obj.removeEnergyStatic
+                finalFeatures = finalFeatures(2:end,:);
+                % disp(size(finalFeatures))
+            end
+            
+            if obj.doCMN
+                m = mean(finalFeatures,2);
+                finalFeatures = finalFeatures - repmat(m,1,size(finalFeatures,2));
+            end
+            
+            % OPTIONAL PLOTTING
+            if ~isempty(obj.featHaxes)
+                pcolor(obj.featHaxes, finalFeatures); shading(obj.featHaxes, 'flat'); colorbar('peer', obj.featHaxes)
+            end
+            if ~isempty(obj.reconHaxes)
+                reconsData = idct(finalFeatures,obj.SACFnBins);
+                axes(obj.reconHaxes);  %#ok<MAXES>
+                imagesc(flipud( reconsData ));
+            end
+            
+            opForHTK(obj, currentWav, finalFeatures);
+        end % ------ OF PROCESSWAVS
+        
+    end % ------ OF METHODS
+    
+    %%  *********************************************************
+    %      _        _   _                       _   _               _
+    %     | |      | | (_)                     | | | |             | |
+    %  ___| |_ __ _| |_ _  ___   _ __ ___   ___| |_| |__   ___   __| |___
+    % / __| __/ _` | __| |/ __| | '_ ` _ \ / _ \ __| '_ \ / _ \ / _` / __|
+    % \__ \ || (_| | |_| | (__  | | | | | |  __/ |_| | | | (_) | (_| \__ \
+    % |___/\__\__,_|\__|_|\___| |_| |_| |_|\___|\__|_| |_|\___/ \__,_|___/
+    %************************************************************
+    
+    methods(Static)
+        %% ********************************************************
+        % makeANsmooth - smooth the AN response into hanning windowed chunks
+        %**********************************************************
+        function ANsmooth = makeANsmooth(ANresponse, sampleRate, winSize, hopSize)
+            if nargin < 3
+                winSize = 25; %default 25 ms window
+            end
+            if nargin < 4
+                hopSize = 10; %default 10 ms jump between windows
+            end
+            
+            winSizeSamples = round(winSize*sampleRate/1000);
+            hopSizeSamples = round(hopSize*sampleRate/1000);
+            
+            % smooth
+            hann = cJob.NRC_hanning(winSizeSamples);
+            
+            ANsmooth = [];%Cannot pre-allocate a size as it is unknown until the enframing
+            for chan = 1:size(ANresponse,1)
+                f = cJob.enframe(ANresponse(chan,:), hann, hopSizeSamples);
+                ANsmooth(chan,:) = mean(f,2)'; %#ok<AGROW> see above comment
+            end
+        end% ------ OF makeANsmooth
+        
+        %% ********************************************************
+        % makeANfeatures - dct wizardry
+        %**********************************************************
+        function ANfeatures = makeANfeatures(ANrate, numCoeff)
+            % make feature vectors
+            features = cJob.GJB_dct(ANrate);
+            ANfeatures = features(1:numCoeff,:);
+        end % ------ OF makeANfeatures
+        
+        %% ************************************************************************
+        % enframe - AVOID SIGNAL PROCESSING TOOLBOX buffer function
+        %**************************************************************************
+        function f=enframe(x,win,inc)
+            %ENFRAME split signal up into (overlapping) frames: one per row. F=(X,WIN,INC)
+            %
+            %	F = ENFRAME(X,LEN) splits the vector X(:) up into
+            %	frames. Each frame is of length LEN and occupies
+            %	one row of the output matrix. The last few frames of X
+            %	will be ignored if its length is not divisible by LEN.
+            %	It is an error if X is shorter than LEN.
+            %
+            %	F = ENFRAME(X,LEN,INC) has frames beginning at increments of INC
+            %	The centre of frame I is X((I-1)*INC+(LEN+1)/2) for I=1,2,...
+            %	The number of frames is fix((length(X)-LEN+INC)/INC)
+            %
+            %	F = ENFRAME(X,WINDOW) or ENFRAME(X,WINDOW,INC) multiplies
+            %	each frame by WINDOW(:)
+            
+            %	   Copyright (C) Mike Brookes 1997
+            %      Version: $Id: enframe.m,v 1.4 2006/06/22 19:07:50 dmb Exp $
+            %
+            %   VOICEBOX is a MATLAB toolbox for speech processing.
+            %   Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html
+            %
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+            %   This program 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 2 of the License, or
+            %   (at your option) any later version.
+            %
+            %   This program 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 can obtain a copy of the GNU General Public License from
+            %   http://www.gnu.org/copyleft/gpl.html or by writing to
+            %   Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+            
+            nx=length(x(:));
+            nwin=length(win);
+            if (nwin == 1)
+                len = win;
+            else
+                len = nwin;
+            end
+            if (nargin < 3)
+                inc = len;
+            end
+            nf = fix((nx-len+inc)/inc);
+            f=zeros(nf,len);
+            indf= inc*(0:(nf-1)).';
+            inds = (1:len);
+            f(:) = x(indf(:,ones(1,len))+inds(ones(nf,1),:));
+            if (nwin > 1)
+                w = win(:)';
+                f = f .* w(ones(nf,1),:);
+            end
+        end % ------ OF ENFRAME
+        
+        %% ************************************************************************
+        % GJB_dct - AVOID SIGNAL PROCESSING TOOLBOX
+        %**************************************************************************
+        function b=GJB_dct(a,n)
+            
+            if nargin == 0,
+                error('Not enough input arguments.');
+            end
+            
+            if isempty(a)
+                b = [];
+                return
+            end
+            
+            % If input is a vector, make it a column:
+            do_trans = (size(a,1) == 1);
+            if do_trans, a = a(:); end
+            
+            if nargin==1,
+                n = size(a,1);
+            end
+            m = size(a,2);
+            
+            % Pad or truncate input if necessary
+            if size(a,1)<n,
+                aa = zeros(n,m);
+                aa(1:size(a,1),:) = a;
+            else
+                aa = a(1:n,:);
+            end
+            
+            % Compute weights to multiply DFT coefficients
+            ww = (exp(-1i*(0:n-1)*pi/(2*n))/sqrt(2*n)).';
+            ww(1) = ww(1) / sqrt(2);
+            
+            if rem(n,2)==1 || ~isreal(a), % odd case
+                % Form intermediate even-symmetric matrix
+                y = zeros(2*n,m);
+                y(1:n,:) = aa;
+                y(n+1:2*n,:) = flipud(aa);
+                
+                % Compute the FFT and keep the appropriate portion:
+                yy = fft(y);
+                yy = yy(1:n,:);
+                
+            else % even case
+                % Re-order the elements of the columns of x
+                y = [ aa(1:2:n,:); aa(n:-2:2,:) ];
+                yy = fft(y);
+                ww = 2*ww;  % Double the weights for even-length case
+            end
+            
+            % Multiply FFT by weights:
+            b = ww(:,ones(1,m)) .* yy;
+            
+            if isreal(a), b = real(b); end
+            if do_trans, b = b.'; end
+        end % ----- of GJB_DCT
+        
+        %% ************************************************************************
+        % NRC_hanning - AVOID SIGNAL PROCESSING TOOLBOX
+        %**************************************************************************
+        function w=NRC_hanning(n)
+            calc_hanning = @(m,n)0.5*(1 - cos(2*pi*(1:m)'/(n+1))); %cheeky anonymous function - I <3 these
+            if ~rem(n,2)
+                % Even length window
+                half = n/2;
+                w = calc_hanning(half,n);
+                w = [w; w(end:-1:1)];
+            else
+                % Odd length window
+                half = (n+1)/2;
+                w = calc_hanning(half,n);
+                w = [w; w(end-1:-1:1)];
+            end
+        end % ------ of NRC_HANNING
+        
+        %% ************************************************************************
+        % writeHTK - convert data to htk format -> by anonymous Sue (2001)
+        %**************************************************************************
+        function retcode = writeHTK(filename, htkdata, nFrames, sampPeriod, SampSize, ParamKind, byte_order)
+            % Write an HTK format file.
+            %
+            % Input parameters:
+            %    filename		HTK data file
+            %    htkdata      HTK data read: an m x n matrix with
+            %                    m = no. of channels
+            %                    n = no. of frames
+            %  The following are from the HTK header (see HTK manual):
+            %    nFrames      no. of frames (samples)
+            %    sampPeriod   sample period (in 100 ns units?)
+            %    SampSize     sample size
+            %    ParamKind    parameter kind code
+            %
+            %    byteorder    'be' for big-endian (typical for Unix) (default)
+            %                 'le' for little-endian (typical for MSWindows)
+            %
+            % Output parameters:
+            %    retcode      0 if successful
+            
+            % Written by Sue 17/12/01
+            
+            retcode=-1;	% initialise in case of error
+            if nargin < 6
+                fprintf('Usage: %s(filename, htkdata, nFrames, sampPeriod, SampSize, ParamKind [, byte_order])', mfilename);
+            end;
+            
+            % Default to big-endian (HTK format)
+            if nargin < 7
+                byte_order = 'be';
+            end;
+            
+            fid = fopen (filename, 'w', sprintf('ieee-%s', byte_order));
+            if fid < 1
+                fprintf('%s: can''t open output file %s\n', mfilename, filename);
+                return
+            end
+            
+            % Write header
+            fwrite (fid, nFrames, 'int32'); %nSamples in HTK
+            fwrite (fid, sampPeriod, 'int32');
+            fwrite (fid, SampSize, 'int16');
+            fwrite (fid, ParamKind, 'int16');
+            
+            % Write actual data
+            fwrite(fid, htkdata, 'float32');
+            
+            fclose(fid);
+            
+            retcode=0;
+        end% ------ OF WRITEHTK
+        
+        %% ************************************************************************
+        % readHTK - just incase you ever want to go backwards
+        %**************************************************************************
+        function [htkdata,nframes,sampPeriod,sampSize,paramKind] = readHTK(filename,byte_order)
+            
+            if nargin<2
+                byte_order = 'be';
+            end
+            
+            fid = fopen(filename,'r',sprintf('ieee-%s',byte_order));
+            
+            nframes = fread(fid,1,'int32');
+            sampPeriod = fread(fid,1,'int32');
+            sampSize = fread(fid,1,'int16');
+            paramKind = fread(fid,1,'int16');
+            
+            % read the data
+            
+            htkdata = fread(fid,nframes*(sampSize/4),'float32');
+            htkdata = reshape(htkdata,sampSize/4,nframes);
+            fclose(fid);
+        end % ------ OF READHTK
+        
+    end % ------ OF STATIC METHODS
+    
+end % ------ OF CLASS
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsASRforDummies/def/Grammar_digit/noSevenZeroDict	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,11 @@
+one one
+two two
+three three
+four four
+five five
+six six
+eight eight
+nine nine
+oh oh
+sp sp
+sil sil
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsASRforDummies/def/Grammar_digit/wdnetNRCnoSP.txt	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,7 @@
+
+$digit = one | two | three | four | five | six | eight | nine | oh;
+
+( 
+	sil $digit $digit $digit sil
+)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsASRforDummies/def/Grammar_digit/wdnetNoSP.slf	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,93 @@
+VERSION=1.0
+N=34   L=57   
+I=0    W=!NULL               
+I=1    W=!NULL               
+I=2    W=sil                 
+I=3    W=one                 
+I=4    W=!NULL               
+I=5    W=two                 
+I=6    W=three               
+I=7    W=four                
+I=8    W=five                
+I=9    W=six                 
+I=10   W=eight               
+I=11   W=nine                
+I=12   W=oh                  
+I=13   W=one                 
+I=14   W=!NULL               
+I=15   W=two                 
+I=16   W=three               
+I=17   W=four                
+I=18   W=five                
+I=19   W=six                 
+I=20   W=eight               
+I=21   W=nine                
+I=22   W=oh                  
+I=23   W=one                 
+I=24   W=!NULL               
+I=25   W=two                 
+I=26   W=three               
+I=27   W=four                
+I=28   W=five                
+I=29   W=six                 
+I=30   W=eight               
+I=31   W=nine                
+I=32   W=oh                  
+I=33   W=sil                 
+J=0     S=33   E=1    
+J=1     S=0    E=2    
+J=2     S=2    E=3    
+J=3     S=3    E=4    
+J=4     S=5    E=4    
+J=5     S=6    E=4    
+J=6     S=7    E=4    
+J=7     S=8    E=4    
+J=8     S=9    E=4    
+J=9     S=10   E=4    
+J=10    S=11   E=4    
+J=11    S=12   E=4    
+J=12    S=2    E=5    
+J=13    S=2    E=6    
+J=14    S=2    E=7    
+J=15    S=2    E=8    
+J=16    S=2    E=9    
+J=17    S=2    E=10   
+J=18    S=2    E=11   
+J=19    S=2    E=12   
+J=20    S=4    E=13   
+J=21    S=13   E=14   
+J=22    S=15   E=14   
+J=23    S=16   E=14   
+J=24    S=17   E=14   
+J=25    S=18   E=14   
+J=26    S=19   E=14   
+J=27    S=20   E=14   
+J=28    S=21   E=14   
+J=29    S=22   E=14   
+J=30    S=4    E=15   
+J=31    S=4    E=16   
+J=32    S=4    E=17   
+J=33    S=4    E=18   
+J=34    S=4    E=19   
+J=35    S=4    E=20   
+J=36    S=4    E=21   
+J=37    S=4    E=22   
+J=38    S=14   E=23   
+J=39    S=23   E=24   
+J=40    S=25   E=24   
+J=41    S=26   E=24   
+J=42    S=27   E=24   
+J=43    S=28   E=24   
+J=44    S=29   E=24   
+J=45    S=30   E=24   
+J=46    S=31   E=24   
+J=47    S=32   E=24   
+J=48    S=14   E=25   
+J=49    S=14   E=26   
+J=50    S=14   E=27   
+J=51    S=14   E=28   
+J=52    S=14   E=29   
+J=53    S=14   E=30   
+J=54    S=14   E=31   
+J=55    S=14   E=32   
+J=56    S=24   E=33   
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsASRforDummies/def/Grammar_digit/words3	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,12 @@
+one
+two
+three
+four
+five
+six
+seven
+eight
+nine
+zero
+oh
+sil
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsASRforDummies/def/Grammar_digit/wordsNoSevenZero	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,10 @@
+one
+two
+three
+four
+five
+six
+eight
+nine
+oh
+sil
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsASRforDummies/def/HERest_digit/mix2_16.hed	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,15 @@
+MU 2 {one.state[2-17].mix}
+MU 2 {two.state[2-17].mix}
+MU 2 {three.state[2-17].mix}
+MU 2 {four.state[2-17].mix}
+MU 2 {five.state[2-17].mix}
+MU 2 {six.state[2-17].mix}
+MU 2 {seven.state[2-17].mix}
+MU 2 {eight.state[2-17].mix}
+MU 2 {nine.state[2-17].mix}
+MU 2 {oh.state[2-17].mix}
+MU 2 {zero.state[2-17].mix}
+MU 3 {sil.state[2-4].mix}
+
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsASRforDummies/def/HERest_digit/mix3_16.hed	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,17 @@
+MU 3 {one.state[2-17].mix}
+MU 3 {two.state[2-17].mix}
+MU 3 {three.state[2-17].mix}
+MU 3 {four.state[2-17].mix}
+MU 3 {five.state[2-17].mix}
+MU 3 {six.state[2-17].mix}
+MU 3 {seven.state[2-17].mix}
+MU 3 {eight.state[2-17].mix}
+MU 3 {nine.state[2-17].mix}
+MU 3 {oh.state[2-17].mix}
+MU 3 {zero.state[2-17].mix}
+MU 6 {sil.state[2-4].mix}
+
+
+
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsASRforDummies/def/HERest_digit/mix5_16.hed	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,11 @@
+MU 5 {one.state[2-17].mix}
+MU 5 {two.state[2-17].mix}
+MU 5 {three.state[2-17].mix}
+MU 5 {four.state[2-17].mix}
+MU 5 {five.state[2-17].mix}
+MU 5 {six.state[2-17].mix}
+MU 5 {seven.state[2-17].mix}
+MU 5 {eight.state[2-17].mix}
+MU 5 {nine.state[2-17].mix}
+MU 5 {oh.state[2-17].mix}
+MU 5 {zero.state[2-17].mix}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsASRforDummies/def/HERest_digit/mix7_16.hed	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,17 @@
+MU 7 {one.state[2-17].mix}
+MU 7 {two.state[2-17].mix}
+MU 7 {three.state[2-17].mix}
+MU 7 {four.state[2-17].mix}
+MU 7 {five.state[2-17].mix}
+MU 7 {six.state[2-17].mix}
+MU 7 {seven.state[2-17].mix}
+MU 7 {eight.state[2-17].mix}
+MU 7 {nine.state[2-17].mix}
+MU 7 {oh.state[2-17].mix}
+MU 7 {zero.state[2-17].mix}
+MU 7 {sil.state[2-4].mix}
+
+
+
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsASRforDummies/def/HERest_digit/sil1.hed	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,7 @@
+MU 2 {sil.state[2-4].mix}
+AT 2 4 0.2 {sil.transP}
+AT 4 2 0.2 {sil.transP}
+
+TI silst {sil.state[3]}
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsASRforDummies/def/config_STANDARD	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,6 @@
+TARGETKIND 	= USER_D_A
+DELTAWINDOW	= 3
+ACCWINDOW	= 2
+HNET:TRACE 	= 2
+# next line to read data machine dependent
+NATURALREADORDER = TRUE
Binary file userProgramsASRforDummies/demo_wavs/TrainingData-Clean/MNC_1359A.wav has changed
Binary file userProgramsASRforDummies/demo_wavs/TrainingData-Clean/MNC_2468A.wav has changed
Binary file userProgramsASRforDummies/demo_wavs/TrainingData-Clean/MNC_312OA.wav has changed
Binary file userProgramsASRforDummies/demo_wavs/TrainingData-Clean/MNC_4321OA.wav has changed
Binary file userProgramsASRforDummies/demo_wavs/TrainingData-Clean/MNC_46598A.wav has changed
Binary file userProgramsASRforDummies/demo_wavs/TrainingData-Clean/MNC_5689OA.wav has changed
Binary file userProgramsASRforDummies/demo_wavs/TrainingData-Clean/MNC_8642A.wav has changed
Binary file userProgramsASRforDummies/demo_wavs/TrainingData-Clean/MNC_9531A.wav has changed
Binary file userProgramsASRforDummies/demo_wavs/TrainingData-Clean/MNC_98564A.wav has changed
Binary file userProgramsASRforDummies/demo_wavs/TrainingData-Clean/MNC_O1234A.wav has changed
Binary file userProgramsASRforDummies/demo_wavs/TrainingData-Clean/MNC_O213A.wav has changed
Binary file userProgramsASRforDummies/demo_wavs/TrainingData-Clean/MNC_O9865A.wav has changed
Binary file userProgramsASRforDummies/demo_wavs/TripletTestData/MNC_132A.wav has changed
Binary file userProgramsASRforDummies/demo_wavs/TripletTestData/MNC_148A.wav has changed
Binary file userProgramsASRforDummies/demo_wavs/TripletTestData/MNC_36OA.wav has changed
Binary file userProgramsASRforDummies/demo_wavs/TripletTestData/MNC_465A.wav has changed
Binary file userProgramsASRforDummies/demo_wavs/TripletTestData/MNC_592A.wav has changed
Binary file userProgramsASRforDummies/demo_wavs/TripletTestData/MNC_8O9A.wav has changed
Binary file userProgramsASRforDummies/demo_wavs/noises/pink_demo.wav has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsASRforDummies/worker.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,88 @@
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%   This program 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 2 of the License, or
+%   (at your option) any later version.
+%
+%   This program 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 can obtain a copy of the GNU General Public License from
+%   http://www.gnu.org/copyleft/gpl.html or by writing to
+%   Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% This is a function the makes sure all of the jobs get completed in an
+% orderly fashion. It is responsible for keeping unruly nodes in line.
+% NC 2010/1011
+
+function worker(workFolder)
+
+%unit testing
+% close all; clear all; clc
+% workFolder = 'D:\exps\_bar';
+
+
+%main script
+isloaded = 0;
+while ~isloaded
+    if numel(dir(fullfile(workFolder,'jobLock.txt'))) %Check to see if lock already in place
+        pTime = randi(30);
+        disp(['Worker function locked out -> waiting for ' num2str(pTime) ' seconds until next retry']);
+        pause(pTime);
+    else
+        load(fullfile(workFolder,'jobObject.mat'))
+        isloaded = 1;
+    end
+end
+
+
+
+x=obj;
+clear obj;
+x.initMAP; %Need to alert it to the path
+
+personalWork = 0;
+while(any(x.todoStatus==0))        
+    x.lockJobList;
+    x = x.loadSelf; %Reload incase changed
+    rJobs = 8+randi(8);%Grab 1st 9-16 open jobs
+    todoNow = find(~x.todoStatus,rJobs,'first');     
+    x.todoStatus(todoNow) = 1; %Flag it (them) as pending
+    x.storeSelf; %store pending flag as quickly as possible to minimise race condition impact
+    x.unlockJobList;
+    disp(['Grabbed ' num2str(numel(todoNow)) ' sound files for current job.'])
+        
+    % ---  DO WORK  ---
+    for tt=1:numel(todoNow)
+        if ~numel(dir(fullfile(x.opFolder,strrep(x.wavList(todoNow(tt)).name, '.wav','.map'))));
+            x.genFeat(x.wavList(todoNow(tt)).name);
+        else
+            disp(['File ' x.wavList(todoNow(tt)).name ' already processed'])
+        end
+        
+    end
+    % --- END OF WORK ---
+    
+    
+    x.lockJobList;
+    x = x.loadSelf; %Reload incase changed while processing (probably has)
+    x.todoStatus(todoNow) = 2; %Flag as complete
+    x.storeSelf; %Update as done immediately    
+    x.unlockJobList;
+        
+    clc
+    personalWork = personalWork+1;
+    disp( ['This process has completed ' num2str(personalWork) ' lists'] )
+    x.checkStatus        
+end
+
+disp('-*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*-')
+disp( ' > COMPLETED CURRENT JOB' )
+disp( ['  In the folder ' workFolder '  .....'] )
+disp( ['  This process completed ' num2str(personalWork) ' lists'] )
+disp('-*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*-')
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsDomenika/test_IC_DominikaTones.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,187 @@
+function test_IC_DominikaTones
+% test_MAP1_14 is a general purpose test routine that can be adjusted to
+% test a number of different applications of MAP1_14
+%
+% A range of options are supplied in the early part of the program
+%
+% One use of the function is to create demonstrations; filenames <demoxx>
+%  to illustrate particular features
+%
+% #1
+% Identify the file (in 'MAPparamsName') containing the model parameters
+%
+% #2
+% Identify the kind of model required (in 'AN_spikesOrProbability').
+%  A full brainstem model (spikes) can be computed or a shorter model
+%  (probability) that computes only so far as the auditory nerve
+%
+% #3
+% Choose between a tone signal or file input (in 'signalType')
+%
+% #4
+% Set the signal rms level (in leveldBSPL)
+%
+% #5
+% Identify the channels in terms of their best frequencies in the vector
+%  BFlist.
+%
+% Last minute changes to the parameters fetched earlier can be made using
+%  the cell array of strings 'paramChanges'.
+%  Each string must have the same format as the corresponding line in the
+%  file identified in 'MAPparamsName'
+%
+% When the demonstration is satisfactory, freeze it by renaming it <demoxx>
+
+dbstop if error
+restorePath=path;
+addpath (['..' filesep 'MAP'],    ['..' filesep 'wavFileStore'], ...
+    ['..' filesep 'utilities'])
+
+%%  #1 parameter file name
+MAPparamsName='Normal';
+
+
+%% #2 probability (fast) or spikes (slow) representation
+AN_spikesOrProbability='spikes';
+%   or
+% AN_spikesOrProbability='probability';
+
+
+%% #3 pure tone, harmonic sequence or speech file input
+signalType= 'tones';
+sampleRate= 50000;
+duration=0.100;                 % seconds
+rampDuration=.005;              % raised cosine ramp (seconds)
+beginSilence=0.050;
+endSilence=0.050;
+toneFrequency= 5000;            % or a pure tone (Hz)
+
+%   or
+% harmonic sequence (Hz)
+% F0=210;
+% toneFrequency= F0:F0:8000;
+
+%   or
+% signalType= 'file';
+% fileName='twister_44kHz';
+
+
+
+%% #4 rms level
+% signal details
+leveldBSPL= 50;                  % dB SPL (80 for Lieberman)
+
+
+%% #5 number of channels in the model
+%   21-channel model (log spacing)
+numChannels=60;
+lowestBF=5000; 	highestBF= 5001;
+BFlist=round(logspace(log10(lowestBF), log10(highestBF), numChannels));
+
+%   or specify your own channel BFs
+% numChannels=1;
+% BFlist=toneFrequency;
+
+
+%% #6 change model parameters
+
+paramChanges={'IHCpreSynapseParams.tauCa= [80e-6];'};
+
+% Parameter changes can be used to change one or more model parameters
+%  *after* the MAPparams file has been read
+% This example declares only one fiber type with a calcium clearance time
+% constant of 80e-6 s (HSR fiber) when the probability option is selected.
+% paramChanges={'AN_IHCsynapseParams.ANspeedUpFactor=5;', ...
+%     'IHCpreSynapseParams.tauCa=86e-6; '};
+
+
+
+%% delare 'showMap' options to control graphical output
+showMapOptions.printModelParameters=1;   % prints all parameters
+showMapOptions.showModelOutput=1;       % plot of all stages
+showMapOptions.printFiringRates=1;      % prints stage activity levels
+showMapOptions.showEfferent=0;          % tracks of AR and MOC
+showMapOptions.ICrasterPlot=1;
+
+% disable certain silly options
+if strcmp(AN_spikesOrProbability, 'spikes')
+    % avoid nonsensical options
+    showMapOptions.surfProbability=0;
+    showMapOptions.showACF=0;
+end
+
+if strcmp(signalType, 'file')
+    % needed for labeling plot
+    showMapOptions.fileName=fileName;
+else
+    showMapOptions.fileName=[];
+end
+
+%% Generate stimuli
+
+switch signalType
+    case 'tones'
+        % Create pure tone stimulus
+        dt=1/sampleRate; % seconds
+        time=dt: dt: duration;
+        inputSignal=sum(sin(2*pi*toneFrequency'*time), 1);
+        amp=10^(leveldBSPL/20)*28e-6;   % converts to Pascals (peak)
+        inputSignal=amp*inputSignal;
+        % apply ramps
+        % catch rampTime error
+        if rampDuration>0.5*duration, rampDuration=duration/2; end
+        rampTime=dt:dt:rampDuration;
+        ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ...
+            ones(1,length(time)-length(rampTime))];
+        inputSignal=inputSignal.*ramp;
+        ramp=fliplr(ramp);
+        inputSignal=inputSignal.*ramp;
+        % add silence
+        intialSilence= zeros(1,round(beginSilence/dt));
+        finalSilence= zeros(1,round(endSilence/dt));
+        inputSignal= [intialSilence inputSignal finalSilence];
+
+    case 'file'
+        %% file input simple or mixed
+        [inputSignal sampleRate]=wavread(fileName);
+        dt=1/sampleRate;
+        inputSignal=inputSignal(:,1);
+        targetRMS=20e-6*10^(leveldBSPL/20);
+        rms=(mean(inputSignal.^2))^0.5;
+        amp=targetRMS/rms;
+        inputSignal=inputSignal*amp;
+        intialSilence= zeros(1,round(0.1/dt));
+        finalSilence= zeros(1,round(0.2/dt));
+        inputSignal= [intialSilence inputSignal' finalSilence];
+end
+
+
+%% run the model
+tic
+fprintf('\n')
+disp(['Signal duration= ' num2str(length(inputSignal)/sampleRate)])
+disp([num2str(numChannels) ' channel model: ' AN_spikesOrProbability])
+disp('Computing ...')
+
+MAP1_14(inputSignal, sampleRate, BFlist, ...
+    MAPparamsName, AN_spikesOrProbability, paramChanges);
+
+
+%% the model run is now complete. Now display the results
+UTIL_showMAP(showMapOptions, paramChanges)
+
+if strcmp(signalType,'tones')
+    disp(['duration=' num2str(duration)])
+    disp(['level=' num2str(leveldBSPL)])
+    disp(['toneFrequency=' num2str(toneFrequency)])
+    global DRNLParams
+    disp(['attenuation factor =' ...
+        num2str(DRNLParams.rateToAttenuationFactor, '%5.3f') ])
+    disp(['attenuation factor (probability)=' ...
+        num2str(DRNLParams.rateToAttenuationFactorProb, '%5.3f') ])
+    disp(AN_spikesOrProbability)
+end
+disp(paramChanges)
+toc
+path(restorePath)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsMathiasDietz/test_binaural.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,433 @@
+function test_binaural
+% test_binaural is a first attempt to produce a binaural model
+%  incorporating MSO and IC models.
+% The monaural response is computed first for left and right stimuli
+%  before using the CN response as input to the binaural MSO model
+%  that, in turn, feeds a single cell IC model.
+%
+% The function has no arguments and everything is set up internally
+%
+% #1
+% Identify the file (in 'MAPparamsName') containing the model parameters
+%  the default is 'PL' which uses primary like neurons in the CN to
+%  simulate spherical bushy cells
+%
+% #2
+% Set AN_spikesOrProbability'). to 'spikes'
+%
+% #3
+% Choose between a tone signal or file input (in 'signalType')
+%
+% #4
+% Set the signal rms level (in leveldBSPL)
+%
+% #5
+% Identify the channels in terms of their best frequencies in the vector
+%  BFlist. This is currently a single-channel model, so only one BF needed
+%
+% #6
+% Last minute changes to the parameters fetched earlier can be made using
+%  the cell array of strings 'paramChanges'.
+%  Each string must have the same format as the corresponding line in the
+%  file identified in 'MAPparamsName'
+% Currently this is used to specify that only HSR fibers are used and
+%  for changing the current per AN spike at the CN dendrite
+%
+% #7
+% specify the parameters of the MSO cells in the MSOParams structure
+%
+% #8
+% specify the parameters of the IC cells in the ICMSOParams structure
+%
+% #9
+% identify the plots required from MAP1_14 (i.e. before the bonaural model)
+%
+% #10
+% Specify ITDs. The program cycles through different ITDs
+%
+
+global CNoutput dtSpikes
+dbstop if error
+restorePath=path;
+addpath (['..' filesep 'MAP'],    ['..' filesep 'wavFileStore'], ...
+    ['..' filesep 'utilities'])
+
+%%  #1 monaural model parameter file name
+MAPparamsName='PL';
+
+
+%% #2 'spikes' are mandatory for this model
+AN_spikesOrProbability='spikes';
+
+
+%% #3 pure tone, harmonic sequence or speech file input
+signalType= 'tones';
+sampleRate= 50000;
+duration=0.050;                 % seconds
+rampDuration=.005;              % raised cosine ramp (seconds)
+beginSilence=0.050;
+endSilence=0.050;
+toneFrequency= 750;            % or a pure tone (Hz)
+
+%   or
+% harmonic sequence (Hz)
+% F0=210;
+% toneFrequency= F0:F0:8000;
+
+%   or
+% signalType= 'file';
+% fileName='twister_44kHz';
+
+if strcmp(signalType, 'file')
+    % needed for labeling plot
+    showMapOptions.fileName=fileName;
+else
+    showMapOptions.fileName=[];
+end
+
+%% #4 rms level
+leveldBSPL= 70;
+
+
+%% #5 number of channels in the model
+BFlist=toneFrequency;
+
+%% #6 change model parameters
+
+paramChanges={'IHCpreSynapseParams.tauCa=80e-6;',...
+    'MacGregorMultiParams.currentPerSpike=0.800e-6;'};
+
+% Parameter changes can be used to change one or more model parameters
+%  *after* the MAPparams file has been read
+
+%% #7 MSO parameters
+MSOParams.nNeuronsPerBF=	10;   % N neurons per BF
+MSOParams.type = 'primary-like cell';
+MSOParams.fibersPerNeuron=4;   % N input fibers
+MSOParams.dendriteLPfreq=2000;  % dendritic filter
+MSOParams.currentPerSpike=0.11e-6; % (A) per spike
+MSOParams.currentPerSpike=0.5e-6; % (A) per spike
+MSOParams.Cap=4.55e-9;   % cell capacitance (Siemens)
+MSOParams.tauM=5e-4;     % membrane time constant (s)
+MSOParams.Ek=-0.01;      % K+ eq. potential (V)
+MSOParams.dGkSpike=3.64e-5; % K+ cond.shift on spike,S
+MSOParams.tauGk=	0.0012; % K+ conductance tau (s)
+MSOParams.Th0=	0.01;   % equilibrium threshold (V)
+MSOParams.c=	0.01;       % threshold shift on spike, (V)
+MSOParams.tauTh=	0.015;  % variable threshold tau
+MSOParams.Er=-0.06;      % resting potential (V)
+MSOParams.Eb=0.06;       % spike height (V)
+MSOParams.debugging=0;        % (special)
+MSOParams.wideband=0;         % special for wideband units
+
+%% #8 IC parameters
+ICchopperParams.nNeuronsPerBF=	10;   % N neurons per BF
+ICchopperParams.type = 'chopper cell';
+ICchopperParams.fibersPerNeuron=10;  % N input fibers
+ICchopperParams.dendriteLPfreq=50;   % dendritic filter
+ICchopperParams.currentPerSpike=50e-9; % *per spike
+ICchopperParams.currentPerSpike=100e-9; % *per spike
+ICchopperParams.Cap=1.67e-8; % ??cell capacitance (Siemens)
+ICchopperParams.tauM=0.002;  % membrane time constant (s)
+ICchopperParams.Ek=-0.01;    % K+ eq. potential (V)
+ICchopperParams.dGkSpike=1.33e-4; % K+ cond.shift on spike,S
+ICchopperParams.tauGk=	0.0005;% K+ conductance tau (s)
+ICchopperParams.Th0=	0.01; % equilibrium threshold (V)
+ICchopperParams.c=	0;        % threshold shift on spike, (V)
+ICchopperParams.tauTh=	0.02; % variable threshold tau
+ICchopperParams.Er=-0.06;    % resting potential (V)
+ICchopperParams.Eb=0.06;     % spike height (V)
+ICchopperParams.PSTHbinWidth=	1e-4;
+
+%% #9 delare 'showMap' options to control graphical output
+% this applies to the monaural input model only
+showMapOptions.printModelParameters=0;   % prints all parameters
+showMapOptions.showModelOutput=1;   % plot all stages if monaural input
+
+%% #10 ITDs
+% the program cycles through a range of stimulus ITDs
+ITDs=0e-6:100e-6:2000e-6;
+% ITDs=0; % single shot
+
+%% Now start computing!
+figure(98), clf, set(gcf, 'name', 'binaural demo')
+MSOcounts=zeros(1,length(ITDs));
+ICcounts=zeros(1,length(ITDs));
+ITDcount=0;
+for ITD=ITDs
+    ITDcount=ITDcount+1;
+    delaySamples=round(ITD* sampleRate);
+    %% Generate stimuli
+    switch signalType
+        case 'tones'
+            % Create pure tone stimulus
+            dt=1/sampleRate; % seconds
+            time=dt: dt: duration;
+            inputSignal=sum(sin(2*pi*toneFrequency'*time), 1);
+            amp=10^(leveldBSPL/20)*28e-6;   % converts to Pascals (peak)
+            inputSignal=amp*inputSignal;
+            % apply ramps
+            % catch rampTime error
+            if rampDuration>0.5*duration, rampDuration=duration/2; end
+            rampTime=dt:dt:rampDuration;
+            ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ...
+                ones(1,length(time)-length(rampTime))];
+            inputSignal=inputSignal.*ramp;
+            ramp=fliplr(ramp);
+            inputSignal=inputSignal.*ramp;
+            % add silence
+            intialSilence= zeros(1,round(beginSilence/dt));
+            finalSilence= zeros(1,round(endSilence/dt));
+            inputSignal= [intialSilence inputSignal finalSilence];
+
+        case 'file'
+            %% file input simple or mixed
+            [inputSignal sampleRate]=wavread(fileName);
+            dt=1/sampleRate;
+            inputSignal=inputSignal(:,1);
+            targetRMS=20e-6*10^(leveldBSPL/20);
+            rms=(mean(inputSignal.^2))^0.5;
+            amp=targetRMS/rms;
+            inputSignal=inputSignal*amp;
+            intialSilence= zeros(1,round(0.1/dt));
+            finalSilence= zeros(1,round(0.2/dt));
+            inputSignal= [intialSilence inputSignal' finalSilence];
+    end
+
+    %% run the monaural model twice
+    t=dt:dt:dt*length(inputSignal);
+    for ear={'left','right'}
+        figure(98), subplot(4,1,1), colour='b'; hold off
+        switch ear{1}
+            case 'right'
+                inputSignal=circshift(inputSignal', delaySamples)';
+                hold on
+                colour='r';
+        end
+        plot(t, inputSignal, colour)
+        title ('binaural inputs signals')
+        ylabel('Pa'), xlabel('time')
+        xlim([0 max(t)])
+
+        % call to monaural model
+        MAP1_14(inputSignal, sampleRate, BFlist, ...
+            MAPparamsName, AN_spikesOrProbability, paramChanges);
+
+        % the model run is now complete. Now display the results
+        UTIL_showMAP(showMapOptions, paramChanges)
+
+        % copy the CN inputspiking pattern to the binaural display
+        figure(98)
+        switch ear{1}
+            case 'left'
+                CNoutputLeft=CNoutput;
+                subplot(4,2,3)
+            case 'right'
+                CNoutputRight=CNoutput;
+                subplot(4,2,4)
+        end
+        plotInstructions=[];
+        plotInstructions.axes=gca;
+        plotInstructions.displaydt=dtSpikes;
+        plotInstructions.title= ['CN spikes ' ear{1}];
+        plotInstructions.rasterDotSize=2;
+        if sum(sum(CNoutput))<100
+            plotInstructions.rasterDotSize=3;
+        end
+        UTIL_plotMatrix(CNoutput, plotInstructions);
+
+    end % left/ right ear
+
+    %%  MSO
+    % run MSO model using left and right CN spikes
+    MSOspikes=MSO(CNoutputLeft,CNoutputRight, dtSpikes, MSOParams);
+    
+    sumspikes=sum(sum(MSOspikes));
+    disp(['ITD/ MSO spikes count= ' num2str([ITD sumspikes])])
+    MSOcounts(ITDcount)=sumspikes;
+    figure(98), subplot(4,2, 8), cla, hold off, plot(ITDs*1e6, MSOcounts)
+
+    %% IC chopper
+    % run IC model using all MSO spikes as input to a single IC cell
+    ICMSOspikes=ICchopper(MSOspikes, dtSpikes, ICchopperParams);
+    
+    sumspikes=sum(sum(ICMSOspikes));
+    disp(['ITD/ ICMSO spikes count= ' num2str([ITD sumspikes])])
+    ICcounts(ITDcount)=sumspikes;
+    figure(98), subplot(4,2,8),hold on, plot(ITDs*1e6, ICcounts,'r')
+    xlabel('ITD'), ylabel(' spike count')
+    title('MSO (blue)/ IC (red) spike counts')
+    legend({'MSO','IC'})
+
+end % ITDs
+
+path(restorePath)
+
+
+function MSOspikes=MSO(CNoutputLeft,CNoutputRight, dtSpikes, MSOparams)
+%%
+[nMSOcells nEpochs]=size(CNoutputLeft);
+inputCurrent=zeros(nMSOcells, nEpochs);
+MSOmembranePotential=inputCurrent;
+
+MSO_tauM=MSOparams.tauM;
+MSO_tauGk=MSOparams.tauGk;
+MSO_tauTh=MSOparams.tauTh;
+MSO_cap=MSOparams.Cap;
+MSO_c=MSOparams.c;
+MSO_b=MSOparams.dGkSpike;
+MSO_Th0=MSOparams.Th0;
+MSO_Ek=MSOparams.Ek;
+MSO_Eb= MSOparams.Eb;
+MSO_Er=MSOparams.Er;
+
+MSO_E=zeros(nMSOcells,1);
+MSO_Gk=zeros(nMSOcells,1);
+MSO_Th=MSO_Th0*ones(nMSOcells,1);
+
+% Dendritic filtering, all spikes are replaced by CNalphaFunction functions
+MSOdendriteLPfreq= MSOparams.dendriteLPfreq;
+MSOcurrentPerSpike=MSOparams.currentPerSpike;
+MSOspikeToCurrentTau=1/(2*pi*MSOdendriteLPfreq);
+t=dtSpikes:dtSpikes:5*MSOspikeToCurrentTau;
+MSO_CNalphaFunction= (MSOcurrentPerSpike / ...
+    MSOspikeToCurrentTau)*t.*exp(-t / MSOspikeToCurrentTau);
+% show alpha function
+% figure(84), subplot(4,2,2), plot(t,MSO_CNalphaFunction)
+% title(['LP cutoff ' num2str(MSOdendriteLPfreq)])
+
+% convert CN spikes to post-dendritic current
+CN_spikes=CNoutputLeft+CNoutputRight;
+for i=1:nMSOcells
+    x= conv2(CN_spikes(i,:),  MSO_CNalphaFunction);
+    inputCurrent(i,:)=x(1:nEpochs);
+end
+
+if MSO_c==0
+    % faster computation when threshold is stable (c==0)
+    for t=1:nEpochs
+        s=MSO_E>MSO_Th0;
+        dE = (-MSO_E/MSO_tauM + inputCurrent(:,t)/MSO_cap +...
+            (MSO_Gk/MSO_cap).*(MSO_Ek-MSO_E))*dtSpikes;
+        dGk=-MSO_Gk*dtSpikes/MSO_tauGk +MSO_b*s;
+        MSO_E=MSO_E+dE;
+        MSO_Gk=MSO_Gk+dGk;
+        MSOmembranePotential(:,t)=MSO_E+s.*(MSO_Eb-MSO_E)+MSO_Er;
+    end
+else
+    %  threshold is changing (MSO_c>0; e.g. bushy cell)
+    for t=1:nEpochs
+        dE = (-MSO_E/MSO_tauM + ...
+            inputCurrent(:,t)/MSO_cap + (MSO_Gk/MSO_cap)...
+            .*(MSO_Ek-MSO_E))*dtSpikes;
+        MSO_E=MSO_E+dE;
+        s=MSO_E>MSO_Th;
+        MSOmembranePotential(:,t)=MSO_E+s.*(MSO_Eb-MSO_E)+MSO_Er;
+        dGk=-MSO_Gk*dtSpikes/MSO_tauGk +MSO_b*s;
+        MSO_Gk=MSO_Gk+dGk;
+
+        % After a spike, the threshold is raised
+        % otherwise it settles to its baseline
+        dTh=-(MSO_Th-MSO_Th0)*dtSpikes/MSO_tauTh +s*MSO_c;
+        MSO_Th=MSO_Th+dTh;
+    end
+end
+
+figure(98),subplot(4,1,3)
+hold off, imagesc(MSOmembranePotential)
+title ('MSO (V)')
+
+MSOspikes=MSOmembranePotential> -0.01;
+% Remove any spike that is immediately followed by a spike
+%  NB 'find' works on columns (whence the transposing)
+MSOspikes=MSOspikes';
+idx=find(MSOspikes);
+idx=idx(1:end-1);
+MSOspikes(idx+1)=0;
+MSOspikes=MSOspikes';
+
+
+function ICMSOspikes=ICchopper(ICMSOspikes, dtSpikes, ICMSOParams)
+%%
+ICMSOspikes=sum(ICMSOspikes);
+[nICMSOcells nEpochs]=size(ICMSOspikes);
+inputCurrent=zeros(nICMSOcells, nEpochs);
+ICMSOmembranePotential=inputCurrent;
+
+ICMSO_tauM=ICMSOParams.tauM;
+ICMSO_tauGk=ICMSOParams.tauGk;
+ICMSO_tauTh=ICMSOParams.tauTh;
+ICMSO_cap=ICMSOParams.Cap;
+ICMSO_c=ICMSOParams.c;
+ICMSO_b=ICMSOParams.dGkSpike;
+ICMSO_Th0=ICMSOParams.Th0;
+ICMSO_Ek=ICMSOParams.Ek;
+ICMSO_Eb= ICMSOParams.Eb;
+ICMSO_Er=ICMSOParams.Er;
+
+ICMSO_E=zeros(nICMSOcells,1);
+ICMSO_Gk=zeros(nICMSOcells,1);
+ICMSO_Th=ICMSO_Th0*ones(nICMSOcells,1);
+
+% Dendritic filtering, all spikes are replaced by CNalphaFunction functions
+ICMSOdendriteLPfreq= ICMSOParams.dendriteLPfreq;
+ICMSOcurrentPerSpike=ICMSOParams.currentPerSpike;
+ICMSOspikeToCurrentTau=1/(2*pi*ICMSOdendriteLPfreq);
+t=dtSpikes:dtSpikes:5*ICMSOspikeToCurrentTau;
+ICMSOalphaFunction= (ICMSOcurrentPerSpike / ...
+    ICMSOspikeToCurrentTau)*t.*exp(-t / ICMSOspikeToCurrentTau);
+% show alpha function
+% figure(84), subplot(4,2,5), plot(t,ICMSOalphaFunction)
+% title(['IC MSO LP cutoff ' num2str(ICMSOdendriteLPfreq)])
+
+% post-dendritic current
+for i=1:nICMSOcells
+    x= conv2(1*ICMSOspikes(i,:),  ICMSOalphaFunction);
+    inputCurrent(i,:)=x(1:nEpochs);
+end
+
+if ICMSO_c==0
+    % faster computation when threshold is stable (c==0)
+    for t=1:nEpochs
+        s=ICMSO_E>ICMSO_Th0;
+        dE = (-ICMSO_E/ICMSO_tauM + inputCurrent(:,t)/ICMSO_cap +...
+            (ICMSO_Gk/ICMSO_cap).*(ICMSO_Ek-ICMSO_E))*dtSpikes;
+        dGk=-ICMSO_Gk*dtSpikes/ICMSO_tauGk +ICMSO_b*s;
+        ICMSO_E=ICMSO_E+dE;
+        ICMSO_Gk=ICMSO_Gk+dGk;
+        ICMSOmembranePotential(:,t)=ICMSO_E+s.*(ICMSO_Eb-ICMSO_E)+ICMSO_Er;
+    end
+else
+    %  threshold is changing (ICMSO_c>0; e.g. bushy cell)
+    for t=1:nEpochs
+        dE = (-ICMSO_E/ICMSO_tauM + ...
+            inputCurrent(:,t)/ICMSO_cap + (ICMSO_Gk/ICMSO_cap)...
+            .*(ICMSO_Ek-ICMSO_E))*dtSpikes;
+        ICMSO_E=ICMSO_E+dE;
+        s=ICMSO_E>ICMSO_Th;
+        ICMSOmembranePotential(:,t)=ICMSO_E+s.*(ICMSO_Eb-ICMSO_E)+ICMSO_Er;
+        dGk=-ICMSO_Gk*dtSpikes/ICMSO_tauGk +ICMSO_b*s;
+        ICMSO_Gk=ICMSO_Gk+dGk;
+
+        % After a spike, the threshold is raised
+        % otherwise it settles to its baseline
+        dTh=-(ICMSO_Th-ICMSO_Th0)*dtSpikes/ICMSO_tauTh +s*ICMSO_c;
+        ICMSO_Th=ICMSO_Th+dTh;
+    end
+end
+
+t=dtSpikes:dtSpikes:dtSpikes*length(ICMSOmembranePotential);
+figure(98),subplot(4,2,7)
+plot(t, ICMSOmembranePotential)
+ylim([-0.07 0]), xlim([0 max(t)])
+title('IC (V)')
+
+ICMSOspikes=ICMSOmembranePotential> -0.01;
+% now remove any spike that is immediately followed by a spike
+% NB 'find' works on columns (whence the transposing)
+ICMSOspikes=ICMSOspikes';
+idx=find(ICMSOspikes);
+idx=idx(1:end-1);
+ICMSOspikes(idx+1)=0;
+ICMSOspikes=ICMSOspikes';
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsMikaelDeroche/runMAP1_14.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,181 @@
+function runMAP1_14
+% runMAP1_14 is a general purpose test routine that can be adjusted to
+% test a number of different applications of MAP1_14
+%
+% A range of options are supplied in the early part of the program
+%
+% #1
+% Identify the file (in 'MAPparamsName') containing the model parameters
+%
+% #2
+% Identify the kind of model required (in 'AN_spikesOrProbability').
+%  A full brainstem model ('spikes') can be computed or a shorter model
+%  ('probability') that computes only so far as the auditory nerve
+%
+% #3
+% Choose between a tone signal or file input (in 'signalType')
+%
+% #4
+% Set the signal rms level (in leveldBSPL)
+%
+% #5
+% Identify the channels in terms of their best frequencies in the vector
+%  BFlist.
+%
+% Last minute changes to the parameters can be made using
+%  the cell array of strings 'paramChanges'.
+%  Each string must have the same format as the corresponding line in the
+%  file identified in 'MAPparamsName'
+
+dbstop if error
+restorePath=path;
+addpath (['..' filesep 'MAP'],    ['..' filesep 'wavFileStore'], ...
+    ['..' filesep 'utilities'])
+
+%%  #1 parameter file name
+MAPparamsName='Normal';
+
+
+%% #2 probability (fast) or spikes (slow) representation: select one
+% AN_spikesOrProbability='spikes';
+%   or
+AN_spikesOrProbability='probability';
+
+
+%% #3 A. pure tone, B. harmonic sequence or C. speech file input
+% comment out unwanted code
+
+% A. tone
+sampleRate= 441000;
+signalType= 'tones';
+toneFrequency= 5000;            % or a pure tone (Hz)
+duration=0.500;                 % seconds
+beginSilence=0.050;               
+endSilence=0.050;                  
+rampDuration=.005;              % raised cosine ramp (seconds)
+
+%   or
+% B. harmonic tone (Hz) - useful to demonstrate a broadband sound
+% sampleRate= 44100;
+% signalType= 'tones';
+% toneFrequency= F0:F0:8000;    
+% duration=0.500;                 % seconds
+% beginSilence=0.250;               
+% endSilence=0.250;                  
+% F0=210;
+% rampDuration=.005;              % raised cosine ramp (seconds)
+
+%   or
+% C. signalType= 'file';
+% fileName='twister_44kHz';
+
+%% #4 rms level
+% signal details
+leveldBSPL= 70;                  % dB SPL (80 for Lieberman)
+
+%% #5 number of channels in the model
+%   21-channel model (log spacing)
+numChannels=21;
+lowestBF=250; 	highestBF= 6000;
+BFlist=round(logspace(log10(lowestBF), log10(highestBF), numChannels));
+
+%   or specify your own channel BFs
+% numChannels=1;
+% BFlist=toneFrequency;
+
+
+%% #6 change model parameters
+
+paramChanges={};
+
+% Parameter changes can be used to change one or more model parameters
+%  *after* the MAPparams file has been read
+% This example declares only one fiber type with a calcium clearance time
+% constant of 80e-6 s (HSR fiber) when the probability option is selected.
+% paramChanges={'AN_IHCsynapseParams.ANspeedUpFactor=5;', ...
+%     'IHCpreSynapseParams.tauCa=86e-6; '};
+
+
+
+%% delare 'showMap' options to control graphical output
+% see UTIL_showMAP for more options
+showMapOptions.printModelParameters=1;   % prints all parameters
+showMapOptions.showModelOutput=1;       % plot of all stages
+showMapOptions.printFiringRates=1;      % prints stage activity levels
+showMapOptions.showEfferent=1;          % tracks of AR and MOC
+showMapOptions.surfProbability=1;       % 2D plot of HSR response 
+
+if strcmp(signalType, 'file')
+    % needed for labeling plot
+    showMapOptions.fileName=fileName;
+else
+    showMapOptions.fileName=[];
+end
+
+%% Generate stimuli
+switch signalType
+    case 'tones'
+        % Create pure tone stimulus
+        dt=1/sampleRate; % seconds
+        time=dt: dt: duration;
+        inputSignal=sum(sin(2*pi*toneFrequency'*time), 1);
+        amp=10^(leveldBSPL/20)*28e-6;   % converts to Pascals (peak)
+        inputSignal=amp*inputSignal;
+        % apply ramps
+        % catch rampTime error
+        if rampDuration>0.5*duration, rampDuration=duration/2; end
+        rampTime=dt:dt:rampDuration;
+        ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ...
+            ones(1,length(time)-length(rampTime))];
+        inputSignal=inputSignal.*ramp;
+        ramp=fliplr(ramp);
+        inputSignal=inputSignal.*ramp;
+        % add silence
+        intialSilence= zeros(1,round(beginSilence/dt));
+        finalSilence= zeros(1,round(endSilence/dt));
+        inputSignal= [intialSilence inputSignal finalSilence];
+
+    case 'file'
+        %% file input simple or mixed
+        [inputSignal sampleRate]=wavread(fileName);
+        dt=1/sampleRate;
+        inputSignal=inputSignal(:,1);
+        targetRMS=20e-6*10^(leveldBSPL/20);
+        rms=(mean(inputSignal.^2))^0.5;
+        amp=targetRMS/rms;
+        inputSignal=inputSignal*amp;
+        intialSilence= zeros(1,round(0.1/dt));
+        finalSilence= zeros(1,round(0.2/dt));
+        inputSignal= [intialSilence inputSignal' finalSilence];
+end
+
+
+%% run the model
+tic
+fprintf('\n')
+disp(['Signal duration= ' num2str(length(inputSignal)/sampleRate)])
+disp([num2str(numChannels) ' channel model: ' AN_spikesOrProbability])
+disp('Computing ...')
+
+MAP1_14(inputSignal, sampleRate, BFlist, ...
+    MAPparamsName, AN_spikesOrProbability, paramChanges);
+
+
+%% the model run is now complete. Now display the results
+UTIL_showMAP(showMapOptions, paramChanges)
+
+if strcmp(signalType,'tones')
+    disp(['duration=' num2str(duration)])
+    disp(['level=' num2str(leveldBSPL)])
+    disp(['toneFrequency=' num2str(toneFrequency)])
+    global DRNLParams
+    disp(['attenuation factor =' ...
+        num2str(DRNLParams.rateToAttenuationFactor, '%5.3f') ])
+    disp(['attenuation factor (probability)=' ...
+        num2str(DRNLParams.rateToAttenuationFactorProb, '%5.3f') ])
+    disp(AN_spikesOrProbability)
+end
+disp(paramChanges)
+toc
+path(restorePath)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsMikaelDeroche/testACF.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,260 @@
+% function [P dt lags SACF]= testACF
+% testACF is a *script* to demonstrate the smoothed ACF of 
+% Balaguer-Ballestera, E. Denham, S.L. and Meddis, R. (2008). 
+%
+% Convert this to a *function* by uncommenting the first line
+%  The function returns the P matrix plotted in Figure 96.
+%  If a function is used, the following outputs are returned:
+%   P:  smoothed SACF (lags x time matrix)
+%   dt: time interval between successive columns of P
+%   lags: lags used in computing P
+%   SACF: unsmoothed SACFs
+%  
+% A range of options are supplied in the early part of the program
+%
+% #1
+% Identify the model parameter file (in 'MAPparamsName') 
+%
+% #2
+% Identify the kind of model required (in 'AN_spikesOrProbability')
+%  'probability' is recommended for ACF work
+%
+% #3
+% Choose between a harmonic complex or file input
+%  by commenting out unwanted code
+%
+% #4
+% Set the signal rms level (in leveldBSPL)
+%
+% #5
+% Identify the model channel BFs in the vector 'BFlist'.
+%
+% #6
+% Last minute changes to the model parameters can be made using
+%  the cell array of strings 'paramChanges'.
+%  This is used here to control the details of the ACF computations
+%  Read the notes in this section for more information
+%
+% displays:
+% Figure 97 shows the AN response to the stimulus. this is a channel x time
+%  display. The z-axis (and colour) is the AN fiber firing rate
+%
+% Figure 96 shows the P-matrix, the smoothed SACF.
+%
+% Figure 89 shows a summary of the evolution of the unsmoothed SACF 
+%  over time. If you wish to take a snapshot of the P-matrix at a
+%  particular time, this figure can help identify when to take it. 
+%  The index on the y-axis, identifies the required row numbers 
+%    of the P or SACF matrix, e.g. P(:,2000)
+%
+%  On request, (filteredSACFParams.plotACFs=1) Figure 89 shows the channel 
+%   by channel ACFs at intervals during the computation as a movie.
+%  The number of ACF displays is controlled by 'plotACFsInterval'
+%   and the movie can be slowed or speeded up using 'plotMoviePauses' 
+%   (see paramChanges section below).
+
+% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
+% This global will find results from MAP1_14
+global savedInputSignal ANprobRateOutput ANoutput dt dtSpikes savedBFlist 
+ % This global,from model parameter file
+global filteredSACFParams                      
+
+dbstop if error
+restorePath=path;
+addpath (['..' filesep 'MAP'],    ['..' filesep 'wavFileStore'], ...
+    ['..' filesep 'utilities'])
+
+% User sets up requirements
+%%  #1 parameter file name
+MAPparamsName='Normal';                 % recommended
+
+
+%% #2 probability (fast) or spikes (slow) representation: select one
+% AN_spikesOrProbability='spikes';
+%   or
+AN_spikesOrProbability='probability';   % recommended
+
+%% #3 A. harmonic sequence or B. speech file input
+% Comment out unwanted code
+% A. harmonic tone (Hz) - useful to demonstrate a broadband sound
+sampleRate= 44100;              % recommended 44100
+signalType= 'tones';
+duration=0.100;                 % seconds
+beginSilence=0.020;
+endSilence=0.020;
+rampDuration=.005;              % raised cosine ramp (seconds)
+
+% toneFrequency is a vector of component frequencies
+F0=120;
+toneFrequency= [3*F0 4*F0 5*F0];
+
+%   or
+% B. file input
+signalType= 'file';
+fileName='Oh No';
+
+%% #4 rms level
+leveldBSPL= 60;                  % dB SPL (80 for Lieberman)
+
+%% #5 number of channels in the model
+%   21-channel model (log spacing of BFs)
+numChannels=21;
+lowestBF=250; 	highestBF= 6000;
+BFlist=round(logspace(log10(lowestBF), log10(highestBF), numChannels));
+
+%% #6 change model parameters
+% Parameter changes can be used to change one or more model parameters
+%  *after* the MAPparams file has been read (see manual)
+
+% Take control of ACF parameters
+%  The filteredACF parameters are set in the MAPparamsNormal file
+%  However, it is convenient to change them here leving the file intacta
+    minPitch=	80; maxPitch=	500; numPitches=50;  
+    maxLag=1/minPitch; minLag=1/maxPitch;
+    lags= linspace(minLag, maxLag, numPitches);
+    
+paramChanges={...
+    'filteredSACFParams.lags=lags;     % autocorrelation lags vector;',...
+    'filteredSACFParams.acfTau=	2;     % (Wiegrebe) time constant ACF;',...
+    'filteredSACFParams.lambda=	0.12;  % slower filter to smooth ACF;',...
+    'filteredSACFParams.plotACFs=1;    % plot ACFs while computing;',...
+    'filteredSACFParams.plotACFsInterval=0.01;',...
+    'filteredSACFParams.plotMoviePauses=.1;  ',...
+    'filteredSACFParams.usePressnitzer=0; % attenuates ACF at  long lags;',...
+    'filteredSACFParams.lagsProcedure=  ''useAllLags'';',...
+    };
+
+% Notes:
+% acfTau:   time constant of unsmoothed ACF
+% lambda:   time constant of smoothed ACFS
+% plotACFs: plot ACFs during computation (0 to switch off, for speed)
+% plotACFsInterval: sampling interval for plots
+% plotMoviePauses:  pause duration between frames to allow viewing
+% usePressnitzer:   gives low weights to long lags
+% lagsProcedure:    used to fiddle with output (ignore)
+
+%% delare 'showMap' options to control graphical output
+% see UTIL_showMAP for more options
+showMapOptions=[];
+% showMapOptions.showModelOutput=0;     % plot of all stages
+showMapOptions.surfAN=1;                % surface plot of HSR response
+showMapOptions.PSTHbinwidth=0.001;      % smoothing for PSTH
+
+if exist('fileName','var')
+    % needed for labeling plot
+    showMapOptions.fileName=fileName;
+end
+
+%% Generate stimuli
+switch signalType
+    case 'tones'
+        % Create tone stimulus
+        dt=1/sampleRate; % seconds
+        time=dt: dt: duration;
+        inputSignal=sum(sin(2*pi*toneFrequency'*time), 1);
+        amp=10^(leveldBSPL/20)*28e-6;   % converts to Pascals (peak)
+        inputSignal=amp*inputSignal;
+        % apply ramps
+        % catch rampTime error
+        if rampDuration>0.5*duration, rampDuration=duration/2; end
+        rampTime=dt:dt:rampDuration;
+        ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ...
+            ones(1,length(time)-length(rampTime))];
+        inputSignal=inputSignal.*ramp;
+        ramp=fliplr(ramp);
+        inputSignal=inputSignal.*ramp;
+        % add silence
+        intialSilence= zeros(1,round(beginSilence/dt));
+        finalSilence= zeros(1,round(endSilence/dt));
+        inputSignal= [intialSilence inputSignal finalSilence];
+
+    case 'file'
+        %% file input simple or mixed
+        [inputSignal sampleRate]=wavread(fileName);
+        dt=1/sampleRate;
+        inputSignal=inputSignal(:,1);
+        targetRMS=20e-6*10^(leveldBSPL/20);
+        rms=(mean(inputSignal.^2))^0.5;
+        amp=targetRMS/rms;
+        inputSignal=inputSignal*amp;
+end
+
+wavplay(inputSignal, sampleRate)
+
+%% run the model
+
+fprintf('\n')
+disp(['Signal duration= ' num2str(length(inputSignal)/sampleRate)])
+disp([num2str(numChannels) ' channel model: ' AN_spikesOrProbability])
+disp('Computing ...')
+
+MAP1_14(inputSignal, sampleRate, BFlist, ...
+    MAPparamsName, AN_spikesOrProbability, paramChanges);
+
+
+%% The model run is now complete. Now display the results
+% display the AN response
+UTIL_showMAP(showMapOptions)
+
+% compute ACF
+switch AN_spikesOrProbability
+    case 'probability'
+        % use only HSR fibers
+        inputToACF=ANprobRateOutput(end-length(savedBFlist)+1:end,:);
+    otherwise
+        inputToACF=ANoutput;
+        dt=dtSpikes;
+end
+
+disp ('computing ACF...')
+
+% read paramChanges to get new filteredSACFParams
+for i=1:length(paramChanges)
+eval(paramChanges{i});
+end
+
+[P BFlist SACF]= filteredSACF(inputToACF, dt, savedBFlist, filteredSACFParams);
+disp(' ACF done.')
+
+%% plot original waveform on summary/smoothed ACF plot
+figure(96), clf
+subplot(3,1,3)
+t=dt*(1:length(savedInputSignal));
+plot(t,savedInputSignal, 'k')
+xlim([0 t(end)])
+title(['stimulus: ' num2str(leveldBSPL, '%4.0f') ' dB SPL']);
+
+% plot SACF
+figure(96)
+subplot(2,1,1)
+imagesc(P)
+colormap bone
+ylabel('periodicities (Hz)'), xlabel('time (s)')
+title(['smoothed SACF. (periodicity x time)'])
+% y-axis specifies pitches (1/lags)
+% Force MATLAB to show the lowest pitch
+postedYvalues=[1 get(gca,'ytick')]; set(gca,'ytick',postedYvalues)
+pitches=1./filteredSACFParams.lags;
+set(gca,'ytickLabel', round(pitches(postedYvalues)))
+% x-axis is time at which P is samples
+[nCH nTimes]=size(P);
+t=dt:dt:dt*nTimes;
+tt=get(gca,'xtick');
+set(gca,'xtickLabel', round(100*t(tt))/100)
+
+%% On a new figure show a cascade of SACFs
+figure(89), clf
+% select 100 samples;
+[r c]=size(SACF);
+step=round(c/100);
+idx=step:step:c;
+
+UTIL_cascadePlot(SACF(:,idx)', 1./pitches)
+
+xlabel('lag (s)'), ylabel('time pointer -->')
+title(' SACF summary over time')
+yValues=get(gca,'yTick');
+set(gca,'yTickLabel', num2str(yValues'*100))
+
+path(restorePath)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsRM/MAPdemoMultiChOAE.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,105 @@
+function [frequencies fft_ampdB]= ...
+    MAPdemoMultiChOAE (leveldBSPL, toneFrequencies)
+% MAPdemo runs the MATLAB auditory periphery model
+%
+% The OAE is simulated by combining the output from all DRNL channels
+%
+% arguments leveldBSPL and toneFrequencies are optional
+%  defaults are 70 and [5000 6000]
+%
+% e.g. 
+%  MAPdemoMultiChOAE (60, [3000 4000])
+
+
+global dt DRNLoutput
+dbstop if error
+restorePath=path;
+addpath (['..' filesep 'MAP'], ['..' filesep 'utilities'], ...
+    ['..' filesep 'parameterStore'],  ['..' filesep 'wavFileStore'],...
+    ['..' filesep 'testPrograms'])
+
+% set parameter file here
+paramsName='Normal';
+% choose probability because spikes not used to evaluate BM
+AN_spikesOrProbability='probability';
+% add parameter changes here. paramchanges is a cell array of command
+% strings
+paramChanges={};
+
+% DRNL channels
+lowestBF=1000; 	highestBF= 8000; 	numChannels=41;
+% includes BFs at 250 500 1000 2000 4000 8000 (for 11, 21, 31 BFs)
+%  the output from all these filters will be combined to form the OAE
+BFlist=round(logspace(log10(lowestBF), log10(highestBF), numChannels));
+
+if nargin<2
+    toneFrequencies= 2000;            % single pure tone test
+    toneFrequencies=[ 2000 3000]; 	%  F1 F2 for DPOAEs
+    toneFrequencies=[ 5000 6000]; 	%  F1 F2
+end
+duration=0.05;                  % seconds
+duration=0.05;                  % seconds
+rampDuration=.005;
+
+if nargin<1
+    leveldBSPL=70;                  % dB SPL
+end
+amp=10^(leveldBSPL/20)*28e-6;   % converts to Pascals (peak level)
+
+% Create pure stimulus
+sampleRate= 100000;
+dt=1/sampleRate;
+time=dt: dt: duration;
+inputSignal=sum(sin(2*pi*toneFrequencies'*time), 1);
+inputSignal=amp*inputSignal;
+
+% apply ramps
+if rampDuration>0.5*duration, rampDuration=duration/2; end
+rampTime=dt:dt:rampDuration;
+ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ...
+    ones(1,length(time)-length(rampTime))];
+inputSignal=inputSignal.*ramp;  % at the beginning
+ramp=fliplr(ramp);
+inputSignal=inputSignal.*ramp;  % and at the end
+
+% add 10 ms silence
+silenceDuration=0.01;
+silence= zeros(1,round(silenceDuration/dt));
+inputSignal= [silence inputSignal silence];
+time=dt: dt: dt*length(inputSignal);
+
+%% delare 'showMap' options to control graphical output
+showMapOptions.printModelParameters=0;   % prints all parameters
+showMapOptions.showModelOutput=1;       % plot of all stages
+showMapOptions.printFiringRates=1;      % prints stage activity levels
+showMapOptions.showACF=0;               % shows SACF (probability only)
+showMapOptions.showEfferent=0;          % tracks of AR and MOC
+showMapOptions.surfProbability=0;       % 2D plot of HSR response
+showMapOptions.surfSpikes=0;            % 2D plot of spikes histogram
+showMapOptions.ICrates=0;               % IC rates by CNtauGk
+
+
+MAP1_14(inputSignal, 1/dt, BFlist, ...
+    paramsName, AN_spikesOrProbability, paramChanges);
+
+UTIL_showMAP(showMapOptions, paramChanges)
+pause(0.1)
+
+% use this to produce a comnplete record of model parameters
+% UTIL_showAllMAPStructures
+
+OAE=sum(DRNLoutput);
+figure(5),subplot(2,1,1)
+plot(time,OAE)
+title(['F=' num2str(toneFrequencies)])
+[fft_powerdB, fft_phase, frequencies, fft_ampdB]= UTIL_FFT(OAE, dt, 1e-15);
+idx=find(frequencies<1e4);
+
+figure(5),subplot(2,1,2)
+plot(frequencies(idx),fft_ampdB(idx))
+title ('FFT of OAE')
+ylabel('dB')
+ylim([0 100])
+grid on
+
+path(restorePath);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsRM/Pavel_MAP1_14.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,189 @@
+function Pavel_MAP1_14
+% test_MAP1_14 is a general purpose test routine that can be adjusted to
+% test a number of different applications of MAP1_14
+%
+% A range of options are supplied in the early part of the program
+%
+% One use of the function is to create demonstrations; filenames <demoxx>
+%  to illustrate particular features
+%
+% #1
+% Identify the file (in 'MAPparamsName') containing the model parameters
+%
+% #2
+% Identify the kind of model required (in 'AN_spikesOrProbability').
+%  A full brainstem model (spikes) can be computed or a shorter model
+%  (probability) that computes only so far as the auditory nerve
+%
+% #3
+% Choose between a tone signal or file input (in 'signalType')
+%
+% #4
+% Set the signal rms level (in leveldBSPL)
+%
+% #5
+% Identify the channels in terms of their best frequencies in the vector
+%  BFlist.
+%
+% Last minute changes to the parameters fetched earlier can be made using
+%  the cell array of strings 'paramChanges'.
+%  Each string must have the same format as the corresponding line in the
+%  file identified in 'MAPparamsName'
+%
+% When the demonstration is satisfactory, freeze it by renaming it <demoxx>
+
+restorePath=path;
+addpath (['..' filesep 'MAP'],    ['..' filesep 'wavFileStore'], ...
+    ['..' filesep 'utilities'])
+
+%%  #1 parameter file name
+MAPparamsName='Normal';
+
+
+%% #2 probability (fast) or spikes (slow) representation
+AN_spikesOrProbability='spikes';
+
+% or
+% AN_spikesOrProbability='probability';
+% NB probabilities are not corrected for refractory effects
+
+
+%% #3 pure tone, harmonic sequence or speech file input
+signalType= 'tones';
+sampleRate= 100000;
+duration=0.1;                 % seconds
+% toneFrequency= 250:250:8000;    % harmonic sequence (Hz)
+toneFrequency= 1000;            % or a pure tone (Hz8
+rampDuration=.005;              % seconds
+
+% or
+% signalType= 'file';
+% fileName='twister_44kHz';
+
+
+%% #4 rms level
+% signal details
+leveldBSPL= 30;                  % dB SPL
+
+
+%% #5 number of channels in the model
+%   21-channel model (log spacing)
+% numChannels=21;
+% lowestBF=250; 	highestBF= 8000;
+% BFlist=round(logspace(log10(lowestBF), log10(highestBF), numChannels));
+
+%   or specify your own channel BFs
+numChannels=1;
+BFlist=toneFrequency;
+
+
+%% #6 change model parameters
+paramChanges=[];
+
+% or
+% Parameter changes can be used to change one or more model parameters
+%  *after* the MAPparams file has been read
+% This example declares only one fiber type with a calcium clearance time
+% constant of 80e-6 s (HSR fiber) when the probability option is selected.
+% It also removes the speed up that normally takes place for AN spikes
+% It also increases the number of AN fibers computed to 500.
+paramChanges={...
+    'AN_IHCsynapseParams.ANspeedUpFactor=1;', ...
+    'IHCpreSynapseParams.tauCa=86e-6;',...
+    'AN_IHCsynapseParams.numFibers=	500;' };
+
+
+%% delare 'showMap' options to control graphical output
+global showMapOptions
+
+% or (example: show everything including an smoothed SACF output
+showMapOptions.printModelParameters=1;   % prints all parameters
+showMapOptions.showModelOutput=1;       % plot of all stages
+showMapOptions.printFiringRates=1;      % prints stage activity levels
+showMapOptions.showACF=0;               % shows SACF (probability only)
+showMapOptions.showEfferent=0;          % tracks of AR and MOC
+showMapOptions.surfProbability=0;       % 2D plot of HSR response 
+if strcmp(AN_spikesOrProbability, 'spikes')
+    % avoid nonsensical options
+    showMapOptions.surfProbability=0;
+    showMapOptions.showACF=0;
+end
+if strcmp(signalType, 'file')
+    % needed for labeling plot
+    showMapOptions.fileName=fileName;
+else
+    showMapOptions.fileName=[];
+end
+
+%% Generate stimuli
+
+dbstop if error
+restorePath=path;
+addpath (['..' filesep 'MAP'],    ['..' filesep 'wavFileStore'])
+switch signalType
+    case 'tones'
+        inputSignal=createMultiTone(sampleRate, toneFrequency, ...
+            leveldBSPL, duration, rampDuration);
+
+    case 'file'
+        %% file input simple or mixed
+        [inputSignal sampleRate]=wavread(fileName);
+        dt=1/sampleRate;
+        inputSignal=inputSignal(:,1);
+        targetRMS=20e-6*10^(leveldBSPL/20);
+        rms=(mean(inputSignal.^2))^0.5;
+        amp=targetRMS/rms;
+        inputSignal=inputSignal*amp;
+        silence= zeros(1,round(0.1/dt));
+        inputSignal= [silence inputSignal' silence];
+end
+
+
+%% run the model
+tic
+
+fprintf('\n')
+disp(['Signal duration= ' num2str(length(inputSignal)/sampleRate)])
+disp([num2str(numChannels) ' channel model'])
+disp('Computing ...')
+
+
+MAP1_14(inputSignal, sampleRate, BFlist, ...
+    MAPparamsName, AN_spikesOrProbability, paramChanges);
+toc
+
+% the model run is now complete. Now display the results
+% the model run is now complete. Now display the results
+disp(' param changes to list of parameters below')
+for i=1:length(paramChanges)
+    disp(paramChanges{i})
+end
+UTIL_showMAP(showMapOptions)
+
+toc
+path(restorePath)
+
+
+function inputSignal=createMultiTone(sampleRate, toneFrequency, ...
+    leveldBSPL, duration, rampDuration)
+% Create pure tone stimulus
+dt=1/sampleRate; % seconds
+time=dt: dt: duration;
+inputSignal=sum(sin(2*pi*toneFrequency'*time), 1);
+amp=10^(leveldBSPL/20)*28e-6;   % converts to Pascals (peak)
+inputSignal=amp*inputSignal;
+
+% apply ramps
+% catch rampTime error
+if rampDuration>0.5*duration, rampDuration=duration/2; end
+rampTime=dt:dt:rampDuration;
+ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ...
+    ones(1,length(time)-length(rampTime))];
+inputSignal=inputSignal.*ramp;
+ramp=fliplr(ramp);
+inputSignal=inputSignal.*ramp;
+
+% add 10 ms silence
+silence= zeros(1,round(0.03/dt));
+inputSignal= [silence inputSignal silence];
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsRM/pitchModel_RM.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,215 @@
+function pitchModel_RM
+% Modification of testMAP_14 to replicate the pitch model published
+%  in JASA 2006.
+%
+% A range of options are supplied in the early part of the program
+%
+% One use of the function is to create demonstrations; filenames <demoxx>
+%  to illustrate particular features
+%
+% #1
+% Identify the file (in 'MAPparamsName') containing the model parameters
+%
+% #2
+% Identify the kind of model required (in 'AN_spikesOrProbability').
+%  A full brainstem model (spikes) can be computed or a shorter model
+%  (probability) that computes only so far as the auditory nerve
+%
+% #3
+% Choose between a tone signal or file input (in 'signalType')
+%
+% #4
+% Set the signal rms level (in leveldBSPL)
+%
+% #5
+% Identify the channels in terms of their best frequencies in the vector
+%  BFlist.
+%
+% Last minute changes to the parameters fetched earlier can be made using
+%  the cell array of strings 'paramChanges'.
+%  Each string must have the same format as the corresponding line in the
+%  file identified in 'MAPparamsName'
+%
+% When the demonstration is satisfactory, freeze it by renaming it <demoxx>
+
+dbstop if error
+restorePath=path;
+addpath (['..' filesep 'MAP'],    ['..' filesep 'wavFileStore'], ...
+    ['..' filesep 'utilities'])
+
+
+
+% Pitch model modification here
+global ICrate           % used to collect rate profile from showMAP temporary
+rates=[]; F0count=0;
+
+% F0s=[150 200 250];          % fundamental frequency
+% harmonics= 3:5;
+
+% F0s=[3000];          % fundamental frequency
+F0s=50:5:1000;
+harmonics= 1;
+% F0s=150;
+for F0=F0s
+    F0count=F0count+1;
+    
+
+%%  #1 parameter file name
+MAPparamsName='Normal';
+
+
+%% #2 probability (fast) or spikes (slow) representation
+AN_spikesOrProbability='spikes';
+
+% or
+% NB probabilities are not corrected for refractory effects
+% AN_spikesOrProbability='probability';
+
+
+%% #3 pure tone, harmonic sequence or speech file input
+signalType= 'tones';
+sampleRate= 50000;
+duration=0.50;                 % seconds
+% toneFrequency= 1000;            % or a pure tone (Hz8
+
+% F0=210;
+toneFrequency= F0*harmonics;  % harmonic sequence (Hz)
+
+rampDuration=.005;              % raised cosine ramp (seconds)
+
+% or
+
+% signalType= 'file';
+% fileName='twister_44kHz';
+
+
+%% #4 rms level
+% signal details
+leveldBSPL= 50;                  % dB SPL
+
+
+%% #5 number of channels in the model
+%   21-channel model (log spacing)
+numChannels=21;
+lowestBF=250; 	highestBF= 8000;
+BFlist=round(logspace(log10(lowestBF), log10(highestBF), numChannels));
+
+%   or specify your own channel BFs
+% numChannels=1;
+BFlist=toneFrequency;
+% BFlist=500;
+
+
+%% #6 change model parameters
+paramChanges={...
+    'MacGregorMultiParams.currentPerSpike=25e-9;'...
+    'MacGregorMultiParams.tauGk=	[0.1e-3:.00005 : 1e-3];'...
+'MacGregorParams.currentPerSpike=40e-9;'...
+};
+
+%% delare 'showMap' options to control graphical output
+
+showMapOptions.printModelParameters=0;   % prints all parameters
+showMapOptions.showModelOutput=1;       % plot of all stages
+showMapOptions.printFiringRates=1;      % prints stage activity levels
+showMapOptions.showACF=0;               % shows SACF (probability only)
+showMapOptions.showEfferent=0;          % tracks of AR and MOC
+showMapOptions.surfProbability=0;       % 2D plot of HSR response 
+showMapOptions.surfSpikes=0;            % 2D plot of spikes histogram
+showMapOptions.ICrates=1;               % IC rates by CNtauGk
+
+% disable certain silly options
+if strcmp(AN_spikesOrProbability, 'spikes')
+    % avoid nonsensical options
+    showMapOptions.surfProbability=0;
+    showMapOptions.showACF=0;
+else
+    showMapOptions.surfSpikes=0;
+end
+if strcmp(signalType, 'file')
+    % needed for labeling plot
+    showMapOptions.fileName=fileName;
+else
+    showMapOptions.fileName=[];
+end
+
+%% Generate stimuli
+
+switch signalType
+    case 'tones'
+        inputSignal=createMultiTone(sampleRate, toneFrequency, ...
+            leveldBSPL, duration, rampDuration);
+
+    case 'file'
+        %% file input simple or mixed
+        [inputSignal sampleRate]=wavread(fileName);
+        dt=1/sampleRate;
+        inputSignal=inputSignal(:,1);
+        targetRMS=20e-6*10^(leveldBSPL/20);
+        rms=(mean(inputSignal.^2))^0.5;
+        amp=targetRMS/rms;
+        inputSignal=inputSignal*amp;
+        silence= zeros(1,round(0.1/dt));
+        inputSignal= [silence inputSignal' silence];
+end
+
+
+%% run the model
+tic
+
+fprintf('\n')
+disp(['Signal duration= ' num2str(length(inputSignal)/sampleRate)])
+disp([num2str(numChannels) ' channel model'])
+disp([num2str(F0) ' F0'])
+disp('Computing ...')
+
+MAP1_14(inputSignal, sampleRate, BFlist, ...
+    MAPparamsName, AN_spikesOrProbability, paramChanges);
+
+
+% the model run is now complete. Now display the results
+UTIL_showMAP(showMapOptions, paramChanges)
+
+%% pitch model Collect and analyse data
+% ICrate is global and computed in showMAP
+%  a vector of 'stage4' rates; one value for each tauCNGk
+rates=[rates; ICrate];
+figure(92), imagesc(rates)
+ylabel ('F0 no'), xlabel('tauGk')
+% figure(92), plot(rates), ylim([0 inf])
+
+h=figure(99); CNmovie(F0count)=getframe(h);
+figure(91), plot(rates'),ylim([0 inf])
+pause (0.1)
+
+end
+%% show results
+toc
+figure(91), plot(F0s,rates'), xlabel('F0'), ylabel('rate'),ylim([0 inf])
+% figure(99),clf,movie(CNmovie,1,4)
+path(restorePath)
+
+
+function inputSignal=createMultiTone(sampleRate, toneFrequency, ...
+    leveldBSPL, duration, rampDuration)
+% Create pure tone stimulus
+dt=1/sampleRate; % seconds
+time=dt: dt: duration;
+inputSignal=sum(sin(2*pi*toneFrequency'*time), 1);
+amp=10^(leveldBSPL/20)*28e-6;   % converts to Pascals (peak)
+inputSignal=amp*inputSignal;
+
+% apply ramps
+% catch rampTime error
+if rampDuration>0.5*duration, rampDuration=duration/2; end
+rampTime=dt:dt:rampDuration;
+ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ...
+    ones(1,length(time)-length(rampTime))];
+inputSignal=inputSignal.*ramp;
+ramp=fliplr(ramp);
+inputSignal=inputSignal.*ramp;
+
+% add 10 ms silence
+silence= zeros(1,round(0.005/dt));
+inputSignal= [silence inputSignal silence];
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsRM/temp.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,134 @@
+function test_speechInNoise
+
+leveldBSPL= 60;                  % dB SPL
+leveldBSPLNoise=-55;
+
+paramChanges={};
+% no attenuation
+paramChanges={'DRNLParams.rateToAttenuationFactorProb = 0.00; '};
+% fixed attenuation
+% paramChanges={'DRNLParams.rateToAttenuationFactorProb = -0.04;'};
+% % dynamic attenuation
+paramChanges={'DRNLParams.MOCtauProb =.15;', ...
+    'DRNLParams.rateToAttenuationFactorProb = 0.01; '};
+% 
+fileName='twister_44kHz';
+fileName='1o7a_44kHz';
+
+dbstop if error
+restorePath=path;
+addpath (['..' filesep 'MAP'],    ['..' filesep 'wavFileStore'], ...
+    ['..' filesep 'utilities'])
+
+%%  #1 parameter file name
+MAPparamsName='Normal';
+
+
+%% #2 probability (fast) or spikes (slow) representation
+AN_spikesOrProbability='spikes';
+%   or
+AN_spikesOrProbability='probability';
+
+
+%% #3  speech file input
+
+beginSilence=.25;
+endSilence=0.25;
+noiseRampDuration=0.01;
+
+%% #5 number of channels in the model
+%   21-channel model (log spacing)
+numChannels=21;
+lowestBF=300; 	highestBF= 6000;
+BFlist=round(logspace(log10(lowestBF), log10(highestBF), numChannels));
+
+%   or specify your own channel BFs
+% numChannels=1;
+% BFlist=1000;
+
+
+
+%% delare 'showMap' options to control graphical output
+showMapOptions.printModelParameters=1;   % prints all parameters
+showMapOptions.showModelOutput=1;       % plot of all stages
+showMapOptions.printFiringRates=1;      % prints stage activity levels
+showMapOptions.showACF=0;               % shows SACF (probability only)
+showMapOptions.showEfferent=1;          % tracks of AR and MOC
+showMapOptions.surfProbability=1;       % 2D plot of HSR response
+showMapOptions.surfSpikes=0;            % 2D plot of spikes histogram
+showMapOptions.ICrates=0;               % IC rates by CNtauGk
+showMapOptions.PSTHbinwidth=0.002;
+
+% disable certain silly options
+if strcmp(AN_spikesOrProbability, 'spikes')
+    % avoid nonsensical options
+    showMapOptions.surfProbability=0;
+    showMapOptions.showACF=0;
+else
+    showMapOptions.surfSpikes=0;
+end
+    % needed for labeling plot
+    showMapOptions.fileName=fileName;
+
+%% Generate stimuli
+
+        %% file input simple or mixed
+        [inputSignal sampleRate]=wavread(fileName);
+        dt=1/sampleRate;
+        inputSignal=inputSignal(:,1);
+        targetRMS=20e-6*10^(leveldBSPL/20);
+        rms=(mean(inputSignal.^2))^0.5;
+        amp=targetRMS/rms;
+        inputSignal=inputSignal*amp;
+        
+        % add silences
+        intialSilence= zeros(1,round(beginSilence*sampleRate));
+        finalSilence= zeros(1,round(endSilence*sampleRate));
+        inputSignal= [intialSilence inputSignal' finalSilence];
+        
+        [inputNoise sampleRateN]=wavread('babble');
+        inputNoise=inputNoise(1:length(inputSignal));
+       inputNoise=inputNoise(:,1);
+        targetRMS=20e-6*10^(leveldBSPLNoise/20);
+        rms=(mean(inputNoise.^2))^0.5;
+        amp=targetRMS/rms;
+        inputNoise=inputNoise*amp;
+        time=dt: dt: dt*length(inputNoise);
+        rampTime=dt:dt:noiseRampDuration;
+        ramp=[0.5*(1+cos(2*pi*rampTime/(2*noiseRampDuration)+pi)) ...
+            ones(1,length(time)-length(rampTime))];
+        inputNoise=inputNoise'.*ramp;
+        inputSignal=inputSignal+inputNoise;
+        
+
+
+%% run the model
+tic
+
+fprintf('\n')
+disp(['Signal duration= ' num2str(length(inputSignal)/sampleRate)])
+disp([num2str(numChannels) ' channel model'])
+disp('Computing ...')
+
+MAP1_14(inputSignal, sampleRate, BFlist, ...
+    MAPparamsName, AN_spikesOrProbability, paramChanges);
+
+
+%% the model run is now complete. Now display the results
+UTIL_showMAP(showMapOptions, paramChanges)
+figure(97), view([-3 82])
+title(['speech/ noise: ' num2str([leveldBSPL leveldBSPLNoise])])
+
+disp(['level=' num2str(leveldBSPL)])
+disp(['noise level=' num2str(leveldBSPLNoise)])
+
+global DRNLParams
+disp(['attenuation factor =' ...
+    num2str(DRNLParams.rateToAttenuationFactor, '%5.3f') ])
+disp(['attenuation factor (probability)=' ...
+    num2str(DRNLParams.rateToAttenuationFactorProb, '%5.3f') ])
+disp(AN_spikesOrProbability)
+disp(paramChanges)
+toc
+path(restorePath)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsRM/testACF.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,261 @@
+% function [LP_SACF dt lags SACF]= testACF
+% testACF is a *script* to demonstrate the smoothed ACF of
+% Balaguer-Ballestera, E. Denham, S.L. and Meddis, R. (2008).
+%
+% Convert this to a *function* by uncommenting the first line
+%  The function returns the LP_SACF matrix plotted in Figure 96.
+%  If a function is used, the following outputs are returned:
+%   LP_SACF:  smoothed SACF (lags x time matrix)
+%   dt: time interval between successive columns of LP_SACF
+%   lags: lags used in computing LP_SACF
+%   SACF: unsmoothed SACFs
+%
+% A range of options are supplied in the early part of the program
+%
+% #1
+% Identify the model parameter file (in 'MAPparamsName')
+%
+% #2
+% Identify the kind of model required (in 'AN_spikesOrProbability')
+%  'probability' is recommended for ACF work
+%
+% #3
+% Choose between a harmonic complex or file input
+%  by commenting out unwanted code
+%
+% #4
+% Set the signal rms level (in leveldBSPL)
+%
+% #5
+% Identify the model channel BFs in the vector 'BFlist'.
+%
+% #6
+% Last minute changes to the model parameters can be made using
+%  the cell array of strings 'paramChanges'.
+%  This is used here to control the details of the ACF computations
+%  Read the notes in this section for more information
+%
+% displays:
+% Figure 97 shows the AN response to the stimulus. this is a channel x time
+%  display. The z-axis (and colour) is the AN fiber firing rate
+%
+% Figure 96 shows the LP_SACF-matrix, the smoothed SACF.
+%
+% Figure 89 shows a summary of the evolution of the unsmoothed SACF
+%  over time. If you wish to take a snapshot of the LP_SACF-matrix at a
+%  particular time, this figure can help identify when to take it.
+%  The index on the y-axis, identifies the required row numbers
+%    of the LP_SACF or SACF matrix, e.g. LP_SACF(:,2000)
+%
+%  On request, (filteredSACFParams.plotACFs=1) Figure 89 shows the channel
+%   by channel ACFs at intervals during the computation as a movie.
+%  The number of ACF displays is controlled by 'plotACFsInterval'
+%   and the movie can be slowed or speeded up using 'plotMoviePauses'
+%   (see paramChanges section below).
+
+% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+% This global will find results from MAP1_14
+global savedInputSignal ANprobRateOutput ANoutput dt dtSpikes savedBFlist
+% This global,from model parameter file
+global filteredSACFParams
+
+% User sets up requirements
+%%  #1 parameter file name
+MAPparamsName='Normal';                 % recommended
+
+
+%% #2 probability (fast) or spikes (slow) representation: select one
+% AN_spikesOrProbability='spikes';
+%   or
+AN_spikesOrProbability='probability';   % recommended
+
+%% #3 A. harmonic sequence or B. speech file input
+% Comment out unwanted code
+% A. harmonic tone (Hz) - useful to demonstrate a broadband sound
+sampleRate= 44100;              % recommended 44100
+signalType= 'tones';
+duration=0.100;                 % seconds
+beginSilence=0.020;
+endSilence=0.020;
+rampDuration=.005;              % raised cosine ramp (seconds)
+
+% toneFrequency is a vector of component frequencies
+F0=120;
+toneFrequency= [3*F0 4*F0 5*F0];
+
+%   or
+% B. file input
+% signalType= 'file';
+% fileName='Oh No';
+% fileName='twister_44kHz';
+
+%% #4 rms level
+leveldBSPL= 100;                  % dB SPL (80 for Lieberman)
+
+%% #5 number of channels in the model
+%   21-channel model (log spacing of BFs)
+numChannels=21;
+lowestBF=250; 	highestBF= 5000;
+BFlist=round(logspace(log10(lowestBF), log10(highestBF), numChannels));
+
+%% #6 change model parameters
+% Parameter changes can be used to change one or more model parameters
+%  *after* the MAPparams file has been read (see manual)
+
+% Take control of ACF parameters
+%  The filteredACF parameters are set in the MAPparamsNormal file
+%  However, it is convenient to change them here leving the file intacta
+minPitch=	400; maxPitch=	3000; numPitches=200;
+maxLag=1/minPitch; minLag=1/maxPitch;
+lags= linspace(minLag, maxLag, numPitches);
+
+paramChanges={...
+    'filteredSACFParams.lags=lags;     % autocorrelation lags vector;',...
+    'filteredSACFParams.acfTau=	2;     % (Wiegrebe) time constant ACF;',...
+    'filteredSACFParams.lambda=	0.12;  % slower filter to smooth ACF;',...
+    'filteredSACFParams.plotACFs=1;    % plot ACFs while computing;',...
+    'filteredSACFParams.plotACFsInterval=0.01;',...
+    'filteredSACFParams.plotMoviePauses=.1;  ',...
+    'filteredSACFParams.usePressnitzer=0; % attenuates ACF at  long lags;',...
+    'filteredSACFParams.lagsProcedure=  ''useAllLags'';',...
+    };
+
+% Notes:
+% acfTau:   time constant of unsmoothed ACF
+% lambda:   time constant of smoothed ACFS
+% plotACFs: plot ACFs during computation (0 to switch off, for speed)
+% plotACFsInterval: sampling interval for plots
+% plotMoviePauses:  pause duration between frames to allow viewing
+% usePressnitzer:   gives low weights to long lags
+% lagsProcedure:    used to fiddle with output (ignore)
+
+%% delare 'showMap' options to control graphical output
+% see UTIL_showMAP for more options
+showMapOptions=[];
+% showMapOptions.showModelOutput=0;     % plot of all stages
+showMapOptions.surfAN=1;                % surface plot of HSR response
+showMapOptions.PSTHbinwidth=0.001;      % smoothing for PSTH
+
+if exist('fileName','var')
+    % needed for labeling plot
+    showMapOptions.fileName=fileName;
+end
+
+%% Generate stimuli
+switch signalType
+    case 'tones'
+        % Create tone stimulus
+        dt=1/sampleRate; % seconds
+        time=dt: dt: duration;
+        inputSignal=sum(sin(2*pi*toneFrequency'*time), 1);
+        amp=10^(leveldBSPL/20)*28e-6;   % converts to Pascals (peak)
+        inputSignal=amp*inputSignal;
+        % apply ramps
+        % catch rampTime error
+        if rampDuration>0.5*duration, rampDuration=duration/2; end
+        rampTime=dt:dt:rampDuration;
+        ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ...
+            ones(1,length(time)-length(rampTime))];
+        inputSignal=inputSignal.*ramp;
+        ramp=fliplr(ramp);
+        inputSignal=inputSignal.*ramp;
+        % add silence
+        intialSilence= zeros(1,round(beginSilence/dt));
+        finalSilence= zeros(1,round(endSilence/dt));
+        inputSignal= [intialSilence inputSignal finalSilence];
+
+    case 'file'
+        %% file input simple or mixed
+        [inputSignal sampleRate]=wavread(fileName);
+        dt=1/sampleRate;
+        inputSignal=inputSignal(:,1);
+        targetRMS=20e-6*10^(leveldBSPL/20);
+        rms=(mean(inputSignal.^2))^0.5;
+        amp=targetRMS/rms;
+        inputSignal=inputSignal*amp;
+end
+
+wavplay(inputSignal, sampleRate)
+
+%% run the model
+dbstop if error
+restorePath=path;
+addpath (['..' filesep 'MAP'],    ['..' filesep 'wavFileStore'], ...
+    ['..' filesep 'utilities'])
+
+fprintf('\n')
+disp(['Signal duration= ' num2str(length(inputSignal)/sampleRate)])
+disp([num2str(numChannels) ' channel model: ' AN_spikesOrProbability])
+disp('Computing MAP ...')
+
+MAP1_14(inputSignal, sampleRate, BFlist, ...
+    MAPparamsName, AN_spikesOrProbability, paramChanges);
+
+
+%% The model run is now complete. Now display the results
+% display the AN response
+UTIL_showMAP(showMapOptions)
+
+% compute ACF
+switch AN_spikesOrProbability
+    case 'probability'
+        % use only HSR fibers
+        inputToACF=ANprobRateOutput(end-length(savedBFlist)+1:end,:);
+    otherwise
+        inputToACF=ANoutput;
+        dt=dtSpikes;
+end
+
+disp ('computing ACF...')
+
+% read paramChanges to get new filteredSACFParams
+for i=1:length(paramChanges)
+    eval(paramChanges{i});
+end
+
+[LP_SACF BFlist SACF]= filteredSACF(inputToACF, dt, savedBFlist, ...
+    filteredSACFParams);
+disp(' ACF done.')
+
+%% plot original waveform on summary/smoothed ACF plot
+figure(96), clf
+subplot(3,1,3)
+t=dt*(1:length(savedInputSignal));
+plot(t,savedInputSignal, 'k')
+xlim([0 t(end)])
+title(['stimulus: ' num2str(leveldBSPL, '%4.0f') ' dB SPL']);
+
+% plot SACF
+figure(96)
+subplot(2,1,1)
+imagesc(LP_SACF)
+colormap bone
+ylabel('periodicities (Hz)'), xlabel('time (s)')
+title(['smoothed SACF. (periodicity x time)'])
+% y-axis specifies pitches (1/lags)
+% Force MATLAB to show the lowest pitch
+postedYvalues=[1 get(gca,'ytick')]; set(gca,'ytick',postedYvalues)
+pitches=1./filteredSACFParams.lags;
+set(gca,'ytickLabel', round(pitches(postedYvalues)))
+% x-axis is time at which LP_SACF is samples
+[nCH nTimes]=size(LP_SACF);
+t=dt:dt:dt*nTimes;
+tt=get(gca,'xtick');
+set(gca,'xtickLabel', round(100*t(tt))/100)
+
+%% On a new figure show a cascade of SACFs
+figure(89), clf
+% select 100 samples;
+[r c]=size(SACF);
+step=round(c/100);
+idx=step:step:c;
+
+UTIL_cascadePlot(SACF(:,idx)', 1./pitches)
+
+xlabel('lag (s)'), ylabel('time pointer -->')
+title(' SACF summary over time')
+yValues=get(gca,'yTick');
+set(gca,'yTickLabel', num2str(yValues'*100))
+
+path(restorePath)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsRM/testDPOAE.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,25 @@
+% testDPOAE
+
+addpath (['..' filesep 'testPrograms'])
+
+leveldB=60;
+f1=3000;
+frequencyDiffs=20:20:1000;
+result=[];
+frequenciesSoFar=[];
+for f2=f1+frequencyDiffs
+    [frequencies fft_ampdB]=testDPOAE (leveldB, [f1 f2]);
+    dpFreq=2*f1-f2;
+    [a idx]=min((frequencies-dpFreq).^2);
+    result=[result fft_ampdB(idx)];
+    frequenciesSoFar=[frequenciesSoFar dpFreq];
+    figure(4), plot(frequenciesSoFar, result)
+    title(['F1= ' num2str(f1) '  F2= ' ...
+        num2str(f1+ [min(frequencyDiffs) max(frequencyDiffs)])...
+        '  leveldB= ' num2str(leveldB)])
+    xlabel('DP (2f1- f2) frequency'), ylim([0 100])
+end
+
+grid on
+
+disp(result)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsRM/test_Dolan_and_Nuttall.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,298 @@
+function test_Dolan_and_Nuttall
+% test_MAP1_14 is a general purpose test routine that can be adjusted to
+% test a number of different applications of MAP1_14
+%
+% A range of options are supplied in the early part of the program
+%
+% One use of the function is to create demonstrations; filenames <demoxx>
+%  to illustrate particular features
+%
+% #1
+% Identify the file (in 'MAPparamsName') containing the model parameters
+%
+% #2
+% Identify the kind of model required (in 'AN_spikesOrProbability').
+%  A full brainstem model (spikes) can be computed or a shorter model
+%  (probability) that computes only so far as the auditory nerve
+%
+% #3
+% Choose between a tone signal or file input (in 'signalType')
+%
+% #4
+% Set the signal rms level (in leveldBSPL)
+%
+% #5
+% Identify the channels in terms of their best frequencies in the vector
+%  BFlist.
+%
+% Last minute changes to the parameters fetched earlier can be made using
+%  the cell array of strings 'paramChanges'.
+%  Each string must have the same format as the corresponding line in the
+%  file identified in 'MAPparamsName'
+%
+% When the demonstration is satisfactory, freeze it by renaming it <demoxx>
+
+global dt dtSpikes  savedBFlist saveAN_spikesOrProbability saveMAPparamsName...
+    savedInputSignal OMEextEarPressure TMoutput OMEoutput ARattenuation ...
+    DRNLoutput IHC_cilia_output IHCrestingCiliaCond IHCrestingV...
+    IHCoutput ANprobRateOutput ANoutput savePavailable ANtauCas  ...
+    CNtauGk CNoutput  ICoutput ICmembraneOutput ICfiberTypeRates ...
+    MOCattenuation
+global OMEParams DRNLParams IHC_cilia_RPParams IHCpreSynapseParams
+global AN_IHCsynapseParams MacGregorParams MacGregorMultiParams
+global ICrate
+
+
+dbstop if error
+restorePath=path;
+addpath (['..' filesep 'MAP'],    ['..' filesep 'wavFileStore'], ...
+    ['..' filesep 'utilities'])
+
+%%  #1 parameter file name
+MAPparamsName='Normal';
+
+
+%% #2 probability (fast) or spikes (slow) representation
+AN_spikesOrProbability='spikes';
+%   or
+% AN_spikesOrProbability='probability';
+
+
+%% #3 pure tone, harmonic sequence or speech file input
+signalType= 'tones';
+toneFrequency= 4000;            % or a pure tone (Hz)
+
+sampleRate= 44100;          % must agree with noise
+duration=0.010;                 % seconds
+beginSilence=0.010;
+endSilence=0.010;
+rampDuration=.001;              % raised cosine ramp (seconds)
+noiseRampDuration=0.002;
+
+%   or
+% harmonic sequence (Hz)
+% F0=210;
+% toneFrequency= F0:F0:8000;
+
+%   or
+% signalType= 'file';
+% fileName='twister_44kHz';
+
+
+
+% %% #4 rms level
+% % signal details
+% leveldBSPL= 80;                  % dB SPL (80 for Lieberman)
+% leveldBSPLNoise=-30;
+
+%% #5 number of channels in the model
+%   21-channel model (log spacing)
+numChannels=21;
+lowestBF=250; 	highestBF= 8000;
+BFlist=round(logspace(log10(lowestBF), log10(highestBF), numChannels));
+
+% %   or specify your own channel BFs
+% numChannels=1;
+% BFlist=toneFrequency;
+
+
+%% #6 change model parameters
+
+paramChanges={};
+
+% Parameter changes can be used to change one or more model parameters
+%  *after* the MAPparams file has been read
+% This example declares only one fiber type with a calcium clearance time
+% constant of 80e-6 s (HSR fiber) when the probability option is selected.
+% paramChanges={'AN_IHCsynapseParams.ANspeedUpFactor=5;', ...
+%     'IHCpreSynapseParams.tauCa=86e-6; '};
+% paramChanges={'DRNLParams.MOCtauProb =.25;', ...
+%     'DRNLParams.rateToAttenuationFactorProb = 0.02; '};
+
+paramChanges={'AN_IHCsynapseParams.numFibers=	50; ',...
+    'DRNLParams.MOCtauProb =.15;', ...
+    'DRNLParams.rateToAttenuationFactorProb = 0.00; '};
+
+% paramChanges={'AN_IHCsynapseParams.numFibers=	50; ',...
+% 'DRNLParams.rateToAttenuationFactorProb = -0.007;'};
+
+
+%% delare 'showMap' options to control graphical output
+showMapOptions.printModelParameters=1;   % prints all parameters
+showMapOptions.showModelOutput=0;       % plot of all stages
+showMapOptions.printFiringRates=1;      % prints stage activity levels
+showMapOptions.showACF=0;               % shows SACF (probability only)
+showMapOptions.showEfferent=1;          % tracks of AR and MOC
+showMapOptions.surfProbability=1;       % 2D plot of HSR response
+showMapOptions.surfSpikes=1;            % 2D plot of spikes histogram
+showMapOptions.ICrates=0;               % IC rates by CNtauGk
+
+% disable certain silly options
+if strcmp(AN_spikesOrProbability, 'spikes')
+    % avoid nonsensical options
+    showMapOptions.surfProbability=0;
+    showMapOptions.showACF=0;
+end
+
+if strcmp(signalType, 'file')
+    % needed for labeling plot
+    showMapOptions.fileName=fileName;
+else
+    showMapOptions.fileName=[];
+end
+
+fprintf('\n')
+disp([num2str(numChannels) ' channel model: ' AN_spikesOrProbability])
+disp('Computing ...')
+
+%%systematic
+probeLevels=30:10:80;
+noiseLevels=[-100 30];
+noRepeats=10;
+
+% probeLevels=80;
+% noiseLevels=[-30];
+% noRepeats=10;
+
+peakCAPs=zeros(4,length(probeLevels));
+
+for noiseCondition=1:length(noiseLevels)
+    leveldBSPLNoise=noiseLevels(noiseCondition);
+    levelNo=0;
+    for probeLevel=probeLevels
+        leveldBSPL=probeLevel;
+        levelNo=levelNo+1;
+        summedCAP=[];
+        for repeatNo= 1:noRepeats
+            disp(['repeat no: ' num2str(repeatNo)])
+            %% Generate stimuli
+
+            switch signalType
+                case 'tones'
+                    % Create pure tone stimulus
+                    dt=1/sampleRate; % seconds
+                    time=dt: dt: duration;
+                    inputSignal=sum(sin(2*pi*toneFrequency'*time), 1);
+                    amp=10^(leveldBSPL/20)*28e-6;   % converts to Pascals (peak)
+                    inputSignal=amp*inputSignal;
+                    % apply ramps
+                    % catch rampTime error
+                    if rampDuration>0.5*duration, rampDuration=duration/2; end
+                    rampTime=dt:dt:rampDuration;
+                    ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ...
+                        ones(1,length(time)-length(rampTime))];
+                    inputSignal=inputSignal.*ramp;
+                    ramp=fliplr(ramp);
+                    inputSignal=inputSignal.*ramp;
+                    % add silence
+                    intialSilence= zeros(1,round(beginSilence/dt));
+                    finalSilence= zeros(1,round(endSilence/dt));
+                    inputSignal= [intialSilence inputSignal finalSilence];
+
+                    %         [inputNoise sampleRateN]=wavread('babble');
+                    [inputNoise sampleRateN]=wavread('white noise');
+                    inputNoise=inputNoise(1:length(inputSignal));
+                    inputNoise=inputNoise(:,1);
+                    targetRMS=20e-6*10^(leveldBSPLNoise/20);
+                    rms=(mean(inputNoise.^2))^0.5;
+                    amp=targetRMS/rms;
+                    inputNoise=inputNoise*amp;
+                    time=dt: dt: dt*length(inputNoise);
+                    rampTime=dt:dt:noiseRampDuration;
+                    ramp=[0.5*(1+cos(2*pi*rampTime/(2*noiseRampDuration)+pi)) ...
+                        ones(1,length(time)-length(rampTime))];
+                    inputNoise=inputNoise'.*ramp;
+                    ramp=fliplr(ramp);
+                    inputNoise=inputNoise.*ramp;
+
+                    inputSignal=inputSignal+inputNoise;
+                    intialSilence= zeros(1,round(beginSilence/dt));
+                    finalSilence= zeros(1,round(endSilence/dt));
+                    inputSignal= [intialSilence inputSignal finalSilence];
+
+                    toneOnset=2*beginSilence;
+
+                    figure(2), subplot(3,1,1)
+                    time=dt:dt:dt*length(inputSignal);
+                    plot(time,inputSignal,'k')
+
+                case 'file'
+                    %% file input simple or mixed
+                    [inputSignal sampleRate]=wavread(fileName);
+                    dt=1/sampleRate;
+                    inputSignal=inputSignal(:,1);
+                    targetRMS=20e-6*10^(leveldBSPL/20);
+                    rms=(mean(inputSignal.^2))^0.5;
+                    amp=targetRMS/rms;
+                    inputSignal=inputSignal*amp;
+                    intialSilence= zeros(1,round(0.1/dt));
+                    finalSilence= zeros(1,round(0.2/dt));
+                    inputSignal= [intialSilence inputSignal' finalSilence];
+
+            end
+
+
+            %% run the model
+            tic
+
+            MAP1_14(inputSignal, sampleRate, BFlist, ...
+                MAPparamsName, AN_spikesOrProbability, paramChanges);
+
+
+            %% the model run is now complete. Now display the results
+                %                 UTIL_showMAP(showMapOptions, paramChanges)
+
+                wholeNerveCAP  = UTIL_CAPgenerator...
+                    (ANoutput, dtSpikes, BFlist, AN_IHCsynapseParams.numFibers, 1);
+
+                if isempty(summedCAP)
+                    summedCAP=wholeNerveCAP;
+                else
+                    summedCAP=summedCAP+wholeNerveCAP;
+                end
+
+                switch AN_spikesOrProbability
+                    case 'spikes'
+                        ANoutput = sum(ANoutput, 1);
+                    case 'probability'
+                        ANoutput = ANprobRateOutput(13+21,:);
+                end
+                figure(2), subplot(3,1,2), plot(ANoutput)
+                spikeTimes=dtSpikes:dtSpikes:dtSpikes* length(wholeNerveCAP);
+                figure(2), subplot(3,1,3), plot(spikeTimes,summedCAP/repeatNo)
+                ylim([-50 50])
+        end % repeat
+
+        spikeTimes=dtSpikes:dtSpikes:dtSpikes* length(wholeNerveCAP);
+        idx=find(spikeTimes>toneOnset & ...
+            spikeTimes>toneOnset+duration+.005);
+        averageCAP=summedCAP/repeatNo;
+        peakCAP=max(averageCAP(idx));
+        peakCAPs(noiseCondition,levelNo)=peakCAPs(noiseCondition,levelNo)+ peakCAP;
+
+        if strcmp(signalType,'tones')
+            disp(['duration=' num2str(duration)])
+            disp(['level=' num2str(leveldBSPL)])
+            disp(['toneFrequency=' num2str(toneFrequency)])
+            disp(['leveldBSPLNoise=' num2str(leveldBSPLNoise)])
+
+            disp(['attenuation factor =' ...
+                num2str(DRNLParams.rateToAttenuationFactor, '%5.3f') ])
+            disp(['attenuation factor (probability)=' ...
+                num2str(DRNLParams.rateToAttenuationFactorProb, '%5.3f') ])
+            disp(AN_spikesOrProbability)
+        end
+
+
+        disp([ 'peak CAP ' num2str(peakCAP)])
+
+        for i=1:length(paramChanges)
+            disp(paramChanges{i})
+        end
+    end % probe level
+    figure(9), subplot(3,1,3), plot(probeLevels,peakCAPs)
+end % condition
+%%
+
+path(restorePath)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsRM/test_MAP1_14Hopkins.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,194 @@
+function test_MAP1_14Hopkins
+% test_MAP1_14 is a general purpose test routine that can be adjusted to
+% test a number of different applications of MAP1_14
+%
+% A range of options are supplied in the early part of the program
+%
+% One use of the function is to create demonstrations; filenames <demoxx>
+%  to illustrate particular features
+%
+% #1
+% Identify the file (in 'MAPparamsName') containing the model parameters
+%
+% #2
+% Identify the kind of model required (in 'AN_spikesOrProbability').
+%  A full brainstem model (spikes) can be computed or a shorter model
+%  (probability) that computes only so far as the auditory nerve
+%
+% #3
+% Choose between a tone signal or file input (in 'signalType')
+%
+% #4
+% Set the signal rms level (in leveldBSPL)
+%
+% #5
+% Identify the channels in terms of their best frequencies in the vector
+%  BFlist.
+%
+% Last minute changes to the parameters fetched earlier can be made using
+%  the cell array of strings 'paramChanges'.
+%  Each string must have the same format as the corresponding line in the
+%  file identified in 'MAPparamsName'
+%
+% When the demonstration is satisfactory, freeze it by renaming it <demoxx>
+
+dbstop if error
+restorePath=path;
+addpath (['..' filesep 'MAP'],    ['..' filesep 'wavFileStore'], ...
+    ['..' filesep 'utilities'])
+
+%%  #1 parameter file name
+MAPparamsName='Normal';
+
+
+%% #2 probability (fast) or spikes (slow) representation
+AN_spikesOrProbability='spikes';
+%   or
+AN_spikesOrProbability='probability';
+
+
+%% #3 pure tone, harmonic sequence or speech file input
+signalType= 'tones';
+sampleRate= 50000;
+duration=0.100;                 % seconds
+rampDuration=.005;              % raised cosine ramp (seconds)
+beginSilence=0.050;               
+endSilence=0.050;                  
+toneFrequency= 1000;            % or a pure tone (Hz)
+
+%   or
+% harmonic sequence (Hz)
+F0=1000/11;
+toneFrequency= 10*F0:F0:12*F0;    
+
+%   or
+% signalType= 'file';
+% fileName='twister_44kHz';
+
+
+
+%% #4 rms level
+% signal details
+leveldBSPL= [44 50 44];                  % dB SPL (80 for Lieberman)
+leveldBSPL= [50 50 50];                  % dB SPL (80 for Lieberman)
+noiseLevel=-35;
+
+%% #5 number of channels in the model
+%   21-channel model (log spacing)
+numChannels=21;
+lowestBF=500; 	highestBF= 2000;
+BFlist=round(logspace(log10(lowestBF), log10(highestBF), numChannels));
+
+%   or specify your own channel BFs
+numChannels=1;
+BFlist=1000;
+
+
+%% #6 change model parameters
+
+paramChanges={};
+
+% Parameter changes can be used to change one or more model parameters
+%  *after* the MAPparams file has been read
+% This example declares only one fiber type with a calcium clearance time
+% constant of 80e-6 s (HSR fiber) when the probability option is selected.
+% paramChanges={'AN_IHCsynapseParams.ANspeedUpFactor=5;', ...
+%     'IHCpreSynapseParams.tauCa=86e-6; '};
+
+
+
+%% delare 'showMap' options to control graphical output
+showMapOptions.printModelParameters=1;   % prints all parameters
+showMapOptions.showModelOutput=1;       % plot of all stages
+showMapOptions.printFiringRates=1;      % prints stage activity levels
+showMapOptions.showACF=0;               % shows SACF (probability only)
+showMapOptions.showEfferent=0;          % tracks of AR and MOC
+showMapOptions.surfProbability=1;       % 2D plot of HSR response 
+showMapOptions.surfSpikes=0;            % 2D plot of spikes histogram
+showMapOptions.ICrates=0;               % IC rates by CNtauGk
+showMapOptions.PSTHbinwidth=0.001;
+showMapOptions.colorbar=0;
+showMapOptions.view=[0 90];
+
+% disable certain silly options
+if strcmp(AN_spikesOrProbability, 'spikes')
+    % avoid nonsensical options
+    showMapOptions.surfProbability=0;
+    showMapOptions.showACF=0;
+end
+
+if strcmp(signalType, 'file')
+    % needed for labeling plot
+    showMapOptions.fileName=fileName;
+else
+    showMapOptions.fileName=[];
+end
+
+%% Generate stimuli
+
+switch signalType
+    case 'tones'
+        % Create pure tone stimulus
+        dt=1/sampleRate; % seconds
+        time=dt: dt: duration;
+        amp=10.^(leveldBSPL/20)*28e-6;   % converts to Pascals (peak)
+        inputSignal=sin(2*pi*toneFrequency'*time);
+        amps=repmat(amp',1,length(time));
+        inputSignal=amps.*inputSignal;
+        inputSignal=sum(inputSignal, 1);
+        % apply ramps
+        % catch rampTime error
+        if rampDuration>0.5*duration, rampDuration=duration/2; end
+        rampTime=dt:dt:rampDuration;
+        ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ...
+            ones(1,length(time)-length(rampTime))];
+        inputSignal=inputSignal.*ramp;
+        ramp=fliplr(ramp);
+        inputSignal=inputSignal.*ramp;
+        % add silence
+        intialSilence= zeros(1,round(beginSilence/dt));
+        finalSilence= zeros(1,round(endSilence/dt));
+        inputSignal= [intialSilence inputSignal finalSilence];
+
+        %% TEN noise input simple or mixed
+        [noise sampleRate]=wavread('TEN.wav');
+        dt=1/sampleRate;
+        noise=noise(:,1);
+        targetRMS=20e-6*10^(noiseLevel/20);
+        rms=(mean(noise.^2))^0.5;
+        amp=targetRMS/rms;
+        noise=noise*amp;
+        inputSignal=inputSignal+noise(1:length(inputSignal))';
+end
+
+
+%% run the model
+tic
+fprintf('\n')
+disp(['Signal duration= ' num2str(length(inputSignal)/sampleRate)])
+disp([num2str(numChannels) ' channel model: ' AN_spikesOrProbability])
+disp('Computing ...')
+
+MAP1_14(inputSignal, sampleRate, BFlist, ...
+    MAPparamsName, AN_spikesOrProbability, paramChanges);
+
+
+%% the model run is now complete. Now display the results
+UTIL_showMAP(showMapOptions, paramChanges)
+figure(97)
+title (['tones / noise levels: ' num2str([leveldBSPL noiseLevel])])
+if strcmp(signalType,'tones')
+    disp(['duration=' num2str(duration)])
+    disp(['level=' num2str(leveldBSPL)])
+    disp(['toneFrequency=' num2str(toneFrequency)])
+    global DRNLParams
+    disp(['attenuation factor =' ...
+        num2str(DRNLParams.rateToAttenuationFactor, '%5.3f') ])
+    disp(['attenuation factor (probability)=' ...
+        num2str(DRNLParams.rateToAttenuationFactorProb, '%5.3f') ])
+    disp(AN_spikesOrProbability)
+end
+disp(paramChanges)
+toc
+path(restorePath)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsRM/test_MAP1_14RAM.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,174 @@
+function test_DRNL_Ruggero97
+% test_DRNL_Ruggero97 attempts to match Ruggero's (1992 and 1997)
+%  iso-intensity data by fiddling with the parameters
+
+% # BF is the BF of the filter to be assessed
+BF=9000;
+
+% # test frequencies. check that BF is one of them
+%    copy Ruggero's test tones as fara as possible
+numFs=6; lowestF=4000; 	highestF= 11030;
+toneFrequencyList=round(logspace(log10(lowestF), log10(highestF), numFs));
+
+%  # parameter file name. this is the base set of parameters
+MAPparamsName='Normal';
+
+% # probability representation (not directly relevant here as only
+%    the DRNL output is used
+AN_spikesOrProbability='probability';
+
+% # tone characteristics
+sampleRate= 100000;
+duration=0.0200;                % Ruggero uses 5, 10, 25 ms tones
+rampDuration=0.0015;              % raised cosine ramp (seconds)
+beginSilence=0.050;
+endSilence=0.020;
+
+% # levels
+levels=[3 10:10:80];
+
+%% # change model parameters
+% Parameter changes can be used to change one or more model parameters
+%  *after* the MAPparams file has been read
+
+paramChanges={};
+% switch off all efferent effects and then play with DRNL params
+paramChanges={...
+    'DRNLParams.rateToAttenuationFactorProb = 0.00; ',...
+    'OMEParams.rateToAttenuationFactorProb=0.0;', ...
+    'DRNLParams.ctBMdB = -20;'...
+    'DRNLParams.g=1000;'...
+    'DRNLParams.linCFs=7000;'...
+    'DRNLParams.linBWs=3500;'...
+    };
+
+% delare 'showMap' options to control graphical output
+% (not needed but might be useful
+% showMapOptions.printModelParameters=0;   % prints all parameters
+% showMapOptions.showModelOutput=1;       % plot of all stages
+% showMapOptions.printFiringRates=0;      % prints stage activity levels
+% showMapOptions.showACF=0;               % shows SACF (probability only)
+% showMapOptions.showEfferent=0;          % tracks of AR and MOC
+% showMapOptions.surfProbability=0;       % 2D plot of HSR response
+% showMapOptions.surfSpikes=0;            % 2D plot of spikes histogram
+% showMapOptions.ICrates=0;               % IC rates by CNtauGk
+% showMapOptions.fileName=[];
+
+% run the program
+global dt  DRNLoutput DRNLParams TMoutput
+dbstop if error
+restorePath=path; 
+addpath (['..' filesep 'MAP'],    ['..' filesep 'wavFileStore'], ...
+    ['..' filesep 'utilities'])
+figure(2), clf,figure(3), clf,figure(4), clf,
+
+peakOutputDisp=zeros(length(levels),length(toneFrequencyList));
+peakStapesDisp=zeros(length(levels),length(toneFrequencyList));
+
+%% now vary level and frequency while measuring the response
+levelNo=0;
+for leveldBSPL=levels
+    levelNo=levelNo+1;
+    disp(['level: ' num2str(leveldBSPL)])
+
+    freqNo=0;
+    for toneFrequency=toneFrequencyList
+        freqNo=freqNo+1;
+
+        %% Generate stimuli
+        dt=1/sampleRate;
+        time=dt: dt: duration;
+        inputSignal=sum(sin(2*pi*toneFrequency'*time), 1);
+        amp=10^(leveldBSPL/20)*28e-6;   % converts to Pascals (peak)
+        inputSignal=amp*inputSignal;
+        % apply ramps
+        if rampDuration>0.5*duration, rampDuration=duration/2; end
+        rampTime=dt:dt:rampDuration;
+        ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ...
+            ones(1,length(time)-length(rampTime))];
+        inputSignal=inputSignal.*ramp;
+        ramp=fliplr(ramp);
+        inputSignal=inputSignal.*ramp;
+        % add silence
+        intialSilence= zeros(1,round(beginSilence/dt));
+        finalSilence= zeros(1,round(endSilence/dt));
+        inputSignal= [intialSilence inputSignal finalSilence];
+
+        %% run the model
+    
+        MAP1_14(inputSignal, sampleRate, BF, ...
+            MAPparamsName, AN_spikesOrProbability, paramChanges);
+
+        peakOutputDisp(levelNo,freqNo)=max(DRNLoutput);
+        peakStapesDisp(levelNo,freqNo)=max(TMoutput);
+
+        % the model run is complete. Now display the results if debugging
+        % UTIL_showMAP(showMapOptions, paramChanges)
+    end % probe frequencies
+    
+    % monitor progress
+    figure(2), loglog(toneFrequencyList, peakOutputDisp), hold on
+    xlabel('frequency')
+    ylabel('peak DRNL displacement (m)')
+    title ('DRNL uncorrected displacement')
+end  % levels
+figure(2),legend(num2str(toneFrequencyList'),'location','northwest')
+
+% convert from model BM displacement to Ruggero's velocity
+DRNLvelocity= peakOutputDisp ...
+    .*repmat(2*pi*toneFrequencyList,length(levels),1);
+% convert from model stapes displacement to Ruggero's velocity
+stapesVelocity= peakStapesDisp ...
+    .*repmat(2*pi*toneFrequencyList,length(levels),1);
+% velocity gain is increased velocity attributable to the DRNL
+DRNLvelocityGain = DRNLvelocity./stapesVelocity;
+DRNLvelocityGain_dB= 20*log10(DRNLvelocityGain );
+% iso-intensity equates all functions at the same outpu for the lowest
+%  velocity tested
+isoIntensityDRNLvel_dB= DRNLvelocityGain_dB- ...
+    repmat(DRNLvelocityGain_dB(:,1),1,length(toneFrequencyList));
+
+% displays
+% iso-velocity function (nrmalised by stapes velocity)
+figure(3), clf, semilogx(toneFrequencyList, isoIntensityDRNLvel_dB)
+ylim([-10 60])
+xlim([2000 20000])
+xlabel('frequency')
+ylabel('peak DRNL velocity gain (dB)')
+title(['CF= ' num2str(BF) ' Hz'])
+legend(num2str(levels'),'location','northwest')
+
+% velocity I/O function
+figure(4), clf, semilogy(levels, (DRNLvelocity*1e6)'), hold on
+ylim([1e0 1e4])
+xlim([0 100])
+xlabel('level')
+ylabel(' velocity (microm/ s)')
+title(['CF= ' num2str(BF) ' Hz'])
+legend(num2str(toneFrequencyList'),'location','northwest')
+
+% command window reports
+disp(''), disp('***')
+disp(AN_spikesOrProbability)
+
+% DRNL parameter set
+UTIL_showStructureSummary(DRNLParams, 'DRNLParams', 10)
+
+% stimulus characteristics
+disp(['CF=' num2str(BF)])
+disp(['tone Duration=' num2str(rampDuration)])
+disp(['ramp Duration=' num2str(duration)])
+
+% particular parameter changes used on this run
+for i=1:length(paramChanges)
+    disp(paramChanges{i})
+end
+
+% if required dump one or more matrices in tab spaced format
+%  (suitable for pasting directly into EXCEL.
+%     UTIL_printTabTable([toneFrequencyList' peakOutputDisp'])
+
+% leave the path as you found it
+path(restorePath)
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsRM/test_MAP1_14RAMworks.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,147 @@
+function test_MAP1_14RAM
+
+global dt  DRNLoutput 
+global  DRNLParams TMoutput
+global peakOutputDisp alignedOutput toneFrequencyList levels leveldBSPL logOutput
+
+
+dbstop if error
+restorePath=path;
+addpath (['..' filesep 'MAP'],    ['..' filesep 'wavFileStore'], ...
+    ['..' filesep 'utilities'])
+figure(2), clf
+
+%% # BFlist is the BF of the filter to be assessed
+BFlist=8000;
+numChannels=1;
+
+% define probe frequencies
+numFs=6;
+lowestF=BFlist/5; 	highestF= BFlist*1.4;
+lowestF=4000; 	highestF= 12600;
+toneFrequencyList=round(logspace(log10(lowestF), log10(highestF), numFs));
+
+%%  # parameter file name
+MAPparamsName='Normal';
+
+%% # probability representation
+AN_spikesOrProbability='probability';
+
+%% # tone duration
+sampleRate= 100000;
+duration=0.0200;                 % seconds
+rampDuration=.005;              % raised cosine ramp (seconds)
+beginSilence=0.050;
+endSilence=0.050;
+
+%% # levels
+% probe details
+levels=0:10:80;
+% levels=80;
+
+%% # change model parameters
+% Parameter changes can be used to change one or more model parameters
+%  *after* the MAPparams file has been read
+
+% adjust linear path gain (previously g=100)
+% switch off all efferent effects
+paramChanges={...
+    'DRNLParams.rateToAttenuationFactorProb = 0.00; ',...
+    'OMEParams.rateToAttenuationFactorProb=0.0;', ...
+    'DRNLParams.ctBMdB = -10;'...
+    'DRNLParams.g=200;'...
+    'DRNLParams.linCFs=6500;'...
+    'DRNLParams.linBWs=2000;'...
+    };
+%     'DRNLParams.a=0;'...
+
+
+%% delare 'showMap' options to control graphical output
+showMapOptions.printModelParameters=0;   % prints all parameters
+showMapOptions.showModelOutput=1;       % plot of all stages
+showMapOptions.printFiringRates=0;      % prints stage activity levels
+showMapOptions.showACF=0;               % shows SACF (probability only)
+showMapOptions.showEfferent=0;          % tracks of AR and MOC
+showMapOptions.surfProbability=0;       % 2D plot of HSR response
+showMapOptions.surfSpikes=0;            % 2D plot of spikes histogram
+showMapOptions.ICrates=0;               % IC rates by CNtauGk
+showMapOptions.fileName=[];
+
+
+%% now vary level and frequency
+peakOutputDisp=zeros(length(levels),length(toneFrequencyList));
+peakStapesDisp=zeros(length(levels),length(toneFrequencyList));
+levelNo=0;
+for leveldBSPL=levels
+    levelNo=levelNo+1;
+disp(['level: ' num2str(leveldBSPL)])
+    freqNo=0;
+    for toneFrequency=toneFrequencyList
+        freqNo=freqNo+1;
+
+        %% Generate stimuli
+        dt=1/sampleRate;
+        time=dt: dt: duration;
+        inputSignal=sum(sin(2*pi*toneFrequency'*time), 1);
+        amp=10^(leveldBSPL/20)*28e-6;   % converts to Pascals (peak)
+        inputSignal=amp*inputSignal;
+        % apply ramps
+        if rampDuration>0.5*duration, rampDuration=duration/2; end
+        rampTime=dt:dt:rampDuration;
+        ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ...
+            ones(1,length(time)-length(rampTime))];
+        inputSignal=inputSignal.*ramp;
+        ramp=fliplr(ramp);
+        inputSignal=inputSignal.*ramp;
+        % add silence
+        intialSilence= zeros(1,round(beginSilence/dt));
+        finalSilence= zeros(1,round(endSilence/dt));
+        inputSignal= [intialSilence inputSignal finalSilence];
+
+        %% run the model
+%         fprintf('\n')
+%         disp([num2str(numChannels) ' channel model: ' AN_spikesOrProbability])
+%         disp('Computing ...')
+
+        MAP1_14(inputSignal, sampleRate, BFlist, ...
+            MAPparamsName, AN_spikesOrProbability, paramChanges);
+
+        peakOutputDisp(levelNo,freqNo)=max(DRNLoutput);
+        peakStapesDisp(levelNo,freqNo)=max(TMoutput);
+
+        %% the model run is complete. Now display the results
+%         UTIL_showMAP(showMapOptions, paramChanges)
+    end % probe frequencies
+figure(2), loglog(toneFrequencyList, peakOutputDisp), hold on
+xlabel('frequency')
+ylabel('peak DRNL displacement (m)')
+    
+end  % levels
+%% alignmed plot
+
+
+x=peakOutputDisp./peakStapesDisp;
+logOutput=20*log10(x.*repmat((2*pi*toneFrequencyList),length(levels),1));
+alignedOutput=logOutput-repmat(logOutput(:,1), 1, length(toneFrequencyList));
+figure(3), clf, semilogx(toneFrequencyList, alignedOutput), hold on
+ylim([-20 80])
+xlim([2000 20000])
+% legend(num2str(levels'))
+xlabel('frequency')
+ylabel('peak DRNL velocity (dB)')
+title(['level ' num2str(leveldBSPL) ' dB SPL'])
+
+disp(['level=' num2str(leveldBSPL)])
+disp(['toneFrequency=' num2str(toneFrequency)])
+
+disp(['attenuation factor =' ...
+    num2str(DRNLParams.rateToAttenuationFactor, '%5.3f') ])
+disp(['attenuation factor (probability)=' ...
+    num2str(DRNLParams.rateToAttenuationFactorProb, '%5.3f') ])
+disp(AN_spikesOrProbability)
+disp(paramChanges)
+
+%     UTIL_printTabTable([toneFrequencyList' peakOutputDisp'])
+
+path(restorePath)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsRM/test_speechInNoise.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,147 @@
+function test_speechInNoise
+
+leveldBSPL= 60;                  % dB SPL
+leveldBSPLNoise=-55;
+
+% leveldBSPL= 90;                  % test AR
+% leveldBSPLNoise=85;
+OMEatten=0.1;
+OMEatten=0.00;
+
+MOCattenuation=0.00;    % no attenuation
+% MOCattenuation=-0.02;   % fixed
+% MOCattenuation=0.02;    % dynamic within-channel
+MOCtauProb=0.150;
+
+paramChanges={};
+
+% no attenuation
+paramChanges={['DRNLParams.rateToAttenuationFactorProb = '...
+    num2str(MOCattenuation) ';'],...
+    ['DRNLParams.MOCtauProb =' num2str(MOCtauProb) ';'],...
+    ['OMEParams.rateToAttenuationFactorProb=' num2str(OMEatten) ';'] };
+
+% 
+fileName='twister_44kHz';
+% fileName='1o7a_44kHz';
+
+dbstop if error
+restorePath=path;
+addpath (['..' filesep 'MAP'],    ['..' filesep 'wavFileStore'], ...
+    ['..' filesep 'utilities'])
+
+%%  #1 parameter file name
+MAPparamsName='Normal';
+
+
+%% #2 probability (fast) or spikes (slow) representation
+AN_spikesOrProbability='spikes';
+%   or
+AN_spikesOrProbability='probability';
+
+
+%% #3  speech file input
+
+beginSilence=.25;
+endSilence=0.25;
+noiseRampDuration=0.01;
+
+%% #5 number of channels in the model
+%   21-channel model (log spacing)
+numChannels=21;
+lowestBF=300; 	highestBF= 6000;
+BFlist=round(logspace(log10(lowestBF), log10(highestBF), numChannels));
+
+%   or specify your own channel BFs
+% numChannels=1;
+% BFlist=toneFrequency;
+
+
+
+%% delare 'showMap' options to control graphical output
+showMapOptions.printModelParameters=1;   % prints all parameters
+showMapOptions.showModelOutput=1;       % plot of all stages
+showMapOptions.printFiringRates=1;      % prints stage activity levels
+showMapOptions.showACF=0;               % shows SACF (probability only)
+showMapOptions.showEfferent=0;          % tracks of AR and MOC
+showMapOptions.surfProbability=1;       % 2D plot of HSR response
+showMapOptions.surfSpikes=0;            % 2D plot of spikes histogram
+showMapOptions.ICrates=0;               % IC rates by CNtauGk
+showMapOptions.PSTHbinwidth=0.010;
+showMapOptions.colorbar=0;
+showMapOptions.view=[0 90];
+
+% disable certain silly options
+if strcmp(AN_spikesOrProbability, 'spikes')
+    % avoid nonsensical options
+    showMapOptions.surfProbability=0;
+    showMapOptions.showACF=0;
+else
+    showMapOptions.surfSpikes=0;
+end
+    % needed for labeling plot
+    showMapOptions.fileName=fileName;
+
+%% Generate stimuli
+
+        %% file input simple or mixed
+        [inputSignal sampleRate]=wavread(fileName);
+        dt=1/sampleRate;
+        inputSignal=inputSignal(:,1);
+        targetRMS=20e-6*10^(leveldBSPL/20);
+        rms=(mean(inputSignal.^2))^0.5;
+        amp=targetRMS/rms;
+        inputSignal=inputSignal*amp;
+        
+        % add silences
+        intialSilence= zeros(1,round(beginSilence*sampleRate));
+        finalSilence= zeros(1,round(endSilence*sampleRate));
+        inputSignal= [intialSilence inputSignal' finalSilence];
+        
+        [inputNoise sampleRateN]=wavread('babble');
+        inputNoise=inputNoise(1:length(inputSignal));
+       inputNoise=inputNoise(:,1);
+        targetRMS=20e-6*10^(leveldBSPLNoise/20);
+        rms=(mean(inputNoise.^2))^0.5;
+        amp=targetRMS/rms;
+        inputNoise=inputNoise*amp;
+        time=dt: dt: dt*length(inputNoise);
+        rampTime=dt:dt:noiseRampDuration;
+        ramp=[0.5*(1+cos(2*pi*rampTime/(2*noiseRampDuration)+pi)) ...
+            ones(1,length(time)-length(rampTime))];
+        inputNoise=inputNoise'.*ramp;
+        inputSignal=inputSignal+inputNoise;
+        
+
+
+%% run the model
+tic
+
+fprintf('\n')
+disp(['Signal duration= ' num2str(length(inputSignal)/sampleRate)])
+disp([num2str(numChannels) ' channel model'])
+disp('Computing ...')
+
+MAP1_14(inputSignal, sampleRate, BFlist, ...
+    MAPparamsName, AN_spikesOrProbability, paramChanges);
+
+
+%% the model run is now complete. Now display the results
+UTIL_showMAP(showMapOptions, paramChanges)
+figure(97), 
+title(['speech/ noise: ' num2str([leveldBSPL leveldBSPLNoise]) ...
+    ';   atten/ tau: ' num2str([MOCattenuation MOCtauProb] )],'fontSize', 14)
+
+disp(['level=' num2str(leveldBSPL)])
+disp(['noise level=' num2str(leveldBSPLNoise)])
+
+global DRNLParams
+disp(['attenuation factor =' ...
+    num2str(DRNLParams.rateToAttenuationFactor, '%5.3f') ])
+disp(['attenuation factor (probability)=' ...
+    num2str(DRNLParams.rateToAttenuationFactorProb, '%5.3f') ])
+disp(AN_spikesOrProbability)
+disp(paramChanges)
+toc
+path(restorePath)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsRM/test_speechInNoiseDelmanhorst.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,150 @@
+function test_speechInNoiseDelmanhorst
+% as used for Delmanhorst presentation
+
+leveldBSPL= 60;                  % dB SPL
+leveldBSPLNoise=-55;
+
+% leveldBSPL= 90;                  % test AR
+% leveldBSPLNoise=85;
+
+% AR rate to attenuation factor
+OMEatten=0.1;
+% OMEatten=0.00;
+
+MOCattenuation=0.00;    % no attenuation
+% MOCattenuation=-0.02;   % fixed
+% MOCattenuation=0.02;    % dynamic within-channel
+
+MOCtauProb=0.150;
+
+paramChanges={};
+
+% no attenuation
+paramChanges={['DRNLParams.rateToAttenuationFactorProb = '...
+    num2str(MOCattenuation) ';'],...
+    ['DRNLParams.MOCtauProb =' num2str(MOCtauProb) ';'],...
+    ['OMEParams.rateToAttenuationFactorProb=' num2str(OMEatten) ';'] };
+
+% 
+fileName='twister_44kHz';
+% fileName='1o7a_44kHz';
+
+dbstop if error
+restorePath=path;
+addpath (['..' filesep 'MAP'],    ['..' filesep 'wavFileStore'], ...
+    ['..' filesep 'utilities'])
+
+%%  #1 parameter file name
+MAPparamsName='Normal';
+
+
+%% #2 probability (fast) or spikes (slow) representation
+% AN_spikesOrProbability='spikes';
+%   or
+AN_spikesOrProbability='probability';
+
+%% #3  speech file input
+
+beginSilence=.25;
+endSilence=0.25;
+noiseRampDuration=0.01;
+
+%% #5 number of channels in the model
+%   21-channel model (log spacing)
+numChannels=21;
+lowestBF=300; 	highestBF= 6000;
+BFlist=round(logspace(log10(lowestBF), log10(highestBF), numChannels));
+
+%   or specify your own channel BFs
+% numChannels=1;
+% BFlist=toneFrequency;
+
+
+
+%% delare 'showMap' options to control graphical output
+showMapOptions.printModelParameters=1;   % prints all parameters
+showMapOptions.showModelOutput=1;       % plot of all stages
+showMapOptions.printFiringRates=1;      % prints stage activity levels
+showMapOptions.showACF=0;               % shows SACF (probability only)
+showMapOptions.showEfferent=0;          % tracks of AR and MOC
+showMapOptions.surfProbability=1;       % 2D plot of HSR response
+showMapOptions.surfSpikes=0;            % 2D plot of spikes histogram
+showMapOptions.ICrates=0;               % IC rates by CNtauGk
+showMapOptions.PSTHbinwidth=0.010;
+showMapOptions.colorbar=0;
+showMapOptions.view=[0 90];
+
+% disable certain silly options
+if strcmp(AN_spikesOrProbability, 'spikes')
+    % avoid nonsensical options
+    showMapOptions.surfProbability=0;
+    showMapOptions.showACF=0;
+else
+    showMapOptions.surfSpikes=0;
+end
+    % needed for labeling plot
+    showMapOptions.fileName=fileName;
+
+%% Generate stimuli
+
+        %% file input simple or mixed
+        [inputSignal sampleRate]=wavread(fileName);
+        dt=1/sampleRate;
+        inputSignal=inputSignal(:,1);
+        targetRMS=20e-6*10^(leveldBSPL/20);
+        rms=(mean(inputSignal.^2))^0.5;
+        amp=targetRMS/rms;
+        inputSignal=inputSignal*amp;
+        
+        % add silences
+        intialSilence= zeros(1,round(beginSilence*sampleRate));
+        finalSilence= zeros(1,round(endSilence*sampleRate));
+        inputSignal= [intialSilence inputSignal' finalSilence];
+        
+        [inputNoise sampleRateN]=wavread('babble');
+        inputNoise=inputNoise(1:length(inputSignal));
+       inputNoise=inputNoise(:,1);
+        targetRMS=20e-6*10^(leveldBSPLNoise/20);
+        rms=(mean(inputNoise.^2))^0.5;
+        amp=targetRMS/rms;
+        inputNoise=inputNoise*amp;
+        time=dt: dt: dt*length(inputNoise);
+        rampTime=dt:dt:noiseRampDuration;
+        ramp=[0.5*(1+cos(2*pi*rampTime/(2*noiseRampDuration)+pi)) ...
+            ones(1,length(time)-length(rampTime))];
+        inputNoise=inputNoise'.*ramp;
+        inputSignal=inputSignal+inputNoise;
+        
+
+
+%% run the model
+tic
+
+fprintf('\n')
+disp(['Signal duration= ' num2str(length(inputSignal)/sampleRate)])
+disp([num2str(numChannels) ' channel model'])
+disp('Computing ...')
+
+MAP1_14(inputSignal, sampleRate, BFlist, ...
+    MAPparamsName, AN_spikesOrProbability, paramChanges);
+
+
+%% the model run is now complete. Now display the results
+UTIL_showMAP(showMapOptions, paramChanges)
+figure(97), 
+title(['speech/ noise: ' num2str([leveldBSPL leveldBSPLNoise]) ...
+    ';   atten/ tau: ' num2str([MOCattenuation MOCtauProb] )],'fontSize', 14)
+
+disp(['level=' num2str(leveldBSPL)])
+disp(['noise level=' num2str(leveldBSPLNoise)])
+
+global DRNLParams
+disp(['attenuation factor =' ...
+    num2str(DRNLParams.rateToAttenuationFactor, '%5.3f') ])
+disp(['attenuation factor (probability)=' ...
+    num2str(DRNLParams.rateToAttenuationFactorProb, '%5.3f') ])
+disp(AN_spikesOrProbability)
+disp(paramChanges)
+toc
+path(restorePath)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsRM/test_toneInNoise.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,225 @@
+function test_toneInNoise
+% test_MAP1_14 is a general purpose test routine that can be adjusted to
+% test a number of different applications of MAP1_14
+%
+% A range of options are supplied in the early part of the program
+%
+% One use of the function is to create demonstrations; filenames <demoxx>
+%  to illustrate particular features
+%
+% #1
+% Identify the file (in 'MAPparamsName') containing the model parameters
+%
+% #2
+% Identify the kind of model required (in 'AN_spikesOrProbability').
+%  A full brainstem model (spikes) can be computed or a shorter model
+%  (probability) that computes only so far as the auditory nerve
+%
+% #3
+% Choose between a tone signal or file input (in 'signalType')
+%
+% #4
+% Set the signal rms level (in leveldBSPL)
+%
+% #5
+% Identify the channels in terms of their best frequencies in the vector
+%  BFlist.
+%
+% Last minute changes to the parameters fetched earlier can be made using
+%  the cell array of strings 'paramChanges'.
+%  Each string must have the same format as the corresponding line in the
+%  file identified in 'MAPparamsName'
+%
+% When the demonstration is satisfactory, freeze it by renaming it <demoxx>
+
+global dt dtSpikes  savedBFlist saveAN_spikesOrProbability saveMAPparamsName...
+    savedInputSignal OMEextEarPressure TMoutput OMEoutput ARattenuation ...
+    DRNLoutput IHC_cilia_output IHCrestingCiliaCond IHCrestingV...
+    IHCoutput ANprobRateOutput ANoutput savePavailable ANtauCas  ...
+    CNtauGk CNoutput  ICoutput ICmembraneOutput ICfiberTypeRates ...
+    MOCattenuation
+global OMEParams DRNLParams IHC_cilia_RPParams IHCpreSynapseParams
+global AN_IHCsynapseParams MacGregorParams MacGregorMultiParams
+global ICrate
+
+
+dbstop if error
+restorePath=path;
+addpath (['..' filesep 'MAP'],    ['..' filesep 'wavFileStore'], ...
+    ['..' filesep 'utilities'])
+
+%%  #1 parameter file name
+MAPparamsName='Normal';
+
+
+%% #2 probability (fast) or spikes (slow) representation
+AN_spikesOrProbability='spikes';
+%   or
+AN_spikesOrProbability='probability'; 
+
+
+%% #3 pure tone, harmonic sequence or speech file input
+signalType= 'tones';
+sampleRate= 44100;          % must agree with noise
+duration=0.010;                 % seconds
+rampDuration=.001;              % raised cosine ramp (seconds)
+beginSilence=0.010;               
+endSilence=0.010;                  
+toneFrequency= 2000;            % or a pure tone (Hz)
+
+%   or
+% harmonic sequence (Hz)
+% F0=210;
+% toneFrequency= F0:F0:8000;    
+
+%   or
+% signalType= 'file';
+% fileName='twister_44kHz';
+
+
+
+%% #4 rms level
+% signal details
+leveldBSPL= 70;                  % dB SPL (80 for Lieberman)
+leveldBSPLNoise=30;
+
+%% #5 number of channels in the model
+%   21-channel model (log spacing)
+numChannels=21;
+lowestBF=250; 	highestBF= 8000;
+BFlist=round(logspace(log10(lowestBF), log10(highestBF), numChannels));
+
+% %   or specify your own channel BFs
+% numChannels=1;
+% BFlist=toneFrequency;
+
+
+%% #6 change model parameters
+
+paramChanges={};
+
+% Parameter changes can be used to change one or more model parameters
+%  *after* the MAPparams file has been read
+% This example declares only one fiber type with a calcium clearance time
+% constant of 80e-6 s (HSR fiber) when the probability option is selected.
+% paramChanges={'AN_IHCsynapseParams.ANspeedUpFactor=5;', ...
+%     'IHCpreSynapseParams.tauCa=86e-6; '};
+paramChanges={'DRNLParams.MOCtauProb =.25;', ...
+    'DRNLParams.rateToAttenuationFactorProb = 0.02; '};
+% paramChanges={'DRNLParams.MOCtauProb =.15;', ...
+%     'DRNLParams.rateToAttenuationFactorProb = 0.00; '};
+
+
+%% delare 'showMap' options to control graphical output
+showMapOptions.printModelParameters=1;   % prints all parameters
+showMapOptions.showModelOutput=1;       % plot of all stages
+showMapOptions.printFiringRates=1;      % prints stage activity levels
+showMapOptions.showACF=0;               % shows SACF (probability only)
+showMapOptions.showEfferent=1;          % tracks of AR and MOC
+showMapOptions.surfProbability=1;       % 2D plot of HSR response 
+showMapOptions.surfSpikes=1;            % 2D plot of spikes histogram
+showMapOptions.ICrates=0;               % IC rates by CNtauGk
+
+% disable certain silly options
+if strcmp(AN_spikesOrProbability, 'spikes')
+    % avoid nonsensical options
+    showMapOptions.surfProbability=0;
+    showMapOptions.showACF=0;
+end
+
+if strcmp(signalType, 'file')
+    % needed for labeling plot
+    showMapOptions.fileName=fileName;
+else
+    showMapOptions.fileName=[];
+end
+
+%% Generate stimuli
+
+switch signalType
+    case 'tones'
+        % Create pure tone stimulus
+        dt=1/sampleRate; % seconds
+        time=dt: dt: duration;
+        inputSignal=sum(sin(2*pi*toneFrequency'*time), 1);
+        amp=10^(leveldBSPL/20)*28e-6;   % converts to Pascals (peak)
+        inputSignal=amp*inputSignal;
+        % apply ramps
+        % catch rampTime error
+        if rampDuration>0.5*duration, rampDuration=duration/2; end
+        rampTime=dt:dt:rampDuration;
+        ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ...
+            ones(1,length(time)-length(rampTime))];
+        inputSignal=inputSignal.*ramp;
+        ramp=fliplr(ramp);
+        inputSignal=inputSignal.*ramp;
+        % add silence
+        intialSilence= zeros(1,round(beginSilence/dt));
+        finalSilence= zeros(1,round(endSilence/dt));
+        inputSignal= [intialSilence inputSignal finalSilence];
+        
+%         [inputNoise sampleRateN]=wavread('babble');
+        [inputNoise sampleRateN]=wavread('white noise');
+        inputNoise=inputNoise(1:length(inputSignal));
+        inputNoise=inputNoise(:,1);
+        targetRMS=20e-6*10^(leveldBSPLNoise/20);
+        rms=(mean(inputNoise.^2))^0.5;
+        amp=targetRMS/rms;
+        inputNoise=inputNoise*amp;
+        inputSignal=inputSignal+inputNoise';
+        figure(2), subplot(2,1,1)
+        time=dt:dt:dt*length(inputSignal);
+        plot(time,inputSignal,'k')
+
+
+    case 'file'
+        %% file input simple or mixed
+        [inputSignal sampleRate]=wavread(fileName);
+        dt=1/sampleRate;
+        inputSignal=inputSignal(:,1);
+        targetRMS=20e-6*10^(leveldBSPL/20);
+        rms=(mean(inputSignal.^2))^0.5;
+        amp=targetRMS/rms;
+        inputSignal=inputSignal*amp;
+        intialSilence= zeros(1,round(0.1/dt));
+        finalSilence= zeros(1,round(0.2/dt));
+        inputSignal= [intialSilence inputSignal' finalSilence];
+        
+end
+
+
+%% run the model
+tic
+fprintf('\n')
+disp(['Signal duration= ' num2str(length(inputSignal)/sampleRate)])
+disp([num2str(numChannels) ' channel model: ' AN_spikesOrProbability])
+disp('Computing ...')
+
+MAP1_14(inputSignal, sampleRate, BFlist, ...
+    MAPparamsName, AN_spikesOrProbability, paramChanges);
+
+
+%% the model run is now complete. Now display the results
+UTIL_showMAP(showMapOptions, paramChanges)
+
+if strcmp(signalType,'tones')
+    disp(['duration=' num2str(duration)])
+    disp(['level=' num2str(leveldBSPL)])
+    disp(['toneFrequency=' num2str(toneFrequency)])
+    global DRNLParams
+    disp(['attenuation factor =' ...
+        num2str(DRNLParams.rateToAttenuationFactor, '%5.3f') ])
+    disp(['attenuation factor (probability)=' ...
+        num2str(DRNLParams.rateToAttenuationFactorProb, '%5.3f') ])
+    disp(AN_spikesOrProbability)
+end
+
+figure(2), subplot(2,1,2), plot(ANprobRateOutput(13+21,:))
+disp([ 'peak channel 13: ' num2str(max(ANprobRateOutput(13+21,:)))])
+
+for i=1:length(paramChanges)
+    disp(paramChanges{i})
+end
+
+path(restorePath)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsTim/IPIHextract.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,181 @@
+function [iih,IPIhisttime,IPIhistweight]=IPIHextract(IFRAN_pattern, sfreq)
+% 
+% tracks the formants according to an analysis proposed in Secker-Walker
+% JASA 1990, section V.A
+% Tim Jürgens, February 2011, code from Guy Brown included
+% 
+% input:  IFRAN_pattern: pattern of the auditory model (dependend on the number of modules used)
+%                        first dimension: frequency channel, 
+%                        second dimension: time (samples)
+%         sfreq:         sampling frequency
+% output: iih:           interpeak-interval histogram, matrix very similar
+%                        the plot 5 in the Secker-Walker paper
+%
+%
+%
+
+
+time_axis = 0:1/sfreq:(size(IFRAN_pattern,2)-1)/sfreq;
+
+%find how many samples of AN_pattern are 10ms and 3ms
+%one_sample_is_a_time_of = time_axis(2);
+[tmp, start_time_index] = min(abs(0-time_axis));
+[tmp, stop20_time_index] = min(abs(0.020-time_axis));
+number_of_samples20ms = stop20_time_index - start_time_index;
+
+[tmp, stop10_time_index] = min(abs(0.010-time_axis));
+number_of_samples10ms = stop10_time_index - start_time_index;
+every_10ms = 1:number_of_samples10ms:size(IFRAN_pattern,2)-number_of_samples20ms;
+
+hamm_window = hamming(11);
+halfHamming = (length(hamm_window)-1)/2;
+
+% window normalization
+
+norm = conv(ones(1,number_of_samples20ms),hamm_window);
+norm = norm(5+1:end-5)';
+win_size = number_of_samples20ms;
+half_win_size = floor(win_size/2);
+hop_size = number_of_samples10ms;
+
+%parameters of the autocorrelation
+params.acfTau=0.1;
+params.lags=[0:1/sfreq:0.02-1/sfreq];
+sampledacf = runningACF(IFRAN_pattern,sfreq,params);
+sampledacf(sampledacf<0)=0;
+sampledacf = sqrt(sampledacf);
+
+
+%pre-allocation due to speed
+%Acorr = zeros(size(IFRAN_pattern,1),size(every_3ms,2),number_of_samples10ms*2+1);
+%RAcorr = zeros(size(IFRAN_pattern,1),size(every_3ms,2),number_of_samples10ms*2+1);
+%SRAcorr = zeros(size(IFRAN_pattern,1),size(every_3ms,2),number_of_samples10ms*2+1-10);
+IPIhisttime = zeros(size(IFRAN_pattern,1),size(every_10ms,2),3);
+IPIhistweight = zeros(size(IFRAN_pattern,1),size(every_10ms,2),3);  %maximum 3 peaks from the SRA
+iih = zeros(half_win_size,size(sampledacf,1));
+
+
+
+
+
+for iCounter = 1:size(sampledacf,2) %each channel
+    fprintf('Channel No. %i\n',iCounter);
+    %time_counter = 1;
+    %for jCounter = every_3ms %every 3ms time segment
+                    
+    for frame=1:size(sampledacf,1)
+        
+        %%debug
+        %if iCounter == 130
+        %    disp('here');
+        %end
+        
+        
+        sra = conv(squeeze(sampledacf(frame,iCounter,:)),hamm_window);
+        sra = sra(halfHamming+1:end-halfHamming)./norm;
+        df = [0 ; diff(sra)];
+        idx = find((df(1:end-1)>=0)&(df(2:end)<0));
+        % interpolate
+        a=df(idx);
+        b=df(idx+1);
+        idx = (idx-1+a./(a-b));
+        % get rid of a zero peak, if it exists
+        idx = idx(idx>1);
+        %include the zeroth peak
+        idx = [1 idx']';
+        % peak values corresponding to these intervals
+        amp = interp1(1:length(sra),sra,idx,'linear');
+        % if required, remove peaks that lie below the mean sra
+        % note that we disregard the value at zero delay
+        %if (params.removePeaksBelowMean)
+        valid = find(amp>1.2*mean(sra(1:floor(length(sra)/2))));
+        %valid = find(amp>mean(sra));
+        %just take the mean of the first half of the sra as a comparison
+        idx = idx(valid);
+        amp = amp(valid);
+        %end
+        % only use the first four peaks (three intervals)
+        idx = idx(1:min(4,length(idx)));
+        % find the intervals
+        interval = diff(idx);
+        % now histogram the intervals
+        if (~isempty(interval))
+            for k=1:length(interval)
+                if interval(k)<=half_win_size
+                    iih(round(interval(k)),frame) = iih(round(interval(k)),frame)+amp(k);
+                    IPIhisttime(iCounter,frame,k) = interval(k)/sfreq;
+                    IPIhistweight(iCounter,frame,k) = amp(k);
+                end
+            end
+        end
+        
+    end
+    
+    
+    
+    
+    %% end Guy's code
+    
+    
+    %         %take the autocorrelation (ACF) of a 10ms-segment of each channel
+    %         Acorr(iCounter,time_counter,:) = xcorr(IFRAN_pattern(iCounter,jCounter:number_of_samples10ms+jCounter),'biased'); %biased scales the ACF by the reciprocal of the length of the segment
+    %         %root calculation
+    %         RAcorr(iCounter,time_counter,:) = sqrt(abs(Acorr(iCounter,time_counter,:)));
+    %
+    %         %smoothing using the 11-point hamming window
+    %         for kCounter = 6:size(RAcorr(iCounter,time_counter,:),3)-5 %start with 6 and end with 5 samples
+    %             %less the length of time_axis not to get in conflict with the length of
+    %             %the hamm_window
+    %             SRAcorr(iCounter,time_counter,kCounter-5) = ...
+    %                 squeeze(RAcorr(iCounter,time_counter,(kCounter-5):(kCounter+5)))'*hamm_window./sum(hamm_window);
+    %         end
+    %
+    %         %mean value of actual SRA
+    %         SRA_mean = mean(SRAcorr(iCounter,time_counter,:));
+    %
+    %         %find signed zero-crossings of the first derivative (=difference)
+    %         z_crossings_indices = find(diff(sign(diff(squeeze(SRAcorr(iCounter,time_counter,:))))) < 0)+1; %+1 is necessary, because diff shortens vector by 1
+    %         middle_index = ceil(size(SRAcorr(iCounter,time_counter,:),3)/2);
+    %
+    %         validCounter = 1;
+    %         valid_z_crossings_indices = [];
+    %         %find valid zero-crossings (peak higher than meanvalue and within first 5 ms of SRA)
+    %         for lCounter = 1:length(z_crossings_indices)
+    %             if (SRAcorr(iCounter,time_counter,z_crossings_indices(lCounter)) > SRA_mean) && ...
+    %                     (abs(z_crossings_indices(lCounter)-middle_index) < round(number_of_samples10ms/2));
+    %                 valid_z_crossings_indices(validCounter) = z_crossings_indices(lCounter);
+    %                 validCounter = validCounter+1;
+    %             end
+    %         end
+    %
+    %         %find main peak in the ACF
+    %         [tmp,index_of_z_crossings_main_index] = min(abs(middle_index-valid_z_crossings_indices));
+    %         if ~tmp == 0
+    %             disp('middle peak not appropriately found');
+    %         end
+    %
+    %         %%% for debugging
+    % %         if iCounter == 130
+    % %             disp('here');
+    % %             figure, plot(squeeze(SRAcorr(iCounter,time_counter,:)));
+    % %             hold on, plot([1 length(squeeze(SRAcorr(iCounter,time_counter,:)))],[SRA_mean SRA_mean],'r-');
+    % %         end
+    %         %%%
+    %
+    %         %generate IPI-histogram: take the first 3 intervals of SRAcorr
+    %         %(positive delay) in the first 5 ms
+    %         histcounter = 1;
+    %         for lCounter = index_of_z_crossings_main_index+1:min([length(valid_z_crossings_indices(index_of_z_crossings_main_index+1:end)) 3])+index_of_z_crossings_main_index
+    %             sampledifference = abs(valid_z_crossings_indices(lCounter)-valid_z_crossings_indices(lCounter-1));
+    %             %the difference between two adjacent peaks in the SRA is taken
+    %             %as IPI estimate
+    %             IPIhisttime(iCounter,time_counter,histcounter) = sampledifference*one_sample_is_a_time_of;
+    %             %the amplitude of the SRA at the start of the SRA interval is
+    %             %taken as the IPIweight
+    %             IPIhistweight(iCounter,time_counter,histcounter) = SRAcorr(iCounter,time_counter,valid_z_crossings_indices(lCounter-1));
+    %             histcounter = histcounter + 1;
+    %         end
+    
+    %time_counter = time_counter+1;
+end
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsTim/MAP1_14_olde_version_dont_use.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,1269 @@
+function  MAP1_14(inputSignal, sampleRate, BFlist, MAPparamsName, ...
+    AN_spikesOrProbability, paramChanges)
+% To test this function use test_MAP1_14 in this folder
+%
+% example:
+% <navigate to 'MAP1_14\MAP'>
+%  [inputSignal FS] = wavread('../wavFileStore/twister_44kHz');
+%  MAP1_14(inputSignal, FS, -1, 'Normal', 'probability', [])
+%
+% All arguments are mandatory.
+%
+%  BFlist is a vector of BFs but can be '-1' to allow MAPparams to choose
+%  MAPparamsName='Normal';          % source of model parameters
+%  AN_spikesOrProbability='spikes'; % or 'probability'
+%  paramChanges is a cell array of strings that can be used to make last
+%   minute parameter changes, e.g., to simulate OHC loss
+%  e.g.  paramChanges{1}= 'DRNLParams.a=0;'; % disable OHCs
+%  e.g.  paramchanges={};                    % no changes
+% The model parameters are established in the MAPparams<***> file
+%  and stored as global
+
+restorePath=path;
+addpath (['..' filesep 'parameterStore'])
+
+global OMEParams DRNLParams IHC_cilia_RPParams IHCpreSynapseParams
+global AN_IHCsynapseParams MacGregorParams MacGregorMultiParams
+
+% All of the results of this function are stored as global
+global dt ANdt  savedBFlist saveAN_spikesOrProbability saveMAPparamsName...
+    savedInputSignal OMEextEarPressure TMoutput OMEoutput ARattenuation ...
+    DRNLoutput IHC_cilia_output IHCrestingCiliaCond IHCrestingV...
+    IHCoutput ANprobRateOutput ANoutput savePavailable ANtauCas  ...
+    CNtauGk CNoutput  ICoutput ICmembraneOutput ICfiberTypeRates ...
+    MOCattenuation
+
+% Normally only ICoutput(logical spike matrix) or ANprobRateOutput will be
+% needed by the user; so the following will suffice
+%   global ANdt ICoutput ANprobRateOutput
+
+% Note that sampleRate has not changed from the original function call and
+%  ANprobRateOutput is sampled at this rate
+% However ANoutput, CNoutput and IC output are stored as logical
+%  'spike' matrices using a lower sample rate (see ANdt).
+
+% When AN_spikesOrProbability is set to probability,
+%  no spike matrices are computed.
+% When AN_spikesOrProbability is set to 'spikes',
+%  no probability output is computed
+
+% Efferent control variables are ARattenuation and MOCattenuation
+%  These are scalars between 1 (no attenuation) and 0.
+%  They are represented with dt=1/sampleRate (not ANdt)
+%  They are computed using either AN probability rate output
+%   or IC (spikes) output as approrpriate.
+% AR is computed using across channel activity
+% MOC is computed on a within-channel basis.
+
+if nargin<1
+    error(' MAP1_14 is not a script but a function that must be called')
+end
+
+if nargin<6
+    paramChanges=[];
+end
+% Read parameters from MAPparams<***> file in 'parameterStore' folder
+% Beware, 'BFlist=-1' is a legitimate argument for MAPparams<>
+%  It means that the calling program allows MAPparams to specify the list
+cmd=['method=MAPparams' MAPparamsName ...
+    '(BFlist, sampleRate, 0, paramChanges);'];
+eval(cmd);
+BFlist=DRNLParams.nonlinCFs;
+
+% save as global for later plotting if required
+savedBFlist=BFlist;
+saveAN_spikesOrProbability=AN_spikesOrProbability;
+saveMAPparamsName=MAPparamsName;
+
+dt=1/sampleRate;
+duration=length(inputSignal)/sampleRate;
+% segmentDuration is specified in parameter file (must be >efferent delay)
+segmentDuration=method.segmentDuration;
+segmentLength=round(segmentDuration/ dt);
+segmentTime=dt*(1:segmentLength); % used in debugging plots
+
+% all spiking activity is computed using longer epochs
+ANspeedUpFactor=AN_IHCsynapseParams.ANspeedUpFactor;  % e.g.5 times
+
+% inputSignal must be  row vector
+[r c]=size(inputSignal);
+if r>c, inputSignal=inputSignal'; end       % transpose
+% ignore stereo signals
+inputSignal=inputSignal(1,:);               % drop any second channel
+savedInputSignal=inputSignal;
+
+% Segment the signal
+% The sgment length is given but the signal length must be adjusted to be a
+% multiple of both the segment length and the reduced segmentlength
+[nSignalRows signalLength]=size(inputSignal);
+segmentLength=ceil(segmentLength/ANspeedUpFactor)*ANspeedUpFactor;
+% Make the signal length a whole multiple of the segment length
+nSignalSegments=ceil(signalLength/segmentLength);
+padSize=nSignalSegments*segmentLength-signalLength;
+pad=zeros(nSignalRows,padSize);
+inputSignal=[inputSignal pad];
+[ignore signalLength]=size(inputSignal);
+
+% AN (spikes) is computed at a lower sample rate when spikes required
+%  so it has a reduced segment length (see 'ANspeeUpFactor' above)
+% AN CN and IC all use this sample interval
+ANdt=dt*ANspeedUpFactor;
+reducedSegmentLength=round(segmentLength/ANspeedUpFactor);
+reducedSignalLength= round(signalLength/ANspeedUpFactor);
+
+%% Initialise with respect to each stage before computing
+%  by allocating memory,
+%  by computing constants
+%  by establishing easy to read variable names
+% The computations are made in segments and boundary conditions must
+%  be established and stored. These are found in variables with
+%  'boundary' or 'bndry' in the name
+
+%% OME ---
+% external ear resonances
+OMEexternalResonanceFilters=OMEParams.externalResonanceFilters;
+[nOMEExtFilters c]=size(OMEexternalResonanceFilters);
+% details of external (outer ear) resonances
+OMEgaindBs=OMEexternalResonanceFilters(:,1);
+OMEgainScalars=10.^(OMEgaindBs/20);
+OMEfilterOrder=OMEexternalResonanceFilters(:,2);
+OMElowerCutOff=OMEexternalResonanceFilters(:,3);
+OMEupperCutOff=OMEexternalResonanceFilters(:,4);
+% external resonance coefficients
+ExtFilter_b=cell(nOMEExtFilters,1);
+ExtFilter_a=cell(nOMEExtFilters,1);
+for idx=1:nOMEExtFilters
+    Nyquist=sampleRate/2;
+    [b, a] = butter(OMEfilterOrder(idx), ...
+        [OMElowerCutOff(idx) OMEupperCutOff(idx)]...
+        /Nyquist);
+    ExtFilter_b{idx}=b;
+    ExtFilter_a{idx}=a;
+end
+OMEExtFilterBndry=cell(2,1);
+OMEextEarPressure=zeros(1,signalLength); % pressure at tympanic membrane
+
+% pressure to velocity conversion using smoothing filter (50 Hz cutoff)
+tau=1/(2*pi*50);
+a1=dt/tau-1; a0=1;
+b0=1+ a1;
+TMdisp_b=b0; TMdisp_a=[a0 a1];
+% figure(9), freqz(TMdisp_b, TMdisp_a)
+OME_TMdisplacementBndry=[];
+
+% OME high pass (simulates poor low frequency stapes response)
+OMEhighPassHighCutOff=OMEParams.OMEstapesLPcutoff;
+Nyquist=sampleRate/2;
+[stapesDisp_b,stapesDisp_a] = butter(1, OMEhighPassHighCutOff/Nyquist, 'high');
+% figure(10), freqz(stapesDisp_b, stapesDisp_a)
+
+OMEhighPassBndry=[];
+
+% OMEampStapes might be reducdant (use OMEParams.stapesScalar)
+stapesScalar= OMEParams.stapesScalar;
+
+% Acoustic reflex
+efferentDelayPts=round(OMEParams.ARdelay/dt);
+% smoothing filter
+a1=dt/OMEParams.ARtau-1; a0=1;
+b0=1+ a1;
+ARfilt_b=b0; ARfilt_a=[a0 a1];
+
+ARattenuation=ones(1,signalLength);
+ARrateThreshold=OMEParams.ARrateThreshold; % may not be used
+ARrateToAttenuationFactor=OMEParams.rateToAttenuationFactor;
+ARrateToAttenuationFactorProb=OMEParams.rateToAttenuationFactorProb;
+ARboundary=[];
+ARboundaryProb=0;
+
+% save complete OME record (stapes displacement)
+OMEoutput=zeros(1,signalLength);
+TMoutput=zeros(1,signalLength);
+
+%% BM ---
+% BM is represented as a list of locations identified by BF
+DRNL_BFs=BFlist;
+nBFs= length(DRNL_BFs);
+
+% DRNLchannelParameters=DRNLParams.channelParameters;
+DRNLresponse= zeros(nBFs, segmentLength);
+
+MOCrateToAttenuationFactor=DRNLParams.rateToAttenuationFactor;
+rateToAttenuationFactorProb=DRNLParams.rateToAttenuationFactorProb;
+MOCrateThresholdProb=DRNLParams.MOCrateThresholdProb;
+
+% smoothing filter for MOC
+a1=dt/DRNLParams.MOCtau-1; a0=1;
+b0=1+ a1;
+MOCfilt_b=b0; MOCfilt_a=[a0 a1];
+% figure(9), freqz(stapesDisp_b, stapesDisp_a)
+MOCboundary=cell(nBFs,1);
+MOCprobBoundary=cell(nBFs,1);
+
+MOCattSegment=zeros(nBFs,reducedSegmentLength);
+MOCattenuation=ones(nBFs,signalLength);
+
+% if DRNLParams.a>0
+%     DRNLcompressionThreshold=10^((1/(1-DRNLParams.c))* ...
+%     log10(DRNLParams.b/DRNLParams.a));
+% else
+%     DRNLcompressionThreshold=inf;
+% end
+DRNLcompressionThreshold=DRNLParams.cTh;
+DRNLlinearOrder= DRNLParams.linOrder;
+DRNLnonlinearOrder= DRNLParams.nonlinOrder;
+
+DRNLa=DRNLParams.a;
+DRNLb=DRNLParams.b;
+DRNLc=DRNLParams.c;
+linGAIN=DRNLParams.g;
+%
+% gammatone filter coefficients for linear pathway
+bw=DRNLParams.linBWs';
+phi = 2 * pi * bw * dt;
+cf=DRNLParams.linCFs';
+theta = 2 * pi * cf * dt;
+cos_theta = cos(theta);
+sin_theta = sin(theta);
+alpha = -exp(-phi).* cos_theta;
+b0 = ones(nBFs,1);
+b1 = 2 * alpha;
+b2 = exp(-2 * phi);
+z1 = (1 + alpha .* cos_theta) - (alpha .* sin_theta) * i;
+z2 = (1 + b1 .* cos_theta) - (b1 .* sin_theta) * i;
+z3 = (b2 .* cos(2 * theta)) - (b2 .* sin(2 * theta)) * i;
+tf = (z2 + z3) ./ z1;
+a0 = abs(tf);
+a1 = alpha .* a0;
+GTlin_a = [b0, b1, b2];
+GTlin_b = [a0, a1];
+GTlinOrder=DRNLlinearOrder;
+GTlinBdry=cell(nBFs,GTlinOrder);
+
+% nonlinear gammatone filter coefficients 
+bw=DRNLParams.nlBWs';
+phi = 2 * pi * bw * dt;
+cf=DRNLParams.nonlinCFs';
+theta = 2 * pi * cf * dt;
+cos_theta = cos(theta);
+sin_theta = sin(theta);
+alpha = -exp(-phi).* cos_theta;
+b0 = ones(nBFs,1);
+b1 = 2 * alpha;
+b2 = exp(-2 * phi);
+z1 = (1 + alpha .* cos_theta) - (alpha .* sin_theta) * i;
+z2 = (1 + b1 .* cos_theta) - (b1 .* sin_theta) * i;
+z3 = (b2 .* cos(2 * theta)) - (b2 .* sin(2 * theta)) * i;
+tf = (z2 + z3) ./ z1;
+a0 = abs(tf);
+a1 = alpha .* a0;
+GTnonlin_a = [b0, b1, b2];
+GTnonlin_b = [a0, a1];
+GTnonlinOrder=DRNLnonlinearOrder;
+GTnonlinBdry1=cell(nBFs, GTnonlinOrder);
+GTnonlinBdry2=cell(nBFs, GTnonlinOrder);
+
+% complete BM record (BM displacement)
+DRNLoutput=zeros(nBFs, signalLength);
+
+
+%% IHC ---
+% IHC cilia activity and receptor potential
+% viscous coupling between BM and stereocilia displacement
+% Nyquist=sampleRate/2;
+% IHCcutoff=1/(2*pi*IHC_cilia_RPParams.tc);
+% [IHCciliaFilter_b,IHCciliaFilter_a]=...
+%     butter(1, IHCcutoff/Nyquist, 'high');
+a1=dt/IHC_cilia_RPParams.tc-1; a0=1;
+b0=1+ a1;
+% high pass (i.e. low pass reversed)
+IHCciliaFilter_b=[a0 a1]; IHCciliaFilter_a=b0;
+% figure(9), freqz(IHCciliaFilter_b, IHCciliaFilter_a)
+
+IHCciliaBndry=cell(nBFs,1);
+
+% IHC apical conductance (Boltzman function)
+IHC_C= IHC_cilia_RPParams.C;
+IHCu0= IHC_cilia_RPParams.u0;
+IHCu1= IHC_cilia_RPParams.u1;
+IHCs0= IHC_cilia_RPParams.s0;
+IHCs1= IHC_cilia_RPParams.s1;
+IHCGmax= IHC_cilia_RPParams.Gmax;
+IHCGa= IHC_cilia_RPParams.Ga; % (leakage)
+
+IHCGu0 = IHCGa+IHCGmax./(1+exp(IHCu0/IHCs0).*(1+exp(IHCu1/IHCs1)));
+IHCrestingCiliaCond=IHCGu0;
+
+% Receptor potential
+IHC_Cab= IHC_cilia_RPParams.Cab;
+IHC_Gk= IHC_cilia_RPParams.Gk;
+IHC_Et= IHC_cilia_RPParams.Et;
+IHC_Ek= IHC_cilia_RPParams.Ek;
+IHC_Ekp= IHC_Ek+IHC_Et*IHC_cilia_RPParams.Rpc;
+
+IHCrestingV= (IHC_Gk*IHC_Ekp+IHCGu0*IHC_Et)/(IHCGu0+IHC_Gk);
+
+IHC_Vnow= IHCrestingV*ones(nBFs,1); % initial voltage
+IHC_RP= zeros(nBFs,segmentLength);
+
+% complete record of IHC receptor potential (V)
+IHCciliaDisplacement= zeros(nBFs,segmentLength);
+IHCoutput= zeros(nBFs,signalLength);
+IHC_cilia_output= zeros(nBFs,signalLength);
+
+
+%% pre-synapse ---
+% Each BF is replicated using a different fiber type to make a 'channel'
+% The number of channels is nBFs x nANfiberTypes
+% Fiber types are specified in terms of tauCa
+nANfiberTypes= length(IHCpreSynapseParams.tauCa);
+ANtauCas= IHCpreSynapseParams.tauCa;
+nANchannels= nANfiberTypes*nBFs;
+synapticCa= zeros(nANchannels,segmentLength);
+
+% Calcium control (more calcium, greater release rate)
+ECa=IHCpreSynapseParams.ECa;
+gamma=IHCpreSynapseParams.gamma;
+beta=IHCpreSynapseParams.beta;
+tauM=IHCpreSynapseParams.tauM;
+mICa=zeros(nANchannels,segmentLength);
+GmaxCa=IHCpreSynapseParams.GmaxCa;
+synapse_z= IHCpreSynapseParams.z;
+synapse_power=IHCpreSynapseParams.power;
+
+% tauCa vector is established across channels to allow vectorization
+%  (one tauCa per channel). Do not confuse with ANtauCas (one pre fiber type)
+tauCa=repmat(ANtauCas, nBFs,1);
+tauCa=reshape(tauCa, nANchannels, 1);
+
+% presynapse startup values (vectors, length:nANchannels)
+% proportion (0 - 1) of Ca channels open at IHCrestingV
+mICaCurrent=((1+beta^-1 * exp(-gamma*IHCrestingV))^-1)...
+    *ones(nBFs*nANfiberTypes,1);
+% corresponding startup currents
+ICaCurrent= (GmaxCa*mICaCurrent.^3) * (IHCrestingV-ECa);
+CaCurrent= ICaCurrent.*tauCa;
+
+% vesicle release rate at startup (one per channel)
+% kt0 is used only at initialisation
+kt0= -synapse_z * CaCurrent.^synapse_power;
+
+
+%% AN ---
+% each row of the AN matrices represents one AN fiber
+% The results computed either for probabiities *or* for spikes (not both)
+% Spikes are necessary if CN and IC are to be computed
+nFibersPerChannel= AN_IHCsynapseParams.numFibers;
+nANfibers= nANchannels*nFibersPerChannel;
+AN_refractory_period= AN_IHCsynapseParams.refractory_period;
+
+y=AN_IHCsynapseParams.y;
+l=AN_IHCsynapseParams.l;
+x=AN_IHCsynapseParams.x;
+r=AN_IHCsynapseParams.r;
+M=round(AN_IHCsynapseParams.M);
+
+% probability            (NB initial 'P' on everything)
+PAN_ydt = repmat(AN_IHCsynapseParams.y*dt, nANchannels,1);
+PAN_ldt = repmat(AN_IHCsynapseParams.l*dt, nANchannels,1);
+PAN_xdt = repmat(AN_IHCsynapseParams.x*dt, nANchannels,1);
+PAN_rdt = repmat(AN_IHCsynapseParams.r*dt, nANchannels,1);
+PAN_rdt_plus_ldt = PAN_rdt + PAN_ldt;
+PAN_M=round(AN_IHCsynapseParams.M);
+
+% compute starting values
+Pcleft    = kt0* y* M ./ (y*(l+r)+ kt0* l);
+Pavailable    = Pcleft*(l+r)./kt0;
+Preprocess    = Pcleft*r/x; % canbe fractional
+
+ANprobability=zeros(nANchannels,segmentLength);
+ANprobRateOutput=zeros(nANchannels,signalLength);
+lengthAbsRefractoryP= round(AN_refractory_period/dt);
+cumANnotFireProb=ones(nANchannels,signalLength);
+% special variables for monitoring synaptic cleft (specialists only)
+savePavailableSeg=zeros(nANchannels,segmentLength);
+savePavailable=zeros(nANchannels,signalLength);
+
+% spikes     % !  !  !    ! !        !   !  !
+lengthAbsRefractory= round(AN_refractory_period/ANdt);
+
+AN_ydt= repmat(AN_IHCsynapseParams.y*ANdt, nANfibers,1);
+AN_ldt= repmat(AN_IHCsynapseParams.l*ANdt, nANfibers,1);
+AN_xdt= repmat(AN_IHCsynapseParams.x*ANdt, nANfibers,1);
+AN_rdt= repmat(AN_IHCsynapseParams.r*ANdt, nANfibers,1);
+AN_rdt_plus_ldt= AN_rdt + AN_ldt;
+AN_M= round(AN_IHCsynapseParams.M);
+
+% kt0  is initial release rate
+% Establish as a vector (length=channel x number of fibers)
+kt0= repmat(kt0', nFibersPerChannel, 1);
+kt0=reshape(kt0, nANfibers,1);
+
+% starting values for reservoirs
+AN_cleft    = kt0* y* M ./ (y*(l+r)+ kt0* l);
+AN_available    = round(AN_cleft*(l+r)./kt0); %must be integer
+AN_reprocess    = AN_cleft*r/x;
+
+% output is in a logical array spikes = 1/ 0.
+ANspikes= false(nANfibers,reducedSegmentLength);
+ANoutput= false(nANfibers,reducedSignalLength);
+
+
+%% CN (first brain stem nucleus - could be any subdivision of CN)
+% Input to a CN neuorn is a random selection of AN fibers within a channel
+%  The number of AN fibers used is ANfibersFanInToCN
+% CNtauGk (Potassium time constant) determines the rate of firing of
+%  the unit when driven hard by a DC input (not normally >350 sp/s)
+% If there is more than one value, everything is replicated accordingly
+
+ANavailableFibersPerChan=AN_IHCsynapseParams.numFibers;
+ANfibersFanInToCN=MacGregorMultiParams.fibersPerNeuron;
+
+CNtauGk=MacGregorMultiParams.tauGk; % row vector of CN types (by tauGk)
+nCNtauGk=length(CNtauGk);
+
+% the total number of 'channels' is now greater
+% 'channel' is defined as collections of units with the same parameters
+%  i.e. same BF, same ANtau, same CNtauGk
+nCNchannels=nANchannels*nCNtauGk;
+
+nCNneuronsPerChannel=MacGregorMultiParams.nNeuronsPerBF;
+tauGk=repmat(CNtauGk, nCNneuronsPerChannel,1);
+tauGk=reshape(tauGk,nCNneuronsPerChannel*nCNtauGk,1);
+
+% Now the number of neurons has been increased
+nCNneurons=nCNneuronsPerChannel*nCNchannels;
+CNmembranePotential=zeros(nCNneurons,reducedSegmentLength);
+
+% establish which ANfibers (by name) feed into which CN nuerons
+CNinputfiberLists=zeros(nANchannels*nCNneuronsPerChannel, ANfibersFanInToCN);
+unitNo=1;
+for ch=1:nANchannels
+    % Each channel contains a number of units =length(listOfFanInValues)
+    for idx=1:nCNneuronsPerChannel
+        for idx2=1:nCNtauGk
+            fibersUsed=(ch-1)*ANavailableFibersPerChan + ...
+                ceil(rand(1,ANfibersFanInToCN)* ANavailableFibersPerChan);
+            CNinputfiberLists(unitNo,:)=fibersUsed;
+            unitNo=unitNo+1;
+        end
+    end
+end
+
+% input to CN units
+AN_PSTH=zeros(nCNneurons,reducedSegmentLength);
+
+% Generate CNalphaFunction function
+%  by which spikes are converted to post-synaptic currents
+CNdendriteLPfreq= MacGregorMultiParams.dendriteLPfreq;
+CNcurrentPerSpike=MacGregorMultiParams.currentPerSpike;
+CNspikeToCurrentTau=1/(2*pi*CNdendriteLPfreq);
+t=ANdt:ANdt:5*CNspikeToCurrentTau;
+CNalphaFunction= (1 / ...
+    CNspikeToCurrentTau)*t.*exp(-t /CNspikeToCurrentTau);
+CNalphaFunction=CNalphaFunction*CNcurrentPerSpike;
+
+% figure(98), plot(t,CNalphaFunction)
+% working memory for implementing convolution
+
+CNcurrentTemp=...
+    zeros(nCNneurons,reducedSegmentLength+length(CNalphaFunction)-1);
+% trailing alphas are parts of humps carried forward to the next segment
+CNtrailingAlphas=zeros(nCNneurons,length(CNalphaFunction));
+
+CN_tauM=MacGregorMultiParams.tauM;
+CN_tauTh=MacGregorMultiParams.tauTh;
+CN_cap=MacGregorMultiParams.Cap;
+CN_c=MacGregorMultiParams.c;
+CN_b=MacGregorMultiParams.dGkSpike;
+CN_Ek=MacGregorMultiParams.Ek;
+CN_Eb= MacGregorMultiParams.Eb;
+CN_Er=MacGregorMultiParams.Er;
+CN_Th0= MacGregorMultiParams.Th0;
+CN_E= zeros(nCNneurons,1);
+CN_Gk= zeros(nCNneurons,1);
+CN_Th= MacGregorMultiParams.Th0*ones(nCNneurons,1);
+CN_Eb=CN_Eb.*ones(nCNneurons,1);
+CN_Er=CN_Er.*ones(nCNneurons,1);
+CNtimeSinceLastSpike=zeros(nCNneurons,1);
+% tauGk is the main distinction between neurons
+%  in fact they are all the same in the standard model
+tauGk=repmat(tauGk,nANchannels,1);
+
+CNoutput=false(nCNneurons,reducedSignalLength);
+
+
+%% MacGregor (IC - second nucleus) --------
+nICcells=nANchannels*nCNtauGk;  % one cell per channel
+CN_PSTH=zeros(nICcells ,reducedSegmentLength);
+
+% ICspikeWidth=0.00015;   % this may need revisiting
+% epochsPerSpike=round(ICspikeWidth/ANdt);
+% if epochsPerSpike<1
+%     error(['MacGregorMulti: sample rate too low to support ' ...
+%         num2str(ICspikeWidth*1e6) '  microsec spikes']);
+% end
+
+% short names
+IC_tauM=MacGregorParams.tauM;
+IC_tauGk=MacGregorParams.tauGk;
+IC_tauTh=MacGregorParams.tauTh;
+IC_cap=MacGregorParams.Cap;
+IC_c=MacGregorParams.c;
+IC_b=MacGregorParams.dGkSpike;
+IC_Th0=MacGregorParams.Th0;
+IC_Ek=MacGregorParams.Ek;
+IC_Eb= MacGregorParams.Eb;
+IC_Er=MacGregorParams.Er;
+
+IC_E=zeros(nICcells,1);
+IC_Gk=zeros(nICcells,1);
+IC_Th=IC_Th0*ones(nICcells,1);
+
+% Dendritic filtering, all spikes are replaced by CNalphaFunction functions
+ICdendriteLPfreq= MacGregorParams.dendriteLPfreq;
+ICcurrentPerSpike=MacGregorParams.currentPerSpike;
+ICspikeToCurrentTau=1/(2*pi*ICdendriteLPfreq);
+t=ANdt:ANdt:3*ICspikeToCurrentTau;
+IC_CNalphaFunction= (ICcurrentPerSpike / ...
+    ICspikeToCurrentTau)*t.*exp(-t / ICspikeToCurrentTau);
+% figure(98), plot(t,IC_CNalphaFunction)
+
+% working space for implementing alpha function
+ICcurrentTemp=...
+    zeros(nICcells,reducedSegmentLength+length(IC_CNalphaFunction)-1);
+ICtrailingAlphas=zeros(nICcells, length(IC_CNalphaFunction));
+
+ICfiberTypeRates=zeros(nANfiberTypes,reducedSignalLength);
+ICoutput=false(nICcells,reducedSignalLength);
+
+ICmembranePotential=zeros(nICcells,reducedSegmentLength);
+ICmembraneOutput=zeros(nICcells,signalLength);
+
+
+%% Main program %%  %%  %%  %%  %%  %%  %%  %%  %%  %%  %%  %%  %%  %%
+
+%  Compute the entire model for each segment
+segmentStartPTR=1;
+reducedSegmentPTR=1; % when sampling rate is reduced
+while segmentStartPTR<signalLength
+    segmentEndPTR=segmentStartPTR+segmentLength-1;
+    % shorter segments after speed up.
+    shorterSegmentEndPTR=reducedSegmentPTR+reducedSegmentLength-1;
+
+    inputPressureSegment=inputSignal...
+        (:,segmentStartPTR:segmentStartPTR+segmentLength-1);
+
+    % segment debugging plots
+    % figure(98)
+    % plot(segmentTime,inputPressureSegment), title('signalSegment')
+
+
+    % OME ----------------------
+
+    % OME Stage 1: external resonances. Add to inputSignal pressure wave
+    y=inputPressureSegment;
+    for n=1:nOMEExtFilters
+        % any number of resonances can be used
+        [x  OMEExtFilterBndry{n}] = ...
+            filter(ExtFilter_b{n},ExtFilter_a{n},...
+            inputPressureSegment, OMEExtFilterBndry{n});
+        x= x* OMEgainScalars(n);
+        % This is a parallel resonance so add it
+        y=y+x;
+    end
+    inputPressureSegment=y;
+    OMEextEarPressure(segmentStartPTR:segmentEndPTR)= inputPressureSegment;
+    
+    % OME stage 2: convert input pressure (velocity) to
+    %  tympanic membrane(TM) displacement using low pass filter
+    [TMdisplacementSegment  OME_TMdisplacementBndry] = ...
+        filter(TMdisp_b,TMdisp_a,inputPressureSegment, ...
+        OME_TMdisplacementBndry);
+    % and save it
+    TMoutput(segmentStartPTR:segmentEndPTR)= TMdisplacementSegment;
+
+    % OME stage 3: middle ear high pass effect to simulate stapes inertia
+    [stapesDisplacement  OMEhighPassBndry] = ...
+        filter(stapesDisp_b,stapesDisp_a,TMdisplacementSegment, ...
+        OMEhighPassBndry);
+
+    % OME stage 4:  apply stapes scalar
+    stapesDisplacement=stapesDisplacement*stapesScalar;
+
+    % OME stage 5:    acoustic reflex stapes attenuation
+    %  Attenuate the TM response using feedback from LSR fiber activity
+    if segmentStartPTR>efferentDelayPts
+        stapesDisplacement= stapesDisplacement.*...
+            ARattenuation(segmentStartPTR-efferentDelayPts:...
+            segmentEndPTR-efferentDelayPts);
+    end
+
+    % segment debugging plots
+    % figure(98)
+    % plot(segmentTime, stapesDisplacement), title ('stapesDisplacement')
+
+    % and save
+    OMEoutput(segmentStartPTR:segmentEndPTR)= stapesDisplacement;
+
+
+    %% BM ------------------------------
+    % Each location is computed separately
+    for BFno=1:nBFs
+
+        %            *linear* path
+        linOutput = stapesDisplacement * linGAIN;  % linear gain
+       
+        for order = 1 : GTlinOrder
+            [linOutput GTlinBdry{BFno,order}] = ...
+                filter(GTlin_b(BFno,:), GTlin_a(BFno,:), linOutput, ...
+                GTlinBdry{BFno,order});
+        end
+
+        %           *nonLinear* path
+        % efferent attenuation (0 <> 1)
+        if segmentStartPTR>efferentDelayPts
+            MOC=MOCattenuation(BFno, segmentStartPTR-efferentDelayPts:...
+                segmentEndPTR-efferentDelayPts);
+        else    % no MOC available yet
+            MOC=ones(1, segmentLength);
+        end
+        % apply MOC to nonlinear input function       
+        nonlinOutput=stapesDisplacement.* MOC;
+
+        %       first gammatone filter (nonlin path)
+        for order = 1 : GTnonlinOrder
+            [nonlinOutput GTnonlinBdry1{BFno,order}] = ...
+                filter(GTnonlin_b(BFno,:), GTnonlin_a(BFno,:), ...
+                nonlinOutput, GTnonlinBdry1{BFno,order});
+        end
+        
+%         %    original   broken stick instantaneous compression
+%         y= nonlinOutput.* DRNLa;  % linear section.
+%         % compress parts of the signal above the compression threshold
+%         abs_x = abs(nonlinOutput);
+%         idx=find(abs_x>DRNLcompressionThreshold);
+%         if ~isempty(idx)>0
+%             y(idx)=sign(y(idx)).* (DRNLb*abs_x(idx).^DRNLc);
+%         end
+%         nonlinOutput=y;
+
+        
+        %   new broken stick instantaneous compression
+        y= nonlinOutput.* DRNLa;  % linear section attenuation/gain.
+        % compress parts of the signal above the compression threshold
+%         holdY=y;
+        abs_y = abs(y);
+        idx=find(abs_y>DRNLcompressionThreshold);
+        if ~isempty(idx)>0
+%             y(idx)=sign(y(idx)).* (DRNLcompressionThreshold + ...
+%                 (abs_y(idx)-DRNLcompressionThreshold).^DRNLc);
+            y(idx)=sign(y(idx)).* (DRNLcompressionThreshold + ...
+                (abs_y(idx)-DRNLcompressionThreshold)*DRNLc);
+        end
+        nonlinOutput=y;
+       
+% % Boltzmann compression
+% y=(nonlinOutput * DRNLa*100000);
+% holdY=y;
+% y=abs(y);
+% s=10; u=0.0;
+% x=1./(1+exp(-(y-u)/s))-0.5;
+% nonlinOutput=sign(nonlinOutput).*x/10000;
+
+
+%         if segmentStartPTR==10*segmentLength+1
+%             figure(90)
+%         plot(holdY,'b'), hold on
+%         plot(nonlinOutput, 'r'), hold off
+%         ylim([-1e-5 1e-5])
+%         pause(1)
+%         end
+
+        %       second filter removes distortion products
+        for order = 1 : GTnonlinOrder
+            [ nonlinOutput GTnonlinBdry2{BFno,order}] = ...
+                filter(GTnonlin_b(BFno,:), GTnonlin_a(BFno,:), ...
+                nonlinOutput, GTnonlinBdry2{BFno,order});
+        end
+
+        %  combine the two paths to give the DRNL displacement
+        DRNLresponse(BFno,:)=linOutput+nonlinOutput;
+%         disp(num2str(max(linOutput)))
+    end % BF
+
+    % segment debugging plots
+    % figure(98)
+    %     if size(DRNLresponse,1)>3
+    %         imagesc(DRNLresponse)  % matrix display
+    %         title('DRNLresponse'); % single or double channel response
+    %     else
+    %         plot(segmentTime, DRNLresponse)
+    %     end
+
+    % and save it
+    DRNLoutput(:, segmentStartPTR:segmentEndPTR)= DRNLresponse;
+
+
+    %% IHC ------------------------------------
+    %  BM displacement to IHCciliaDisplacement is  a high-pass filter
+    %   because of viscous coupling
+    for idx=1:nBFs
+        [IHCciliaDisplacement(idx,:)  IHCciliaBndry{idx}] = ...
+            filter(IHCciliaFilter_b,IHCciliaFilter_a, ...
+            DRNLresponse(idx,:), IHCciliaBndry{idx});
+    end
+    
+    % apply scalar
+    IHCciliaDisplacement=IHCciliaDisplacement* IHC_C;
+
+    % and save it
+    IHC_cilia_output(:,segmentStartPTR:segmentStartPTR+segmentLength-1)=...
+        IHCciliaDisplacement;
+
+    % compute apical conductance
+    G=IHCGmax./(1+exp(-(IHCciliaDisplacement-IHCu0)/IHCs0).*...
+        (1+exp(-(IHCciliaDisplacement-IHCu1)/IHCs1)));
+    Gu=G + IHCGa;
+
+    % Compute receptor potential
+    for idx=1:segmentLength
+        IHC_Vnow=IHC_Vnow+ (-Gu(:, idx).*(IHC_Vnow-IHC_Et)-...
+            IHC_Gk*(IHC_Vnow-IHC_Ekp))*  dt/IHC_Cab;
+        IHC_RP(:,idx)=IHC_Vnow;
+    end
+
+    % segment debugging plots
+    %     if size(IHC_RP,1)>3
+    %         surf(IHC_RP), shading interp, title('IHC_RP')
+    %     else
+    %         plot(segmentTime, IHC_RP)
+    %     end
+
+    % and save it
+    IHCoutput(:, segmentStartPTR:segmentStartPTR+segmentLength-1)=IHC_RP;
+
+
+    %% synapse -----------------------------
+    % Compute the vesicle release rate for each fiber type at each BF
+    % replicate IHC_RP for each fiber type
+    Vsynapse=repmat(IHC_RP, nANfiberTypes,1);
+
+    % look-up table of target fraction channels open for a given IHC_RP
+    mICaINF=    1./( 1 + exp(-gamma  * Vsynapse)  /beta);
+    % fraction of channel open - apply time constant
+    for idx=1:segmentLength
+        % mICaINF is the current 'target' value of mICa
+        mICaCurrent=mICaCurrent+(mICaINF(:,idx)-mICaCurrent)*dt./tauM;
+        mICa(:,idx)=mICaCurrent;
+    end
+
+    ICa=   (GmaxCa* mICa.^3) .* (Vsynapse- ECa);
+
+    for idx=1:segmentLength
+        CaCurrent=CaCurrent +  ICa(:,idx)*dt - CaCurrent*dt./tauCa;
+        synapticCa(:,idx)=CaCurrent;
+    end
+    synapticCa=-synapticCa; % treat synapticCa as positive substance
+
+    % NB vesicleReleaseRate is /s and is independent of dt
+    vesicleReleaseRate = synapse_z * synapticCa.^synapse_power; % rate
+
+    % segment debugging plots
+    %     if size(vesicleReleaseRate,1)>3
+    %         surf(vesicleReleaseRate), shading interp, title('vesicleReleaseRate')
+    %     else
+    %         plot(segmentTime, vesicleReleaseRate)
+    %     end
+
+
+    %% AN
+    switch AN_spikesOrProbability
+        case 'probability'
+            % No refractory effect is applied
+            for t = 1:segmentLength;
+                M_Pq=PAN_M-Pavailable;
+                M_Pq(M_Pq<0)=0;
+                Preplenish = M_Pq .* PAN_ydt;
+                Pejected = Pavailable.* vesicleReleaseRate(:,t)*dt;
+                Preprocessed = M_Pq.*Preprocess.* PAN_xdt;
+
+                ANprobability(:,t)= min(Pejected,1);
+                reuptakeandlost= PAN_rdt_plus_ldt .* Pcleft;
+                reuptake= PAN_rdt.* Pcleft;
+
+                Pavailable= Pavailable+ Preplenish- Pejected+ Preprocessed;
+                Pcleft= Pcleft + Pejected - reuptakeandlost;
+                Preprocess= Preprocess + reuptake - Preprocessed;
+                Pavailable(Pavailable<0)=0;
+                savePavailableSeg(:,t)=Pavailable;    % synapse tracking
+                
+            end
+
+            % and save it as *rate*
+            ANrate=ANprobability/dt;
+            ANprobRateOutput(:, segmentStartPTR:...
+                segmentStartPTR+segmentLength-1)=  ANrate;
+            % monitor synapse contents (only sometimes used)
+            savePavailable(:, segmentStartPTR:segmentStartPTR+segmentLength-1)=...
+                savePavailableSeg;
+            
+            %% Apply refractory effect
+               % the probability of a spike's occurring in the preceding
+               %  refractory window (t= tnow-refractory period to tnow-)
+               %    pFired= 1 - II(1-p(t)),
+               % we need a running account of cumProb=II(1-p(t))
+               %   cumProb(t)= cumProb(t-1)*(1-p(t))/(1-p(t-refracPeriod))
+               %   cumProb(0)=0
+               %   pFired(t)= 1-cumProb(t)
+               % This gives the fraction of firing events that must be 
+               %  discounted because of a firing event in the refractory
+               %  period
+               %   p(t)= ANprobOutput(t) * pFired(t)
+               % where ANprobOutput is the uncorrected firing probability
+               %  based on vesicle release rate
+               % NB this covers only the absoute refractory period
+               % not the relative refractory period. To approximate this it
+               % is necessary to extend the refractory period by 50%
+
+
+                for t = segmentStartPTR:segmentEndPTR;
+                    if t>1
+                    ANprobRateOutput(:,t)= ANprobRateOutput(:,t)...
+                        .* cumANnotFireProb(:,t-1);
+                    end
+                    % add recent and remove distant probabilities
+                    refrac=round(lengthAbsRefractoryP * 1.5);
+                    if t>refrac
+                        cumANnotFireProb(:,t)= cumANnotFireProb(:,t-1)...
+                            .*(1-ANprobRateOutput(:,t)*dt)...
+                            ./(1-ANprobRateOutput(:,t-refrac)*dt);
+                    end
+                end
+%                 figure(88), plot(cumANnotFireProb'), title('cumNotFire')
+%                 figure(89), plot(ANprobRateOutput'), title('ANprobRateOutput')
+
+            %% Estimate efferent effects. ARattenuation (0 <> 1)
+            %  acoustic reflex
+            [r c]=size(ANrate);
+            if r>nBFs % Only if LSR fibers are computed
+                ARAttSeg=mean(ANrate(1:nBFs,:),1); %LSR channels are 1:nBF
+                % smooth
+                [ARAttSeg, ARboundaryProb] = ...
+                    filter(ARfilt_b, ARfilt_a, ARAttSeg, ARboundaryProb);
+                ARAttSeg=ARAttSeg-ARrateThreshold;
+                ARAttSeg(ARAttSeg<0)=0;   % prevent negative strengths
+                ARattenuation(segmentStartPTR:segmentEndPTR)=...
+                    (1-ARrateToAttenuationFactorProb.* ARAttSeg);
+            end
+            %             plot(ARattenuation)
+
+            % MOC attenuation based on within-channel HSR fiber activity
+            HSRbegins=nBFs*(nANfiberTypes-1)+1;
+            rates=ANrate(HSRbegins:end,:);
+            if rateToAttenuationFactorProb<0
+                % negative factor implies a fixed attenuation
+                MOCattenuation(:,segmentStartPTR:segmentEndPTR)= ...
+                    ones(size(rates))* -rateToAttenuationFactorProb;
+            else
+                for idx=1:nBFs
+                    [smoothedRates, MOCprobBoundary{idx}] = ...
+                        filter(MOCfilt_b, MOCfilt_a, rates(idx,:), ...
+                        MOCprobBoundary{idx});
+                    smoothedRates=smoothedRates-MOCrateThresholdProb;
+                    smoothedRates=max(smoothedRates, 0);
+                    
+                    x=(1- smoothedRates* rateToAttenuationFactorProb);
+                    x=max(x, 10^(-30/20));
+                    MOCattenuation(idx,segmentStartPTR:segmentEndPTR)= x;
+                end
+            end
+            MOCattenuation(MOCattenuation<0)=0.001;
+
+            %             plot(MOCattenuation)
+
+
+        case 'spikes'
+            ANtimeCount=0;
+            % implement speed upt
+            for t = ANspeedUpFactor:ANspeedUpFactor:segmentLength;
+                ANtimeCount=ANtimeCount+1;
+                % convert release rate to probabilities
+                releaseProb=vesicleReleaseRate(:,t)*ANdt;
+                % releaseProb is the release probability per channel
+                %  but each channel has many synapses
+                releaseProb=repmat(releaseProb',nFibersPerChannel,1);
+                releaseProb=reshape(releaseProb, nFibersPerChannel*nANchannels,1);
+
+                % AN_available=round(AN_available); % vesicles must be integer, (?needed)
+                M_q=AN_M- AN_available;     % number of missing vesicles
+                M_q(M_q<0)= 0;              % cannot be less than 0
+
+                % AN_N1 converts probability to discrete events
+                %   it considers each event that might occur
+                %   (how many vesicles might be released)
+                %   and returns a count of how many were released
+
+                % slow line
+%                 probabilities= 1-(1-releaseProb).^AN_available;
+                probabilities= 1-intpow((1-releaseProb), AN_available);
+                ejected= probabilities> rand(length(AN_available),1);
+
+                reuptakeandlost = AN_rdt_plus_ldt .* AN_cleft;
+                reuptake = AN_rdt.* AN_cleft;
+
+                % slow line
+%                 probabilities= 1-(1-AN_reprocess.*AN_xdt).^M_q;
+                probabilities= 1-intpow((1-AN_reprocess.*AN_xdt), M_q);
+                reprocessed= probabilities>rand(length(M_q),1);
+
+                % slow line
+%                 probabilities= 1-(1-AN_ydt).^M_q;
+                 probabilities= 1-intpow((1-AN_ydt), M_q);
+
+                replenish= probabilities>rand(length(M_q),1);
+
+                AN_available = AN_available + replenish - ejected ...
+                    + reprocessed;
+                AN_cleft = AN_cleft + ejected - reuptakeandlost;
+                AN_reprocess = AN_reprocess + reuptake - reprocessed;
+
+                % ANspikes is logical record of vesicle release events>0
+                ANspikes(:, ANtimeCount)= ejected;
+            end % t
+
+            % zero any events that are preceded by release events ...
+            %  within the refractory period
+            % The refractory period consist of two periods
+            %  1) the absolute period where no spikes occur
+            %  2) a relative period where a spike may occur. This relative
+            %     period is realised as a variable length interval
+            %     where the length is chosen at random
+            %     (esentially a linear ramp up)
+
+            % Andreas has a fix for this
+            for t = 1:ANtimeCount-2*lengthAbsRefractory;
+                % identify all spikes across fiber array at time (t)
+                % idx is a list of channels where spikes occurred
+                % ?? try sparse matrices?
+                idx=find(ANspikes(:,t));
+                for j=idx  % consider each spike
+                    % specify variable refractory period
+                    %  between abs and 2*abs refractory period
+                    nPointsRefractory=lengthAbsRefractory+...
+                        round(rand*lengthAbsRefractory);
+                    % disable spike potential for refractory period
+                    % set all values in this range to 0
+                    ANspikes(j,t+1:t+nPointsRefractory)=0;
+                end
+            end  %t
+
+            % segment debugging
+            % plotInstructions.figureNo=98;
+            % plotInstructions.displaydt=ANdt;
+            %  plotInstructions.numPlots=1;
+            %  plotInstructions.subPlotNo=1;
+            % UTIL_plotMatrix(ANspikes, plotInstructions);
+
+            % and save it. NB, AN is now on 'speedUp' time
+            ANoutput(:, reducedSegmentPTR: shorterSegmentEndPTR)=ANspikes;
+
+
+            %% CN Macgregor first neucleus -------------------------------
+            % input is from AN so ANdt is used throughout
+            % Each CNneuron has a unique set of input fibers selected
+            %  at random from the available AN fibers (CNinputfiberLists)
+
+            % Create the dendritic current for that neuron
+            % First get input spikes to this neuron
+            synapseNo=1;
+            for ch=1:nCNchannels
+                for idx=1:nCNneuronsPerChannel
+                    % determine candidate fibers for this unit
+                    fibersUsed=CNinputfiberLists(synapseNo,:);
+                    % ANpsth has a bin width of ANdt
+                    %  (just a simple sum across fibers)
+                    AN_PSTH(synapseNo,:) = ...
+                        sum(ANspikes(fibersUsed,:), 1);
+                    synapseNo=synapseNo+1;
+                end
+            end
+
+            % One alpha function per spike
+            [alphaRows alphaCols]=size(CNtrailingAlphas);
+
+            for unitNo=1:nCNneurons
+                CNcurrentTemp(unitNo,:)= ...
+                    conv2(AN_PSTH(unitNo,:),CNalphaFunction);
+            end
+%             disp(['sum(AN_PSTH)= ' num2str(sum(AN_PSTH(1,:)))])
+            % add post-synaptic current  left over from previous segment
+            CNcurrentTemp(:,1:alphaCols)=...
+                CNcurrentTemp(:,1:alphaCols)+ CNtrailingAlphas;
+
+            % take post-synaptic current for this segment
+            CNcurrentInput= CNcurrentTemp(:, 1:reducedSegmentLength);
+%                 disp(['mean(CNcurrentInput)= ' num2str(mean(CNcurrentInput(1,:)))])
+
+            % trailingalphas are the ends of the alpha functions that
+            % spill over into the next segment
+            CNtrailingAlphas= ...
+                CNcurrentTemp(:, reducedSegmentLength+1:end);
+
+            if CN_c>0
+                % variable threshold condition (slow)
+                for t=1:reducedSegmentLength
+                    CNtimeSinceLastSpike=CNtimeSinceLastSpike-ANdt;
+                    s=CN_E>CN_Th & CNtimeSinceLastSpike<0 ;
+                    CNtimeSinceLastSpike(s)=0.0005;         % 0.5 ms for sodium spike
+                    dE =(-CN_E/CN_tauM + ...
+                        CNcurrentInput(:,t)/CN_cap+(...
+                        CN_Gk/CN_cap).*(CN_Ek-CN_E))*ANdt;
+                    dGk=-CN_Gk*ANdt./tauGk + CN_b*s;
+                    dTh=-(CN_Th-CN_Th0)*ANdt/CN_tauTh + CN_c*s;
+                    CN_E=CN_E+dE;
+                    CN_Gk=CN_Gk+dGk;
+                    CN_Th=CN_Th+dTh;
+                    CNmembranePotential(:,t)=CN_E+s.*(CN_Eb-CN_E)+CN_Er;
+                end
+            else
+                % static threshold (faster)
+                E=zeros(1,reducedSegmentLength);
+                Gk=zeros(1,reducedSegmentLength);
+                ss=zeros(1,reducedSegmentLength);
+                for t=1:reducedSegmentLength
+                    % time of previous spike moves back in time
+                    CNtimeSinceLastSpike=CNtimeSinceLastSpike-ANdt;
+                    % action potential if E>threshold
+                    %  allow time for s to reset between events
+                    s=CN_E>CN_Th0 & CNtimeSinceLastSpike<0 ;  
+                    ss(t)=s(1);
+                    CNtimeSinceLastSpike(s)=0.0005; % 0.5 ms for sodium spike
+                    dE = (-CN_E/CN_tauM + ...
+                        CNcurrentInput(:,t)/CN_cap +...
+                        (CN_Gk/CN_cap).*(CN_Ek-CN_E))*ANdt;
+                    dGk=-CN_Gk*ANdt./tauGk +CN_b*s;
+                    CN_E=CN_E+dE;
+                    CN_Gk=CN_Gk+dGk;
+                    E(t)=CN_E(1);
+                    Gk(t)=CN_Gk(1);
+                    % add spike to CN_E and add resting potential (-60 mV)
+                    CNmembranePotential(:,t)=CN_E +s.*(CN_Eb-CN_E)+CN_Er;
+                end
+            end
+%             disp(['CN_E= ' num2str(sum(CN_E(1,:)))])
+%             disp(['CN_Gk= ' num2str(sum(CN_Gk(1,:)))])
+%             disp(['CNmembranePotential= ' num2str(sum(CNmembranePotential(1,:)))])
+%             plot(CNmembranePotential(1,:))
+
+
+            % extract spikes.  A spike is a substantial upswing in voltage
+            CN_spikes=CNmembranePotential> -0.02;
+%             disp(['CNspikesbefore= ' num2str(sum(sum(CN_spikes)))])
+
+            % now remove any spike that is immediately followed by a spike
+            % NB 'find' works on columns (whence the transposing)
+            % for each spike put a zero in the next epoch
+            CN_spikes=CN_spikes';
+            idx=find(CN_spikes);
+            idx=idx(1:end-1);
+            CN_spikes(idx+1)=0;
+            CN_spikes=CN_spikes';
+%             disp(['CNspikes= ' num2str(sum(sum(CN_spikes)))])
+
+            % segment debugging
+            % plotInstructions.figureNo=98;
+            % plotInstructions.displaydt=ANdt;
+            %  plotInstructions.numPlots=1;
+            %  plotInstructions.subPlotNo=1;
+            % UTIL_plotMatrix(CN_spikes, plotInstructions);
+
+            % and save it
+            CNoutput(:, reducedSegmentPTR:shorterSegmentEndPTR)=...
+                CN_spikes;
+
+
+            %% IC ----------------------------------------------
+                %  MacGregor or some other second order neurons
+
+                % combine CN neurons in same channel (BF x AN tau x CNtau) 
+                %  i.e. same BF, same tauCa, same CNtau
+                %  to generate inputs to single IC unit
+                channelNo=0;
+                for idx=1:nCNneuronsPerChannel: ...
+                        nCNneurons-nCNneuronsPerChannel+1;
+                    channelNo=channelNo+1;
+                    CN_PSTH(channelNo,:)=...
+                        sum(CN_spikes(idx:idx+nCNneuronsPerChannel-1,:));
+                end
+
+                [alphaRows alphaCols]=size(ICtrailingAlphas);
+                for ICneuronNo=1:nICcells
+                    ICcurrentTemp(ICneuronNo,:)= ...
+                        conv2(CN_PSTH(ICneuronNo,:),  IC_CNalphaFunction);
+                end
+
+                % add the unused current from the previous convolution
+                ICcurrentTemp(:,1:alphaCols)=ICcurrentTemp(:,1:alphaCols)...
+                    + ICtrailingAlphas;
+                % take what is required and keep the trailing part for next time
+                inputCurrent=ICcurrentTemp(:, 1:reducedSegmentLength);
+                ICtrailingAlphas=ICcurrentTemp(:, reducedSegmentLength+1:end);
+
+                if IC_c==0
+                    % faster computation when threshold is stable (c==0)
+                    for t=1:reducedSegmentLength
+                        s=IC_E>IC_Th0;
+                        dE = (-IC_E/IC_tauM + inputCurrent(:,t)/IC_cap +...
+                            (IC_Gk/IC_cap).*(IC_Ek-IC_E))*ANdt;
+                        dGk=-IC_Gk*ANdt/IC_tauGk +IC_b*s;
+                        IC_E=IC_E+dE;
+                        IC_Gk=IC_Gk+dGk;
+                        ICmembranePotential(:,t)=IC_E+s.*(IC_Eb-IC_E)+IC_Er;
+                    end
+                else
+                    %  threshold is changing (IC_c>0; e.g. bushy cell)
+                    for t=1:reducedSegmentLength
+                        dE = (-IC_E/IC_tauM + ...
+                            inputCurrent(:,t)/IC_cap + (IC_Gk/IC_cap)...
+                            .*(IC_Ek-IC_E))*ANdt;
+                        IC_E=IC_E+dE;
+                        s=IC_E>IC_Th;
+                        ICmembranePotential(:,t)=IC_E+s.*(IC_Eb-IC_E)+IC_Er;
+                        dGk=-IC_Gk*ANdt/IC_tauGk +IC_b*s;
+                        IC_Gk=IC_Gk+dGk;
+
+                        % After a spike, the threshold is raised
+                        % otherwise it settles to its baseline
+                        dTh=-(IC_Th-Th0)*ANdt/IC_tauTh +s*IC_c;
+                        IC_Th=IC_Th+dTh;
+                    end
+                end
+
+                ICspikes=ICmembranePotential> -0.01;
+                % now remove any spike that is immediately followed by a spike
+                % NB 'find' works on columns (whence the transposing)
+                ICspikes=ICspikes';
+                idx=find(ICspikes);
+                idx=idx(1:end-1);
+                ICspikes(idx+1)=0;
+                ICspikes=ICspikes';
+
+                nCellsPerTau= nICcells/nANfiberTypes;
+                firstCell=1;
+                lastCell=nCellsPerTau;
+                for tauCount=1:nANfiberTypes
+                    % separate rates according to fiber types
+                    % currently only the last segment is saved
+                    ICfiberTypeRates(tauCount, ...
+                        reducedSegmentPTR:shorterSegmentEndPTR)=...
+                        sum(ICspikes(firstCell:lastCell, :))...
+                        /(nCellsPerTau*ANdt);
+                    firstCell=firstCell+nCellsPerTau;
+                    lastCell=lastCell+nCellsPerTau;
+                end
+                
+                ICoutput(:,reducedSegmentPTR:shorterSegmentEndPTR)=ICspikes;
+                
+                % store membrane output on original dt scale
+                % do this for single channel models only 
+                % and only for the HSR-driven IC cells
+                if round(nICcells/length(ANtauCas))==1  % single channel
+                    % select HSR driven cells
+                    x= ICmembranePotential(length(ANtauCas),:);
+                    % restore original dt
+                    x= repmat(x, ANspeedUpFactor,1);
+                    x= reshape(x,1,segmentLength);
+                    if nANfiberTypes>1  % save HSR and LSR
+                        y=repmat(ICmembranePotential(end,:),...
+                            ANspeedUpFactor,1);
+                        y= reshape(y,1,segmentLength);
+                        x=[x; y];
+                    end
+                    ICmembraneOutput(:, segmentStartPTR:segmentEndPTR)= x;
+                end
+
+                % estimate efferent effects.
+                % ARis based on LSR units. LSR channels are 1:nBF
+                if nANfiberTypes>1  % AR is multi-channel only
+                    ARAttSeg=sum(ICspikes(1:nBFs,:),1)/ANdt;
+                    [ARAttSeg, ARboundary] = ...
+                        filter(ARfilt_b, ARfilt_a, ARAttSeg, ARboundary);
+                    ARAttSeg=ARAttSeg-ARrateThreshold;
+                    ARAttSeg(ARAttSeg<0)=0;   % prevent negative strengths
+                    % scale up to dt from ANdt
+                    x=    repmat(ARAttSeg, ANspeedUpFactor,1);
+                    x=reshape(x,1,segmentLength);
+                    ARattenuation(segmentStartPTR:segmentEndPTR)=...
+                        (1-ARrateToAttenuationFactor* x);
+                    ARattenuation(ARattenuation<0)=0.001;
+                else
+                    % single channel model; disable AR
+                    ARattenuation(segmentStartPTR:segmentEndPTR)=...
+                        ones(1,segmentLength);
+                end
+
+                % MOC attenuation using HSR response only
+                % Separate MOC effect for each BF
+                HSRbegins=nBFs*(nANfiberTypes-1)+1;
+                rates=ICspikes(HSRbegins:end,:)/ANdt;
+                for idx=1:nBFs
+                    [smoothedRates, MOCboundary{idx}] = ...
+                        filter(MOCfilt_b, MOCfilt_a, rates(idx,:), ...
+                        MOCboundary{idx});
+                    % spont 'rates' is zero for IC
+                    MOCattSegment(idx,:)=smoothedRates;
+                    % expand timescale back to model dt from ANdt
+                    x= repmat(MOCattSegment(idx,:), ANspeedUpFactor,1);
+                    x= reshape(x,1,segmentLength);
+                    MOCattenuation(idx,segmentStartPTR:segmentEndPTR)= ...
+                        (1- MOCrateToAttenuationFactor*  x);
+                end
+                MOCattenuation(MOCattenuation<0)=0.04;
+                % segment debugging
+                % plotInstructions.figureNo=98;
+                % plotInstructions.displaydt=ANdt;
+                %  plotInstructions.numPlots=1;
+                %  plotInstructions.subPlotNo=1;
+                % UTIL_plotMatrix(ICspikes, plotInstructions);
+
+    end     % AN_spikesOrProbability
+    segmentStartPTR=segmentStartPTR+segmentLength;
+    reducedSegmentPTR=reducedSegmentPTR+reducedSegmentLength;
+
+
+end  % segment
+
+%% apply refractory correction to spike probabilities
+
+% the probability of a spike's having occurred in the preceding 
+%  refractory window 
+%    pFired= 1 - II(1-p(t)), t= tnow-refractory period: tnow-1
+% we need a running account of cumProb=II(1-p(t))
+%   cumProb(t)= cumProb(t-1)*(1-p(t-1))/(1-p(t-refracPeriod))
+%   cumProb(0)=0
+%   pFired(t)= 1-cumProb(t)
+% whence
+%   p(t)= ANprobOutput(t) * pFired(t)
+% where ANprobOutput is the uncorrected probability
+
+
+% switch AN_spikesOrProbability
+%     case 'probability'
+%         ANprobOutput=ANprobRateOutput*dt;
+%         [r nEpochs]=size(ANprobOutput);
+%         % find probability of no spikes in refractory period
+%         pNoSpikesInRefrac=ones(size(ANprobOutput));
+%         pSpike=zeros(size(ANprobOutput));
+%         for epochNo=lengthAbsRefractoryP+2:nEpochs
+%             pNoSpikesInRefrac(:,epochNo)=...
+%                 pNoSpikesInRefrac(:,epochNo-2)...
+%                 .*(1-pSpike(:,epochNo-1))...
+%                 ./(1-pSpike(:,epochNo-lengthAbsRefractoryP-1));
+%             pSpike(:,epochNo)= ANprobOutput(:,epochNo)...
+%                 .*pNoSpikesInRefrac(:,epochNo);
+%         end
+%         ANprobRateOutput=pSpike/dt;
+% end
+
+path(restorePath)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsTim/Pavel_MAP1_14.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,189 @@
+function Pavel_MAP1_14
+% test_MAP1_14 is a general purpose test routine that can be adjusted to
+% test a number of different applications of MAP1_14
+%
+% A range of options are supplied in the early part of the program
+%
+% One use of the function is to create demonstrations; filenames <demoxx>
+%  to illustrate particular features
+%
+% #1
+% Identify the file (in 'MAPparamsName') containing the model parameters
+%
+% #2
+% Identify the kind of model required (in 'AN_spikesOrProbability').
+%  A full brainstem model (spikes) can be computed or a shorter model
+%  (probability) that computes only so far as the auditory nerve
+%
+% #3
+% Choose between a tone signal or file input (in 'signalType')
+%
+% #4
+% Set the signal rms level (in leveldBSPL)
+%
+% #5
+% Identify the channels in terms of their best frequencies in the vector
+%  BFlist.
+%
+% Last minute changes to the parameters fetched earlier can be made using
+%  the cell array of strings 'paramChanges'.
+%  Each string must have the same format as the corresponding line in the
+%  file identified in 'MAPparamsName'
+%
+% When the demonstration is satisfactory, freeze it by renaming it <demoxx>
+
+restorePath=path;
+addpath (['..' filesep 'MAP'],    ['..' filesep 'wavFileStore'], ...
+    ['..' filesep 'utilities'])
+
+%%  #1 parameter file name
+MAPparamsName='Normal';
+
+
+%% #2 probability (fast) or spikes (slow) representation
+AN_spikesOrProbability='spikes';
+
+% or
+% AN_spikesOrProbability='probability';
+% NB probabilities are not corrected for refractory effects
+
+
+%% #3 pure tone, harmonic sequence or speech file input
+signalType= 'tones';
+sampleRate= 100000;
+duration=0.1;                 % seconds
+% toneFrequency= 250:250:8000;    % harmonic sequence (Hz)
+toneFrequency= 1000;            % or a pure tone (Hz8
+rampDuration=.005;              % seconds
+
+% or
+% signalType= 'file';
+% fileName='twister_44kHz';
+
+
+%% #4 rms level
+% signal details
+leveldBSPL= 30;                  % dB SPL
+
+
+%% #5 number of channels in the model
+%   21-channel model (log spacing)
+% numChannels=21;
+% lowestBF=250; 	highestBF= 8000;
+% BFlist=round(logspace(log10(lowestBF), log10(highestBF), numChannels));
+
+%   or specify your own channel BFs
+numChannels=1;
+BFlist=toneFrequency;
+
+
+%% #6 change model parameters
+paramChanges=[];
+
+% or
+% Parameter changes can be used to change one or more model parameters
+%  *after* the MAPparams file has been read
+% This example declares only one fiber type with a calcium clearance time
+% constant of 80e-6 s (HSR fiber) when the probability option is selected.
+% It also removes the speed up that normally takes place for AN spikes
+% It also increases the number of AN fibers computed to 500.
+paramChanges={...
+    'AN_IHCsynapseParams.ANspeedUpFactor=1;', ...
+    'IHCpreSynapseParams.tauCa=86e-6;',...
+    'AN_IHCsynapseParams.numFibers=	500;' };
+
+
+%% delare 'showMap' options to control graphical output
+global showMapOptions
+
+% or (example: show everything including an smoothed SACF output
+showMapOptions.printModelParameters=1;   % prints all parameters
+showMapOptions.showModelOutput=1;       % plot of all stages
+showMapOptions.printFiringRates=1;      % prints stage activity levels
+showMapOptions.showACF=0;               % shows SACF (probability only)
+showMapOptions.showEfferent=0;          % tracks of AR and MOC
+showMapOptions.surfProbability=0;       % 2D plot of HSR response 
+if strcmp(AN_spikesOrProbability, 'spikes')
+    % avoid nonsensical options
+    showMapOptions.surfProbability=0;
+    showMapOptions.showACF=0;
+end
+if strcmp(signalType, 'file')
+    % needed for labeling plot
+    showMapOptions.fileName=fileName;
+else
+    showMapOptions.fileName=[];
+end
+
+%% Generate stimuli
+
+dbstop if error
+restorePath=path;
+addpath (['..' filesep 'MAP'],    ['..' filesep 'wavFileStore'])
+switch signalType
+    case 'tones'
+        inputSignal=createMultiTone(sampleRate, toneFrequency, ...
+            leveldBSPL, duration, rampDuration);
+
+    case 'file'
+        %% file input simple or mixed
+        [inputSignal sampleRate]=wavread(fileName);
+        dt=1/sampleRate;
+        inputSignal=inputSignal(:,1);
+        targetRMS=20e-6*10^(leveldBSPL/20);
+        rms=(mean(inputSignal.^2))^0.5;
+        amp=targetRMS/rms;
+        inputSignal=inputSignal*amp;
+        silence= zeros(1,round(0.1/dt));
+        inputSignal= [silence inputSignal' silence];
+end
+
+
+%% run the model
+tic
+
+fprintf('\n')
+disp(['Signal duration= ' num2str(length(inputSignal)/sampleRate)])
+disp([num2str(numChannels) ' channel model'])
+disp('Computing ...')
+
+
+MAP1_14(inputSignal, sampleRate, BFlist, ...
+    MAPparamsName, AN_spikesOrProbability, paramChanges);
+toc
+
+% the model run is now complete. Now display the results
+% the model run is now complete. Now display the results
+disp(' param changes to list of parameters below')
+for i=1:length(paramChanges)
+    disp(paramChanges{i})
+end
+UTIL_showMAP(showMapOptions)
+
+toc
+path(restorePath)
+
+
+function inputSignal=createMultiTone(sampleRate, toneFrequency, ...
+    leveldBSPL, duration, rampDuration)
+% Create pure tone stimulus
+dt=1/sampleRate; % seconds
+time=dt: dt: duration;
+inputSignal=sum(sin(2*pi*toneFrequency'*time), 1);
+amp=10^(leveldBSPL/20)*28e-6;   % converts to Pascals (peak)
+inputSignal=amp*inputSignal;
+
+% apply ramps
+% catch rampTime error
+if rampDuration>0.5*duration, rampDuration=duration/2; end
+rampTime=dt:dt:rampDuration;
+ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ...
+    ones(1,length(time)-length(rampTime))];
+inputSignal=inputSignal.*ramp;
+ramp=fliplr(ramp);
+inputSignal=inputSignal.*ramp;
+
+% add 10 ms silence
+silence= zeros(1,round(0.03/dt));
+inputSignal= [silence inputSignal silence];
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsTim/cutsignal.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,96 @@
+function outsignal = cutsignal(insignal,samplingfrequency,vocabularyset)
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%
+%   This function cuts the silence before and after the audiosignal
+%
+%  (c) Tim Jürgens, Medizinische Physik, Feb.2006
+%
+%  usage: outsignal = cutsignal(insignal,samplingfrequency,vocabularyset)
+%
+%   
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% initial_energythreshold = 0.11;
+% final_energythreshold = 0.05;
+% 
+% % choose initial and final delay due to different vocabularysets
+% if (strcmp(vocabularyset,'f_f') > 0)
+%     initial_delay = 0.17; % the speech started delay seconds before trespassing threshold (default 0.01, for f_f: 0.17)
+%     final_delay = 0.2; %default 0.1, for f_f: 0.2
+% else
+%     initial_delay = 0.01; % the speech started delay seconds before trespassing threshold (default 0.01, for f_f: 0.2)
+%     final_delay = 0.1; %default 0.1, for f_f: 0.2
+% end
+% 
+% [initialsample_of_frame, energy] = compute_energy(insignal, samplingfrequency);
+% for i = 1:length(initialsample_of_frame)
+%     if (energy(i) > initial_energythreshold)
+%         initialsample = initialsample_of_frame(i)-samplingfrequency*initial_delay;
+%         break;
+%     end
+% end
+% 
+% time_inverted_energy = energy(end:-1:1); %turn signal around
+% time_inverted_initialsample = initialsample_of_frame(end:-1:1);
+% 
+% for i = 1:length(time_inverted_initialsample)
+%     if (time_inverted_energy(i) > final_energythreshold)
+%         finalsample = time_inverted_initialsample(i)+samplingfrequency*final_delay;
+%         break;
+%     end
+% end
+% 
+% if (finalsample > length(insignal))
+%     finalsample = length(insignal);
+% end
+% outsignal = insignal(initialsample:finalsample);
+
+if nargin < 3
+    vocabularyset = 'a_a'; %default vocabularyset
+end
+
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+initial_threshold = 0.15; %amplitude threshold for detection of speech
+final_threshold = 0.1;
+
+% choose initial and final delay due to different vocabularysets
+if (strcmp(vocabularyset,'f_f') > 0)
+    initial_delay = 0.2; % the speech started delay seconds before trespassing threshold (default 0.01, for f_f: 0.2)
+    final_delay = 0.2; %default 0.1, for f_f: 0.2
+else
+    initial_delay = 0.01; % the speech started delay seconds before trespassing threshold (default 0.01, for f_f: 0.2)
+    final_delay = 0.1; %default 0.1, for f_f: 0.2
+end
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+
+%cut signal with taking initial delay into account
+for(i = 1:length(insignal))
+    if (abs(insignal(i)) > initial_threshold)
+        initialsample = i - samplingfrequency*initial_delay;
+        break;
+    end
+end
+
+
+time_inverted_insignal = insignal(end:-1:1); %turn signal around
+% cut it with taking a final delay into account
+for(i = 1:length(time_inverted_insignal))
+    if (abs(time_inverted_insignal(i)) > final_threshold)
+        finalsample = i - samplingfrequency*final_delay;
+        break;
+    end
+end
+
+if (finalsample < 0)
+    finalsample = 0;
+end
+if (initialsample < 1)
+    initialsample = 1;
+end
+
+%% output %%%
+outsignal = insignal(initialsample:end-finalsample);
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsTim/enframe.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,74 @@
+function [f,t]=enframe(x,win,inc)
+%ENFRAME split signal up into (overlapping) frames: one per row. [F,T]=(X,WIN,INC)
+%
+%	F = ENFRAME(X,LEN) splits the vector X(:) up into
+%	frames. Each frame is of length LEN and occupies
+%	one row of the output matrix. The last few frames of X
+%	will be ignored if its length is not divisible by LEN.
+%	It is an error if X is shorter than LEN.
+%
+%	F = ENFRAME(X,LEN,INC) has frames beginning at increments of INC
+%	The centre of frame I is X((I-1)*INC+(LEN+1)/2) for I=1,2,...
+%	The number of frames is fix((length(X)-LEN+INC)/INC)
+%
+%	F = ENFRAME(X,WINDOW) or ENFRAME(X,WINDOW,INC) multiplies
+%	each frame by WINDOW(:)
+%
+%   The second output argument, T, gives the time in samples at the centre
+%   of each frame. T=i corresponds to the time of sample X(i). 
+%
+% Example of frame-based processing:
+%          INC=20       													% set frame increment
+%          NW=INC*2     													% oversample by a factor of 2 (4 is also often used)
+%          S=cos((0:NW*7)*6*pi/NW);								% example input signal
+%          W=sqrt(hamming(NW+1)); W(end)=[];      % sqrt hamming window of period NW
+%          F=enframe(S,W,INC);               			% split into frames
+%          ... process frames ...
+%          X=overlapadd(F,W,INC);           			% reconstitute the time waveform (omit "X=" to plot waveform)
+
+%	   Copyright (C) Mike Brookes 1997
+%      Version: $Id: enframe.m,v 1.7 2009/11/01 21:08:21 dmb Exp $
+%
+%   VOICEBOX is a MATLAB toolbox for speech processing.
+%   Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html
+%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%   This program 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 2 of the License, or
+%   (at your option) any later version.
+%
+%   This program 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 can obtain a copy of the GNU General Public License from
+%   http://www.gnu.org/copyleft/gpl.html or by writing to
+%   Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+nx=length(x(:));
+nwin=length(win);
+if (nwin == 1)
+   len = win;
+else
+   len = nwin;
+end
+if (nargin < 3)
+   inc = len;
+end
+nf = fix((nx-len+inc)/inc);
+f=zeros(nf,len);
+indf= inc*(0:(nf-1)).';
+inds = (1:len);
+f(:) = x(indf(:,ones(1,len))+inds(ones(nf,1),:));
+if (nwin > 1)
+    w = win(:)';
+    f = f .* w(ones(nf,1),:);
+end
+if nargout>1
+    t=(1+len)/2+indf;
+end
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsTim/fourier_analyse.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,22 @@
+function [frequency,out] = fourier_analyse(in, sfreq,color_plot)
+%
+%plots absolute values of fft of input signal on a semilogarithmic scale
+%long term spectrum
+%
+%use:      [frequency,out] = fourier_analyse(in, sfreq)
+%          in: input signal
+%          sfreq: samplingfrequency
+%          frequency: frequency vector
+%          out: fourier-spectrum (complex)
+if ~exist('color_plot')
+    color_plot = 'b';
+end
+out = fft(in)/(length(in));  %%Normierung auf Wurzel der Länge, da Matlab intern ohne Normierung der Hin-Fouriertransformation arbeitet
+t = [0:1/sfreq:length(in)/sfreq-1/sfreq];
+frequency = [0:1/t(end):1/(2*(t(2)-t(1)))];
+%spektrale leistungsdichte wird geplottet, wobei eine amplitude von 1 100
+%dB entspricht
+plot(frequency,20*log10(sqrt(2)*abs(out(1:round(length(in)/2)))),color_plot);
+%sqrt(2) weil Gesamtenergie auch in Spiegelfrequenzen enthalten
+xlabel('frequency / Hz');
+ylabel('fourier amplitude / dB');
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsTim/fourierautocorrelationhistogram.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,83 @@
+function fach=fourierautocorrelationhistogram(ANpattern,sfreq)
+
+
+time_axis = 0:1/sfreq:(size(ANpattern,2)-1)/sfreq;
+
+%find how many samples of AN_pattern are 10ms and 3ms
+%one_sample_is_a_time_of = time_axis(2);
+[tmp, start_time_index] = min(abs(0-time_axis));
+[tmp, stop20_time_index] = min(abs(0.020-time_axis));
+number_of_samples20ms = stop20_time_index - start_time_index;
+
+[tmp, stop3_time_index] = min(abs(0.003-time_axis));
+number_of_samples3ms = stop3_time_index - start_time_index;
+every_3ms = 1:number_of_samples3ms:size(ANpattern,2)-number_of_samples20ms;
+
+hamm_window = hamming(11);
+halfHamming = (length(hamm_window)-1)/2;
+
+% window normalization
+
+norm = conv(ones(1,floor(number_of_samples20ms/2)),hamm_window);
+norm = norm(5+1:end-5)';
+win_size = number_of_samples20ms;
+half_win_size = floor(win_size/2);
+hop_size = number_of_samples3ms;
+
+%preallocation due to speed
+fach = zeros(half_win_size,size(every_3ms,2));
+
+for iCounter = 1:size(ANpattern,1) %each channel
+    fprintf('Channel No. %i\n',iCounter);
+    %time_counter = 1;
+    %for jCounter = every_3ms %every 3ms time segment
+    
+    
+    
+    %% Guy's code
+    % enframe this signal
+    
+    frames = enframe(ANpattern(iCounter,:),win_size,hop_size);
+    
+    % compute the autocorrelation
+    
+    acf = real(ifft(abs(fft(frames,[],2)).^2,[],2));
+    acf(acf<0)=0;
+    acf = sqrt(acf(:,1:half_win_size));
+    
+    % smooth with hamming window and take the root
+    
+    for frame=1:size(acf,1)
+        
+               
+        smoothed_correlation = conv(acf(frame,:),hamm_window);
+        smoothed_correlation = smoothed_correlation(halfHamming+1:end-halfHamming)./norm';
+        fsra = abs(fft(smoothed_correlation-mean(smoothed_correlation)));
+        fsra = fsra(1:floor(length(fsra)/2));
+        
+        t = [0:1/sfreq:length(smoothed_correlation)/sfreq-1/sfreq];
+        frequency = [0:1/t(end):1/(2*(t(2)-t(1)))];
+        %identify peaks in the fft
+        df = [0 ; diff(fsra')];
+        idx = find((df(1:end-1)>=0)&(df(2:end)<0));
+%         % interpolate
+%         a=df(idx);
+%         b=df(idx+1);
+%         idx = (idx-1+a./(a-b));
+        [sorted,sortedindex]=sort(fsra(idx),'descend');
+        % just take the three highest values of the fourier-transform
+         valid_peak_index = sortedindex(1:min([length(sortedindex) 3]));
+         amp = sorted(1:min([length(sortedindex) 3]));
+         
+         %store valid peaks according to amplitude in a histogram
+         if (~isempty(valid_peak_index))
+            for k=1:length(valid_peak_index),
+                fach(idx(valid_peak_index(k)),frame) = fach(idx(valid_peak_index(k)),frame)+amp(k);            
+            end
+        end
+         %transform index into frequencies
+         
+    end
+end
+
+%fach = 0;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsTim/fourierautocorrelationhistogram_direct.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,109 @@
+function fach=fourierautocorrelationhistogram_direct(ANpattern,sfreq,plothandle)
+
+
+time_axis = 0:1/sfreq:(size(ANpattern,2)-1)/sfreq;
+
+%find how many samples of AN_pattern are 10ms and 3ms
+%one_sample_is_a_time_of = time_axis(2);
+[tmp, start_time_index] = min(abs(0-time_axis));
+[tmp, stop20_time_index] = min(abs(0.020-time_axis));
+number_of_samples20ms = stop20_time_index - start_time_index;
+
+[tmp, stop3_time_index] = min(abs(0.003-time_axis));
+number_of_samples3ms = stop3_time_index - start_time_index;
+every_3ms = 1:number_of_samples3ms:size(ANpattern,2)-number_of_samples20ms;
+
+hamm_window = hamming(11);
+halfHamming = (length(hamm_window)-1)/2;
+
+% window normalization
+
+norm = conv(ones(1,floor(number_of_samples20ms/2)),hamm_window);
+norm = norm(5+1:end-5)';
+win_size = number_of_samples20ms;
+half_win_size = floor(win_size/2);
+hop_size = number_of_samples3ms;
+
+%preallocation due to speed
+fach = zeros(half_win_size,size(every_3ms,2)+1);
+
+for iCounter = 1:size(ANpattern,1) %each channel
+    fprintf('Channel No. %i\n',iCounter);
+    %time_counter = 1;
+    %for jCounter = every_3ms %every 3ms time segment
+    
+    
+    
+    %% Guy's code
+    % enframe this signal
+    
+    frames = enframe(ANpattern(iCounter,:),win_size,hop_size);
+    
+    % compute the autocorrelation
+    
+    %acf = real(ifft(abs(fft(frames,[],2)).^2,[],2));
+    %acf(acf<0)=0;
+    %acf = sqrt(acf(:,1:half_win_size));
+    
+    % smooth with hamming window and take the root
+    
+    for frame=1:size(frames,1)
+        
+               
+        smoothed_frame = conv(frames(frame,:),hamm_window);
+        smoothed_frame = smoothed_frame(halfHamming+1:end-halfHamming);
+        fsra = 20*log10(abs(fft(smoothed_frame-mean(smoothed_frame))));
+        fsra = fsra(1:floor(length(fsra)/2));
+        
+        t = [0:1/sfreq:length(smoothed_frame)/sfreq-1/sfreq];
+        frequency = [0:1/t(end):1/(2*(t(2)-t(1)))];
+        %identify peaks in the fft
+        df = [0 ; diff(fsra')];
+        idx = find((df(1:end-1)>=0)&(df(2:end)<0));
+%         % interpolate
+%         a=df(idx);
+%         b=df(idx+1);
+%         idx = (idx-1+a./(a-b));
+        [sorted,sortedindex]=sort(fsra(idx),'descend');
+        % just take the three highest values of the fourier-transform
+         valid_peak_index = sortedindex(1:min([length(sortedindex) 1]));
+         amp = sorted(1:min([length(sortedindex) 1]));
+         
+         %store valid peaks according to amplitude in a histogram
+         if (~isempty(valid_peak_index))
+            for k=1:length(valid_peak_index),
+                fach(idx(valid_peak_index(k)),frame) = fach(idx(valid_peak_index(k)),frame)+amp(k);            
+            end
+        end
+         %transform index into frequencies
+         
+    end
+end
+
+
+%plot the result
+if ~exist('plothandle'), plothandle=figure; end
+maxfrequency = 4000;
+[tmp,number_of_channels_to_display] = min(abs(frequency-maxfrequency));
+frequency = frequency(1:number_of_channels_to_display);
+
+set(gcf,'Currentaxes',plothandle);
+
+YTickIdx = 1:floor(numel(frequency)/6):numel(frequency);
+XTickIdx = 1:floor(numel(every_3ms)/6):numel(every_3ms);
+YTickIdxRev = numel(frequency)+1-YTickIdx;
+if ~isempty(gca)
+    axes(gca);  %#ok<MAXES>
+    imagesc(fach(1:number_of_channels_to_display,:));
+    axis xy
+    set(gca, 'YTick', YTickIdx);
+    set(gca, 'YTickLabel', num2str(   frequency(YTickIdx)', '%0.0f' ));
+    ylabel('frequency (Hz)')
+    set(gca, 'XTick', XTickIdx);
+    set(gca, 'XTickLabel', XTickIdx.*3);
+    xlabel('Time (ms)')
+end
+
+
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsTim/iloga2sloga.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,160 @@
+function [sOut] = iloga2sloga(iIn)
+% string logatome to integer logatome
+% Bernd Meyer / Medical Physik / University of Oldenburg
+% bernd.meyer@uni-oldenburg.de; March 2005
+
+switch iIn
+   case 001; sOut = 'adda'; 
+   case 002; sOut = 'atta'; 
+   case 003; sOut = 'agga'; 
+   case 004; sOut = 'acka'; 
+   case 005; sOut = 'affa'; 
+   case 006; sOut = 'assa'; 
+   case 007; sOut = 'abba'; 
+   case 008; sOut = 'appa'; 
+   case 009; sOut = 'awwa'; 
+   case 010; sOut = 'azza'; 
+   case 011; sOut = 'amma'; 
+   case 012; sOut = 'anna'; 
+   case 013; sOut = 'ascha';
+   case 014; sOut = 'alla'; 
+   case 015; sOut = 'edde'; 
+   case 016; sOut = 'ette'; 
+   case 017; sOut = 'egge'; 
+   case 018; sOut = 'ecke'; 
+   case 019; sOut = 'effe'; 
+   case 020; sOut = 'esse'; 
+   case 021; sOut = 'ebbe'; 
+   case 022; sOut = 'eppe'; 
+   case 023; sOut = 'ewwe'; 
+   case 024; sOut = 'ezze'; 
+   case 025; sOut = 'emme'; 
+   case 026; sOut = 'enne'; 
+   case 027; sOut = 'esche';
+   case 027; sOut = 'escha';
+   case 028; sOut = 'elle'; 
+   case 029; sOut = 'iddi'; 
+   case 030; sOut = 'itti'; 
+   case 031; sOut = 'iggi'; 
+   case 032; sOut = 'icki'; 
+   case 033; sOut = 'iffi'; 
+   case 034; sOut = 'issi'; 
+   case 035; sOut = 'ibbi'; 
+   case 036; sOut = 'ippi'; 
+   case 037; sOut = 'iwwi'; 
+   case 038; sOut = 'izzi'; 
+   case 039; sOut = 'immi'; 
+   case 040; sOut = 'inni'; 
+   case 041; sOut = 'ischi';
+   case 042; sOut = 'illi'; 
+   case 043; sOut = 'oddo'; 
+   case 044; sOut = 'otto'; 
+   case 045; sOut = 'oggo'; 
+   case 046; sOut = 'ocko'; 
+   case 047; sOut = 'offo'; 
+   case 048; sOut = 'osso'; 
+   case 049; sOut = 'obbo'; 
+   case 050; sOut = 'oppo'; 
+   case 051; sOut = 'owwo'; 
+   case 052; sOut = 'ozzo'; 
+   case 053; sOut = 'ommo'; 
+   case 054; sOut = 'onno'; 
+   case 055; sOut = 'oscho';
+   case 056; sOut = 'ollo'; 
+   case 057; sOut = 'uddu'; 
+   case 058; sOut = 'uttu'; 
+   case 059; sOut = 'uggu'; 
+   case 060; sOut = 'ucku'; 
+   case 061; sOut = 'uffu'; 
+   case 062; sOut = 'ussu'; 
+   case 063; sOut = 'ubbu'; 
+   case 064; sOut = 'uppu'; 
+   case 065; sOut = 'uwwu'; 
+   case 066; sOut = 'uzzu'; 
+   case 067; sOut = 'ummu'; 
+   case 068; sOut = 'unnu'; 
+   case 069; sOut = 'uschu';
+   case 070; sOut = 'ullu'; 
+   case 071; sOut = 'dadd'; 
+   case 072; sOut = 'tatt'; 
+   case 073; sOut = 'gagg'; 
+   case 074; sOut = 'kakk'; 
+   case 075; sOut = 'faff'; 
+   case 076; sOut = 'sass'; 
+   case 077; sOut = 'babb'; 
+   case 078; sOut = 'papp'; 
+   case 079; sOut = 'dedd'; 
+   case 080; sOut = 'tett'; 
+   case 081; sOut = 'gegg'; 
+   case 082; sOut = 'kekk'; 
+   case 083; sOut = 'feff'; 
+   case 084; sOut = 'sess'; 
+   case 085; sOut = 'bebb'; 
+   case 086; sOut = 'pepp'; 
+   case 087; sOut = 'didd'; 
+   case 088; sOut = 'titt'; 
+   case 089; sOut = 'gigg'; 
+   case 090; sOut = 'kikk'; 
+   case 091; sOut = 'fiff'; 
+   case 092; sOut = 'siss'; 
+   case 093; sOut = 'bibb'; 
+   case 094; sOut = 'pipp'; 
+   case 095; sOut = 'dodd'; 
+   case 096; sOut = 'tott'; 
+   case 097; sOut = 'gogg'; 
+   case 098; sOut = 'kokk'; 
+   case 099; sOut = 'foff'; 
+   case 100; sOut = 'soss'; 
+   case 101; sOut = 'bobb'; 
+   case 102; sOut = 'popp'; 
+   case 103; sOut = 'dudd'; 
+   case 104; sOut = 'tutt'; 
+   case 105; sOut = 'gugg'; 
+   case 106; sOut = 'kukk'; 
+   case 107; sOut = 'fuff'; 
+   case 108; sOut = 'suss'; 
+   case 109; sOut = 'bubb'; 
+   case 110; sOut = 'pupp'; 
+   case 111; sOut = 'dahd'; 
+   case 112; sOut = 'taht'; 
+   case 113; sOut = 'gahg'; 
+   case 114; sOut = 'kahk'; 
+   case 115; sOut = 'fahf'; 
+   case 116; sOut = 'sahs'; 
+   case 117; sOut = 'bahb'; 
+   case 118; sOut = 'pahp'; 
+   case 119; sOut = 'dehd'; 
+   case 120; sOut = 'teht'; 
+   case 121; sOut = 'gehg'; 
+   case 122; sOut = 'kehk'; 
+   case 123; sOut = 'fehf'; 
+   case 124; sOut = 'sehs'; 
+   case 125; sOut = 'behb'; 
+   case 126; sOut = 'pehp'; 
+   case 127; sOut = 'died'; 
+   case 128; sOut = 'tiet'; 
+   case 129; sOut = 'gieg'; 
+   case 130; sOut = 'kiek'; 
+   case 131; sOut = 'fief'; 
+   case 132; sOut = 'sies'; 
+   case 133; sOut = 'bieb'; 
+   case 134; sOut = 'piep'; 
+   case 135; sOut = 'dohd'; 
+   case 136; sOut = 'toht'; 
+   case 137; sOut = 'gohg'; 
+   case 138; sOut = 'kohk'; 
+   case 139; sOut = 'fohf'; 
+   case 140; sOut = 'sohs'; 
+   case 141; sOut = 'bohb'; 
+   case 142; sOut = 'pohp'; 
+   case 143; sOut = 'duhd'; 
+   case 144; sOut = 'tuht'; 
+   case 145; sOut = 'guhg'; 
+   case 146; sOut = 'kuhk'; 
+   case 147; sOut = 'fuhf'; 
+   case 148; sOut = 'suhs'; 
+   case 149; sOut = 'buhb'; 
+   case 150; sOut = 'puhp'; 
+otherwise
+   error(['no logatome ' num2str(iIn) ' found in list']);
+end % of switch
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsTim/map_iih_onto_log.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,48 @@
+function [mappediih,centerfreqs] = map_iih_onto_log(iih,numchannels,sfreq)
+
+%function to map an IPIH from the interval axis onto the frequency axis
+%with no overlap and mean firing rate.
+%
+% Tim Juergens, September 2011
+%
+% input: iih: IPIH with dimensions interval (1) and time step (2)
+%             the first dimension translates to time using the actual
+%             sampling frequency
+%        numchannels: number of desired channels
+%        sfreq: sampling frequency
+% output: mappediih: IPIH with dimensions frequency channel (1) and time
+%                    step (2)
+%         centerfreqs: center frequencies of the channels of mappediih
+
+ctr_intervals = [1/sfreq:1/sfreq:size(iih,1)/sfreq];
+lowestBF=1/ctr_intervals(end);
+highestBF=10000;
+
+borderfreqs = logspace(log10(lowestBF),log10(highestBF),numchannels+1);
+
+for iCounter = 1:numchannels
+    centerfreqs(iCounter)=(borderfreqs(iCounter)+borderfreqs(iCounter+1))/2;
+end
+
+for iCounter = 1:length(borderfreqs) %find the indices that correspond to the borderfrequencies of the BF filters
+    [tmp,channelbordersIPIindex(iCounter)]=min(abs(borderfreqs(iCounter)-1./ctr_intervals));
+end
+
+for iCounter = 1:length(centerfreqs)
+    %mapping with one interval sample overlap
+    mappediih(iCounter,:) = mean(iih(channelbordersIPIindex(end-iCounter+1):channelbordersIPIindex(end-iCounter),:));
+end
+
+
+
+% OPTIONAL PLOTTING
+            figure
+            YTickIdx = 1:floor(numel(centerfreqs)/6):numel(centerfreqs);
+            YTickIdxRev = numel(centerfreqs)+1-YTickIdx;
+            if ~isempty(gca)
+                axes(gca);  %#ok<MAXES>
+                imagesc(mappediih);         
+                set(gca, 'YTick', YTickIdx);                
+                set(gca, 'YTickLabel', num2str(   centerfreqs(YTickIdxRev)', '%0.0f' ));
+                ylabel('cf in Hz')                
+            end
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsTim/mellin_trafo.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,45 @@
+function out = mellin_trafo(inx,iny)
+
+%This function computes the Mellin Transformation of a one-dimensional
+%Signal in analytical terms given as
+%
+% S(p)=Integral from 0 to infty of s(t) t^(p-1)dt
+% Which equals 
+% S(c) = Integral from -Infty to Infty s(t)*exp(j*c*log(t))d(log(t))
+%
+% taken from Irino and Patterson, Speech Communication 2002 Eq. (1) and (3)
+% Tim Juergens, September 2011
+%
+
+%Resample the Signal onto a log(t) axis
+minimalx=min(inx);
+maximalx=max(inx);
+logarithmicx= exp([log(minimalx):(log(maximalx)-log(minimalx))/length(inx):log(maximalx)]);
+logarithmicy= interp1(inx,iny,logarithmicx,'linear','extrap');
+%figure, semilogx(logarithmicx,logarithmicy);
+
+%Absolute of the inverse Fourier-Transform of the resampled signal
+out = abs(ifft(logarithmicy));
+%figure, plot(out(1:40));
+
+
+%%just to show that the mellin transform results in invariable patterns if
+%%the formants are a constant ratio
+% frequencies_short = [1:8:8000];
+% frequencies_long = [1:10:10000];
+% Intervals_long = 1./frequencies_long;
+% Intervals_short = 1./frequencies_short;
+% contoursin = sin(2*pi*0.00015.*frequencies_long).^2
+% figure, plot(frequencies_long,contoursin), hold on, plot(frequencies_short,contoursin,'r')
+% xlabel('Frequency (Hz)')
+% ylabel('Rate (arb. units)')
+% figure, semilogx(Intervals_long,contoursin), hold on, plot(Intervals_short,contoursin,'r')
+% xlabel('Interval (s)')
+% ylabel('Rate (arb. units)')
+% m1 = mellin_trafo(Intervals_long,contoursin);
+% m2 = mellin_trafo(Intervals_short,contoursin);
+% figure, plot(m1(1:40)), hold on, plot(m2(1:40),'r');
+% xlabel('Mellin variable c');
+% ylabel('Magnitude');
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsTim/pitchModel_RM.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,242 @@
+function pitchModel_RM
+% Modification of testMAP_14 to replicate the pitch model published
+%  in JASA 2006.
+%
+% test_MAP1_14 is a general purpose test routine that can be adjusted to
+% test a number of different applications of MAP1_14
+%
+% A range of options are supplied in the early part of the program
+%
+% One use of the function is to create demonstrations; filenames <demoxx>
+%  to illustrate particular features
+%
+% #1
+% Identify the file (in 'MAPparamsName') containing the model parameters
+%
+% #2
+% Identify the kind of model required (in 'AN_spikesOrProbability').
+%  A full brainstem model (spikes) can be computed or a shorter model
+%  (probability) that computes only so far as the auditory nerve
+%
+% #3
+% Choose between a tone signal or file input (in 'signalType')
+%
+% #4
+% Set the signal rms level (in leveldBSPL)
+%
+% #5
+% Identify the channels in terms of their best frequencies in the vector
+%  BFlist.
+%
+% Last minute changes to the parameters fetched earlier can be made using
+%  the cell array of strings 'paramChanges'.
+%  Each string must have the same format as the corresponding line in the
+%  file identified in 'MAPparamsName'
+%
+% When the demonstration is satisfactory, freeze it by renaming it <demoxx>
+
+dbstop if error
+restorePath=path;
+addpath (['..' filesep 'MAP'],    ['..' filesep 'wavFileStore'], ...
+    ['..' filesep 'utilities'])
+
+% Pitch model modification here
+global ICrate           % used to collect rate profile from showMAP temporary
+rates=[]; F0count=0;
+
+% F0s=[150 200 250];          % fundamental frequency
+% harmonics= 3:5;
+
+% F0s=[3000];          % fundamental frequency
+F0s=50:5:1000;
+harmonics= 1;
+% F0s=150;
+for F0=F0s
+    F0count=F0count+1;
+    
+
+%%  #1 parameter file name
+MAPparamsName='Normal';
+
+
+%% #2 probability (fast) or spikes (slow) representation
+AN_spikesOrProbability='spikes';
+
+% or
+% NB probabilities are not corrected for refractory effects
+% AN_spikesOrProbability='probability';
+
+
+%% #3 pure tone, harmonic sequence or speech file input
+signalType= 'tones';
+sampleRate= 50000;
+duration=0.50;                 % seconds
+% toneFrequency= 1000;            % or a pure tone (Hz8
+
+% F0=210;
+toneFrequency= F0*harmonics;  % harmonic sequence (Hz)
+
+rampDuration=.005;              % raised cosine ramp (seconds)
+
+% or
+
+% signalType= 'file';
+% fileName='twister_44kHz';
+
+
+%% #4 rms level
+% signal details
+leveldBSPL= 50;                  % dB SPL
+
+
+%% #5 number of channels in the model
+%   21-channel model (log spacing)
+numChannels=21;
+lowestBF=250; 	highestBF= 8000;
+BFlist=round(logspace(log10(lowestBF), log10(highestBF), numChannels));
+
+%   or specify your own channel BFs
+% numChannels=1;
+BFlist=toneFrequency;
+% BFlist=500;
+
+
+%% #6 change model parameters
+paramChanges=[];
+
+% or
+% Parameter changes can be used to change one or more model parameters
+%  *after* the MAPparams file has been read
+% This example declares only one fiber type with a calcium clearance time
+% constant of 80e-6 s (HSR fiber) when the probability option is selected.
+
+% paramChanges={'AN_IHCsynapseParams.ANspeedUpFactor=5;', ...
+%     'IHCpreSynapseParams.tauCa=86e-6;'};
+
+% paramChanges={'DRNLParams.rateToAttenuationFactorProb = 0;'};
+
+% paramChanges={'IHCpreSynapseParams.tauCa=86e-6;',
+%     'AN_IHCsynapseParams.numFibers=	1000;'};
+
+% fixed MOC attenuation(using negative factor)
+% paramChanges={'DRNLParams.rateToAttenuationFactorProb=-0.005;'};
+
+% slow the CN chopping rate
+% paramChanges={'IHCpreSynapseParams.tauCa= 70e-6;'...'
+%     'MacGregorMultiParams.tauGk=	[0.75e-3:.0001 : 3e-3];'...
+%     ' MacGregorParams.dendriteLPfreq=4000;'...
+%     'MacGregorParams.tauGk=	1e-4;'...
+%     'MacGregorParams.currentPerSpike=220e-8;'...
+% };
+paramChanges={...
+    'MacGregorMultiParams.currentPerSpike=25e-9;'...
+    'MacGregorMultiParams.tauGk=	[0.1e-3:.00005 : 1e-3];'...
+'MacGregorParams.currentPerSpike=40e-9;'...
+};
+
+%% delare 'showMap' options to control graphical output
+
+showMapOptions.printModelParameters=0;   % prints all parameters
+showMapOptions.showModelOutput=1;       % plot of all stages
+showMapOptions.printFiringRates=1;      % prints stage activity levels
+showMapOptions.showACF=0;               % shows SACF (probability only)
+showMapOptions.showEfferent=0;          % tracks of AR and MOC
+showMapOptions.surfProbability=0;       % 2D plot of HSR response 
+showMapOptions.surfSpikes=0;            % 2D plot of spikes histogram
+showMapOptions.ICrates=1;               % IC rates by CNtauGk
+
+% disable certain silly options
+if strcmp(AN_spikesOrProbability, 'spikes')
+    % avoid nonsensical options
+    showMapOptions.surfProbability=0;
+    showMapOptions.showACF=0;
+else
+    showMapOptions.surfSpikes=0;
+end
+if strcmp(signalType, 'file')
+    % needed for labeling plot
+    showMapOptions.fileName=fileName;
+else
+    showMapOptions.fileName=[];
+end
+
+%% Generate stimuli
+
+switch signalType
+    case 'tones'
+        inputSignal=createMultiTone(sampleRate, toneFrequency, ...
+            leveldBSPL, duration, rampDuration);
+
+    case 'file'
+        %% file input simple or mixed
+        [inputSignal sampleRate]=wavread(fileName);
+        dt=1/sampleRate;
+        inputSignal=inputSignal(:,1);
+        targetRMS=20e-6*10^(leveldBSPL/20);
+        rms=(mean(inputSignal.^2))^0.5;
+        amp=targetRMS/rms;
+        inputSignal=inputSignal*amp;
+        silence= zeros(1,round(0.1/dt));
+        inputSignal= [silence inputSignal' silence];
+end
+
+
+%% run the model
+tic
+
+fprintf('\n')
+disp(['Signal duration= ' num2str(length(inputSignal)/sampleRate)])
+disp([num2str(numChannels) ' channel model'])
+disp([num2str(F0) ' F0'])
+disp('Computing ...')
+
+MAP1_14(inputSignal, sampleRate, BFlist, ...
+    MAPparamsName, AN_spikesOrProbability, paramChanges);
+
+
+% the model run is now complete. Now display the results
+UTIL_showMAP(showMapOptions, paramChanges)
+
+%% pitch model Collect and analyse data
+% ICrate is global and computed in showMAP
+%  a vector of 'stage4' rates; one value for each tauCNGk
+rates=[rates; ICrate];
+figure(92), imagesc(rates)
+ylabel ('F0 no'), xlabel('tauGk')
+% figure(92), plot(rates), ylim([0 inf])
+
+h=figure(99); CNmovie(F0count)=getframe(h);
+figure(91), plot(rates'),ylim([0 inf])
+pause (0.1)
+path(restorePath)
+
+end
+%% show results
+toc
+figure(91), plot(F0s,rates'), xlabel('F0'), ylabel('rate'),ylim([0 inf])
+% figure(99),clf,movie(CNmovie,1,4)
+
+
+function inputSignal=createMultiTone(sampleRate, toneFrequency, ...
+    leveldBSPL, duration, rampDuration)
+% Create pure tone stimulus
+dt=1/sampleRate; % seconds
+time=dt: dt: duration;
+inputSignal=sum(sin(2*pi*toneFrequency'*time), 1);
+amp=10^(leveldBSPL/20)*28e-6;   % converts to Pascals (peak)
+inputSignal=amp*inputSignal;
+
+% apply ramps
+% catch rampTime error
+if rampDuration>0.5*duration, rampDuration=duration/2; end
+rampTime=dt:dt:rampDuration;
+ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ...
+    ones(1,length(time)-length(rampTime))];
+inputSignal=inputSignal.*ramp;
+ramp=fliplr(ramp);
+inputSignal=inputSignal.*ramp;
+
+% add 10 ms silence
+silence= zeros(1,round(0.005/dt));
+inputSignal= [silence inputSignal silence];
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsTim/plotIFRAN.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,54 @@
+function plotIFRAN(data_matrix,start_time,end_time,sfreq,BFlist,plothandle)
+
+%function that produces a plot similar to the plots in Secker-Walker, JASA
+%1990 Fig.2 (Neurograms) from a IFRAN data matrix
+%Tim Jürgens, January 2011
+
+%plot 50ms right from the middle of the signal
+time_axis = [0:1/sfreq:(size(data_matrix,2)-1)/sfreq];
+%start_time = size(data_matrix,2)/2/sfreq-0.025; %start time to plot in s
+%temporal_length = min([0.05 size(data_matrix,2)/sfreq]); %length to plot in s, at least 50ms or the length of the stimulus
+[tmp, start_time_index] = min(abs(start_time-time_axis));
+%end_time = start_time+temporal_length;
+[tmp, end_time_index] = min(abs(end_time-time_axis));
+
+
+%smoothing using a 4-point hamming window
+hamm_window = hamming(4);
+for iCounter = 1:size(data_matrix,1)
+    for jCounter = 2:length(time_axis)-2 %start with 2 and end with 2 samples
+        %less the length of time_axis in order not to get in conflict with the length of
+        %the hamm_window
+        smoothed_data_matrix(iCounter,jCounter-1) = ...
+            data_matrix(iCounter,(jCounter-1):(jCounter+2))*hamm_window./sum(hamm_window);
+    end
+end
+
+smoothed_time_axis = time_axis(2:end-2);
+
+if ~exist('plothandle'), plothandle=figure; end
+
+verticalshift = 1000; %vertical shift of single time series in z-coordinate units
+Tickvector = [];
+TickLabels = [];
+for iCounter = 1:size(data_matrix,1)
+    set(gcf,'Currentaxes',plothandle);
+    
+    %multiply by 1000 to set abscissa to ms units
+    verticalposition = -verticalshift*(iCounter-1);
+    plot(1000.*smoothed_time_axis(start_time_index:end_time_index), ...
+        smoothed_data_matrix(size(data_matrix,1)-iCounter+1,start_time_index:end_time_index)+verticalposition, ...
+        'k','LineWidth',0.5);
+    xlim([1000*start_time 1000*end_time]);
+    if mod(iCounter,5) == 1 %set best frequency as a label every 5 channels
+        Tickvector = [Tickvector verticalposition];
+        TickLabels = [TickLabels; BFlist(size(data_matrix,1)-iCounter+1)];
+    end
+    hold on;
+end
+set(gca,'yTick',Tickvector(end:-1:1),'yTickLabel',num2str(TickLabels(end:-1:1),'%4.0f'));
+ylabel('Best Frequency of Filter (Hz)');
+xlabel('Stimulus Time (ms)');
+set(gca,'YLim',[-(size(data_matrix,1))*verticalshift verticalshift*1.5]);
+box on;
+hold off;
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsTim/poolIPI_across_channels.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,83 @@
+function [pooledIPIdata,ctr] = poolIPI_across_channels(IPIhisttime,IPIhistweight)
+
+%function that pools IPIdata across all channels in order to plot the data
+%as in Secker-Walker JASA 1990 Fig. 6
+
+%plots IPI-Histograms in a matrix display as in Secker-Walker JASA 1990
+%Fig. 4
+%
+%   Tim Jürgens, February 2011
+%
+% input:  IPIhisttime:     matrix containing the interval times found in the
+%                          analysis
+%                          first dimension: frequency channel
+%                          second dimension: time step (hop position)
+%                          third dimension: interval dimension (max 3)
+%         IPIhistweight:   matrix containing the interval weights found in the
+%                          analysis, same dimensions as IPIhisttime
+% output: pooledIPIdata:   matrix containing the pooled and weighted IPI
+%                          histograms as a function of time (hop position)
+%                          first dimension: time step (hop position)                           
+%                          second dimension: IPI intervals
+%         ctr:             center values of classes of IPI intervals
+% ATTENTION: depending on the amplitude of the signals the value
+% 'verticalshift' might have to be adjusted in order to see structures in
+% the plot
+
+verticalshift =   3000; %0.008;%vertical shift of single time series in z-coordinate units
+ctr = [0:0.02:5].*1e-3; %classes (center-values) of 20 microsec width
+
+%preallocation of variables
+pooledIPIdata = zeros(size(IPIhisttime,2),length(ctr));
+smoothed_pooledIPI = zeros(size(IPIhisttime,2),length(ctr)-5);
+
+for iCounter = 1:size(IPIhisttime,2) %one for time spacing
+    %cannot use matlabs hist function because weighting must be applied
+   
+    tmpIPIhisttime = squeeze(IPIhisttime(:,iCounter,:));
+    tmpIPIhistweight = squeeze(IPIhistweight(:,iCounter,:));
+    tmpIPIhisttime = tmpIPIhisttime(:);
+    tmpIPIhistweight = tmpIPIhistweight(:);
+    for jCounter = 1:length(tmpIPIhisttime)
+        %look which class
+        [tmp1,classindex] = min(abs(tmpIPIhisttime(jCounter)-ctr));
+        pooledIPIdata(iCounter,classindex) = pooledIPIdata(iCounter,classindex)+tmpIPIhistweight(jCounter);
+    end
+    
+end
+
+%smooth data using a 5-point hamming window
+hamm_window = hamming(5);
+for iCounter = 1:size(pooledIPIdata,1)
+    for jCounter = 3:length(ctr)-2 %start with 3 and end with 2 samples
+        %less the length of ctr in order not to get in conflict with the length of
+        %the hamm_window
+        smoothed_pooledIPI(iCounter,jCounter-2) = ...
+            pooledIPIdata(iCounter,(jCounter-2):(jCounter+2))*hamm_window./sum(hamm_window);
+    end
+end
+smoothed_ctr = ctr(3:end-2);
+
+
+figure;
+
+Tickvector = [];
+TickLabels = [];
+for iCounter = 1:size(IPIhisttime,2)
+    hold on;
+    verticalposition = verticalshift*(iCounter-1);
+    %multiply by 1000 to set abscissa to ms units
+    plot(1000.*smoothed_ctr, ...
+        smoothed_pooledIPI(iCounter,:)+verticalposition, ...
+        'k','LineWidth',2);  
+    if mod(iCounter,5) == 1 %set best frequency as a label every 10 channels
+        Tickvector = [Tickvector verticalposition];
+        TickLabels = [TickLabels; (iCounter-1)*3]; %time spacing is every 3ms
+    end
+end
+set(gca,'yTick',Tickvector,'yTickLabel',num2str(TickLabels,'%4.0f'));
+ylabel('Stimulus Time (ms)');
+xlabel('Interval (ms)');
+xlim([min(1000*ctr) max(1000*ctr)]);
+ylim([-verticalshift verticalposition+3*verticalshift]);
+box on;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsTim/runningACF.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,97 @@
+function sampledacf = runningACF(inputSignalMatrix, sfreq, params)
+% runningACF computes within-channel, running autocorrelations (acfs)
+%  and samples it at given time steps
+%
+% INPUT
+%  	inputSignalMatrix: a matrix (channel x time) of AN activity
+%  	sfreq: sampling frequency
+%   
+% params: 	a list of parmeters to guide the computation:
+%   params.lags: an array of lags to be computed (seconds)
+%   params.acfTau: time constant (sec) of the running acf calculations
+%     
+%
+%
+% OUTPUT
+%  	sampledacf:  	(time x lags)
+
+%%
+boundaryValue=[];
+[nChannels inputLength]= size(inputSignalMatrix);
+% list of BFs must be repeated is many fiber types used
+%BFlist=method.nonlinCF;
+%nfibertypes=nChannels/length(BFlist);
+%BFlist=repmat(BFlist',2,1)';
+
+dt=1/sfreq;
+
+samplelength=0.003; %sample length in ms
+gridpoints=round([samplelength:samplelength:inputLength*dt]/dt);
+gridpoints=[1 gridpoints];
+
+lags=params.lags;
+
+nLags=length(lags);
+
+
+% Establish matrix of lag time constants 
+%   these are all the same if tau<1
+
+if params.acfTau<1          % all taus are the same
+    acfTaus=repmat(params.acfTau, 1, nLags);
+    acfDecayFactors=ones(size(lags)).*exp(-dt/params.acfTau);
+else                     
+    error('acfTau must be <1');
+end
+% make acfDecayFactors into a (channels x lags) matrix for speedy computation
+acfDecayFactors=repmat(acfDecayFactors,nChannels, 1);
+
+% P function lowpass filter decay (only one value needed)
+%pDecayFactor=exp(-dt/params.lambda);
+
+% ACF
+% lagPointers is a list of pointers relative to 'time now'
+lagPointers=round(lags/dt);
+lagWeights=ones(nChannels,nLags);
+if max(lagPointers)+1>inputLength
+    error([' filteredSACF: not enough signal to evaluate ACF. Max(lag)= ' num2str(max(lags))])
+end
+
+
+
+    acf=zeros(nChannels,nLags);
+    sampledacf = zeros(length(gridpoints),nChannels,nLags);
+    % create a runup buffer of signal
+    buffer= zeros(nChannels, max(lagPointers));
+
+inputSignalMatrix=[buffer inputSignalMatrix];
+[nChannels inputLength]= size(inputSignalMatrix);
+
+timeCounter=0; biggestSACF=0;
+gridcounter =1;
+for timePointer= max(lagPointers)+1:inputLength
+    % acf is a continuously changing channels x lags matrix
+    %   Only the current value is stored
+    % sacf is the vertical summary of acf ( a vector) and all values are kept and returned
+    % P is the smoothed version of sacf and all values are kept and returned
+    % lagWeights emphasise some BF/lag combinations and ignore others
+    % NB time now begins at the longest lag.
+    % E.g. if max(lags) is .04 then this is when the ACf will begin.
+    %            AN                                       AN delayed                             weights               filtering
+    
+    % This is the ACF calculation
+    timeCounter=timeCounter+1;
+    acf = (repmat(inputSignalMatrix(:, timePointer), 1, nLags) .* inputSignalMatrix(:, timePointer-lagPointers)).*lagWeights *dt + acf.* acfDecayFactors;
+    
+    %just sample on certain samplepoints
+    if ~isempty(find(timeCounter==gridpoints))
+        sampledacf(gridcounter,:,:)=acf;
+        gridcounter = gridcounter+1;
+    end
+    
+    end
+end
+
+
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsTim/sloga2iloga.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,169 @@
+function [iOut] = sloga2iloga(sIn, gVar)
+% string logatome to integer logatome
+% Bernd Meyer / Medical Physik  / University of Oldenburg
+% bernd.meyer@uni-oldenburg.de; March 2005
+
+if ~exist('gVar')
+  gVar.iVerboseFlag = 1;
+end
+
+sIn = strrep(sIn,' ','');
+
+switch sIn
+   case 'adda'; iOut =  001;
+   case 'atta'; iOut =  002;
+   case 'agga'; iOut =  003;
+   case 'acka'; iOut =  004;
+   case 'affa'; iOut =  005;
+   case 'assa'; iOut =  006;
+   case 'abba'; iOut =  007;
+   case 'appa'; iOut =  008;
+   case 'awwa'; iOut =  009;
+   case 'azza'; iOut =  010;
+   case 'amma'; iOut =  011;
+   case 'anna'; iOut =  012;
+   case 'ascha'; iOut = 013;
+   case 'alla'; iOut =  014;
+   case 'edde'; iOut =  015;
+   case 'ette'; iOut =  016;
+   case 'egge'; iOut =  017;
+   case 'ecke'; iOut =  018;
+   case 'effe'; iOut =  019;
+   case 'esse'; iOut =  020;
+   case 'ebbe'; iOut =  021;
+   case 'eppe'; iOut =  022;
+   case 'ewwe'; iOut =  023;
+   case 'ezze'; iOut =  024;
+   case 'emme'; iOut =  025;
+   case 'enne'; iOut =  026;
+   case 'esche'; iOut = 027;
+   case 'escha'; iOut = 027;
+   case 'elle'; iOut =  028;
+   case 'iddi'; iOut =  029;
+   case 'itti'; iOut =  030;
+   case 'iggi'; iOut =  031;
+   case 'icki'; iOut =  032;
+   case 'iffi'; iOut =  033;
+   case 'issi'; iOut =  034;
+   case 'ibbi'; iOut =  035;
+   case 'ippi'; iOut =  036;
+   case 'iwwi'; iOut =  037;
+   case 'izzi'; iOut =  038;
+   case 'immi'; iOut =  039;
+   case 'inni'; iOut =  040;
+   case 'ischi'; iOut = 041;
+   case 'illi'; iOut =  042;
+   case 'oddo'; iOut =  043;
+   case 'otto'; iOut =  044;
+   case 'oggo'; iOut =  045;
+   case 'ocko'; iOut =  046;
+   case 'offo'; iOut =  047;
+   case 'osso'; iOut =  048;
+   case 'obbo'; iOut =  049;
+   case 'oppo'; iOut =  050;
+   case 'owwo'; iOut =  051;
+   case 'ozzo'; iOut =  052;
+   case 'ommo'; iOut =  053;
+   case 'onno'; iOut =  054;
+   case 'oscho'; iOut = 055;
+   case 'ollo'; iOut =  056;
+   case 'uddu'; iOut =  057;
+   case 'uttu'; iOut =  058;
+   case 'uggu'; iOut =  059;
+   case 'ucku'; iOut =  060;
+   case 'uffu'; iOut =  061;
+   case 'ussu'; iOut =  062;
+   case 'ubbu'; iOut =  063;
+   case 'uppu'; iOut =  064;
+   case 'uwwu'; iOut =  065;
+   case 'uzzu'; iOut =  066;
+   case 'ummu'; iOut =  067;
+   case 'unnu'; iOut =  068;
+   case 'uschu'; iOut = 069;
+   case 'ullu'; iOut =  070;
+   case 'dadd'; iOut =  071;
+   case 'tatt'; iOut =  072;
+   case 'gagg'; iOut =  073;
+   case 'kakk'; iOut =  074;
+   case 'faff'; iOut =  075;
+   case 'sass'; iOut =  076;
+   case 'babb'; iOut =  077;
+   case 'papp'; iOut =  078;
+   case 'dedd'; iOut =  079;
+   case 'tett'; iOut =  080;
+   case 'gegg'; iOut =  081;
+   case 'kekk'; iOut =  082;
+   case 'feff'; iOut =  083;
+   case 'sess'; iOut =  084;
+   case 'bebb'; iOut =  085;
+   case 'pepp'; iOut =  086;
+   case 'didd'; iOut =  087;
+   case 'titt'; iOut =  088;
+   case 'gigg'; iOut =  089;
+   case 'kikk'; iOut =  090;
+   case 'fiff'; iOut =  091;
+   case 'siss'; iOut =  092;
+   case 'bibb'; iOut =  093;
+   case 'pipp'; iOut =  094;
+   case 'dodd'; iOut =  095;
+   case 'tott'; iOut =  096;
+   case 'gogg'; iOut =  097;
+   case 'kokk'; iOut =  098;
+   case 'foff'; iOut =  099;
+   case 'soss'; iOut =  100;
+   case 'bobb'; iOut =  101;
+   case 'popp'; iOut =  102;
+   case 'dudd'; iOut =  103;
+   case 'tutt'; iOut =  104;
+   case 'gugg'; iOut =  105;
+   case 'kukk'; iOut =  106;
+   case 'fuff'; iOut =  107;
+   case 'suss'; iOut =  108;
+   case 'bubb'; iOut =  109;
+   case 'pupp'; iOut =  110;
+   case 'dahd'; iOut =  111;
+   case 'taht'; iOut =  112;
+   case 'gahg'; iOut =  113;
+   case 'kahk'; iOut =  114;
+   case 'fahf'; iOut =  115;
+   case 'sahs'; iOut =  116;
+   case 'bahb'; iOut =  117;
+   case 'pahp'; iOut =  118;
+   case 'dehd'; iOut =  119;
+   case 'teht'; iOut =  120;
+   case 'gehg'; iOut =  121;
+   case 'kehk'; iOut =  122;
+   case 'fehf'; iOut =  123;
+   case 'sehs'; iOut =  124;
+   case 'behb'; iOut =  125;
+   case 'pehp'; iOut =  126;
+   case 'died'; iOut =  127;
+   case 'tiet'; iOut =  128;
+   case 'gieg'; iOut =  129;
+   case 'kiek'; iOut =  130;
+   case 'fief'; iOut =  131;
+   case 'sies'; iOut =  132;
+   case 'bieb'; iOut =  133;
+   case 'piep'; iOut =  134;
+   case 'dohd'; iOut =  135;
+   case 'toht'; iOut =  136;
+   case 'gohg'; iOut =  137;
+   case 'kohk'; iOut =  138;
+   case 'fohf'; iOut =  139;
+   case 'sohs'; iOut =  140;
+   case 'bohb'; iOut =  141;
+   case 'pohp'; iOut =  142;
+   case 'duhd'; iOut =  143;
+   case 'tuht'; iOut =  144;
+   case 'guhg'; iOut =  145;
+   case 'kuhk'; iOut =  146;
+   case 'fuhf'; iOut =  147;
+   case 'suhs'; iOut =  148;
+   case 'buhb'; iOut =  149;
+   case 'puhp'; iOut =  150;
+  otherwise
+      if gVar.iVerboseFlag
+        disp(['no logatome ' sIn ' found in list']);
+      end
+      iOut = -1;
+end % of switch
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsTim/speech_stimuli_check.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,168 @@
+%skript to test several stimuli with MAP1_14
+% Tim Juergens, September 2011
+
+%addpath('C:\Documents and Settings\tjurgens\My Documents\Dropbox\matlab');
+addpath('C:\MAP\userPrograms');
+parameterfile='Normal';
+
+%Read the wavfiles
+[da,sfreq] = wavread('..\wavFileStore\new-da-44khz.wav'); %artificial stimulus 
+ba = wavread('..\wavFileStore\new-ba-44khz.wav'); %artificial stimulus
+
+%set level of speech stimuli (RMS 1 equals 94 dB)
+da_69dB = da./sqrt(mean(da.^2)).*10^(-(94-69)/20);
+da_49dB = da./sqrt(mean(da.^2)).*10^(-(94-49)/20);
+ba_69dB = ba./sqrt(mean(ba.^2)).*10^(-(94-69)/20);
+%20*log10(sqrt(mean(ba_69dB.^2))/20e-6) %reference pressure: 20uPa
+
+
+cd ..
+cd MAP
+
+%MAP and store AN output of HSR fibers in variables
+MAP1_14(da_69dB,sfreq,-1,parameterfile,'probability');
+global ANprobRateOutput
+AN_da_69dB = ANprobRateOutput(1:size(ANprobRateOutput,1)/2,:);
+
+ MAP1_14(da_49dB,sfreq,-1,parameterfile,'probability');
+ global ANprobRateOutput
+ AN_da_49dB = ANprobRateOutput(1:size(ANprobRateOutput,1)/2,:);
+% 
+ MAP1_14(ba_69dB,sfreq,-1,parameterfile,'probability');
+ global ANprobRateOutput
+ global savedBFlist
+ AN_ba_69dB = ANprobRateOutput(1:size(ANprobRateOutput,1)/2,:);
+
+%Do the IPIH analysis
+ [iih_da_69dB,IPIhisttime_da_69dB,IPIhistweight_da_69dB] = track_formants_from_IPI_guy(AN_da_69dB,sfreq);
+ %[iih_da_69dB,IPIhisttime_da_69dB,IPIhistweight_da_69dB] = IPIHextract(AN_da_69dB,sfreq);
+ poolIPI_across_channels(IPIhisttime_da_69dB,IPIhistweight_da_69dB);
+ map_iih_onto_log(iih_da_69dB,30,sfreq);
+  [iih_da_49dB,IPIhisttime_da_49dB,IPIhistweight_da_49dB] = track_formants_from_IPI_guy(AN_da_49dB,sfreq);
+%  poolIPI_across_channels(IPIhisttime_da_49dB,IPIhistweight_da_49dB);
+%  
+  [iih_ba_69dB,IPIhisttime_ba_69dB,IPIhistweight_ba_69dB] = track_formants_from_IPI_guy(AN_ba_69dB,sfreq);
+%  [tmp,ctr]=poolIPI_across_channels(IPIhisttime_ba_69dB,IPIhistweight_ba_69dB);
+%  
+ 
+ 
+ 
+ %%%%%% OLLO stimuli %%%%%%%%%%%%%%%%%
+%  OLLOwavfiles = {'dahd','bahb','dehd','behb','died','bieb','dohd','bohb','duhd','buhb','atta','ascha','assa'};
+%  OLLO_level = 69; %level of OLLO files in dB SPL
+%  paramChanges = [];%{'DRNLParams.rateToAttenuationFactorProb = 0;'};
+%  
+% for iCounter = 1:length(OLLOwavfiles)
+%     
+%     %read the stimuli
+%     eval(['[' OLLOwavfiles{iCounter} ',sfreq_OLLO] = wavread([''..\wavFileStore\S02M_L' ...
+%         sprintf('%3.3i',sloga2iloga(OLLOwavfiles{iCounter})) '_V6_M1_N2_CS0.wav'']);'])
+%     
+%     %delete preceding and subsequent silence and resample to 44100 Hz
+%     %sampling frequency
+%     eval([OLLOwavfiles{iCounter} ' = cutsignal(' OLLOwavfiles{iCounter} ',sfreq_OLLO,''d_d'');']);
+%     eval([OLLOwavfiles{iCounter} ' = resample(' OLLOwavfiles{iCounter} ',sfreq,sfreq_OLLO);']);
+%     
+%     %set level
+%     partfilename = [OLLOwavfiles{iCounter} num2str(OLLO_level) 'dB'];
+%     eval([partfilename ' = ' OLLOwavfiles{iCounter} ...
+%         './sqrt(mean(' OLLOwavfiles{iCounter} '.^2)).*10^(-(94-' num2str(OLLO_level) ')/20);']);
+%     
+%     %use MAP
+%     eval(['MAP1_14(' partfilename ',sfreq,-1,parameterfile,''probability'', paramChanges );']);
+%     global ANprobRateOutput
+%     eval(['AN_' partfilename ' = ANprobRateOutput(1:size(ANprobRateOutput,1)/2,:);']);
+%     
+%     %Do the IPIH analysis
+%     eval(['[iih_' partfilename ',IPIhisttime_' partfilename ',IPIhistweight_' ...
+%         partfilename '] = track_formants_from_IPI_guy(AN_' partfilename ',sfreq);']);
+%     eval(['poolIPI_across_channels(IPIhisttime_' partfilename ',IPIhistweight_' partfilename ');']);
+%     title(partfilename);
+%     %set(gca,'Title',partfilename);
+%     xlabel('Interval (ms)')
+%     ylabel('Stimulus time (ms)');
+%     
+%     eval(['map_iih_onto_log(iih_' partfilename ',30,sfreq);']);
+%     title(partfilename);
+% end
+
+
+%%%%%%%%%%%%% OLLO stimuli from different speakers
+%  OLLOwavfiles = {'S01F_L111_V6_M1_N2_CS0.wav','S02M_L111_V6_M1_N2_CS0.wav'};
+%  OLLO_level = 69; %level of OLLO files in dB SPL
+% for iCounter = 1:length(OLLOwavfiles)
+%     
+%     partfilename = [OLLOwavfiles{iCounter}(1:end-4) num2str(OLLO_level) 'dB'];
+%     %read the stimuli
+%     eval(['[' partfilename ',sfreq_OLLO] = wavread([''..\wavFileStore\' OLLOwavfiles{iCounter} ''']);'])
+%     
+%     %delete preceding and subsequent silence and resample to 44100 Hz
+%     %sampling frequency
+%     eval([partfilename ' = cutsignal(' partfilename ',sfreq_OLLO,''d_d'');']);
+%     eval([partfilename ' = resample(' partfilename ',sfreq,sfreq_OLLO);']);
+%     
+%     %set level
+%     
+%     eval([partfilename ' = ' partfilename ...
+%         './sqrt(mean(' partfilename '.^2)).*10^(-(94-' num2str(OLLO_level) ')/20);']);
+%     
+%     %use MAP
+%     eval(['MAP1_14(' partfilename ',sfreq,-1,parameterfile,''probability'');']);
+%     global ANprobRateOutput
+%     eval(['AN_' partfilename ' = ANprobRateOutput(1:size(ANprobRateOutput,1)/2,:);']);
+%     
+%     %Do the IPIH analysis
+%     eval(['[iih_' partfilename ',IPIhisttime_' partfilename ',IPIhistweight_' ...
+%         partfilename '] = track_formants_from_IPI_guy(AN_' partfilename ',sfreq);']);
+%     eval(['poolIPI_across_channels(IPIhisttime_' partfilename ',IPIhistweight_' partfilename ');']);
+%     title(partfilename);
+%     %set(gca,'Title',partfilename);
+%     xlabel('Interval (ms)')
+%     ylabel('Stimulus time (ms)');
+%     
+%     eval(['map_iih_onto_log(iih_' partfilename ',30,sfreq);']);
+%     title(partfilename);
+% end
+
+
+
+%%%%%% da stimuli with different pitches %%%%%%%%%%%%%%%%%
+ 
+  dawavfiles = { '200ms_da_080Hz.wav','200ms_da_100Hz.wav','200ms_da_120Hz.wav','200ms_da_140Hz.wav', ... 
+      '200ms_da_160Hz.wav','200ms_da_180Hz.wav','200ms_da_200Hz.wav','200ms_da_220Hz.wav', ...
+      '200ms_da_240Hz.wav', ...
+      'noise.wav', ...
+      'da_whispered.wav', ...
+      };
+      
+ da_level = 69; %level of OLLO files in dB SPL
+for iCounter = 1:length(dawavfiles)
+    
+    %read the stimuli
+    partfilename = ['da' dawavfiles{iCounter}(1:end-4)];
+    eval([ partfilename ' = wavread(''..\wavFileStore\' dawavfiles{iCounter} ''');'])
+    
+    %set level
+    eval([partfilename ' = ' partfilename ...
+        './sqrt(mean(' partfilename '.^2)).*10^(-(94-' num2str(da_level) ')/20);']);
+    
+    %use MAP
+    eval(['MAP1_14(' partfilename ',sfreq,-1,parameterfile,''probability'');']);
+    global ANprobRateOutput
+    eval(['AN_' partfilename ' = ANprobRateOutput(1:size(ANprobRateOutput,1)/2,:);']);
+    
+    %Do the IPIH analysis
+    eval(['[iih_' partfilename ',IPIhisttime_' partfilename ',IPIhistweight_' ...
+            partfilename '] = IPIHextract(AN_' partfilename ',sfreq);']);%partfilename '] = track_formants_from_IPI_guy(AN_' partfilename ',sfreq);']);%
+    eval(['poolIPI_across_channels(IPIhisttime_' partfilename ',IPIhistweight_' partfilename ');']);
+    title(partfilename);
+    %set(gca,'Title',partfilename);
+    xlabel('Interval (ms)')
+    ylabel('Stimulus time (ms)');
+    
+    eval(['map_iih_onto_log(iih_' partfilename ',30,sfreq);']);
+    title(partfilename);
+end
+% 
+% 
+
Binary file userProgramsTim/speechmanipulation.fig has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsTim/speechmanipulation.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,714 @@
+function varargout = speechmanipulation(varargin)
+% SPEECHMANIPULATION MATLAB code for speechmanipulation.fig
+%      SPEECHMANIPULATION, by itself, creates a new SPEECHMANIPULATION or raises the existing
+%      singleton*.
+%
+%      H = SPEECHMANIPULATION returns the handle to a new SPEECHMANIPULATION or the handle to
+%      the existing singleton*.
+%
+%      SPEECHMANIPULATION('CALLBACK',hObject,eventData,handles,...) calls the local
+%      function named CALLBACK in SPEECHMANIPULATION.M with the given input arguments.
+%
+%      SPEECHMANIPULATION('Property','Value',...) creates a new SPEECHMANIPULATION or raises the
+%      existing singleton*.  Starting from the left, property value pairs are
+%      applied to the GUI before speechmanipulation_OpeningFcn gets called.  An
+%      unrecognized property name or invalid value makes property application
+%      stop.  All inputs are passed to speechmanipulation_OpeningFcn via varargin.
+%
+%      *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 speechmanipulation
+
+% Last Modified by GUIDE v2.5 05-Oct-2011 11:21:58
+
+% Begin initialization code - DO NOT EDIT
+gui_Singleton = 1;
+gui_State = struct('gui_Name',       mfilename, ...
+                   'gui_Singleton',  gui_Singleton, ...
+                   'gui_OpeningFcn', @speechmanipulation_OpeningFcn, ...
+                   'gui_OutputFcn',  @speechmanipulation_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 speechmanipulation is made visible.
+function speechmanipulation_OpeningFcn(hObject, eventdata, handles, varargin)
+% This function has no output args, see OutputFcn.
+% hObject    handle to figure
+% eventdata  reserved - to be defined in a future version of MATLAB
+% handles    structure with handles and user data (see GUIDATA)
+% varargin   command line arguments to speechmanipulation (see VARARGIN)
+global wavfilescell;
+global rateaxeshandle; %handle to axis6 is needed, if radiobuttons12 and 13 change
+
+
+% Choose default command line output for speechmanipulation
+handles.output = hObject;
+
+% Update handles structure
+guidata(hObject, handles);
+
+% UIWAIT makes speechmanipulation wait for user response (see UIRESUME)
+% uiwait(handles.figure1);
+wavfiles = dir(['..' filesep 'wavFileStore' filesep '*.wav']);
+for iCounter = 1:length(wavfiles)
+    wavfilescell{iCounter} = wavfiles(iCounter).name;
+end
+set(handles.popupmenu1,'String',wavfilescell);
+set(handles.popupmenu2,'String',wavfilescell);
+set(handles.uipanel8,'SelectionChangeFcn',@radiobuttonselected);
+rateaxeshandle = handles.axes6;
+
+% --- Outputs from this function are returned to the command line.
+function varargout = speechmanipulation_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;
+
+function edit1_Callback(hObject, eventdata, handles)
+function edit2_Callback(hObject, eventdata, handles)
+function edit3_Callback(hObject, eventdata, handles)
+function edit4_Callback(hObject, eventdata, handles)
+function edit5_Callback(hObject, eventdata, handles)
+function edit6_Callback(hObject, eventdata, handles)
+function edit7_Callback(hObject, eventdata, handles)
+function edit8_Callback(hObject, eventdata, handles)
+function edit9_Callback(hObject, eventdata, handles)
+function edit10_Callback(hObject, eventdata, handles)
+function edit11_Callback(hObject, eventdata, handles)
+function edit12_Callback(hObject, eventdata, handles)
+
+
+% --- Executes on selection change in popupmenu1.
+function popupmenu1_Callback(hObject, eventdata, handles)
+% hObject    handle to popupmenu1 (see GCBO)
+% eventdata  reserved - to be defined in a future version of MATLAB
+% handles    structure with handles and user data (see GUIDATA)
+
+% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu1 contents as cell array
+%        contents{get(hObject,'Value')} returns selected item from popupmenu1
+%% CHOOSE AND LOAD WAVEFORM
+global wavfilescell
+global originalsignal
+global actualsignal
+
+%get the number from the popupmenu
+selectedfileno = get(handles.popupmenu1,'Value');
+
+%load it
+[waveform,sfreq] = wavread(['..' filesep 'wavFileStore' filesep wavfilescell{selectedfileno}]);
+
+%if it is from OLLO then cut it
+if regexp(wavfilescell{selectedfileno}, 'S[0-9]*[A-Z]_L[0-9]*_V[0-9]_M[0-9]_N[0-9]_CS0.wav') %pattern for OLLO-files
+    waveform = cutsignal(waveform,sfreq,'a_a');
+end
+
+%store it in global variables
+actualsignal.waveform = waveform;
+actualsignal.sfreq = sfreq;
+originalsignal.waveform = waveform;
+originalsignal.sfreq = sfreq;
+
+%plot it
+multipleplot(actualsignal,handles);
+
+% --- Executes during object creation, after setting all properties.
+function popupmenu1_CreateFcn(hObject, eventdata, handles)
+% hObject    handle to popupmenu1 (see GCBO)
+% eventdata  reserved - to be defined in a future version of MATLAB
+% handles    empty - handles not created until after all CreateFcns called
+
+% Hint: popupmenu controls usually have a white background on Windows.
+%       See ISPC and COMPUTER.
+if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
+    set(hObject,'BackgroundColor','white');
+end
+
+
+% --- Executes on button press in pushbutton1.
+function pushbutton1_Callback(hObject, eventdata, handles)
+% hObject    handle to pushbutton1 (see GCBO)
+% eventdata  reserved - to be defined in a future version of MATLAB
+% handles    structure with handles and user data (see GUIDATA)
+%% LOAD WAVEFORM
+global wavfilescell
+global originalsignal
+global actualsignal
+
+%get the number from the popupmenu
+selectedfileno = get(handles.popupmenu1,'Value');
+
+%load it
+[waveform,sfreq] = wavread(['..' filesep 'wavFileStore' filesep wavfilescell{selectedfileno}]);
+
+%if it is from OLLO then cut it
+if regexp(wavfilescell{selectedfileno}, 'S[0-9]*[A-Z]_L[0-9]*_V[0-9]_M[0-9]_N[0-9]_CS0.wav') %pattern for OLLO-files
+    waveform = cutsignal(waveform,sfreq,'a_a');
+end
+
+%store it in global variables
+actualsignal.waveform = waveform;
+actualsignal.sfreq = sfreq;
+originalsignal.waveform = waveform;
+originalsignal.sfreq = sfreq;
+
+%plot it
+multipleplot(actualsignal,handles)
+
+
+% --- Executes during object creation, after setting all properties.
+function edit1_CreateFcn(hObject, eventdata, handles)
+% hObject    handle to edit1 (see GCBO)
+% eventdata  reserved - to be defined in a future version of MATLAB
+% handles    empty - handles not created until after all CreateFcns called
+
+% Hint: edit controls usually have a white background on Windows.
+%       See ISPC and COMPUTER.
+if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
+    set(hObject,'BackgroundColor','white');
+end
+
+
+% --- Executes on button press in pushbutton2.
+function pushbutton2_Callback(hObject, eventdata, handles)
+% hObject    handle to pushbutton2 (see GCBO)
+% eventdata  reserved - to be defined in a future version of MATLAB
+% handles    structure with handles and user data (see GUIDATA)
+%% PLAY THE ACTUAL (MANIPULATED) SIGNAL
+global actualsignal
+global toplay
+
+toplay = audioplayer(actualsignal.waveform,actualsignal.sfreq);
+play(toplay);
+
+
+% --- Executes on button press in pushbutton3.
+function pushbutton3_Callback(hObject, eventdata, handles)
+% hObject    handle to pushbutton3 (see GCBO)
+% eventdata  reserved - to be defined in a future version of MATLAB
+% handles    structure with handles and user data (see GUIDATA)
+
+%% MANIPULATE SIGNAL
+global wavfilescell
+global originalsignal
+global actualsignal
+
+actualsignal = originalsignal; %reset
+
+%% speed factor change
+speedfactor = str2num(get(handles.edit1,'String'));
+newfakesfreq=actualsignal.sfreq*speedfactor;
+if speedfactor == 1
+else
+    actualsignal.waveform = resample(actualsignal.waveform,actualsignal.sfreq,newfakesfreq);
+end
+
+%% low and high pass filter (butterworth)
+% get the desired filter from radio buttons
+radiofilterhandles=get(handles.uipanel2,'Children');
+for iCounter = 1:length(radiofilterhandles)
+    if get(radiofilterhandles(iCounter),'Value') == 1
+        filtertype = get(radiofilterhandles(iCounter),'String');
+    end
+end
+% read parameters
+tmp = get(handles.edit3,'String');
+cutofffreq=str2num(tmp{1});
+tmp = get(handles.edit4,'String');
+filterorder=str2num(tmp{1});
+%do the filter calculations
+switch filtertype
+    case 'none'
+    case 'High pass'
+        if isempty(cutofffreq) || isempty(filterorder)
+            error('Please specify cutoff frequency and/or filter order')
+        else
+            [a,b] = butter(filterorder,cutofffreq*2/actualsignal.sfreq,'high');
+            actualsignal.waveform=filter(a,b,actualsignal.waveform);
+        end
+    case 'Low pass'
+        if isempty(cutofffreq)|| isempty(filterorder)
+            error('Please specify cutoff frequency')
+        else
+            [a,b] = butter(filterorder,cutofffreq*2/actualsignal.sfreq,'low');
+            actualsignal.waveform=filter(a,b,actualsignal.waveform);
+        end
+end
+
+%additive noise
+% get the desired filter from radio buttons
+radionoisehandles=get(handles.uipanel4,'Children');
+for iCounter = 1:length(radionoisehandles)
+    if get(radionoisehandles(iCounter),'Value') == 1
+        noisetype = get(radionoisehandles(iCounter),'String');
+    end
+end      
+% read parameters
+tmp = get(handles.edit5,'String');
+snr=str2num(tmp{1});
+%do the noise calculations
+switch noisetype
+    case 'none'
+    case 'White noise'
+        if isempty(snr) 
+            error('Please specify SNR')
+        else
+            whitenoise = rand(length(actualsignal.waveform),1)-0.5;
+            %set level
+            levelsignal = 20*log10(sqrt(mean(actualsignal.waveform.^2)));
+            levelnoise = levelsignal-snr;
+            whitenoise = whitenoise./sqrt(mean(whitenoise.^2)).*10^(levelnoise/20);
+            %20*log10(sqrt(mean(whitenoise.^2)))
+            actualsignal.waveform=actualsignal.waveform+whitenoise;
+        end
+    case 'From file'
+        if isempty(snr) 
+            error('Please specify SNR')
+        else
+            selectedfileno = get(handles.popupmenu2,'Value');
+
+            [noisewaveform,noisesfreq] = wavread(['..' filesep 'wavFileStore' filesep wavfilescell{selectedfileno}]);
+            if noisesfreq == actualsignal.sfreq
+            else
+                noisewaveform = resample(noisewaveform,actualsignal.sfreq,noisesfreq);
+                noisesfreq = actualsignal.sfreq;
+            end
+            if length(noisewaveform) < length(actualsignal.waveform)
+                warning('Noise waveform too short. Noise is looped without fading at the endings!');
+                noisewaveform = repmat(noisewaveform, ceil(length(actualsignal.waveform)/length(noisewaveform)),1);
+            end
+            noisewaveform=noisewaveform(1:length(actualsignal.waveform));
+            %set level
+            levelsignal = 20*log10(sqrt(mean(actualsignal.waveform.^2)));
+            levelnoise = levelsignal-snr;
+            noisewaveform = noisewaveform./sqrt(mean(noisewaveform.^2)).*10^(levelnoise/20);
+            %20*log10(sqrt(mean(noisewaveform.^2)))
+            %finally add the two signals
+            actualsignal.waveform = actualsignal.waveform + noisewaveform;
+        end
+end
+
+%plot the resulting manipulated waveform
+multipleplot(actualsignal,handles);
+
+% --- Executes during object creation, after setting all properties.
+function edit3_CreateFcn(hObject, eventdata, handles)
+% hObject    handle to edit3 (see GCBO)
+% eventdata  reserved - to be defined in a future version of MATLAB
+% handles    empty - handles not created until after all CreateFcns called
+
+% Hint: edit controls usually have a white background on Windows.
+%       See ISPC and COMPUTER.
+if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
+    set(hObject,'BackgroundColor','white');
+end
+
+
+% --- Executes during object creation, after setting all properties.
+function edit4_CreateFcn(hObject, eventdata, handles)
+% hObject    handle to edit4 (see GCBO)
+% eventdata  reserved - to be defined in a future version of MATLAB
+% handles    empty - handles not created until after all CreateFcns called
+
+% Hint: edit controls usually have a white background on Windows.
+%       See ISPC and COMPUTER.
+if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
+    set(hObject,'BackgroundColor','white');
+end
+
+
+% --- Executes during object creation, after setting all properties.
+function edit5_CreateFcn(hObject, eventdata, handles)
+% hObject    handle to edit5 (see GCBO)
+% eventdata  reserved - to be defined in a future version of MATLAB
+% handles    empty - handles not created until after all CreateFcns called
+
+% Hint: edit controls usually have a white background on Windows.
+%       See ISPC and COMPUTER.
+if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
+    set(hObject,'BackgroundColor','white');
+end
+
+
+% --- Executes during object creation, after setting all properties.
+function popupmenu2_CreateFcn(hObject, eventdata, handles)
+% hObject    handle to popupmenu2 (see GCBO)
+% eventdata  reserved - to be defined in a future version of MATLAB
+% handles    empty - handles not created until after all CreateFcns called
+
+% Hint: popupmenu controls usually have a white background on Windows.
+%       See ISPC and COMPUTER.
+if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
+    set(hObject,'BackgroundColor','white');
+end
+
+
+% --- Executes on button press in pushbutton4.
+function pushbutton4_Callback(hObject, eventdata, handles)
+% hObject    handle to pushbutton4 (see GCBO)
+% eventdata  reserved - to be defined in a future version of MATLAB
+% handles    structure with handles and user data (see GUIDATA)
+%% PLAY THE ORIGINAL WAVEFORM
+global originalsignal
+global toplay
+toplay = audioplayer(originalsignal.waveform,originalsignal.sfreq);
+play(toplay)
+
+
+% --- Executes on button press in pushbutton5.
+function pushbutton5_Callback(hObject, eventdata, handles)
+% hObject    handle to pushbutton5 (see GCBO)
+% eventdata  reserved - to be defined in a future version of MATLAB
+% handles    structure with handles and user data (see GUIDATA)
+global toplay
+stop(toplay);
+
+
+function edit6_Callback(hObject, eventdata, handles)
+% hObject    handle to edit6 (see GCBO)
+% eventdata  reserved - to be defined in a future version of MATLAB
+% handles    structure with handles and user data (see GUIDATA)
+
+% Hints: get(hObject,'String') returns contents of edit6 as text
+%        str2double(get(hObject,'String')) returns contents of edit6 as a double
+
+
+% --- Executes during object creation, after setting all properties.
+function edit6_CreateFcn(hObject, eventdata, handles)
+% hObject    handle to edit6 (see GCBO)
+% eventdata  reserved - to be defined in a future version of MATLAB
+% handles    empty - handles not created until after all CreateFcns called
+
+% Hint: edit controls usually have a white background on Windows.
+%       See ISPC and COMPUTER.
+if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
+    set(hObject,'BackgroundColor','white');
+end
+
+% --- Executes during object creation, after setting all properties.
+function edit7_CreateFcn(hObject, eventdata, handles)
+% hObject    handle to edit7 (see GCBO)
+% eventdata  reserved - to be defined in a future version of MATLAB
+% handles    empty - handles not created until after all CreateFcns called
+
+% Hint: edit controls usually have a white background on Windows.
+%       See ISPC and COMPUTER.
+if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
+    set(hObject,'BackgroundColor','white');
+end
+
+
+% --- Executes during object creation, after setting all properties.
+function edit8_CreateFcn(hObject, eventdata, handles)
+% hObject    handle to edit8 (see GCBO)
+% eventdata  reserved - to be defined in a future version of MATLAB
+% handles    empty - handles not created until after all CreateFcns called
+
+% Hint: edit controls usually have a white background on Windows.
+%       See ISPC and COMPUTER.
+if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
+    set(hObject,'BackgroundColor','white');
+end
+
+
+% --- Executes on button press in pushbutton6.
+function pushbutton6_Callback(hObject, eventdata, handles)
+% hObject    handle to pushbutton6 (see GCBO)
+% eventdata  reserved - to be defined in a future version of MATLAB
+% handles    structure with handles and user data (see GUIDATA)
+
+%% CALCULATE MAP 1.14 auditory nerve probability output
+addpath(['..' filesep 'MAP']);
+addpath(['..' filesep 'utilities']);
+global actualsignal
+global AN_HSRoutput
+
+tmp = get(handles.edit6,'String');
+level4MAP=str2num(tmp);
+if isempty(level4MAP)
+    error('Please specify level');
+end
+
+tmp = get(handles.edit7,'String');
+parameterfile=tmp;
+if isempty(parameterfile)
+    error('Please specify parameter file');
+end
+
+% identify model parameter changes if any
+paramChanges=get(handles.edit8,'string');
+if ~strcmp(paramChanges, ';'), paramChanges=[paramChanges ';']; end
+eval(paramChanges);
+
+%set level
+actualsignal.waveform = actualsignal.waveform./sqrt(mean(actualsignal.waveform.^2)).*10^(-(94-level4MAP)/20);
+%20*log10(sqrt(mean(actualsignal.waveform.^2))/20e-6) %reference pressure: 20uPa
+
+MAP1_14(actualsignal.waveform,actualsignal.sfreq,-1,parameterfile, ...
+    'probability',paramChanges);
+global ANprobRateOutput savedBFlist
+
+%take only the HSR fibers
+AN_HSRoutput = ANprobRateOutput(size(ANprobRateOutput)/2+1:end,:);
+
+%plot the auditory nerve firing probability as line plot
+start_time = size(AN_HSRoutput,2)/2/actualsignal.sfreq-0.025; %start time to plot in s
+end_time = start_time+0.05; %plot 50ms
+plotIFRAN(AN_HSRoutput,start_time,end_time,actualsignal.sfreq,savedBFlist,handles.axes4);
+set(handles.edit11,'String',num2str(1000*size(AN_HSRoutput,2)/2/actualsignal.sfreq));
+
+%plot the fourierhistogram as image plot
+formantpattern = fourierautocorrelationhistogram_direct(AN_HSRoutput,actualsignal.sfreq,handles.axes5);
+caxis([0 2000]);
+colorbar;
+
+%plot the rate output
+plotrateOutput(AN_HSRoutput,actualsignal.sfreq,handles.axes6,[33.7 300]);
+set(handles.radiobutton12,'Value',1);
+
+%calculate the IPIH
+ipih=track_formants_from_IPI_guy(AN_HSRoutput, actualsignal.sfreq);
+%the following code assumes that the bin width is 1/actualsignal.sfreq and 
+%the temporal step size is 3ms
+
+ipihfreqaxis=1./[1/actualsignal.sfreq:1/actualsignal.sfreq:size(ipih,1)/actualsignal.sfreq];
+ipihtimeaxis=[0:3:size(ipih,2)*3];
+set(gcf,'CurrentAxes',handles.axes7);
+YTickIdx = 1:floor(numel(ipihfreqaxis)/6):numel(ipihfreqaxis);
+XTickIdx = 1:floor(numel(ipihtimeaxis)/6):numel(ipihtimeaxis);
+imagesc(ipih);
+set(gca, 'YTick', YTickIdx);
+set(gca, 'YTickLabel', num2str(  ipihfreqaxis(YTickIdx)', '%0.0f' ));
+ylabel('best frequency (Hz)')
+set(gca, 'XTick', XTickIdx);
+set(gca, 'XTickLabel', XTickIdx.*3);
+xlabel('Time (ms)');
+caxis([0 8e4]); %set color 
+colorbar;
+
+%calculate and plot summarized autocorrelation, code from Ray
+method.dt=1/actualsignal.sfreq;
+method.segmentNo=1;
+method.nonlinCF=savedBFlist;
+
+minPitch=	80; maxPitch=	4000; numPitches=100;    % specify lags
+pitches=10.^ linspace(log10(minPitch), log10(maxPitch),numPitches);
+pitches=fliplr(pitches);
+filteredSACFParams.lags=1./pitches;     % autocorrelation lags vector
+filteredSACFParams.acfTau=	.003;       % time constant of running ACF
+filteredSACFParams.lambda=	0.12;       % slower filter to smooth ACF
+filteredSACFParams.lambda=	0.01;       % slower filter to smooth ACF
+
+filteredSACFParams.plotACFs=0;          % special plot (see code)
+filteredSACFParams.plotFilteredSACF=0;  % 0 plots unfiltered ACFs
+filteredSACFParams.plotMoviePauses=.5;%.3          % special plot (see code)
+
+filteredSACFParams.usePressnitzer=0; % attenuates ACF at  long lags
+filteredSACFParams.lagsProcedure=  'useAllLags';
+filteredSACFParams.criterionForOmittingLags=3;
+filteredSACFParams.plotACFsInterval=50;%200;
+
+% compute ACF
+%switch saveAN_spikesOrProbability
+%    case 'probability'
+        inputToACF=ANprobRateOutput.^0.5;
+%    otherwise
+%        inputToACF=ANoutput;
+%end
+
+disp ('computing ACF...')
+t=method.dt*(1:length(actualsignal.waveform));
+[P, BFlist, sacf, boundaryValue] = ...
+    filteredSACF(inputToACF, method, filteredSACFParams);
+P = real(P); %dont know why sometimes P can be (very slightly) complex
+disp(' ACF done.')
+
+% SACF
+set(gcf,'CurrentAxes',handles.axes8);
+imagesc(P)
+ylabel('periodicities (Hz)')
+xlabel('time (s)')
+%title(['running smoothed (root) SACF. ' saveAN_spikesOrProbability ' input'])
+pt=[1 get(gca,'ytick')]; % force top xtick to show
+set(gca,'ytick',pt)
+set(gca,'ytickLabel', round(pitches(pt)))
+tt=get(gca,'xtick');
+tt=tt(tt<length(t));
+set(gca,'xtickLabel', round(100*t(tt))/100)
+colorbar;
+
+% --- Executes on button press in pushbutton7.
+function pushbutton7_Callback(hObject, eventdata, handles)
+% hObject    handle to pushbutton7 (see GCBO)
+% eventdata  reserved - to be defined in a future version of MATLAB
+% handles    structure with handles and user data (see GUIDATA)
+
+%% SHOW THE  (PREVIOUSLY STORED) AUDITORY PROFILE CORRESPONDING TO THE
+%% PARAMETER FILE
+addpath(['..' filesep 'multithreshold 1.46' filesep]);
+% read the parameter file
+tmp = get(handles.edit7,'String');
+parameterfile=tmp;
+if isempty(parameterfile)
+    error('Please specify parameter file');
+end
+
+%what kind of profiles are in the profiles directory?
+files_in_profiles = dir(['..' filesep 'profiles' filesep '*.m']);%if exist('',file)
+done = 0;
+
+%try to map the specified parameter file to these found in the directory
+%and
+for iCounter = 1:length(files_in_profiles)
+    if strfind(files_in_profiles(iCounter).name,parameterfile)
+        %ask the user if this is the correct file - because you'll never
+        %know ;)
+        stringtoask = ['Is ' files_in_profiles(iCounter).name ' the correct profile file?'];
+        Answer = questdlg(stringtoask,'Possible match found','Yes','No','Yes');
+        switch Answer,
+            case 'Yes'
+                plotprofile(files_in_profiles(iCounter).name(1:end-2),'profile_CMA_L');
+                done = 1;
+            case 'No'
+        end %switch
+    end %if
+end
+if ~done
+    msgbox('No match for this parameter file found.');
+end
+
+function multipleplot(actualsignal,handles)
+%% FUNCTION TO DO 3 PLOTS
+time_axis = [0:1/actualsignal.sfreq:(length(actualsignal.waveform)-1)/actualsignal.sfreq];
+
+%waveform plot (temporal)
+plot(handles.axes1,time_axis,actualsignal.waveform);
+set(get(handles.axes1,'XLabel'),'String','Time (s)');
+set(get(handles.axes1,'YLabel'),'String','Amplitude');
+set(handles.axes1,'XLim',[0 length(actualsignal.waveform)/actualsignal.sfreq]);
+highestabsampl = max(abs(actualsignal.waveform))*1.05;
+set(handles.axes1,'YLim',[-highestabsampl highestabsampl]);
+
+%average spectrum plot
+complspectrum = fft(actualsignal.waveform)/(length(actualsignal.waveform));
+frequency = [0:1/time_axis(end):1/(2*(time_axis(2)-time_axis(1)))];
+plot(handles.axes2,frequency,20*log10(sqrt(2)*abs(complspectrum(1:round(length(complspectrum)/2)))));
+set(get(handles.axes2,'XLabel'),'String','frequency (Hz)');
+set(get(handles.axes2,'YLabel'),'String','fourier amplitude (dB)');
+set(handles.axes2,'XLim',[100 10000]);
+set(handles.axes2,'XScale','log');
+
+%spectrogram plot (10 ms temporal resolution)
+[s,f,t] = spectrogram(actualsignal.waveform,hann(round(0.01*actualsignal.sfreq)),[],[],actualsignal.sfreq); %10ms short term windows
+set(gcf,'CurrentAxes',handles.axes3);
+if max(f)>10000
+    [tmp,idx] = min(abs(f-10000));
+    imagesc(t,f(1:idx),20*log10(abs(s(1:idx,:))));
+else
+    imagesc(t,f,20*log10(abs(s)));
+end
+axis xy;
+set(get(handles.axes3,'YLabel'),'String','frequency (Hz)');
+set(get(handles.axes3,'XLabel'),'String','Time (s)');
+
+
+function plotrateOutput(ratepattern,sfreq,axeshandle,colorrange)
+%% calculate rate representation and plot, code from Nick
+global savedBFlist
+%calculate rate representation
+ANsmooth = [];%Cannot pre-allocate a size as it is unknown until the enframing
+hopSize = 10; %ms
+winSize = 25; %ms
+winSizeSamples = round(winSize*sfreq/1000);
+hann = hanning(winSizeSamples);
+hopSizeSamples = round(hopSize*sfreq/1000);
+for chan = 1:size(ratepattern,1)
+    f = enframe(ratepattern(chan,:), hann, hopSizeSamples);
+    ANsmooth(chan,:) = mean(f,2)';
+end
+
+%plot rate representation
+time_axis_rate=[0:hopSize/1000:size(ratepattern,2)/sfreq];
+set(gcf,'CurrentAxes',axeshandle);
+YTickIdx = 1:floor(numel(savedBFlist)/6):numel(savedBFlist);
+XTickIdx = 1:floor(numel(time_axis_rate)/6):numel(time_axis_rate);
+imagesc(ANsmooth);
+axis xy;
+set(gca, 'YTick', YTickIdx);
+set(gca, 'YTickLabel', num2str(  savedBFlist(YTickIdx)', '%0.0f' ));
+ylabel('best frequency (Hz)')
+set(gca, 'XTick', XTickIdx);
+set(gca, 'XTickLabel', XTickIdx.*10);
+xlabel('Time (ms)');
+caxis(colorrange); %set color from average spontaneous rate to a maximum of 600
+colorbar;
+
+
+% --- Executes if the radiobuttons hsr and lsr are changed
+function radiobuttonselected(source, eventdata)
+
+global rateaxeshandle
+global ANprobRateOutput
+global actualsignal
+
+selected = get(get(source,'SelectedObject'),'String');
+
+if isempty(ANprobRateOutput)
+    msgbox('Please calculate AN pattern first!');
+elseif strcmp(selected,'HSR')
+    AN_HSRoutput = ANprobRateOutput(size(ANprobRateOutput)/2+1:end,:);
+    colorrange = [33.7 300];
+    plotrateOutput(AN_HSRoutput,actualsignal.sfreq,rateaxeshandle,colorrange);
+else
+    AN_LSRoutput = ANprobRateOutput(1:size(ANprobRateOutput)/2,:);
+    colorrange = [10.7 100];
+    plotrateOutput(AN_LSRoutput,actualsignal.sfreq,rateaxeshandle,colorrange);
+end
+
+
+% --- Executes during object creation, after setting all properties.
+function edit11_CreateFcn(hObject, eventdata, handles)
+% hObject    handle to edit11 (see GCBO)
+% eventdata  reserved - to be defined in a future version of MATLAB
+% handles    empty - handles not created until after all CreateFcns called
+
+% Hint: edit controls usually have a white background on Windows.
+%       See ISPC and COMPUTER.
+if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
+    set(hObject,'BackgroundColor','white');
+end
+
+
+% --- Executes on button press in pushbutton8.
+function pushbutton8_Callback(hObject, eventdata, handles)
+% hObject    handle to pushbutton8 (see GCBO)
+% eventdata  reserved - to be defined in a future version of MATLAB
+% handles    structure with handles and user data (see GUIDATA)
+%plot the auditory nerve firing probability as line plot after grabbing the
+%time value from edit11
+global AN_HSRoutput
+global actualsignal
+global savedBFlist
+
+middletime = str2num(get(handles.edit11,'String'))/1000;
+
+start_time = min([size(AN_HSRoutput,2)/actualsignal.sfreq-0.01 max([0 middletime-0.025])]); %start time to plot in s
+end_time = max([start_time+0.01 min([start_time+0.05 size(AN_HSRoutput,2)/actualsignal.sfreq-0.01])]); %plot max 50ms
+plotIFRAN(AN_HSRoutput,start_time,end_time,actualsignal.sfreq,savedBFlist,handles.axes4);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsTim/test_autocorr.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,14 @@
+addpath('..\utilities');
+addpath('..\MAP')
+
+%% delare 'showMap' options to control graphical output
+showMapOptions.printModelParameters=1;   % prints all parameters
+showMapOptions.showModelOutput=1;       % plot of all stages
+showMapOptions.printFiringRates=1;      % prints stage activity levels
+showMapOptions.showACF=1;               % shows SACF (probability only)
+showMapOptions.showEfferent=1;          % tracks of AR and MOC
+showMapOptions.surfProbability=1;       % 2D plot of HSR response 
+showMapOptions.surfSpikes=1;            % 2D plot of spikes histogram
+showMapOptions.ICrates=0;               % IC rates by CNtauGk
+
+UTIL_showMAP(showMapOptions, {})
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsTim/track_formants_from_IPI_guy.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,182 @@
+function [iih,IPIhisttime,IPIhistweight]=track_formants_from_IPI_guy(IFRAN_pattern, sfreq)
+% 
+% tracks the formants according to an analysis proposed in Secker-Walker
+% JASA 1990, section V.A
+% Tim Jürgens, February 2011, code from Guy Brown included
+% 
+% input:  IFRAN_pattern: pattern of the auditory model (dependend on the number of modules used)
+%                        first dimension: frequency channel, 
+%                        second dimension: time (samples)
+%         sfreq:         sampling frequency
+% output: iih:           interpeak-interval histogram, matrix very similar
+%                        the plot 5 in the Secker-Walker paper
+%
+%
+%
+
+
+time_axis = 0:1/sfreq:(size(IFRAN_pattern,2)-1)/sfreq;
+
+%find how many samples of AN_pattern are 10ms and 3ms
+%one_sample_is_a_time_of = time_axis(2);
+[tmp, start_time_index] = min(abs(0-time_axis));
+[tmp, stop10_time_index] = min(abs(0.01-time_axis));
+number_of_samples10ms = stop10_time_index - start_time_index;
+
+[tmp, stop3_time_index] = min(abs(0.003-time_axis));
+number_of_samples3ms = stop3_time_index - start_time_index;
+every_3ms = 1:number_of_samples3ms:size(IFRAN_pattern,2)-number_of_samples10ms;
+
+hamm_window = hamming(11);
+halfHamming = (length(hamm_window)-1)/2;
+
+% window normalization
+
+norm = conv(ones(1,floor(number_of_samples10ms/2)),hamm_window);
+norm = norm(5+1:end-5)';
+win_size = number_of_samples10ms;
+half_win_size = floor(win_size/2);
+hop_size = number_of_samples3ms;
+
+
+%pre-allocation due to speed
+%Acorr = zeros(size(IFRAN_pattern,1),size(every_3ms,2),number_of_samples10ms*2+1);
+%RAcorr = zeros(size(IFRAN_pattern,1),size(every_3ms,2),number_of_samples10ms*2+1);
+%SRAcorr = zeros(size(IFRAN_pattern,1),size(every_3ms,2),number_of_samples10ms*2+1-10);
+IPIhisttime = zeros(size(IFRAN_pattern,1),size(every_3ms,2),3);
+IPIhistweight = zeros(size(IFRAN_pattern,1),size(every_3ms,2),3);  %maximum 3 peaks from the SRA
+iih = zeros(half_win_size,size(every_3ms,2)+1);
+
+
+
+
+for iCounter = 1:size(IFRAN_pattern,1) %each channel
+    fprintf('Channel No. %i\n',iCounter);
+    %time_counter = 1;
+    %for jCounter = every_3ms %every 3ms time segment
+    
+    
+    
+    %% Guy's code
+    % enframe this signal
+    
+    frames = enframe(IFRAN_pattern(iCounter,:),win_size,hop_size);
+    
+    % compute the autocorrelation
+    
+    acf = real(ifft(abs(fft(frames,[],2)).^2,[],2));
+    acf(acf<0)=0;
+    acf = sqrt(acf(:,1:half_win_size));
+    
+    % smooth with hamming window and take the root
+    
+    for frame=1:size(acf,1)
+        
+        %%debug
+        %if iCounter == 130
+        %    disp('here');
+        %end
+        
+        
+        sra = conv(acf(frame,:),hamm_window);
+        sra = sra(halfHamming+1:end-halfHamming)./norm';
+        df = [0 ; diff(sra')];
+        idx = find((df(1:end-1)>=0)&(df(2:end)<0));
+        % interpolate
+        a=df(idx);
+        b=df(idx+1);
+        idx = (idx-1+a./(a-b));
+        % get rid of a zero peak, if it exists
+        idx = idx(idx>1);
+        % peak values corresponding to these intervals
+        amp = interp1(1:length(sra),sra,idx,'linear');
+        % if required, remove peaks that lie below the mean sra
+        % note that we disregard the value at zero delay
+        %if (params.removePeaksBelowMean)
+        valid = find(amp>mean(sra(2:end)));
+        idx = idx(valid);
+        amp = amp(valid);
+        %end
+        % only use the first four peaks (three intervals)
+        idx = idx(1:min(4,length(idx)));
+        % find the intervals
+        interval = diff(idx);
+        % now histogram the intervals
+        if (~isempty(interval))
+            for k=1:length(interval),
+                iih(round(interval(k)),frame) = iih(round(interval(k)),frame)+amp(k);
+                IPIhisttime(iCounter,frame,k) = interval(k)/sfreq;
+                IPIhistweight(iCounter,frame,k) = amp(k);
+            end
+        end
+        
+    end
+    
+    
+    
+    
+    %% end Guy's code
+    
+    
+    %         %take the autocorrelation (ACF) of a 10ms-segment of each channel
+    %         Acorr(iCounter,time_counter,:) = xcorr(IFRAN_pattern(iCounter,jCounter:number_of_samples10ms+jCounter),'biased'); %biased scales the ACF by the reciprocal of the length of the segment
+    %         %root calculation
+    %         RAcorr(iCounter,time_counter,:) = sqrt(abs(Acorr(iCounter,time_counter,:)));
+    %
+    %         %smoothing using the 11-point hamming window
+    %         for kCounter = 6:size(RAcorr(iCounter,time_counter,:),3)-5 %start with 6 and end with 5 samples
+    %             %less the length of time_axis not to get in conflict with the length of
+    %             %the hamm_window
+    %             SRAcorr(iCounter,time_counter,kCounter-5) = ...
+    %                 squeeze(RAcorr(iCounter,time_counter,(kCounter-5):(kCounter+5)))'*hamm_window./sum(hamm_window);
+    %         end
+    %
+    %         %mean value of actual SRA
+    %         SRA_mean = mean(SRAcorr(iCounter,time_counter,:));
+    %
+    %         %find signed zero-crossings of the first derivative (=difference)
+    %         z_crossings_indices = find(diff(sign(diff(squeeze(SRAcorr(iCounter,time_counter,:))))) < 0)+1; %+1 is necessary, because diff shortens vector by 1
+    %         middle_index = ceil(size(SRAcorr(iCounter,time_counter,:),3)/2);
+    %
+    %         validCounter = 1;
+    %         valid_z_crossings_indices = [];
+    %         %find valid zero-crossings (peak higher than meanvalue and within first 5 ms of SRA)
+    %         for lCounter = 1:length(z_crossings_indices)
+    %             if (SRAcorr(iCounter,time_counter,z_crossings_indices(lCounter)) > SRA_mean) && ...
+    %                     (abs(z_crossings_indices(lCounter)-middle_index) < round(number_of_samples10ms/2));
+    %                 valid_z_crossings_indices(validCounter) = z_crossings_indices(lCounter);
+    %                 validCounter = validCounter+1;
+    %             end
+    %         end
+    %
+    %         %find main peak in the ACF
+    %         [tmp,index_of_z_crossings_main_index] = min(abs(middle_index-valid_z_crossings_indices));
+    %         if ~tmp == 0
+    %             disp('middle peak not appropriately found');
+    %         end
+    %
+    %         %%% for debugging
+    % %         if iCounter == 130
+    % %             disp('here');
+    % %             figure, plot(squeeze(SRAcorr(iCounter,time_counter,:)));
+    % %             hold on, plot([1 length(squeeze(SRAcorr(iCounter,time_counter,:)))],[SRA_mean SRA_mean],'r-');
+    % %         end
+    %         %%%
+    %
+    %         %generate IPI-histogram: take the first 3 intervals of SRAcorr
+    %         %(positive delay) in the first 5 ms
+    %         histcounter = 1;
+    %         for lCounter = index_of_z_crossings_main_index+1:min([length(valid_z_crossings_indices(index_of_z_crossings_main_index+1:end)) 3])+index_of_z_crossings_main_index
+    %             sampledifference = abs(valid_z_crossings_indices(lCounter)-valid_z_crossings_indices(lCounter-1));
+    %             %the difference between two adjacent peaks in the SRA is taken
+    %             %as IPI estimate
+    %             IPIhisttime(iCounter,time_counter,histcounter) = sampledifference*one_sample_is_a_time_of;
+    %             %the amplitude of the SRA at the start of the SRA interval is
+    %             %taken as the IPIweight
+    %             IPIhistweight(iCounter,time_counter,histcounter) = SRAcorr(iCounter,time_counter,valid_z_crossings_indices(lCounter-1));
+    %             histcounter = histcounter + 1;
+    %         end
+    
+    %time_counter = time_counter+1;
+end
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/userProgramsTim/track_formants_from_IPI_guy_olde.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,184 @@
+function [iih,IPIhisttime,IPIhistweight]=track_formants_from_IPI_guy(IFRAN_pattern, sfreq)
+% 
+% tracks the formants according to an analysis proposed in Secker-Walker
+% JASA 1990, section V.A
+% Tim Jürgens, February 2011, code from Guy Brown included
+% 
+% input:  IFRAN_pattern: pattern of the auditory model (dependend on the number of modules used)
+%                        first dimension: frequency channel, 
+%                        second dimension: time (samples)
+%         sfreq:         sampling frequency
+% output: iih:           interpeak-interval histogram, matrix very similar
+%                        the plot 5 in the Secker-Walker paper
+%
+%
+%
+
+
+time_axis = 0:1/sfreq:(size(IFRAN_pattern,2)-1)/sfreq;
+
+%find how many samples of AN_pattern are 10ms and 3ms
+%one_sample_is_a_time_of = time_axis(2);
+[tmp, start_time_index] = min(abs(0-time_axis));
+[tmp, stop10_time_index] = min(abs(0.010-time_axis));
+number_of_samples10ms = stop10_time_index - start_time_index;
+
+[tmp, stop3_time_index] = min(abs(0.003-time_axis));
+number_of_samples3ms = stop3_time_index - start_time_index;
+every_3ms = 1:number_of_samples3ms:size(IFRAN_pattern,2)-number_of_samples10ms;
+
+hamm_window = hamming(11);
+halfHamming = (length(hamm_window)-1)/2;
+
+% window normalization
+
+norm = conv(ones(1,floor(number_of_samples10ms/2)),hamm_window);
+norm = norm(5+1:end-5)';
+win_size = number_of_samples10ms;
+half_win_size = floor(win_size/2);
+hop_size = number_of_samples3ms;
+
+
+%pre-allocation due to speed
+%Acorr = zeros(size(IFRAN_pattern,1),size(every_3ms,2),number_of_samples10ms*2+1);
+%RAcorr = zeros(size(IFRAN_pattern,1),size(every_3ms,2),number_of_samples10ms*2+1);
+%SRAcorr = zeros(size(IFRAN_pattern,1),size(every_3ms,2),number_of_samples10ms*2+1-10);
+IPIhisttime = zeros(size(IFRAN_pattern,1),size(every_3ms,2),3);
+IPIhistweight = zeros(size(IFRAN_pattern,1),size(every_3ms,2),3);  %maximum 3 peaks from the SRA
+iih = zeros(half_win_size,size(every_3ms,2));
+
+
+
+
+for iCounter = 1:size(IFRAN_pattern,1) %each channel
+    fprintf('Channel No. %i\n',iCounter);
+    %time_counter = 1;
+    %for jCounter = every_3ms %every 3ms time segment
+    
+    
+    
+    %% Guy's code
+    % enframe this signal
+    
+    frames = enframe(IFRAN_pattern(iCounter,:),win_size,hop_size);
+    
+    % compute the autocorrelation
+    
+    acf = real(ifft(abs(fft(frames,[],2)).^2,[],2));
+    acf(acf<0)=0;
+    acf = sqrt(acf(:,1:half_win_size));
+    
+    % smooth with hamming window and take the root
+    
+    for frame=1:size(acf,1)
+        
+        %%debug
+        %if iCounter == 130
+        %    disp('here');
+        %end
+        
+        
+        sra = conv(acf(frame,:),hamm_window);
+        sra = sra(halfHamming+1:end-halfHamming)./norm';
+        df = [0 ; diff(sra')];
+        idx = find((df(1:end-1)>=0)&(df(2:end)<0));
+        % interpolate
+        a=df(idx);
+        b=df(idx+1);
+        idx = (idx-1+a./(a-b));
+        % get rid of a zero peak, if it exists
+        idx = idx(idx>1);
+        %include the zeroth peak
+        %idx = [1 idx']';
+        % peak values corresponding to these intervals
+        amp = interp1(1:length(sra),sra,idx,'linear');
+        % if required, remove peaks that lie below the mean sra
+        % note that we disregard the value at zero delay
+        %if (params.removePeaksBelowMean)
+        valid = find(amp>1.2*mean(sra(1:end)));
+        idx = idx(valid);
+        amp = amp(valid);
+        %end
+        % only use the first four peaks (three intervals)
+        idx = idx(1:min(4,length(idx)));
+        % find the intervals
+        interval = diff(idx);
+        % now histogram the intervals
+        if (~isempty(interval))
+            for k=1:length(interval),
+                iih(round(interval(k)),frame) = iih(round(interval(k)),frame)+amp(k);
+                IPIhisttime(iCounter,frame,k) = interval(k)/sfreq;
+                IPIhistweight(iCounter,frame,k) = amp(k);
+            end
+        end
+        
+    end
+    
+    
+    
+    
+    %% end Guy's code
+    
+    
+    %         %take the autocorrelation (ACF) of a 10ms-segment of each channel
+    %         Acorr(iCounter,time_counter,:) = xcorr(IFRAN_pattern(iCounter,jCounter:number_of_samples10ms+jCounter),'biased'); %biased scales the ACF by the reciprocal of the length of the segment
+    %         %root calculation
+    %         RAcorr(iCounter,time_counter,:) = sqrt(abs(Acorr(iCounter,time_counter,:)));
+    %
+    %         %smoothing using the 11-point hamming window
+    %         for kCounter = 6:size(RAcorr(iCounter,time_counter,:),3)-5 %start with 6 and end with 5 samples
+    %             %less the length of time_axis not to get in conflict with the length of
+    %             %the hamm_window
+    %             SRAcorr(iCounter,time_counter,kCounter-5) = ...
+    %                 squeeze(RAcorr(iCounter,time_counter,(kCounter-5):(kCounter+5)))'*hamm_window./sum(hamm_window);
+    %         end
+    %
+    %         %mean value of actual SRA
+    %         SRA_mean = mean(SRAcorr(iCounter,time_counter,:));
+    %
+    %         %find signed zero-crossings of the first derivative (=difference)
+    %         z_crossings_indices = find(diff(sign(diff(squeeze(SRAcorr(iCounter,time_counter,:))))) < 0)+1; %+1 is necessary, because diff shortens vector by 1
+    %         middle_index = ceil(size(SRAcorr(iCounter,time_counter,:),3)/2);
+    %
+    %         validCounter = 1;
+    %         valid_z_crossings_indices = [];
+    %         %find valid zero-crossings (peak higher than meanvalue and within first 5 ms of SRA)
+    %         for lCounter = 1:length(z_crossings_indices)
+    %             if (SRAcorr(iCounter,time_counter,z_crossings_indices(lCounter)) > SRA_mean) && ...
+    %                     (abs(z_crossings_indices(lCounter)-middle_index) < round(number_of_samples10ms/2));
+    %                 valid_z_crossings_indices(validCounter) = z_crossings_indices(lCounter);
+    %                 validCounter = validCounter+1;
+    %             end
+    %         end
+    %
+    %         %find main peak in the ACF
+    %         [tmp,index_of_z_crossings_main_index] = min(abs(middle_index-valid_z_crossings_indices));
+    %         if ~tmp == 0
+    %             disp('middle peak not appropriately found');
+    %         end
+    %
+    %         %%% for debugging
+    % %         if iCounter == 130
+    % %             disp('here');
+    % %             figure, plot(squeeze(SRAcorr(iCounter,time_counter,:)));
+    % %             hold on, plot([1 length(squeeze(SRAcorr(iCounter,time_counter,:)))],[SRA_mean SRA_mean],'r-');
+    % %         end
+    %         %%%
+    %
+    %         %generate IPI-histogram: take the first 3 intervals of SRAcorr
+    %         %(positive delay) in the first 5 ms
+    %         histcounter = 1;
+    %         for lCounter = index_of_z_crossings_main_index+1:min([length(valid_z_crossings_indices(index_of_z_crossings_main_index+1:end)) 3])+index_of_z_crossings_main_index
+    %             sampledifference = abs(valid_z_crossings_indices(lCounter)-valid_z_crossings_indices(lCounter-1));
+    %             %the difference between two adjacent peaks in the SRA is taken
+    %             %as IPI estimate
+    %             IPIhisttime(iCounter,time_counter,histcounter) = sampledifference*one_sample_is_a_time_of;
+    %             %the amplitude of the SRA at the start of the SRA interval is
+    %             %taken as the IPIweight
+    %             IPIhistweight(iCounter,time_counter,histcounter) = SRAcorr(iCounter,time_counter,valid_z_crossings_indices(lCounter-1));
+    %             histcounter = histcounter + 1;
+    %         end
+    
+    %time_counter = time_counter+1;
+end
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/utilities/UTIL_Butterworth.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,31 @@
+function x=UTIL_Butterworth (x, dt, fl, fu, order)
+% UTIL_Butterworth (x, dt, fu, fl, order)
+% Taken from Yuel and beauchamp page 261
+% NB error in their table for K (see their text)
+% x is original signal
+% x is the filtered output (approx 3 dB down at cutoff for first order filter)
+% fu, fl upper and lower cutoff
+% order is the number of times the filter is applied
+% (approx 6 dB attenuation is corrected)
+
+sampleRate=1/dt;
+if 4*fu>sampleRate  
+    error(['UTIL_Butterworth: sample rate ' num2str(sampleRate) ' is too low.  Sampling rate should be >' num2str(4*fu)])
+end
+
+
+q=(pi*dt*(fu-fl));
+J=1/(1+ cot(q));
+K= (2*cos(pi*dt*(fu+fl)))/((1+tan(q))*cos(q));
+L= (tan(q)-1)/(tan(q)+1);
+b=[J 0 -J];
+a=[1 -K  -L];
+
+[numChannels nDataPoints]=size(x);
+for channelNumber=1:numChannels
+	for j=1:order
+		% x2 compensate for 6 dB attenuation
+		x(channelNumber,:)=2*filter(b, a, x(channelNumber,:));
+	end
+end
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/utilities/UTIL_CAPgenerator.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,64 @@
+function wholeNerveCAP  = UTIL_CAPgenerator...
+    (ANresponse, dt, BFlist, numANfibers, plotCAP)
+% 
+% Generates a compound action potential by convolving an impulse repsonse,
+% as defined by Mark Chertoff (2004, JASA), with the response of the 
+% auditory nerve.
+%
+%
+% -e(-k*time)*SIN(2*PI()*f*time)
+%
+% mu(t) = e^-kt * sin(omega*t)
+% omega = 2 * pi * f
+%
+%
+% Robert T. Ferry
+% 01st May 2008
+%
+%
+
+nChannels=length(BFlist);
+[r nSpikeEpochs]=size(ANresponse);
+
+wholeNerveCAP       = [];
+channelCAP          = [];
+e                   = exp(1);
+k                   = 1000;
+impulseDuration     = 0.01;
+impulseFrequency    = 750;
+impulseTime         = dt:dt:impulseDuration;
+impulseResponse     = -e.^(-k*impulseTime).*sin(2*pi*impulseFrequency*impulseTime);
+impulseResponse=impulseResponse-mean(impulseResponse);
+
+% WholeNerveCAP
+ANoutput = sum(ANresponse, 1);
+convolvedWholeNerveCAP = conv(ANoutput, impulseResponse(1,:));
+% truncate
+convolvedWholeNerveCAP=convolvedWholeNerveCAP(1:nSpikeEpochs);
+
+% apply measurement time constant
+sampleRate=1/dt;
+upperFreq=sampleRate/4;
+lowPassCutOff=40;
+wholeNerveCAP = UTIL_Butterworth(convolvedWholeNerveCAP, dt, lowPassCutOff, upperFreq, 1);
+% or do not do this
+% wholeNerveCAP = convolvedWholeNerveCAP;
+
+% Plot output?
+
+CAPtime = dt:dt:dt*length(wholeNerveCAP);
+
+if (plotCAP == 1)
+    figure(9)
+
+    subplot(3,1,1), plot(impulseTime, impulseResponse)
+    title('Impulse response')
+    xlabel('Time (s)'), ylabel('Amplitude (Pa)')
+    xlim([0 max(impulseTime)]), ylim([-inf inf])
+	
+    subplot(3,1,2), plot(CAPtime, wholeNerveCAP)
+    title(['AN CAP (whole-nerve)  '   num2str(length(BFlist)) ' channels' num2str(numANfibers) ' fibers/ch'])
+    xlabel('Time (s)'), ylabel('Amplitude (Pa)')
+    xlim([0 max(CAPtime)]), ylim([-inf inf])   
+	
+end
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/utilities/UTIL_FFT.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,39 @@
+function [fft_powerdB, fft_phase, frequencies, fft_ampdB]=...
+    UTIL_FFT(getFFTsignal, dt, referenceAmplitude)
+% UTIL_FFT
+% [fft_powerdB, fft_phase, frequencies, fft_ampdB]= UTIL_FFT(getFFTsignal, dt, referenceAmplitude)
+
+x=length(getFFTsignal);         % adjust the length of the signal to a power of 2 for FFT
+n=2;
+while n<=x
+    n=n*2;
+end
+n=round(n/2);
+getFFTsignal=getFFTsignal(1:n);
+frequencies = (1/dt)*(1:n/2)/n;
+
+fft_result = fft(getFFTsignal, n);				    % Compute FFT of the input signal.
+fft_power = fft_result .* conj(fft_result); % / n;	% Compute power spectrum.  
+% Dividing by 'n' we get the power spectral density.
+%     fft_power = fft_result .* conj(fft_result) / n;	% Compute power spectralDensity.  
+
+% Prepare the FFT for display
+fft_power=fft_power(1:length(fft_power)/2);         % remove mirror frequencies
+%     fft_powerdB = UTIL_amp2dB (fft_power, max(fft_power)); % convert to dB
+fft_powerdB = 10*log10(fft_power);                  % convert to dB
+
+% amplitude spectrum
+if nargin<3
+    referenceAmplitude=28e-6; % for SPL
+end
+% refAmpdB= referenceAmplitude^0.5;
+fft_ampdB = 10*log10(fft_power/referenceAmplitude); % convert to dB
+%     peak_fft_powerdBSPL=max(fft_ampdB)
+
+
+fft_phase = angle(fft_result);			            % Compute the phase spectrum.
+fft_phase=fft_phase(1:length(fft_phase)/2);         % remove mirror phases
+jags=find(diff(fft_phase)>0);                       % unwrap phase
+for i=jags, 
+    fft_phase(i+1:end)=fft_phase(i+1:end)-2*pi; 
+end
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/utilities/UTIL_cascadePlot.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,26 @@
+function UTIL_cascadePlot(toPlot, colValues)
+% % useful code
+[nChannels nLags]=size(toPlot);
+
+% cunning code to represent channels as parallel lines
+[nRows nCols]=size(toPlot);
+if nChannels<2
+    error('UTIL_cascadePlot: only one row found')
+end
+
+% a is the height to be added to each channel
+a=max(max(toPlot))*(0:nRows-1)';
+
+% peakGain emphasises the peak height
+% peaks can be higher than the space between channels
+peakGain=10;
+x=peakGain*toPlot+repmat(a,1,nCols);
+x=nRows*x/max(max(x));
+
+for row=1:nRows-1
+    x(row,:)=min(x(row,:), x(row+1,:));
+end
+
+plot(colValues,   x','k')
+ylim([0 nRows])
+
--- a/utilities/UTIL_plotMatrix.m	Thu Oct 06 15:43:20 2011 +0100
+++ b/utilities/UTIL_plotMatrix.m	Mon Nov 28 13:34:28 2011 +0000
@@ -2,80 +2,75 @@
 % UTIL_plotMatrix general purpose plotting utility for plotting the results
 %  of the MAP auditory model.
 % All plots are placed in subplots of a figure (default figure 1).
+%
 % Input arguments:
 % 	'toPlot' is matrix (either numeric or logical)
 % 	'method' is a structure containing plot instructions
 %
-%   surface plots have log z-axis when all values are >1
-%
-% when calling this function, always increment the subPlotNo in method
-% 	method.subPlotNo=method.subPlotNo+1;
-% 	method.subPlotNo=method.subPlotNo;
-%
 % mandatory parameters:
-% 	method.displaydt			xValues spacing between data points
-% 	method.numPlots      total number of subPlots in the figure
-% 	method.subPlotNo     number of this plot
-%   method.yValues 		mandatory only for 3D plots
+% 	method.displaydt		xValues spacing between data points
+%   method.yValues          yaxis labels mandatory only for 3D plots
 %
 % optional
-% 	method.figureNo      normally figure(1)
-% 	method.zValuesRange 	[min max] value pair to define yaxis limits
-%   method.zValuesRange  [min max] CLIMS for 3-D plot
-% 	method.yLabel 		(string) y-axis label
-% 	method.xLabel		(string) x-axis label
-% 	method.title  		     (string) subplot title
+% 	method.figureNo         default figure(1)
+% 	method.numPlots         number of subPlots in the figure (default=1)
+% 	method.subPlotNo        number of this plot (default=1)
+% 	method.zValuesRange     [min max] value pair to define yaxis limits
+%   method.zValuesRange     [min max] CLIMS for 3-D plot
+% 	method.yLabel           (string) y-axis label
+%   method.minyMaxy         y-axis limits
+% 	method.xLabel           (string) x-axis label
+% 	method.title  		    (string) subplot title
 %   method.bar    		    =1,  to force bar histogram (single channel only)
-%   method.view			  3D plot 'view' settings e.g. [-6 40]
-%   method.axes           (handle) used for writing to GUIs (specifies panel)
-%   method.maxPixels     maximum number of pixels (used to speed plotting)
-%   method.blackOnWhite =1;  % NB inverts display for 2D plots
-%   method.forceLog      positive values are put on log z-scale
-%   method.rasterDotSize min value is 1
-%   method.defaultFontSize
-%   method.timeStart        default=dt
-%   method.defaultTextColor default ='w'
-%   method.defaultAxesColor default = 'w'
-%   method.nCols            default=1
-%   method.nRows            default=method.numPlots
+%   method.view             3D plot 'view' settings e.g. [-6 40]
+%   method.axes             (handle) where to plot (overules all others)
+%   method.maxPixels        maximum number of pixels (used to speed plotting)
+%   method.blackOnWhite     =1; inverts display for 2D plots
+%   method.forceLog         positive values are put on log z-scale
+%   method.rasterDotSize    min value is 1
+%   method.defaultFontSize  deafult= 12
+%   method.timeStart        default= dt
+%   method.defaultTextColor default ='k'
+%   method.defaultAxesColor default ='k'
+%   method.nCols            default = 1 (layout for subplots)
+%   method.nRows            default=method.numPlots (layout for subplots
+%   method.segmentNumber    plot only this segment while 'hold on'
 %
-% useful paste for calling program
-% 	method.numPlots=method.numPlots;
-%	method.subPlotNo=method.subPlotNo+1;
-% 	method.subPlotNo=method.subPlotNo;
-% 	dt=dt;
-% 	method.yValues=method.nonlinCF;	% for 3D plots only
-%
-% 	method.figureNo=1;
-% 	method.yLabel='useThisLabel';
-% 	method.xLabel='use this label';
-% 	method.title='myTitle';
-%
+% e.g.
 %   UTIL_plotMatrix(toPlot, method)
 
 dt=method.displaydt;
+[r cols]=size(toPlot);
+if cols==1
+    % toPlot should be a wide matrix or a long vector
+    toPlot=toPlot';
+end
+
+if ~isfield(method,'numPlots') || isempty(method.numPlots)
+    method.numPlots =1;
+    method.subPlotNo =1;
+end
+
 if ~isfield(method,'figureNo') || isempty(method.figureNo)
     method.figureNo=99;
 end
+
 % if ~isfield(method,'zValuesRange') || isempty(method.zValuesRange)
 %     method.zValuesRange=[-inf inf];
 % end
 
 % set some defaults
-if ~isfield( method,'plotDivider') || isempty(method.plotDivider)
-    method.plotDivider=0; 
-end
 if ~isfield( method,'blackOnWhite') || isempty(method.blackOnWhite)
-    method.blackOnWhite=0; 
+    method.blackOnWhite=0;
 end
 if ~isfield(method,'timeStart')|| isempty(method.timeStart)
-    method.timeStart=dt; 
+    method.timeStart=dt;
 end
 if ~isfield(method,'objectDuration') || isempty(method.objectDuration)
     [nRows nCols]=size(toPlot); method.objectDuration=dt*nCols;
 end
 if ~isfield(method,'defaultFontSize') || isempty(method.defaultFontSize)
-    method.defaultFontSize=12; 
+    method.defaultFontSize=12;
 end
 if ~isfield(method,'defaultTextColor') || isempty(method.defaultTextColor)
     method.defaultTextColor='k';
@@ -84,7 +79,7 @@
     defaultTextColor='k';
 end
 if ~isfield( method,'defaultAxesColor') || isempty(method.defaultAxesColor)
-    method.defaultAxesColor=defaultTextColor; 
+    method.defaultAxesColor=defaultTextColor;
 end
 defaultAxesColor=method.defaultAxesColor;
 
@@ -107,8 +102,11 @@
 %   if both are specified, 'axes' takes priority
 figure(method.figureNo)
 if isfield(method,'axes') && ~isempty(method.axes)
-    % select an axis in some location other than 'figure'
-    h=axes(method.axes);
+    % user defines where to plot it
+    axes(method.axes);
+    method.numPlots =1;
+    method.subPlotNo =1;
+    
 else
     % now using a regular figure
     if method.subPlotNo>method.numPlots;
@@ -119,7 +117,7 @@
     
     if isfield(method,'segmentNumber') && ~isempty(method.segmentNumber)...
             && method.segmentNumber>1
-        % in multi-segment mode do not clear the image 
+        % in multi-segment mode do not clear the image
         %  from the previous segment
         hold on
     else
@@ -139,6 +137,14 @@
     yValues=1:numYvalues;
 end
 
+if round(numYvalues/length(yValues))>1
+    % case where the plot matrix is double height (e.g. LSR+HSR)
+    yValues=[yValues yValues];
+    method.plotDivider=1;
+else
+    method.plotDivider=0;
+end
+
 % Now start the plot.
 %  3D plotting for 4 or more channels
 %  otherwise special cases for fewer channels
@@ -195,11 +201,9 @@
             end
             
         otherwise                       % >3 channels: surface plot
-            % add white line to separate HSR and LSR
+            % add  line to separate HSR and LSR
             if method.plotDivider && size(toPlot,1) > 2
                 [r c]=size(toPlot);
-%                 if isempty(method.zValuesRange), method.zValuesRange=0; end
-%                 mm=method.zValuesRange(2);
                 emptyLine=max(max(toPlot))*ones(2,c);
                 halfway=round(r/2);
                 toPlot=[toPlot(1:halfway,:); emptyLine; toPlot(halfway+1:end,:)];
@@ -225,28 +229,12 @@
             %  zValuesRange
             if isfield(method,'zValuesRange') ...
                     && ~isempty(method.zValuesRange)
-                % zValuesRange gives the max and min values
-%                 a=method.zValuesRange(1);
-%                 b=method.zValuesRange(2);
-%                 toPlot=(toPlot-a)/(b-a);
-%                 clims=[0 1];
                 clims=(method.zValuesRange);
                 imagesc(xValues, yValues, toPlot, clims), axis xy; %NB assumes equally spaced y-values
             else
                 % automatically scaled
                 imagesc(xValues, yValues, toPlot), axis xy; %NB assumes equally spaced y-values
                 
-                %                 if ~isfield(method,'zValuesRange')
-                %                     method.zValuesRange=[-inf inf];
-                %                 end
-                %
-                %                 if method.blackOnWhite
-                %                     % NB plotted values have negative sign for black on white
-                %                     caxis([-method.zValuesRange(2) -method.zValuesRange(1)])
-                %                 else
-                %                     caxis(method.zValuesRange)
-                %                 end
-                
                 if ~isfield(method,'zValuesRange')...
                         || isempty(method.zValuesRange)
                     method.zValuesRange=[-inf inf];
@@ -264,9 +252,8 @@
             % NB segmentation may shorten signal duration
             [r c]=size(toPlot);
             imageDuration=c*method.displaydt;
-            xlim([0 imageDuration])            
-%             xlim([0 method.objectDuration])
-
+            xlim([0 imageDuration])
+            
             % yaxis
             if isfield(method,'minyMaxy') && ~isempty(method.minyMaxy)
                 ylim(method.minyMaxy)
@@ -275,17 +262,29 @@
                     ylim([min(yValues) max(yValues)])
                 end
             end
-            if min(yValues)>1  % put channel array on a log scale
+            
+            % y-axis design yTickLabels
+            if min(yValues)>1
                 tickValues=[min(yValues) max(yValues)];
+                tickLabels=num2str(tickValues');
+                if method.plotDivider && size(toPlot,1) > 2
+                    % show min/max yvalues with slight shift
+                    yList=yValues;
+                    yValues=1:length(yValues);
+                    tickValues=[1 halfway-1 halfway+2 length(yValues)];
+                    idx=[1 halfway halfway+1 length(yValues)];
+                    tickLabels=num2str(yList(idx)');
+                    imagesc(xValues, yValues, toPlot), axis xy;
+                end
+                
                 set(gca,'ytick',tickValues)
-                set(gca,'ytickLabel', strvcat(num2str(tickValues')))
+                set(gca,'ytickLabel', strvcat(tickLabels))
                 set(gca,'FontSize', method.defaultFontSize)
             end
             
     end
     
-else	% is logical 
-    
+else	% is logical
     % logical implies spike array. Use raster plot
     [y,x]=find(toPlot);	%locate all spikes: y is fiber number ie row
     x=x*dt+method.timeStart;   % x is time
@@ -314,6 +313,7 @@
         plot([0 c*method.displaydt],[halfWayUp halfWayUp], 'b')
         hold off
     end
+    
 end
 
 set(gca, 'xcolor', defaultAxesColor)
@@ -330,7 +330,7 @@
     set(gca,'xtick',[],'FontSize', method.defaultFontSize)
     if method.subPlotNo==method.numPlots
         if isfield(method,'xLabel') && ~isempty(method.xLabel)
-%               set(gca,'ActivePositionProperty','outerposition')
+            %               set(gca,'ActivePositionProperty','outerposition')
             %  xlabel(method.xLabel)
             xlabel(method.xLabel, 'FontSize', method.defaultFontSize, 'color', defaultTextColor)
         end
--- a/utilities/UTIL_printTabTable.m	Thu Oct 06 15:43:20 2011 +0100
+++ b/utilities/UTIL_printTabTable.m	Mon Nov 28 13:34:28 2011 +0000
@@ -2,7 +2,7 @@
 % printTabTable prints a matrix as a table with tabs
 %headers are optional
 %headers=strvcat('firstname', 'secondname')
-%  printTabTable([1 2; 3 4],strvcat('a1','a2'));
+%  UTIL_printTabTable([1 2; 3 4],strvcat('a1','a2'));
 
 if nargin<3
     format='%g';
--- a/utilities/UTIL_showMAP.m	Thu Oct 06 15:43:20 2011 +0100
+++ b/utilities/UTIL_showMAP.m	Mon Nov 28 13:34:28 2011 +0000
@@ -1,62 +1,71 @@
-function UTIL_showMAP (showMapOptions, paramChanges)
+function UTIL_showMAP (showMapOptions)
 % UTIL_showMAP produces summaries of the output from MAP's mmost recent run
-%  All MAP outputs are stored in global variables and UTIL_showMAP
-%  simply assumes that they are in place.
+%  All MAP_14 outputs are stored in global variables and UTIL_showMAP
+%   simply assumes that they are in place. It uses whatever it there.
 %
-% showMapOptions
+% showMapOptions:
 % showMapOptions.printModelParameters=1; % print model parameters
 % showMapOptions.showModelOutput=1;      % plot all stages output
 % showMapOptions.printFiringRates=1;     % mean activity at all stages
 % showMapOptions.showACF=1;              % SACF (probabilities only)
 % showMapOptions.showEfferent=1;         % plot of efferent activity
-% showMapOptions.surfProbability=0;      % HSR (probability) surf plot
-% showMapOptions.fileName=[];            % parameter filename for plot title
-
+% showMapOptions.surfAN=0;               % AN output surf plot
+% showMapOptions.fileName='';            % parameter filename for plot title
+% showMapOptions.PSTHbinwidth=0.001      % binwidth for surface plots
+% showMapOptions.colorbar=1;             % request color bar if appropriate
+% showMapOptions.view=[0 90];
 % dbstop if warning
 
-global dt ANdt  savedBFlist saveAN_spikesOrProbability saveMAPparamsName...
-    savedInputSignal OMEextEarPressure TMoutput OMEoutput ARattenuation ...
-    DRNLoutput IHC_cilia_output IHCrestingCiliaCond IHCrestingV...
-    IHCoutput ANprobRateOutput ANoutput savePavailable ANtauCas  ...
-    CNtauGk CNoutput  ICoutput ICmembraneOutput ICfiberTypeRates ...
-    MOCattenuation
-global OMEParams DRNLParams IHC_cilia_RPParams IHCpreSynapseParams
-global AN_IHCsynapseParams MacGregorParams MacGregorMultiParams
+% Discover results left behind by MAP1_14
+global  savedParamChanges savedBFlist saveAN_spikesOrProbability ...
+    saveMAPparamsName savedInputSignal dt dtSpikes ...
+    OMEextEarPressure TMoutput OMEoutput DRNLoutput...
+    IHC_cilia_output IHCrestingCiliaCond IHCrestingV...
+    IHCoutput ANprobRateOutput ANoutput savePavailable saveNavailable ...
+    ANtauCas CNtauGk CNoutput ICoutput ICmembraneOutput ICfiberTypeRates...
+    MOCattenuation ARattenuation 
+
+% Find parameters created in MAPparams<name>
+global inputStimulusParams OMEParams DRNLParams IHC_cilia_RPParams
+global IHCpreSynapseParams  AN_IHCsynapseParams
+global MacGregorParams MacGregorMultiParams  filteredSACFParams
 global ICrate
 
 
 restorePath=path;
 addpath ( ['..' filesep 'utilities'], ['..' filesep 'parameterStore'])
 
-if nargin<1
-    showMapOptions=[];
-end
+if nargin<1,  showMapOptions=[]; end
+paramChanges=savedParamChanges; 
+
 % defaults (plot staged outputs and print rates only) if options omitted
 if ~isfield(showMapOptions,'printModelParameters')
     showMapOptions.printModelParameters=0; end
-if ~isfield(showMapOptions,'showModelOutput'),showMapOptions.showModelOutput=1;end
-if ~isfield(showMapOptions,'printFiringRates'),showMapOptions.printFiringRates=1;end
+if ~isfield(showMapOptions,'showModelOutput'),showMapOptions.showModelOutput=0;end
+if ~isfield(showMapOptions,'printFiringRates'),showMapOptions.printFiringRates=0;end
+if ~isfield(showMapOptions,'surfAN'),showMapOptions.surfAN=0;end
+if ~isfield(showMapOptions,'ICrates'),showMapOptions.ICrates=0;end
 if ~isfield(showMapOptions,'showACF'),showMapOptions.showACF=0;end
 if ~isfield(showMapOptions,'showEfferent'),showMapOptions.showEfferent=0;end
-if ~isfield(showMapOptions,'surfProbability'),showMapOptions.surfProbability=0;end
+if ~isfield(showMapOptions,'PSTHbinwidth'),showMapOptions.PSTHbinwidth=0.001;end
 if ~isfield(showMapOptions,'fileName'),showMapOptions.fileName=[];end
-if ~isfield(showMapOptions,'surfSpikes'),showMapOptions.surfSpikes=0;end
-if ~isfield(showMapOptions,'ICrates'),showMapOptions.ICrates=0;end
+if ~isfield(showMapOptions,'colorbar'),showMapOptions.colorbar=1;end
+if ~isfield(showMapOptions,'view'),showMapOptions.view=[-25 80];end
+if ~isfield(showMapOptions,'ICrasterPlot'),showMapOptions.ICrasterPlot=0;end
 
 %% send all model parameters to command window
 if showMapOptions.printModelParameters
     % Read parameters from MAPparams<***> file in 'parameterStore' folder
     %  and print out all parameters
-    if nargin>1
         cmd=['MAPparams' saveMAPparamsName '(-1, 1/dt, 1, paramChanges);'];
         eval(cmd);
-    else
-        cmd=['MAPparams' saveMAPparamsName '(-1, 1/dt, 1);'];
-        eval(cmd);
-        disp(' no parameter changes found')
-    end
 end
 
+% ignore zero elements in signal
+signalRMS=mean(savedInputSignal(find(savedInputSignal)).^2)^0.5;
+signalRMSdb=20*log10(signalRMS/20e-6);
+nANfiberTypes=length(ANtauCas);
+
 %% summarise firing rates in command window
 if showMapOptions.printFiringRates
     %% print summary firing rates
@@ -64,7 +73,6 @@
     disp('summary')
     disp(['AR: ' num2str(min(ARattenuation))])
     disp(['MOC: ' num2str(min(min(MOCattenuation)))])
-    nANfiberTypes=length(ANtauCas);
     if strcmp(saveAN_spikesOrProbability, 'spikes')
         nANfibers=size(ANoutput,1);
         nHSRfibers=nANfibers/nANfiberTypes;
@@ -93,10 +101,6 @@
 %% figure (99): display output from all model stages
 if showMapOptions.showModelOutput
     plotInstructions.figureNo=99;
-    
-    % ignore zero elements in signal
-    signalRMS=mean(savedInputSignal(find(savedInputSignal)).^2)^0.5;
-    signalRMSdb=20*log10(signalRMS/20e-6);
 
     % plot signal (1)
     plotInstructions.displaydt=dt;
@@ -104,9 +108,7 @@
     plotInstructions.subPlotNo=1;
     plotInstructions.title=...
         ['stimulus (Pa).  ' num2str(signalRMSdb, '%4.0f') ' dB SPL'];
-    r=size(savedInputSignal,1);
-    if r==1, savedInputSignal=savedInputSignal'; end
-    UTIL_plotMatrix(savedInputSignal', plotInstructions);
+    UTIL_plotMatrix(savedInputSignal, plotInstructions);
 
     % stapes (2)
     plotInstructions.subPlotNo=2;
@@ -119,17 +121,17 @@
     [r c]=size(DRNLoutput);
     if r>1
         plotInstructions.title= ['BM displacement'];
-    UTIL_plotMatrix(abs(DRNLoutput), plotInstructions);
+        UTIL_plotMatrix(abs(DRNLoutput), plotInstructions);
     else
         plotInstructions.title= ['BM displacement. BF=' ...
             num2str(savedBFlist) ' Hz'];
-    UTIL_plotMatrix(DRNLoutput, plotInstructions);
+        UTIL_plotMatrix(DRNLoutput, plotInstructions);
     end
 
     switch saveAN_spikesOrProbability
         case 'spikes'
             % AN (4)
-            plotInstructions.displaydt=ANdt;
+            plotInstructions.displaydt=dtSpikes;
             plotInstructions.title='AN';
             plotInstructions.subPlotNo=4;
             plotInstructions.yLabel='BF';
@@ -146,7 +148,7 @@
             UTIL_plotMatrix(ANoutput, plotInstructions);
 
             % CN (5)
-            plotInstructions.displaydt=ANdt;
+            plotInstructions.displaydt=dtSpikes;
             plotInstructions.subPlotNo=5;
             plotInstructions.title='CN spikes';
             if sum(sum(CNoutput))<100
@@ -155,7 +157,7 @@
             UTIL_plotMatrix(CNoutput, plotInstructions);
 
             % IC (6)
-            plotInstructions.displaydt=ANdt;
+            plotInstructions.displaydt=dtSpikes;
             plotInstructions.subPlotNo=6;
             plotInstructions.title='Brainstem 2nd level';
             if size(ICoutput,1)>1
@@ -172,64 +174,79 @@
             end
 
         otherwise % AN rate based on probability of firing
-            PSTHbinWidth=0.001;
+            PSTHbinWidth=0.0005;
             PSTH= UTIL_PSTHmakerb(ANprobRateOutput, dt, PSTHbinWidth);
-%             PSTH = makeANsmooth(PSTH, 1/PSTHbinWidth);
+            plotInstructions=[];
             plotInstructions.displaydt=PSTHbinWidth;
+            plotInstructions.plotDivider=0;
             plotInstructions.numPlots=2;
             plotInstructions.subPlotNo=2;
             plotInstructions.yLabel='BF';
-            plotInstructions.xLabel='time';
+            plotInstructions.yValues=savedBFlist;
+            plotInstructions.xLabel='time (s)';
             plotInstructions.zValuesRange= [0 300];
+
             if nANfiberTypes>1,
-                plotInstructions.yLabel='LSR    HSR';
+                plotInstructions.yLabel='LSR                   HSR';
                 plotInstructions.plotDivider=1;
             end
             plotInstructions.title='AN - spike rate';
             UTIL_plotMatrix(PSTH, plotInstructions);
             shading interp
-            colorbar('southOutside')
+            if showMapOptions.colorbar, colorbar('southOutside'), end
     end
     set(gcf,'name','MAP output')
 end
 
-if showMapOptions.surfProbability &&...
+
+%% surface plot of AN response
+%   probability
+if showMapOptions.surfAN &&...
         strcmp(saveAN_spikesOrProbability,'probability') && ...
         length(savedBFlist)>2
-    %% surface plot of probability
-        % select only HSR fibers
-        figure(97), clf
-        HSRprobOutput= ANprobRateOutput(end-length(savedBFlist)+1:end,:);
-        PSTHbinWidth=0.001;
-        PSTH=UTIL_PSTHmakerb(HSRprobOutput, ANdt, PSTHbinWidth);
-        [nY nX]=size(PSTH);
-        time=PSTHbinWidth*(1:nX);
-        surf(time, savedBFlist, PSTH)
-        shading interp
-        set(gca, 'yScale','log')
-        xlim([0 max(time)])
-        ylim([0 max(savedBFlist)])
-        zlim([0 1000])
-        xlabel('time (s)')
-        ylabel('best frequency (Hz)')
-        zlabel('spike rate')
-        view([-20 60])
-        %     view([0 90])
-        disp(['max max AN: ' num2str(max(max(PSTH)))])
-
-        title (['firing probability of HSR fibers only. Level= ' ...
-            num2str(signalRMSdb,'% 3.0f') ' dB'])
-        colorbar('southOutside')
+    % select only HSR fibers
+    figure(97), clf
+    PSTHbinWidth=showMapOptions.PSTHbinwidth;
+    PSTH= UTIL_PSTHmakerb(...
+        ANprobRateOutput(end-length(savedBFlist)+1:end,:), ...
+        dt, PSTHbinWidth);
+    [nY nX]=size(PSTH);
+    time=PSTHbinWidth*(1:nX);
+    surf(time, savedBFlist, PSTH)
+    caxis([0 500])
+    shading interp
+    set(gca, 'yScale','log')
+    xlim([0 max(time)])
+    ylim([0 max(savedBFlist)])
+    zlim([0 500])
+    myFontSize=10;
+    xlabel('time (s)', 'fontsize',myFontSize)
+    ylabel('BF (Hz)', 'fontsize',myFontSize)
+    zlabel('spike rate')
+    view(showMapOptions.view)
+    set(gca,'ytick',[500 1000 2000 8000],'fontSize',myFontSize)
+    title (['AN response. Level= ' ...
+        num2str(signalRMSdb,'% 3.0f') ' dB'...
+        '  binwidth= ' num2str(1000*PSTHbinWidth) ' s'])
+    if showMapOptions.colorbar, colorbar('southOutside'), end
 end
 
-%% surface plot of AN spikes
-if showMapOptions.surfSpikes ...
-    && strcmp(saveAN_spikesOrProbability, 'spikes')
+%% surfAN ('spikes')
+if showMapOptions.surfAN ...
+        && strcmp(saveAN_spikesOrProbability, 'spikes')...
+        && length(savedBFlist)>2
     figure(97), clf
+    % combine fibers across channels
+    nFibersPerChannel=AN_IHCsynapseParams.numFibers;
+    [r nEpochs]=size(ANoutput);
+    nChannels=round(r/nFibersPerChannel);
+    x=reshape(ANoutput,nChannels,nFibersPerChannel,nEpochs);
+    x=squeeze(sum(x,2));
     % select only HSR fibers at the bottom of the matrix
-    ANoutput= ANoutput(end-length(savedBFlist)+1:end,:);
-    PSTHbinWidth=0.005; % 1 ms bins
-    PSTH=UTIL_makePSTH(ANoutput, ANdt, PSTHbinWidth);
+    HSRoutput= x(end-length(savedBFlist)+1:end,:);
+    PSTH=HSRoutput;
+    PSTHbinWidth=showMapOptions.PSTHbinwidth;
+    PSTH=UTIL_makePSTH(HSRoutput, dtSpikes, PSTHbinWidth);
     [nY nX]=size(PSTH);
     time=PSTHbinWidth*(1:nX);
     surf(time, savedBFlist, PSTH)
@@ -241,12 +258,42 @@
     xlabel('time (s)')
     ylabel('best frequency (Hz)')
     zlabel('spike rate')
-    view([-20 60])
-    %     view([0 90])
+    view(showMapOptions.view)
     title ([showMapOptions.fileName ':   ' num2str(signalRMSdb,'% 3.0f') ' dB'])
     set(97,'name', 'spikes surface plot')
 end
 
+%% IC raster plot
+if showMapOptions.ICrasterPlot &&...
+        strcmp(saveAN_spikesOrProbability,'spikes') && ...
+        length(savedBFlist)>2
+    figure(91), clf
+    plotInstructions=[];
+    plotInstructions.numPlots=2;
+    plotInstructions.subPlotNo=2;
+    plotInstructions.title=...
+        ['IC raster plot'];
+    plotInstructions.figureNo=91;
+    plotInstructions.displaydt=dtSpikes;
+    plotInstructions.title='Brainstem 2nd level';
+    plotInstructions.yLabel='BF';
+    plotInstructions.yValues= savedBFlist;
+
+    if size(ICoutput,1)>1
+        if sum(sum(ICoutput))<100
+            plotInstructions.rasterDotSize=3;
+        end
+        UTIL_plotMatrix(ICoutput, plotInstructions);
+    end
+
+    % plot signal (1)
+    plotInstructions.displaydt=dt;
+    plotInstructions.subPlotNo=1;
+    plotInstructions.title=...
+        ['stimulus (Pa).  ' num2str(signalRMSdb, '%4.0f') ' dB SPL'];
+    UTIL_plotMatrix(savedInputSignal, plotInstructions);
+
+end
 
 %% figure(98) plot efferent control values as dB
 if showMapOptions.showEfferent
@@ -259,9 +306,9 @@
     plotInstructions.zValuesRange= [-1 1];
     plotInstructions.title= ['RMS level='...
         num2str(signalRMSdb, '%4.0f') ' dB SPL'];
-    UTIL_plotMatrix(savedInputSignal', plotInstructions);
-    
-    
+    UTIL_plotMatrix(savedInputSignal, plotInstructions);
+
+
     plotInstructions.subPlotNo=2;
     plotInstructions.zValuesRange=[ -25 0];
     plotInstructions.title= ['AR stapes attenuation (dB); tau='...
@@ -275,60 +322,37 @@
     plotInstructions.yLabel= 'dB';
     if strcmp(saveAN_spikesOrProbability,'spikes')
         rate2atten=DRNLParams.rateToAttenuationFactor;
-    plotInstructions.title= ['MOC atten; tau=' ...
-        num2str(DRNLParams.MOCtau) '; factor='...
-        num2str(rate2atten, '%6.4f')];
+        plotInstructions.title= ['MOC atten; tau=' ...
+            num2str(DRNLParams.MOCtau) '; factor='...
+            num2str(rate2atten, '%6.4f')];
     else
         rate2atten=DRNLParams.rateToAttenuationFactorProb;
-    plotInstructions.title= ['MOC atten; tauProb=' ...
-        num2str(DRNLParams.MOCtauProb) '; factor='...
-        num2str(rate2atten, '%6.4f')];
+        plotInstructions.title= ['MOC atten; tauProb=' ...
+            num2str(DRNLParams.MOCtauProb) '; factor='...
+            num2str(rate2atten, '%6.4f')];
     end
     plotInstructions.zValuesRange=[0 -DRNLParams.minMOCattenuationdB+5];
     UTIL_plotMatrix(-20*log10(MOCattenuation), plotInstructions);
     hold on
     [r c]=size(MOCattenuation);
-    if r>2
-    colorbar('southOutside')
+    if r>2 && showMapOptions.colorbar
+        colorbar('southOutside')
     end
     set(plotInstructions.figureNo, 'name', 'AR/ MOC')
-    
+
     binwidth=0.1;
     [PSTH ]=UTIL_PSTHmaker(20*log10(MOCattenuation), dt, binwidth);
     PSTH=PSTH*length(PSTH)/length(MOCattenuation);
     t=binwidth:binwidth:binwidth*length(PSTH);
     fprintf('\n\n')
-%     UTIL_printTabTable([t' PSTH'])
-%     fprintf('\n\n')
-    
+    %     UTIL_printTabTable([t' PSTH'])
+    %     fprintf('\n\n')
+
 end
 
-%% ACF plot if required
+%% ACF plot
 if showMapOptions.showACF
     tic
-    method.dt=dt;
-    method.segmentNo=1;
-    method.nonlinCF=savedBFlist;
-
-    minPitch=	80; maxPitch=	4000; numPitches=100;    % specify lags
-    pitches=10.^ linspace(log10(minPitch), log10(maxPitch),numPitches);
-    pitches=fliplr(pitches);
-    filteredSACFParams.lags=1./pitches;     % autocorrelation lags vector
-    filteredSACFParams.acfTau=	.003;       % time constant of running ACF
-    filteredSACFParams.lambda=	0.12;       % slower filter to smooth ACF
-    filteredSACFParams.lambda=	0.01;       % slower filter to smooth ACF
-
-    filteredSACFParams.plotACFs=0;          % special plot (see code)
-    filteredSACFParams.plotFilteredSACF=0;  % 0 plots unfiltered ACFs
-    filteredSACFParams.plotMoviePauses=.3;          % special plot (see code)
-
-    filteredSACFParams.usePressnitzer=0; % attenuates ACF at  long lags
-    filteredSACFParams.lagsProcedure=  'useAllLags';
-    % filteredSACFParams.lagsProcedure=  'useBernsteinLagWeights';
-    % filteredSACFParams.lagsProcedure=  'omitShortLags';
-    filteredSACFParams.criterionForOmittingLags=3;
-    filteredSACFParams.plotACFsInterval=200;
-
     if filteredSACFParams.plotACFs
         % plot original waveform on ACF plot
         figure(13), clf
@@ -339,6 +363,19 @@
         title(['stimulus: ' num2str(signalRMSdb, '%4.0f') ' dB SPL']);
     end
 
+    % compute ACF
+    switch saveAN_spikesOrProbability
+        case 'probability'
+            inputToACF=ANprobRateOutput(end-length(savedBFlist)+1:end,:);
+        otherwise
+            inputToACF=ANoutput;
+    end
+
+    disp ('computing ACF...')
+    [P, BFlist, sacf, boundaryValue] = ...
+        filteredSACF(inputToACF, dt, savedBFlist, filteredSACFParams);
+    disp(' ACF done.')
+
     % plot original waveform on summary/smoothed ACF plot
     figure(96), clf
     subplot(2,1,1)
@@ -347,29 +384,20 @@
     xlim([0 t(end)])
     title(['stimulus: ' num2str(signalRMSdb, '%4.0f') ' dB SPL']);
 
-
-    % compute ACF
-    switch saveAN_spikesOrProbability
-        case 'probability'
-            inputToACF=ANprobRateOutput.^0.5;
-        otherwise
-            inputToACF=ANoutput;
-    end
-
-    disp ('computing ACF...')
-    [P, BFlist, sacf, boundaryValue] = ...
-        filteredSACF(inputToACF, method, filteredSACFParams);
-    disp(' ACF done.')
-
-    % SACF
+    % plot SACF
+    figure(96)
     subplot(2,1,2)
     imagesc(P)
+%     surf(filteredSACFParams.lags, t, P)
     ylabel('periodicities (Hz)')
     xlabel('time (s)')
-    title(['running smoothed (root) SACF. ' saveAN_spikesOrProbability ' input'])
-    pt=[1 get(gca,'ytick')]; % force top xtick to show
+    title(['running smoothed SACF. ' saveAN_spikesOrProbability ' input'])
+    pt=[1 get(gca,'ytick')]; % force top ytick to show
     set(gca,'ytick',pt)
+    pitches=1./filteredSACFParams.lags;     % autocorrelation lags vector
     set(gca,'ytickLabel', round(pitches(pt)))
+    [nCH nTimes]=size(P);
+    t=dt:dt:dt*nTimes;
     tt=get(gca,'xtick');
     set(gca,'xtickLabel', round(100*t(tt))/100)
 end
@@ -395,22 +423,22 @@
 % end
 
 function ANsmooth = makeANsmooth(ANresponse, sampleRate, winSize, hopSize)
-            if nargin < 3
-                winSize = 25; %default 25 ms window
-            end
-            if nargin < 4
-                hopSize = 10; %default 10 ms jump between windows
-            end
-            
-            winSizeSamples = round(winSize*sampleRate/1000);
-            hopSizeSamples = round(hopSize*sampleRate/1000);
-            
-            % smooth
-            hann = hanning(winSizeSamples);
-            
-            ANsmooth = [];%Cannot pre-allocate a size as it is unknown until the enframing
-            for chan = 1:size(ANresponse,1)
-                f = enframe(ANresponse(chan,:), hann, hopSizeSamples);
-                ANsmooth(chan,:) = mean(f,2)'; %#ok<AGROW> see above comment
-            end
+if nargin < 3
+    winSize = 25; %default 25 ms window
+end
+if nargin < 4
+    hopSize = 10; %default 10 ms jump between windows
+end
+
+winSizeSamples = round(winSize*sampleRate/1000);
+hopSizeSamples = round(hopSize*sampleRate/1000);
+
+% smooth
+hann = hanning(winSizeSamples);
+
+ANsmooth = [];%Cannot pre-allocate a size as it is unknown until the enframing
+for chan = 1:size(ANresponse,1)
+    f = enframe(ANresponse(chan,:), hann, hopSizeSamples);
+    ANsmooth(chan,:) = mean(f,2)'; %#ok<AGROW> see above comment
+end
 %         end% ------ OF makeANsmooth
--- a/utilities/stimulusCreate.m	Thu Oct 06 15:43:20 2011 +0100
+++ b/utilities/stimulusCreate.m	Mon Nov 28 13:34:28 2011 +0000
@@ -399,7 +399,7 @@
             stimulus=applyGaussianRamps(stimulus, -stim.rampOnDur, 1/dt);
         end
 
-        % Initial silence
+        % begin silence
         % start with a signal of the right length consisting of zeros
         signal=zeros(1, globalStimParams.nSignalPoints);
         % identify start of stimulus
@@ -414,7 +414,7 @@
 
         % time signature
         time=dt:dt:dt*length(signal);
-        %     figure(22), plot(signal), title([num2str(ear) ' - ' num2str(componentNo)]),pause (1)
+        % figure(22), plot(signal), title([num2str(ear) ' - ' num2str(componentNo)]),pause (1)
 
         try
             % create a column vector and trap if no signal has been created
@@ -574,33 +574,63 @@
 function stimulus=makeOHIOtones(globalStimParams, stimComponents)
 
 % Generates a stimulus consisting of one or more 10-ms tones
-% Tones are presented at 10-ms intervals
+%  The length of the list of frequencies determines the numberof tones
+% Tones are either presented at 10-ms intervals or simultaneously
+% all tones are individually ramped
 % Each tone has its own amplitude and its own ramp.
 
 frequencies=stimComponents.frequencies;
 amplitudesdB=stimComponents.amplitudesdB;
 nFrequencies=length(frequencies);
 
+if amplitudesdB==-100
+    % catch trial
+    amplitudesdB=repmat(-100,1,nFrequencies);
+end
+
 dt=globalStimParams.dt;
+
 toneDuration=.010;
 time=dt:dt:toneDuration;
 
-rampDuration=stimComponents.rampOnDur;
+% fixed ramp, silenceDuration, toneDuration
+rampDuration=0.005;
 rampTime=dt:dt:rampDuration;
-ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ones(1,length(time)-length(rampTime))];
+ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ...
+    ones(1,length(time)-length(rampTime))];
 ramp=ramp.*fliplr(ramp);
 
-stimulus= zeros(1,round((toneDuration+globalStimParams.beginSilences(end))/dt)+1);
+silenceDuration=0.010;
+silenceDurationLength=round(silenceDuration/dt);
+initialSilence=zeros(1,silenceDurationLength);
+
+silenceToneDuration=toneDuration + silenceDuration;
+silenceToneDurationLength=round(silenceToneDuration/dt);
+
+% OHIO spect produces simultaneous tones
+if strcmp(stimComponents.OHIOtype,'OHIOspect')
+    totalDuration=silenceToneDuration;
+else
+    totalDuration=silenceToneDuration*nFrequencies;
+end
+
+totalDurationLength=round(totalDuration/dt);
+stimulus=zeros(1,totalDurationLength);
+toneBeginPTR=1;
 
 for i=1:nFrequencies
-    toneBeginPTR=round(globalStimParams.beginSilences(i)/dt)+1;
-
     frequency=frequencies(i);
     dBSPL=amplitudesdB(i);
     amplitude=28e-6* 10.^(dBSPL/20);
     tone=amplitude*sin(2*pi*frequency*time);
     tone=tone.*ramp;
-    stimulus(toneBeginPTR:toneBeginPTR+length(tone)-1)=stimulus(toneBeginPTR:toneBeginPTR+length(tone)-1)+tone;
+    % stimulus is normally zeros except for OHIOspect
+    stimulus(toneBeginPTR:toneBeginPTR+silenceToneDurationLength-1)=...
+        [initialSilence tone]+...
+        stimulus(toneBeginPTR:toneBeginPTR+silenceToneDurationLength-1);    
+    if ~strcmp(stimComponents.OHIOtype,'OHIOspect')
+        toneBeginPTR=toneBeginPTR+silenceToneDurationLength;
+    end
 end
 % figure(2), plot( stimulus')
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/utilities/temp.m	Mon Nov 28 13:34:28 2011 +0000
@@ -0,0 +1,39 @@
+frequencies=[1000 1250];
+amplitudesdB=[20 23];
+nFrequencies=length(frequencies);
+
+dt=0.0001;
+
+toneDuration=.010;
+time=dt:dt:toneDuration;
+
+% fixed ramp, silenceDuration, toneDuration
+rampDuration=0.005;
+rampTime=dt:dt:rampDuration;
+ramp=[0.5*(1+cos(2*pi*rampTime/(2*rampDuration)+pi)) ...
+    ones(1,length(time)-length(rampTime))];
+ramp=ramp.*fliplr(ramp);
+
+silenceDuration=0.010;
+silenceDurationLength=round(silenceDuration/dt);
+initialSilence=zeros(1,silenceDurationLength);
+
+silenceToneDuration=toneDuration + silenceDuration;
+silenceToneDurationLength=round(silenceToneDuration/dt);
+
+totalDuration=silenceToneDuration*nFrequencies;
+totalDurationLength=round(totalDuration/dt);
+stimulus=zeros(1,totalDurationLength);
+toneBeginPTR=1;
+
+for i=1:nFrequencies
+    frequency=frequencies(i);
+    dBSPL=amplitudesdB(i);
+    amplitude=28e-6* 10.^(dBSPL/20);
+    tone=amplitude*sin(2*pi*frequency*time);
+    tone=tone.*ramp;
+    stimulus(toneBeginPTR:toneBeginPTR+silenceToneDurationLength-1)=...
+        [initialSilence tone];    
+    toneBeginPTR=toneBeginPTR+silenceToneDurationLength;
+end
+figure(2), plot( stimulus')
Binary file wavFileStore/1o7a_44kHz.wav has changed
Binary file wavFileStore/1z67931a_44kHz.wav has changed
Binary file wavFileStore/Oh No.wav has changed
Binary file wavFileStore/ten.wav has changed
Binary file wavFileStore/white noise.wav has changed