function analyze_waveforms_clusters_mixtures_using_database(preinduction_asynch_events,postinduction_asynch_events)
%oct 2007 -- called from command line
clear all,close all,warning off MATLAB:divideByZero,tic
lookat_preinduc_ao_induc_ao_postinduc=7;  %1 is preinduc only, 2 is induc only, 3 is postinduc only, 7 is all three
interval_selection_method=1;   %interval_selection_method 1 is use all pre and postinduction trials, 2 is use the general window for all cases, 3 is use from the beginning of the preinduc spec window to end of the postinduc specific window contiguously, 4 is use the preinduc specific window and the postinduc specific window without using the postinduction portion prior to the specific window
	general_time_window_before=[-10 0];   %in minutes
	general_time_window_after=[15 25];  %in minutes
		ensure_equal_lengths=1;
careful_asynch_measurement_yesno=0;
careful_charge_calculator_yesno=1;
    analyze_and_plot_mean_responses_charge_yesno=0;
batch_exporting=0;
instant_archiving=0;
general_figure_position=[30 40 1200 850];

for presentcase=1
    
    %generating the query and querying the database to retrieve the appropriate filenames and other file info
	selection_clauses=query_generator(2,'20070208','[]')
	selection_clauses{1}
	error('z')
	[preinduction_files]=find_flagged_filenames_from_access(selection_clauses{1});
	[induction_files]=find_flagged_filenames_from_access(selection_clauses{2});
	[postinduction_files]=find_flagged_filenames_from_access(selection_clauses{3});
	npre=size(preinduction_files,1);nind=size(induction_files,1);npost=size(postinduction_files,1);
	if any(npre~=[nind npost]),a=npre, b=nind,c=npost,error('filesizemismatch'),end

    if any(presentcase==casecheck)       %used for skipping trials if needed
        disp(strcat('Currently analyzing case #',num2str(presentcase)))
        presentcases=[presentcases,presentcase];
        x_offset=(.5-rand)/4;   %this provides an offset so individual experiments should be more visible if rung plots are generated
        if lookat_preinduc_ao_induc_ao_postinduc==1 || lookat_preinduc_ao_induc_ao_postinduc==7  %load preinduction files
            namestartzpreinduc=findstr(preinduction_files{presentcase,1},'[');nameendzpreinduc=findstr(preinduction_files{presentcase,1},']');
			skipstartzpreinduc=findstr(preinduction_files{presentcase,2},'[');skipendzpreinduc=findstr(preinduction_files{presentcase,2},']');
            suffixpreinduc=strrep(preinduction_files{presentcase,3},'[','');suffixpreinduc=strrep(suffixpreinduc,']','');
            preinduction_psc=[]; preinduction_crit=[];preinduction_raw=[];preind_presyn_pulse_duration=[];preinduction_raw_asynch_trace=[];preinduction_raw_asynch_criterion=[];
            for presentpreinducfile=1:length(namestartzpreinduc)
                current_load_file_preinduc=preinduction_files{presentcase,1}((namestartzpreinduc(presentpreinducfile)+1):(nameendzpreinduc(presentpreinducfile)-1));
                current_delete_columns_preinduc=str2num(preinduction_files{presentcase,2}((skipstartzpreinduc(presentpreinducfile)+1):(skipendzpreinduc(presentpreinducfile)-1)));
                a=load(strcat('H:\extracted_values_modulebayHD\',current_load_file_preinduc,'__pre-postPSC',suffixpreinduc));
                a(:,current_delete_columns_preinduc)=[]; 
                preinduction_psc=[preinduction_psc a];
                b=load(strcat('H:\extracted_values_modulebayHD\',current_load_file_preinduc,'__criterion_vals',suffixpreinduc));
                b(:,current_delete_columns_preinduc)=[];
                preinduction_crit=[preinduction_crit b];
                if careful_charge_calculator_yesno
                    preraw=load(strcat('H:\extracted_values_modulebayHD\',current_load_file_preinduc,'____raw',suffixpreinduc));
                    %figure(100+presentcase),plot(preraw(:,1),'k'),hold on  %a small plot to check that the presyn trace to confirm that the startpoint is the same for each expt
                    %figure(presentcase),plot(preraw(:,2),'k'),hold on, title(current_load_file_preinduc)%plot of the postsyn trace to overlay preinduction and postinduction to confirm the amplitude scaling is the same for each
                    preraw=preraw(:,2:2:end);
                    preraw(:,current_delete_columns_preinduc)=[];
                    preinduction_raw=[preinduction_raw preraw];
                    vinn=create_basic_text_file_justforstimduration(current_load_file_preinduc);
                    preind_presyn_pulse_duration=[preind_presyn_pulse_duration vinn];
                end
                if careful_asynch_measurement_yesno
                    prerawasynchtracecrit=load(strcat('H:\extracted_values_modulebayHD\',current_load_file_preinduc,'__asynch_criterion_vals',suffixpreinduc));
                    prerawasynchtrace=prerawasynchtracecrit(:,[1:2:end]);
                    prerawasynchtrace(:,current_delete_columns_preinduc)=[];
                    preinduction_raw_asynch_trace=[preinduction_raw_asynch_trace prerawasynchtrace];
                    prerawasynchcriterion=prerawasynchtracecrit(:,[2:2:end]);
                    prerawasynchcriterion(:,current_delete_columns_preinduc)=[];
                    preinduction_raw_asynch_criterion=[preinduction_raw_asynch_criterion prerawasynchcriterion]; 
                end
            end
            if length(preind_presyn_pulse_duration)>1,preind_presyn_pulse_duration=max(preind_presyn_pulse_duration),end
            if size(preinduction_psc,2)~=size(preinduction_crit,2),disp(preinduction_files{presentcase,1}),error('preinduction criterion/psc size mismatch'),end;
            preinduction_patchtitle=strcat(preinduction_files{presentcase,1},preinduction_files{presentcase,3});
            if lookat_preinduc_ao_induc_ao_postinduc==1
                critmat_fullrange=[preinduction_crit];
                pscmat_fullrange=[preinduction_psc];
                trialcountmat_fullrange=size(preinduction_psc,2);
                patchtitle=preinduction_patchtitle;
                casecolor=str2num(preinduction_files{presentcase,7});
                asynchtracemat=[preinduction_raw_asynch_trace];
                asynchcriterionmat=[preinduction_raw_asynch_criterion];
            end
            general_info_files=preinduction_files;
		end
        
        if lookat_preinduc_ao_induc_ao_postinduc==2  %induction files are loaded within analyze_realtime
            patchtitle=induction_files{presentcase,1};
            casecolor=str2num(induction_files{presentcase,4});
        end
           
        if lookat_preinduc_ao_induc_ao_postinduc==3 || lookat_preinduc_ao_induc_ao_postinduc==7  %load the postinduction files
            namestartzpostinduc=findstr(postinduction_files{presentcase,1},'[');nameendzpostinduc=findstr(postinduction_files{presentcase,1},']');
            skipstartzpostinduc=findstr(postinduction_files{presentcase,2},'[');skipendzpostinduc=findstr(postinduction_files{presentcase,2},']');
            suffixpostinduc=strrep(postinduction_files{presentcase,3},'[','');suffixpostinduc=strrep(suffixpostinduc,']','');
            postinduction_psc=[];postinduction_crit=[];postinduction_raw=[];postind_presyn_pulse_duration=[];postinduction_raw_asynch_trace=[];postinduction_raw_asynch_criterion=[];
            for presentpostinducfile=1:length(namestartzpostinduc)
                current_load_file_postinduc=postinduction_files{presentcase,1}((namestartzpostinduc(presentpostinducfile)+1):(nameendzpostinduc(presentpostinducfile)-1));
                current_delete_columns_postinduc=str2num(postinduction_files{presentcase,2}((skipstartzpostinduc(presentpostinducfile)+1):(skipendzpostinduc(presentpostinducfile)-1)));
                c=load(strcat('H:\extracted_values_modulebayHD\',current_load_file_postinduc,'__pre-postPSC',suffixpostinduc));
                c(:,current_delete_columns_postinduc)=[];
                postinduction_psc=[postinduction_psc c];
                d=load(strcat('H:\extracted_values_modulebayHD\',current_load_file_postinduc,'__criterion_vals',suffixpostinduc));
                d(:,current_delete_columns_postinduc)=[];
                postinduction_crit=[postinduction_crit d];
                if careful_charge_calculator_yesno
                    postraw=load(strcat('H:\extracted_values_modulebayHD\',current_load_file_postinduc,'____raw',suffixpostinduc));
                    %figure(100+presentcase),plot(postraw(:,1),'r'),hold on  %a small plot to check that the presyn trace to confirm that the startpoint is the same for each expt
                    %figure(presentcase),plot(postraw(:,2),'r')    %plot of the postsyn trace to overlay preinduction and postinduction to confirm the amplitude scaling is the same for each
                    postraw=postraw(:,2:2:end);
                    postraw(:,current_delete_columns_postinduc)=[];
                    postinduction_raw=[postinduction_raw postraw];
                    ninn=create_basic_text_file_justforstimduration(current_load_file_postinduc);
                    postind_presyn_pulse_duration=[postind_presyn_pulse_duration ninn];
                end
                if careful_asynch_measurement_yesno
                    postrawasynchtracecrit=load(strcat('H:\extracted_values_modulebayHD\',current_load_file_postinduc,'__asynch_criterion_vals',suffixpostinduc));
                    postrawasynchtrace=postrawasynchtracecrit(:,[1:2:end]);
                    postrawasynchtrace(:,current_delete_columns_postinduc)=[];
                    postinduction_raw_asynch_trace=[postinduction_raw_asynch_trace postrawasynchtrace];
                    postrawasynchcriterion=postrawasynchtracecrit(:,[2:2:end]);
                    postrawasynchcriterion(:,current_delete_columns_postinduc)=[];
                    postinduction_raw_asynch_criterion=[postinduction_raw_asynch_criterion postrawasynchcriterion]; 
                end
                %y=load(strcat('H:\extracted_values_modulebayHD\',current_load_file_postinduc,'__presyn_I_Na_array'));
                %if~all(all(y)),disp(current_load_file_postinduc),error('Problem with presynaptic sodium current'), end
            end
            if length(postind_presyn_pulse_duration)>1,postind_presyn_pulse_duration=max(postind_presyn_pulse_duration),end
            if size(preinduction_psc,1)~=size(postinduction_psc,1),error('psc size mismatch'),end;
            if size(preinduction_crit,1)~=size(postinduction_crit,1),disp(postinduction_files{presentcase,1}),error('criterion size mismatch'),end;
            if size(postinduction_psc,2)~=size(postinduction_crit,2),error('postinduction criterion/psc size mismatch'),end;
            postinduction_patchtitle=strcat(postinduction_files{presentcase,1},postinduction_files{presentcase,3});
            casecolor=str2num(postinduction_files{presentcase,7});
            if lookat_preinduc_ao_induc_ao_postinduc==3
                critmat_fullrange=[postinduction_crit];
                pscmat_fullrange=[postinduction_psc];
                trialcountmat_fullrange=size(postinduction_psc,2);
                patchtitle=postinduction_patchtitle;
                general_info_files=postinduction_files;
                asynchtracemat=[postinduction_raw_asynch_trace];
                asynchcriterionmat=[postinduction_raw_asynch_criterion];
            elseif lookat_preinduc_ao_induc_ao_postinduc == 7
                critmat_fullrange=[preinduction_crit postinduction_crit];
                pscmat_fullrange=[preinduction_psc postinduction_psc];
                trialcountmat_fullrange=[size(preinduction_psc,2) size(postinduction_psc,2)];
                patchtitle=strcat(preinduction_patchtitle,postinduction_patchtitle);
                asynchtracemat=[preinduction_raw_asynch_trace postinduction_raw_asynch_trace];
                asynchcriterionmat=[preinduction_raw_asynch_criterion postinduction_raw_asynch_criterion];
            end
        end
        casecolor=clr(find(presentcase==casecheck),:);%overriding the colors from the database to use an hsv colormap
        %general_info_files{presentcase,4}=2;     %overriding the threshold setting from the database to use 2 (which is the maximum any of the cases are set to in the database)
        criterion_each_case=[criterion_each_case general_info_files{presentcase,4}];
        minutes_per_trial_each_case=[minutes_per_trial_each_case general_info_files{presentcase,5}];
               
        %finding the detection criterion and latency matrices
        [latenciez_fullrange,critz_fullrange]=find_detection_crits_and_latencies_generalizedform(critmat_fullrange,general_info_files{presentcase,4},general_info_files{presentcase,6});
        
        %finding the time windows
        [livetrials_preinduc_generalwindow,livetrials_postinduc_generalwindow,livetrials_preinduc_specificwindow,livetrials_postinduc_specificwindow,...
            tooshorttomeasure,tooshorttomeasurenames]=find_time_windows(general_time_window_before,general_time_window_after,str2num(preinduction_files{presentcase,8}),...
            str2num(postinduction_files{presentcase,8}),general_info_files{presentcase,5},pscmat_fullrange,trialcountmat_fullrange,patchtitle,tooshorttomeasurenames,ensure_equal_lengths)
		IPI_array_fullrange=pscmat_fullrange(1:2,:);
        rawmat_fullrange=[preinduction_raw,postinduction_raw];
        
        livetrials_preinduc_fullwindow=[1:trialcountmat_fullrange(1)];livetrials_postinduc_fullwindow=[1:trialcountmat_fullrange(2)]+trialcountmat_fullrange(1);
        full_time_window_before=[-1*round(trialcountmat_fullrange(1)*general_info_files{presentcase,5}) 0];full_time_window_after=[1 round(trialcountmat_fullrange(2)*general_info_files{presentcase,5})];
        
        pscmat_generalcontinuouswindowrange=pscmat_fullrange(:,[livetrials_preinduc_generalwindow(1):livetrials_postinduc_generalwindow(end)]);
        critz_generalcontinuouswindowrange=critz_fullrange(:,[livetrials_preinduc_generalwindow(1):livetrials_postinduc_generalwindow(end)]);
        trialcountmat_generalcontinuouswindowrange=[length(livetrials_preinduc_generalwindow) livetrials_postinduc_generalwindow(end)-livetrials_preinduc_generalwindow(end)];
        latenciez_generalcontinuouswindowrange=latenciez_fullrange(:,[livetrials_preinduc_generalwindow(1):livetrials_postinduc_generalwindow(end)]);
        
        pscmat_specificcontinuouswindowrange=pscmat_fullrange(:,[livetrials_preinduc_specificwindow(1):livetrials_postinduc_specificwindow(end)]);
        critz_specificcontinuouswindowrange=critz_fullrange(:,[livetrials_preinduc_specificwindow(1):livetrials_postinduc_specificwindow(end)]);
        trialcountmat_specificcontinuouswindowrange=[length(livetrials_preinduc_specificwindow) livetrials_postinduc_specificwindow(end)-livetrials_preinduc_specificwindow(end)];
        latenciez_specificcontinuouswindowrange=latenciez_fullrange(:,[livetrials_preinduc_specificwindow(1):livetrials_postinduc_specificwindow(end)]);
        %rawmat_specificcontinuouswindowrange=rawmat_fullrange(:,[livetrials_preinduc_specificwindow(1):livetrials_postinduc_specificwindow(end)]);
        
        pscmat_specificdiscretewindowrange=pscmat_fullrange(:,[livetrials_preinduc_specificwindow livetrials_postinduc_specificwindow]);
        critz_specificdiscretewindowrange=critz_fullrange(:,[livetrials_preinduc_specificwindow livetrials_postinduc_specificwindow]);
        trialcountmat_specificdiscretewindowrange=[length(livetrials_preinduc_specificwindow) length(livetrials_postinduc_specificwindow)];
        latenciez_specificdiscretewindowrange=latenciez_fullrange(:,[livetrials_preinduc_specificwindow livetrials_postinduc_specificwindow]);
        
        case_numbers_and_trialcountmats=[case_numbers_and_trialcountmats [presentcase;livetrials_preinduc_specificwindow(end);trialcountmat_fullrange(1);trialcountmat_fullrange(2);trialcountmat_specificcontinuouswindowrange(1);trialcountmat_specificcontinuouswindowrange(2);trialcountmat_specificdiscretewindowrange(1);trialcountmat_specificdiscretewindowrange(2)]];
        disp(patchtitle)
        
        if interval_selection_method==1
            pscmat=pscmat_fullrange;
            critz=critz_fullrange;
            trialcountmat=trialcountmat_fullrange;
            latenciez=latenciez_fullrange;
            livetrials_preinduc=livetrials_preinduc_fullwindow;livetrials_postinduc=livetrials_postinduc_fullwindow;
            time_window_before=full_time_window_before;time_window_after=full_time_window_after;
        elseif interval_selection_method==2 %this is for continuous postinduc window, not discrete
            pscmat=pscmat_generalcontinuouswindowrange;
            critz=critz_generalcontinuouswindowrange;
            trialcountmat=trialcountmat_generalcontinuouswindowrange;
            latenciez=latenciez_generalcontinuouswindowrange;
            livetrials_preinduc=livetrials_preinduc_generalwindow;livetrials_postinduc=[(livetrials_preinduc_generalwindow(end)+1):livetrials_postinduc_generalwindow(end)];
            time_window_before=general_time_window_before;time_window_after=[1 general_time_window_after(2)];
        elseif interval_selection_method==3
            pscmat=pscmat_specificcontinuouswindowrange;
            critz=critz_specificcontinuouswindowrange;
            trialcountmat=trialcountmat_specificcontinuouswindowrange;
            latenciez=latenciez_specificcontinuouswindowrange;
            livetrials_preinduc=livetrials_preinduc_specificwindow;livetrials_postinduc=[(livetrials_preinduc_specificwindow(end)+1):livetrials_postinduc_specificwindow(end)];
            time_window_before=str2num(preinduction_files{presentcase,8});time_window_after=str2num(postinduction_files{presentcase,8});time_window_after=[1 time_window_after(2)];
        elseif interval_selection_method==4
            pscmat=pscmat_specificdiscretewindowrange;
            critz=critz_specificdiscretewindowrange;
            trialcountmat=trialcountmat_specificdiscretewindowrange;
            latenciez=latenciez_specificdiscretewindowrange;
            livetrials_preinduc=livetrials_preinduc_specificwindow;livetrials_postinduc=livetrials_postinduc_specificwindow;
            time_window_before=str2num(preinduction_files{presentcase,8});time_window_after=str2num(postinduction_files{presentcase,8});
        end
        time_axis=[-1*(trialcountmat(1)-1):trialcountmat(2)]*(general_info_files{presentcase,5});
               
        if careful_asynch_measurement_yesno
           [asynch_count_by_trial,bgrd_asynch_count_by_trial,asynch_event_sizes_and_trials,bgrd_event_sizes_and_trials]=careful_asynch_measurer(general_info_files{presentcase,4},...
               asynchcriterionmat,asynchtracemat,trialcountmat_fullrange,livetrials_preinduc,livetrials_postinduc,presentcase,general_info_files{presentcase,5});
           if ~isempty(asynch_event_data_holder),[asynch_event_data_holder,asynch_event_sizes_and_trials]=match_num_rows_by_addition(asynch_event_data_holder,asynch_event_sizes_and_trials);end
           asynch_event_data_holder=[asynch_event_data_holder asynch_event_sizes_and_trials];
           if ~isempty(bgrd_event_data_holder),[bgrd_event_data_holder,bgrd_event_sizes_and_trials]=match_num_rows_by_addition(bgrd_event_data_holder,bgrd_event_sizes_and_trials);end
           bgrd_event_data_holder=[bgrd_event_data_holder bgrd_event_sizes_and_trials];
        else 
            asynch_count_by_trial=repmat(nan,1,size(pscmat,2));bgrd_asynch_count_by_trial=repmat(nan,1,size(pscmat,2));
        end
        if careful_charge_calculator_yesno
             if preind_presyn_pulse_duration~=postind_presyn_pulse_duration,disp(num2str([preind_presyn_pulse_duration postind_presyn_pulse_duration])),end
             for carefulcharge_interval_selection_method=interval_selection_method%1:5
                 for first_waveform_only=0
                     for success_waveforms_only=0%0:1
                         [array_of_charges,meanpreindwave,meanpostindwave,special_waveform_matrix_preinduc,special_waveform_matrix_postinduc]=careful_charge_calculator(livetrials_preinduc_generalwindow,livetrials_postinduc_generalwindow,...
                             livetrials_preinduc_specificwindow,livetrials_postinduc_specificwindow,IPI_array_fullrange,preinduction_raw,postinduction_raw,general_info_files{presentcase,3},general_info_files{presentcase,6}, patchtitle,casecolor,presentcase,...
                             max([preind_presyn_pulse_duration postind_presyn_pulse_duration]),carefulcharge_interval_selection_method,first_waveform_only,general_figure_position,critz_fullrange,success_waveforms_only,general_info_files{presentcase,5},...
                             general_info_files{presentcase,9},str2num(general_info_files{presentcase,10}));
                         if analyze_and_plot_mean_responses_charge_yesno && carefulcharge_interval_selection_method==1 && ~success_waveforms_only
                            mean_charge_and_error_matrix=analyze_and_plot_mean_responses(livetrials_preinduc_specificwindow,livetrials_postinduc_specificwindow,critz_fullrange,array_of_charges,casecolor,x_offset,70)    
                            mean_charge_and_error_matrices=[mean_charge_and_error_matrices mean_charge_and_error_matrix];    
                        end
                         if ~first_waveform_only && carefulcharge_interval_selection_method==1
                             [h_first,p_first,ci_first,stats_first]=ttest2(array_of_charges(1,livetrials_preinduc_specificwindow),array_of_charges(1,livetrials_postinduc_specificwindow));
                             first_ratio=mean(array_of_charges(1,livetrials_postinduc_specificwindow))/mean(array_of_charges(1,livetrials_preinduc_specificwindow));
                             [h_all,p_all,ci_all,stats_all]=ttest2(sum(array_of_charges(:,livetrials_preinduc_specificwindow)),sum(array_of_charges(:,livetrials_postinduc_specificwindow)));
                             summed_ratio=mean(sum(array_of_charges(:,livetrials_postinduc_specificwindow)))/mean(sum(array_of_charges(:,livetrials_preinduc_specificwindow)));
                             charge_p_value_holder=[charge_p_value_holder,[presentcase;h_first;p_first;first_ratio;h_all;p_all;summed_ratio]]
                             
                             [h_first_psc,p_first_psc,ci_first_psc,stats_first_psc]=ttest2(pscmat(3,livetrials_preinduc_specificwindow),pscmat(3,livetrials_postinduc_specificwindow));
                             first_ratio_psc=mean(pscmat(3,livetrials_postinduc_specificwindow))/mean(pscmat(3,livetrials_preinduc_specificwindow));
                             [h_all_psc,p_all_psc,ci_all_psc,stats_all_psc]=ttest2(sum(pscmat(3:end,livetrials_preinduc_specificwindow)),sum(pscmat(3:end,livetrials_postinduc_specificwindow)));
                             summed_ratio_psc=mean(sum(pscmat(3:end,livetrials_postinduc_specificwindow)))/mean(sum(pscmat(3:end,livetrials_preinduc_specificwindow)));
                             psc_p_value_holder=[psc_p_value_holder,[presentcase;h_first_psc;p_first_psc;first_ratio_psc;h_all_psc;p_all_psc;summed_ratio_psc]]
                         end
                     end
                 end
             end
             
             
        else
            %array_of_charges=array_of_charges_cell_array{presentcase};
            array_of_charges=repmat(nan,1,length(livetrials_preinduc)+length(livetrials_postinduc));
            meanpreindwave=nan;meanpostindwave=nan;special_waveform_matrix_preinduc=nan;special_waveform_matrix_postinduc=nan;
        end
        %array_of_charges_fullrange_cell_array{presentcase}=array_of_charges;%rawmat_cell_array{presentcase}=rawmat_specificcontinuouswindowrange;critz_cell_array{presentcase}=critz_specificcontinuouswindowrange;
        pscmat_cell_array{presentcase}=pscmat_specificcontinuouswindowrange; 
        special_waveforms_cell_array{1,presentcase}=special_waveform_matrix_preinduc;
        special_waveforms_cell_array{2,presentcase}=special_waveform_matrix_postinduc;
        
        end
        for iii=1:num_trials
            for jjj=1:num_APs
                
                load the waveforms(raw file) and the noise file, which must be created and which will contain at least 2 noise traces for use below
                
                
                find_multiple_peaks
                %if not multipeaked, plateau analyses (if multipeaked, split peaks and continue analysis)
                bootstrap_on_residuals, where does the observed plateau fit relative to all possible plateaux for this waveform?
                compare to bootstrap sim waveform with recombined noise having same peak -- where does observed plateau fit relative to the distribtuion of possible plateau?
        stored_jitters=montecarlo_jittered_events(measured_size,measured_riseplateau,successful_sims_required,maximum_possible_simulation_loops)
                compare to double waveforms with given jitter and recombined noise having same peak and plateau -- what does jitter distribution look like?
                
                %if not plateau, rise time analyses
                bootstrap_on_residuals, where does the observed rise time fit relative to all possible rise times for this waveform
                compare to bootstrap sim waveform with recombined noise having same peak -- where does rise time fall relative to the distribution of possible rise times
                compare to double waveforms with given jitter and recombined noise -- what does jitter distribution look like
                
                stored_jitters=montecarlo_jittered_events(measured_size,measured_riseplateau,successful_sims_required,maximum_possible_simulation_loops)
                
                n_o=noise_recombinase(n_i,splisiterequirements,find_unique_segments,breakpoints_mustbe_consecutive)
                
                template=iterative_curve_fit_singledecay(trace)
        
    else
        disp('No matching cases found')
    end
end

warning on MATLAB:divideByZero
toc

if batch_exporting
    batch_export_figures
end

%storing/displaying the record of what was queried & record of what was returned
if instant_archiving
	%fortherecord=strcat(selection_clauses{1},preinduction_files{:,1},'___',selection_clauses{2},induction_files{:,1},'___',selection_clauses{3},postinduction_files{:,1});
    %fortherecord=strcat(preinduction_files{:,1},'___',induction_files{:,1},'___',postinduction_files{:,1});
    dd=''; 
    for ii=1:size(preinduction_files,1), aa=preinduction_files{ii,1}; bb=induction_files{ii,1}; cc=postinduction_files{ii,1};  dd=strcat(dd,aa,'__',bb,'__',cc,'stop');  end
end

% 
%     
%     
% % fast_fits=[];
% % for jjj=1:size(fast_events_alltrials,1)
% %     fastemplate=iterative_curve_fit_singledecay(fast_events_alltrials(jjj,7:60));
% %     fast_fits=[fast_fits;fastemplate];
% % end
% % 
% % slow_fits=[];anz=[];
% % for ttt=1:size(slow_events_alltrials,1)
% %     slotemplate=iterative_curve_fit_singledecay(slow_events_alltrials(ttt,14:80));
% %     slow_fits=[slow_fits;slotemplate];
% %     gyu=size(slotemplate);
% %     latency=round(slotemplate(end-3));
% %     slotemplate=slotemplate-(slotemplate(end-4));
% %     anz=[anz;slotemplate(latency:latency+50)];
% % end
% % 
% % %anz=slotemplate(1,slotemplate(1,end-3):end-slotemplate(1,end-3))
% % clr=colormap(jet(size(anz,1)));figure(10),hold on
% % for bvd=1:size(anz,1)
% %     plot(anz(bvd,:),'color',clr(bvd,:))
% % end
% % %figure(10),plot(anz,'c','linewidth',3)
% % 
% % ccc=size(fast_fits)
% % %should remove any AP_o events before fitting, clustering -- knowledge of the number of pre APo events is a good ctrl, but after counting them get rid of them
% % 
% % figure
% % [g,h]=cumulative_histogram(-1*fast_fits(:,end-2),'b');
% % figure
% % [p,q]=cumulative_histogram(-1*slow_fits(:,end-2),'m');
% %     
% %     
% %     %skip all the above for now, fit the events detected with .45 thresh, with the fast template as seed, cluster the fits
% % %if cluster_fitted_curves
% % 
% % idx=kmeans(anz,2)
% % %fitss=[];while ~isempty(idx),fitss=[fitss idx(1:3)];idx(1:3)=[];end, fitss
% % %end
% % figure(11), hold on
% % couleur=colormap(jet(length(idx)));
% % for bbb=1:max(idx)
% %     gooduns=find(bbb==idx)
% %     for ccc=1:length(gooduns)
% %         plot(anz(gooduns(ccc),:),'color',couleur(bbb,:))
% %     end
% % end

 
% %[fast_events,number_of_fast_events_each_trial]=mini_waveform_extractor(asyn(:,column_adder+1),asyn(:,column_adder+2),fast_event_thresh,fast_event_jitter);
%     %[slow_events,number_of_slow_events_each_trial]=mini_waveform_extractor(asyn(:,column_adder+1),asyn(:,column_adder+3),slow_event_thresh,slow_event_jitter);
%     
%     
% 
% %find_multiple_peaks
%     %if not multipeaked, plateau analyses (if multipeaked, split peaks and continue analysis)
%     %bootstrap_on_residuals, where does the observed plateau fit relative to all possible plateaux for this waveform?
%     %compare to bootstrap sim waveform with recombined noise having same peak -- where does observed plateau fit relative to the distribtuion of possible plateau?
% 	%stored_jitters=montecarlo_jittered_events(measured_size,measured_riseplateau,successful_sims_required,maximum_possible_simulation_loops)
%     %compare to double waveforms with given jitter and recombined noise having same peak and plateau -- what does jitter distribution look like?
%     
%     %if not plateau, rise time analyses
%     %bootstrap_on_residuals, where does the observed rise time fit relative to all possible rise times for this waveform
%     %compare to bootstrap sim waveform with recombined noise having same peak -- where does rise time fall relative to the distribution of possible rise times
%     %compare to double waveforms with given jitter and recombined noise -- what does jitter distribution look like
%     
%     %stored_jitters=montecarlo_jittered_events(measured_size,measured_riseplateau,successful_sims_required,maximum_possible_simulation_loops)
%     
%     %n_o=noise_recombinase(n_i,splisiterequirements,find_unique_segments,breakpoints_mustbe_consecutive)
%     
%     %template=iterative_curve_fit_singledecay(trace)