function [template_parameters,resnorm,residual,exitflag,output,lambda,jacobian]=extract_events_for_simulatedpscinnoise_template
%description: opens hdf files, extracts, aligns, and scales events, and fits the average scaled event to get template parameters
%called by: command line
%calls: create_basic_text_file_justforsimpscinnoisetemplate, monoexprisedecay_template_generator
%notes: all time values in samples; changing the latency value from 1:6 results in slightly different amplitude and tau values, but the resulting templates are almost indistinguishable when overlaid
%code confirmed date: 13 nov 2012

eventindices=0:99;
minwindow=-2:2;
latency_value=5;

seed_vals=[10 5 45 0 latency_value];   %amplitude_scaler,tau_rise,tau_decay,y_offset,latency
lower_bounds=[4 3 6 -3 latency_value-2];
upper_bounds=[50 100 500 3 latency_value+2];
optionz=optimset('display','on','Algorithm','trust-region-reflective');

epochs={'20060916T193215'  '20070208T163503' '20070220T171211'  '20070319T125639'  '20070321T105508'}; 
windowings=[1 1 1 1 1];
returnranges={[-20000:30000] [-20000:30000] [-20000:30000] [-20000:30000] [-20000:30000]};
%trials=[37 36 7 15 12];%old
trials=[42 42 14 19 28];
columns=[2 2 2 2 2];
scalings=[100 100 100 100 100];
%startrows=[20046 21052 20610 20556 20063];%old
startrows=[ 20964 20731 20923 24770 20749];
leakstosubtract={[13000:18000] [8000:12000 14000:19000] [2000:6500 14000:19000] [1000:10000] [4000:12000]};

eventstack=[];minstack=[];
for i=1:length(epochs)
    wave=create_basic_text_file_justforsimpscinnoisetemplate(epochs{i},windowings(i),returnranges{i},trials(i),columns(i));
    wave=wave*scalings(i);
    wave=wave-mean(wave(leakstosubtract{i}));
    event=wave(startrows(i)-latency_value+eventindices)';
    figure,plot(event)
    eventstack=[eventstack; event];
    [~,minind]=min(event)
    minstack=[minstack; mean(event(minind+minwindow))];
end

alfa=min(minstack);
scaler=alfa./minstack
scalmat=repmat(scaler,1,length(eventindices));

eventstack=eventstack.*scalmat;

figure, hold on
for j=1:length(scaler), plot(eventstack(j,:),'k'), end

meanevent=mean(eventstack);
plot(meanevent,'r','linewidth',2)

[template_parameters,resnorm,residual,exitflag,output,lambda,jacobian]=lsqcurvefit(@monoexprisedecay_template_generator,seed_vals,[1:length(meanevent)],meanevent,lower_bounds,upper_bounds,optionz);

t=monoexprisedecay_template_generator(template_parameters,[1:length(eventindices)]);
plot(t,'g','linewidth',3)