function [asynchmats,bgrdasynchmats]=analyze_across_expts_workingcopy(cell_array_of_patchlogfilenames,query_style)
%description: queries the sql database and returns information on files matching the selection selection pattern;  loads the extracted data for each
%of these experiments, and runs analyses as directed by flags set at the beginning of the program
%called by: command line
%calls: 
%notes:
%code confirmed date: modification of analyze_across_expts_workingcopy expected; analyze_across_expts confirmed as of 

clearvars -except cell_array_of_patchlogfilenames
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=3;   %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;
ttest_psco_yesno=0;
     writettestresulttodatabase_yesno=0;
analyze_and_plot_mean_responses_psc_yesno=0;
analyze_sd_yesno=0;
careful_asynch_measurement_yesno=1;
careful_charge_calculator_yesno=0;
    analyze_and_plot_mean_responses_charge_yesno=0;
analyze_release_dependence_yesno=0;
analyze_correlation_between_successive_pscs_yesno=0;
analyze_autocorrelation_yesno=0;
analyze_history_dependence_yesno=0;
analyze_sd_over_time_yesno=0;
    use_psc_instead_of_charge_sdovertime=0;
analyze_diary_yesno=0;
    use_psc_instead_of_charge_diary=0;
analyze_realtime_yesno=0;
analyze_latencies_yesno=0;
analyze_size_distributions_yesno=0;
find_changepoint_yesno=0;
    num_bootstrap_runs=1000;
    num_permutations=1000;
    cp_ID_method=2;
    bootstrap_style=2;
batch_exporting=0;
instant_archiving=0;
general_figure_position=[30 40 1200 850];

%------------

%generating the query and querying the database to retrieve the appropriate filenames and other file info
%query styles: 1 = , 2 = second argument cell_array_of_patchlogfilenames should be a text string fragment of the file name, 3 = will be generated 4, it should
%be a cell array of file names
if nargin==2
    selection_clauses=query_generator(query_style, cell_array_of_patchlogfilenames)
elseif nargin==1
    selection_clauses=query_generator(3,cell_array_of_patchlogfilenames,'[]')   
elseif nargin==0
    selection_clauses=query_generator(3,'','[]')
end
[preinduction_files]=retrieve_data_from_sql_database(selection_clauses{1})
npre=size(preinduction_files,1);
if length(selection_clauses)>1
    [induction_files]=retrieve_data_from_sql_database(selection_clauses{2})
    [postinduction_files]=retrieve_data_from_sql_database(selection_clauses{3})
    nind=size(induction_files,1);npost=size(postinduction_files,1);
    if any(npre~=[nind npost]),a=npre, b=nind,c=npost,error('filesizemismatch'),end
end

%loop for loading and analyzing the data contained in the files with the names just retrieved
tooshorttomeasurenames=[];significantlydifferentbefafnames=[];summed_slopes_each_induction=[];charge_information_vector=[];cp_output_mat=[];
indiv_charges_by_sweep_preinduction=[];indiv_charges_by_sweep_postinduction=[];mean_sem_induc_matrix=[];mean_asym_sem_induc_matrix=[];
presentcases=[];asynch_event_data_holder=[];bgrd_event_data_holder=[];case_numbers_and_trialcountmats=[];charge_p_value_holder=[];psc_p_value_holder=[];
sd_ratio_diff_times=[];minutes_per_trial_each_case=[];mean_charge_and_error_matrices=[];mean_psc_and_error_matrices=[];criterion_each_case=[];sd_change_info_holder=[];
%array_of_charges_fullrange_cell_array={};%rawmat_cell_array={};critz_cell_array={};
mean_induction_traces={};slopes_each_induction={};individual_induction_traces_all_expts={};pscmat_cell_array={};special_waveforms_cell_array={};difftimes=[];
successes=[ 1     5     8    10    12    14     15     25    26    30]
failures=[2     7     9    27    28]
%succs_and_fails=[1     5     8    10    12    14     15     25    26    30 2     7     9    27    28];
succs_and_fails=[1 2 5 7 8 9 10 12 14 15 25 26 27 28 30];

casecheck=successes; clr=colors_for_stdp_expts(length(casecheck));
for presentcase=1:npre
    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('~/dwn_data_analysis_system/extracted_values_dwn/',current_load_file_preinduc,'__pre-postPSC',suffixpreinduc));
                a(:,current_delete_columns_preinduc)=[]; 
                preinduction_psc=[preinduction_psc a];
                %b=load(strcat('~/dwn_data_analysis_system/extracted_values_dwn/',current_load_file_preinduc,'__criterion_vals',suffixpreinduc));
                b=load(strcat('~/dwn_data_analysis_system/extracted_values_dwn/',current_load_file_preinduc,'__criteria_for_latency',suffixpreinduc));
                b(:,current_delete_columns_preinduc)=[];
                preinduction_crit=[preinduction_crit b];
                if careful_charge_calculator_yesno
                    preraw=load(strcat('~/dwn_data_analysis_system/extracted_values_dwn/',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('~/dwn_data_analysis_system/extracted_values_dwn/',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('~/dwn_data_analysis_system/extracted_values_dwn/',current_load_file_postinduc,'__pre-postPSC',suffixpostinduc));
                c(:,current_delete_columns_postinduc)=[];
                postinduction_psc=[postinduction_psc c];
                %d=load(strcat('~/dwn_data_analysis_system/extracted_values_dwn/',current_load_file_postinduc,'__criterion_vals',suffixpostinduc));
                d=load(strcat('~/dwn_data_analysis_system/extracted_values_dwn/',current_load_file_postinduc,'__criteria_for_latency',suffixpostinduc));
                d(:,current_delete_columns_postinduc)=[];
                postinduction_crit=[postinduction_crit d];
                if careful_charge_calculator_yesno
                    postraw=load(strcat('~/dwn_data_analysis_system/extracted_values_dwn/',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('~/dwn_data_analysis_system/extracted_values_dwn/',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('~/dwn_data_analysis_system/extracted_values_dwn/',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; disp('override threshold')    %overriding the threshold setting from 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}];
        
        %temporary inclusions for analysis of files not in the STDP dataset
        %preinduction_files{presentcase,8}='[-10 0]'
        %postinduction_files{presentcase,8}='[-10 0]'
        %general_info_files{presentcase,9}=[120]
        %if presentcase==4,general_info_files{presentcase,9}=[90],end
        %general_info_files{presentcase,10}='[1:10]'
        %casecolor=[.2 .2 .2]
               
        %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})
        
        time_axes{presentcase}=time_axis;
        pscmats{presentcase}=pscmat_fullrange(:,[livetrials_preinduc_specificwindow(1):livetrials_preinduc_specificwindow(end)]);
        critmats{presentcase}=critz_fullrange(:,[livetrials_preinduc_specificwindow(1):livetrials_preinduc_specificwindow(end)]);
               
        %t-test and comparison of means and SEMs
        if ttest_psco_yesno && ~tooshorttomeasure
             h=0;
             [h,p,ci,stats]=simpleteetester(pscmat_fullrange,livetrials_preinduc,livetrials_postinduc,writettestresulttodatabase_yesno,postinduction_files{presentcase,1},postinduction_files{presentcase,3});
             if h,significantlydifferentbefafnames=[significantlydifferentbefafnames,patchtitle];end
        end
        if analyze_and_plot_mean_responses_psc_yesno && ~tooshorttomeasure %& h
            mean_psc_and_error_matrix=analyze_and_plot_mean_responses(livetrials_preinduc_specificwindow,livetrials_postinduc_specificwindow,critz_fullrange,pscmat_fullrange(3:end,:),casecolor,x_offset,60);
            mean_psc_and_error_matrices=[mean_psc_and_error_matrices mean_psc_and_error_matrix];
        end       
        	
        %further analyses
        if analyze_sd_yesno %UNREAD AUG 2007
           analyze_sd(lookat_preinduc_ao_induc_ao_postinduc,pscmat,trialcountmat,critz,latenciez,general_info_files{presentcase,5},general_info_files{presentcase,6},casecolor,patchtitle,size(preinduction_files,1),presentcase);
        end
        if careful_asynch_measurement_yesno
           [asynch_count_by_trial,bgrd_asynch_count_by_trial,asynch_event_sizes_and_trials,bgrd_event_sizes_and_trials,preinduction_asynch_events,postinduction_asynch_events,...
               preinduction_bgrd_events,postinduction_bgrd_events]=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
        asynchmats{presentcase}=preinduction_asynch_events;
        bgrdasynchmats{presentcase}=preinduction_bgrd_events;
        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;
        if analyze_release_dependence_yesno
             if carefulcharge_interval_selection_method ~=1, error('need charge array from all trials'),end
             analyze_release_dependence(critz_fullrange,pscmat_fullrange,array_of_charges,trialcountmat_fullrange,livetrials_preinduc_specificwindow,livetrials_postinduc_specificwindow,...
                presentcase,casecolor,patchtitle,special_waveform_matrix_preinduc,special_waveform_matrix_postinduc)
        end
        if  analyze_correlation_between_successive_pscs_yesno
            analyze_correlation_between_successive_pscs(pscmat_fullrange,casecolor,livetrials_preinduc_specificwindow,livetrials_postinduc_specificwindow)
        end
        if analyze_autocorrelation_yesno
            analyze_autocorrelation(pscmat_fullrange(3,1:trialcountmat(1)),casecolor,patchtitle,presentcase,general_info_files{presentcase,5})
        end
        if analyze_history_dependence_yesno
            %array_of_charges=nan;special_waveform_matrix_preinduc=nan;special_waveform_matrix_postinduc=nan;
            analyze_history_dependence(pscmat_fullrange,critz_fullrange,array_of_charges,trialcountmat_fullrange,livetrials_preinduc_specificwindow,livetrials_postinduc_specificwindow,[special_waveform_matrix_preinduc,...
                special_waveform_matrix_postinduc],casecolor,presentcase,general_info_files{presentcase,6},patchtitle)           
        end
        if analyze_sd_over_time_yesno
            sd_ratio_windows=[1 5 10 15 20 25];
            for current_sd_ratio_window=1:length(sd_ratio_windows)
               [processed_sd,sd_ratio,sd_ratio_diff_time]=analyze_sd_over_time(time_axis,pscmat,critz,presentcase,general_info_files{presentcase,5},patchtitle,array_of_charges,...
                   use_psc_instead_of_charge_sdovertime,sd_ratio_windows,current_sd_ratio_window);
               %sd_ratio_diff_times=[sd_ratio_diff_times sd_ratio_diff_time];
               for sd_change_iteration=1:10
                   [numshuffles_neededfor_largerdiffthanorigdata,timemaxoriginaldif]=finding_confidence_for_timeofchangeinSTSD(sd_ratio(find(time_axis>=0)),...
                       round(sd_ratio_windows(current_sd_ratio_window)*inv(general_info_files{presentcase,5})),processed_sd(1,:),processed_sd(2,:));
                   sd_change_info_holder(presentcase,sd_change_iteration,current_sd_ratio_window)=numshuffles_neededfor_largerdiffthanorigdata;
                   difftimes=[difftimes,timemaxoriginaldif*general_info_files{presentcase,5}]
               end
           end
        else
            processed_sd=nan;sd_ratio=nan;
        end
        if analyze_diary_yesno%--
            [reliability,mean_potency]=analyze_diary(critz,general_info_files{presentcase,5},general_info_files{presentcase,6},pscmat,patchtitle,trialcountmat,casecolor,presentcase,asynch_count_by_trial,...
                bgrd_asynch_count_by_trial,array_of_charges,general_figure_position,str2num(preinduction_files{presentcase,8}),str2num(postinduction_files{presentcase,8}),sd_ratio,processed_sd,use_psc_instead_of_charge_diary);
        end
        if analyze_realtime_yesno
            individual_induction_traces=analyze_realtime(induction_files{presentcase,1},(1000/induction_files{presentcase,2}),induction_files{presentcase,3},casecolor,'-',presentcase,...
                meanpreindwave,meanpostindwave,general_figure_position);
            %summed_slopes_each_induction=[summed_slopes_each_induction sum(slopes_this_induction)];
            %mean_induction_traces{presentcase}=mean_induction_trace;
            individual_induction_traces_all_expts{presentcase}=individual_induction_traces;
            %slopes_each_induction{presentcase}=slopes_this_induction;
        end
        if analyze_latencies_yesno
            latency_summarizer(latenciez_fullrange,presentcase,{[livetrials_preinduc_specificwindow] [(livetrials_preinduc_specificwindow(end)+1):...
                livetrials_postinduc_specificwindow(end)]});
        end
        if analyze_size_distributions_yesno
            a=size(pscmat),b=size(critz),c=size(array_of_charges)
            analyze_size_distributions(pscmat_fullrange(3:end,:),array_of_charges,critz_fullrange,presentcase,[-1000:1000],{[livetrials_preinduc_specificwindow] [(livetrials_preinduc_specificwindow(end)+1):...
                livetrials_postinduc_specificwindow(end)]});
        end
        if find_changepoint_yesno   
            num_trials_first_epoch=trialcountmat(1)
            total_q=sum(array_of_charges)
            max_q=max(array_of_charges)
            q_o=array_of_charges(1,:)
            q_a=array_of_charges(2,:)
            q_b=array_of_charges(3,:)
            if general_info_files{presentcase,6}==4
               q_c=array_of_charges(4,:)
            else
               q_c=rand(1,size(array_of_charges,2))
            end
            pr_o=critz(1,:)
            pot_q_o=q_o;pot_q_o(find(~pr_o))=0;
            pot_q_o=replace_zeros(pot_q_o);
            aretherezeros=mean_potency
            mean_pot_without_zero=replace_zeros(mean_potency)
            %error('t')
            if size(pr_o)~=size(max_q),error('size problems'),end
            aa=mean_potency
            bb=time_axis
            meanpotpostinduconly=mean_potency(find(~time_axis):end)
            
%             %---preinduc only, for stability checks
%             pscmat=pscmat(:,1:trialcountmat(1));
%             array_of_charges=array_of_charges(:,1:trialcountmat(1));
%             q_o=array_of_charges(1,:);
%             reliability=reliability(:,1:trialcountmat(1));
%             mean_potency=mean_potency(:,1:trialcountmat(1));
            
          [cp_occur_conf_psc_o,cp_psc_o,tempwin_psc_o]=change_point_analysis_formal_method(pscmat(3,:),num_bootstrap_runs,num_permutations,cp_ID_method,bootstrap_style);
            %cp_psc_o=cp_psc_o-num_trials_first_epoch;tempwin_psc=tempwin_psc-num_trials_first_epoch;
%             [cp_occur_conf_totalq,cp_totalq,tempwin_totalq]=change_point_analysis_formal_method(total_q,num_bootstrap_runs,num_permutations,cp_ID_method,bootstrap_style);
%             cp_totalq=cp_totalq-num_trials_first_epoch;tempwin_totalq=tempwin_totalq-num_trials_first_epoch;
%              [cp_occur_conf_maxq,cp_maxq,tempwin_maxq]=change_point_analysis_formal_method(max_q,num_bootstrap_runs,num_permutations,cp_ID_method,bootstrap_style);
%             cp_maxq=cp_maxq-num_trials_first_epoch;tempwin_maxq=tempwin_maxq-num_trials_first_epoch;
          [cp_occur_conf_q_o,cp_q_o,tempwin_q_o]=change_point_analysis_formal_method(q_o,num_bootstrap_runs,num_permutations,cp_ID_method,bootstrap_style);
            %cp_q_o=cp_q_o-num_trials_first_epoch;tempwin_q_o=tempwin_q_o-num_trials_first_epoch;
%              [cp_occur_conf_q_a,cp_q_a,tempwin_q_a]=change_point_analysis_formal_method(q_a,num_bootstrap_runs,num_permutations,cp_ID_method,bootstrap_style);
%             cp_q_a=cp_q_a-num_trials_first_epoch;tempwin_q_a=tempwin_q_a-num_trials_first_epoch;
%              [cp_occur_conf_q_b,cp_q_b,tempwin_q_b]=change_point_analysis_formal_method(q_b,num_bootstrap_runs,num_permutations,cp_ID_method,bootstrap_style);
%             cp_q_b=cp_q_b-num_trials_first_epoch;tempwin_q_b=tempwin_q_b-num_trials_first_epoch;
%              [cp_occur_conf_q_c,cp_q_c,tempwin_q_c]=change_point_analysis_formal_method(q_c,num_bootstrap_runs,num_permutations,cp_ID_method,bootstrap_style);
%             cp_q_c=cp_q_c-num_trials_first_epoch;tempwin_q_c=tempwin_q_c-num_trials_first_epoch;
             [cp_occur_conf_rel,cp_rel,tempwin_rel]=change_point_analysis_formal_method(reliability,num_bootstrap_runs,num_permutations,cp_ID_method,bootstrap_style);
            %cp_rel=cp_rel-num_trials_first_epoch;tempwin_rel=tempwin_rel-num_trials_first_epoch;
          [cp_occur_conf_pot,cp_pot,tempwin_pot]=change_point_analysis_formal_method(mean_potency,num_bootstrap_runs,num_permutations,cp_ID_method,bootstrap_style);
            %cp_pot=cp_pot-num_trials_first_epoch;tempwin_pot=tempwin_pot-num_trials_first_epoch;
%              [cp_occur_conf_processed_sd1,cp_processed_sd1,tempwin_processed_sd1]=change_point_analysis_formal_method(processed_sd(1,:),num_bootstrap_runs,num_permutations,cp_ID_method,bootstrap_style);
%             cp_processed_sd1=cp_processed_sd1-num_trials_first_epoch;tempwin_processed_sd1=tempwin_processed_sd1-num_trials_first_epoch;
%              [cp_occur_conf_processed_sd2,cp_processed_sd2,tempwin_processed_sd2]=change_point_analysis_formal_method(processed_sd(2,:),num_bootstrap_runs,num_permutations,cp_ID_method,bootstrap_style);
%             cp_processed_sd2=cp_processed_sd2-num_trials_first_epoch;tempwin_processed_sd2=tempwin_processed_sd2-num_trials_first_epoch;
%              [cp_occur_conf_sdratio,cp_sdratio,tempwin_sdratio]=change_point_analysis_formal_method(sd_ratio,num_bootstrap_runs,num_permutations,cp_ID_method,bootstrap_style);
%             cp_sdratio=cp_sdratio-num_trials_first_epoch;tempwin_sdratio=tempwin_sdratio-num_trials_first_epoch;
%              [cp_occur_conf_negsdratio,cp_negsdratio,tempwin_negsdratio]=change_point_analysis_formal_method(-1*sd_ratio,num_bootstrap_runs,num_permutations,cp_ID_method,bootstrap_style);
%             cp_negsdratio=cp_negsdratio-num_trials_first_epoch;tempwin_negsdratio=tempwin_negsdratio-num_trials_first_epoch;
%             [cp_occur_conf_asynch,cp_asynch,tempwin_asynch]=change_point_analysis_formal_method(asynch_count_by_trial,num_bootstrap_runs,num_permutations,cp_ID_method,bootstrap_style);
%             cp_asynch=cp_asynch-num_trials_first_epoch;tempwin_asynch=tempwin_asynch-num_trials_first_epoch;
%             [cp_occur_conf_bgrdasynch,cp_bgrdasynch,tempwin_bgrdasynch]=change_point_analysis_formal_method(bgrd_asynch_count_by_trial,num_bootstrap_runs,num_permutations,cp_ID_method,bootstrap_style);
%             cp_bgrdasynch=cp_bgrdasynch-num_trials_first_epoch;tempwin_bgrdasynch=tempwin_bgrdasynch-num_trials_first_epoch;
% 			 [cp_occur_conf_pr_o,cp_pr_o,tempwin_pr_o]=change_point_analysis_formal_method(pr_o,num_bootstrap_runs,num_permutations,cp_ID_method,bootstrap_style);
%             cp_pr_o=cp_pr_o-num_trials_first_epoch;tempwin_pr_o=tempwin_pr_o-num_trials_first_epoch;
%              [cp_occur_conf_pot_q_o,cp_pot_q_o,tempwin_pot_q_o]=change_point_analysis_formal_method(pot_q_o,num_bootstrap_runs,num_permutations,cp_ID_method,bootstrap_style);
%             cp_pot_q_o=cp_pot_q_o-num_trials_first_epoch;tempwin_pot_q_o=tempwin_pot_q_o-num_trials_first_epoch;
%              
          [cp_occur_conf_mean_pot_without_zero,cp_mean_pot_without_zero,tempwin_mean_pot_without_zero]=change_point_analysis_formal_method(mean_pot_without_zero,num_bootstrap_runs,num_permutations,cp_ID_method,bootstrap_style);
%             cp_mean_pot_without_zero=cp_mean_pot_without_zero-num_trials_first_epoch;tempwin_mean_pot_without_zero=tempwin_mean_pot_without_zero-num_trials_first_epoch;
                %[cp_occur_conf_postinducpotency,cp_postinducpotency,tempwin_postinducpotency]=change_point_analysis_formal_method(meanpotpostinduconly,num_bootstrap_runs,num_permutations,cp_ID_method,bootstrap_style);
               %cp_postinducpotency=cp_postinducpotency-num_trials_first_epoch;tempwin_postinducpotency=tempwin_postinducpotency-num_trials_first_epoch;
            
            cp_output_thistrial=[general_info_files{presentcase,4};presentcase];
            cp_output_thistrial=[cp_output_thistrial;cp_occur_conf_psc_o;cp_psc_o;tempwin_psc_o(1);tempwin_psc_o(2)];
%             cp_output_thistrial=[cp_output_thistrial;cp_occur_conf_totalq;cp_totalq;tempwin_totalq(1);tempwin_totalq(2)];
%             cp_output_thistrial=[cp_output_thistrial;cp_occur_conf_maxq;cp_maxq;tempwin_maxq(1);tempwin_maxq(2)];
            cp_output_thistrial=[cp_output_thistrial;cp_occur_conf_q_o;cp_q_o;tempwin_q_o(1);tempwin_q_o(2)];
%             cp_output_thistrial=[cp_output_thistrial;cp_occur_conf_q_a;cp_q_a;tempwin_q_a(1);tempwin_q_a(2)];
%             cp_output_thistrial=[cp_output_thistrial;cp_occur_conf_q_b;cp_q_b;tempwin_q_b(1);tempwin_q_b(2)];
%             cp_output_thistrial=[cp_output_thistrial;cp_occur_conf_q_c;cp_q_c;tempwin_q_c(1);tempwin_q_c(2)];
            cp_output_thistrial=[cp_output_thistrial;cp_occur_conf_rel;cp_rel;tempwin_rel(1);tempwin_rel(2)];
            cp_output_thistrial=[cp_output_thistrial;cp_occur_conf_pot;cp_pot;tempwin_pot(1);tempwin_pot(2)];
%             cp_output_thistrial=[cp_output_thistrial;cp_occur_conf_processed_sd1;cp_processed_sd1;tempwin_processed_sd1(1);tempwin_processed_sd1(2)];
%             cp_output_thistrial=[cp_output_thistrial;cp_occur_conf_processed_sd2;cp_processed_sd2;tempwin_processed_sd2(1);tempwin_processed_sd2(2)];
%             cp_output_thistrial=[cp_output_thistrial;cp_occur_conf_sdratio;cp_sdratio;tempwin_sdratio(1);tempwin_sdratio(2)];
%             cp_output_thistrial=[cp_output_thistrial;cp_occur_conf_negsdratio;cp_negsdratio;tempwin_negsdratio(1);tempwin_negsdratio(2)];
%             cp_output_thistrial=[cp_output_thistrial;cp_occur_conf_pr_o;cp_pr_o;tempwin_pr_o(1);tempwin_pr_o(2)];
%             cp_output_thistrial=[cp_output_thistrial;cp_occur_conf_pot_q_o;cp_pot_q_o;tempwin_pot_q_o(1);tempwin_pot_q_o(2)];
            cp_output_thistrial=[cp_output_thistrial;cp_occur_conf_mean_pot_without_zero;cp_mean_pot_without_zero;tempwin_mean_pot_without_zero(1);tempwin_mean_pot_without_zero(2)];
%                cp_output_thistrial=[cp_output_thistrial;cp_occur_conf_postinducpotency;cp_postinducpotency;tempwin_postinducpotency(1);tempwin_postinducpotency(2)];
            
            cp_output_mat=[cp_output_mat cp_output_thistrial]
            
            
            clkchk=clock;
            save('clockcheck','clkchk','-ascii','-tabs','-double')
            save('cp_output_mat_by_trial','cp_output_mat','-ascii','-tabs','-double')
        end
        else
        disp('No matching cases found')
    end
    close all    
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