% TODO 
% add option for user to change screen resolution in watching traces.
% make sure that if a neuron has several stable points they all can be
% plotted and analyzed.

% This is the main function used for the single unit analysis. I based it
% to some extent on Eitan Schechtman's "neuron_profile.m"

% This code will receive the following: 
% - Electrode structure (from the processed data storage - containing the 
%   single unit *digital* information, i.e.locations of spikes for the 
%   whole time period of the recorded cell.
%   * electrode(x,1).channel(x,1).unit.Spikes
%   * electrode(x,1).channel(x,1).unit.StablStartTime + StableStopTime
% - elec_num, channel_num and unit_num to be analyzed.
% - generalInfo structure - containing the SAMPLING variable (sampling frequency).
% - polysomnography structure - containing the staging for the entire
%   session when the unit was recorded.
% Finally, the code will provide a cell array sized 6XN, N being the number
% of bins (10, 30, 60 seconds. Didn't decide yet) along which the cell has 
% been recorded. The rows of this matrix will be as follows:
% 1. Sleep Stages - 'W','N1','N2','N3' or 'R'.
% 2. FR
% 3. CV
% 4. Pause Probability
% 5. Pause Frequency
% 6. LFP-spike Phase locking measure.
% Then, the program will draw those measures along 30 sec segments, plot
% the results and save them accordingly.

% Algorithm
% =========
% PSTH
% ----
% 1. smooth the digital data OR average on 30 seconds (I'm not sure
% smoothing is relevant if you average such a vast length)
% 2. Receive the staging from the code I have previously wrote, and plot
% these together.
% 3. Have an option to average on different units.
% 4. 2. Insert results to the general data matrix.

% CV
% --
% 1. Compute CV per 30 second segments. 
% 2. Receive the staging from the code I have previously wrote, and plot
% these together.
% 3. Insert results to the general data matrix.

% Pause Probability and Frequency
% -------------------------------
% 1. Use Elias's surprise method to locate pauses.
% 2. Compute Probability and Frequency.
% 3. Receive the staging from the code I have previously wrote, and plot
% these together.

% PHASE LOCKING ANALYSIS
% ----------------------
% 1. Find specific places where the LFP has beta, gamma etc. activity.
% 2. Specifically in those places, look at the spike discharge and check
%    if the spikes are locked to specific phases of the oscillatory
%    activity.

% when profile_type=1 - normal sleep analysis with no events
% profile_type=2 - "Events" must be given to the algorithm. Another GUI platform
% will allow the user to choose the specific analysis, so neuron_profile
% will receive only a specific "kind" of event a time (e.g. "Aversive cue
% presentation" with a series of required analyses, specified by
% binsize_vector as for the sleep analysis. Event will be a cell with two
% equal length vectors - "begin" and "end", with she samples where these
% events started.
% profile_type=3 - Event related analysis.

function Neuron_Profile_Aviv (filenames,unit,Event,Info,Datafiles,ElecNum,ChannelNum,UnitNum,polysomnography,binsize_vec,singleOrmulti,overlap_smoothing_settings)
    
    monkey=1;                           % 1=Daenerys % 2 = Nymeria
    nucleus='GPe';
    
    if ~iscell(unit)
        unit={unit};
    end;
    if ~iscell(filenames)
        filenames={filenames};
    end;
    if ~iscell(Event)
        Event={Event};
    end;
    if ~iscell(Info)
        Info={Info};
    end;
    stage_length=cell(1,length(unit));
    
    if binsize_vec(1,10) || binsize_vec(1,8) % a little trick to allow me to erase vars in the end of every unit calculation to save memory
        save('C:\Aviv\Sleep\Code\Main\BACKUP_FILES_FOR_CROSS_CORRELATION','Datafiles','Info','filenames','polysomnography','unit')
    end 
  
    if (strcmp(nucleus,'GPe') || strcmp(nucleus,'GPi') || strcmp(nucleus,'SNr'))
        min_num_of_spikes_per_10_seconds=0;
    elseif (strcmp(nucleus,'STN') || strcmp(nucleus,'Thalamus'))
        min_num_of_spikes_per_10_seconds=0;
    elseif strcmp(nucleus,'Cortex')
        min_num_of_spikes_per_10_seconds=0;        
    elseif strcmp(nucleus,'MSN')
        min_num_of_spikes_per_10_seconds=0;                
    end
    
    No_pause_analysis=0; % An idea we had was to check whether what we see is a consequence of the pause activity. So, this analysis will delete all the pauses from the data and redo all analyses. See further.
    pauser=0;
    burster=1;
    LFP_to_unit_analysis=0; % spike locking on LFP SW not as part of the pair analysis, but as part of the unit analysis
    Prune_BG_spikes_for_PS_analysis=0;
    num_of_reps_for_pruning=10;
    Analyze_EEG_to_FR_SW_correlation=0;
    Analyze_spike_to_EEG_SW_phase_locking=0;
    destination_FR_for_pruning=5; % elliminate 80% of spikes
    Calculate_EEG_spectrum_all_stages=0;
    Check_polysomnogrphy_EEG_for_figure_1=0;
    percent_thresh_for_SW_definition_LFP=50; % changed 061617, used to be 50
    percent_thresh_for_SW_definition_FR=50; % changed 061617, used to be 50
    minimum_energy_threshold_for_FR=0.03;
    bandpass_SW=[0.1,2]; % used to be 0.1
    bandstop_SW=[0.05,2.5]; % used to be 0.05
    bandpass_wider=[0.1,40]; % used to be 0.1
    bandstop_wider=[0.05,50]; % used to be 0.05    
    calculate_EEG_measures=0; %071817
    if LFP_to_unit_analysis % 062517
        dsmp_factor_Local_LFP=32;
    else
        dsmp_factor_Local_LFP=1;
    end
    if monkey==1
        wave_amplitude_min_thresh=40; % microvolts.  CHANGE!!!!!!! back to 40
    elseif monkey==2
        wave_amplitude_min_thresh=40; % microvolts. CHANGE!!!!!! back to 50
    end
    bitre=38.1470/20;
    N3_fraction=0.2; %0.1     
    firing_rate_amp_thresh_for_SW_definition=nan(1,length(unit));
        
if Event{1,1}==0
    data2plot=struct('FR',[],'CV',[],'pause',[],'AutoCorrelation',[],'LFP_spike',[],'SignalCorrelation',[],'NoiseCorrelation',[],'Pause_locked_PSTH',[],'CrossCorrelation',[]);
    all_stage_corrected=nan(2,length(unit));
    for unitnum=1:length(unit)
            % first step for every unit would be to update the stablestarttime and 
            % the stablestoptime to correspond to the beginning of the first, and 
            % ending of the last, polysomnographic stage. This is done to ensure 
            % that when the entire period is divided to 1-, 2-, 5-, 10-sec periods, 
            % these whole periods will be maximally contained in one stage, that is 
            % to prevent a situation where, for example, for a 5-sec segment, it
            % accidentally began in the end of N2 and ended in the beginning of N3, 
            % and then 2.5 secs of it will erroneously considered N3 (or N2). This 
            % will "dilute" the results. 012716, all appearances of StableStartTime 
            % and StableStopTime were updated to _stagecorrected.
            unit{unitnum}.StableStartTime_stagecorrected=unit{unitnum}.StableStartTime;
            unit{unitnum}.StableStopTime_stagecorrected=unit{unitnum}.StableStopTime;
            for kk=1:length(unit{unitnum}.StableStartTime)
                if strcmp(filenames{1,unitnum}(1,strfind(filenames{1,unitnum},'Data')+5:strfind(filenames{1,unitnum},'Data')+10),'091515')
                    unit{unitnum}.StableStartTime_stagecorrected(kk)=polysomnography{unitnum}.all_beginnings(max(3,find(polysomnography{unitnum}.all_beginnings>=unit{unitnum}.StableStartTime(kk),1,'first'))); % see readme in the relevant folder
                    unit{unitnum}.StableStopTime_stagecorrected(kk)=polysomnography{unitnum}.all_ends(find(polysomnography{unitnum}.all_ends<=unit{unitnum}.StableStopTime(kk),1,'last'));
                else
                    unit{unitnum}.StableStartTime_stagecorrected(kk)=polysomnography{unitnum}.all_beginnings(find(polysomnography{unitnum}.all_beginnings>=unit{unitnum}.StableStartTime(kk),1,'first'));
                    unit{unitnum}.StableStopTime_stagecorrected(kk)=polysomnography{unitnum}.all_ends(find(polysomnography{unitnum}.all_ends<=unit{unitnum}.StableStopTime(kk),1,'last'));
                end
            end
            % This next piece of code was addded 030117. The reason is that the way FR_begin_samples would be determined was in order to
            % coincide with the existing polysomnography.all_beginnings. This was so that the sleep stages will overlap with the bins
            % of the unit. The problem is that sometimes you would get that two consecutive all_beginnings would not have 440000 samples (10
            % seconds) between them, but more. This is probably the result of hiccups in file switches etc. So, the bins were very close
            % to the beginnings until the hiccup and then there would have formes a constant >1000 samples difference between the
            % FR_begin and the closest all_beginnings and this would disqualify the bin. In this way I lost many bins. Yhe
            % solution to this problem is making sure that whenever a non-440000 samples length difference existed between two
            % consecutive all_beginnings, I would start another stable period for the unit, starting from right after the
            % probalematic difference. This is what this code does. For each problematic difference, if it too close to the beginning
            % or end of the unit then it would ust start or end the unit there, respectively, and if it is in the middle it would
            % break the current stable period in two. kk is the index of the original stable periods in the unit and dd is the index
            % of problematic differences. whenever two problematic difference were too close, I regarded them as one. This
            % corresponds to the "continue" part and the move_to_next logical.
            clear kk
            length_of_one_polysomnography_segment=10; % sec FROM HERE to next "UNTIL HERE" - added 030117 to prevent the situation where the starts of bins loose synchronization with the start of polysomnography beginnings because of "glitches" in polysomnography.all_beginnings
            unit{unitnum}.StableStartTime_stagecorrected_diffcorrected=unit{unitnum}.StableStartTime_stagecorrected;
            unit{unitnum}.StableStopTime_stagecorrected_diffcorrected=unit{unitnum}.StableStopTime_stagecorrected;
            for kk=1:length(unit{unitnum}.StableStartTime_stagecorrected)
                relevant_beginnings=polysomnography{unitnum}.all_beginnings(find(polysomnography{unitnum}.all_beginnings>=unit{unitnum}.StableStartTime_stagecorrected(kk) & polysomnography{unitnum}.all_ends<=unit{unitnum}.StableStopTime_stagecorrected(kk)));
                relevant_endings=polysomnography{unitnum}.all_ends(find(polysomnography{unitnum}.all_beginnings>=unit{unitnum}.StableStartTime_stagecorrected(kk) & polysomnography{unitnum}.all_ends<=unit{unitnum}.StableStopTime_stagecorrected(kk)));
                begin_sample_diffs=diff(relevant_beginnings);
                deviations_from_full_segment=abs(begin_sample_diffs-44000*length_of_one_polysomnography_segment);
                deviate=find(deviations_from_full_segment>=1001);
                move_to_next=0;
                added_segment=0;
                for dd=1:length(deviate)
                    if move_to_next==1
                        move_to_next=0;
                        continue;
                    else
                        if ((deviate(dd)>=4) && (deviate(dd)<=length(relevant_beginnings)-3))
                            if size(unit{unitnum}.StableStartTime_stagecorrected_diffcorrected)==1 % to take care of a bug that has to do with the shape of the Spike vector in units with more than 1 stable period.
                                if size(unit{unitnum}.Spikes,1)~=1
                                    unit{unitnum}.Spikes=unit{unitnum}.Spikes';                           
                                end
                            end
                            if ((dd~=length(deviate)) && (deviate(dd+1)-deviate(dd)<=4))
                                unit{unitnum}.StableStartTime_stagecorrected_diffcorrected=[unit{unitnum}.StableStartTime_stagecorrected(1:kk+added_segment),relevant_beginnings(deviate(dd+1)+1),unit{unitnum}.StableStartTime_stagecorrected(kk+1+added_segment:end)];
                                unit{unitnum}.StableStopTime_stagecorrected_diffcorrected=[unit{unitnum}.StableStopTime_stagecorrected(1:kk-1+added_segment),relevant_endings(deviate(dd)-1),unit{unitnum}.StableStopTime_stagecorrected(kk+added_segment:end)];                                
                                move_to_next=1;
                                added_segment=added_segment+1;
                            else
                                unit{unitnum}.StableStartTime_stagecorrected_diffcorrected=[unit{unitnum}.StableStartTime_stagecorrected(1:kk+added_segment),relevant_beginnings(deviate(dd)+1),unit{unitnum}.StableStartTime_stagecorrected(kk+1+added_segment:end)];
                                unit{unitnum}.StableStopTime_stagecorrected_diffcorrected=[unit{unitnum}.StableStopTime_stagecorrected(1:kk-1+added_segment),relevant_endings(deviate(dd)-1),unit{unitnum}.StableStopTime_stagecorrected(kk+added_segment:end)];                                
                                added_segment=added_segment+1;
                            end
                        elseif deviate(dd)<4
                            if ((dd~=length(deviate)) && (deviate(dd+1)-deviate(dd)<=4))
                                unit{unitnum}.StableStartTime_stagecorrected_diffcorrected=unit{unitnum}.StableStartTime_stagecorrected;
                                unit{unitnum}.StableStartTime_stagecorrected_diffcorrected(kk+added_segment)=relevant_beginnings(deviate(dd+1)+1);
                                move_to_next=1;
                            else
                                unit{unitnum}.StableStartTime_stagecorrected_diffcorrected=unit{unitnum}.StableStartTime_stagecorrected;
                                unit{unitnum}.StableStartTime_stagecorrected_diffcorrected(kk+added_segment)=relevant_beginnings(deviate(dd)+1);
                            end
                        elseif deviate(dd)>length(relevant_beginnings)-3
                            if ((dd~=length(deviate)) && (deviate(dd+1)-deviate(dd)<=4))
                                unit{unitnum}.StableStopTime_stagecorrected_diffcorrected=unit{unitnum}.StableStopTime_stagecorrected;
                                unit{unitnum}.StableStopTime_stagecorrected_diffcorrected(kk+added_segment)=relevant_endings(deviate(dd)-1);                                                                
                                move_to_next=1;                                
                            else
                                unit{unitnum}.StableStopTime_stagecorrected_diffcorrected=unit{unitnum}.StableStopTime_stagecorrected;
                                unit{unitnum}.StableStopTime_stagecorrected_diffcorrected(kk+added_segment)=relevant_endings(deviate(dd)-1);                                
                            end
                        end
                    end
                    unit{unitnum}.StableStartTime_stagecorrected=unit{unitnum}.StableStartTime_stagecorrected_diffcorrected;
                    unit{unitnum}.StableStopTime_stagecorrected=unit{unitnum}.StableStopTime_stagecorrected_diffcorrected;
                end
            end
            unit{unitnum}.StableStartTime_stagecorrected=unit{unitnum}.StableStartTime_stagecorrected_diffcorrected;
            unit{unitnum}.StableStopTime_stagecorrected=unit{unitnum}.StableStopTime_stagecorrected_diffcorrected;  % UNTIL HERE          
            first_stable_sample=unit{unitnum}.StableStartTime_stagecorrected;
            last_stable_sample=unit{unitnum}.StableStopTime_stagecorrected;
            all_stage_corrected(1,unitnum)=first_stable_sample(1);
            all_stage_corrected(2,unitnum)=last_stable_sample(end);
            
            % find the length of periods of time for the W, N1, N2, N3 and R recordings.
            disp(['unitnum=',num2str(unitnum)])
           
            % find pauses for all stable periods to avoid multiple calls to pause_detect
            stablespikes=unit{unitnum}.Spikes(find(sum((repmat(unit{unitnum}.Spikes',1,size(unit{unitnum}.StableStartTime_stagecorrected,2))>=repmat(unit{unitnum}.StableStartTime_stagecorrected,size(unit{unitnum}.Spikes,2),1)).*(repmat(unit{unitnum}.Spikes',1,size(unit{unitnum}.StableStopTime_stagecorrected,2))<=repmat(unit{unitnum}.StableStopTime_stagecorrected,size(unit{unitnum}.Spikes,2),1)),2)));
            tempindexedspikes=stablespikes;
            for ii=1:length(unit{unitnum}.StableStartTime_stagecorrected)-1
                tempindexedspikes(stablespikes>unit{unitnum}.StableStopTime_stagecorrected(ii))=tempindexedspikes(stablespikes>unit{unitnum}.StableStopTime_stagecorrected(ii))-(unit{unitnum}.StableStartTime_stagecorrected(ii+1)-unit{unitnum}.StableStopTime_stagecorrected(ii))+1;
            end
            clear ii
            [pause_start,pause_end]=pause_detect(tempindexedspikes,Info{unitnum}.SAMPLING);
            % only for TAN analysis - eliminate all pauses which are longer
            % than 10 secs
%             aaa=find((pause_end-pause_start)/44000>5);
%             pause_end(aaa)=[];
%             pause_start(aaa)=[];
%             ALL_ISI_RAW{unitnum,1}=[ALL_ISI_RAW{unitnum,1},diff(tempindexedspikes)];
            % until here TAN analysis - eliminate all pauses which are
            % longer than 10 secs
            [~,locations]=intersect(tempindexedspikes,pause_start);
            pause_start=stablespikes(locations);
            [~,locations]=intersect(tempindexedspikes,pause_end);
            pause_end=stablespikes(locations);
            recording_period=(unit{unitnum}.StableStopTime_stagecorrected(end)-unit{unitnum}.StableStartTime_stagecorrected(1))/Info{unitnum}.SAMPLING/1000;
            spike_times=(stablespikes-stablespikes(1)+1)/Info{unitnum}.SAMPLING/1000;
            split_burst_detection=1;
            surprise=8; %5 
            if split_burst_detection
                % This algorithm uses the firing rate as measured for the
                % entire period to find bursts. This might produce erroneous
                % results, so I am changing that so bursts will be detected in
                % 100-sec segments.
                burst_start=[];
                burst_end=[];
                burst_size=[];
                num_sec=30;
                for burst_counter=1:ceil(recording_period/num_sec)
                    spec_spike_times=spike_times(spike_times>=spike_times(1)+(burst_counter-1)*num_sec & spike_times<spike_times(1)+(burst_counter)*num_sec);
                    if length(spec_spike_times)>=5
                        if burst_counter~=ceil(recording_period/num_sec)
                            [bstart,bend,bsize]=burst_detect(spec_spike_times,num_sec,surprise);
                        else
                            [bstart,bend,bsize]=burst_detect(spec_spike_times,mod(recording_period,num_sec),surprise);
                        end
                    else
                        bstart=[];
                        bend=[];
                        bsize=[];
                    end
                    burst_start=[burst_start;bstart];
                    burst_end=[burst_end;bend];
                    burst_size=[burst_size;bsize];
                end
            else
                [burst_start,burst_end,burst_size]=burst_detect(spike_times,recording_period,surprise);
                clear spike_times
            end
            max_burst_length=44000*0.05; %0.1 seconds as a max length for bursts.
            max_spikes_in_burst=12; %12
            true_bursts=intersect(find((burst_end-burst_start)<=max_burst_length & (burst_end-burst_start)>0),find(burst_size<max_spikes_in_burst & burst_size>0));
            burst_start=burst_start(true_bursts);
            burst_end=burst_end(true_bursts);
            burst_size=burst_size(true_bursts);
%             figure; 
%             stablespikes=stablespikes-stablespikes(1)+1;
%             line([0,(stablespikes(end)-stablespikes(1))/44000],[0,0]);
%             for uu=1:length(stablespikes)
%                 hold all;
%                 line([stablespikes(uu)/44000,stablespikes(uu)/44000],[-10,10]);
%             end
%             hold all; 
%             scatter(burst_start/44000,10*ones(1,length(burst_start)),'g','filled');
%             hold all; 
%             scatter(burst_end/44000,10*ones(1,length(burst_end)),'r','filled');            
%             ylim([-15,15])
%             stablespikes=stablespikes+stablespikes(1)-1;
%             title('thresh=5')
            burst_start=burst_start+stablespikes(1)-1;
            burst_end=burst_end+stablespikes(1)-1;
            clear locations
            for stable_period_count=1:length(first_stable_sample) % go over stable periods of the specific unit
                if No_pause_analysis
                    % The Pause analysis is done for every unit.
                    % This is how the pause deletion works: The code goes pause by pause and "erases" it by shifting the entire spiking
                    % activity backwards by (pause length-mean ISI) samples. The code then takes care of the stable period and the polysomnography data.
                    % stable periods: All the starts and stops of stable periods after the pause (all the pauses are in stable periods, so no need to worry 
                    % about pauses that are between periods or something like that) are moved backwards by (pause length-mean ISI) samples.
                    % Polysomnography stages: This is more complicated as stage
                    % changes could be in or out of pauses. For every pause, 6 cases are considered:
                    % 1. n and n+1, the last sample of stage x and the first sample of stage x+1, are both in a pause. In this case the new n would be the last spike of the pre-pause
                    % spiking period, and n+1 would be the sample after. Of course, after the shifting of the spikes, this would correspond to the first sample of the ISI following that
                    % last spike. All the beginnings and ends of stages that will come after these n and n+1 are shigted
                    % backwards as well. This case could be solved easily by converting it to case 5 or 6 below and continuing from there.
                    % 2. There are no n or n+1 in this pause. This means They are in a spiking period. Here, all the beginnings and ends of stages that come after the pause end are shifted backwards by
                    % (pause length-mean ISI) samples. This case does not need further consideration because by the shifting all the spikes and all thr beginnings and ends of stages by the same (pause
                    % length-mean ISI) samples, n and n+1 wil allign back to where they were before the deletion. 
                    % 3. pause start = n
                    % 4. pause start = n+1
                    % 5. pause end = n
                    % 6. pause end = n+1
                    % Cases 3 and 4 are trivial. These specific n and n+1 shouldn't be changed because they will now refer to the newly shifted data from the "future". For cases 5
                    % and 6, n and n+1 should simply be shifted back. So actually, provided all case 1s are converted to case 5 or 6, the algorithm can be simple: for every pause
                    % start,check if a stage switch is in it (i.e. beginning and end are both in pause). If so, move the switch to the pause end (such that pause end equals
                    % stage beginning). b. For all stage beginnings and ends that are both bigger than the current pause start, shift them back. This is not bigger or equal
                    % because of the fact that this accounts to case 3 above, which shouldn't require any moving of that same stage begininng.
                    % Notes: 
                    % 1. I'm assuming there can be no situation where two state changes are in the same pause. This is because Pauses are seldom or never larger than 5 seconds, and my
                    % staging is based on 10-sec segments.
                    % 2. The unit mean ISI that is used to compute (pause length-mean ISI) samples is computed as a furst step for every new unit.

                    % compute mean ISI    
                    stable_digital=unit{unitnum}.Spikes;
                    stable_digital=stable_digital(stable_digital>=first_stable_sample(1,stable_period_count) & stable_digital<=last_stable_sample(1,stable_period_count));
                    pause_minimal_length=300; %ms 
                    all_ISIs=diff(stable_digital);
                    all_ISIs=all_ISIs(all_ISIs<=pause_minimal_length*Info{1,unitnum}.SAMPLING); % ISIs are only those that are shorter than the pause minimal length.
                    mean_ISI=round(nanmean(all_ISIs));
                    clear pause_minimal_length all_ISIs stable_digital
                    
                    % make the pause_star signify the first sample after
                    % the last spike, and the pause_end the last sample
                    % before the first spike.
                    pause_start=pause_start+1;
                    pause_end=pause_end-1;
                    
                    % for pauses that include the beginning or ending of
                    % the stable period, change their start and end time so
                    % that they overlap with the ending and beginning of
                    % the stable period. This assures that all the pauses
                    % in the stable period are fully contained in the
                    % period.
                    in_pause_beginning=find(pause_start<=first_stable_sample(stable_period_count),1,'last');
                    in_pause_end=find(pause_end>=first_stable_sample(stable_period_count),1,'first');
                    if in_pause_beginning==in_pause_end
                        first_stable_sample(stable_period_count)=pause_end(in_pause_beginning)+1;
                    end
                    in_pause_beginning=find(pause_start<=last_stable_sample(stable_period_count),1,'last');
                    in_pause_end=find(pause_end>=last_stable_sample(stable_period_count),1,'first');
                    if in_pause_beginning==in_pause_end
                        last_stable_sample(stable_period_count)=pause_start(in_pause_beginning)-1;
                    end      
                    clear in_pause_beginning in_pause_end
                    
                    % go pause by pause. For every pause, carry on the
                    % shifting described before.
                    local_pauses=intersect(find(pause_start>first_stable_sample(stable_period_count)),find(pause_end<last_stable_sample(stable_period_count)));
                    local_pause_start=pause_start(local_pauses);
                    local_pause_end=pause_end(local_pauses);
                    clear local_pauses
                    
                    for ii=1:length(local_pause_start)
                        shift=local_pause_end(ii)-local_pause_start(ii)+1-mean_ISI;
                        % shift back the spike data.
                        unit{unitnum}.Spikes(unit{unitnum}.Spikes<=local_pause_end(ii) & unit{unitnum}.Spikes>=local_pause_start(ii))=[]; % clear spikes that are *in* the actual pause.
                        unit{unitnum}.Spikes(unit{unitnum}.Spikes>local_pause_end(ii))=unit{unitnum}.Spikes(unit{unitnum}.Spikes>local_pause_end(ii))-shift;
                        % shift back the stable periods
                        first_stable_sample(first_stable_sample>local_pause_end(ii))=first_stable_sample(first_stable_sample>local_pause_end(ii))-shift;
                        last_stable_sample(last_stable_sample>local_pause_end(ii))=last_stable_sample(last_stable_sample>local_pause_end(ii))-shift;
                        % shift back all pauses that are after this pause
                        pause_start(pause_start>local_pause_end(ii))=pause_start(pause_start>local_pause_end(ii))-shift;
                        pause_end(pause_end>local_pause_end(ii))=pause_end(pause_end>local_pause_end(ii))-shift;
                        local_pause_start(local_pause_start>local_pause_end(ii))=local_pause_start(local_pause_start>local_pause_end(ii))-shift;
                        local_pause_end(local_pause_end>local_pause_end(ii))=local_pause_end(local_pause_end>local_pause_end(ii))-shift;
                        % shift back the polysomnography data
                        % first, convert case 1 to case 5 above
                        x=find(polysomnography{1,unitnum}.all_beginnings>local_pause_start(ii),1,'first');
                        if x~=1 && polysomnography{1,unitnum}.all_ends(x-1)<local_pause_end(ii) && polysomnography{1,unitnum}.all_ends(x-1)>local_pause_start(ii)
                            w=find(polysomnography{1,unitnum}.stages.W.begin_sample==polysomnography{1,unitnum}.all_beginnings(x));
                            n1=find(polysomnography{1,unitnum}.stages.N1.begin_sample==polysomnography{1,unitnum}.all_beginnings(x));
                            n2=find(polysomnography{1,unitnum}.stages.N2.begin_sample==polysomnography{1,unitnum}.all_beginnings(x));
                            n3=find(polysomnography{1,unitnum}.stages.N3.begin_sample==polysomnography{1,unitnum}.all_beginnings(x));
                            r=find(polysomnography{1,unitnum}.stages.R.begin_sample==polysomnography{1,unitnum}.all_beginnings(x));
                            u=find(polysomnography{1,unitnum}.stages.U.begin_sample==polysomnography{1,unitnum}.all_beginnings(x));
                            if ~isempty(w)
                                polysomnography{1,unitnum}.stages.W.begin_sample(w)=local_pause_end(ii)+1;
                                polysomnography{1,unitnum}.all_beginnings(x)=local_pause_end(ii)+1;
                            elseif ~isempty(n1)
                                polysomnography{1,unitnum}.stages.N1.begin_sample(n1)=local_pause_end(ii)+1;
                                polysomnography{1,unitnum}.all_beginnings(x)=local_pause_end(ii)+1;                                
                            elseif ~isempty(n2)
                                polysomnography{1,unitnum}.stages.N2.begin_sample(n2)=local_pause_end(ii)+1;
                                polysomnography{1,unitnum}.all_beginnings(x)=local_pause_end(ii)+1;                                                      
                            elseif ~isempty(n3)
                                polysomnography{1,unitnum}.stages.N3.begin_sample(n3)=local_pause_end(ii)+1;
                                polysomnography{1,unitnum}.all_beginnings(x)=local_pause_end(ii)+1;                                                                
                            elseif ~isempty(r)
                                polysomnography{1,unitnum}.stages.R.begin_sample(r)=local_pause_end(ii)+1;
                                polysomnography{1,unitnum}.all_beginnings(x)=local_pause_end(ii)+1;                                                                
                            elseif ~isempty(u)
                                polysomnography{1,unitnum}.stages.U.begin_sample(u)=local_pause_end(ii)+1;
                                polysomnography{1,unitnum}.all_beginnings(x)=local_pause_end(ii)+1;                                                                
                            end
                            w=find(polysomnography{1,unitnum}.stages.W.end_sample==polysomnography{1,unitnum}.all_ends(x-1));
                            n1=find(polysomnography{1,unitnum}.stages.N1.end_sample==polysomnography{1,unitnum}.all_ends(x-1));
                            n2=find(polysomnography{1,unitnum}.stages.N2.end_sample==polysomnography{1,unitnum}.all_ends(x-1));
                            n3=find(polysomnography{1,unitnum}.stages.N3.end_sample==polysomnography{1,unitnum}.all_ends(x-1));
                            r=find(polysomnography{1,unitnum}.stages.R.end_sample==polysomnography{1,unitnum}.all_ends(x-1));
                            u=find(polysomnography{1,unitnum}.stages.U.end_sample==polysomnography{1,unitnum}.all_ends(x-1));
                            if ~isempty(w)
                                polysomnography{1,unitnum}.stages.W.end_sample(w)=local_pause_end(ii);
                                polysomnography{1,unitnum}.all_ends(x-1)=local_pause_end(ii);
                            elseif ~isempty(n1)
                                polysomnography{1,unitnum}.stages.N1.end_sample(n1)=local_pause_end(ii);
                                polysomnography{1,unitnum}.all_ends(x-1)=local_pause_end(ii);                                
                            elseif ~isempty(n2)
                                polysomnography{1,unitnum}.stages.N2.end_sample(n2)=local_pause_end(ii);
                                polysomnography{1,unitnum}.all_ends(x-1)=local_pause_end(ii);                                                      
                            elseif ~isempty(n3)
                                polysomnography{1,unitnum}.stages.N3.end_sample(n3)=local_pause_end(ii);
                                polysomnography{1,unitnum}.all_ends(x-1)=local_pause_end(ii);                                                                
                            elseif ~isempty(r)
                                polysomnography{1,unitnum}.stages.R.end_sample(r)=local_pause_end(ii);
                                polysomnography{1,unitnum}.all_ends(x-1)=local_pause_end(ii);                                                                
                            elseif ~isempty(u)
                                polysomnography{1,unitnum}.stages.U.end_sample(u)=local_pause_end(ii);
                                polysomnography{1,unitnum}.all_ends(x-1)=local_pause_end(ii);                                                                
                            end
                        elseif x==1
                            w=find(polysomnography{1,unitnum}.stages.W.begin_sample==polysomnography{1,unitnum}.all_beginnings(x));
                            n1=find(polysomnography{1,unitnum}.stages.N1.begin_sample==polysomnography{1,unitnum}.all_beginnings(x));
                            n2=find(polysomnography{1,unitnum}.stages.N2.begin_sample==polysomnography{1,unitnum}.all_beginnings(x));
                            n3=find(polysomnography{1,unitnum}.stages.N3.begin_sample==polysomnography{1,unitnum}.all_beginnings(x));
                            r=find(polysomnography{1,unitnum}.stages.R.begin_sample==polysomnography{1,unitnum}.all_beginnings(x));
                            u=find(polysomnography{1,unitnum}.stages.U.begin_sample==polysomnography{1,unitnum}.all_beginnings(x));
                            if ~isempty(w)
                                polysomnography{1,unitnum}.stages.W.begin_sample(w)=local_pause_end(ii)+1;
                                polysomnography{1,unitnum}.all_beginnings(x)=local_pause_end(ii)+1;
                            elseif ~isempty(n1)
                                polysomnography{1,unitnum}.stages.N1.begin_sample(n1)=local_pause_end(ii)+1;
                                polysomnography{1,unitnum}.all_beginnings(x)=local_pause_end(ii)+1;                                
                            elseif ~isempty(n2)
                                polysomnography{1,unitnum}.stages.N2.begin_sample(n2)=local_pause_end(ii)+1;
                                polysomnography{1,unitnum}.all_beginnings(x)=local_pause_end(ii)+1;                                                      
                            elseif ~isempty(n3)
                                polysomnography{1,unitnum}.stages.N3.begin_sample(n3)=local_pause_end(ii)+1;
                                polysomnography{1,unitnum}.all_beginnings(x)=local_pause_end(ii)+1;                                                                
                            elseif ~isempty(r)
                                polysomnography{1,unitnum}.stages.R.begin_sample(r)=local_pause_end(ii)+1;
                                polysomnography{1,unitnum}.all_beginnings(x)=local_pause_end(ii)+1;                                                                
                            elseif ~isempty(u)
                                polysomnography{1,unitnum}.stages.U.begin_sample(u)=local_pause_end(ii)+1;
                                polysomnography{1,unitnum}.all_beginnings(x)=local_pause_end(ii)+1;                                                                
                            end                            
                        end
                        % for all beginning and ends which are both bigger than local_pase_start, shift them back
                        for jj=1:length(polysomnography{1,unitnum}.all_beginnings)
                            if jj~=length(polysomnography{1,unitnum}.all_beginnings)
                                if (polysomnography{1,unitnum}.all_beginnings(jj+1)>local_pause_start(ii) && polysomnography{1,unitnum}.all_ends(jj)>local_pause_start(ii))
                                    polysomnography{1,unitnum}.all_ends(jj)=polysomnography{1,unitnum}.all_ends(jj)-shift;
                                    polysomnography{1,unitnum}.all_beginnings(jj+1)=polysomnography{1,unitnum}.all_beginnings(jj+1)-shift;
                                end
                                if jj==1
                                    if polysomnography{1,unitnum}.all_beginnings(jj)>local_pause_start(ii)
                                        polysomnography{1,unitnum}.all_beginnings(jj)=polysomnography{1,unitnum}.all_beginnings(jj)-shift;
                                    end
                                end
                            elseif jj==length(polysomnography{1,unitnum}.all_beginnings)
                                if polysomnography{1,unitnum}.all_ends(jj)>local_pause_start(ii)
                                    polysomnography{1,unitnum}.all_ends(jj)=polysomnography{1,unitnum}.all_ends(jj)-shift;
                                end
                            end
                        end
                        for jj=1:length(polysomnography{1,unitnum}.stages.W.begin_sample)
                            if polysomnography{1,unitnum}.stages.W.begin_sample(jj)-1>local_pause_start(ii) % the -1 thing is to ensure neither the begin or end is equal or bigger in only one sample from the beginning of the pause, as this would be cases 3 and 4 that should not be changed.
                                polysomnography{1,unitnum}.stages.W.begin_sample(jj)=polysomnography{1,unitnum}.stages.W.begin_sample(jj)-shift;
                            end
                            if polysomnography{1,unitnum}.stages.W.end_sample(jj)-1>local_pause_start(ii)
                                polysomnography{1,unitnum}.stages.W.end_sample(jj)=polysomnography{1,unitnum}.stages.W.end_sample(jj)-shift;
                            end                            
                        end
                        for jj=1:length(polysomnography{1,unitnum}.stages.N1.begin_sample)
                            if polysomnography{1,unitnum}.stages.N1.begin_sample(jj)-1>local_pause_start(ii) % the -1 thing is to ensure neither the begin or end is equal or bigger in only one sample from the beginning of the pause, as this would be cases 3 and 4 that should not be changed.
                                polysomnography{1,unitnum}.stages.N1.begin_sample(jj)=polysomnography{1,unitnum}.stages.N1.begin_sample(jj)-shift;
                            end
                            if polysomnography{1,unitnum}.stages.N1.end_sample(jj)-1>local_pause_start(ii)
                                polysomnography{1,unitnum}.stages.N1.end_sample(jj)=polysomnography{1,unitnum}.stages.N1.end_sample(jj)-shift;
                            end                            
                        end
                        for jj=1:length(polysomnography{1,unitnum}.stages.N2.begin_sample)
                            if polysomnography{1,unitnum}.stages.N2.begin_sample(jj)-1>local_pause_start(ii) % the -1 thing is to ensure neither the begin or end is equal or bigger in only one sample from the beginning of the pause, as this would be cases 3 and 4 that should not be changed.
                                polysomnography{1,unitnum}.stages.N2.begin_sample(jj)=polysomnography{1,unitnum}.stages.N2.begin_sample(jj)-shift;
                            end
                            if polysomnography{1,unitnum}.stages.N2.end_sample(jj)-1>local_pause_start(ii)
                                polysomnography{1,unitnum}.stages.N2.end_sample(jj)=polysomnography{1,unitnum}.stages.N2.end_sample(jj)-shift;
                            end                            
                        end
                        for jj=1:length(polysomnography{1,unitnum}.stages.N3.begin_sample)
                            if polysomnography{1,unitnum}.stages.N3.begin_sample(jj)-1>local_pause_start(ii) % the -1 thing is to ensure neither the begin or end is equal or bigger in only one sample from the beginning of the pause, as this would be cases 3 and 4 that should not be changed.
                                polysomnography{1,unitnum}.stages.N3.begin_sample(jj)=polysomnography{1,unitnum}.stages.N3.begin_sample(jj)-shift;
                            end
                            if polysomnography{1,unitnum}.stages.N3.end_sample(jj)-1>local_pause_start(ii)
                                polysomnography{1,unitnum}.stages.N3.end_sample(jj)=polysomnography{1,unitnum}.stages.N3.end_sample(jj)-shift;
                            end                            
                        end
                        for jj=1:length(polysomnography{1,unitnum}.stages.R.begin_sample)
                            if polysomnography{1,unitnum}.stages.R.begin_sample(jj)-1>local_pause_start(ii) % the -1 thing is to ensure neither the begin or end is equal or bigger in only one sample from the beginning of the pause, as this would be cases 3 and 4 that should not be changed.
                                polysomnography{1,unitnum}.stages.R.begin_sample(jj)=polysomnography{1,unitnum}.stages.R.begin_sample(jj)-shift;
                            end
                            if polysomnography{1,unitnum}.stages.R.end_sample(jj)-1>local_pause_start(ii)
                                polysomnography{1,unitnum}.stages.R.end_sample(jj)=polysomnography{1,unitnum}.stages.R.end_sample(jj)-shift;
                            end                            
                        end
                        for jj=1:length(polysomnography{1,unitnum}.stages.U.begin_sample)
                            if polysomnography{1,unitnum}.stages.U.begin_sample(jj)-1>local_pause_start(ii) % the -1 thing is to ensure neither the begin or end is equal or bigger in only one sample from the beginning of the pause, as this would be cases 3 and 4 that should not be changed.
                                polysomnography{1,unitnum}.stages.U.begin_sample(jj)=polysomnography{1,unitnum}.stages.U.begin_sample(jj)-shift;
                            end
                            if polysomnography{1,unitnum}.stages.U.end_sample(jj)-1>local_pause_start(ii)
                                polysomnography{1,unitnum}.stages.U.end_sample(jj)=polysomnography{1,unitnum}.stages.U.end_sample(jj)-shift;
                            end                            
                        end
                    end
                end
                [stage_length{1,unitnum},all_begs,all_ends]=get_sleep_stages_lengths(first_stable_sample,last_stable_sample,polysomnography{1,unitnum});                
                stable_digital=unit{unitnum}.Spikes;
                stable_digital=stable_digital(stable_digital>=first_stable_sample(1,stable_period_count) & stable_digital<=last_stable_sample(1,stable_period_count));
                milli_second_begin_sample=nan(1,ceil((last_stable_sample(1,stable_period_count)-first_stable_sample(1,stable_period_count)+1)/Info{unitnum}.SAMPLING)); % The number of milliseconds in the stripe where the unit was recorded. not +1 because here what is important is the number of gaps, and not the number of samples.
                milli_second_begin_sample=first_stable_sample(1,stable_period_count)+round(Info{unitnum}.SAMPLING*[0:1:length(milli_second_begin_sample)-1]); % check the round doesnt do anything when you get your 44 KHz system. 
                spikes_per_milli_sec=zeros(1,length(milli_second_begin_sample));
                % next 2 lines create a vector of 1 or 0 depending on whether a spike was in the corresponding place
                if mod(Info{unitnum}.SAMPLING,1)==0
                    % assuming no more than one spike per ms.. makes good sense
                    stable_digital_ms=ceil((stable_digital-first_stable_sample(1,stable_period_count)+1)/Info{unitnum}.SAMPLING);
%                     if stable_digital_ms(1,1)==0
%                         stable_digital_ms(1,1)=1;
%                     end
%                     for zz=1:length(stable_digital_ms)
%                         spikes_per_milli_sec(1,stable_digital_ms(zz))=spikes_per_milli_sec(1,stable_digital_ms(zz))+1;
%                     end
                    spikes_per_milli_sec(1,stable_digital_ms)=1;
%                     A=(reshape([1:1:length(milli_second_begin_sample)*Info{unitnum}.SAMPLING],Info{unitnum}.SAMPLING,length(milli_second_begin_sample)))'+first_stable_sample(1,stable_period_count)-1;
%                     spikes_per_milli_sec=sum(ismember(A,stable_digital),2)';
                else
                    for first_finder=1:length(stable_digital)
                        a=find(milli_second_begin_sample<=stable_digital(1,first_finder),1,'last');
                        spikes_per_milli_sec(1,a)=spikes_per_milli_sec(1,a)+1;
                    end
                end
                clear stable_digital_ms
                
                if (binsize_vec(1,1) || binsize_vec(1,2))
                   % prepare data for the next N3 detection period
                   [FR_per_bs,bs_begin_sample_FR]=Calculate_FR(spikes_per_milli_sec,milli_second_begin_sample,binsize_vec(2,2),overlap_smoothing_settings,1);                
                end
                
                %%CHECK MULTI UNIT PS CODE. THE MAIN CHANGES I INSERTED
                %121616 ARE: 
                % 1. AN OPTION TO CALCULATE BOTH LOCAL_LFP AND GLOBAL_EEG.
                % SEE THAT THEY DONT USE THE SAME VARS AND MIX IN EACH
                % OTHER
                % 2. IF LFP IS CHOSEN, THE LFP_SEGMENTED_1 VAR IS EXPORTED
                % TO THE PS CALCULATION CODE AND IS CALCULATED THERE. CHECK
                % THIS WORKS INCLUDING SAVING ETC.
                % 3. BARE IN MIND THAT FOR NOW PS, FR AND SWS SEGMENT
                % FINDER ALL HAVE RO RECEIVE THE SAME BINSIZE - 10. THAT,
                % IF YOU WANT TO USE THE DATA FROM THE LFT/MU PART OF THE
                % EEG PHASE ANALYSIS CODE TO ANALYZE THE PS OF THE
                % MULTI-UNIT ACTIVITY.
                % The old Neurop_Profile_Aviv is saved in functions
                use_SWS_N3_data=1; % mark this as 1 if you want the cross correlation algorithm to calculate the cross-correlations separately for N3 segments, as defined by the SWS analysis.
                Calculate_MU_Spectrum=0;
                if binsize_vec(1,9) % EEG phase Analysis
                    % For each 10s "NREM" bin, a narrow band filtration of
                    % the signal is made and a criterion is applied to find
                    % slow wave segments (AASM criterion, Iber 2007).
                    % a. If the SWS activity exceeds the criterion the bin
                    %    is used for further analysis:
                    % b. for every segment of SWS within the bin, the
                    %    instantaneous phase of the oscillation is
                    %    calculated.
                    % Next, local spikes are considered and each is given
                    % an instantaneous phase value in radians.
                    
                    Local_LFP=0;
                    Global_EEG=1;
                    % Retrieve EEG traces for the unit
                    if Global_EEG
                        EEG_1=[]; % D: lead 4, No. 020, frontal-L, ipsilateral to chamber N: same but D: lead 7, No. 023
                        EEG_2=[]; % lead 5, No. 021, central-L, ipsilateral to chamber
                        EEG_3=[]; % lead 2, No. 018, central-R, contralateral to chamber
                        EEG_4=[]; % lead 6, No. 022, Occipital-L, ipsilateral to chamber
                        EEG_5=[]; % lead 3, No. 019, Occipital-R, contralateral to chamber
                    end
                    if Local_LFP
                        LFP_1=[]; % The same in which the electrode was recorded
                        if LFP_to_unit_analysis
                            LFP_1_for_thresh=[];
                        end
                    end
                        
                    all_file_starts=[];
                    all_file_ends=[];
                    for ff=1:length(Datafiles{1,unitnum})
                        all_file_starts=[all_file_starts,Datafiles{1,unitnum}(ff,1).start_sample];
                        all_file_ends=[all_file_ends,Datafiles{1,unitnum}(ff,1).end_sample];
                    end
                    beginning_file=find(all_file_starts<=first_stable_sample(stable_period_count),1,'last');
                    ending_file=find(all_file_ends>=last_stable_sample(stable_period_count),1,'first');
                    for ff=beginning_file:1:ending_file
                        % This next piece of code was written after I found out that not *all* my file-2-file gaps (in samples) was only 1 sample, as requested. A very
                        % preliminary check showed that some are indeed 1, many are -X, -30<X<0 and one was a few seconds - This corresponds to shut down and turn on of the
                        % machine in the middle of recording. Either way, if I concatenate files I have to be ready for that. Gere comes this code - for every new file,
                        % if the number of samples between this and the last file was bigger than 1, nans are added. If the difference is smaller than 1, meaning the new
                        % file started "prematurely", the needed number of samples from LFP will be erased. Next, if I have portions of the LFP vector which have more than
                        % 50% NaNs, this won't be analyzed - the RMS and the PS will get all NaNs.

                        if ff~=beginning_file % see below (spike triggered LFP code) why this workaround is unnecessary.
                            difference_between_samples=Datafiles{1,unitnum}(ff,1).start_sample-Datafiles{1,unitnum}(ff-1,1).end_sample;
                            if difference_between_samples>1
                                if Global_EEG
                                    EEG_1=[EEG_1,zeros(1,round((difference_between_samples-1)/Info{1,unitnum}.SAMPLING*EEG_SR_KHz))];
                                    EEG_2=[EEG_2,zeros(1,round((difference_between_samples-1)/Info{1,unitnum}.SAMPLING*EEG_SR_KHz))];
                                    EEG_3=[EEG_3,zeros(1,round((difference_between_samples-1)/Info{1,unitnum}.SAMPLING*EEG_SR_KHz))];
                                    EEG_4=[EEG_4,zeros(1,round((difference_between_samples-1)/Info{1,unitnum}.SAMPLING*EEG_SR_KHz))];
                                    EEG_5=[EEG_5,zeros(1,round((difference_between_samples-1)/Info{1,unitnum}.SAMPLING*EEG_SR_KHz))];
                                end
                                if Local_LFP
                                    LFP_1=[LFP_1,zeros(1,round((difference_between_samples-1)/Info{1,unitnum}.SAMPLING*(LFP_SR_KHz/dsmp_factor_Local_LFP)))];
                                    if LFP_to_unit_analysis
                                        LFP_1_for_thresh=[LFP_1_for_thresh,zeros(1,round((difference_between_samples-1)/Info{1,unitnum}.SAMPLING*(LFP_SR_KHz/dsmp_factor_Local_LFP)))];
                                    end
                                end
                            elseif difference_between_samples<1
                                if Global_EEG
                                    EEG_1=EEG_1(1:length(EEG_1)-round((1-difference_between_samples)/Info{1,unitnum}.SAMPLING*EEG_SR_KHz));
                                    EEG_2=EEG_2(1:length(EEG_2)-round((1-difference_between_samples)/Info{1,unitnum}.SAMPLING*EEG_SR_KHz));
                                    EEG_3=EEG_3(1:length(EEG_3)-round((1-difference_between_samples)/Info{1,unitnum}.SAMPLING*EEG_SR_KHz));
                                    EEG_4=EEG_4(1:length(EEG_4)-round((1-difference_between_samples)/Info{1,unitnum}.SAMPLING*EEG_SR_KHz));
                                    EEG_5=EEG_5(1:length(EEG_5)-round((1-difference_between_samples)/Info{1,unitnum}.SAMPLING*EEG_SR_KHz));
                                end
                                if Local_LFP
                                    LFP_1=LFP_1(1:length(LFP_1)-round((1-difference_between_samples)/Info{1,unitnum}.SAMPLING*(LFP_SR_KHz/dsmp_factor_Local_LFP)));
                                    if LFP_to_unit_analysis
                                        LFP_1_for_thresh=LFP_1_for_thresh(1:length(LFP_1_for_thresh)-round((1-difference_between_samples)/Info{1,unitnum}.SAMPLING*(LFP_SR_KHz/dsmp_factor_Local_LFP)));
                                    end
                                end
                            end
                        end
                        a=0;
                        if Global_EEG
                            if monkey==1
                                EEG_Samples_1='CRAW_020';
                                EEG_Samples_1_no_raw='CLFP_020';
                                EEG_TimeBegin_1='CRAW_020_TimeBegin';
                            elseif monkey==2
                                EEG_Samples_1='CRAW_023';
                                EEG_Samples_1_no_raw='CLFP_023';
                                EEG_TimeBegin_1='CRAW_023_TimeBegin';
                            end
                                EEG_Samples_2='CRAW_021';
                                EEG_Samples_2_no_raw='CLFP_021';
                                EEG_Samples_3='CRAW_018';
                                EEG_Samples_3_no_raw='CLFP_018';
                                EEG_Samples_4='CRAW_022';
                                EEG_Samples_4_no_raw='CLFP_022';
                                EEG_Samples_5='CRAW_019';
                                EEG_Samples_5_no_raw='CLFP_019';
                                EEG_TimeBegin_2='CRAW_021_TimeBegin';
                                EEG_TimeBegin_3='CRAW_018_TimeBegin';
                                EEG_TimeBegin_4='CRAW_022_TimeBegin';
                                EEG_TimeBegin_5='CRAW_019_TimeBegin';
                                EEG_SR_KHz='CRAW_019_KHz';
                        end
                        if Local_LFP
                            LFP_Samples_1=['CRAW_00',num2str(ElecNum(1,unitnum))];
                            LFP_TimeBegin_1=['CRAW_00',num2str(ElecNum(1,unitnum)),'_TimeBegin'];
                            LFP_SR_KHz=['CRAW_00',num2str(ElecNum(1,unitnum)),'_KHz'];
                        end
                        if Global_EEG
                        filename=Datafiles{1,unitnum}(ff,1).name;
                        if exist(filename)
                            if monkey==1
                                load(filename,'-mat',EEG_Samples_1,EEG_Samples_2,EEG_Samples_3,EEG_Samples_4,EEG_Samples_5);
                                if (~exist(EEG_Samples_1,'var') && ~exist(EEG_Samples_2,'var') && ~exist(EEG_Samples_3,'var') && ~exist(EEG_Samples_4,'var') && ~exist(EEG_Samples_5,'var'))
                                    load(filename,'-mat',EEG_Samples_1_no_raw,EEG_Samples_2_no_raw,EEG_Samples_3_no_raw,EEG_Samples_4_no_raw,EEG_Samples_5_no_raw);
                                    eval([EEG_Samples_1,'=',EEG_Samples_1_no_raw,'; clear ',EEG_Samples_1_no_raw,';']); 
                                    eval([EEG_Samples_2,'=',EEG_Samples_2_no_raw,'; clear ',EEG_Samples_2_no_raw,';']); 
                                    eval([EEG_Samples_3,'=',EEG_Samples_3_no_raw,'; clear ',EEG_Samples_3_no_raw,';']); 
                                    eval([EEG_Samples_4,'=',EEG_Samples_4_no_raw,'; clear ',EEG_Samples_4_no_raw,';']); 
                                    eval([EEG_Samples_5,'=',EEG_Samples_5_no_raw,'; clear ',EEG_Samples_5_no_raw,';']); 
                                    eval(['no_raw_sample_rate=',EEG_Samples_1,'.KHz;']);
                                    if no_raw_sample_rate==1.375
                                        eval([EEG_Samples_1,'.Samples=interp1(1:length(',EEG_Samples_1,'.Samples),',EEG_Samples_1,'.Samples,[0.5:0.5:length(',EEG_Samples_1,'.Samples)]);']);
                                        eval([EEG_Samples_1,'.KHz=2.750;']);
                                        if eval(['isnan(',EEG_Samples_1,'.Samples(1))']) % to avoid a situation where the dfirst sanples is a nan and then upon filtration everything becomes nans.
                                            eval([EEG_Samples_1,'.Samples(1)=0;'])
                                        end
                                        eval([EEG_Samples_2,'.Samples=interp1(1:length(',EEG_Samples_2,'.Samples),',EEG_Samples_2,'.Samples,[0.5:0.5:length(',EEG_Samples_2,'.Samples)]);']);
                                        eval([EEG_Samples_2,'.KHz=2.750;']);
                                        if eval(['isnan(',EEG_Samples_2,'.Samples(1))']) % to avoid a situation where the dfirst sanples is a nan and then upon filtration everything becomes nans.
                                            eval([EEG_Samples_2,'.Samples(1)=0;'])
                                        end                                        
                                        eval([EEG_Samples_3,'.Samples=interp1(1:length(',EEG_Samples_3,'.Samples),',EEG_Samples_3,'.Samples,[0.5:0.5:length(',EEG_Samples_3,'.Samples)]);']);
                                        eval([EEG_Samples_3,'.KHz=2.750;']);
                                        if eval(['isnan(',EEG_Samples_3,'.Samples(1))']) % to avoid a situation where the dfirst sanples is a nan and then upon filtration everything becomes nans.
                                            eval([EEG_Samples_3,'.Samples(1)=0;'])
                                        end            
                                        eval([EEG_Samples_4,'.Samples=interp1(1:length(',EEG_Samples_4,'.Samples),',EEG_Samples_4,'.Samples,[0.5:0.5:length(',EEG_Samples_4,'.Samples)]);']);
                                        eval([EEG_Samples_4,'.KHz=2.750;']);
                                        if eval(['isnan(',EEG_Samples_4,'.Samples(1))']) % to avoid a situation where the dfirst sanples is a nan and then upon filtration everything becomes nans.
                                            eval([EEG_Samples_4,'.Samples(1)=0;'])
                                        end            
                                        eval([EEG_Samples_5,'.Samples=interp1(1:length(',EEG_Samples_5,'.Samples),',EEG_Samples_5,'.Samples,[0.5:0.5:length(',EEG_Samples_5,'.Samples)]);']);
                                        eval([EEG_Samples_5,'.KHz=2.750;']);
                                        if eval(['isnan(',EEG_Samples_5,'.Samples(1))']) % to avoid a situation where the dfirst sanples is a nan and then upon filtration everything becomes nans.
                                            eval([EEG_Samples_5,'.Samples(1)=0;'])
                                        end            
                                    end
                                end
                            elseif monkey==2
                                EEG_Samples_1_with_star='CRAW_023*';
                                load(filename,'-mat',EEG_Samples_1_with_star,EEG_Samples_2,EEG_Samples_3,EEG_Samples_4,EEG_Samples_5);
                                if exist('CRAW_023')
                                    if isstruct(CRAW_021) && ~isstruct(CRAW_023)
                                        dsmp_for_23=CRAW_023_KHz/CRAW_021.KHz;
                                        CRAW_023_Samples=CRAW_023(find(mod(1:length(CRAW_023),dsmp_for_23)==1));
                                        CRAW_023=CRAW_021;
                                        CRAW_023.Samples=CRAW_023_Samples;
                                        clear CRAW_023_* dsmp_for_23
                                    elseif isstruct(CRAW_021) && isstruct(CRAW_023)
                                        dsmp_for_23=CRAW_023.KHz/CRAW_021.KHz;
                                        CRAW_023_Samples=CRAW_023.Samples;
                                        CRAW_023_Samples=double(CRAW_023_Samples(find(mod(1:length(CRAW_023_Samples),dsmp_for_23)==1)));
                                        CRAW_023=CRAW_021;
                                        CRAW_023.Samples=CRAW_023_Samples;
                                        clear CRAW_023_* dsmp_for_23
                                    elseif ~isstruct(CRAW_021) && ~isstruct(CRAW_023)
                                        dsmp_for_23=CRAW_023_KHz/CRAW_021_KHz;
                                        CRAW_023=double(CRAW_023(find(mod(1:length(CRAW_023),dsmp_for_23)==1)));
                                        CRAW_023_KHz=CRAW_021_KHz;
                                        CRAW_023_KHz_Orig=CRAW_021_KHz_Orig;
                                        clear dsmp_for_23
                                    end
                                else
                                    load(filename,'-mat','CRAW_020');
                                end
                            end
                            eval(['a=~isstruct(',EEG_Samples_5,');'])
                            if a==1
                                load(filename,'-mat',EEG_TimeBegin_1,EEG_TimeBegin_2,EEG_TimeBegin_3,EEG_TimeBegin_4,EEG_TimeBegin_5,EEG_SR_KHz);
                                if (monkey==1 || (monkey==2 && ~exist('CRAW_023')))
                                    CRAW_020.Samples=double(CRAW_020);
                                    CRAW_020.KHz=double(CRAW_019_KHz);
                                    CRAW_020.TimeBegin=double(CRAW_020_TimeBegin);                                    
                                elseif (monkey==2 && exist('CRAW_023'))
                                    CRAW_023.Samples=double(CRAW_023);
                                    CRAW_023.KHz=double(CRAW_019_KHz);
                                    CRAW_023.TimeBegin=double(CRAW_023_TimeBegin);                                                                        
                                end
                                CRAW_018.Samples=double(CRAW_018);
                                CRAW_019.Samples=double(CRAW_019);
                                CRAW_021.Samples=double(CRAW_021);
                                CRAW_022.Samples=double(CRAW_022);
                                CRAW_018.KHz=double(CRAW_019_KHz);
                                CRAW_019.KHz=double(CRAW_019_KHz);
                                CRAW_021.KHz=double(CRAW_019_KHz);
                                CRAW_022.KHz=double(CRAW_019_KHz);
                                CRAW_018.TimeBegin=double(CRAW_018_TimeBegin);
                                CRAW_019.TimeBegin=double(CRAW_019_TimeBegin);
                                CRAW_021.TimeBegin=double(CRAW_021_TimeBegin);
                                CRAW_022.TimeBegin=double(CRAW_022_TimeBegin);
                            end                            
                        end
                        end
                        if Local_LFP
                            filename=Datafiles{1,unitnum}(ff,1).name;
                            if exist(filename)
                                load(filename,'-mat',LFP_Samples_1);
                                eval(['a=~isstruct(',LFP_Samples_1,');'])
                                if a==1
                                    load(filename,'-mat',LFP_TimeBegin_1,LFP_SR_KHz);
                                    eval(['CRAW_00',num2str(ElecNum(1,unitnum)),'.Samples=double(CRAW_00',num2str(ElecNum(1,unitnum)),');'])
                                    eval(['CRAW_00',num2str(ElecNum(1,unitnum)),'.KHz=double(CRAW_00',num2str(ElecNum(1,unitnum)),'_KHz);'])
                                    eval(['CRAW_00',num2str(ElecNum(1,unitnum)),'.TimeBegin=double(CRAW_00',num2str(ElecNum(1,unitnum)),'_TimeBegin);'])
                                end                            
                            end
                        end
                        if Global_EEG
                            if (monkey==1 || (monkey==2 && ~exist('CRAW_023')))
                                signal_EEG_1=CRAW_020.Samples;
                            elseif (monkey==2 && exist('CRAW_023'))
                                signal_EEG_1=CRAW_023.Samples;
                            end
                            signal_EEG_2=CRAW_021.Samples;
                            signal_EEG_3=CRAW_018.Samples;
                            signal_EEG_4=CRAW_022.Samples;
                            signal_EEG_5=CRAW_019.Samples;
                            EEG_SR_KHz=CRAW_022.KHz;
                            if ff==beginning_file
                                if (monkey==1 || (monkey==2 && ~exist('CRAW_023')))
                                    file_begin_sample_EEG_1=floor(CRAW_020.TimeBegin*EEG_SR_KHz*1000);
                                elseif (monkey==2 && exist('CRAW_023'))
                                    file_begin_sample_EEG_1=floor(CRAW_023.TimeBegin*EEG_SR_KHz*1000);
                                end
                                file_begin_sample_EEG_2=floor(CRAW_021.TimeBegin*EEG_SR_KHz*1000);
                                file_begin_sample_EEG_3=floor(CRAW_018.TimeBegin*EEG_SR_KHz*1000);
                                file_begin_sample_EEG_4=floor(CRAW_022.TimeBegin*EEG_SR_KHz*1000);
                                file_begin_sample_EEG_5=floor(CRAW_019.TimeBegin*EEG_SR_KHz*1000);
                            end
                            signal_EEG_1=signal_EEG_1-nanmean(signal_EEG_1);
                            signal_EEG_2=signal_EEG_2-nanmean(signal_EEG_2);
                            signal_EEG_3=signal_EEG_3-nanmean(signal_EEG_3);
                            signal_EEG_4=signal_EEG_4-nanmean(signal_EEG_4);
                            signal_EEG_5=signal_EEG_5-nanmean(signal_EEG_5);

                            % change back 050217
% %                             signal_EEG_1=BWfilter_designer(double(signal_EEG_1), EEG_SR_KHz*1000, bandpass_SW, bandstop_SW, 'BP'); % used tp be [0.5,2], [0.1,2.5] but then I wanted to check the proportion of SW power of all frequencies, so I filter only to EEG frequency now. SW filtration is done before calculating the Hilbert transform
% %                             signal_EEG_2=BWfilter_designer(double(signal_EEG_2), EEG_SR_KHz*1000, bandpass_SW, bandstop_SW, 'BP');
% %                             signal_EEG_3=BWfilter_designer(double(signal_EEG_3), EEG_SR_KHz*1000, bandpass_SW, bandstop_SW, 'BP');
% %                             signal_EEG_4=BWfilter_designer(double(signal_EEG_4), EEG_SR_KHz*1000, bandpass_SW, bandstop_SW, 'BP');
% %                             signal_EEG_5=BWfilter_designer(double(signal_EEG_5), EEG_SR_KHz*1000, bandpass_SW, bandstop_SW, 'BP');

%                             signal_EEG_1=BWfilter_designer(double(signal_EEG_1), EEG_SR_KHz*1000, bandpass_EEG, bandstop_EEG, 'BP'); % used tp be [0.5,2], [0.1,2.5] but then I wanted to check the proportion of SW power of all frequencies, so I filter only to EEG frequency now. SW filtration is done before calculating the Hilbert transform
%                             signal_EEG_2=BWfilter_designer(double(signal_EEG_2), EEG_SR_KHz*1000, bandpass_EEG, bandstop_EEG, 'BP');
%                             signal_EEG_3=BWfilter_designer(double(signal_EEG_3), EEG_SR_KHz*1000, bandpass_EEG, bandstop_EEG, 'BP');
%                             signal_EEG_4=BWfilter_designer(double(signal_EEG_4), EEG_SR_KHz*1000, bandpass_EEG, bandstop_EEG, 'BP');
%                             signal_EEG_5=BWfilter_designer(double(signal_EEG_5), EEG_SR_KHz*1000, bandpass_EEG, bandstop_EEG, 'BP');

                            EEG_1=[EEG_1,signal_EEG_1]; % no assumption of no sample loss between files (see before)
                            EEG_2=[EEG_2,signal_EEG_2];
                            EEG_3=[EEG_3,signal_EEG_3];
                            EEG_4=[EEG_4,signal_EEG_4];
                            EEG_5=[EEG_5,signal_EEG_5];
                        end
                        if Local_LFP
                            eval(['signal_LFP_1=CRAW_00',num2str(ElecNum(1,unitnum)),'.Samples;']);
                            eval(['LFP_SR_KHz=CRAW_00',num2str(ElecNum(1,unitnum)),'.KHz;']);
                            if ff==beginning_file
                                eval(['file_begin_sample_LFP_1=floor(CRAW_00',num2str(ElecNum(1,unitnum)),'.TimeBegin*LFP_SR_KHz*1000);'])
                            end
                            signal_LFP_1=signal_LFP_1-nanmean(signal_LFP_1);
                            if ~Calculate_MU_Spectrum && ~LFP_to_unit_analysis
                                signal_LFP_1_filtered=BWfilter_designer(double(signal_LFP_1), LFP_SR_KHz*1000, bandpass_SW, bandstop_SW, 'BP'); 
                            elseif ~Calculate_MU_Spectrum && LFP_to_unit_analysis
                                signal_LFP_1_filtered=BWfilter_designer(double(signal_LFP_1), LFP_SR_KHz*1000, bandpass_wider, bandstop_wider, 'BP'); % changed 062217 to a wider range, because I don't want to use the LFP for the same purpose I use the EEG (defining SW) but for LFP SW analysis in respect of all other frequencies. For now I want to find, for every LFP segment, its poewr on the SW range in relative to the 0.1-40 Hz range, so first I filter to the wider range
                                signal_LFP_1_for_thresh=BWfilter_designer(double(signal_LFP_1), LFP_SR_KHz*1000, bandpass_SW, bandstop_SW, 'BP');
                            elseif Calculate_MU_Spectrum
                                signal_LFP_1_filtered=signal_LFP_1;                                
                            end
                            downsampled_signal_LFP_1_filtered=signal_LFP_1_filtered(mod((1:length(signal_LFP_1_filtered)),dsmp_factor_Local_LFP)==0); % changed from ==1 to ==0 to enable a state where I don't do dsmpling by only changing the dsmp factor to 1 062517
                            LFP_1=[LFP_1,downsampled_signal_LFP_1_filtered]; % no assumption of no sample loss between files (see before)                            
                            if LFP_to_unit_analysis
                                downsampled_signal_LFP_1_for_thresh=signal_LFP_1_for_thresh(mod((1:length(signal_LFP_1_for_thresh)),dsmp_factor_Local_LFP)==0); % changed from ==1 to ==0 to enable a state where I don't do dsmpling by only changing the dsmp factor to 1 062517
                                LFP_1_for_thresh=[LFP_1_for_thresh,downsampled_signal_LFP_1_for_thresh];
                            end
                        end
                        clear CRAW_0*
                    end
                    clear a beginning_file ending_file all_file_starts all_file_ends all_nan difference_between_samples ff filename filename_* ii marker signal_EEG_*
                    if Local_LFP && LFP_to_unit_analysis
%                         LFP_1_for_thresh=LFP_1_for_thresh(mod((1:length(LFP_1_for_thresh)),32)==1); % downsample by 32
                        SW_definition_thresh_LFP_only_for_current_cell=prctile(abs(hilbert(LFP_1_for_thresh)),percent_thresh_for_SW_definition_LFP);
                    end
                    if Local_LFP % added 062817
                        clear LFP_1_for_thresh
                        LFP_SR_KHz=LFP_SR_KHz/dsmp_factor_Local_LFP;
                        file_begin_sample_LFP_1=ceil(file_begin_sample_LFP_1/dsmp_factor_Local_LFP);
                    end
                      % create a new vector. Its elements are the LFP vector segments for the PS calculation
                   if Global_EEG
                   EEG_1_segmented={};
                   EEG_2_segmented={};
                   EEG_3_segmented={};
                   EEG_4_segmented={};
                   EEG_5_segmented={};

                   bs_begin_sample_PS_EEG=[];

                   first_stable_sample_EEG=max(file_begin_sample_EEG_1,floor(bs_begin_sample_FR(1,1)/Info{1,unitnum}.SAMPLING*EEG_SR_KHz)); % added 111316
                   last_stable_sample_EEG=floor(last_stable_sample(1,stable_period_count)/Info{1,unitnum}.SAMPLING*EEG_SR_KHz);

                   while first_stable_sample_EEG+(length(EEG_5_segmented)+1)*EEG_SR_KHz*1000*binsize_vec(2,9)-1<=last_stable_sample_EEG
                       EEG_1_segmented{1,length(EEG_1_segmented)+1}=EEG_1(max(1,first_stable_sample_EEG+length(EEG_1_segmented)*EEG_SR_KHz*1000*binsize_vec(2,9)-file_begin_sample_EEG_1+1):first_stable_sample_EEG+(length(EEG_1_segmented)+1)*EEG_SR_KHz*1000*binsize_vec(2,9)-file_begin_sample_EEG_1); 
                       EEG_2_segmented{1,length(EEG_2_segmented)+1}=EEG_2(max(1,first_stable_sample_EEG+length(EEG_2_segmented)*EEG_SR_KHz*1000*binsize_vec(2,9)-file_begin_sample_EEG_2+1):first_stable_sample_EEG+(length(EEG_2_segmented)+1)*EEG_SR_KHz*1000*binsize_vec(2,9)-file_begin_sample_EEG_2);
                       EEG_3_segmented{1,length(EEG_3_segmented)+1}=EEG_3(max(1,first_stable_sample_EEG+length(EEG_3_segmented)*EEG_SR_KHz*1000*binsize_vec(2,9)-file_begin_sample_EEG_3+1):first_stable_sample_EEG+(length(EEG_3_segmented)+1)*EEG_SR_KHz*1000*binsize_vec(2,9)-file_begin_sample_EEG_3);
                       EEG_4_segmented{1,length(EEG_4_segmented)+1}=EEG_4(max(1,first_stable_sample_EEG+length(EEG_4_segmented)*EEG_SR_KHz*1000*binsize_vec(2,9)-file_begin_sample_EEG_4+1):first_stable_sample_EEG+(length(EEG_4_segmented)+1)*EEG_SR_KHz*1000*binsize_vec(2,9)-file_begin_sample_EEG_4);
                       EEG_5_segmented{1,length(EEG_5_segmented)+1}=EEG_5(max(1,first_stable_sample_EEG+length(EEG_5_segmented)*EEG_SR_KHz*1000*binsize_vec(2,9)-file_begin_sample_EEG_5+1):first_stable_sample_EEG+(length(EEG_5_segmented)+1)*EEG_SR_KHz*1000*binsize_vec(2,9)-file_begin_sample_EEG_5);
                       bs_begin_sample_PS_EEG(1,length(bs_begin_sample_PS_EEG)+1)=first_stable_sample_EEG+(length(EEG_5_segmented)-1)*EEG_SR_KHz*1000*binsize_vec(2,9);
                       if (first_stable_sample_EEG+(length(EEG_5_segmented)+1)*EEG_SR_KHz*1000*binsize_vec(2,9)-1>=last_stable_sample_EEG) && ~ismember(first_stable_sample_EEG+(length(EEG_5_segmented))*EEG_SR_KHz*1000*binsize_vec(2,9)-1,last_stable_sample_EEG+[0,-1]) % this minus 1 sample jitter is added to avoid a situation where when last_stable_sample_EEG is only one sample higher than the length of the last segment, a whole new unnecessary segment will be created. This jitter is justified because of the floor operator I am doing to calculate the first_stable_sample_EEG and last_stable_sample_EEG - the rounding can introduce plus minus one sample which doesn't correspond to real length. In the +1 case this is not a problem since zero padding is performed. In the -1 case it should be corrected.
                           EEG_1_segmented{1,length(EEG_1_segmented)+1}=EEG_1(first_stable_sample_EEG+length(EEG_1_segmented)*EEG_SR_KHz*1000*binsize_vec(2,9)-file_begin_sample_EEG_1+1:min(length(EEG_1),last_stable_sample_EEG-file_begin_sample_EEG_1+1));
                           EEG_1_segmented{1,length(EEG_1_segmented)}=[EEG_1_segmented{1,length(EEG_1_segmented)},zeros(1,EEG_SR_KHz*1000*binsize_vec(2,9)-length(EEG_1_segmented{1,length(EEG_1_segmented)}))]; % ZP
                           EEG_2_segmented{1,length(EEG_2_segmented)+1}=EEG_2(first_stable_sample_EEG+length(EEG_2_segmented)*EEG_SR_KHz*1000*binsize_vec(2,9)-file_begin_sample_EEG_2+1:min(length(EEG_2),last_stable_sample_EEG-file_begin_sample_EEG_2+1));
                           EEG_2_segmented{1,length(EEG_2_segmented)}=[EEG_2_segmented{1,length(EEG_2_segmented)},zeros(1,EEG_SR_KHz*1000*binsize_vec(2,9)-length(EEG_2_segmented{1,length(EEG_2_segmented)}))]; % ZP
                           EEG_3_segmented{1,length(EEG_3_segmented)+1}=EEG_3(first_stable_sample_EEG+length(EEG_3_segmented)*EEG_SR_KHz*1000*binsize_vec(2,9)-file_begin_sample_EEG_3+1:min(length(EEG_3),last_stable_sample_EEG-file_begin_sample_EEG_3+1));
                           EEG_3_segmented{1,length(EEG_3_segmented)}=[EEG_3_segmented{1,length(EEG_3_segmented)},zeros(1,EEG_SR_KHz*1000*binsize_vec(2,9)-length(EEG_3_segmented{1,length(EEG_3_segmented)}))]; % ZP
                           EEG_4_segmented{1,length(EEG_4_segmented)+1}=EEG_4(first_stable_sample_EEG+length(EEG_4_segmented)*EEG_SR_KHz*1000*binsize_vec(2,9)-file_begin_sample_EEG_4+1:min(length(EEG_4),last_stable_sample_EEG-file_begin_sample_EEG_4+1));
                           EEG_4_segmented{1,length(EEG_4_segmented)}=[EEG_4_segmented{1,length(EEG_4_segmented)},zeros(1,EEG_SR_KHz*1000*binsize_vec(2,9)-length(EEG_4_segmented{1,length(EEG_4_segmented)}))]; % ZP
                           EEG_5_segmented{1,length(EEG_5_segmented)+1}=EEG_5(first_stable_sample_EEG+length(EEG_5_segmented)*EEG_SR_KHz*1000*binsize_vec(2,9)-file_begin_sample_EEG_5+1:min(length(EEG_5),last_stable_sample_EEG-file_begin_sample_EEG_5+1));
                           EEG_5_segmented{1,length(EEG_5_segmented)}=[EEG_5_segmented{1,length(EEG_5_segmented)},zeros(1,EEG_SR_KHz*1000*binsize_vec(2,9)-length(EEG_5_segmented{1,length(EEG_5_segmented)}))]; % ZP
                           bs_begin_sample_PS_EEG(1,length(bs_begin_sample_PS_EEG)+1)=first_stable_sample_EEG+(length(EEG_5_segmented)-1)*EEG_SR_KHz*1000*binsize_vec(2,9);
                       end
                   end
                   if Analyze_EEG_to_FR_SW_correlation
                       if stable_period_count==1
                           EEG_SW_content=nan(5,0);
                           mean_amplitude_EEG_SW=nan(5,0);
                           above_thresh_EEG_SW=nan(5,0);     
                       end
                       for pow_at_SW=1:length(EEG_5_segmented) % added 031217 to check whether there is a correlation between SW content in the EEGs and SW content in the FR spectrum
                           EEG_SW_content_per_bin=nan(5,1);
                           EEG_SW_mean_amplitude_per_bin=nan(5,1);
                           EEG_SW_above_thresh_per_bin=nan(5,1);

                           EEG_1_segmented{1,pow_at_SW}=EEG_1_segmented{1,pow_at_SW}-nanmean(EEG_1_segmented{1,pow_at_SW});
                           [spectrum_for_EEG_1,f_EEG]=periodogram(EEG_1_segmented{1,pow_at_SW},hamming(length(EEG_1_segmented{1,pow_at_SW})),2^(nextpow2(length(EEG_1_segmented{1,pow_at_SW}))),EEG_SR_KHz*1000); % PSD is returned in units: V^2/Hz.
                           spectrum_for_EEG_1=spectrum_for_EEG_1(1:find(f_EEG>=35,1,'first'));
                           spectrum_for_EEG_1=spectrum_for_EEG_1/sum(spectrum_for_EEG_1);
                           EEG_SW_content_per_bin(1,1)=sum(spectrum_for_EEG_1(find(f_EEG>=0.1,1,'first'):find(f_EEG<=2,1,'last')));
%                            EEG_SW_content_per_bin(1,1)=nanmean(spectrum_for_EEG_1(find(f_EEG>=9,1,'first'):find(f_EEG<=15,1,'last')))/nanmean(spectrum_for_EEG_1(find(f_EEG>=0.3,1,'first'):find(f_EEG<=2,1,'last')));
                           signal=BWfilter_designer(EEG_1_segmented{1,pow_at_SW}, EEG_SR_KHz*1000, bandpass_SW, bandstop_SW, 'BP'); % added 031217. I normally did the SW filtration before, when I first harvested the data, but then I wanted to compare the SW proportion out of all power with the SW power at FR.
                           h_signal=hilbert(signal); ins_amp=abs(h_signal); clear h_signal % this is the instantaneous amplitude of the (already filtered) signal
                           ins_amp(1,1:100)=ins_amp(1,101); ins_amp(1,end-100+1:end)=ins_amp(1,end-100); % a correction to the edge casea 020517                       
                           EEG_SW_mean_amplitude_per_bin(1,1)=nanmean(ins_amp);
                           EEG_SW_above_thresh_per_bin(1,1)=length(find(ins_amp*bitre>wave_amplitude_min_thresh))/length(ins_amp); clear ins_amp

                           EEG_2_segmented{1,pow_at_SW}=EEG_2_segmented{1,pow_at_SW}-nanmean(EEG_2_segmented{1,pow_at_SW});
                           [spectrum_for_EEG_2,f_EEG]=periodogram(EEG_2_segmented{1,pow_at_SW},hamming(length(EEG_2_segmented{1,pow_at_SW})),2^(nextpow2(length(EEG_2_segmented{1,pow_at_SW}))),EEG_SR_KHz*1000); % PSD is returned in units: V^2/Hz.
                           spectrum_for_EEG_2=spectrum_for_EEG_2(1:find(f_EEG>=35,1,'first'));
                           spectrum_for_EEG_2=spectrum_for_EEG_2/sum(spectrum_for_EEG_2);
                           EEG_SW_content_per_bin(2,1)=sum(spectrum_for_EEG_2(find(f_EEG>=0.1,1,'first'):find(f_EEG<=2,1,'last')));
%                            EEG_SW_content_per_bin(2,1)=nanmean(spectrum_for_EEG_2(find(f_EEG>=9,1,'first'):find(f_EEG<=15,1,'last')))/nanmean(spectrum_for_EEG_2(find(f_EEG>=0.3,1,'first'):find(f_EEG<=2,1,'last')));
                           signal=BWfilter_designer(EEG_2_segmented{1,pow_at_SW}, EEG_SR_KHz*1000, bandpass_SW, bandstop_SW, 'BP'); % added 031217. I normally did the SW filtration before, when I first harvested the data, but then I wanted to compare the SW proportion out of all power with the SW power at FR.
                           h_signal=hilbert(signal); ins_amp=abs(h_signal); clear h_signal % this is the instantaneous amplitude of the (already filtered) signal
                           ins_amp(1,1:100)=ins_amp(1,101); ins_amp(1,end-100+1:end)=ins_amp(1,end-100);
                           EEG_SW_mean_amplitude_per_bin(2,1)=nanmean(ins_amp);
                           EEG_SW_above_thresh_per_bin(2,1)=length(find(ins_amp*bitre>wave_amplitude_min_thresh))/length(ins_amp); clear ins_amp                      

                           EEG_3_segmented{1,pow_at_SW}=EEG_3_segmented{1,pow_at_SW}-nanmean(EEG_3_segmented{1,pow_at_SW});
                           [spectrum_for_EEG_3,f_EEG]=periodogram(EEG_3_segmented{1,pow_at_SW},hamming(length(EEG_3_segmented{1,pow_at_SW})),2^(nextpow2(length(EEG_3_segmented{1,pow_at_SW}))),EEG_SR_KHz*1000); % PSD is returned in units: V^2/Hz.
                           spectrum_for_EEG_3=spectrum_for_EEG_3(1:find(f_EEG>=35,1,'first'));
                           spectrum_for_EEG_3=spectrum_for_EEG_3/sum(spectrum_for_EEG_3);
                           EEG_SW_content_per_bin(3,1)=sum(spectrum_for_EEG_3(find(f_EEG>=0.1,1,'first'):find(f_EEG<=2,1,'last')));
%                            EEG_SW_content_per_bin(3,1)=nanmean(spectrum_for_EEG_3(find(f_EEG>=9,1,'first'):find(f_EEG<=15,1,'last')))/nanmean(spectrum_for_EEG_3(find(f_EEG>=0.3,1,'first'):find(f_EEG<=2,1,'last')));
                           signal=BWfilter_designer(EEG_3_segmented{1,pow_at_SW}, EEG_SR_KHz*1000, bandpass_SW, bandstop_SW, 'BP'); % added 031217. I normally did the SW filtration before, when I first harvested the data, but then I wanted to compare the SW proportion out of all power with the SW power at FR.
                           h_signal=hilbert(signal); ins_amp=abs(h_signal); % this is the instantaneous amplitude of the (already filtered) signal
                           ins_amp(1,1:100)=ins_amp(1,101); ins_amp(1,end-100+1:end)=ins_amp(1,end-100);
                           EEG_SW_mean_amplitude_per_bin(3,1)=nanmean(ins_amp);
                           EEG_SW_above_thresh_per_bin(3,1)=length(find(ins_amp*bitre>wave_amplitude_min_thresh))/length(ins_amp); clear ins_amp                                             

                           EEG_4_segmented{1,pow_at_SW}=EEG_4_segmented{1,pow_at_SW}-nanmean(EEG_4_segmented{1,pow_at_SW});
                           [spectrum_for_EEG_4,f_EEG]=periodogram(EEG_4_segmented{1,pow_at_SW},hamming(length(EEG_4_segmented{1,pow_at_SW})),2^(nextpow2(length(EEG_4_segmented{1,pow_at_SW}))),EEG_SR_KHz*1000); % PSD is returned in units: V^2/Hz.
                           spectrum_for_EEG_4=spectrum_for_EEG_4(1:find(f_EEG>=35,1,'first'));
                           spectrum_for_EEG_4=spectrum_for_EEG_4/sum(spectrum_for_EEG_4);
                           EEG_SW_content_per_bin(4,1)=sum(spectrum_for_EEG_4(find(f_EEG>=0.1,1,'first'):find(f_EEG<=2,1,'last')));
%                            EEG_SW_content_per_bin(4,1)=nanmean(spectrum_for_EEG_4(find(f_EEG>=9,1,'first'):find(f_EEG<=15,1,'last')))/nanmean(spectrum_for_EEG_4(find(f_EEG>=0.3,1,'first'):find(f_EEG<=2,1,'last')));
                           signal=BWfilter_designer(EEG_4_segmented{1,pow_at_SW}, EEG_SR_KHz*1000, bandpass_SW, bandstop_SW, 'BP'); % added 031217. I normally did the SW filtration before, when I first harvested the data, but then I wanted to compare the SW proportion out of all power with the SW power at FR.
                           h_signal=hilbert(signal); ins_amp=abs(h_signal); % this is the instantaneous amplitude of the (already filtered) signal
                           ins_amp(1,1:100)=ins_amp(1,101); ins_amp(1,end-100+1:end)=ins_amp(1,end-100);
                           EEG_SW_mean_amplitude_per_bin(4,1)=nanmean(ins_amp);
                           EEG_SW_above_thresh_per_bin(4,1)=length(find(ins_amp*bitre>wave_amplitude_min_thresh))/length(ins_amp); clear ins_amp

                           EEG_5_segmented{1,pow_at_SW}=EEG_5_segmented{1,pow_at_SW}-nanmean(EEG_5_segmented{1,pow_at_SW});
                           [spectrum_for_EEG_5,f_EEG]=periodogram(EEG_5_segmented{1,pow_at_SW},hamming(length(EEG_5_segmented{1,pow_at_SW})),2^(nextpow2(length(EEG_5_segmented{1,pow_at_SW}))),EEG_SR_KHz*1000); % PSD is returned in units: V^2/Hz.
                           spectrum_for_EEG_5=spectrum_for_EEG_1(1:find(f_EEG>=35,1,'first'));
                           spectrum_for_EEG_5=spectrum_for_EEG_5/sum(spectrum_for_EEG_5);
                           EEG_SW_content_per_bin(5,1)=sum(spectrum_for_EEG_5(find(f_EEG>=0.1,1,'first'):find(f_EEG<=2,1,'last')));                       
%                            EEG_SW_content_per_bin(5,1)=nanmean(spectrum_for_EEG_5(find(f_EEG>=9,1,'first'):find(f_EEG<=15,1,'last')))/nanmean(spectrum_for_EEG_5(find(f_EEG>=0.3,1,'first'):find(f_EEG<=2,1,'last')));
                           signal=BWfilter_designer(EEG_5_segmented{1,pow_at_SW}, EEG_SR_KHz*1000, bandpass_SW, bandstop_SW, 'BP'); % added 031217. I normally did the SW filtration before, when I first harvested the data, but then I wanted to compare the SW proportion out of all power with the SW power at FR.
                           h_signal=hilbert(signal); ins_amp=abs(h_signal); % this is the instantaneous amplitude of the (already filtered) signal
                           ins_amp(1,1:100)=ins_amp(1,101); ins_amp(1,end-100+1:end)=ins_amp(1,end-100);
                           EEG_SW_mean_amplitude_per_bin(5,1)=nanmean(ins_amp);
                           EEG_SW_above_thresh_per_bin(5,1)=length(find(ins_amp*bitre>wave_amplitude_min_thresh))/length(ins_amp); clear ins_amp                     

                           EEG_SW_content=[EEG_SW_content,EEG_SW_content_per_bin];
                           mean_amplitude_EEG_SW=[mean_amplitude_EEG_SW,EEG_SW_mean_amplitude_per_bin];
                           above_thresh_EEG_SW=[above_thresh_EEG_SW,EEG_SW_above_thresh_per_bin];
                       end
                   end
                   end
                   if Local_LFP
                       LFP_1_segmented={};
                       bs_begin_sample_PS_LFP=[];
                       if LFP_SR_KHz==44
                           first_stable_sample_LFP=max(file_begin_sample_LFP_1,bs_begin_sample_FR(1,1));
                       else
                           first_stable_sample_LFP=max(file_begin_sample_LFP_1,floor(bs_begin_sample_FR(1,1)/Info{1,unitnum}.SAMPLING*LFP_SR_KHz)); % added 111316
                       end
                       last_stable_sample_LFP=floor(last_stable_sample(1,stable_period_count)/Info{1,unitnum}.SAMPLING*LFP_SR_KHz);

                       while first_stable_sample_LFP+(length(LFP_1_segmented)+1)*LFP_SR_KHz*1000*binsize_vec(2,9)-1<=last_stable_sample_LFP
                           LFP_1_segmented{1,length(LFP_1_segmented)+1}=LFP_1(first_stable_sample_LFP+length(LFP_1_segmented)*LFP_SR_KHz*1000*binsize_vec(2,9)-file_begin_sample_LFP_1+1:first_stable_sample_LFP+(length(LFP_1_segmented)+1)*LFP_SR_KHz*1000*binsize_vec(2,9)-file_begin_sample_LFP_1); 
                           bs_begin_sample_PS_LFP(1,length(bs_begin_sample_PS_LFP)+1)=first_stable_sample_LFP+(length(LFP_1_segmented)-1)*LFP_SR_KHz*1000*binsize_vec(2,9);
                           if (first_stable_sample_LFP+(length(LFP_1_segmented)+1)*LFP_SR_KHz*1000*binsize_vec(2,9)-1>=last_stable_sample_LFP) && ~ismember(first_stable_sample_LFP+(length(LFP_1_segmented))*LFP_SR_KHz*1000*binsize_vec(2,9)-1,last_stable_sample_LFP+[0,-1]) % 070817 this minus 1 sample jitter is added to avoid a situation where when last_stable_sample_EEG is only one sample higher than the length of the last segment, a whole new unnecessary segment will be created. This jitter is justified because of the floor operator I am doing to calculate the first_stable_sample_EEG and last_stable_sample_EEG - the rounding can introduce plus minus one sample which doesn't correspond to real length. In the +1 case this is not a problem since zero padding is performed. In the -1 case it should be corrected.
                               LFP_1_segmented{1,length(LFP_1_segmented)+1}=LFP_1(first_stable_sample_LFP+length(LFP_1_segmented)*LFP_SR_KHz*1000*binsize_vec(2,9)-file_begin_sample_LFP_1+1:last_stable_sample_LFP-file_begin_sample_LFP_1+1);
                               LFP_1_segmented{1,length(LFP_1_segmented)}=[LFP_1_segmented{1,length(LFP_1_segmented)},zeros(1,LFP_SR_KHz*1000*binsize_vec(2,9)-length(LFP_1_segmented{1,length(LFP_1_segmented)}))]; % ZP
                               bs_begin_sample_PS_LFP(1,length(bs_begin_sample_PS_LFP)+1)=first_stable_sample_LFP+(length(LFP_1_segmented)-1)*LFP_SR_KHz*1000*binsize_vec(2,9);
                           end
                       end
                   end

                   if stable_period_count==1
                       N3_begs=[];
                       N3_ends=[];
                       if Global_EEG && Analyze_spike_to_EEG_SW_phase_locking
                           fruitful_segments=zeros(1,5);
%                            best_typical_waveforms=nan(0,EEG_SR_KHz*2*1000+500+500+1); % (2-sec+100 samples)-lengthed examples of oscillations
                       end
                       if Local_LFP && ~Calculate_MU_Spectrum && Analyze_spike_to_EEG_SW_phase_locking
                           fruitful_segments=zeros(1,1);
%                            best_typical_waveforms=nan(0,LFP_SR_KHz*2*1000+500+500+1); % (2-sec+100 samples)-lengthed examples of oscillations                           
                       end
%                        best_typical_spikes=cell(0,1);
%                        best_typical_lead=nan(0,1);
                   end
                   N3_segments_Fr_OR_Cr=[];
                   if unitnum==1 && stable_period_count==1
                    SWS_stats=cell(1,length(unit)); % changed 061617 from =struct, and all the appearances of SWS_stats were changed to SWS_stats{1,unitnum}
                   end
                   % find NREM bins and erase all which are not
                   NREM_bins=[]; REM_bins=[]; WAKE_bins=[];
%                    if Local_LFP && ~Calculate_MU_Spectrum
%                        bs_begin_sample_PS=floor(bs_begin_sample_PS_LFP/LFP_SR_KHz*Info{1,unitnum}.SAMPLING);
%                    end
                   if Global_EEG
                       bs_begin_sample_PS=floor(bs_begin_sample_PS_EEG/EEG_SR_KHz*Info{1,unitnum}.SAMPLING);
                   end
                   for ii=1:length(bs_begin_sample_PS)
                       A=find(all_begs<=bs_begin_sample_PS(1,ii),1,'last');
%                        if ii==1 && all_begs(1)>bs_begin_sample_PS(1,1) % erase 022217!!
%                            A=1;
%                        end
                       closest_bin_end=min(bs_begin_sample_PS(1,ii)+Info{unitnum}.SAMPLING*binsize_vec(2,9)*1000-1,last_stable_sample(stable_period_count));
                       B=find(all_ends>=closest_bin_end,1,'first');
                       marker=NaN;
                       if isempty(A) % ERASE
                           A=1;
                       end
                       if ((B-A)==0 || ((B-A)==1 && closest_bin_end-all_begs(A+1)<all_begs(A+1)-bs_begin_sample_PS(1,ii)))
                          marker=all_begs(A);
                       elseif ((B-A)==1 && closest_bin_end-all_begs(A+1)>=all_begs(A+1)-bs_begin_sample_PS(1,ii))
                          marker=all_begs(A+1);
                       elseif (B-A)==2 % I added this in 062317 after I figures out that this situation can actually happen, If the epoch is a few samples short of 440000 and the bs happens to start really at the end of the previous one, traverse the entire shorter epoch and then end in the following one.
                          marker=all_begs(A+1);                                                        
                       end
                       if ismember(marker,polysomnography{unitnum}.stages.N2.begin_sample)
                           NREM_bins=[NREM_bins,ii];
                       elseif ismember(marker,polysomnography{unitnum}.stages.R.begin_sample)
                           REM_bins=[REM_bins,ii];
                       elseif ismember(marker,polysomnography{unitnum}.stages.W.begin_sample)
                           WAKE_bins=[WAKE_bins,ii];                           
                       end
                   end
                   NREM_starts=bs_begin_sample_FR(NREM_bins); % only works when binsize_FR=binsize_SWS=10s;
                   aaa=[];
                   for nn=1:length(NREM_starts)
                       aaa=[aaa,find(polysomnography{1,unitnum}.all_beginnings>=NREM_starts(nn)-1000 & polysomnography{1,unitnum}.all_beginnings<=NREM_starts(nn)+1000)];
                       if isempty(find(polysomnography{1,unitnum}.all_beginnings>=NREM_starts(nn)-1000 & polysomnography{1,unitnum}.all_beginnings<=NREM_starts(nn)+1000))
                           disp(['unitnum=',num2str(unitnum),' NREM segment=',num2str(nn),' out of ',num2str(length(NREM_starts)),': A-synchrony in polysomnography Beginning files in relation to bin beginnings. Bin begins ingnored from now on'])
                           continue;
                       end
                   end
                   NREM_begs=polysomnography{1,unitnum}.all_beginnings(aaa)'; % for N3 analysis, Aviv 113016
                   NREM_ends=polysomnography{1,unitnum}.all_ends(aaa)';
                   
                   SWS_stats{1,unitnum}.NREM_bins{1,stable_period_count}=NREM_bins;
                   SWS_stats{1,unitnum}.NREM_bins_sample_starts{1,stable_period_count}=bs_begin_sample_FR(NREM_bins);
                   SWS_stats{1,unitnum}.REM_bins{1,stable_period_count}=REM_bins;
                   SWS_stats{1,unitnum}.WAKE_bins{1,stable_period_count}=WAKE_bins;
                   SWS_stats{1,unitnum}.polysomnography_NREM_bins{1,stable_period_count}=aaa;

                   if calculate_EEG_measures
                       EEG_range_correlation=nan(length(EEG_1_segmented),10);
                       SW_range_correlation=nan(length(EEG_1_segmented),10);
                       EEG_instantaneous_frequency=nan(length(EEG_1_segmented),5);
                       for ss=1:length(EEG_1_segmented)
                           clear data_cell_*
                           for arranger=1:5
                               eval(['signal=EEG_',num2str(arranger),'_segmented{1,ss};']);
                                data_cell_EEG{1,arranger}=BWfilter_designer(signal,1000*EEG_SR_KHz,bandpass_wider,bandstop_wider,'BP');
                                data_cell_SW{1,arranger}=BWfilter_designer(signal,1000*EEG_SR_KHz,bandpass_SW,bandstop_SW,'BP');
                           end
                           corrs_EEG=[];
                           corrs_SW=[];
                           for oneside=1:5
                               for secondside=oneside+1:5
                                   % calculate correlation between all EEG electrodes,
                                   % in the SW range and in the EEG range
                                   corrs_EEG=[corrs_EEG;corr2(data_cell_EEG{1,oneside},data_cell_EEG{1,secondside})];
                                   corrs_SW=[corrs_SW;corr2(data_cell_SW{1,oneside},data_cell_SW{1,secondside})];
                               end
                               % calculate the mean instantaneous frequency of the
                               % EEG in the SW range                               
                               ins_freq_EEG=[0,1000*EEG_SR_KHz/(2*pi)*diff(unwrap(angle(hilbert(data_cell_SW{1,oneside}))))]; % 070217
                               ins_freq_EEG(find(ins_freq_EEG<=0 | ins_freq_EEG>=2))=NaN;
                               EEG_instantaneous_frequency(ss,oneside)=nanmean(ins_freq_EEG);                           
                           end
                           SW_range_correlation(ss,:)=corrs_SW';
                           EEG_range_correlation(ss,:)=corrs_EEG';
                       end
                   end                   
                   
                   if Calculate_EEG_spectrum_all_stages
                       EEG_1_segmented_example_PS=EEG_1_segmented;
                       EEG_2_segmented_example_PS=EEG_2_segmented;
                       EEG_3_segmented_example_PS=EEG_3_segmented;
                       EEG_4_segmented_example_PS=EEG_4_segmented;
                       EEG_5_segmented_example_PS=EEG_5_segmented;
                   end
                   EEG_1_segmented_orig=EEG_1_segmented;
                   EEG_2_segmented_orig=EEG_2_segmented;
                   EEG_3_segmented_orig=EEG_3_segmented;
                   if Global_EEG
                       EEG_1_segmented=EEG_1_segmented(1,NREM_bins);
                       EEG_2_segmented=EEG_2_segmented(1,NREM_bins);
                       EEG_3_segmented=EEG_3_segmented(1,NREM_bins);
                       EEG_4_segmented=EEG_4_segmented(1,NREM_bins);
                       EEG_5_segmented=EEG_5_segmented(1,NREM_bins);
                       bs_begin_sample_PS_EEG=bs_begin_sample_PS_EEG(1,NREM_bins);
                   end
                   % calculate the SW content of the LFP segments, to
                   % compare with unit SW content during SWS
                   if Local_LFP && LFP_to_unit_analysis
                       if stable_period_count==1
                           % 070817
                           All_unit_LFP_spectrum_N2=[];
                           All_unit_LFP_EEG_corr_N2=[];
                           All_unit_LFP_IF_N2=[];
                           
                           All_unit_LFP_spectrum_N3=[];
                           All_unit_LFP_EEG_corr_N3=[]; 
                           All_unit_LFP_IF_N3=[]; 
                           
                           All_unit_LFP_spectrum_R=[];
                           All_unit_LFP_EEG_corr_R=[]; 
                           All_unit_LFP_IF_R=[]; 
                           
                           All_unit_LFP_spectrum_W=[];
                           All_unit_LFP_EEG_corr_W=[]; 
                           All_unit_LFP_IF_W=[]; 
                       end
                       for p=1:length(LFP_1_segmented)
                           LFP_1_segmented{1,p}=LFP_1_segmented{1,p}-nanmean(LFP_1_segmented{1,p});
                           LFP_1_segmented{1,p}=LFP_1_segmented{1,p}/std(LFP_1_segmented{1,p});
                           [PXX,FREQAXIS_LFP]=periodogram(LFP_1_segmented{1,p},hamming(length(LFP_1_segmented{1,p})),2^(nextpow2(length(LFP_1_segmented{1,p}))),LFP_SR_KHz*1000);
%                             load('freqaxis_for_LFP_PS_do_not_erase')
%                            [PXX,FREQAXIS_LFP]=periodogram(LFP_1_segmented{1,p},hamming(length(LFP_1_segmented{1,p})),freqs_to_analyze,LFP_SR_KHz*1000);
%                            PXX=PXX(1:find(FREQAXIS_LFP>=bandpass_wider(2),1,'first')); 
                           PXX=PXX/sum(PXX);
                           period_LFP_spectrum(:,p)=PXX;
                           filtered_rel_LFP=BWfilter_designer(double(LFP_1_segmented{1,p}),LFP_SR_KHz*1000,bandpass_SW,bandstop_SW,'BP');
                           ins_freq_LFP=[0,1000*LFP_SR_KHz/(2*pi)*diff(unwrap(angle(hilbert(filtered_rel_LFP))))]; % 070217
                           ins_freq_LFP(find(ins_freq_LFP<=0 | ins_freq_LFP>=2))=NaN;
                           period_LFP_IF(1,p)=nanmean(ins_freq_LFP);                           
                           
                           %070217
                           EEG_1_filtered=BWfilter_designer(double(EEG_1_segmented_orig{1,p}),EEG_SR_KHz*1000,bandpass_SW,bandstop_SW,'BP');
                           EEG_1_filtered=EEG_1_filtered(find(mod(1:length(EEG_1_filtered),2)==0));
                           filtered_rel_LFP=(filtered_rel_LFP-nanmean(filtered_rel_LFP))/std(filtered_rel_LFP);
                           EEG_1_filtered=(EEG_1_filtered-nanmean(EEG_1_filtered))/std(EEG_1_filtered);
                           LFP_EEG_corr(1,p)=corr2(filtered_rel_LFP,EEG_1_filtered);
                           EEG_2_filtered=BWfilter_designer(double(EEG_2_segmented_orig{1,p}),EEG_SR_KHz*1000,bandpass_SW,bandstop_SW,'BP');
                           EEG_2_filtered=EEG_2_filtered(find(mod(1:length(EEG_2_filtered),2)==0));
                           LFP_EEG_corr(2,p)=corr2(filtered_rel_LFP,EEG_2_filtered);
                           EEG_3_filtered=BWfilter_designer(double(EEG_3_segmented_orig{1,p}),EEG_SR_KHz*1000,bandpass_SW,bandstop_SW,'BP');
                           EEG_3_filtered=EEG_3_filtered(find(mod(1:length(EEG_3_filtered),2)==0));                           
                           LFP_EEG_corr(3,p)=corr2(filtered_rel_LFP,EEG_3_filtered);
                       end
                   end
                   
                  % Move over all NREM bins, compute their instantaneous amplitude and phase, 
                   % and use the amplitude to decide whether this is NREM3
                   min_phase_std_for_subsegment=0.3;
                   max_amplitude_for_subsegment=300;
                   min_sec_for_SWS_subsegment=0.05; % original: 0.25 This is the min length for a SWS subsegment within a NREM bin. There may be ofcourse many subsegments.
                   SWS_stats{1,unitnum}.wave_amplitude_min_thresh=wave_amplitude_min_thresh;
                   SWS_stats{1,unitnum}.N3_fraction=N3_fraction;
                   bin_width=8; %ms. This is the minimal ms number that would give an integer num of samples.
                   SWS_stats{1,unitnum}.bin_width=bin_width;
                   SWS_stats{1,unitnum}.min_phase_std_for_subsegment=min_phase_std_for_subsegment;
                   SWS_stats{1,unitnum}.max_amplitude_for_subsegment=max_amplitude_for_subsegment;
                   SWS_stats{1,unitnum}.min_sec_for_SWS_subsegment=min_sec_for_SWS_subsegment;
                   if Global_EEG
                        stablespikes_on_EEG_KHz=round(stablespikes/Info{1,unitnum}.SAMPLING*EEG_SR_KHz);
                   end
                   if Local_LFP && ~Calculate_MU_Spectrum
                       stablespikes_on_LFP_KHz=round(stablespikes/Info{1,unitnum}.SAMPLING*LFP_SR_KHz);
                   end
%                  pause_end_on_EEG_KHz=round(pause_end/Info{1,unitnum}.SAMPLING*EEG_SR_KHz); % take only the first spike in an "up" fifinr period.
    %              phase_map=-pi:2*pi/1000:3*pi-2*pi/1000; % changed 043017 to have more range - -pi to 3 pi that will convert to 0-4pi
                   phase_map=0:2*pi/1000:2*pi-2*pi/1000;
    %              phase_map=0:1:627; % changed to check what happens if I use 1000 bins that cover all the circle.
                   if Analyze_spike_to_EEG_SW_phase_locking
                       phase_per_spike=nan(length(stablespikes),5); % to have all the spikes from all recording time of the same neuron together
                       spikes_per_phase=zeros(length(phase_map),5); % organized 0 to 2*pi
    %                    phase_per_bin=nan(length(EEG_5_segmented),5,2); % for every NREM bin an std and mean phase of the oscillation is calculated
                   end
                   if Global_EEG && Analyze_spike_to_EEG_SW_phase_locking
                      length_of_SWS_segments{1,stable_period_count}=zeros(length(EEG_5_segmented),5,100); % 4 is the probable maximal number of SWS subsegments per N3 10-s segment;
                      spikes_per_SWS_segments{1,stable_period_count}=NaN(length(EEG_5_segmented),5); %number of spikes is summed all over the SWS segment, not subsegment.
                   end
                   if Local_LFP && ~Calculate_MU_Spectrum && Analyze_spike_to_EEG_SW_phase_locking
                       length_of_SWS_segments{1,stable_period_count}=zeros(length(LFP_1_segmented),5,100); % 4 is the probable maximal number of SWS subsegments per N3 10-s segment;
                       spikes_per_SWS_segments{1,stable_period_count}=NaN(length(LFP_1_segmented),5); %number of spikes is summed all over the SWS segment, not subsegment.                       
                   end
                   if Global_EEG
                       if Analyze_EEG_to_FR_SW_correlation && stable_period_count==1
                           SW_amplitude_FR=[];
                           mean_SW_amplitude_EEG=nan(0,0);
                           above_thresh_SW_amplitude_EEG=nan(0,0);
                       elseif Analyze_EEG_to_FR_SW_correlation && stable_period_count~=1
                           mean_SW_amplitude_EEG_to_concatenate=nan(0,0);
                           above_thresh_SW_amplitude_EEG_to_concatenate=nan(0,0);
                       end
                       % bring back the next two to action 0050217
%                        ins_amp_FR_SW=Calculate_Phase_measures_of_FR(spikes_per_milli_sec,milli_second_begin_sample,binsize_vec(2,6),overlap_smoothing_settings,1);
%                        SW_amplitude_FR=[SW_amplitude_FR,ins_amp_FR_SW(1,NREM_bins)];
                       if stable_period_count==1
                           DAY_INST_FREQS=[];
                       end
                       INST_FREQS=nan(5,length(EEG_5_segmented));
                       for eeg_traces=1:5
                       for NREM_index=1:length(EEG_5_segmented)
                           local_spikes_EEG_KHz=stablespikes_on_EEG_KHz(stablespikes_on_EEG_KHz>=bs_begin_sample_PS_EEG(1,NREM_index) & stablespikes_on_EEG_KHz<bs_begin_sample_PS_EEG(1,NREM_index)+EEG_SR_KHz*1000*binsize_vec(2,9)-1)-bs_begin_sample_PS_EEG(1,NREM_index)+1; % define local spikes as the spikes that are inside the specific bin                           
%                          local_spikes_EEG_KHz=pause_end_on_EEG_KHz(pause_end_on_EEG_KHz>=bs_begin_sample_PS_EEG(1,NREM_index) & pause_end_on_EEG_KHz<bs_begin_sample_PS_EEG(1,NREM_index)+EEG_SR_KHz*1000*binsize_vec(2,9)-1)-bs_begin_sample_PS_EEG(1,NREM_index)+1; % define local spikes as the spikes that are inside the specific bin                                                                             
                           switch eeg_traces
                               case 1
                                   signal=EEG_1_segmented{1,NREM_index};
                               case 2
                                   signal=EEG_2_segmented{1,NREM_index};                                   
                               case 3
                                   signal=EEG_3_segmented{1,NREM_index};
                               case 4
                                   signal=EEG_4_segmented{1,NREM_index};
                               case 5
                                   signal=EEG_5_segmented{1,NREM_index};
                           end
                           signal=double(signal-nanmean(signal));
                           signal=BWfilter_designer(signal, EEG_SR_KHz*1000, bandpass_SW, bandstop_SW, 'BP'); % added 031217. I normally did the SW filtration before, when I first harvested the data, but then I wanted to compare the SW proportion out of all power with the SW power at FR.
                           h_signal=hilbert(signal);
                           ins_amp=abs(h_signal); % this is the instantaneous amplitude of the (already filtered) signal
                           ins_amp(1,1:100)=ins_amp(1,101); ins_amp(1,end-100+1:end)=ins_amp(1,end-100); % a correction to the edge casea 020517
                           ins_phase=atan2(imag(h_signal),real(h_signal));
                           ins_phase(find(ins_phase<0))=ins_phase(find(ins_phase<0))+2*pi; % convert to 0:2*pi rather than -pi:pi to avoid std artifacts.
                           
                           ins_freq_signal=[0,1000*EEG_SR_KHz/(2*pi)*diff(unwrap(angle(h_signal)))];
                           ins_freq_signal(find(ins_freq_signal<=0 | ins_freq_signal>=2))=NaN;
                           
                           if Analyze_spike_to_EEG_SW_phase_locking
                               rounded_ins_phase=interp1(phase_map,phase_map,ins_phase,'nearest','extrap'); % a line I found in the internet that should do the rounding of a vector to the nearest element in another vector.
    %                            rounded_ins_phase=round(ins_phase*100); % changed to check what happens if I use 1000 bins that cover all the circle.
                           end
                           h=find(ins_amp*bitre>=wave_amplitude_min_thresh);
                           ah=diff(h);
                           bh=diff([0 ah 0]==1);
                           bh_start=find(bh==1);
                           bh_end=find(bh==-1);
                           ch=bh_end-bh_start;
                           dh=find(ch>=min_sec_for_SWS_subsegment*EEG_SR_KHz*1000);
                           consolidated_SWA=[];
                           if Analyze_spike_to_EEG_SW_phase_locking
                               bin_starts_SWA=[];
    %                            bin_lengths=[];
                           end
                           for aaa=1:length(dh)
                               subsegment=h(bh_start(dh(aaa))):1:h(bh_end(dh(aaa)));
                               if (max(ins_amp(subsegment)*bitre)<max_amplitude_for_subsegment && std(ins_phase(subsegment))>=min_phase_std_for_subsegment)
                                   consolidated_SWA=[consolidated_SWA,subsegment];
                                   if Analyze_spike_to_EEG_SW_phase_locking
                                        length_of_SWS_segments{1,stable_period_count}(NREM_index,eeg_traces,aaa)=length_of_SWS_segments{1,stable_period_count}(NREM_index,eeg_traces,aaa)+length(subsegment);                                       
        %                                specific_segment=rounded_ins_phase(h(bh_start(dh(aaa))):h(bh_end(dh(aaa))));
        %                                phase_jumps_locations=find(diff(specific_segment)~=0)+1;
        %                                bin_starts_SWA=[bin_starts_SWA,h(bh_start(dh(aaa)))-1+[1,phase_jumps_locations]];
        %                                bin_lengths=[bin_lengths,diff(bin_starts_SWA),max(1,length(specific_segment)-phase_jumps_locations(end))];
                                        num_of_bins=ceil((h(bh_end(dh(aaa)))-h(bh_start(dh(aaa)))+1)/(bin_width*EEG_SR_KHz));
                                        first_bin_start=h(bh_start(dh(aaa)));
                                        bin_starts_SWA=[bin_starts_SWA,first_bin_start+bin_width*EEG_SR_KHz*[0:1:num_of_bins-1]];
                                   end
                               end
                           end
                           if length(consolidated_SWA)>=N3_fraction*length(ins_amp) % AASM criteria: more than 20% of the bin have more than 75 uV slow wave activity
                               % below, occipital derivations are not considered for SWS according to the AASM manual, that regards only frontals (We don't have enough frontals, so we also take centrals, which are very close to frontals).
                               if monkey==1
                                   if (strcmp(filenames{1,unitnum}(1,strfind(filenames{1,unitnum},'Data')+5:strfind(filenames{1,unitnum},'Data')+10),'101915') || strcmp(filenames{1,unitnum}(1,strfind(filenames{1,unitnum},'Data')+5:strfind(filenames{1,unitnum},'Data')+10),'102015') || strcmp(filenames{1,unitnum}(1,strfind(filenames{1,unitnum},'Data')+5:strfind(filenames{1,unitnum},'Data')+10),'061915') || strcmp(filenames{1,unitnum}(1,strfind(filenames{1,unitnum},'Data')+5:strfind(filenames{1,unitnum},'Data')+10),'100515') || strcmp(filenames{1,unitnum}(1,strfind(filenames{1,unitnum},'Data')+5:strfind(filenames{1,unitnum},'Data')+10),'061515') || strcmp(filenames{1,unitnum}(1,strfind(filenames{1,unitnum},'Data')+5:strfind(filenames{1,unitnum},'Data')+10),'061715'))                                   
                                       if (eeg_traces==3) % 101815, 101915, 100415, 061415, 061615, 061815
                                          N3_segments_Fr_OR_Cr=[N3_segments_Fr_OR_Cr,NREM_index]; 
                                          INST_FREQS(eeg_traces,NREM_index)=nanmean(ins_freq_signal(consolidated_SWA)); % take the instantaneous frequency as the mean of the frequencies only for those segments that are "declared" N3.
                                       end
                                   elseif (strcmp(filenames{1,unitnum}(1,strfind(filenames{1,unitnum},'Data')+5:strfind(filenames{1,unitnum},'Data')+10),'102215') || strcmp(filenames{1,unitnum}(1,strfind(filenames{1,unitnum},'Data')+5:strfind(filenames{1,unitnum},'Data')+10),'101415') || strcmp(filenames{1,unitnum}(1,strfind(filenames{1,unitnum},'Data')+5:strfind(filenames{1,unitnum},'Data')+10),'101515') || strcmp(filenames{1,unitnum}(1,strfind(filenames{1,unitnum},'Data')+5:strfind(filenames{1,unitnum},'Data')+10),'062615'))                                   
                                       if (eeg_traces==2 || eeg_traces==3) % 102115, 101315, 101415, 062515
                                          N3_segments_Fr_OR_Cr=[N3_segments_Fr_OR_Cr,NREM_index]; 
                                          INST_FREQS(eeg_traces,NREM_index)=nanmean(ins_freq_signal(consolidated_SWA)); 
                                       end                                   
                                   else
                                       if (eeg_traces==1 || eeg_traces==2 || eeg_traces==3)
                                          N3_segments_Fr_OR_Cr=[N3_segments_Fr_OR_Cr,NREM_index]; 
                                          INST_FREQS(eeg_traces,NREM_index)=nanmean(ins_freq_signal(consolidated_SWA)); 
                                       end
                                   end
                               elseif monkey==2
                                   if (strcmp(filenames{1,unitnum}(1,strfind(filenames{1,unitnum},'Data')+5:strfind(filenames{1,unitnum},'Data')+10),'041816') || strcmp(filenames{1,unitnum}(1,strfind(filenames{1,unitnum},'Data')+5:strfind(filenames{1,unitnum},'Data')+10),'070416'))                                   
                                       if (eeg_traces==1 || eeg_traces==3) % 041716, 070316
                                          N3_segments_Fr_OR_Cr=[N3_segments_Fr_OR_Cr,NREM_index]; 
                                          INST_FREQS(eeg_traces,NREM_index)=nanmean(ins_freq_signal(consolidated_SWA)); 
                                       end                                   
                                   else
                                       if (eeg_traces==1 || eeg_traces==2 || eeg_traces==3)
                                          N3_segments_Fr_OR_Cr=[N3_segments_Fr_OR_Cr,NREM_index]; 
                                          INST_FREQS(eeg_traces,NREM_index)=nanmean(ins_freq_signal(consolidated_SWA)); 
                                       end
                                   end                                   
                               end
                               if Analyze_spike_to_EEG_SW_phase_locking
                                   appropriate_spikes=find(ismember(local_spikes_EEG_KHz,consolidated_SWA)); % spikes which are appropriate are those that happen during a real SWS segment, according to the AASM manual
                                   fruitful_segments(1,eeg_traces)=fruitful_segments(1,eeg_traces)+1;
                                   if ~isempty(appropriate_spikes)
                                       spikes_per_SWS_segments{1,stable_period_count}(NREM_index,eeg_traces)=length(appropriate_spikes);
                                       phase_per_spike(find(isnan(phase_per_spike(:,eeg_traces)),1,'first'):find(isnan(phase_per_spike(:,eeg_traces)),1,'first')+length(ins_phase(local_spikes_EEG_KHz(appropriate_spikes)))-1,eeg_traces)=ins_phase(local_spikes_EEG_KHz(appropriate_spikes));
                                       bin2phase_mapping=rounded_ins_phase(bin_starts_SWA);
                                       subtract_bins_from_spikes_mat=(repmat(local_spikes_EEG_KHz(appropriate_spikes),length(bin_starts_SWA),1)-repmat(bin_starts_SWA',1,length(local_spikes_EEG_KHz(appropriate_spikes))));
                                       subtract_bins_from_spikes_mat(subtract_bins_from_spikes_mat<0)=inf;
                                       [~,indind]=min(subtract_bins_from_spikes_mat);
                                       for jjj=1:length(indind)
    %                                        if bin2phase_mapping(indind(jjj))==6.28
    %                                            bin2phase_mapping(indind(jjj))=0;
    %                                        end
    %                                        spikes_per_phase(floor(bin2phase_mapping(indind(jjj))/0.01)+1,eeg_traces)=spikes_per_phase(floor(bin2phase_mapping(indind(jjj))/0.01)+1,eeg_traces)+1/(bin_lengths(indind(jjj))/EEG_SR_KHz)*1000;
                                            spikes_per_phase(find(phase_map==bin2phase_mapping(indind(jjj))),eeg_traces)=spikes_per_phase(find(phase_map==bin2phase_mapping(indind(jjj))),eeg_traces)+1;
                                       end
    %                                    mean_phase=[mean_phase,nanmean(ins_phase(local_spikes_EEG_KHz(appropriate_spikes)))];
    %                                    phase_std=[phase_std,nanstd(ins_phase(local_spikes_EEG_KHz(appropriate_spikes)))];
                                         % Best typicals
    %                                      if rand(1)>0.5  % perform the procedure of finding the Best Typicals only in some cases
    %                                          if (h(bh_start(dh(1)))>=EEG_SR_KHz*1000+500 && h(bh_end(dh(1)))<=length(signal)-(EEG_SR_KHz*1000+500)) 
    %                                              bt=signal(h(bh_start(dh(1))):1:h(bh_end(dh(1))));
    %                                              [~,bt_max_ind]=max(bt);
    %                                              index_of_maximum_in_signal=h(bh_start(dh(1)))+bt_max_ind-1;
    %                                              bt=signal(index_of_maximum_in_signal-EEG_SR_KHz*1000-500:index_of_maximum_in_signal+EEG_SR_KHz*1000+500); % to create a 2751+500+500-lengthed vector
    %                                              bt_spikes=local_spikes_EEG_KHz(appropriate_spikes);
    %                                              bt_spikes=bt_spikes(bt_spikes>=index_of_maximum_in_signal-EEG_SR_KHz*1000-500 &bt_spikes<=index_of_maximum_in_signal+EEG_SR_KHz*1000+500)-(index_of_maximum_in_signal-EEG_SR_KHz*1000-500);
    %                                              best_typical_waveforms(size(best_typical_waveforms,1)+1,:)=bt; % 2-sec examples of oscillations
    %                                              best_typical_spikes{size(best_typical_spikes,1)+1,1}=bt_spikes;
    %                                              best_typical_lead(size(best_typical_lead,1)+1,1)=eeg_traces;
    %                                          end
    %                                      end
                                   end
                               end
%                                phase_per_bin(NREM_index,eeg_traces,1)=nanmean(mean_phase);
%                                phase_per_bin(NREM_index,eeg_traces,2)=nanmean(phase_std);
                           end
                       end
                    end
                    clear stablespikes_on_EEG_KHz                   
                   end
                   if Local_LFP && ~Calculate_MU_Spectrum
                       if stable_period_count==1
                           DAY_INST_FREQS_LFP=[];
                       end
                       if ~isempty(NREM_bins) && NREM_bins(end)>length(LFP_1_segmented) % 070817
                           NREM_bins_for_LFP=NREM_bins(1:end-1);
                           if ~isempty(N3_segments_Fr_OR_Cr) && N3_segments_Fr_OR_Cr(end)==length(NREM_bins)
                               N3_segments_Fr_OR_Cr_for_LFP=N3_segments_Fr_OR_Cr(1:end-1);
                           end
                       else
                           NREM_bins_for_LFP=NREM_bins;
                           N3_segments_Fr_OR_Cr_for_LFP=N3_segments_Fr_OR_Cr;
                       end         
                       if ~isempty(WAKE_bins) && WAKE_bins(end)>length(LFP_1_segmented) % 070817
                            WAKE_bins_for_LFP=WAKE_bins(1:end-1);
                       else
                           WAKE_bins_for_LFP=WAKE_bins;
                       end
                       if ~isempty(REM_bins) && REM_bins_bins(end)>length(LFP_1_segmented) % 070817
                            REM_bins_for_LFP=REM_bins(1:end-1);
                       else
                           REM_bins_for_LFP=REM_bins;
                       end                       
                       LFP_1_segmented=LFP_1_segmented(1,NREM_bins); % moved from above 080817
                       bs_begin_sample_PS_LFP=bs_begin_sample_PS_LFP(1,NREM_bins); % moved from above 080817
                        INST_FREQS_LFP=nan(1,length(LFP_1_segmented));
                        if Local_LFP && LFP_to_unit_analysis && stable_period_count==1
                            normalizer=0; 
                            phase_map=0:2*pi/1000:2*pi-2*pi/1000;
                            spikes_per_phase_LFP=zeros(length(phase_map),1);
                        end                    
                        for lfp_traces=1:1 
                           for NREM_index=1:length(LFP_1_segmented)
                               signal=LFP_1_segmented{1,NREM_index}; 
                               signal=double(signal-nanmean(signal));
                               signal=BWfilter_designer(signal, LFP_SR_KHz*1000, bandpass_SW, bandstop_SW, 'BP');                           
                               h_signal=hilbert(signal);
                               ins_amp=abs(h_signal); % this is the instantaneous amplitude of the (already filtered) signal
                               ins_freq_signal=[0,1000*LFP_SR_KHz/(2*pi)*diff(unwrap(angle(h_signal)))];
                               ins_freq_signal(find(ins_freq_signal<0 | ins_freq_signal>2))=NaN;                           
                               INST_FREQS_LFP(1,NREM_index)=nanmean(ins_freq_signal);
                               if LFP_to_unit_analysis
                                   normalizer=normalizer+1;
                                   local_spikes_LFP_KHz=stablespikes_on_LFP_KHz(stablespikes_on_LFP_KHz>=bs_begin_sample_PS_LFP(1,NREM_index) & stablespikes_on_LFP_KHz<bs_begin_sample_PS_LFP(1,NREM_index)+LFP_SR_KHz*1000*binsize_vec(2,9)-1)-bs_begin_sample_PS_LFP(1,NREM_index)+1; % define local spikes as the spikes that are inside the specific bin                           
                                   ins_phase=atan2(imag(h_signal),real(h_signal));
                                   ins_phase(find(ins_phase<0))=ins_phase(find(ins_phase<0))+2*pi; % convert to 0:2*pi rather than -pi:pi to avoid std artifacts.                                   
                                   rounded_ins_phase_LFP=interp1(phase_map,phase_map,ins_phase,'nearest','extrap'); % a line I found in the internet that should do the rounding of a vector to the nearest element in another vector.
                                   clear h_signal
                                   num_of_bins_LFP=ceil(length(ins_phase)/(bin_width*LFP_SR_KHz));
                                   first_bin_start_LFP=1;
                                   bin_starts_LFP=[first_bin_start_LFP+bin_width*LFP_SR_KHz*[0:1:num_of_bins_LFP-1]];
                                   appropriate_spikes=local_spikes_LFP_KHz;
%                                    appropriate_spikes=ceil(local_spikes_LFP_KHz/Info{1,unitnum}.SAMPLING*LFP_SR_KHz);
                                   if ~isempty(appropriate_spikes) && appropriate_spikes(length(appropriate_spikes))-length(ins_amp)==1
                                       appropriate_spikes(length(appropriate_spikes))=appropriate_spikes(length(appropriate_spikes))-1;
                                   end
                                   appropriate_spikes=appropriate_spikes(find(bitre*ins_amp(appropriate_spikes)>=bitre*SW_definition_thresh_LFP_only_for_current_cell));
                                   if ~isempty(appropriate_spikes)
                                       bin2phase_mapping_LFP=rounded_ins_phase_LFP(bin_starts_LFP);
                                       subtract_bins_from_spikes_mat=(repmat(appropriate_spikes,length(bin_starts_LFP),1)-repmat(bin_starts_LFP',1,length(appropriate_spikes)));
                                       subtract_bins_from_spikes_mat(subtract_bins_from_spikes_mat<0)=inf;
                                       [~,indind]=min(subtract_bins_from_spikes_mat);
                                       clear subtract_bins_from_spikes_mat rounded_ins_phase_LFP
                                       for jjj=1:length(indind)
                                           spikes_per_phase_LFP(find(phase_map==bin2phase_mapping_LFP(indind(jjj))),1)=spikes_per_phase_LFP(find(phase_map==bin2phase_mapping_LFP(indind(jjj))),1)+(1/(bin_width)*1000/(length(find(bin2phase_mapping_LFP==bin2phase_mapping_LFP(indind(jjj)))))); % to normalize by the number of times each specific phase appears in the course of the 10 seconds.
                                       end
                                    end
                                    clear appropriate_spikes
                               end
                               % all the following code I turned to a note
                               % becasue I am not using the oprion to stage
                               % N3 epochs by LFP anymore and I don't want
                               % it to take computation time and insert
                               % wrong variables. 062217
                               
%                                ins_phase=atan2(imag(h_signal),real(h_signal));
%                                ins_phase(find(ins_phase<0))=ins_phase(find(ins_phase<0))+2*pi; % convert to 0:2*pi rather than -pi:pi to avoid std artifacts.
%                                if Analyze_spike_to_EEG_SW_phase_locking
        %                            rounded_ins_phase=interp1(phase_map,phase_map,ins_phase,'nearest','extrap'); % a line I found in the internet that should do the rounding of a vector to the nearest element in another vector.
%                                    rounded_ins_phase=round(ins_phase*100);
%                                end
%                                h=find(ins_amp*bitre>=wave_amplitude_min_thresh);
%                                ah=diff(h);
%                                bh=diff([0 ah 0]==1);
%                                bh_start=find(bh==1);
%                                bh_end=find(bh==-1);
%                                ch=bh_end-bh_start;
%                                dh=find(ch>=min_sec_for_SWS_subsegment*LFP_SR_KHz*1000);
%                                consolidated_SWA=[];
%                                if Analyze_spike_to_EEG_SW_phase_locking
%                                    bin_starts_SWA=[];
%         %                            bin_lengths=[];
%                                end
%                                for aaa=1:length(dh)
%                                    subsegment=h(bh_start(dh(aaa))):1:h(bh_end(dh(aaa)));
%                                    if (max(ins_amp(subsegment)*bitre)<max_amplitude_for_subsegment && std(ins_phase(subsegment))>=min_phase_std_for_subsegment)
%                                        consolidated_SWA=[consolidated_SWA,subsegment];
%                                        if Analyze_spike_to_EEG_SW_phase_locking
%                                             length_of_SWS_segments{1,stable_period_count}(NREM_index,lfp_traces,aaa)=length_of_SWS_segments{1,stable_period_count}(NREM_index,lfp_traces,aaa)+length(subsegment);                                       
%             %                                specific_segment=rounded_ins_phase(h(bh_start(dh(aaa))):h(bh_end(dh(aaa))));
%             %                                phase_jumps_locations=find(diff(specific_segment)~=0)+1;
%             %                                bin_starts_SWA=[bin_starts_SWA,h(bh_start(dh(aaa)))-1+[1,phase_jumps_locations]];
%             %                                bin_lengths=[bin_lengths,diff(bin_starts_SWA),max(1,length(specific_segment)-phase_jumps_locations(end))];
%                                             num_of_bins=ceil((h(bh_end(dh(aaa)))-h(bh_start(dh(aaa)))+1)/(bin_width*LFP_SR_KHz));
%                                             first_bin_start=h(bh_start(dh(aaa)));
%                                             bin_starts_SWA=[bin_starts_SWA,first_bin_start+bin_width*LFP_SR_KHz*[0:1:num_of_bins-1]];
%                                        end
%                                    end
%                                end
%                                if length(consolidated_SWA)>=N3_fraction*length(ins_amp) % AASM criteria: more than 20% of the bin have more than 75 uV slow wave activity
% %                                    if (lfp_traces==1 || lfp_traces==2)
% %                                       N3_segments_Fr_OR_Cr=[N3_segments_Fr_OR_Cr,NREM_index]; 
% %                                    end
%                                    if Analyze_spike_to_EEG_SW_phase_locking
%                                        appropriate_spikes=find(ismember(local_spikes_LFP_KHz,consolidated_SWA)); % spikes which are appropriate are those that happen during a real SWS segment, according to the AASM manual
%                                        fruitful_segments(1,lfp_traces)=fruitful_segments(1,lfp_traces)+1;
%                                        if ~isempty(appropriate_spikes)
%                                            spikes_per_SWS_segments{1,stable_period_count}(NREM_index,lfp_traces)=length(appropriate_spikes);
%                                            phase_per_spike(find(isnan(phase_per_spike(:,lfp_traces)),1,'first'):find(isnan(phase_per_spike(:,lfp_traces)),1,'first')+length(ins_phase(local_spikes_LFP_KHz(appropriate_spikes)))-1,lfp_traces)=ins_phase(local_spikes_LFP_KHz(appropriate_spikes));
%                                            bin2phase_mapping=rounded_ins_phase(bin_starts_SWA);
%                                            subtract_bins_from_spikes_mat=(repmat(local_spikes_LFP_KHz(appropriate_spikes),length(bin_starts_SWA),1)-repmat(bin_starts_SWA',1,length(local_spikes_LFP_KHz(appropriate_spikes))));
%                                            subtract_bins_from_spikes_mat(subtract_bins_from_spikes_mat<0)=inf;
%                                            [~,indind]=min(subtract_bins_from_spikes_mat);
%                                            for jjj=1:length(indind)
%         %                                        if bin2phase_mapping(indind(jjj))==6.28
%         %                                            bin2phase_mapping(indind(jjj))=0;
%         %                                        end
%         %                                        spikes_per_phase(floor(bin2phase_mapping(indind(jjj))/0.01)+1,eeg_traces)=spikes_per_phase(floor(bin2phase_mapping(indind(jjj))/0.01)+1,eeg_traces)+1/(bin_lengths(indind(jjj))/LFP_SR_KHz)*1000;
%                                                 spikes_per_phase(find(phase_map==bin2phase_mapping(indind(jjj))),lfp_traces)=spikes_per_phase(find(phase_map==bin2phase_mapping(indind(jjj))),lfp_traces)+1;
%                                            end
%         %                                    mean_phase=[mean_phase,nanmean(ins_phase(local_spikes_LFP_KHz(appropriate_spikes)))];
%         %                                    phase_std=[phase_std,nanstd(ins_phase(local_spikes_LFP_KHz(appropriate_spikes)))];
%                                              % Best typicals
%         %                                      if rand(1)>0.5  % perform the procedure of finding the Best Typicals only in some cases
%         %                                          if (h(bh_start(dh(1)))>=LFP_SR_KHz*1000+500 && h(bh_end(dh(1)))<=length(signal)-(LFP_SR_KHz*1000+500)) 
%         %                                              bt=signal(h(bh_start(dh(1))):1:h(bh_end(dh(1))));
%         %                                              [~,bt_max_ind]=max(bt);
%         %                                              index_of_maximum_in_signal=h(bh_start(dh(1)))+bt_max_ind-1;
%         %                                              bt=signal(index_of_maximum_in_signal-LFP_SR_KHz*1000-500:index_of_maximum_in_signal+LFP_SR_KHz*1000+500); % to create a 2751+500+500-lengthed vector
%         %                                              bt_spikes=local_spikes_LFP_KHz(appropriate_spikes);
%         %                                              bt_spikes=bt_spikes(bt_spikes>=index_of_maximum_in_signal-LFP_SR_KHz*1000-500 &bt_spikes<=index_of_maximum_in_signal+LFP_SR_KHz*1000+500)-(index_of_maximum_in_signal-LFP_SR_KHz*1000-500);
%         %                                              best_typical_waveforms(size(best_typical_waveforms,1)+1,:)=bt; % 2-sec examples of oscillations
%         %                                              best_typical_spikes{size(best_typical_spikes,1)+1,1}=bt_spikes;
%         %                                              best_typical_lead(size(best_typical_lead,1)+1,1)=lfp_traces;
%         %                                          end
%         %                                      end
%                                        end
%                                    end
%     %                                phase_per_bin(NREM_index,eeg_traces,1)=nanmean(mean_phase);
%     %                                phase_per_bin(NREM_index,eeg_traces,2)=nanmean(phase_std);
%                                end
                           end
                        end                       
                   end
                   DAY_INST_FREQS=[DAY_INST_FREQS,INST_FREQS];
                   N3_segments_Fr_OR_Cr=unique(N3_segments_Fr_OR_Cr);
                   if Local_LFP && ~Calculate_MU_Spectrum
                       DAY_INST_FREQS_LFP=[DAY_INST_FREQS_LFP,INST_FREQS_LFP(N3_segments_Fr_OR_Cr)];
                   end
                   N3_segments_Fr_OR_Cr=N3_segments_Fr_OR_Cr(1:find(N3_segments_Fr_OR_Cr<=length(NREM_begs),1,'last'));
                   SWS_stats{1,unitnum}.N3_bins{1,stable_period_count}=NREM_bins(N3_segments_Fr_OR_Cr);
                   N3_begs=[N3_begs,NREM_begs(N3_segments_Fr_OR_Cr)];
                   N3_ends=[N3_ends,NREM_ends(N3_segments_Fr_OR_Cr)];
                   if calculate_EEG_measures
                      if stable_period_count==0
                          All_unit_EEG_range_correlation_W=[];
                          All_unit_SW_range_correlation_W=[];
                          All_unit_EEG_instantaneous_frequency_W=[];
                          All_unit_EEG_range_correlation_R=[];
                          All_unit_SW_range_correlation_R=[];
                          All_unit_EEG_instantaneous_frequency_R=[];                          
                          All_unit_EEG_range_correlation_N1_2=[];
                          All_unit_SW_range_correlation_N1_2=[];
                          All_unit_EEG_instantaneous_frequency_N3=[];                          
                          All_unit_EEG_range_correlation_N3=[];
                          All_unit_SW_range_correlation_N3=[];
                          All_unit_EEG_instantaneous_frequency_N3=[];                                                    
                      end
                       All_unit_EEG_range_correlation_W=[All_unit_EEG_range_correlation_W;EEG_range_correlation(WAKE_bins,10)];
                       All_unit_SW_range_correlation_W=[All_unit_SW_range_correlation_W;SW_range_correlation(WAKE_bins,10)];
                       All_unit_EEG_instantaneous_frequency_W=[All_unit_EEG_instantaneous_frequency_W;EEG_instantaneous_frequency(WAKE_bins,5)];
                       
                       All_unit_EEG_range_correlation_R=[All_unit_EEG_range_correlation_R;EEG_range_correlation(REM_bins,10)];
                       All_unit_SW_range_correlation_R=[All_unit_SW_range_correlation_R;SW_range_correlation(REM_bins,10)];
                       All_unit_EEG_instantaneous_frequency_R=[All_unit_EEG_instantaneous_frequency_R;EEG_instantaneous_frequency(REM_bins,5)];                       
                       
                       All_unit_EEG_range_correlation_N3=[All_unit_EEG_range_correlation_N3;EEG_range_correlation(NREM_bins(N3_segments_Fr_OR_Cr),10)];
                       All_unit_SW_range_correlation_N3=[All_unit_SW_range_correlation_N3;SW_range_correlation(NREM_bins(N3_segments_Fr_OR_Cr),10)];
                       All_unit_EEG_instantaneous_frequency_N3=[All_unit_EEG_instantaneous_frequency_N3;EEG_instantaneous_frequency(NREM_bins(N3_segments_Fr_OR_Cr),5)];
                       
                       All_unit_EEG_range_correlation_N1_2=[All_unit_EEG_range_correlation_N1_2;EEG_range_correlation(NREM_bins(setdiff([1:length(NREM_bins)],N3_segments_Fr_OR_Cr)),10)];
                       All_unit_SW_range_correlation_N1_2=[All_unit_SW_range_correlation_N1_2;SW_range_correlation(NREM_bins(setdiff([1:length(NREM_bins)],N3_segments_Fr_OR_Cr)),10)];
                       All_unit_EEG_instantaneous_frequency_N1_2=[All_unit_EEG_instantaneous_frequency_N1_2;EEG_instantaneous_frequency(NREM_bins(setdiff([1:length(NREM_bins)],N3_segments_Fr_OR_Cr)),5)];                       
                       if stable_period_count==length(first_stable_sample)
                           data2plot.EEG_analysis{1,unitnum}=struct('All_unit_EEG_range_correlation_W',All_unit_EEG_range_correlation_W,'All_unit_SW_range_correlation_W',All_unit_SW_range_correlation_W,'All_unit_EEG_instantaneous_frequency_W',All_unit_EEG_instantaneous_frequency_W,'All_unit_EEG_range_correlation_R',All_unit_EEG_range_correlation_R,'All_unit_SW_range_correlation_R',All_unit_SW_range_correlation_R,'All_unit_EEG_instantaneous_frequency_R',All_unit_EEG_instantaneous_frequency_R,'All_unit_EEG_range_correlation_N3',All_unit_EEG_range_correlation_N3,'All_unit_SW_range_correlation_N3',All_unit_SW_range_correlation_N3,'All_unit_EEG_instantaneous_frequency_N3',All_unit_EEG_instantaneous_frequency_N3,'All_unit_EEG_range_correlation_N1_2',All_unit_EEG_range_correlation_N1_2,'All_unit_SW_range_correlation_N1_2',All_unit_SW_range_correlation_N1_2,'All_unit_EEG_instantaneous_frequency_N1_2',All_unit_EEG_instantaneous_frequency_N1_2);
                       end
                   end                   
                   clear period_LFP_spectrum_N2 period_LFP_spectrum_N3 period_LFP_spectrum_R period_LFP_spectrum_W
                   if LFP_to_unit_analysis && exist('period_LFP_spectrum','var')
                       %070817
                       period_LFP_spectrum_N2=period_LFP_spectrum(:,NREM_bins_for_LFP);
                       LFP_EEG_corr_N2=LFP_EEG_corr(:,NREM_bins_for_LFP);
                       period_LFP_IF_N2=period_LFP_IF(1,NREM_bins_for_LFP); 
                   
                       period_LFP_spectrum_N3=period_LFP_spectrum_N2(:,N3_segments_Fr_OR_Cr_for_LFP);
                       LFP_EEG_corr_N3=LFP_EEG_corr_N2(:,N3_segments_Fr_OR_Cr_for_LFP); 
                       period_LFP_IF_N3=period_LFP_IF_N2(1,N3_segments_Fr_OR_Cr_for_LFP);
                   
                       period_LFP_spectrum_R=period_LFP_spectrum(:,REM_bins_for_LFP);
                       LFP_EEG_corr_R=LFP_EEG_corr(:,REM_bins_for_LFP); 
                       period_LFP_IF_R=period_LFP_IF(1,REM_bins_for_LFP); 
                   
                       period_LFP_spectrum_W=period_LFP_spectrum(:,WAKE_bins_for_LFP);
                       LFP_EEG_corr_W=LFP_EEG_corr(:,WAKE_bins_for_LFP);
                       period_LFP_IF_W=period_LFP_IF(1,WAKE_bins_for_LFP);
                   end
                   if stable_period_count==1
                       num_of_NREM=length(NREM_bins);
                       num_of_REM=length(REM_bins);
                       if length(first_stable_sample)==1
                           num_of_N3=length(N3_begs);
                       end
                   else
                       if stable_period_count==length(first_stable_sample)
                           num_of_N3=length(N3_begs);
                       end
                       num_of_NREM=num_of_NREM+length(NREM_bins);
                       num_of_REM=num_of_REM+length(REM_bins);
                   end
%                    poly_for_cross{1,unitnum}.begin_samples=N3_begs;
%                    poly_for_cross{1,unitnum}.end_samples=N3_ends;
                   polysomnography_with_N3{1,unitnum}=polysomnography{1,unitnum};
                   polysomnography_with_N3{1,unitnum}.stages.N3.begin_sample=N3_begs;
                   polysomnography_with_N3{1,unitnum}.stages.N3.end_sample=N3_ends;
                   if Check_polysomnogrphy_EEG_for_figure_1
                      R_indicators=REM_bins;
                      W_indicators=WAKE_bins;
                      N2_indicators=setdiff(NREM_bins,SWS_stats{1,unitnum}.N3_bins{1,stable_period_count});
                      N3_indicators=SWS_stats{1,unitnum}.N3_bins{1,stable_period_count};                       
                      all_NREM_1=EEG_1_segmented_orig(1,N2_indicators); 
                      all_NREM_2=EEG_2_segmented_orig(1,N2_indicators);
                      all_NREM_3=EEG_3_segmented_orig(1,N2_indicators);
                      all_SWS_1=EEG_1_segmented_orig(1,N3_indicators); 
                      all_SWS_2=EEG_2_segmented_orig(1,N3_indicators);
                      all_SWS_3=EEG_3_segmented_orig(1,N3_indicators);                      
                      all_REM_1=EEG_1_segmented_orig(1,R_indicators); 
                      all_REM_2=EEG_2_segmented_orig(1,R_indicators);
                      all_REM_3=EEG_3_segmented_orig(1,R_indicators);
                      all_WAKE_1=EEG_1_segmented_orig(1,W_indicators); 
                      all_WAKE_2=EEG_2_segmented_orig(1,W_indicators);
                      all_WAKE_3=EEG_3_segmented_orig(1,W_indicators);                      
                      NREM_EEG_PS=cell(length(all_NREM_1),3);
                      SWS_EEG_PS=cell(length(all_SWS_1),3);
                      REM_EEG_PS=cell(length(all_REM_1),3);
                      WAKE_EEG_PS=cell(length(all_WAKE_1),3);
                      stopfreq=35;
                      for nnn=1:length(all_NREM_1)
                          % NREM, frontal L
                           all_NREM_1{1,nnn}=all_NREM_1{1,nnn}-nanmean(all_NREM_1{1,nnn});
                           [spectrum_for_NREM1,f_EEG_NREM1]=pwelch(all_NREM_1{1,nnn},hamming(2*EEG_SR_KHz*1000),EEG_SR_KHz*1000,2^(nextpow2(2*EEG_SR_KHz*1000)),EEG_SR_KHz*1000); 
                           spectrum_for_NREM1=spectrum_for_NREM1(1:find(f_EEG_NREM1>=stopfreq,1,'first'));
%                            spectrum_for_NREM1=spectrum_for_NREM1/sum(spectrum_for_NREM1);                          
%                            spectrum_for_NREM1=spectrum_for_NREM1/rms(all_NREM_1{1,nnn});
                           NREM_EEG_PS{nnn,1}=spectrum_for_NREM1;
                           
                          % NREM, Central L
                           all_NREM_2{1,nnn}=all_NREM_2{1,nnn}-nanmean(all_NREM_2{1,nnn});
                           [spectrum_for_NREM2,f_EEG_NREM2]=pwelch(all_NREM_2{1,nnn},hamming(2*EEG_SR_KHz*1000),EEG_SR_KHz*1000,2^(nextpow2(2*EEG_SR_KHz*1000)),EEG_SR_KHz*1000); 
                           spectrum_for_NREM2=spectrum_for_NREM2(1:find(f_EEG_NREM2>=stopfreq,1,'first'));
%                            spectrum_for_NREM2=spectrum_for_NREM2/sum(spectrum_for_NREM2);                          
%                            spectrum_for_NREM2=spectrum_for_NREM2/rms(all_NREM_2{1,nnn});                          
                           NREM_EEG_PS{nnn,2}=spectrum_for_NREM2;
                           
                           % NREM, Central R
                           all_NREM_3{1,nnn}=all_NREM_3{1,nnn}-nanmean(all_NREM_3{1,nnn});
                           [spectrum_for_NREM3,f_EEG_NREM3]=pwelch(all_NREM_3{1,nnn},hamming(2*EEG_SR_KHz*1000),EEG_SR_KHz*1000,2^(nextpow2(2*EEG_SR_KHz*1000)),EEG_SR_KHz*1000); 
                           spectrum_for_NREM3=spectrum_for_NREM3(1:find(f_EEG_NREM3>=stopfreq,1,'first'));
%                            spectrum_for_NREM3=spectrum_for_NREM3/sum(spectrum_for_NREM3);
%                            spectrum_for_NREM3=spectrum_for_NREM3/rms(all_NREM_3{1,nnn});
                           NREM_EEG_PS{nnn,3}=spectrum_for_NREM3;                           
                      end
                      for sss=1:length(all_SWS_1)
                          % SWS, frontal L
                           all_SWS_1{1,sss}=all_SWS_1{1,sss}-nanmean(all_SWS_1{1,sss});
                           [spectrum_for_SWS1,f_EEG_SWS1]=pwelch(all_SWS_1{1,sss},hamming(2*EEG_SR_KHz*1000),EEG_SR_KHz*1000,2^(nextpow2(2*EEG_SR_KHz*1000)),EEG_SR_KHz*1000); 
                           spectrum_for_SWS1=spectrum_for_SWS1(1:find(f_EEG_SWS1>=stopfreq,1,'first'));
%                            spectrum_for_SWS1=spectrum_for_SWS1/sum(spectrum_for_SWS1);                          
%                            spectrum_for_SWS1=spectrum_for_SWS1/rms(all_SWS_1{1,nnn});
                           SWS_EEG_PS{sss,1}=spectrum_for_SWS1;
                           
                          % SWS, Central L
                           all_SWS_2{1,sss}=all_SWS_2{1,sss}-nanmean(all_SWS_2{1,sss});
                           [spectrum_for_SWS2,f_EEG_SWS2]=pwelch(all_SWS_2{1,sss},hamming(2*EEG_SR_KHz*1000),EEG_SR_KHz*1000,2^(nextpow2(2*EEG_SR_KHz*1000)),EEG_SR_KHz*1000); 
                           spectrum_for_SWS2=spectrum_for_SWS2(1:find(f_EEG_SWS2>=stopfreq,1,'first'));
%                            spectrum_for_SWS2=spectrum_for_SWS2/sum(spectrum_for_SWS2);                          
%                            spectrum_for_SWS2=spectrum_for_SWS2/rms(all_SWS_2{1,nnn});                          
                           SWS_EEG_PS{sss,2}=spectrum_for_SWS2;
                           
                           % SWS, Central R
                           all_SWS_3{1,sss}=all_SWS_3{1,sss}-nanmean(all_SWS_3{1,sss});
                           [spectrum_for_SWS3,f_EEG_SWS3]=pwelch(all_SWS_3{1,sss},hamming(2*EEG_SR_KHz*1000),EEG_SR_KHz*1000,2^(nextpow2(2*EEG_SR_KHz*1000)),EEG_SR_KHz*1000); 
                           spectrum_for_SWS3=spectrum_for_SWS3(1:find(f_EEG_SWS3>=stopfreq,1,'first'));
%                            spectrum_for_SWS3=spectrum_for_SWS3/sum(spectrum_for_SWS3);
%                            spectrum_for_SWS3=spectrum_for_SWS3/rms(all_SWS_3{1,nnn});
                           SWS_EEG_PS{sss,3}=spectrum_for_SWS3;                           
                      end                      
                      for rrr=1:length(all_REM_1)
                          % REM, frontal L
                           all_REM_1{1,rrr}=all_REM_1{1,rrr}-nanmean(all_REM_1{1,rrr});
                           [spectrum_for_REM1,f_EEG_REM1]=pwelch(all_REM_1{1,rrr},hamming(2*EEG_SR_KHz*1000),EEG_SR_KHz*1000,2^(nextpow2(2*EEG_SR_KHz*1000)),EEG_SR_KHz*1000); 
                           spectrum_for_REM1=spectrum_for_REM1(1:find(f_EEG_REM1>=stopfreq,1,'first'));
%                            spectrum_for_REM1=spectrum_for_REM1/sum(spectrum_for_REM1);                          
%                            spectrum_for_REM1=spectrum_for_REM1/rms(all_REM_1{1,rrr});
                           REM_EEG_PS{rrr,1}=spectrum_for_REM1;
                           
                          % REM, Central L
                           all_REM_2{1,rrr}=all_REM_2{1,rrr}-nanmean(all_REM_2{1,rrr});
                           [spectrum_for_REM2,f_EEG_REM2]=pwelch(all_REM_2{1,rrr},hamming(2*EEG_SR_KHz*1000),EEG_SR_KHz*1000,2^(nextpow2(2*EEG_SR_KHz*1000)),EEG_SR_KHz*1000); 
                           spectrum_for_REM2=spectrum_for_REM2(1:find(f_EEG_REM2>=stopfreq,1,'first'));
%                            spectrum_for_REM2=spectrum_for_REM2/sum(spectrum_for_REM2);                          
%                            spectrum_for_REM2=spectrum_for_REM2/rms(all_REM_2{1,rrr});
                           REM_EEG_PS{rrr,2}=spectrum_for_REM2;
                           
                           % REM, Central R
                           all_REM_3{1,rrr}=all_REM_3{1,rrr}-nanmean(all_REM_3{1,rrr});
                           [spectrum_for_REM3,f_EEG_REM3]=pwelch(all_REM_3{1,rrr},hamming(2*EEG_SR_KHz*1000),EEG_SR_KHz*1000,2^(nextpow2(2*EEG_SR_KHz*1000)),EEG_SR_KHz*1000);
                           spectrum_for_REM3=spectrum_for_REM3(1:find(f_EEG_REM3>=stopfreq,1,'first'));
%                            spectrum_for_REM3=spectrum_for_REM3/sum(spectrum_for_REM3);
%                            spectrum_for_REM3=spectrum_for_REM3/rms(all_REM_3{1,rrr});
                           REM_EEG_PS{rrr,3}=spectrum_for_REM3;                           
                      end          
                      for www=1:length(all_WAKE_1)
                          % WAKE, frontal L
                           all_WAKE_1{1,www}=all_WAKE_1{1,www}-nanmean(all_WAKE_1{1,www});
                           [spectrum_for_WAKE1,f_EEG_WAKE1]=pwelch(all_WAKE_1{1,www},hamming(2*EEG_SR_KHz*1000),EEG_SR_KHz*1000,2^(nextpow2(2*EEG_SR_KHz*1000)),EEG_SR_KHz*1000); 
                           spectrum_for_WAKE1=spectrum_for_WAKE1(1:find(f_EEG_WAKE1>=stopfreq,1,'first'));
%                            spectrum_for_WAKE1=spectrum_for_WAKE1/sum(spectrum_for_WAKE1);                          
%                            spectrum_for_WAKE1=spectrum_for_WAKE1/rms(all_WAKE_1{1,www});
                           WAKE_EEG_PS{www,1}=spectrum_for_WAKE1;
                           
                          % WAKE, Central L
                           all_WAKE_2{1,www}=all_WAKE_2{1,www}-nanmean(all_WAKE_2{1,www});
                           [spectrum_for_WAKE2,f_EEG_WAKE2]=pwelch(all_WAKE_2{1,www},hamming(2*EEG_SR_KHz*1000),EEG_SR_KHz*1000,2^(nextpow2(2*EEG_SR_KHz*1000)),EEG_SR_KHz*1000); 
                           spectrum_for_WAKE2=spectrum_for_WAKE2(1:find(f_EEG_WAKE2>=stopfreq,1,'first'));
%                            spectrum_for_WAKE2=spectrum_for_WAKE2/sum(spectrum_for_WAKE2);                          
%                            spectrum_for_WAKE2=spectrum_for_WAKE2/rms(all_WAKE_2{1,www});
                           WAKE_EEG_PS{www,2}=spectrum_for_WAKE2;
                           
                           % WAKE, Central R
                           all_WAKE_3{1,www}=all_WAKE_3{1,www}-nanmean(all_WAKE_3{1,www});
                           [spectrum_for_WAKE3,f_EEG_WAKE3]=pwelch(all_WAKE_3{1,www},hamming(2*EEG_SR_KHz*1000),EEG_SR_KHz*1000,2^(nextpow2(2*EEG_SR_KHz*1000)),EEG_SR_KHz*1000); 
                           spectrum_for_WAKE3=spectrum_for_WAKE3(1:find(f_EEG_WAKE3>=stopfreq,1,'first'));
%                            spectrum_for_WAKE3=spectrum_for_WAKE3/sum(spectrum_for_WAKE3);
%                            spectrum_for_WAKE3=spectrum_for_WAKE3/rms(all_WAKE_3{1,www});
                           WAKE_EEG_PS{www,3}=spectrum_for_WAKE3;                           
                      end                          
                   end
                   
                   if Calculate_EEG_spectrum_all_stages
                       length_of_PS_segment=5*EEG_SR_KHz*1000; % to receive a frequency resolution of 0.2 Hz
                       for tt=1:5
                           eval(['only_N2_examples=EEG_',num2str(tt),'_segmented_example_PS(1,N2_indicators);']);
                           N2_example_PS=[];
                           for nn2=1:length(only_N2_examples)
                               [pxx_temp,f_hz]=pwelch(double(only_N2_examples{1,nn2}),hamming(length_of_PS_segment),0.5*length_of_PS_segment,2^nextpow2(length_of_PS_segment),EEG_SR_KHz*1000);
                               N2_example_PS=[N2_example_PS,pxx_temp];
                           end
                           SWS_stats{1,unitnum}.Spectra_of_EEG{1,stable_period_count}.N2{1,tt}=nanmean(N2_example_PS,2);
                           eval(['only_N3_examples=EEG_',num2str(tt),'_segmented_example_PS(1,N3_indicators);']);
                           N3_example_PS=[];
                           for nn3=1:length(only_N3_examples)
                               [pxx_temp,f_hz]=pwelch(double(only_N3_examples{1,nn3}),hamming(length_of_PS_segment),0.5*length_of_PS_segment,2^nextpow2(length_of_PS_segment),EEG_SR_KHz*1000);
                               N3_example_PS=[N3_example_PS,pxx_temp];
                           end
                           SWS_stats{1,unitnum}.Spectra_of_EEG{1,stable_period_count}.N3{1,tt}=nanmean(N3_example_PS,2);                           
                           clear N3_example_PS only_N3_examples
                           eval(['only_R_examples=EEG_',num2str(tt),'_segmented_example_PS(1,R_indicators);']);
                           R_example_PS=[];
                           for rr=1:length(only_R_examples)
                               [pxx_temp,f_hz]=pwelch(double(only_R_examples{1,rr}),hamming(length_of_PS_segment),0.5*length_of_PS_segment,2^nextpow2(length_of_PS_segment),EEG_SR_KHz*1000);
                               R_example_PS=[R_example_PS,pxx_temp];
                           end
                           SWS_stats{1,unitnum}.Spectra_of_EEG{1,stable_period_count}.R{1,tt}=nanmean(R_example_PS,2);                                                      
                           eval(['only_W_examples=EEG_',num2str(tt),'_segmented_example_PS(1,W_indicators);']);
                           W_example_PS=[];
                           for ww=1:length(only_W_examples)
                               [pxx_temp,f_hz]=pwelch(double(only_W_examples{1,ww}),hamming(length_of_PS_segment),0.5*length_of_PS_segment,2^nextpow2(length_of_PS_segment),EEG_SR_KHz*1000);
                               W_example_PS=[W_example_PS,pxx_temp];
                           end
                           SWS_stats{1,unitnum}.Spectra_of_EEG{1,stable_period_count}.W{1,tt}=nanmean(W_example_PS,2);                           
                       end
                   end
                   SWS_stats_struct=SWS_stats{1,unitnum};
                   save([filenames{1,unitnum}(1:strfind(filenames{1,unitnum},'Data')-1),'polysomnography_with_N3_new'],'polysomnography_with_N3','SWS_stats_struct');
%                    string_to_use=filenames{1,unitnum}; % 090817
%                    substring=string_to_use(strfind(filenames{1,unitnum},'Data_')-7:strfind(filenames{1,unitnum},'Data_')-2); % 090817

%                    save([filenames{1,unitnum}(1:strfind(filenames{1,unitnum},'Data')-1),['PSG_ALL_',substring]],'polysomnography_with_N3');
                   clear SWS_stats_struct
%                    clear polysomnography_with_N3
                   
                   if stable_period_count==length(first_stable_sample)
                       percent_N3_out_of_NREM=num_of_N3/(num_of_REM+num_of_NREM)*100;
                        disp(['Percent of N3 out of all unit recording is ',num2str(percent_N3_out_of_NREM)]);
                        if Analyze_spike_to_EEG_SW_phase_locking
                            SWS_stats{1,unitnum}.length_of_SWS_segments=length_of_SWS_segments;                            
                            SWS_stats{1,unitnum}.spikes_per_SWS_segments=spikes_per_SWS_segments;                                       
                        end
%                         SWS_stats{1,unitnum}.best_typical_waveforms=best_typical_waveforms;
%                         SWS_stats{1,unitnum}.best_typical_spikes=best_typical_spikes;
%                         SWS_stats{1,unitnum}.best_typical_lead=best_typical_lead;
                        if Analyze_EEG_to_FR_SW_correlation
                            SWS_stats{1,unitnum}.mean_SW_amplitude_EEG=mean_SW_amplitude_EEG;
                            SWS_stats{1,unitnum}.above_thresh_SW_amplitude_EEG=above_thresh_SW_amplitude_EEG;
                            SWS_stats{1,unitnum}.SW_amplitude_FR=SW_amplitude_FR;                            
                            SWS_stats{1,unitnum}.EEG_SW_content=EEG_SW_content;
                            SWS_stats{1,unitnum}.mean_amplitude_EEG_SW=mean_amplitude_EEG_SW;
                            SWS_stats{1,unitnum}.above_thresh_EEG_SW=above_thresh_EEG_SW;
                        end
%                         SWS_stats{1,unitnum}.temp_all_ind=temp_all_ind;
                   end
                end
                
                % if N3 are found, enable sorting of neural data also to N3. This code will be available for all the single unit neural measures
                if use_SWS_N3_data && exist('polysomnography_with_N3','var') && ~isempty(polysomnography_with_N3{1,unitnum}.stages.N3.begin_sample) 
                    W_begins=polysomnography{unitnum}.stages.W.begin_sample; W_ends=polysomnography{unitnum}.stages.W.end_sample;
                    N1_begins=polysomnography{unitnum}.stages.N1.begin_sample; N1_ends=polysomnography{unitnum}.stages.N1.end_sample;
                    N2_begins=polysomnography{unitnum}.stages.N2.begin_sample; N2_ends=polysomnography{unitnum}.stages.N2.end_sample;
                    R_begins=polysomnography{unitnum}.stages.R.begin_sample; R_ends=polysomnography{unitnum}.stages.R.end_sample;
                    U_begins=polysomnography{unitnum}.stages.U.begin_sample; U_ends=polysomnography{unitnum}.stages.U.end_sample;
                    N3_begins=polysomnography_with_N3{1,unitnum}.stages.N3.begin_sample; N3_ends=polysomnography_with_N3{1,unitnum}.stages.N3.end_sample;
                    for kk=1:length(N3_begins)
                        if ismember(N3_begins(kk),N2_begins) && ismember(N3_ends(kk),N2_ends)
                            N2_begins=N2_begins(N2_begins~=N3_begins(kk));
                            N2_ends=N2_ends(N2_ends~=N3_ends(kk));
                        elseif ismember(N3_begins(kk),N2_begins) && ~ismember(N3_ends(kk),N2_ends)
                            N2_begins(find(N2_begins==N3_begins(kk)))=N3_ends(kk)+1;
                        elseif ~ismember(N3_begins(kk),N2_begins) && ismember(N3_ends(kk),N2_ends)
                            N2_ends(find(N2_ends==N3_ends(kk)))=N3_begins(kk)-1;
                        elseif ~ismember(N3_begins(kk),N2_begins) && ~ismember(N3_ends(kk),N2_ends)
                            N2_begins=sort([N2_begins,N3_ends(kk)+1]);
                            N2_ends=sort([N2_ends,N3_begins(kk)-1]);
                        end
                        all_begs_N3_included=sort(unique([W_begins,N1_begins,N2_begins,N3_begins,R_begins,U_begins]));
                        all_ends_N3_included=sort(unique([W_ends,N1_ends,N2_ends,N3_ends,R_ends,U_ends]));
                    end
                end
                clear EEG_* FR_per_bs REM_* WAKE_* aaa A B added_segment ah begin_sample_diffs bend bh bh_end bh_start bsize bstart ch closest_bin_end consolidated_SWA dd deviate deviations_from_full_segment dh eeg_traces file_begin_sample_EEG_* first_stable_sample_EEG h h_signal ii ins_* kk local_spikes_EEG_KHz marker move_to_next nn percent_N3_out_of_NREM signal subsegment true_burst
                clear LFP_1 signal_LFP_*
                
                % Analyse Firing Rates along stable period
                if (binsize_vec(1,1) || binsize_vec(1,2))
                   % find an FR vector along the stablle periods, by specific binsize
                   [FR_per_bs,bs_begin_sample_FR]=Calculate_FR(spikes_per_milli_sec,milli_second_begin_sample,binsize_vec(2,2),overlap_smoothing_settings,1);
                   % create a table holding the firing rates (per binsizes) for all sleep stages 
                   if overlap_smoothing_settings(1,1)~=0
                       bs_begin_before_smoothing_FR=milli_second_begin_sample(mod((1:length(milli_second_begin_sample)),1000*binsize_vec(2,2))==1);
                   end
                   FR_on_stages=nan(6,length(bs_begin_sample_FR));
                   if stable_period_count==1
                       temp_all_ind=[];
                   end
                   if use_SWS_N3_data && exist('polysomnography_with_N3','var') && ~isempty(polysomnography_with_N3{1,unitnum}.stages.N3.begin_sample) 
                       for ii=1:length(bs_begin_sample_FR)
                           A=find(all_begs_N3_included<=bs_begin_sample_FR(1,ii),1,'last');
                           closest_bin_end=min(bs_begin_sample_FR(1,ii)+Info{unitnum}.SAMPLING*binsize_vec(2,2)*1000-1,last_stable_sample(stable_period_count));
                           B=find(all_ends_N3_included>=closest_bin_end,1,'first');
                           marker=NaN;
                           if ((B-A)==0 || ((B-A)==1 && closest_bin_end-all_begs_N3_included(A+1)<all_begs_N3_included(A+1)-bs_begin_sample_FR(1,ii)))
                              marker=all_begs_N3_included(A);
                           elseif ((B-A)==1 && closest_bin_end-all_begs_N3_included(A+1)>=all_begs_N3_included(A+1)-bs_begin_sample_FR(1,ii))
                              marker=all_begs_N3_included(A+1);
                           elseif (B-A)==2 % I added this in 062317 after I figures out that this situation can actually happen, If the epoch is a few samples short of 440000 and the bs happens to start really at the end of the previous one, traverse the entire shorter epoch and then end in the following one.
                              marker=all_begs_N3_included(A+1);                              
                           end
                           if ismember(marker,W_begins)
                              ind=1;
                           elseif ismember(marker,N1_begins)
                              ind=2;
                           elseif ismember(marker,N2_begins)
                              ind=3;
                           elseif ismember(marker,N3_begins)
                              ind=4;
                           elseif ismember(marker,R_begins)
                              ind=5;                
                           elseif ismember(marker,U_begins)
                              ind=6;                
                           end
%                        temp_all_ind=[temp_all_ind,ind];
                       all_nan=squeeze(isnan(FR_on_stages(ind,:)));
                       FR_on_stages(ind,find(all_nan==1,1,'first'))=FR_per_bs(1,ii);
                       end
                   else
                       for ii=1:length(bs_begin_sample_FR)
                           A=find(all_begs<=bs_begin_sample_FR(1,ii),1,'last');
                           closest_bin_end=min(bs_begin_sample_FR(1,ii)+Info{unitnum}.SAMPLING*binsize_vec(2,2)*1000-1,last_stable_sample(stable_period_count));
                           B=find(all_ends>=closest_bin_end,1,'first');
                           marker=NaN;
                           if ((B-A)==0 || ((B-A)==1 && closest_bin_end-all_begs(A+1)<all_begs(A+1)-bs_begin_sample_FR(1,ii)))
                              marker=all_begs(A);
                           elseif ((B-A)==1 && closest_bin_end-all_begs(A+1)>=all_begs(A+1)-bs_begin_sample_FR(1,ii))
                              marker=all_begs(A+1);
                           elseif (B-A)==2 % I added this in 062317 after I figures out that this situation can actually happen, If the epoch is a few samples short of 440000 and the bs happens to start really at the end of the previous one, traverse the entire shorter epoch and then end in the following one.
                              marker=all_begs(A+1);                              
                           end
                           if ismember(marker,polysomnography{unitnum}.stages.W.begin_sample)
                              ind=1;
                           elseif ismember(marker,polysomnography{unitnum}.stages.N1.begin_sample)
                              ind=2;
                           elseif ismember(marker,polysomnography{unitnum}.stages.N2.begin_sample)
                              ind=3;
                           elseif ismember(marker,polysomnography{unitnum}.stages.N3.begin_sample)
                              ind=4;
                           elseif ismember(marker,polysomnography{unitnum}.stages.R.begin_sample)
                              ind=5;                
                           elseif ismember(marker,polysomnography{unitnum}.stages.U.begin_sample)
                              ind=6;                
                           end
%                        temp_all_ind=[temp_all_ind,ind];
                       all_nan=squeeze(isnan(FR_on_stages(ind,:)));
                       FR_on_stages(ind,find(all_nan==1,1,'first'))=FR_per_bs(1,ii);
                       end                                          
                   end
                end
                clear ii marker A B ind all_nan

                if (binsize_vec(1,1) || binsize_vec(1,3))
                   % find an CV vector along the stablle periods, by specific binsize
                    [CV_per_bs,bs_begin_sample_CV,bin_centers,ITI_matrix]=Calculate_CV (Info{unitnum},stable_digital,milli_second_begin_sample,spikes_per_milli_sec,binsize_vec(2,3),overlap_smoothing_settings,1);
                   % create a table holding the CV (per binsizes) for all sleep stages
                   if overlap_smoothing_settings(1,1)~=0
                       bs_begin_before_smoothing_CV=milli_second_begin_sample(mod((1:length(milli_second_begin_sample)),1000*binsize_vec(2,3))==1);
                   end
                   CV_on_stages=nan(6,length(bs_begin_sample_CV));
                   ITI_on_stages=nan(6,length(bs_begin_sample_CV),length(bin_centers));
                   
                   if use_SWS_N3_data && exist('polysomnography_with_N3','var') && ~isempty(polysomnography_with_N3{1,unitnum}.stages.N3.begin_sample) 
                       for ii=1:length(bs_begin_sample_CV)
                           A=find(all_begs_N3_included<=bs_begin_sample_CV(1,ii),1,'last');
                           closest_bin_end=min(bs_begin_sample_CV(1,ii)+Info{unitnum}.SAMPLING*binsize_vec(2,3)*1000-1,last_stable_sample(stable_period_count));
                           B=find(all_ends_N3_included>=closest_bin_end,1,'first');
                           marker=NaN;
                           if ((B-A)==0 || ((B-A)==1 && closest_bin_end-all_begs_N3_included(A+1)<all_begs_N3_included(A+1)-bs_begin_sample_CV(1,ii)))
                              marker=all_begs_N3_included(A);
                           elseif ((B-A)==1 && closest_bin_end-all_begs_N3_included(A+1)>=all_begs_N3_included(A+1)-bs_begin_sample_CV(1,ii))
                              marker=all_begs_N3_included(A+1);
                           elseif (B-A)==2 % I added this in 062317 after I figures out that this situation can actually happen, If the epoch is a few samples short of 440000 and the bs happens to start really at the end of the previous one, traverse the entire shorter epoch and then end in the following one.
                              marker=all_begs_N3_included(A+1);                              
                           end
                           if ismember(marker,W_begins)
                              ind=1;
                           elseif ismember(marker,N1_begins)
                              ind=2;
                           elseif ismember(marker,N2_begins)
                              ind=3;
                           elseif ismember(marker,N3_begins)
                              ind=4;
                           elseif ismember(marker,R_begins)
                              ind=5;                
                           elseif ismember(marker,U_begins)
                              ind=6;                
                           end
                           all_nan=squeeze(isnan(CV_on_stages(ind,:)));
                           CV_on_stages(ind,find(all_nan==1,1,'first'))=CV_per_bs(1,ii);
                           ITI_on_stages(ind,find(all_nan==1,1,'first'),:)=ITI_matrix(ii,:);
                       end
                   else
                       for ii=1:length(bs_begin_sample_CV)
                           A=find(all_begs<=bs_begin_sample_CV(1,ii),1,'last');
                           closest_bin_end=min(bs_begin_sample_CV(1,ii)+Info{unitnum}.SAMPLING*binsize_vec(2,3)*1000-1,last_stable_sample(stable_period_count));
                           B=find(all_ends>=closest_bin_end,1,'first');
                           marker=NaN;
                           if ((B-A)==0 || ((B-A)==1 && closest_bin_end-all_begs(A+1)<all_begs(A+1)-bs_begin_sample_CV(1,ii)))
                              marker=all_begs(A);
                           elseif ((B-A)==1 && closest_bin_end-all_begs(A+1)>=all_begs(A+1)-bs_begin_sample_CV(1,ii))
                              marker=all_begs(A+1);
                           elseif (B-A)==2 % I added this in 062317 after I figures out that this situation can actually happen, If the epoch is a few samples short of 440000 and the bs happens to start really at the end of the previous one, traverse the entire shorter epoch and then end in the following one.
                              marker=all_begs(A+1);                                                            
                           end
                           if ismember(marker,polysomnography{unitnum}.stages.W.begin_sample)
                              ind=1;
                           elseif ismember(marker,polysomnography{unitnum}.stages.N1.begin_sample)
                              ind=2;
                           elseif ismember(marker,polysomnography{unitnum}.stages.N2.begin_sample)
                              ind=3;
                           elseif ismember(marker,polysomnography{unitnum}.stages.N3.begin_sample)
                              ind=4;
                           elseif ismember(marker,polysomnography{unitnum}.stages.R.begin_sample)
                              ind=5;                
                           elseif ismember(marker,polysomnography{unitnum}.stages.U.begin_sample)
                              ind=6;                
                           end
                           all_nan=squeeze(isnan(CV_on_stages(ind,:)));
                           CV_on_stages(ind,find(all_nan==1,1,'first'))=CV_per_bs(1,ii);
                           ITI_on_stages(ind,find(all_nan==1,1,'first'),:)=ITI_matrix(ii,:);
                       end                                          
                   end                   
                end
                clear A B ind ii all_nan ITI_matrix marker
                
                if ((binsize_vec(1,1) || binsize_vec(1,4)) && ~No_pause_analysis && pauser && ~burster)
                    rel_pause_locations=((pause_start>=first_stable_sample(1,stable_period_count)) & (pause_end<=last_stable_sample(1,stable_period_count)));
                    rel_pause_start=pause_start(rel_pause_locations); rel_pause_end=pause_end(rel_pause_locations);
                    % find Pause Probability, Duration and Frequency vectors along the stable periods, by specific binsize
                    [pause_dur_per_bs,pause_freq_per_bs,pause_prob_per_bs,bs_begin_sample_pause]=Analyze_pauses(rel_pause_start,rel_pause_end,stable_period_count,last_stable_sample,Info{unitnum}.SAMPLING,milli_second_begin_sample,binsize_vec(2,4),overlap_smoothing_settings,1);
                    % create a table holding the pause data (per binsizes) for all sleep stages
                    if overlap_smoothing_settings(1,1)~=0
                        bs_begin_before_smoothing_pause=milli_second_begin_sample(mod((1:length(milli_second_begin_sample)),1000*binsize_vec(2,4))==1);
                    end
                    pause_on_stages=nan(6,3,length(bs_begin_sample_pause));
                    
                   if use_SWS_N3_data && exist('polysomnography_with_N3','var') && ~isempty(polysomnography_with_N3{1,unitnum}.stages.N3.begin_sample) 
                       for ii=1:length(bs_begin_sample_pause)
                           A=find(all_begs_N3_included<=bs_begin_sample_pause(1,ii),1,'last');
                           closest_bin_end=min(bs_begin_sample_pause(1,ii)+Info{unitnum}.SAMPLING*binsize_vec(2,4)*1000-1,last_stable_sample(stable_period_count));
                           B=find(all_ends_N3_included>=closest_bin_end,1,'first');
                           marker=NaN;
                           if ((B-A)==0 || ((B-A)==1 && closest_bin_end-all_begs_N3_included(A+1)<all_begs_N3_included(A+1)-bs_begin_sample_pause(1,ii)))
                              marker=all_begs_N3_included(A);
                           elseif ((B-A)==1 && closest_bin_end-all_begs_N3_included(A+1)>=all_begs_N3_included(A+1)-bs_begin_sample_pause(1,ii))
                              marker=all_begs_N3_included(A+1);
                           elseif (B-A)==2 % I added this in 062317 after I figures out that this situation can actually happen, If the epoch is a few samples short of 440000 and the bs happens to start really at the end of the previous one, traverse the entire shorter epoch and then end in the following one.
                              marker=all_begs_N3_included(A+1);                              
                           end
                           if ismember(marker,W_begins)
                              ind=1;
                           elseif ismember(marker,N1_begins)
                              ind=2;
                           elseif ismember(marker,N2_begins)
                              ind=3;
                           elseif ismember(marker,N3_begins)
                              ind=4;
                           elseif ismember(marker,R_begins)
                              ind=5;                
                           elseif ismember(marker,U_begins)
                              ind=6;                
                           end
                           all_nan=squeeze(isnan(pause_on_stages(ind,1,:)));
                           pause_on_stages(ind,1,find(all_nan==1,1,'first'))=pause_dur_per_bs(1,ii);

                           all_nan=squeeze(isnan(pause_on_stages(ind,2,:)));
                           pause_on_stages(ind,2,find(all_nan==1,1,'first'))=pause_freq_per_bs(1,ii);

                           all_nan=squeeze(isnan(pause_on_stages(ind,3,:)));
                           pause_on_stages(ind,3,find(all_nan==1,1,'first'))=pause_prob_per_bs(1,ii);
                       end
                   else
                       for ii=1:length(bs_begin_sample_pause)
                           A=find(all_begs<=bs_begin_sample_pause(1,ii),1,'last');
                           closest_bin_end=min(bs_begin_sample_pause(1,ii)+Info{unitnum}.SAMPLING*binsize_vec(2,4)*1000-1,last_stable_sample(stable_period_count));
                           B=find(all_ends>=closest_bin_end,1,'first');
                           marker=NaN;
                           if ((B-A)==0 || ((B-A)==1 && closest_bin_end-all_begs(A+1)<all_begs(A+1)-bs_begin_sample_pause(1,ii)))
                              marker=all_begs(A);
                           elseif ((B-A)==1 && closest_bin_end-all_begs(A+1)>=all_begs(A+1)-bs_begin_sample_pause(1,ii))
                              marker=all_begs(A+1);
                           elseif (B-A)==2 % I added this in 062317 after I figures out that this situation can actually happen, If the epoch is a few samples short of 440000 and the bs happens to start really at the end of the previous one, traverse the entire shorter epoch and then end in the following one.
                              marker=all_begs(A+1);                                                            
                           end
                           if ismember(marker,polysomnography{unitnum}.stages.W.begin_sample)
                              ind=1;
                           elseif ismember(marker,polysomnography{unitnum}.stages.N1.begin_sample)
                              ind=2;
                           elseif ismember(marker,polysomnography{unitnum}.stages.N2.begin_sample)
                              ind=3;
                           elseif ismember(marker,polysomnography{unitnum}.stages.N3.begin_sample)
                              ind=4;
                           elseif ismember(marker,polysomnography{unitnum}.stages.R.begin_sample)
                              ind=5;                
                           elseif ismember(marker,polysomnography{unitnum}.stages.U.begin_sample)
                              ind=6;                
                           end
                           all_nan=squeeze(isnan(pause_on_stages(ind,1,:)));
                           pause_on_stages(ind,1,find(all_nan==1,1,'first'))=pause_dur_per_bs(1,ii);

                           all_nan=squeeze(isnan(pause_on_stages(ind,2,:)));
                           pause_on_stages(ind,2,find(all_nan==1,1,'first'))=pause_freq_per_bs(1,ii);

                           all_nan=squeeze(isnan(pause_on_stages(ind,3,:)));
                           pause_on_stages(ind,3,find(all_nan==1,1,'first'))=pause_prob_per_bs(1,ii);
                       end                                          
                   end                    
                end
                clear ii ind marker A B all_nan rel_pause_locations rel_pause_end rel_pause_start

                if ((binsize_vec(1,1) || binsize_vec(1,4)) && ~pauser && burster)
                    rel_burst_locations=((burst_start>=first_stable_sample(1,stable_period_count)) & (burst_end<=last_stable_sample(1,stable_period_count)));
                    rel_burst_start=burst_start(rel_burst_locations); rel_burst_end=burst_end(rel_burst_locations); rel_burst_size=burst_size(rel_burst_locations);
                    % find Pause Probability, Duration and Frequency vectors along the stable periods, by specific binsize
                    [burst_frequency_per_bs,burst_probability_per_bs,burst_mean_duration_per_bs,burst_size_per_bs,percent_spikes_in_bursts_per_bs,burst_CV_per_bs,bs_begin_sample_burst]=Analyze_bursts(rel_burst_start,rel_burst_end,rel_burst_size,stable_period_count,last_stable_sample,stablespikes,Info{unitnum}.SAMPLING,milli_second_begin_sample,binsize_vec(2,4),overlap_smoothing_settings,1,FR_per_bs);
                    % create a table holding the pause data (per binsizes) for all sleep stages
                    if overlap_smoothing_settings(1,1)~=0
                        bs_begin_before_smoothing_burst=milli_second_begin_sample(mod((1:length(milli_second_begin_sample)),1000*binsize_vec(2,4))==1);
                    end
                    burst_on_stages=nan(6,6,length(bs_begin_sample_burst));

                   if use_SWS_N3_data && exist('polysomnography_with_N3','var') && ~isempty(polysomnography_with_N3{1,unitnum}.stages.N3.begin_sample) 
                       for ii=1:length(bs_begin_sample_burst)
                           A=find(all_begs_N3_included<=bs_begin_sample_burst(1,ii),1,'last');
                           closest_bin_end=min(bs_begin_sample_burst(1,ii)+Info{unitnum}.SAMPLING*binsize_vec(2,4)*1000-1,last_stable_sample(stable_period_count));
                           B=find(all_ends_N3_included>=closest_bin_end,1,'first');
                           marker=NaN;
                           if ((B-A)==0 || ((B-A)==1 && closest_bin_end-all_begs_N3_included(A+1)<all_begs_N3_included(A+1)-bs_begin_sample_burst(1,ii)))
                              marker=all_begs_N3_included(A);
                           elseif ((B-A)==1 && closest_bin_end-all_begs_N3_included(A+1)>=all_begs_N3_included(A+1)-bs_begin_sample_burst(1,ii))
                              marker=all_begs_N3_included(A+1);
                           elseif (B-A)==2 % I added this in 062317 after I figures out that this situation can actually happen, If the epoch is a few samples short of 440000 and the bs happens to start really at the end of the previous one, traverse the entire shorter epoch and then end in the following one.
                              marker=all_begs_N3_included(A+1);                              
                           end
                           if ismember(marker,W_begins)
                              ind=1;
                           elseif ismember(marker,N1_begins)
                              ind=2;
                           elseif ismember(marker,N2_begins)
                              ind=3;
                           elseif ismember(marker,N3_begins)
                              ind=4;
                           elseif ismember(marker,R_begins)
                              ind=5;                
                           elseif ismember(marker,U_begins)
                              ind=6;                
                           end
                           all_nan=squeeze(isnan(burst_on_stages(ind,1,:)));
                           burst_on_stages(ind,1,find(all_nan==1,1,'first'))=burst_frequency_per_bs(1,ii); % how many bursts per second

                           all_nan=squeeze(isnan(burst_on_stages(ind,2,:)));
                           burst_on_stages(ind,2,find(all_nan==1,1,'first'))=burst_probability_per_bs(1,ii); % probability of being in a burst

                           all_nan=squeeze(isnan(burst_on_stages(ind,3,:)));
                           burst_on_stages(ind,3,find(all_nan==1,1,'first'))=burst_size_per_bs(1,ii); % mean number of spikes per burst
                        
                           all_nan=squeeze(isnan(burst_on_stages(ind,4,:)));
                           burst_on_stages(ind,4,find(all_nan==1,1,'first'))=percent_spikes_in_bursts_per_bs(1,ii);                        

                           all_nan=squeeze(isnan(burst_on_stages(ind,5,:)));
                           burst_on_stages(ind,5,find(all_nan==1,1,'first'))=burst_CV_per_bs(1,ii);
                        
                           all_nan=squeeze(isnan(burst_on_stages(ind,6,:)));
                           burst_on_stages(ind,6,find(all_nan==1,1,'first'))=burst_mean_duration_per_bs(1,ii); % mean burst duration
                       end
                   else
                       for ii=1:length(bs_begin_sample_burst)
                           A=find(all_begs<=bs_begin_sample_burst(1,ii),1,'last');
                           closest_bin_end=min(bs_begin_sample_burst(1,ii)+Info{unitnum}.SAMPLING*binsize_vec(2,4)*1000-1,last_stable_sample(stable_period_count));
                           B=find(all_ends>=closest_bin_end,1,'first');
                           marker=NaN;
                           if ((B-A)==0 || ((B-A)==1 && closest_bin_end-all_begs(A+1)<all_begs(A+1)-bs_begin_sample_burst(1,ii)))
                              marker=all_begs(A);
                           elseif ((B-A)==1 && closest_bin_end-all_begs(A+1)>=all_begs(A+1)-bs_begin_sample_burst(1,ii))
                              marker=all_begs(A+1);
                           elseif (B-A)==2 % I added this in 062317 after I figures out that this situation can actually happen, If the epoch is a few samples short of 440000 and the bs happens to start really at the end of the previous one, traverse the entire shorter epoch and then end in the following one.
                              marker=all_begs(A+1);                                                            
                           end
                           if ismember(marker,polysomnography{unitnum}.stages.W.begin_sample)
                              ind=1;
                           elseif ismember(marker,polysomnography{unitnum}.stages.N1.begin_sample)
                              ind=2;
                           elseif ismember(marker,polysomnography{unitnum}.stages.N2.begin_sample)
                              ind=3;
                           elseif ismember(marker,polysomnography{unitnum}.stages.N3.begin_sample)
                              ind=4;
                           elseif ismember(marker,polysomnography{unitnum}.stages.R.begin_sample)
                              ind=5;                
                           elseif ismember(marker,polysomnography{unitnum}.stages.U.begin_sample)
                              ind=6;                
                           end
                           all_nan=squeeze(isnan(burst_on_stages(ind,1,:)));
                           burst_on_stages(ind,1,find(all_nan==1,1,'first'))=burst_frequency_per_bs(1,ii); % how many bursts per second

                           all_nan=squeeze(isnan(burst_on_stages(ind,2,:)));
                           burst_on_stages(ind,2,find(all_nan==1,1,'first'))=burst_probability_per_bs(1,ii); % probability of being in a burst

                           all_nan=squeeze(isnan(burst_on_stages(ind,3,:)));
                           burst_on_stages(ind,3,find(all_nan==1,1,'first'))=burst_size_per_bs(1,ii); % mean number of spikes per burst
                        
                           all_nan=squeeze(isnan(burst_on_stages(ind,4,:)));
                           burst_on_stages(ind,4,find(all_nan==1,1,'first'))=percent_spikes_in_bursts_per_bs(1,ii);                        

                           all_nan=squeeze(isnan(burst_on_stages(ind,5,:)));
                           burst_on_stages(ind,5,find(all_nan==1,1,'first'))=burst_CV_per_bs(1,ii);
                        
                           all_nan=squeeze(isnan(burst_on_stages(ind,6,:)));
                           burst_on_stages(ind,6,find(all_nan==1,1,'first'))=burst_mean_duration_per_bs(1,ii); % mean burst duration
                       end                                          
                   end                                        
                end
                clear ii ind marker A B all_nan rel_burst_locations rel_burst_end rel_burst_start                                 

                if binsize_vec(1,6)
                    if Prune_BG_spikes_for_PS_analysis % prune a certain number of spikes only for this analysis to show that the SW presence in the BG does not vanish when spikes are diminished.
                        % pruning analysis is made randomly 10 times to  avoid mistakes
                        spikes_per_milli_sec_original=spikes_per_milli_sec;
                        % prune spikes, changed 062517
                        locations_of_spikes_to_prune=find(spikes_per_milli_sec==1);
                        if unit{1,unitnum}.FR>destination_FR_for_pruning
                            fraction_to_prune_per_unit=1-(destination_FR_for_pruning/unit{1,unitnum}.FR);
                        else
                            fraction_to_prune_per_unit=0;
                        end
                        num_to_leave=round((1-fraction_to_prune_per_unit)*length(locations_of_spikes_to_prune));
                        for rep=1:num_of_reps_for_pruning
                            locations_of_spikes_to_prune=locations_of_spikes_to_prune(randperm(length(locations_of_spikes_to_prune)));
                            new_locations_of_spikes=locations_of_spikes_to_prune(1:num_to_leave);
                            spikes_per_milli_sec_toprune=zeros(1,length(spikes_per_milli_sec));
                            spikes_per_milli_sec_toprune(new_locations_of_spikes)=1;
                            [PS_per_bs,bs_begin_sample_PS,F,~,SW_definition_thresh_FR,instantaneous_freq_per_bs,no_spike_segments]=Calculate_Spike_Power_Spectra(spikes_per_milli_sec,milli_second_begin_sample,binsize_vec(2,6),overlap_smoothing_settings,1,bandpass_SW,bandstop_SW,percent_thresh_for_SW_definition_FR,SWS_stats{1,unitnum}.NREM_bins{1,stable_period_count});
                            ALL_PS_per_bs(rep,:)=PS_per_bs;
                        end
                        PS_per_bs=nanmean(ALL_PS_per_bs,1);
                    else
                        [PS_per_bs,bs_begin_sample_PS,F,~,SW_definition_thresh_FR,instantaneous_freq_per_bs,no_spike_segments]=Calculate_Spike_Power_Spectra(spikes_per_milli_sec,milli_second_begin_sample,binsize_vec(2,6),overlap_smoothing_settings,1,bandpass_SW,bandstop_SW,percent_thresh_for_SW_definition_FR,SWS_stats{1,unitnum}.NREM_bins{1,stable_period_count});
                    end
%                    [PS_per_bs_1,bs_begin_sample_PS_1,F_1,~,SW_definition_thresh_FR_1,instantaneous_freq_per_bs_1]=Calculate_Spike_Power_Spectra_1(spikes_per_milli_sec,milli_second_begin_sample,binsize_vec(2,6),overlap_smoothing_settings,1,bandpass_SW,bandstop_SW,percent_thresh_for_SW_definition_FR);
%                    [PS_per_bs_2,bs_begin_sample_PS_2,F_2,~,SW_definition_thresh_FR_2,instantaneous_freq_per_bs_2]=Calculate_Spike_Power_Spectra_2(spikes_per_milli_sec,milli_second_begin_sample,binsize_vec(2,6),overlap_smoothing_settings,1,bandpass_SW,bandstop_SW,percent_thresh_for_SW_definition_FR);
                   if isnan(firing_rate_amp_thresh_for_SW_definition(1,unitnum))
                       firing_rate_amp_thresh_for_SW_definition(1,unitnum)=SW_definition_thresh_FR;
                   else
                       firing_rate_amp_thresh_for_SW_definition(1,unitnum)=firing_rate_amp_thresh_for_SW_definition(1,unitnum)+SW_definition_thresh_FR;
                   end
                   if Analyze_EEG_to_FR_SW_correlation
                       if stable_period_count==1 % added 031217 to check whether there is a correlation between SW content in the EEGs and SW content in the FR spectrum
                           FR_SW_content=[];
                       end
                       temp_PS_per_bs=PS_per_bs(1:find(F>=35,1,'first'),:); % added 031217 to check whether there is a correlation between SW content in the EEGs and SW content in the FR spectrum
                       FR_SW_content=nanmean(temp_PS_per_bs(find(F>=0.3,1,'first'):find(F<=2,1,'last'),:),1)./nanmean(temp_PS_per_bs(find(F>=9,1,'first'):find(F<=15,1,'last'),:),1);
                       clear temp_PS_per_bs
    %                    temp_PS_per_bs=temp_PS_per_bs./repmat(sum(temp_PS_per_bs,1),size(temp_PS_per_bs,1),1);
    %                    temp_PS_per_bs=temp_PS_per_bs(find(F>=0.5,1,'first'):find(F<=2,1,'last'),:);
    %                    FR_SW_content=[FR_SW_content,sum(temp_PS_per_bs,1)];
                       if stable_period_count==length(first_stable_sample)
                           SWS_stats{1,unitnum}.FR_SW_content=FR_SW_content;
                           clear FR_SW_content
                       end
                   end
                   if Calculate_MU_Spectrum
                       MUA_no_LFP=1;
                       calculate_instantaneous_frequency=1;
                       [PS_per_bs_MU,bs_begin_sample_PS_MU,F_MU,~,MU_instantaneous_freq_per_bs]=Calculate_MU_Power_Spectra(LFP_1_segmented,bs_begin_sample_PS_LFP,LFP_SR_KHz,binsize_vec(2,6),MUA_no_LFP,calculate_instantaneous_frequency,bandpass_SW,bandstop_SW);
%                        [PS_per_bs_MU,bs_begin_sample_PS_MU,F_MU,~]=Calculate_MU_Power_Spectra(LFP_1_segmented,bs_begin_sample_PS_LFP,LFP_SR_KHz,binsize_vec(2,6));
                   end
                   % one column of S is an entire spectrum
                   if overlap_smoothing_settings(1,1)~=0
                       bs_begin_before_smoothing_PS=milli_second_begin_sample(mod((1:length(milli_second_begin_sample)),1000*binsize_vec(2,6))==1);
                   end
                   PS_on_stages=nan(6,length(bs_begin_sample_PS),size(PS_per_bs,1));
%                    PS_on_stages_1=nan(6,length(bs_begin_sample_PS_1),size(PS_per_bs_1,1));
%                    PS_on_stages_2=nan(6,length(bs_begin_sample_PS_2),size(PS_per_bs_2,1));
                   instantaneous_frequency_on_stages=nan(6,length(bs_begin_sample_PS),size(instantaneous_freq_per_bs,1));
                   if Calculate_MU_Spectrum
                       PS_on_stages_MU=nan(6,length(bs_begin_sample_PS_MU),size(PS_per_bs_MU,1));
                       MU_instantaneous_frequency_on_stages=nan(6,length(bs_begin_sample_PS_MU),size(MU_instantaneous_freq_per_bs,1));
                   end
                   if use_SWS_N3_data && exist('polysomnography_with_N3','var') && ~isempty(polysomnography_with_N3{1,unitnum}.stages.N3.begin_sample) 
                       % I made the next part a comment because this computation is done before and I dont want it to be redundant
%                        W_begins=polysomnography{unitnum}.stages.W.begin_sample; W_ends=polysomnography{unitnum}.stages.W.end_sample;
%                        N1_begins=polysomnography{unitnum}.stages.N1.begin_sample; N1_ends=polysomnography{unitnum}.stages.N1.end_sample;
%                        N2_begins=polysomnography{unitnum}.stages.N2.begin_sample; N2_ends=polysomnography{unitnum}.stages.N2.end_sample;
%                        R_begins=polysomnography{unitnum}.stages.R.begin_sample; R_ends=polysomnography{unitnum}.stages.R.end_sample;
%                        U_begins=polysomnography{unitnum}.stages.U.begin_sample; U_ends=polysomnography{unitnum}.stages.U.end_sample;
%                        N3_begins=poly_for_cross{1,unitnum}.begin_samples; N3_ends=poly_for_cross{1,unitnum}.end_samples;
%                        for kk=1:length(N3_begins)
%                            if ismember(N3_begins(kk),N2_begins) && ismember(N3_ends(kk),N2_ends)
%                                N2_begins=N2_begins(N2_begins~=N3_begins(kk));
%                                N2_ends=N2_ends(N2_ends~=N3_ends(kk));
%                            elseif ismember(N3_begins(kk),N2_begins) && ~ismember(N3_ends(kk),N2_ends)
%                                N2_begins(find(N2_begins==N3_begins(kk)))=N3_ends(kk)+1;
%                            elseif ~ismember(N3_begins(kk),N2_begins) && ismember(N3_ends(kk),N2_ends)
%                                N2_ends(find(N2_ends==N3_ends(kk)))=N3_begins(kk)-1;
%                            elseif ~ismember(N3_begins(kk),N2_begins) && ~ismember(N3_ends(kk),N2_ends)
%                                N2_begins=sort([N2_begins,N3_ends(kk)+1]);
%                                N2_ends=sort([N2_ends,N3_begins(kk)-1]);
%                            end
%                        all_begs_N3_included=sort(unique([W_begins,N1_begins,N2_begins,N3_begins,R_begins,U_begins]));
%                        all_ends_N3_included=sort(unique([W_ends,N1_ends,N2_ends,N3_ends,R_ends,U_ends]));
%                        end
                       for ii=1:length(bs_begin_sample_PS)
                           A=find(all_begs_N3_included<=bs_begin_sample_PS(1,ii),1,'last');
                           closest_bin_end=min(bs_begin_sample_PS(1,ii)+Info{unitnum}.SAMPLING*binsize_vec(2,6)*1000-1,last_stable_sample(stable_period_count));
                           B=find(all_ends_N3_included>=closest_bin_end,1,'first');
                           marker=NaN;
                           if ((B-A)==0 || ((B-A)==1 && closest_bin_end-all_begs_N3_included(A+1)<all_begs_N3_included(A+1)-bs_begin_sample_PS(1,ii)))
                              marker=all_begs_N3_included(A);
                           elseif ((B-A)==1 && closest_bin_end-all_begs_N3_included(A+1)>=all_begs_N3_included(A+1)-bs_begin_sample_PS(1,ii))
                              marker=all_begs_N3_included(A+1);
                           elseif (B-A)==2 % I added this in 062317 after I figures out that this situation can actually happen, If the epoch is a few samples short of 440000 and the bs happens to start really at the end of the previous one, traverse the entire shorter epoch and then end in the following one.
                              marker=all_begs_N3_included(A+1);
                           end
                           if ismember(marker,W_begins)
                              ind=1;
                           elseif ismember(marker,N1_begins)
                              ind=2;
                           elseif ismember(marker,N2_begins)
                              ind=3;
                           elseif ismember(marker,N3_begins)
                              ind=4;
                           elseif ismember(marker,R_begins)
                              ind=5;                
                           elseif ismember(marker,U_begins)
                              ind=6;                
                           end
                           all_nan=squeeze(isnan(PS_on_stages(ind,:,1))); % 1 only for convenience - to find the next NaN
                           PS_on_stages(ind,find(all_nan==1,1,'first'),:)=PS_per_bs(:,ii);
%                            all_nan_1=squeeze(isnan(PS_on_stages_1(ind,:,1))); % 1 only for convenience - to find the next NaN
%                            PS_on_stages_1(ind,find(all_nan_1==1,1,'first'),:)=PS_per_bs_1(:,ii);
%                            all_nan_2=squeeze(isnan(PS_on_stages_2(ind,:,1))); % 1 only for convenience - to find the next NaN
%                            PS_on_stages_2(ind,find(all_nan_2==1,1,'first'),:)=PS_per_bs_2(:,ii);
                           instantaneous_frequency_on_stages(ind,find(all_nan==1,1,'first'),:)=instantaneous_freq_per_bs(:,ii);
                       end
                       if Calculate_MU_Spectrum
                           for ii=1:length(bs_begin_sample_PS_MU)
                               A=find(all_begs_N3_included<=bs_begin_sample_PS_MU(1,ii),1,'last');
                               closest_bin_end=min(bs_begin_sample_PS_MU(1,ii)+Info{unitnum}.SAMPLING*binsize_vec(2,6)*1000-1,last_stable_sample(stable_period_count));
                               B=find(all_ends_N3_included>=closest_bin_end,1,'first');
                               marker=NaN;
                               if ((B-A)==0 || ((B-A)==1 && closest_bin_end-all_begs_N3_included(A+1)<all_begs_N3_included(A+1)-bs_begin_sample_PS_MU(1,ii)))
                                  marker=all_begs_N3_included(A);
                               elseif ((B-A)==1 && closest_bin_end-all_begs_N3_included(A+1)>=all_begs_N3_included(A+1)-bs_begin_sample_PS_MU(1,ii))
                                  marker=all_begs_N3_included(A+1);
                               elseif (B-A)==2 % I added this in 062317 after I figures out that this situation can actually happen, If the epoch is a few samples short of 440000 and the bs happens to start really at the end of the previous one, traverse the entire shorter epoch and then end in the following one.
                                  marker=all_begs_N3_included(A+1);                                  
                               end
                               if ismember(marker,W_begins)
                                  ind=1;
                               elseif ismember(marker,N1_begins)
                                  ind=2;
                               elseif ismember(marker,N2_begins)
                                  ind=3;
                               elseif ismember(marker,N3_begins)
                                  ind=4;
                               elseif ismember(marker,R_begins)
                                  ind=5;                
                               elseif ismember(marker,U_begins)
                                  ind=6;                
                               end
                               all_nan=squeeze(isnan(PS_on_stages_MU(ind,:,1))); % 1 only for convenience - to find the next NaN
                               PS_on_stages_MU(ind,find(all_nan==1,1,'first'),:)=PS_per_bs_MU(:,ii);
                               MU_instantaneous_frequency_on_stages(ind,find(all_nan==1,1,'first'),:)=MU_instantaneous_freq_per_bs(:,ii);
                           end                       
                       end
                   else
                       for ii=1:length(bs_begin_sample_PS)
                           if last_stable_sample(stable_period_count)-bs_begin_sample_PS(end)==0
                               continue;
                           end % added 070217 
                           if Calculate_MU_Spectrum
                               if length(bs_begin_sample_PS)-size(PS_on_stages_MU,2)==1 && ii==length(bs_begin_sample_PS)
                                   continue;
                               end % added 071117      
                           end
                           A=find(all_begs<=bs_begin_sample_PS(1,ii),1,'last');
                           closest_bin_end=min(bs_begin_sample_PS(1,ii)+Info{unitnum}.SAMPLING*binsize_vec(2,6)*1000-1,last_stable_sample(stable_period_count));
                           B=find(all_ends>=closest_bin_end,1,'first');
                           marker=NaN;
                           if ((B-A)==0 || ((B-A)==1 && closest_bin_end-all_begs(A+1)<all_begs(A+1)-bs_begin_sample_PS(1,ii)))
                              marker=all_begs(A);
                           elseif ((B-A)==1 && closest_bin_end-all_begs(A+1)>=all_begs(A+1)-bs_begin_sample_PS(1,ii))
                              marker=all_begs(A+1);
                           elseif (B-A)==2 % I added this in 062317 after I figures out that this situation can actually happen, If the epoch is a few samples short of 440000 and the bs happens to start really at the end of the previous one, traverse the entire shorter epoch and then end in the following one.
                              marker=all_begs(A+1);                                                            
                           end
                           if ismember(marker,polysomnography{unitnum}.stages.W.begin_sample)
                              ind=1;
                           elseif ismember(marker,polysomnography{unitnum}.stages.N1.begin_sample)
                              ind=2;
                           elseif ismember(marker,polysomnography{unitnum}.stages.N2.begin_sample)
                              ind=3;
                           elseif ismember(marker,polysomnography{unitnum}.stages.N3.begin_sample)
                              ind=4;
                           elseif ismember(marker,polysomnography{unitnum}.stages.R.begin_sample)
                              ind=5;                
                           elseif ismember(marker,polysomnography{unitnum}.stages.U.begin_sample)
                              ind=6;                
                           end
                           all_nan=squeeze(isnan(PS_on_stages(ind,:,1))); % 1 only for convenience - to find the next NaN
                           PS_on_stages(ind,find(all_nan==1,1,'first'),:)=PS_per_bs(:,ii);
                           instantaneous_frequency_on_stages(ind,find(all_nan==1,1,'first'),:)=instantaneous_freq_per_bs(:,ii);
                           if Calculate_MU_Spectrum
                               all_nan=squeeze(isnan(PS_on_stages_MU(ind,:,1))); % 1 only for convenience - to find the next NaN
                               PS_on_stages_MU(ind,find(all_nan==1,1,'first'),:)=PS_per_bs_MU(:,ii);          
                               MU_instantaneous_frequency_on_stages(ind,find(all_nan==1,1,'first'),:)=MU_instantaneous_freq_per_bs(:,ii);
                           end
                       end                                          
                   end
                   if Prune_BG_spikes_for_PS_analysis 
                       spikes_per_milli_sec=spikes_per_milli_sec_original; % return to the original spikes_per_milli_sec, for the next analyses
                   end                   
                end
                if LFP_to_unit_analysis && exist('period_LFP_spectrum','var')
                    % for the LFP locking analysis, eliminate the N3 epochs
                    % during which there weer no spikes and hence no unit
                    % spectrum 
                    % changed 070817
                    
%                     period_LFP_spectrum_N3=period_LFP_spectrum_N3(:,setdiff(1:size(period_LFP_spectrum_N3,2),find(ismember(NREM_bins_for_LFP(N3_segments_Fr_OR_Cr_for_LFP),no_spike_segments)==1)));
                    All_unit_LFP_spectrum_N3=[All_unit_LFP_spectrum_N3,period_LFP_spectrum_N3];
%                     All_unit_LFP_IF_N3=[All_unit_LFP_IF_N3,period_LFP_IF_N3(1,setdiff([1:length(period_LFP_IF_N3)],[find(ismember(NREM_bins_for_LFP(N3_segments_Fr_OR_Cr_for_LFP),no_spike_segments)==1),find(isnan(instantaneous_frequency_on_stages(4,1:length(period_LFP_IF_N3))))]))]; %070217
                    All_unit_LFP_IF_N3=[All_unit_LFP_IF_N3,period_LFP_IF_N3];
                    All_unit_LFP_EEG_corr_N3=[All_unit_LFP_EEG_corr_N3,LFP_EEG_corr_N3];
                    
                    All_unit_LFP_spectrum_N2=[All_unit_LFP_spectrum_N2,period_LFP_spectrum_N2];
                    All_unit_LFP_IF_N2=[All_unit_LFP_IF_N2,period_LFP_IF_N2];
                    All_unit_LFP_EEG_corr_N2=[All_unit_LFP_EEG_corr_N2,LFP_EEG_corr_N2];
                    
                    All_unit_LFP_spectrum_R=[All_unit_LFP_spectrum_R,period_LFP_spectrum_R];
                    All_unit_LFP_IF_R=[All_unit_LFP_IF_R,period_LFP_IF_R];
                    All_unit_LFP_EEG_corr_R=[All_unit_LFP_EEG_corr_R,LFP_EEG_corr_R];
                    
                    All_unit_LFP_spectrum_W=[All_unit_LFP_spectrum_W,period_LFP_spectrum_W];
                    All_unit_LFP_IF_W=[All_unit_LFP_IF_W,period_LFP_IF_W];
                    All_unit_LFP_EEG_corr_W=[All_unit_LFP_EEG_corr_W,LFP_EEG_corr_W];
                end
                if binsize_vec(1,10)==1 % check if the unit is eligible for SW-based analysis
                    [~,min_loc]=min(abs(F-bandpass_SW(1)));
                    [~,max_loc]=min(abs(F-bandpass_SW(2)));
                    mean_SW_during_SWS=nanmean(nanmean(PS_on_stages(4,:,min_loc:max_loc)));
                    mean_SW_during_W=nanmean(nanmean(PS_on_stages(1,:,min_loc:max_loc)));
                    SWS_stats{1,unitnum}.SWS_to_W_ratio(1,stable_period_count)=mean_SW_during_SWS/mean_SW_during_W;
                end
                clear ii ind marker A B all_nan spikes_per_milli_sec milli_second_begin_sample appropriate_spikes               
                
                if binsize_vec(1,7) % LFP (&EEG) analysis
                    % ALL EEG lines are remarked, to make computations
                    % faster. They are marked "remarked: 062016 EEG start/end"
                    % If the "remarked" line had to me modified to allow
                    % normal computations, the modified line was inserted
                    % between the "start/end". When you change back, be
                    % sure to reintroduce the erased line and erase the one
                    % I added now. 062016.
                    % Two computations will be performed on the LFP - 
                    % 1. RMS analysis (binsizes analogous to FR analysis).
                    % 2. Power Spectra (binsizes analogous to PS analysis).
                    
                    % Retrieve LFP traces for the unit
                    LFP=[];
                    % remarked: 062016 EEG start/end
%                     EEG_1=[]; % lead 3, occipital
%                     EEG_2=[]; % lead 2, central
%                     EEG_3=[]; % lead 4, frontal, didn't always work
                    % remarked: 062016 EEG start/end
                    all_file_starts=[];
                    all_file_ends=[];
                    for ff=1:length(Datafiles{1,unitnum})
                        all_file_starts=[all_file_starts,Datafiles{1,unitnum}(ff,1).start_sample];
                        all_file_ends=[all_file_ends,Datafiles{1,unitnum}(ff,1).end_sample];
                    end
                    beginning_file=find(all_file_starts<=first_stable_sample(stable_period_count),1,'last');
                    ending_file=find(all_file_ends>=last_stable_sample(stable_period_count),1,'first');
                    for ff=beginning_file:1:ending_file
                        % This next piece of code was written after I found out that not *all* my file-2-file gaps (in samples) was only 1 sample, as requested. A very
                        % preliminary check showed that some are indeed 1, many are -X, -30<X<0 and one was a few seconds - This corresponds to shut down and turn on of the
                        % machine in the middle of recording. Either way, if I concatenate files I have to be ready for that. Gere comes this code - for every new file,
                        % if the number of samples between this and the last file was bigger than 1, nans are added. If the difference is smaller than 1, meaning the new
                        % file started "prematurely", the needed number of samples from LFP will be erased. Next, if I have portions of the LFP vector which have more than
                        % 50% NaNs, this won't be analyzed - the RMS and the PS will get all NaNs.

%                         if ff~=beginning_file % see below (spike triggered LFP code) why this workaround is unnecessary.
%                             difference_between_samples=Datafiles{1,unitnum}(ff,1).start_sample-Datafiles{1,unitnum}(ff-1,1).end_sample;
%                             if difference_between_samples>1
%                                 LFP=[LFP,nan(1,round((difference_between_samples-1)/Info{1,unitnum}.SAMPLING*LFP_KHz))];
%                                 EEG_1=[EEG_1,nan(1,round((difference_between_samples-1)/Info{1,unitnum}.SAMPLING*EEG_KHz))];
%                                 EEG_2=[EEG_2,nan(1,round((difference_between_samples-1)/Info{1,unitnum}.SAMPLING*EEG_KHz))];
%                                 EEG_3=[EEG_3,nan(1,round((difference_between_samples-1)/Info{1,unitnum}.SAMPLING*EEG_KHz))];
%                             elseif difference_between_samples<1
%                                 LFP=LFP(1:length(LFP)-round((1-difference_between_samples)/Info{1,unitnum}.SAMPLING*LFP_KHz));
%                                 EEG_1=EEG_1(1:length(EEG_1)-round((1-difference_between_samples)/Info{1,unitnum}.SAMPLING*EEG_KHz));
%                                 EEG_2=EEG_2(1:length(EEG_2)-round((1-difference_between_samples)/Info{1,unitnum}.SAMPLING*EEG_KHz));
%                                 EEG_3=EEG_3(1:length(EEG_3)-round((1-difference_between_samples)/Info{1,unitnum}.SAMPLING*EEG_KHz));
%                             end
%                         end
                        a=0;
                        AA=['CLFP_00',num2str(ElecNum(1,unitnum))];
                        BB=['CLFP_00',num2str(ElecNum(1,unitnum)),'_KHz'];
                        CC=['CLFP_00',num2str(ElecNum(1,unitnum)),'_TimeBegin'];
                        % remarked: 062016 EEG start/end
%                         EE_1='CLFP_019';
%                         EE_2='CLFP_018';
%                         EE_3='CLFP_020';
%                         FF_1='CLFP_019_TimeBegin';
%                         FF_2='CLFP_018_TimeBegin';
%                         FF_3='CLFP_020_TimeBegin';
%                         GG='CLFP_019_KHz';
                        % remarked: 062016 EEG start/end
                        filename=Datafiles{1,unitnum}(ff,1).name;
                        if exist(filename)
                            % remarked: 062016 EEG start/end
%                             load(filename,AA,EE_1,EE_2,EE_3);
                            load(filename,'-mat',AA);
                            % remarked: 062016 EEG start/end
                            eval(['a=~isstruct(',AA,');'])
                            if a==1
                                % remarked: 062016 EEG start/end
%                                 load(filename,BB,CC,FF_1,FF_2,FF_3,GG);
                                load(filename,'-mat',BB,CC);
                                % remarked: 062016 EEG start/end
                                eval(['CLFP_00',num2str(ElecNum(1,unitnum)),'.Samples=double(',AA,');']);
                                eval(['CLFP_00',num2str(ElecNum(1,unitnum)),'.KHz=double(',BB,');']);
                                eval(['CLFP_00',num2str(ElecNum(1,unitnum)),'.TimeBegin=double(',CC,');']);
                                % remarked: 062016 EEG start/end
%                                 CLFP_019.Samples=double(CLFP_019);
%                                 CLFP_018.Samples=double(CLFP_018);
%                                 CLFP_020.Samples=double(CLFP_020);
%                                 CLFP_019.KHz=double(CLFP_019_KHz);
%                                 CLFP_018.KHz=double(CLFP_019_KHz);
%                                 CLFP_020.KHz=double(CLFP_019_KHz);
%                                 CLFP_019.TimeBegin=double(CLFP_019_TimeBegin);
%                                 CLFP_018.TimeBegin=double(CLFP_018_TimeBegin);
%                                 CLFP_020.TimeBegin=double(CLFP_020_TimeBegin);                                
                                % remarked: 062016 EEG start/end
                            end                            
                        else % try to proceed day
                            filename_1=[filename(1:end-22),num2str(str2num(filename(end-21:end-20))+1),filename(end-19:end)];
                            if exist(filename_1)
                                % remarked: 062016 EEG start/end
%                                 load(filename_1,AA,EE_1,EE_2,EE_3);
                                load(filename_1,'-mat',AA);
                                % remarked: 062016 EEG start/end
                                eval(['a=~isstruct(',AA,');'])
                                if a==1
                                    % remarked: 062016 EEG start/end
%                                     load(filename_1,BB,CC,FF_1,FF_2,FF_3,GG);
                                    load(filename_1,'-mat',BB,CC);
                                    % remarked: 062016 EEG start/end
                                    eval(['CLFP_00',num2str(ElecNum(1,unitnum)),'.Samples=double(',AA,');']);
                                    eval(['CLFP_00',num2str(ElecNum(1,unitnum)),'.KHz=double(',BB,');']);
                                    eval(['CLFP_00',num2str(ElecNum(1,unitnum)),'.TimeBegin=double(',CC,');']);
                                    % remarked: 062016 EEG start/end
%                                     CLFP_019.Samples=double(CLFP_019);
%                                     CLFP_018.Samples=double(CLFP_018);
%                                     CLFP_020.Samples=double(CLFP_020);
%                                     CLFP_019.KHz=double(CLFP_019_KHz);
%                                     CLFP_018.KHz=double(CLFP_019_KHz);
%                                     CLFP_020.KHz=double(CLFP_019_KHz);
%                                     CLFP_019.TimeBegin=double(CLFP_019_TimeBegin);
%                                     CLFP_018.TimeBegin=double(CLFP_018_TimeBegin);
%                                     CLFP_020.TimeBegin=double(CLFP_020_TimeBegin);
                                    % remarked: 062016 EEG start/end
                                end 
                            else  % try to move day back
                                filename_2=[filename(1:end-22),num2str(str2num(filename(end-21:end-20))-1),filename(end-19:end)];
                                if exist(filename_2)
                                    % remarked: 062016 EEG start/end
%                                     load(filename_2,AA,EE_1,EE_2,EE_3);
                                    load(filename_2,'-mat',AA);
                                    % remarked: 062016 EEG start/end
                                    eval(['a=~isstruct(',AA,');'])
                                    if a==1
                                        % remarked: 062016 EEG start/end
                                        load(filename_2,'-mat',BB,CC);
%                                         load(filename_2,BB,CC,FF_1,FF_2,FF_3,GG);
                                        % remarked: 062016 EEG start/end
                                        eval(['CLFP_00',num2str(ElecNum(1,unitnum)),'.Samples=double(',AA,');']);
                                        eval(['CLFP_00',num2str(ElecNum(1,unitnum)),'.KHz=double(',BB,');']);
                                        eval(['CLFP_00',num2str(ElecNum(1,unitnum)),'.TimeBegin=double(',CC,');']);
                                        % remarked: 062016 EEG start/end
%                                         CLFP_019.Samples=double(CLFP_019);
%                                         CLFP_018.Samples=double(CLFP_018);
%                                         CLFP_020.Samples=double(CLFP_020);
%                                         CLFP_019.KHz=double(CLFP_019_KHz);
%                                         CLFP_018.KHz=double(CLFP_019_KHz);
%                                         CLFP_020.KHz=double(CLFP_019_KHz);
%                                         CLFP_019.TimeBegin=double(CLFP_019_TimeBegin);
%                                         CLFP_018.TimeBegin=double(CLFP_018_TimeBegin);
%                                         CLFP_020.TimeBegin=double(CLFP_020_TimeBegin);
                                        % remarked: 062016 EEG start/end
                                    end                                     
                                else % for a case where the file name is longer because of files>100, proceed day
                                    filename_3=[filename(1:end-23),num2str(str2num(filename(end-22:end-21))+1),filename(end-20:end)];
                                    if exist(filename_3)
                                        % remarked: 062016 EEG start/end
                                        load(filename_3,'-mat',AA);
%                                         load(filename_3,AA,EE_1,EE_2,EE_3);
                                        % remarked: 062016 EEG start/end
                                        eval(['a=~isstruct(',AA,');'])
                                        if a==1
                                            % remarked: 062016 EEG start/end
%                                             load(filename_3,BB,CC,FF_1,FF_2,FF_3,GG);
                                               load(filename_3,'-mat',BB,CC);
                                            % remarked: 062016 EEG start/end
                                            eval(['CLFP_00',num2str(ElecNum(1,unitnum)),'.Samples=double(',AA,');']);
                                            eval(['CLFP_00',num2str(ElecNum(1,unitnum)),'.KHz=double(',BB,');']);
                                            eval(['CLFP_00',num2str(ElecNum(1,unitnum)),'.TimeBegin=double(',CC,');']);
                                            % remarked: 062016 EEG start/end
%                                             CLFP_019.Samples=double(CLFP_019);
%                                             CLFP_018.Samples=double(CLFP_018);
%                                             CLFP_020.Samples=double(CLFP_020);
%                                             CLFP_019.KHz=double(CLFP_019_KHz);
%                                             CLFP_018.KHz=double(CLFP_019_KHz);
%                                             CLFP_020.KHz=double(CLFP_019_KHz);
%                                             CLFP_019.TimeBegin=double(CLFP_019_TimeBegin);
%                                             CLFP_018.TimeBegin=double(CLFP_018_TimeBegin);
%                                             CLFP_020.TimeBegin=double(CLFP_020_TimeBegin);
                                            % remarked: 062016 EEG start/end
                                        end                                         
                                    else  % for a case where the file name is longer because of files>100, day back
                                        filename_4=[filename(1:end-23),num2str(str2num(filename(end-22:end-21))-1),filename(end-20:end)];
                                        % remarked: 062016 EEG start/end
                                        load(filename_4,'-mat',AA);
%                                         load(filename_4,AA,EE_1,EE_2,EE_3);
                                        % remarked: 062016 EEG start/end
                                        eval(['a=~isstruct(',AA,');'])
                                        if a==1
                                            % remarked: 062016 EEG start/end
                                            load(filename_4,'-mat',BB,CC);
%                                             load(filename_4,BB,CC,FF_1,FF_2,FF_3,GG);
                                            % remarked: 062016 EEG start/end
                                            eval(['CLFP_00',num2str(ElecNum(1,unitnum)),'.Samples=double(',AA,');']);
                                            eval(['CLFP_00',num2str(ElecNum(1,unitnum)),'.KHz=double(',BB,');']);
                                            eval(['CLFP_00',num2str(ElecNum(1,unitnum)),'.TimeBegin=double(',CC,');']);
                                            % remarked: 062016 EEG start/end
%                                             CLFP_019.Samples=double(CLFP_019);
%                                             CLFP_018.Samples=double(CLFP_018);
%                                             CLFP_020.Samples=double(CLFP_020);
%                                             CLFP_019.KHz=double(CLFP_019_KHz);
%                                             CLFP_018.KHz=double(CLFP_019_KHz);
%                                             CLFP_020.KHz=double(CLFP_019_KHz);
%                                             CLFP_019.TimeBegin=double(CLFP_019_TimeBegin);
%                                             CLFP_018.TimeBegin=double(CLFP_018_TimeBegin);
%                                             CLFP_020.TimeBegin=double(CLFP_020_TimeBegin);
                                            % remarked: 062016 EEG start/end
                                        end                                         
                                    end
                                end
                            end
                        end
                        eval(['signal=CLFP_00',num2str(ElecNum(1,unitnum)),'.Samples;']);
%                         % remarked: 062016 EEG start/end
%                         signal_EEG_1=CLFP_019.Samples;
%                         signal_EEG_2=CLFP_018.Samples;
%                         signal_EEG_3=CLFP_020.Samples;
                          % remarked: 062016 EEG start/end
                        if ff==beginning_file
                            eval(['LFP_KHz=CLFP_00',num2str(ElecNum(1,unitnum)),'.KHz;']);
                            % remarked: 062016 EEG start/end
%                             EEG_KHz=CLFP_019.KHz;
                            % remarked: 062016 EEG start/end
                            eval(['file_begin_sample=floor(CLFP_00',num2str(ElecNum(1,unitnum)),'.TimeBegin*LFP_KHz*1000);']);
                            % remarked: 062016 EEG start/end
%                             file_begin_sample_EEG_1=floor(CLFP_019.TimeBegin*EEG_KHz*1000);
%                             file_begin_sample_EEG_2=floor(CLFP_018.TimeBegin*EEG_KHz*1000);
%                             file_begin_sample_EEG_3=floor(CLFP_020.TimeBegin*EEG_KHz*1000);
                            % remarked: 062016 EEG start/end
                        end
                        signal=double(signal-nanmean(signal));
                        % remarked: 062016 EEG start/end
%                         signal_EEG_1=signal_EEG_1-nanmean(signal_EEG_1);
%                         signal_EEG_2=signal_EEG_2-nanmean(signal_EEG_2);
%                         signal_EEG_3=signal_EEG_3-nanmean(signal_EEG_3);
                        % remarked: 062016 EEG start/end
                        signal=BWfilter_designer(double(signal), LFP_KHz*1000, 70, 85, 'LP');
                        % remarked: 062016 EEG start/end
%                         signal_EEG_1=BWfilter_designer(double(signal_EEG_1), EEG_KHz*1000, 70, 85, 'LP');
%                         signal_EEG_2=BWfilter_designer(double(signal_EEG_2), EEG_KHz*1000, 70, 85, 'LP');
%                         signal_EEG_3=BWfilter_designer(double(signal_EEG_3), EEG_KHz*1000, 70, 85, 'LP');
                        % remarked: 062016 EEG start/end
                        LFP=[LFP,signal]; % no assumption of no sample loss between files (see before)
                        % remarked: 062016 EEG start/end
%                         EEG_1=[EEG_1,signal_EEG_1];
%                         EEG_2=[EEG_2,signal_EEG_2];
%                         EEG_3=[EEG_3,signal_EEG_3];
                        % remarked: 062016 EEG start/end
                        clear CLFP_0*
                    end
                    % create a new vector. Its elements are the LFP vector segments corresponding to the bins from the FR calculation
                    bs_begin_sample_LFP_RMS=floor(bs_begin_sample_FR/Info{1,unitnum}.SAMPLING*LFP_KHz);
                    LFP_segmented=cell(1,length(bs_begin_sample_LFP_RMS));
                    for ff=1:length(bs_begin_sample_LFP_RMS)
                        if bs_begin_sample_LFP_RMS(1,1)<file_begin_sample                        
                            bs_begin_sample_LFP_RMS(1,1)=file_begin_sample;
                        end
                        if ff~=length(bs_begin_sample_LFP_RMS)
                            LFP_segmented{1,ff}=LFP(bs_begin_sample_LFP_RMS(1,ff)-file_begin_sample+1:bs_begin_sample_LFP_RMS(1,ff+1)-1-file_begin_sample+1);
                        else
                            LFP_segmented{1,ff}=LFP(bs_begin_sample_LFP_RMS(1,ff)-file_begin_sample+1:bs_begin_sample_LFP_RMS(1,ff)-file_begin_sample+length(LFP_segmented{1,ff-1})); % simply take a segment whose length is as the previous one's
                        end
                    end
                    % compute the RMS for each segment
                    LFP_RMS_per_bs=nan(1,length(LFP_segmented));
                    for ff=1:length(LFP_segmented)
                        if sum(isnan(LFP_segmented{1,ff}))>=0.5*length(LFP_segmented{1,ff})
                            LFP_RMS_per_bs(1,ff)=NaN;
                        else
                            LFP_RMS_per_bs(1,ff)=rms(LFP_segmented{1,ff});
                        end
                    end
                   % use the original FR begin sample to do more "correct" distribution of sleep stages
                   LFP_RMS_on_stages=nan(6,length(bs_begin_sample_FR));
                   for ii=1:length(bs_begin_sample_FR)
                       A=find(all_begs<=bs_begin_sample_FR(1,ii),1,'last');
                       closest_bin_end=min(bs_begin_sample_FR(1,ii)+Info{unitnum}.SAMPLING*binsize_vec(2,2)*1000-1,last_stable_sample(stable_period_count));
                       B=find(all_ends>=closest_bin_end,1,'first'); % this RMS calculation os analog to the FR calculation, so the right bisize is that of the FR.
                       marker=NaN;
                       if ((B-A)==0 || ((B-A)==1 && closest_bin_end-all_begs(A+1)<all_begs(A+1)-bs_begin_sample_FR(1,ii)))
                          marker=all_begs(A);
                       elseif ((B-A)==1 && closest_bin_end-all_begs(A+1)>=all_begs(A+1)-bs_begin_sample_FR(1,ii))
                          marker=all_begs(A+1);
                       elseif (B-A)==2 % I added this in 062317 after I figures out that this situation can actually happen, If the epoch is a few samples short of 440000 and the bs happens to start really at the end of the previous one, traverse the entire shorter epoch and then end in the following one.
                          marker=all_begs(A+1);                                                        
                       end
                       if ismember(marker,polysomnography{unitnum}.stages.W.begin_sample)
                          ind=1;
                       elseif ismember(marker,polysomnography{unitnum}.stages.N1.begin_sample)
                          ind=2;
                       elseif ismember(marker,polysomnography{unitnum}.stages.N2.begin_sample)
                          ind=3;
                       elseif ismember(marker,polysomnography{unitnum}.stages.N3.begin_sample)
                          ind=4;
                       elseif ismember(marker,polysomnography{unitnum}.stages.R.begin_sample)
                          ind=5;                
                       elseif ismember(marker,polysomnography{unitnum}.stages.U.begin_sample)
                          ind=6;                                          
                       end
                       all_nan=squeeze(isnan(LFP_RMS_on_stages(ind,:)));
                       LFP_RMS_on_stages(ind,find(all_nan==1,1,'first'))=LFP_RMS_per_bs(1,ii);
                   end 
                   clear A AA B BB CC LFP_segmented marker ind a beginning_file ending_file all_file_starts all_file_ends all_nan difference_between_samples ff filename filename_1 ii marker signal
                   
                   % calculate the LFP PS
                   % create a new vector. Its elements are the LFP vector segments for the PS calculation
                   LFP_segmented={};
                   % remarked: 062016 EEG start/end
%                    EEG_1_segmented={};
%                    EEG_2_segmented={};
%                    EEG_3_segmented={};
                   % remarked: 062016 EEG start/end
                   bs_begin_sample_PS_LFP=[];
                   % remarked: 062016 EEG start/end
%                    bs_begin_sample_PS_EEG=[];
                   % remarked: 062016 EEG start/end
                   first_stable_sample_LFP=floor(bs_begin_sample_FR(1,1)/Info{1,unitnum}.SAMPLING*LFP_KHz);
                   last_stable_sample_LFP=floor(last_stable_sample(1,stable_period_count)/Info{1,unitnum}.SAMPLING*LFP_KHz);
                   % remarked: 062016 EEG start/end
%                    first_stable_sample_EEG=floor(bs_begin_sample_FR(1,1)/Info{1,unitnum}.SAMPLING*EEG_KHz);
%                    last_stable_sample_EEG=floor(last_stable_sample(1,stable_period_count)/Info{1,unitnum}.SAMPLING*EEG_KHz);                   
                   % remarked: 062016 EEG start/end
                   if first_stable_sample_LFP<file_begin_sample                        
                       first_stable_sample_LFP=file_begin_sample;
                   end
                   % remarked: 062016 EEG start/end
%                    if first_stable_sample_EEG<file_begin_sample                        
%                        first_stable_sample_EEG=file_begin_sample;
%                    end 
                   % remarked: 062016 EEG start/end
                   % create LFP_segmented
                    while first_stable_sample_LFP+(length(LFP_segmented)+1)*LFP_KHz*1000*binsize_vec(2,7)<=last_stable_sample_LFP
                        LFP_segmented{1,length(LFP_segmented)+1}=LFP(first_stable_sample_LFP+length(LFP_segmented)*LFP_KHz*1000*binsize_vec(2,7)-file_begin_sample+1:first_stable_sample_LFP+(length(LFP_segmented)+1)*LFP_KHz*1000*binsize_vec(2,7)-file_begin_sample);
                        bs_begin_sample_PS_LFP(1,length(bs_begin_sample_PS_LFP)+1)=first_stable_sample_LFP+(length(LFP_segmented)-1)*LFP_KHz*1000*binsize_vec(2,7);                        
                        if (first_stable_sample_LFP+(length(LFP_segmented)+1)*LFP_KHz*1000*binsize_vec(2,7)>last_stable_sample_LFP) && (first_stable_sample_LFP+(length(LFP_segmented))*LFP_KHz*1000*binsize_vec(2,7)~=last_stable_sample_LFP)
                            LFP_segmented{1,length(LFP_segmented)+1}=LFP(first_stable_sample_LFP+length(LFP_segmented)*LFP_KHz*1000*binsize_vec(2,7)-file_begin_sample+1:last_stable_sample_LFP-file_begin_sample+1);
                            LFP_segmented{1,length(LFP_segmented)}=[LFP_segmented{1,length(LFP_segmented)},zeros(1,LFP_KHz*1000*binsize_vec(2,7)-length(LFP_segmented{1,length(LFP_segmented)})+1)]; % ZP 
                            bs_begin_sample_PS_LFP(1,length(bs_begin_sample_PS_LFP)+1)=first_stable_sample_LFP+(length(LFP_segmented)-1)*LFP_KHz*1000*binsize_vec(2,7);                        
                        end
                    end
                   % create EEG_X_segmented
                   % remarked: 062016 EEG start/end
%                     while first_stable_sample_EEG+(length(EEG_1_segmented)+1)*EEG_KHz*1000*binsize_vec(2,7)<=last_stable_sample_EEG
%                         EEG_1_segmented{1,length(EEG_1_segmented)+1}=EEG_1(first_stable_sample_EEG+length(EEG_1_segmented)*EEG_KHz*1000*binsize_vec(2,7)-file_begin_sample_EEG_1+1:first_stable_sample_EEG+(length(EEG_1_segmented)+1)*EEG_KHz*1000*binsize_vec(2,7)-file_begin_sample_EEG_1);
%                         EEG_2_segmented{1,length(EEG_2_segmented)+1}=EEG_2(first_stable_sample_EEG+length(EEG_2_segmented)*EEG_KHz*1000*binsize_vec(2,7)-file_begin_sample_EEG_2+1:first_stable_sample_EEG+(length(EEG_2_segmented)+1)*EEG_KHz*1000*binsize_vec(2,7)-file_begin_sample_EEG_2);
%                         EEG_3_segmented{1,length(EEG_3_segmented)+1}=EEG_3(first_stable_sample_EEG+length(EEG_3_segmented)*EEG_KHz*1000*binsize_vec(2,7)-file_begin_sample_EEG_3+1:first_stable_sample_EEG+(length(EEG_3_segmented)+1)*EEG_KHz*1000*binsize_vec(2,7)-file_begin_sample_EEG_3);
%                         bs_begin_sample_PS_EEG(1,length(bs_begin_sample_PS_EEG)+1)=first_stable_sample_EEG+(length(EEG_1_segmented)-1)*EEG_KHz*1000*binsize_vec(2,7);
%                         if (first_stable_sample_EEG+(length(EEG_1_segmented)+1)*EEG_KHz*1000*binsize_vec(2,7)>last_stable_sample_EEG) && (first_stable_sample_EEG+(length(EEG_1_segmented))*EEG_KHz*1000*binsize_vec(2,7)~=last_stable_sample_EEG)
%                             EEG_1_segmented{1,length(EEG_1_segmented)+1}=EEG_1(first_stable_sample_EEG+length(EEG_1_segmented)*EEG_KHz*1000*binsize_vec(2,7)-file_begin_sample_EEG_1+1:last_stable_sample_EEG-file_begin_sample_EEG_1+1);
%                             EEG_1_segmented{1,length(EEG_1_segmented)}=[EEG_1_segmented{1,length(EEG_1_segmented)},zeros(1,EEG_KHz*1000*binsize_vec(2,7)-length(EEG_1_segmented{1,length(EEG_1_segmented)})+1)]; % ZP 
%                             EEG_2_segmented{1,length(EEG_2_segmented)+1}=EEG_2(first_stable_sample_EEG+length(EEG_2_segmented)*EEG_KHz*1000*binsize_vec(2,7)-file_begin_sample_EEG_2+1:last_stable_sample_EEG-file_begin_sample_EEG_2+1);
%                             EEG_2_segmented{1,length(EEG_2_segmented)}=[EEG_2_segmented{1,length(EEG_2_segmented)},zeros(1,EEG_KHz*1000*binsize_vec(2,7)-length(EEG_2_segmented{1,length(EEG_2_segmented)})+1)]; % ZP 
%                             EEG_3_segmented{1,length(EEG_3_segmented)+1}=EEG_3(first_stable_sample_EEG+length(EEG_3_segmented)*EEG_KHz*1000*binsize_vec(2,7)-file_begin_sample_EEG_3+1:last_stable_sample_EEG-file_begin_sample_EEG_3+1);
%                             EEG_3_segmented{1,length(EEG_3_segmented)}=[EEG_3_segmented{1,length(EEG_3_segmented)},zeros(1,EEG_KHz*1000*binsize_vec(2,7)-length(EEG_3_segmented{1,length(EEG_3_segmented)})+1)]; % ZP                             
%                             bs_begin_sample_PS_EEG(1,length(bs_begin_sample_PS_EEG)+1)=first_stable_sample_EEG+(length(EEG_1_segmented)-1)*EEG_KHz*1000*binsize_vec(2,7);
%                         end
%                     end
                    % remarked: 062016 EEG start/end
                    % calculate PS
                    LFP_PS_per_bs=cell(1,length(LFP_segmented));
                    for ff=1:length(LFP_segmented)
                        if sum(isnan(LFP_segmented{1,ff}))>=0.5*length(LFP_segmented{1,ff})
                            LFP_PS_per_bs{1,ff}=NaN(1,length(F_LFP));
                        else
                            LFP_segmented{1,ff}=LFP_segmented{1,ff}-nanmean(LFP_segmented{1,ff});
                            [LFP_PS_per_bs{1,ff},F_LFP]=periodogram(LFP_segmented{1,ff},hamming(length(LFP_segmented{1,ff})),2^(nextpow2(length(LFP_segmented{1,ff}))),LFP_KHz*1000); % PSD is returned in units: V^2/Hz.
%                             LFP_PS_per_bs{1,ff}=LFP_PS_per_bs{1,ff}/sum(LFP_PS_per_bs{1,ff}); % normalize the power spectra
                        end
                    end
                    % calculate PS EEG
                    % remarked: 062016 EEG start/end
%                     EEG_PS_per_bs=cell(3,length(EEG_1_segmented));
%                     for ff=1:length(EEG_1_segmented)
%                         if sum(isnan(EEG_1_segmented{1,ff}))>=0.5*length(EEG_1_segmented{1,ff})
%                             EEG_PS_per_bs{1,ff}=NaN(1,length(F_EEG));
%                             EEG_PS_per_bs{2,ff}=NaN(1,length(F_EEG));
%                             EEG_PS_per_bs{3,ff}=NaN(1,length(F_EEG));
%                         else
%                             EEG_1_segmented{1,ff}=EEG_1_segmented{1,ff}-nanmean(EEG_1_segmented{1,ff});
%                             [EEG_PS_per_bs{1,ff},F_EEG]=periodogram(EEG_1_segmented{1,ff},hamming(length(EEG_1_segmented{1,ff})),2^(nextpow2(length(EEG_1_segmented{1,ff}))),EEG_KHz*1000); % PSD is returned in units: V^2/Hz.
%                             EEG_2_segmented{1,ff}=EEG_2_segmented{1,ff}-nanmean(EEG_2_segmented{1,ff});
%                             [EEG_PS_per_bs{2,ff},F_EEG]=periodogram(EEG_2_segmented{1,ff},hamming(length(EEG_2_segmented{1,ff})),2^(nextpow2(length(EEG_2_segmented{1,ff}))),EEG_KHz*1000); % PSD is returned in units: V^2/Hz.                            
%                             EEG_3_segmented{1,ff}=EEG_3_segmented{1,ff}-nanmean(EEG_3_segmented{1,ff});
%                             [EEG_PS_per_bs{3,ff},F_EEG]=periodogram(EEG_3_segmented{1,ff},hamming(length(EEG_3_segmented{1,ff})),2^(nextpow2(length(EEG_3_segmented{1,ff}))),EEG_KHz*1000); % PSD is returned in units: V^2/Hz.                                                        
%                         end
%                     end
                    % remarked: 062016 EEG start/end
                   bs_begin_sample_PS=floor(bs_begin_sample_PS_LFP/LFP_KHz*Info{1,unitnum}.SAMPLING); % this is to do the division to stages in the "conventional" way, using the 44 SR                                       
                   LFP_PS_on_stages=nan(6,length(bs_begin_sample_PS),length(LFP_PS_per_bs{1,1}));
                   for ii=1:length(bs_begin_sample_PS)
                       A=find(all_begs<=bs_begin_sample_PS(1,ii),1,'last');
                       closest_bin_end=min(bs_begin_sample_PS(1,ii)+Info{unitnum}.SAMPLING*binsize_vec(2,7)*1000-1,last_stable_sample(stable_period_count));
                       B=find(all_ends>=closest_bin_end,1,'first');
                       marker=NaN;
                       if ((B-A)==0 || ((B-A)==1 && closest_bin_end-all_begs(A+1)<all_begs(A+1)-bs_begin_sample_PS(1,ii)))
                          marker=all_begs(A);
                       elseif ((B-A)==1 && closest_bin_end-all_begs(A+1)>=all_begs(A+1)-bs_begin_sample_PS(1,ii))
                          marker=all_begs(A+1);
                       elseif (B-A)==2 % I added this in 062317 after I figures out that this situation can actually happen, If the epoch is a few samples short of 440000 and the bs happens to start really at the end of the previous one, traverse the entire shorter epoch and then end in the following one.
                          marker=all_begs(A+1);                                                        
                       end
                       if ismember(marker,polysomnography{unitnum}.stages.W.begin_sample)
                          ind=1;
                       elseif ismember(marker,polysomnography{unitnum}.stages.N1.begin_sample)
                          ind=2;
                       elseif ismember(marker,polysomnography{unitnum}.stages.N2.begin_sample)
                          ind=3;
                       elseif ismember(marker,polysomnography{unitnum}.stages.N3.begin_sample)
                          ind=4;
                       elseif ismember(marker,polysomnography{unitnum}.stages.R.begin_sample)
                          ind=5;                
                       elseif ismember(marker,polysomnography{unitnum}.stages.U.begin_sample)
                          ind=6;                
                       end
                       all_nan=squeeze(isnan(LFP_PS_on_stages(ind,:,1))); % 1 only for convenience - to find the next NaN
                       LFP_PS_on_stages(ind,find(all_nan==1,1,'first'),:)=LFP_PS_per_bs{1,ii};
                   end
                   clear A B all_nan ind marker ii
                   % remarked: 062016 EEG start/end
%                    bs_begin_sample_PS=floor(bs_begin_sample_PS_EEG/EEG_KHz*Info{1,unitnum}.SAMPLING);
%                    EEG_PS_on_stages=nan(3,6,length(bs_begin_sample_PS_EEG),length(EEG_PS_per_bs{1,1}));                   
%                    for ii=1:length(bs_begin_sample_PS)
%                        A=find(all_begs<=bs_begin_sample_PS(1,ii),1,'last');
%                        closest_bin_end=min(bs_begin_sample_PS(1,ii)+Info{unitnum}.SAMPLING*binsize_vec(2,7)*1000-1,last_stable_sample(stable_period_count));
%                        B=find(all_ends>=closest_bin_end,1,'first');
%                        marker=NaN;
%                        if ((B-A)==0 || ((B-A)==1 && closest_bin_end-all_begs(A+1)<all_begs(A+1)-bs_begin_sample_PS(1,ii)))
%                           marker=all_begs(A);
%                        elseif ((B-A)==1 && closest_bin_end-all_begs(A+1)>=all_begs(A+1)-bs_begin_sample_PS(1,ii))
%                           marker=all_begs(A+1);
%                        end
%                        if ismember(marker,polysomnography{unitnum}.stages.W.begin_sample)
%                           ind=1;
%                        elseif ismember(marker,polysomnography{unitnum}.stages.N1.begin_sample)
%                           ind=2;
%                        elseif ismember(marker,polysomnography{unitnum}.stages.N2.begin_sample)
%                           ind=3;
%                        elseif ismember(marker,polysomnography{unitnum}.stages.N3.begin_sample)
%                           ind=4;
%                        elseif ismember(marker,polysomnography{unitnum}.stages.R.begin_sample)
%                           ind=5;                
%                        elseif ismember(marker,polysomnography{unitnum}.stages.U.begin_sample)
%                           ind=6;                
%                        end
%                        all_nan=squeeze(isnan(EEG_PS_on_stages(1,ind,:,1))); % 1 in both dims only for convenience - to find the next NaN
%                        EEG_PS_on_stages(1,ind,find(all_nan==1,1,'first'),:)=EEG_PS_per_bs{1,ii};
%                        EEG_PS_on_stages(2,ind,find(all_nan==1,1,'first'),:)=EEG_PS_per_bs{2,ii};
%                        EEG_PS_on_stages(3,ind,find(all_nan==1,1,'first'),:)=EEG_PS_per_bs{3,ii};
%                    end                   
                % remarked: 062016 EEG start/end
                end
                
        %  AUTO-CORRELATION                
                if binsize_vec(1,5)
                    % the "binsize" for auto- and cross-correlation calculation is longer than a few seconds, and typically I think I will use multiples of 30 secs (it is commonly thought thatat least 1000 spikes are
                    % needed for calculating an autocorrelation function=~20 secs in GPe firing rate. Therefore, the problem of bins not matching the polysomnography bins is substantial here - I don't want bins to not
                    % coincide with the actual sleep stages. This is why I will send the function binsize-lengthed vectors starting in the beginning of each new sleep-staging segment. The actual vectors are sent in 
                    % (binsize-1)-segment length overlap, i.e. if the user chose the binsize to be 3 segments-long, and if the relevant stable period has segments number 34-35-36-37-38, then the following periods-to-analyze 
                    % will be sent to the Autocorrelation function: 34-36,35-37,36-38. Typically I think the binsize will be 2 segment length and the overlap will be 1. Notice that in this code I "discard" the samples
                    % between the beginning of the recording and the start of the nearest segment. This is not so bad, taking into account that a segment less than ~1000 spikes or ~20 secs is not "valid" for autocorrelation calculation.
                    beginners={polysomnography{1,unitnum}.stages.W.begin_sample;polysomnography{1,unitnum}.stages.N1.begin_sample;polysomnography{1,unitnum}.stages.N2.begin_sample;polysomnography{1,unitnum}.stages.N3.begin_sample;polysomnography{1,unitnum}.stages.R.begin_sample;polysomnography{1,unitnum}.stages.U.begin_sample};
                    enders={polysomnography{1,unitnum}.stages.W.end_sample;polysomnography{1,unitnum}.stages.N1.end_sample;polysomnography{1,unitnum}.stages.N2.end_sample;polysomnography{1,unitnum}.stages.N3.end_sample;polysomnography{1,unitnum}.stages.R.end_sample;polysomnography{1,unitnum}.stages.U.end_sample};
                    All_AutoCorr{1,stable_period_count}.W.y_axis=[];
                    All_AutoCorr{1,stable_period_count}.N1.y_axis=[];
                    All_AutoCorr{1,stable_period_count}.N2.y_axis=[];
                    All_AutoCorr{1,stable_period_count}.N3.y_axis=[];
                    All_AutoCorr{1,stable_period_count}.R.y_axis=[];
                    All_AutoCorr{1,stable_period_count}.U.y_axis=[];
                    all_segments_begs=polysomnography{1,unitnum}.all_beginnings;
                    all_segments_ends=polysomnography{1,unitnum}.all_ends;
                    overlap_between_bins=binsize_vec(2,5)-1; % THIS means every next analyzed period begins 1 segment-length after the previous one
                    rel_segments=find(((all_segments_begs>=first_stable_sample(1,stable_period_count)).*(all_segments_ends<=last_stable_sample(1,stable_period_count)))==1);
                    A=cell(0,1);
                    for segment=1:overlap_between_bins:length(rel_segments) % sets the overlap between analyzed periods
                        start=all_segments_begs(rel_segments(segment));
                        if length(rel_segments)>=segment+binsize_vec(2,5)-1
                            stop=all_segments_ends(rel_segments(segment)+binsize_vec(2,5)-1);
                        else
                            stop=all_segments_ends(rel_segments(end));
                        end
                        relevant_stage=0; % this next segment is to find the stage to which the segment belongs and make sure the entire segment is within it.
                        for stage_finder=1:5
                            if ~isempty(find(beginners{stage_finder,1}<=start,1,'last')) && ~isempty(find(enders{stage_finder,1}>=stop,1,'first')) && (find(beginners{stage_finder,1}<=start,1,'last')==find(enders{stage_finder,1}>=stop,1,'first'))
                                 relevant_stage=stage_finder;
                            end
                        end
                        if relevant_stage~=0
                            stable_digital_for_auto=stable_digital(stable_digital>=start & stable_digital<=stop);
                            A=struct('Spikes',stable_digital_for_auto,'StableStartTime',start,'StableStopTime',stop);
                            [autocorrelogram_x, autocorrelogram_y]=AutoCorr_Aviv(A,Info{1,unitnum},length(A));
                            clear A
                            switch relevant_stage
                                case 1 
                                    All_AutoCorr{1,stable_period_count}.W.y_axis=[All_AutoCorr{1,stable_period_count}.W.y_axis;autocorrelogram_y];
                                case 2
                                    All_AutoCorr{1,stable_period_count}.N1.y_axis=[All_AutoCorr{1,stable_period_count}.N1.y_axis;autocorrelogram_y];
                                case 3
                                    All_AutoCorr{1,stable_period_count}.N2.y_axis=[All_AutoCorr{1,stable_period_count}.N2.y_axis;autocorrelogram_y];                                        
                                case 4
                                   All_AutoCorr{1,stable_period_count}.N3.y_axis=[All_AutoCorr{1,stable_period_count}.N3.y_axis;autocorrelogram_y];
                                case 5
                                    All_AutoCorr{1,stable_period_count}.R.y_axis=[All_AutoCorr{1,stable_period_count}.R.y_axis;autocorrelogram_y];
                                case 6
                                    All_AutoCorr{1,stable_period_count}.U.y_axis=[All_AutoCorr{1,stable_period_count}.U.y_axis;autocorrelogram_y];                                        
                            end
                         end
                    end
                    All_AutoCorr{1,stable_period_count}.x_axis=autocorrelogram_x;
                end
                clear beginners enders overlap_between_bins rel_segments relevant_stage segment stable_digital stable_digital_for_auto stage_finder start stop A all_segments_begs all_segments_ends

            if stable_period_count==1
                All_unit_bs_begin_sample_FR=[]; All_unit_bs_begin_sample_CV=[]; All_unit_bs_begin_sample_pause=[]; All_unit_bs_begin_sample_burst=[]; All_unit_bs_begin_sample_PS=[]; All_unit_bs_begin_sample_PS_MU=[]; All_unit_bs_begin_sample_LFP_RMS=[]; All_unit_bs_begin_sample_PS_LFP=[]; All_unit_bs_begin_sample_PS_EEG=[];
                    if overlap_smoothing_settings(1,1)~=0
                        All_unit_bs_begin_sample_FR_before_smoothing=[]; All_unit_bs_begin_sample_CV_before_smoothing=[]; All_unit_bs_begin_sample_pause_before_smoothing=[]; All_unit_bs_begin_sample_burst_before_smoothing=[]; All_unit_bs_begin_sample_PS_before_smoothing=[]; All_unit_bs_begin_sample_PS_before_smoothing_MU=[];
                    end
                All_unit_FR_per_bs=[]; All_unit_CV_per_bs=[]; All_unit_pause_per_bs_dur=[]; All_unit_pause_per_bs_freq=[]; All_unit_pause_per_bs_prob=[]; All_unit_burst_per_bs_freq=[]; All_unit_burst_per_bs_prob=[]; All_unit_burst_per_bs_dur=[]; All_unit_burst_per_bs_size=[]; All_unit_burst_per_bs_percent=[]; All_unit_burst_per_bs_cv=[]; All_unit_PS_per_bs=[]; All_unit_instantaneous_freq_per_bs=[]; All_unit_MU_instantaneous_freq_per_bs=[]; All_unit_PS_per_bs_MU=[]; All_unit_LFP_RMS_per_bs=[];
                All_unit_FR_on_stages=[]; All_unit_CV_on_stages=[]; All_unit_ITI_on_stages=[]; All_unit_pause_on_stages=[]; All_unit_burst_on_stages=[]; All_unit_PS_on_stages=[]; All_unit_instantaneous_freq_on_stages=[]; All_unit_PS_on_stages_MU=[]; All_unit_LFP_RMS_on_stages=[]; All_unit_LFP_PS_on_stages=[]; All_unit_EEG_PS_on_stages=[]; All_unit_MU_instantaneous_freq_on_stages=[];
                num_of_bs_for_each_stable_period_FR=[]; num_of_bs_for_each_stable_period_CV=[]; num_of_bs_for_each_stable_period_pause=[]; num_of_bs_for_each_stable_period_burst=[]; num_of_bs_for_each_stable_period_PS=[]; num_of_bs_for_each_stable_period_PS_MU=[];
                All_unit_phase_per_spike=[];
%                 All_unit_spikes_per_phase=zeros(2000,5); % changed to allow wider range. 043017
                All_unit_spikes_per_phase=zeros(1000,5); % changed to allow better coverage of circle as exaplained before. 041917
%                 All_unit_spikes_per_phase=zeros(628,5);
            end
            
            %unite data from all stable periods of the same unit                
            All_unit_bs_begin_sample_FR=cat(2,All_unit_bs_begin_sample_FR,bs_begin_sample_FR); 
            All_unit_bs_begin_sample_CV=cat(2,All_unit_bs_begin_sample_CV,bs_begin_sample_CV); 
            if ~No_pause_analysis && pauser && ~burster
                All_unit_bs_begin_sample_pause=cat(2,All_unit_bs_begin_sample_pause,bs_begin_sample_pause);
            end
            if burster && ~pauser
                All_unit_bs_begin_sample_burst=cat(2,All_unit_bs_begin_sample_burst,bs_begin_sample_burst);
            end            
            if binsize_vec(1,6)
                All_unit_bs_begin_sample_PS=cat(2,All_unit_bs_begin_sample_PS,bs_begin_sample_PS);
                Frequency_axis_for_spectrogram=F;
                if Calculate_MU_Spectrum
                    All_unit_bs_begin_sample_PS_MU=cat(2,All_unit_bs_begin_sample_PS_MU,bs_begin_sample_PS_MU);
                    Frequency_axis_for_spectrogram_MU=F_MU;
                end
            end
            if binsize_vec(1,7)
                All_unit_bs_begin_sample_LFP_RMS=cat(2,All_unit_bs_begin_sample_LFP_RMS,bs_begin_sample_LFP_RMS);                
                All_unit_bs_begin_sample_PS_LFP=cat(2,All_unit_bs_begin_sample_PS_LFP,bs_begin_sample_PS_LFP);
                Frequency_axis_for_spectrogram_LFP=F_LFP;
                % remarked: 062016 EEG start/end
%                 All_unit_bs_begin_sample_PS_EEG=cat(2,All_unit_bs_begin_sample_PS_EEG,bs_begin_sample_PS_EEG);
%                 Frequency_axis_for_spectrogram_EEG=F_EEG;                                
                % remarked: 062016 EEG start/end
            end
            if binsize_vec(1,9) 
                if Analyze_spike_to_EEG_SW_phase_locking
                    All_unit_phase_per_spike=[All_unit_phase_per_spike;phase_per_spike];
                    clear phase_per_spike
                    All_unit_spikes_per_phase=[All_unit_spikes_per_phase+spikes_per_phase]; 
                    if stable_period_count==length(first_stable_sample)
                        for traces=1:size(fruitful_segments,2)
                            if fruitful_segments(1,traces)~=0
                               All_unit_spikes_per_phase(:,traces)=All_unit_spikes_per_phase(:,traces)/(bin_width)*1000/fruitful_segments(1,traces); % to move to sp/s
                            end
                        end
                    end
                end
                if Local_LFP && LFP_to_unit_analysis && exist('All_unit_LFP_spectrum_N3','var') && exist('FREQAXIS_LFP','var') 
                   N3_LFP_spike_per_phase=spikes_per_phase_LFP/normalizer;
                   data2plot.LFP_N3_analysis{1,unitnum}=struct('N3_LFP_spike_per_phase',N3_LFP_spike_per_phase,'All_unit_LFP_spectrum_N2',All_unit_LFP_spectrum_N2,'All_unit_LFP_IF_N2',All_unit_LFP_IF_N2,'All_unit_LFP_EEG_corr_N2',All_unit_LFP_EEG_corr_N2,'All_unit_LFP_spectrum_N3',All_unit_LFP_spectrum_N3,'All_unit_LFP_IF_N3',All_unit_LFP_IF_N3,'All_unit_LFP_EEG_corr_N3',All_unit_LFP_EEG_corr_N3,'All_unit_LFP_spectrum_R',All_unit_LFP_spectrum_R,'All_unit_LFP_IF_R',All_unit_LFP_IF_R,'All_unit_LFP_EEG_corr_R',All_unit_LFP_EEG_corr_R,'All_unit_LFP_spectrum_W',All_unit_LFP_spectrum_W,'All_unit_LFP_IF_W',All_unit_LFP_IF_W,'All_unit_LFP_EEG_corr_W',All_unit_LFP_EEG_corr_W,'F_LFP',FREQAXIS_LFP); %070817
                end
                data2plot.EEG_mean_frequency{1,unitnum}=DAY_INST_FREQS;
                if Local_LFP && ~Calculate_MU_Spectrum
                    data2plot.LFP_mean_frequency{1,unitnum}=DAY_INST_FREQS_LFP;
                end
            end
            
            if overlap_smoothing_settings(1,1)~=0 % not checked 050516
                All_unit_bs_begin_sample_FR_before_smoothing=cat(2,All_unit_bs_begin_sample_FR_before_smoothing,bs_begin_before_smoothing_FR); 
                All_unit_bs_begin_sample_CV_before_smoothing=cat(2,All_unit_bs_begin_sample_CV_before_smoothing,bs_begin_before_smoothing_CV); 
                if ~No_pause_analysis && pauser && ~burster
                    All_unit_bs_begin_sample_pause_before_smoothing=cat(2,All_unit_bs_begin_sample_pause_before_smoothing,bs_begin_before_smoothing_pause);            
                end
                if ~pauser && burster
                    All_unit_bs_begin_sample_burst_before_smoothing=cat(2,All_unit_bs_begin_sample_burst_before_smoothing,bs_begin_before_smoothing_burst);
                end                
                if binsize_vec(1,6)            
                    All_unit_bs_begin_sample_PS_before_smoothing=cat(2,All_unit_bs_begin_sample_PS_before_smoothing,bs_begin_before_smoothing_PS); 
                    if Calculate_MU_Spectrum
                        All_unit_bs_begin_sample_PS_before_smoothing_MU=cat(2,All_unit_bs_begin_sample_PS_before_smoothing_MU,bs_begin_before_smoothing_PS_MU); 
                    end
                end
            end
            
            num_of_bs_for_each_stable_period_FR=[num_of_bs_for_each_stable_period_FR,length(bs_begin_sample_FR)];
            num_of_bs_for_each_stable_period_CV=[num_of_bs_for_each_stable_period_CV,length(bs_begin_sample_CV)];
            if ~No_pause_analysis && pauser && ~burster
                num_of_bs_for_each_stable_period_pause=[num_of_bs_for_each_stable_period_pause,length(bs_begin_sample_pause)];
            end
            if ~pauser && burster
                num_of_bs_for_each_stable_period_burst=[num_of_bs_for_each_stable_period_burst,length(bs_begin_sample_burst)];
            end            
            if binsize_vec(1,6)
                num_of_bs_for_each_stable_period_PS=[num_of_bs_for_each_stable_period_PS,length(bs_begin_sample_PS)];
                if Calculate_MU_Spectrum
                    num_of_bs_for_each_stable_period_PS_MU=[num_of_bs_for_each_stable_period_PS_MU,length(bs_begin_sample_PS_MU)];
                end
            end
            
            All_unit_FR_per_bs=cat(2,All_unit_FR_per_bs,FR_per_bs);
            All_unit_CV_per_bs=cat(2,All_unit_CV_per_bs,CV_per_bs);
            if ~No_pause_analysis && pauser && ~burster
                All_unit_pause_per_bs_dur=cat(2,All_unit_pause_per_bs_dur,pause_dur_per_bs);
                All_unit_pause_per_bs_freq=cat(2,All_unit_pause_per_bs_freq,pause_freq_per_bs);
                All_unit_pause_per_bs_prob=cat(2,All_unit_pause_per_bs_prob,pause_prob_per_bs);
            end
            if ~pauser && burster
                All_unit_burst_per_bs_prob=cat(2,All_unit_burst_per_bs_prob,burst_probability_per_bs);
                All_unit_burst_per_bs_dur=cat(2,All_unit_burst_per_bs_dur,burst_mean_duration_per_bs);
                All_unit_burst_per_bs_freq=cat(2,All_unit_burst_per_bs_freq,burst_frequency_per_bs);
                All_unit_burst_per_bs_size=cat(2,All_unit_burst_per_bs_size,burst_size_per_bs);
                All_unit_burst_per_bs_percent=cat(2,All_unit_burst_per_bs_percent,percent_spikes_in_bursts_per_bs);
                All_unit_burst_per_bs_cv=cat(2,All_unit_burst_per_bs_cv,burst_CV_per_bs);
            end  
            if binsize_vec(1,6)
                All_unit_PS_per_bs=cat(2,All_unit_PS_per_bs,PS_per_bs);
                All_unit_instantaneous_freq_per_bs=cat(2,All_unit_instantaneous_freq_per_bs,instantaneous_freq_per_bs);
                if Calculate_MU_Spectrum
                    All_unit_PS_per_bs_MU=cat(2,All_unit_PS_per_bs_MU,PS_per_bs_MU);
                    All_unit_MU_instantaneous_freq_per_bs=cat(2,All_unit_MU_instantaneous_freq_per_bs,MU_instantaneous_freq_per_bs);
                end
            end
            if binsize_vec(1,7)
                All_unit_LFP_RMS_per_bs=cat(2,All_unit_LFP_RMS_per_bs,LFP_RMS_per_bs);            
            end            
            
            All_unit_FR_on_stages=cat(2,All_unit_FR_on_stages,FR_on_stages); 
            All_unit_CV_on_stages=cat(2,All_unit_CV_on_stages,CV_on_stages);
            All_unit_ITI_on_stages=cat(2,All_unit_ITI_on_stages,ITI_on_stages);
            if ~No_pause_analysis && pauser && ~burster
                All_unit_pause_on_stages=cat(3,All_unit_pause_on_stages,pause_on_stages);
            end
            if ~pauser && burster
                All_unit_burst_on_stages=cat(3,All_unit_burst_on_stages,burst_on_stages);
                clear burst_on_stages
            end            
            if binsize_vec(1,6)
                All_unit_PS_on_stages=cat(2,All_unit_PS_on_stages,PS_on_stages);
                All_unit_instantaneous_freq_on_stages=cat(2,All_unit_instantaneous_freq_on_stages,instantaneous_frequency_on_stages);
                if Calculate_MU_Spectrum
                    All_unit_PS_on_stages_MU=cat(2,All_unit_PS_on_stages_MU,PS_on_stages_MU); 
                    All_unit_MU_instantaneous_freq_on_stages=cat(2,All_unit_MU_instantaneous_freq_on_stages,MU_instantaneous_frequency_on_stages);
                end
            end
            if binsize_vec(1,7)
                All_unit_LFP_RMS_on_stages=cat(2,All_unit_LFP_RMS_on_stages,LFP_RMS_on_stages);
                All_unit_LFP_PS_on_stages=cat(2,All_unit_LFP_PS_on_stages,LFP_PS_on_stages); 
                % remarked: 062016 EEG start/end
%                 All_unit_EEG_PS_on_stages=cat(3,All_unit_EEG_PS_on_stages,EEG_PS_on_stages);                 
                % remarked: 062016 EEG start/end
            end
            end
            % eliminate all NaNs
            if overlap_smoothing_settings(1,1)~=0
                data2plot.FR{1,unitnum}=struct('binsize_begin_sample',All_unit_bs_begin_sample_FR,'data_per_bs',All_unit_FR_per_bs,'data_on_stages',All_unit_FR_on_stages,'stable_period_lengths_in_bs',num_of_bs_for_each_stable_period_FR,'bs_before_smoothing',All_unit_bs_begin_sample_FR_before_smoothing);
                data2plot.CV{1,unitnum}=struct('binsize_begin_sample',All_unit_bs_begin_sample_CV,'data_per_bs',All_unit_CV_per_bs,'data_on_stages',All_unit_CV_on_stages,'ITI_on_stages',All_unit_ITI_on_stages,'bin_centers_for_ITI',bin_centers,'stable_period_lengths_in_bs',num_of_bs_for_each_stable_period_CV,'bs_before_smoothing',All_unit_bs_begin_sample_CV_before_smoothing);
                if ~No_pause_analysis && pauser && ~burster 
                    data2plot.pause{1,unitnum}=struct('binsize_begin_sample',All_unit_bs_begin_sample_pause,'data_per_bs_dur',All_unit_pause_per_bs_dur,'data_per_bs_freq',All_unit_pause_per_bs_freq,'data_per_bs_prob',All_unit_pause_per_bs_prob,'data_on_stages',All_unit_pause_on_stages,'stable_period_lengths_in_bs',num_of_bs_for_each_stable_period_pause,'bs_before_smoothing',All_unit_bs_begin_sample_pause_before_smoothing);
                end
                if ~pauser && burster 
                    data2plot.burst{1,unitnum}=struct('binsize_begin_sample',All_unit_bs_begin_sample_burst,'data_per_bs_burst',All_unit_burst_per_bs_prob,'data_per_bs_burst_dur',All_unit_burst_per_bs_dur,'data_per_bs_freq',All_unit_burst_per_bs_freq,'data_per_bs_size',All_unit_burst_per_bs_size,'data_per_bs_percent',All_unit_burst_per_bs_percent,'data_per_bs_cv',All_unit_burst_per_bs_cv,'data_per_bs_burst_dur',All_unit_burst_per_bs_dur,'data_on_stages',All_unit_burst_on_stages,'stable_period_lengths_in_bs',num_of_bs_for_each_stable_period_burst,'bs_before_smoothing',All_unit_bs_begin_sample_burst_before_smoothing);
                end                
                if binsize_vec(1,5)
                    data2plot.AutoCorrelation{1,unitnum}=All_AutoCorr;
                end
                if binsize_vec(1,6)                  
                    data2plot.PS{1,unitnum}=struct('binsize_begin_sample',All_unit_bs_begin_sample_PS,'data_per_bs',All_unit_PS_per_bs,'instantaneous_frequency_per_bs',All_unit_instantaneous_freq_per_bs,'instantaneous_MU_frequency_per_bs',All_unit_MU_instantaneous_freq_per_bs,'data_on_stages',All_unit_PS_on_stages,'instantaneous_freq_on_stages',All_unit_instantaneous_freq_on_stages,'stable_period_lengths_in_bs',num_of_bs_for_each_stable_period_PS,'bs_before_smoothing',All_unit_bs_begin_sample_PS_before_smoothing,'freqaxis',Frequency_axis_for_spectrogram);
                    if Calculate_MU_Spectrum
                        data2plot.PS{1,unitnum}=struct('binsize_begin_sample',All_unit_bs_begin_sample_PS,'data_per_bs',All_unit_PS_per_bs,'instantaneous_frequency_per_bs',All_unit_instantaneous_freq_per_bs,'data_on_stages',All_unit_PS_on_stages,'instantaneous_freq_on_stages',All_unit_instantaneous_freq_on_stages,'instantaneous_MU_freq_on_stages',All_unit_MU_instantaneous_freq_on_stages,'stable_period_lengths_in_bs',num_of_bs_for_each_stable_period_PS,'bs_before_smoothing',All_unit_bs_begin_sample_PS_before_smoothing,'freqaxis',Frequency_axis_for_spectrogram,'binsize_begin_sample_MU',All_unit_bs_begin_sample_PS_MU,'data_per_bs_MU',All_unit_PS_per_bs_MU,'data_on_stages_MU',All_unit_PS_on_stages_MU,'stable_period_lengths_in_bs_MU',num_of_bs_for_each_stable_period_PS_MU,'bs_before_smoothing_MU',All_unit_bs_begin_sample_PS_before_smoothing_MU,'freqaxis_MU',Frequency_axis_for_spectrogram_MU);
                    end
                end
                if binsize_vec(1,7)
                    data2plot.LFP_PS{1,unitnum}=struct('binsize_begin_sample',All_unit_bs_begin_sample_PS_LFP,'data_on_stages',All_unit_LFP_PS_on_stages,'freqaxis',Frequency_axis_for_spectrogram_LFP);
                    % remarked: 062016 EEG start/end
%                     data2plot.EEG_PS{1,unitnum}=struct('binsize_begin_sample',All_unit_bs_begin_sample_PS_EEG,'data_on_stages',All_unit_EEG_PS_on_stages,'freqaxis',Frequency_axis_for_spectrogram_EEG);
                    % remarked: 062016 EEG start/end
                    data2plot.LFP_RMS{1,unitnum}=struct('binsize_begin_sample',All_unit_bs_begin_sample_LFP_RMS,'data_per_bs',All_unit_LFP_RMS_per_bs,'data_on_stages',All_unit_LFP_RMS_on_stages);
                end            
                if binsize_vec(1,9)
                    data2plot.EEG_phase_Analysis{1,unitnum}=struct('phase_per_spike',All_unit_phase_per_spike,'spikes_per_phase',All_unit_spikes_per_phase,'SWS_stats',SWS_stats{1,unitnum});
%                     data2plot.EEG_phase_Analysis{1,unitnum}=struct('phase_per_bin',phase_per_bin);
                end
            else
                data2plot.FR{1,unitnum}=struct('binsize_begin_sample',All_unit_bs_begin_sample_FR,'data_per_bs',All_unit_FR_per_bs,'data_on_stages',All_unit_FR_on_stages,'stable_period_lengths_in_bs',num_of_bs_for_each_stable_period_FR);
                data2plot.CV{1,unitnum}=struct('binsize_begin_sample',All_unit_bs_begin_sample_CV,'data_per_bs',All_unit_CV_per_bs,'data_on_stages',All_unit_CV_on_stages,'ITI_on_stages',All_unit_ITI_on_stages,'bin_centers_for_ITI',bin_centers,'stable_period_lengths_in_bs',num_of_bs_for_each_stable_period_CV);
                if ~No_pause_analysis && pauser && ~burster
                    data2plot.pause{1,unitnum}=struct('binsize_begin_sample',All_unit_bs_begin_sample_pause,'data_per_bs_dur',All_unit_pause_per_bs_dur,'data_per_bs_freq',All_unit_pause_per_bs_freq,'data_per_bs_prob',All_unit_pause_per_bs_prob,'data_on_stages',All_unit_pause_on_stages,'stable_period_lengths_in_bs',num_of_bs_for_each_stable_period_pause);
                end
                if ~pauser && burster
                    data2plot.burst{1,unitnum}=struct('binsize_begin_sample',All_unit_bs_begin_sample_burst,'data_per_bs_prob',All_unit_burst_per_bs_prob,'data_per_bs_prob_dur',All_unit_burst_per_bs_dur,'data_per_bs_freq',All_unit_burst_per_bs_freq,'data_per_bs_size',All_unit_burst_per_bs_size,'data_per_bs_percent',All_unit_burst_per_bs_percent,'data_per_bs_cv',All_unit_burst_per_bs_cv,'data_on_stages',All_unit_burst_on_stages,'stable_period_lengths_in_bs',num_of_bs_for_each_stable_period_burst);
                end                
                if binsize_vec(1,5)
                    data2plot.AutoCorrelation{1,unitnum}=All_AutoCorr;
                end
                if binsize_vec(1,6)  
                    data2plot.PS{1,unitnum}=struct('binsize_begin_sample',All_unit_bs_begin_sample_PS,'data_per_bs',All_unit_PS_per_bs,'data_on_stages',All_unit_PS_on_stages,'instantaneous_freq_on_stages',All_unit_instantaneous_freq_on_stages,'stable_period_lengths_in_bs',num_of_bs_for_each_stable_period_PS,'freqaxis',Frequency_axis_for_spectrogram);
                    if Calculate_MU_Spectrum
                        data2plot.PS{1,unitnum}=struct('binsize_begin_sample',All_unit_bs_begin_sample_PS,'data_per_bs',All_unit_PS_per_bs,'data_on_stages',All_unit_PS_on_stages,'instantaneous_freq_on_stages',All_unit_instantaneous_freq_on_stages,'instantaneous_MU_freq_on_stages',All_unit_MU_instantaneous_freq_on_stages,'stable_period_lengths_in_bs',num_of_bs_for_each_stable_period_PS,'freqaxis',Frequency_axis_for_spectrogram,'binsize_begin_sample_MU',All_unit_bs_begin_sample_PS_MU,'data_per_bs_MU',All_unit_PS_per_bs_MU,'data_on_stages_MU',All_unit_PS_on_stages_MU,'stable_period_lengths_in_bs_MU',num_of_bs_for_each_stable_period_PS_MU,'freqaxis_MU',Frequency_axis_for_spectrogram_MU);
                    end
                end
                if binsize_vec(1,7)
                    data2plot.LFP_PS{1,unitnum}=struct('binsize_begin_sample',All_unit_bs_begin_sample_PS_LFP,'data_on_stages',All_unit_LFP_PS_on_stages,'freqaxis',Frequency_axis_for_spectrogram_LFP);
                    % remarked: 062016 EEG start/end
%                     data2plot.EEG_PS{1,unitnum}=struct('binsize_begin_sample',All_unit_bs_begin_sample_PS_EEG,'data_on_stages',All_unit_EEG_PS_on_stages,'freqaxis',Frequency_axis_for_spectrogram_EEG);
                    % remarked: 062016 EEG start/end
                    data2plot.LFP_RMS{1,unitnum}=struct('binsize_begin_sample',All_unit_bs_begin_sample_LFP_RMS,'data_per_bs',All_unit_LFP_RMS_per_bs,'data_on_stages',All_unit_LFP_RMS_on_stages);
                end            
                if binsize_vec(1,9)
                    data2plot.EEG_phase_Analysis{1,unitnum}=struct('phase_per_spike',All_unit_phase_per_spike,'spikes_per_phase',All_unit_spikes_per_phase,'SWS_stats',SWS_stats{1,unitnum});
%                     data2plot.EEG_phase_Analysis{1,unitnum}=struct('phase_per_bin',phase_per_bin);
                end
            end
        % save some space by elliminating all unit_data 
        Datafiles{1,unitnum}=[];
        Info{1,unitnum}=[];
        filenames{1,unitnum}=[];
        polysomnography{1,unitnum}=[];
        unit{1,unitnum}=[];
        firing_rate_amp_thresh_for_SW_definition(1,unitnum)=firing_rate_amp_thresh_for_SW_definition(1,unitnum)/length(first_stable_sample);
        clear All_AutoCorr stable_period_count CV_on_stages CV_per_bs F F_LFP F_EEG FR_on_stages FR_per_bs Frequency_axis_for_spectrogram Frequency_axis_for_spectrogram_LFP Frequency_axis_for_spectrogram_EEG ITI_on_stages LFP_RMS_on_stages LFP_RMS_per_bs PS_on_stages PS_per_bs bin_centers bs_begin_sample_* num_of_bs_* pause_dur_per_bs pause_freq_per_bs pause_prob_per_bs pause_on_stages first_stable_sample last_stable_sample all_begs all_ends pause_start pause_end All_unit_* EEG_* N2_* N1_* NREM_* R_* U_* W_* all_begs_N3_included all_ends_N3_included stable_spikes spike_times stablespikes tempindexedspikes consolidated_SWA
    end
    clear ITI_on_stages All_unit_ITI_on_stages milli_second_begin_sample spikes_per_milli_sec All_unit_PS_on_stages PS_on_stages All_unit_PS_per_bs PS_per_bs spike_times stablespikes tempindexedspikes stable_digital All_unit_instantaneous_freq_on_stages instantaneous_* All_unit_* pause_* CV_on_stages FR_on_stages F bin_centers Frequency_axis_for_spectrogram CV_per_bs FR_per_bs bs_begin_* burst_* percent_spikes_in_bursts_per_bs rel_burst_size spec_spike_times burst_* N3_segments_Fr_OR_Cr last_stable_sample first_stable_sample closest_bin_end  last_stable_sample_EEG
        
        %  CROSS-CORRELATION & PAUSE-CORRELATION
        tic
        shift_data=0;
        analyze_N3_SWS_synchronization=1;
        compute_spike_SW_cross_correlation=0;
        compute_pause_correlation=0;
        compare_cortex_LFP_PS=0;
        compute_coherence=0;
        analyze_simultaneous_Cortex_GPe=0;
        analyze_LFP_phase_locking_in_N3=1; % Find the locking between LFP and spikes for all N3 segments
        if binsize_vec(1,10)
            load('C:\Aviv\Sleep\Code\Main\BACKUP_FILES_FOR_CROSS_CORRELATION')
            if use_SWS_N3_data
                for kk=1:length(polysomnography)
                    polysomnography{1,kk}.stages.N3.begin_sample=polysomnography_with_N3{1,kk}.stages.N3.begin_sample; 
                    polysomnography{1,kk}.stages.N3.end_sample=polysomnography_with_N3{1,kk}.stages.N3.end_sample;
                end
            end            
            All_CrossCorr=cell(1,0);
            [filenames_unique,~,indices]=unique(filenames);
             MIN_OVERLAP_TIME=5; %sec.             
             overlap_between_bins=binsize_vec(2,10)-1; % THIS means every next analyzed period begins 1 segment-length after the previous one
             if compare_cortex_LFP_PS
                 depth_EEG_power_spectrum_across_stages=cell(1,5);
             end
             for fil=1:length(filenames_unique)
                 if analyze_simultaneous_Cortex_GPe
    %                  LFP_amp_across_stages_same=cell(1,5);             
    %                  LFP_amp_across_stages_other=cell(1,5);             
    %                  LFP_ins_amp_same=[];
    %                  LFP_ins_amp_other=[];
    %                  EEG_PS_for_LFP_comparison_1=cell(1,0);
    %                  EEG_PS_for_LFP_comparison_2=cell(1,0);
                     All_LFP_GPe_Cortex_comparison{1,fil}.LFP_GPe_unit_PS_for_LFP_comparison=cell(1,0);
                     All_LFP_GPe_Cortex_comparison{1,fil}.LFP_Cortex_unit_PS_for_LFP_comparison=cell(1,0);
                     All_LFP_GPe_Cortex_comparison{1,fil}.LFP_PS_for_LFP_comparison_same=cell(1,0);
                     All_LFP_GPe_Cortex_comparison{1,fil}.LFP_PS_for_LFP_comparison_other=cell(1,0);
                     All_LFP_GPe_Cortex_comparison{1,fil}.LFP_relevant_stage=cell(1,0);
                     % Cortex-Cortex
%                      All_LFP_Cortex_Cortex_comparison{1,fil}.LFP_unit_PS_for_LFP_comparison=cell(1,0);
%                      All_LFP_Cortex_Cortex_comparison{1,fil}.LFP_PS_for_LFP_comparison_same=cell(1,0);
%                      All_LFP_Cortex_Cortex_comparison{1,fil}.LFP_PS_for_LFP_comparison_other=cell(1,0);
%                      All_LFP_Cortex_Cortex_comparison{1,fil}.LFP_relevant_stage=cell(1,0);                     
                 end                 
                 same_file=find(indices==fil);
                 if compute_pause_correlation
                     All_Pauses=cell(2,length(same_file));                 
                     for ii=1:length(same_file)
                        [All_Pauses{1,ii},All_Pauses{2,ii}]=pause_detect(unit{1,same_file(ii)}.Spikes,Info{1}.SAMPLING);
                     end
                 end
                 all_NREM_starts_for_LFP=cell(1,length(SWS_stats));
                 for ll=1:length(SWS_stats)
                     for nn=1:length(SWS_stats{1,ll}.NREM_bins_sample_starts)
                         all_NREM_starts_for_LFP{1,ll}=[all_NREM_starts_for_LFP{1,ll},SWS_stats{1,ll}.NREM_bins_sample_starts{1,nn}];
                     end
                 end
                 if analyze_LFP_phase_locking_in_N3 && use_SWS_N3_data && ~analyze_simultaneous_Cortex_GPe
                     [LFP_library,File_Starts,LFP_SR_for_N3,SW_definition_thresh_LFP,EEG_library_1,EEG_library_2]=create_LFP_library(ElecNum(same_file),Datafiles(same_file),all_stage_corrected(:,same_file),Info(same_file),bandpass_SW,bandstop_SW,percent_thresh_for_SW_definition_LFP,1,0,all_NREM_starts_for_LFP(same_file));
                 elseif analyze_LFP_phase_locking_in_N3 && use_SWS_N3_data && analyze_simultaneous_Cortex_GPe
                     [LFP_library,File_Starts,LFP_SR_for_N3,SW_definition_thresh_LFP,EEG_library_1,EEG_library_2]=create_LFP_library(ElecNum(same_file),Datafiles(same_file),all_stage_corrected(:,same_file),Info(same_file),bandpass_SW,bandstop_SW,percent_thresh_for_SW_definition_LFP,0,1,all_NREM_starts_for_LFP(same_file));                     
                 end
                 if analyze_simultaneous_Cortex_GPe
                     last_ii_CG=0; last_jj_CG=0;
%                      last_ii_CC=0; last_jj_CC=0;
                 end
                 analyzed_units=nan(0,2); % to make sure the same pair is not analyzed twice
                 for ii=same_file(1):same_file(end)
                     if ii==same_file(1)
                         N3_SWA_synchronization{1,fil}.Synchrony_SWS_strength_phase=cell(1,length(polysomnography{1,ii}.all_beginnings));
                         N3_SWA_synchronization{1,fil}.Synchrony_SWS_strength_correlation=cell(1,length(polysomnography{1,ii}.all_beginnings));
                     end
                     all_segments_begs=polysomnography{1,ii}.all_beginnings; % general, not specific. true for all units.
                     all_segments_ends=polysomnography{1,ii}.all_ends;                     
                     beginners={polysomnography{1,ii}.stages.W.begin_sample;polysomnography{1,ii}.stages.N1.begin_sample;polysomnography{1,ii}.stages.N2.begin_sample;polysomnography{1,ii}.stages.N3.begin_sample;polysomnography{1,ii}.stages.R.begin_sample;polysomnography{1,ii}.stages.U.begin_sample};
                     enders={polysomnography{1,ii}.stages.W.end_sample;polysomnography{1,ii}.stages.N1.end_sample;polysomnography{1,ii}.stages.N2.end_sample;polysomnography{1,ii}.stages.N3.end_sample;polysomnography{1,ii}.stages.R.end_sample;polysomnography{1,ii}.stages.U.end_sample};                          
                     for jj=[same_file(1):ii-1,ii+1:same_file(end)]
                         if isempty(intersect(find(analyzed_units(:,2)==ii),find(analyzed_units(:,1)==jj))) % to make sure the same pair is not analyzed again
                             All_CrossCorr{1,fil}.first_unit{1,ii}.second_unit{1,jj}.W.y_axis=[];
                             All_CrossCorr{1,fil}.first_unit{1,ii}.second_unit{1,jj}.N1.y_axis=[];
                             All_CrossCorr{1,fil}.first_unit{1,ii}.second_unit{1,jj}.N2.y_axis=[];
                             All_CrossCorr{1,fil}.first_unit{1,ii}.second_unit{1,jj}.N3.y_axis=[];
                             All_CrossCorr{1,fil}.first_unit{1,ii}.second_unit{1,jj}.R.y_axis=[];
                             All_CrossCorr{1,fil}.first_unit{1,ii}.second_unit{1,jj}.U.y_axis=[];
                             if compute_pause_correlation
                                 All_PauseCorr{1,fil}.first_unit{1,ii}.second_unit{1,jj}.W.y_axis=[];
                                 All_PauseCorr{1,fil}.first_unit{1,ii}.second_unit{1,jj}.N1.y_axis=[];
                                 All_PauseCorr{1,fil}.first_unit{1,ii}.second_unit{1,jj}.N2.y_axis=[];
                                 All_PauseCorr{1,fil}.first_unit{1,ii}.second_unit{1,jj}.N3.y_axis=[];
                                 All_PauseCorr{1,fil}.first_unit{1,ii}.second_unit{1,jj}.R.y_axis=[];
                                 All_PauseCorr{1,fil}.first_unit{1,ii}.second_unit{1,jj}.U.y_axis=[];
                             end
                             if compute_coherence
                                 All_Coherence{1,fil}.first_unit{1,ii}.second_unit{1,jj}.W.y_axis=[];
                                 All_Coherence{1,fil}.first_unit{1,ii}.second_unit{1,jj}.N1.y_axis=[];
                                 All_Coherence{1,fil}.first_unit{1,ii}.second_unit{1,jj}.N2.y_axis=[];
                                 All_Coherence{1,fil}.first_unit{1,ii}.second_unit{1,jj}.N3.y_axis=[];
                                 All_Coherence{1,fil}.first_unit{1,ii}.second_unit{1,jj}.R.y_axis=[];
                                 All_Coherence{1,fil}.first_unit{1,ii}.second_unit{1,jj}.U.y_axis=[];
                             end
                             if analyze_N3_SWS_synchronization && use_SWS_N3_data
                                 min_frequency_difference_for_phase_comparison=0.3; % originally 0.3
                                 binsize_for_N3_SWA_Synchronization=5; %ms. was previously 10. changed 041917
                                 Fs_N3_SWA=1000/binsize_for_N3_SWA_Synchronization;
                                 min_phase_std_for_N3_SW=0.2;
                                 min_height_for_peaks_N3_SW=3;
                                 min_num_std_for_peak_detection=1;
                                 min_inst_amplitude_for_peak_point_1=firing_rate_amp_thresh_for_SW_definition(1,ii);
                                 min_inst_amplitude_for_peak_point_2=firing_rate_amp_thresh_for_SW_definition(1,jj);
    %                              min_inst_amplitude_for_peak_point_1=0.75;
    %                              min_inst_amplitude_for_peak_point_2=0.75;
    %                              min_inst_amplitude_for_peak_point=0.75;
                                 N3_SWA_synchronization{1,fil}.first_unit{1,ii}.second_unit{1,jj}.inst_frequency_neuron_1=[]; % the instanstaneous frequency of neuron 1, to be updated every phase 0 of the oscillation, for each segment. Therefore, this is a cell with length equal to the number of segments the neurons were recorded together, where in each element there is a vector of instantaneous frequencies whose length is the number of peaks of the oscillation per that specific segment.
                                 N3_SWA_synchronization{1,fil}.first_unit{1,ii}.second_unit{1,jj}.inst_frequency_neuron_2=[]; % same as above, only for the second neuron.
                                 N3_SWA_synchronization{1,fil}.first_unit{1,ii}.second_unit{1,jj}.inst_phase_neuron_1=[]; % same exact thing like the instantaneous freq, but for phase. The phase is determined relatively to the oscillation of the *other* neuron, i.e. the instantaneous phase of the peak (0 degrees) point relative to the other neuron.
                                 N3_SWA_synchronization{1,fil}.first_unit{1,ii}.second_unit{1,jj}.inst_phase_neuron_2=[]; % same only for neuron 2
                                 N3_SWA_synchronization{1,fil}.first_unit{1,ii}.second_unit{1,jj}.SW_correlation_neuron_1=[]; % Correlation of the area around the peak between the two neurons
                                 N3_SWA_synchronization{1,fil}.first_unit{1,ii}.second_unit{1,jj}.SW_correlation_neuron_2=[]; % same only for neuron 2                             
                                 N3_SWA_synchronization{1,fil}.first_unit{1,ii}.second_unit{1,jj}.LFP_LFP_correlation=[]; % added 070217
                                 N3_SWA_synchronization{1,fil}.first_unit{1,ii}.second_unit{1,jj}.SW_distance_1=[]; % Euclidean distance between the two vectprs corresponding to the area around the peak between the two neurons
                                 N3_SWA_synchronization{1,fil}.first_unit{1,ii}.second_unit{1,jj}.SW_distance_2=[]; % same only for neuron 2                                                          
                                 N3_SWA_synchronization{1,fil}.first_unit{1,ii}.second_unit{1,jj}.inst_freq_differences_1=[]; % the difference between firing frequencies of the two cells                             
                                 N3_SWA_synchronization{1,fil}.first_unit{1,ii}.second_unit{1,jj}.inst_freq_other_cell_1=[]; % Frequency of oscillation of other cell
                                 N3_SWA_synchronization{1,fil}.first_unit{1,ii}.second_unit{1,jj}.inst_freq_differences_2=[]; % the difference between firing frequencies of the two cells                             
                                 N3_SWA_synchronization{1,fil}.first_unit{1,ii}.second_unit{1,jj}.inst_freq_other_cell_2=[]; % Frequency of oscillation of other cell                             
                             end
                             if analyze_LFP_phase_locking_in_N3 && use_SWS_N3_data
                                 N3_Spiking_LFP_Phase{1,fil}.first_unit{1,ii}.second_unit{1,jj}.same_neuron=[];
                                 N3_Spiking_LFP_Phase{1,fil}.first_unit{1,ii}.second_unit{1,jj}.other_neuron=[];
                             end
                             if compute_spike_SW_cross_correlation && use_SWS_N3_data
                                 spike_SW_cross{1,fil}.first_unit{1,ii}.second_unit{1,jj}.neuron_1=[];
                                 spike_SW_cross{1,fil}.first_unit{1,ii}.second_unit{1,jj}.neuron_2=[];
                             end
                             [x,y]=find_intersect({unit{1,ii}.StableStartTime,unit{1,jj}.StableStartTime}, {unit{1,ii}.StableStopTime,unit{1,jj}.StableStopTime});
                             good_stable=find((y-x)>=(MIN_OVERLAP_TIME*1000*Info{1,ii}.SAMPLING));
                             LFP_LFP_corr=[]; %070217
%                              LFP_LFP_coher=[]; %070317
                             for kk=1:length(good_stable)
                                 rel_segments=find(((all_segments_begs>=x(kk)).*(all_segments_ends<=y(kk)))==1);
                                 A=cell(0,1);
                                 if use_SWS_N3_data
                                     spikes_per_phase_same=zeros(length(phase_map),1);
                                     spikes_per_phase_other=zeros(length(phase_map),1);
                                 end
                                 normalizer=0;
                                 num_of_analyzed_segments=0;
                                 relevant_stage_0=0;
                                 relevant_stage_6=0;
                                 too_little_spikes=0;
                                 relevant_stage_not_4=0;
                                 too_little_SW_power=0;
                                 no_peaks=0;
                                 for segment=1:max(overlap_between_bins,1):length(rel_segments) % sets the overlap between analyzed periods
                                     start=all_segments_begs(rel_segments(segment));
                                     if length(rel_segments)>=segment+binsize_vec(2,10)-1
                                        stop=all_segments_ends(rel_segments(segment)+binsize_vec(2,10)-1);
                                     else
                                        stop=all_segments_ends(rel_segments(end));
                                     end                                 
                                     relevant_stage=0; % this next segment is to find the stage to which the segment belongs and make sure the entire segment is within it.
                                     if use_SWS_N3_data==1
                                         for stage_finder=[1,2,4,5,6];  %change
                                             if ~isempty(find(beginners{stage_finder,1}<=start,1,'last')) && ~isempty(find(enders{stage_finder,1}>=stop,1,'first')) && (find(beginners{stage_finder,1}<=start+20,1,'last')==find(enders{stage_finder,1}>=stop-20,1,'first'))
                                                  relevant_stage=stage_finder;
                                             end 
                                         end
                                     else
                                         for stage_finder=1:6
                                             if ~isempty(find(beginners{stage_finder,1}<=start,1,'last')) && ~isempty(find(enders{stage_finder,1}>=stop,1,'first')) && (find(beginners{stage_finder,1}<=start+20,1,'last')==find(enders{stage_finder,1}>=stop-20,1,'first'))
                                                  relevant_stage=stage_finder;
                                             end
                                         end 
                                     end
                                     if relevant_stage~=0                                 
                                         if relevant_stage~=6                                 
                                             if compare_cortex_LFP_PS
                                                 LFP_trace_to_check_1=LFP_library{1,find(same_file==ii)}(ceil((start-File_Starts(1,find(same_file==ii))+1)/Info{1,1}.SAMPLING*LFP_SR_for_N3):ceil((stop-File_Starts(1,find(same_file==ii))+1)/Info{1,1}.SAMPLING*LFP_SR_for_N3)); 
                                                 [pxx_lfp_1,f_lfp_1] = periodogram(LFP_trace_to_check_1,hanning(length(LFP_trace_to_check_1)),2^nextpow2(length(LFP_trace_to_check_1)),1375); 
                                                 pxx_lfp_1=pxx_lfp_1(1:find(f_lfp_1<20,1,'last')); f_lfp_1=f_lfp_1(1:find(f_lfp_1<20,1,'last'));
                                                 depth_EEG_power_spectrum_across_stages{1,relevant_stage}=[depth_EEG_power_spectrum_across_stages{1,relevant_stage},pxx_lfp_1/sum(pxx_lfp_1)];
                                                 LFP_trace_to_check_2=LFP_library{1,find(same_file==jj)}(ceil((start-File_Starts(1,find(same_file==jj))+1)/Info{1,1}.SAMPLING*LFP_SR_for_N3):ceil((stop-File_Starts(1,find(same_file==jj))+1)/Info{1,1}.SAMPLING*LFP_SR_for_N3)); 
                                                 [pxx_lfp_2,f_lfp_2] = periodogram(LFP_trace_to_check_2,hanning(length(LFP_trace_to_check_2)),2^nextpow2(length(LFP_trace_to_check_2)),1375); 
                                                 pxx_lfp_2=pxx_lfp_2(1:find(f_lfp_2<20,1,'last')); f_lfp_2=f_lfp_2(1:find(f_lfp_2<20,1,'last'));
                                                 depth_EEG_power_spectrum_across_stages{1,relevant_stage}=[depth_EEG_power_spectrum_across_stages{1,relevant_stage},pxx_lfp_2/sum(pxx_lfp_2)];
                                             end                                         
                                         % compute spike-2-spike correlation
                                         stable_digital_ii=unit{1,ii}.Spikes; stable_digital_jj=unit{1,jj}.Spikes;
                                         stable_digital_for_auto_ii=stable_digital_ii(stable_digital_ii>=start & stable_digital_ii<=stop);
                                         stable_digital_for_auto_jj=stable_digital_jj(stable_digital_jj>=start & stable_digital_jj<=stop);
                                         clear stable_digital_ii stable_digital_jj
                                         if shift_data % each spike from the regerence unit is shifted uniformly in time, when the shift is taken from a uniform distribution of -LagTime:LagTime. This is done remembering that I don't consider spikes in the reference unit that are LagTime before the end of the segment or LagTime after its beginning. This shifting allows me to keep the average number of spikes in the reference unit the same, because every spike that has been moved away is balanced by a spike (in average) that wasn't meant to be considered and was delayed into the relevent period (i.e. from 0:Lagtime to LagTime+) or brought earlier to it (from Lagtime:end to before Lagtime).
                                             for shifter=1:length(stable_digital_for_auto_ii)
                                                 LagTime=1500*Info{1}.SAMPLING;
                                                 stable_digital_for_auto_ii(shifter)=stable_digital_for_auto_ii(shifter)+round((2*LagTime).*rand(1,1) - LagTime);
                                             end
                                             stable_digital_for_auto_ii=stable_digital_for_auto_ii(stable_digital_for_auto_ii>=start & stable_digital_for_auto_ii<=stop);                                         
                                         end 
                                         A{1,1}=struct('Spikes',stable_digital_for_auto_ii,'StableStartTime',start,'StableStopTime',stop);
                                         A{1,2}=struct('Spikes',stable_digital_for_auto_jj,'StableStartTime',start,'StableStopTime',stop);
                                         if (length(stable_digital_for_auto_ii)>=min_num_of_spikes_per_10_seconds && length(stable_digital_for_auto_jj)>=min_num_of_spikes_per_10_seconds) % inclusion criteria on number of spikes
                                             [crosscorrelogram_x, crosscorrelogram_y]=CrossCorr_Aviv(A,Info{1,unitnum});
                                             clear A
                                             if compute_coherence
                                                 binsize_for_coherence_computation=1; %ms 
                                                 [Coh_F,Coh]=Compute_FR_Coherence(stable_digital_for_auto_ii,stable_digital_for_auto_jj,start,stop,binsize_for_coherence_computation);
                                             end
                                             if analyze_N3_SWS_synchronization && use_SWS_N3_data && relevant_stage==4
                                                 % Compute firing rates for the two simultaneous neurons
                                                while mod((stop-start+1),(binsize_for_N3_SWA_Synchronization*Info{1,unitnum}.SAMPLING))~=0
                                                    stop=stop+1;
                                                end
                                                FR_1_RAW=zeros(1,(stop-start+1)/(binsize_for_N3_SWA_Synchronization*Info{1,unitnum}.SAMPLING));
                                                quetched_spikes=ceil((stable_digital_for_auto_ii-start+1)/(binsize_for_N3_SWA_Synchronization*Info{1,unitnum}.SAMPLING));
                                                for ff=1:length(quetched_spikes)
                                                    FR_1_RAW(1,quetched_spikes(1,ff))=FR_1_RAW(1,quetched_spikes(1,ff))+1;
                                                end
                                                FR_1_RAW=FR_1_RAW*Fs_N3_SWA; % to move to sp/s
                                                FR_2_RAW=zeros(1,(stop-start+1)/(binsize_for_N3_SWA_Synchronization*Info{1,unitnum}.SAMPLING));
                                                quetched_spikes=ceil((stable_digital_for_auto_jj-start+1)/(binsize_for_N3_SWA_Synchronization*Info{1,unitnum}.SAMPLING));
                                                for ff=1:length(quetched_spikes)
                                                    FR_2_RAW(1,quetched_spikes(1,ff))=FR_2_RAW(1,quetched_spikes(1,ff))+1;
                                                end                                        
                                                FR_2_RAW=FR_2_RAW*Fs_N3_SWA; % to move to sp/s

                                                FR_1_RAW=FR_1_RAW-nanmean(FR_1_RAW);
                                                FR_2_RAW=FR_2_RAW-nanmean(FR_2_RAW);
                                                % next few lines - add another constraint on analysis of SW synchronization in Firing Rate: each FR has to have a
                                                % certain amount of slow wave power
                                                [PXX_FR1,F_FR1]=periodogram(FR_1_RAW,hamming(length(FR_1_RAW)),2^(nextpow2(length(FR_1_RAW))),Fs_N3_SWA);
                                                [PXX_FR2,F_FR2]=periodogram(FR_2_RAW,hamming(length(FR_2_RAW)),2^(nextpow2(length(FR_2_RAW))),Fs_N3_SWA);
                                                relevant_freq_40=find(F_FR1<40,1,'last');
                                                PXX_FR1=PXX_FR1(1:relevant_freq_40); PXX_FR1=PXX_FR1/sum(PXX_FR1);
                                                PXX_FR2=PXX_FR2(1:relevant_freq_40); PXX_FR2=PXX_FR2/sum(PXX_FR2);
                                                [~,relevant_freq_upper_SW_boundary]=min(abs(F_FR1-bandpass_SW(1,2)));
                                                [~,relevant_freq_lower_SW_boundary]=min(abs(F_FR1-bandpass_SW(1,1)));
                                                power_SW_range_1=sum(PXX_FR1(relevant_freq_lower_SW_boundary:relevant_freq_upper_SW_boundary));
                                                power_SW_range_2=sum(PXX_FR2(relevant_freq_lower_SW_boundary:relevant_freq_upper_SW_boundary));
                                                if power_SW_range_1>=minimum_energy_threshold_for_FR && power_SW_range_2>=minimum_energy_threshold_for_FR %% changed 061617 to a more robust condition of SWS/Wake slow wange power ratio larger than 1
%                                                   if ~(nanmean(SWS_stats{1,ii}.SWS_to_W_ratio)<1 || nanmean(SWS_stats{1,jj}.SWS_to_W_ratio)<1)
                                                    % add flanking segments to avoid edge effects in filtration
                                                    flank_length=round(0.1*(length(FR_1_RAW))); 
                                                    FR_1_RAW=[(-nanmean(FR_1_RAW))*ones(1,flank_length),FR_1_RAW,(-nanmean(FR_1_RAW))*ones(1,flank_length)];
                                                    FR_2_RAW=[(-nanmean(FR_2_RAW))*ones(1,flank_length),FR_2_RAW,(-nanmean(FR_2_RAW))*ones(1,flank_length)];                                                    
                                                    FR_1=BWfilter_designer(double(FR_1_RAW), Fs_N3_SWA, bandpass_SW, bandstop_SW, 'BP');
                                                    FR_2=BWfilter_designer(double(FR_2_RAW), Fs_N3_SWA, bandpass_SW, bandstop_SW, 'BP');
                                                    % eliminate flanks
                                                    FR_1=FR_1(flank_length+1:end-flank_length);
                                                    FR_2=FR_2(flank_length+1:end-flank_length);
                                                    hilbert_FR1=hilbert(FR_1);
                                                    ins_phase_FR1=atan2(imag(hilbert_FR1),real(hilbert_FR1));
                                                    ins_freq_FR1=[0,Fs_N3_SWA/(2*pi)*diff(unwrap(angle(hilbert_FR1)))];
                                                    ins_freq_FR1(find(ins_freq_FR1<0))=0; % Do not change
                                                    ins_freq_FR1(find(ins_freq_FR1>2))=2; % Do not change
                                                    ins_amp_FR1 = abs(hilbert_FR1);
                                                    hilbert_FR2=hilbert(FR_2);
                                                    ins_phase_FR2=atan2(imag(hilbert_FR2),real(hilbert_FR2));
                                                    ins_freq_FR2=[0,Fs_N3_SWA/(2*pi)*diff(unwrap(angle(hilbert_FR2)))];
                                                    ins_freq_FR2(find(ins_freq_FR2<0))=0; % Do not change
                                                    ins_freq_FR2(find(ins_freq_FR2>2))=2; % Do not change
                                                    ins_amp_FR2 = abs(hilbert_FR2);
                                                    SW_correlation_1=[];
                                                    SW_correlation_2=[];
                                                    Distance_1=[];
                                                    Distance_2=[];
                                                    clear peak_ind_1 peak_ind_2 hilbert_*
                                                    MPD=70; % chaged 061617, used to be 75.
                                                    horizon=70; % chaged 061617, used to be 75.                                                    
                                                    if std(ins_phase_FR1)>min_phase_std_for_N3_SW
                                                        [~,peak_ind_start_1]=findpeaks(FR_1,'MinPeakDistance',MPD);
                                                        % next: elliminate very small peaks
                                                        peak_ind_1=[];
                                                        for pp=1:length(peak_ind_start_1)
                                                            if peak_ind_start_1(pp)<=horizon
                                                                [~,ind_max]=max(FR_1(1:peak_ind_start_1(pp)+horizon));
                                                                if ind_max==peak_ind_start_1(pp)
                                                                    peak_ind_1=[peak_ind_1,peak_ind_start_1(pp)];
                                                                end
                                                            elseif peak_ind_start_1(pp)>=length(FR_1)-horizon
                                                                [~,ind_max]=max(FR_1(peak_ind_start_1(pp)-horizon:length(FR_1)));
                                                                if ind_max==horizon+1
                                                                    peak_ind_1=[peak_ind_1,peak_ind_start_1(pp)];
                                                                end                                                                
                                                            elseif (peak_ind_start_1(pp)>horizon && peak_ind_start_1(pp)<length(FR_1)-horizon)
                                                                [~,ind_max]=max(FR_1(peak_ind_start_1(pp)-horizon:peak_ind_start_1(pp)+horizon));
                                                                if ind_max==horizon+1
                                                                    peak_ind_1=[peak_ind_1,peak_ind_start_1(pp)];
                                                                end                                                                
                                                            end
                                                        end
                                                        % 
%                                                         min_inst_amplitude_for_peak_point_1=prctile(sort(ins_amp_FR1),percent_thresh_for_SW_definition_FR);
%                                                         min_inst_amplitude_for_peak_point_2=prctile(sort(ins_amp_FR2),percent_thresh_for_SW_definition_FR);
                                                        indices_to_keep=find(ins_amp_FR1(peak_ind_1)>=min_inst_amplitude_for_peak_point_1 & ins_amp_FR2(peak_ind_1)>=min_inst_amplitude_for_peak_point_2); % To make sure that the peaks, and the corresponding points in the other signal are both a part of an oscillation and not a point that is not a part of any SW oscillation. %%% changed 042217
        %                                                 indices_to_keep=find(peak_value_1>=min_height_for_peaks_N3_SW & peak_value_1-ins_phase_FR1(peak_ind_1+2)>=2 & FR_1(peak_ind_1)<=nanmean(FR_1)-min_num_std_for_peak_detection*std(FR_1) & ins_amp_FR1(peak_ind_1)>=min_inst_amplitude_for_peak_point & ins_amp_FR2(peak_ind_1)>=min_inst_amplitude_for_peak_point); % peak must be above certain height, and must be on the verge of a "fall" in the phase graph, i.e. a peak, , and must be below certain depth in the original graph (because phase peaks (phase=3.14) are actually troughs in the real data). The amplitude condition is there to make sure that the peaks, and the corresponding points in the other signal are both a part of an oscillation and not a point that is not a part of any SW oscillation.
                                                        peak_ind_1=peak_ind_1(indices_to_keep);
                                                        indices_that_stay=[]; % added and changed 041917: This line, the loop below and the line after the loop. The change is aimed at making sure that the estimate for the instantaneous freqiency is more reliable, by taking it along one period around the peak index.
                                                        for indrunner=1:length(peak_ind_1)
                                                            freq1_at_ind1=ins_freq_FR1(peak_ind_1(indrunner));
%                                                             if isnan(freq1_at_ind1)  % Do not change
%                                                                 freq1_at_ind1=0.5;
%                                                             end
                                                            freq2_at_ind1=ins_freq_FR2(peak_ind_1(indrunner));                                                            
%                                                             if isnan(freq2_at_ind1) % Do not change
%                                                                 freq2_at_ind1=0.5;
%                                                             end                                                            
                                                            start_1=max(1,peak_ind_1(indrunner)-round(Fs_N3_SWA*1/(2*freq1_at_ind1)));
                                                            end_1=min(peak_ind_1(indrunner)+round(Fs_N3_SWA*1/(2*freq1_at_ind1)),length(ins_freq_FR1));
                                                            start_2=max(1,peak_ind_1(indrunner)-round(Fs_N3_SWA*1/(2*freq2_at_ind1)));
                                                            end_2=min(peak_ind_1(indrunner)+round(Fs_N3_SWA*1/(2*freq2_at_ind1)),length(ins_freq_FR2));
                                                            if abs(nanmean(ins_freq_FR1(start_1:end_1))-nanmean(ins_freq_FR2(start_2:end_2)))<=min_frequency_difference_for_phase_comparison; 
                                                                indices_that_stay=[indices_that_stay,indrunner];
                                                            end
                                                        end
                                                        peak_ind_1=peak_ind_1(indices_that_stay);

                                                        if compute_spike_SW_cross_correlation && ~isempty(peak_ind_1)
                                                            A_spikes_SW{1,2}=struct('Spikes',stable_digital_for_auto_jj,'StableStartTime',start,'StableStopTime',stop); % normalize spikes to fiting rate sampling
                                                            A_spikes_SW{1,1}=struct('Spikes',peak_ind_1/(Fs_N3_SWA/1000)*Info{1,1}.SAMPLING+start,'StableStartTime',start,'StableStopTime',stop); 
                                                            [crosscorrelogram_spikes_SW_x, crosscorrelogram_spikes_SW_1]=CrossCorr_Aviv_spikes_SW(A_spikes_SW,Info(1,unitnum));
                                                        end
                                                        for peak=1:length(peak_ind_1) % compute the correlation between FR_1 and FR_2 one Period around the peak (which is actually a trough)
                                                            specific_freq=ins_freq_FR1(peak_ind_1(peak));
                                                            if isnan(specific_freq)
                                                                specific_freq=0.5;
                                                            end
                                                            samples_to_any_direction=round(Fs_N3_SWA/specific_freq*0.5);
                                                            segment_start=max(1,peak_ind_1(peak)-samples_to_any_direction);
                                                            segment_end=min(peak_ind_1(peak)+samples_to_any_direction,length(FR_1));
                                                            first=FR_1(segment_start:segment_end)';
                                                            second=FR_2(segment_start:segment_end)';
                                                            % normalize the two signals to have the same frame
                                                            first=first-nanmean(first);
                                                            second=second-nanmean(second);
                                                            second=second/std(second);
                                                            first=first/std(first);
        %                                                     second=second*nanmean(min(first))/nanmean(min(second));
                                                            if ~isempty(first) && ~isempty(second)
                                                                SW_correlation_1=[SW_correlation_1,corr(first,second)];
                                                                Distance_1=[Distance_1,norm(first-second)/length(first)];
                                                            end
                                                        end
                                                    end
                                                    if std(ins_phase_FR2)>min_phase_std_for_N3_SW
                                                        [~,peak_ind_start_2]=findpeaks(FR_2,'MinPeakDistance',MPD);
                                                        % next: elliminate very small peaks
                                                        peak_ind_2=[];
                                                        for pp=1:length(peak_ind_start_2)
                                                            if peak_ind_start_2(pp)<=horizon
                                                                [~,ind_max]=max(FR_2(1:peak_ind_start_2(pp)+horizon));
                                                                if ind_max==peak_ind_start_2(pp)
                                                                    peak_ind_2=[peak_ind_2,peak_ind_start_2(pp)];
                                                                end
                                                            elseif peak_ind_start_2(pp)>=length(FR_2)-horizon
                                                                [~,ind_max]=max(FR_2(peak_ind_start_2(pp)-horizon:length(FR_2)));
                                                                if ind_max==horizon+1
                                                                    peak_ind_2=[peak_ind_2,peak_ind_start_2(pp)];
                                                                end                                                                
                                                            elseif (peak_ind_start_2(pp)>horizon && peak_ind_start_2(pp)<length(FR_2)-horizon)
                                                                [~,ind_max]=max(FR_2(peak_ind_start_2(pp)-horizon:peak_ind_start_2(pp)+horizon));
                                                                if ind_max==horizon+1
                                                                    peak_ind_2=[peak_ind_2,peak_ind_start_2(pp)];
                                                                end                                                                
                                                            end
                                                        end
                                                        % 
                                                        indices_to_keep=find(ins_amp_FR1(peak_ind_2)>=min_inst_amplitude_for_peak_point_1 & ins_amp_FR2(peak_ind_2)>=min_inst_amplitude_for_peak_point_2); % To make sure that the peaks, and the corresponding points in the other signal are both a part of an oscillation and not a point that is not a part of any SW oscillation. %%% changed 042217
        %                                                 indices_to_keep=find(peak_value_1>=min_height_for_peaks_N3_SW & peak_value_1-ins_phase_FR1(peak_ind_1+2)>=2 & FR_1(peak_ind_1)<=nanmean(FR_1)-min_num_std_for_peak_detection*std(FR_1) & ins_amp_FR1(peak_ind_1)>=min_inst_amplitude_for_peak_point & ins_amp_FR2(peak_ind_1)>=min_inst_amplitude_for_peak_point); % peak must be above certain height, and must be on the verge of a "fall" in the phase graph, i.e. a peak, , and must be below certain depth in the original graph (because phase peaks (phase=3.14) are actually troughs in the real data). The amplitude condition is there to make sure that the peaks, and the corresponding points in the other signal are both a part of an oscillation and not a point that is not a part of any SW oscillation.
                                                        peak_ind_2=peak_ind_2(indices_to_keep);
                                                        indices_that_stay=[]; % added and changed 041917: This line, the loop below and the line after the loop. The change is aimed at making sure that the estimate for the instantaneous freqiency is more reliable, by taking it along one period around the peak index.
                                                        for indrunner=1:length(peak_ind_2)
                                                            freq1_at_ind2=ins_freq_FR1(peak_ind_2(indrunner));
                                                            freq2_at_ind2=ins_freq_FR2(peak_ind_2(indrunner));
                                                            start_1=max(1,peak_ind_2(indrunner)-round(Fs_N3_SWA*1/(2*freq1_at_ind2)));
                                                            end_1=min(peak_ind_2(indrunner)+round(Fs_N3_SWA*1/(2*freq1_at_ind2)),length(ins_freq_FR1));
                                                            start_2=max(1,peak_ind_2(indrunner)-round(Fs_N3_SWA*1/(2*freq2_at_ind2)));
                                                            end_2=min(peak_ind_2(indrunner)+round(Fs_N3_SWA*1/(2*freq2_at_ind2)),length(ins_freq_FR2));
                                                            if abs(nanmean(ins_freq_FR1(start_1:end_1))-nanmean(ins_freq_FR2(start_2:end_2)))<=min_frequency_difference_for_phase_comparison; 
                                                                indices_that_stay=[indices_that_stay,indrunner];
                                                            end
                                                        end
                                                        peak_ind_2=peak_ind_2(indices_that_stay);
                                                        if compute_spike_SW_cross_correlation && ~isempty(peak_ind_2)
                                                            A_spikes_SW{1,2}=struct('Spikes',stable_digital_for_auto_ii,'StableStartTime',start,'StableStopTime',stop); % normalize spikes to fiting rate sampling
                                                            A_spikes_SW{1,1}=struct('Spikes',peak_ind_2/(Fs_N3_SWA/1000)*Info{1,1}.SAMPLING+start,'StableStartTime',start,'StableStopTime',stop);
                                                            [crosscorrelogram_spikes_SW_x, crosscorrelogram_spikes_SW_2]=CrossCorr_Aviv_spikes_SW(A_spikes_SW,Info(1,unitnum));
                                                        end                                            
                                                        for peak=1:length(peak_ind_2)
                                                            specific_freq=ins_freq_FR1(peak_ind_2(peak));
                                                            if specific_freq==0
                                                                specific_freq=1;
                                                            end
                                                            samples_to_any_direction=round(Fs_N3_SWA/specific_freq*0.5);
                                                            segment_start=max(1,peak_ind_2(peak)-samples_to_any_direction);
                                                            segment_end=min(peak_ind_2(peak)+samples_to_any_direction,length(FR_2));                                                            
                                                            first=FR_1(segment_start:segment_end)';
                                                            second=FR_2(segment_start:segment_end)';
                                                            % normalize the two signals to have the same frame
                                                            first=first-nanmean(first);
                                                            second=second-nanmean(second);
                                                            second=second*nanmean(min(first))/nanmean(min(second));
                                                            if ~isempty(first) && ~isempty(second)
                                                                SW_correlation_2=[SW_correlation_2,corr(first,second)];
                                                                Distance_2=[Distance_2,norm(first-second)/length(first)];
                                                            end
                                                        end                                            
                                                        clear FR_1 FR_2  F_FR1 F_FR2 PXX_FR1 PXX_FR2
                                                    end
                                                    if exist('peak_ind_1')
                                                        N3_SWA_synchronization{1,fil}.first_unit{1,ii}.second_unit{1,jj}.inst_frequency_neuron_1{1,segment}=ins_freq_FR1(peak_ind_1); 
                                                        N3_SWA_synchronization{1,fil}.first_unit{1,ii}.second_unit{1,jj}.inst_phase_neuron_1{1,segment}=ins_phase_FR2(peak_ind_1); 
                                                        N3_SWA_synchronization{1,fil}.Synchrony_SWS_strength_phase{1,rel_segments(segment)}=[N3_SWA_synchronization{1,fil}.Synchrony_SWS_strength_phase{1,rel_segments(segment)},ins_phase_FR2(peak_ind_1)]; % For correlation of synchrony vs. EEG SWS depth
                                                        N3_SWA_synchronization{1,fil}.Synchrony_SWS_strength_correlation{1,rel_segments(segment)}=[N3_SWA_synchronization{1,fil}.Synchrony_SWS_strength_correlation{1,rel_segments(segment)},SW_correlation_1];
                                                        N3_SWA_synchronization{1,fil}.first_unit{1,ii}.second_unit{1,jj}.inst_freq_other_cell_1{1,segment}=ins_freq_FR2(peak_ind_1);
                                                        N3_SWA_synchronization{1,fil}.first_unit{1,ii}.second_unit{1,jj}.inst_freq_differences_1{1,segment}=ins_freq_FR1(peak_ind_1)-ins_freq_FR2(peak_ind_1);
                                                    end
                                                    if exist('peak_ind_2')
                                                        N3_SWA_synchronization{1,fil}.first_unit{1,ii}.second_unit{1,jj}.inst_frequency_neuron_2{1,segment}=ins_freq_FR2(peak_ind_2); 
                                                        N3_SWA_synchronization{1,fil}.first_unit{1,ii}.second_unit{1,jj}.inst_phase_neuron_2{1,segment}=ins_phase_FR1(peak_ind_2); 
                                                        N3_SWA_synchronization{1,fil}.Synchrony_SWS_strength_phase{1,rel_segments(segment)}=[N3_SWA_synchronization{1,fil}.Synchrony_SWS_strength_phase{1,rel_segments(segment)},ins_phase_FR1(peak_ind_2)]; % For correlation of synchrony vs. EEG SWS depth
                                                        N3_SWA_synchronization{1,fil}.Synchrony_SWS_strength_correlation{1,rel_segments(segment)}=[N3_SWA_synchronization{1,fil}.Synchrony_SWS_strength_correlation{1,rel_segments(segment)},SW_correlation_2];
                                                        N3_SWA_synchronization{1,fil}.first_unit{1,ii}.second_unit{1,jj}.inst_freq_other_cell_2{1,segment}=ins_freq_FR1(peak_ind_2);
                                                        N3_SWA_synchronization{1,fil}.first_unit{1,ii}.second_unit{1,jj}.inst_freq_differences_2{1,segment}=ins_freq_FR2(peak_ind_2)-ins_freq_FR1(peak_ind_2);
                                                    end
                                                    N3_SWA_synchronization{1,fil}.first_unit{1,ii}.second_unit{1,jj}.SW_correlation_neuron_1{1,segment}=SW_correlation_1; 
                                                    N3_SWA_synchronization{1,fil}.first_unit{1,ii}.second_unit{1,jj}.SW_correlation_neuron_2{1,segment}=SW_correlation_2; 
                                                    N3_SWA_synchronization{1,fil}.first_unit{1,ii}.second_unit{1,jj}.SW_distance_1{1,segment}=Distance_1;
                                                    N3_SWA_synchronization{1,fil}.first_unit{1,ii}.second_unit{1,jj}.SW_distance_2{1,segment}=Distance_2;
                                                    clear ins_phase_FR1 ins_phase_FR2 ins_freq_FR1 ins_freq_FR2 ins_amp_FR1 ins_amp_FR2
                                                end
                                             end
                                             % Analyze simultaneously recorded Cortex and GPe data to establish a connection between cortical LFP, GPe LFP and GPe unit slow wave oscillation                                         
                                             if analyze_simultaneous_Cortex_GPe
                                                 LFP_trace_to_check_same=LFP_library{1,find(same_file==ii)}(ceil((start-File_Starts(1,find(same_file==ii))+1)/Info{1,1}.SAMPLING*LFP_SR_for_N3):ceil((stop-File_Starts(1,find(same_file==ii))+1)/Info{1,1}.SAMPLING*LFP_SR_for_N3)); [pxx_lfp_same,f_lfp_same] = periodogram(LFP_trace_to_check_same,hanning(length(LFP_trace_to_check_same)),2^nextpow2(length(LFP_trace_to_check_same)),1375); 
                                                 LFP_trace_to_check_other=LFP_library{1,find(same_file==jj)}(ceil((start-File_Starts(1,find(same_file==jj))+1)/Info{1,1}.SAMPLING*LFP_SR_for_N3):ceil((stop-File_Starts(1,find(same_file==jj))+1)/Info{1,1}.SAMPLING*LFP_SR_for_N3)); [pxx_lfp_other,f_lfp_other] = periodogram(LFP_trace_to_check_other,hanning(length(LFP_trace_to_check_other)),2^nextpow2(length(LFP_trace_to_check_other)),1375); 
%                                                  EEG_trace_to_check_1=EEG_library_1{1,find(same_file==jj)}(ceil((start-File_Starts(1,find(same_file==jj))+1)/Info{1,1}.SAMPLING*LFP_SR_for_N3):ceil((stop-File_Starts(1,find(same_file==jj))+1)/Info{1,1}.SAMPLING*LFP_SR_for_N3)); [pxx_eeg1,f_eeg1] = periodogram(EEG_trace_to_check_1,hanning(length(EEG_trace_to_check_1)),2^nextpow2(length(EEG_trace_to_check_1)),1375); 
%                                                  EEG_trace_to_check_2=EEG_library_2{1,find(same_file==jj)}(ceil((start-File_Starts(1,find(same_file==jj))+1)/Info{1,1}.SAMPLING*LFP_SR_for_N3):ceil((stop-File_Starts(1,find(same_file==jj))+1)/Info{1,1}.SAMPLING*LFP_SR_for_N3)); [pxx_eeg2,f_eeg2] = periodogram(EEG_trace_to_check_2,hanning(length(EEG_trace_to_check_2)),2^nextpow2(length(EEG_trace_to_check_2)),1375);
%                                                  h_signal_same=hilbert(LFP_trace_to_check_same);
%                                                  h_signal_other=hilbert(LFP_trace_to_check_other);
%                                                  ins_amp_same=bitre*abs(h_signal_same);
%                                                  ins_amp_other=bitre*abs(h_signal_other);
%                                                  LFP_amp_across_stages_same{1,relevant_stage}=[LFP_amp_across_stages_same{1,relevant_stage},length(find(ins_amp_same>75))/(length(ins_amp_same))];
%                                                  LFP_amp_across_stages_other{1,relevant_stage}=[LFP_amp_across_stages_other{1,relevant_stage},length(find(ins_amp_other>75))/(length(ins_amp_other))];
                                                if monkey==1 || (monkey==2 && ~strcmp(filenames{1,unitnum}(1,strfind(filenames{1,unitnum},'Data')+5:strfind(filenames{1,unitnum},'Data')+10),'062016')) 
                                                    last_GPe_electrode=4;
                                                elseif (monkey==2 && strcmp(filenames{1,unitnum}(1,strfind(filenames{1,unitnum},'Data')+5:strfind(filenames{1,unitnum},'Data')+10),'062016'))
                                                    last_GPe_electrode=3;
                                                end
                                                 if ElecNum(ii)<=last_GPe_electrode && ElecNum(jj)>last_GPe_electrode %(jj = Cortex, ii = GPe)
                                                     right_bin_ii=find(ismember(data2plot.PS{1,ii}.binsize_begin_sample,[start-30:1:start+30]));
                                                     right_bin_jj=find(ismember(data2plot.PS{1,jj}.binsize_begin_sample,[start-30:1:start+30]));
                                                     if ~isempty(right_bin_ii) && ~isempty(right_bin_jj)
%                                                          if length(ins_amp_same)>13751
%                                                              ins_amp_same=ins_amp_same(1:13751);
%                                                          elseif length(ins_amp_same)<13751
%                                                              ins_amp_same=[ins_amp_same,zeros(1,13751-length(ins_amp_same))];
%                                                          end
%                                                          if length(ins_amp_other)>13751
%                                                              ins_amp_other=ins_amp_other(1:13751);
%                                                          elseif length(ins_amp_other)<13751
%                                                              ins_amp_other=[ins_amp_other,zeros(1,13751-length(ins_amp_other))];
%                                                          end
                                                         if ~(last_ii_CG==ii && last_jj_CG==jj)
                                                             if ~(last_ii_CG==0 && last_jj_CG==0)
                                                                 All_LFP_GPe_Cortex_comparison{1,fil}.LFP_GPe_unit_PS_for_LFP_comparison{1,end+1}=LFP_GPe_unit_PS_for_LFP_comparison_per_pair_CG;
                                                                 All_LFP_GPe_Cortex_comparison{1,fil}.LFP_Cortex_unit_PS_for_LFP_comparison{1,end+1}=LFP_Cortex_unit_PS_for_LFP_comparison_per_pair_CG;
                                                                 All_LFP_GPe_Cortex_comparison{1,fil}.LFP_PS_for_LFP_comparison_same{1,end+1}=LFP_PS_for_LFP_comparison_same_per_pair_CG;
                                                                 All_LFP_GPe_Cortex_comparison{1,fil}.LFP_PS_for_LFP_comparison_other{1,end+1}=LFP_PS_for_LFP_comparison_other_per_pair_CG;
%                                                                  EEG_PS_for_LFP_comparison_1{1,end+1}=EEG_PS_for_LFP_comparison_1_per_pair;
%                                                                  EEG_PS_for_LFP_comparison_2{1,end+1}=EEG_PS_for_LFP_comparison_2_per_pair;
                                                                 All_LFP_GPe_Cortex_comparison{1,fil}.LFP_relevant_stage{1,end+1}=LFP_relevant_stage_per_pair_CG;
                                                                 clear LFP_GPe_unit_PS_for_LFP_comparison_per_pair LFP_Cortex_unit_PS_for_LFP_comparison_per_pair LFP_PS_for_LFP_comparison_same_per_pair LFP_PS_for_LFP_comparison_other_per_pair LFP_relevant_stage_per_pair
                                                             end
                                                             last_ii_CG=ii; last_jj_CG=jj;
                                                             LFP_GPe_unit_PS_for_LFP_comparison_per_pair_CG=[];
                                                             LFP_Cortex_unit_PS_for_LFP_comparison_per_pair_CG=[];
                                                             LFP_PS_for_LFP_comparison_same_per_pair_CG=[];
                                                             LFP_PS_for_LFP_comparison_other_per_pair_CG=[];
                                                             LFP_relevant_stage_per_pair_CG=[];
%                                                              EEG_PS_for_LFP_comparison_1_per_pair=[];
%                                                              EEG_PS_for_LFP_comparison_2_per_pair=[];
                                                        end
%                                                          LFP_ins_amp_same=[LFP_ins_amp_same,ins_amp_same'];
%                                                          LFP_ins_amp_other=[LFP_ins_amp_other,ins_amp_other'];
                                                         LFP_GPe_unit_PS_for_LFP_comparison_per_pair_CG=[LFP_GPe_unit_PS_for_LFP_comparison_per_pair_CG,data2plot.PS{1,ii}.data_per_bs(:,right_bin_ii)];
                                                         LFP_Cortex_unit_PS_for_LFP_comparison_per_pair_CG=[LFP_Cortex_unit_PS_for_LFP_comparison_per_pair_CG,data2plot.PS{1,jj}.data_per_bs(:,right_bin_jj)];
                                                         LFP_PS_for_LFP_comparison_same_per_pair_CG=[LFP_PS_for_LFP_comparison_same_per_pair_CG,pxx_lfp_same/sum(pxx_lfp_same)];
                                                         LFP_PS_for_LFP_comparison_other_per_pair_CG=[LFP_PS_for_LFP_comparison_other_per_pair_CG,pxx_lfp_other/sum(pxx_lfp_other)];
%                                                          EEG_PS_for_LFP_comparison_1_per_pair=[EEG_PS_for_LFP_comparison_1_per_pair,pxx_eeg1/sum(pxx_eeg1)];
%                                                          EEG_PS_for_LFP_comparison_2_per_pair=[EEG_PS_for_LFP_comparison_2_per_pair,pxx_eeg2/sum(pxx_eeg2)];
                                                         LFP_relevant_stage_per_pair_CG=[LFP_relevant_stage_per_pair_CG,relevant_stage];
                                                     end
%                                                  elseif ElecNum(ii)>last_GPe_electrode && ElecNum(jj)>last_GPe_electrode %(jj = Cortex, ii = GPe)
%                                                      right_bin=find(ismember(data2plot.PS{1,ii}.binsize_begin_sample,[start-30:1:start+30]));
%                                                      if ~isempty(right_bin)
%                                                          if ~(last_ii_CC==ii && last_jj_CC==jj)
%                                                              if ~(last_ii_CC==0 && last_jj_CC==0)
%                                                                  All_LFP_Cortex_Cortex_comparison{1,fil}.LFP_unit_PS_for_LFP_comparison{1,end+1}=LFP_unit_PS_for_LFP_comparison_per_pair_CC;
%                                                                  All_LFP_Cortex_Cortex_comparison{1,fil}.LFP_PS_for_LFP_comparison_same{1,end+1}=LFP_PS_for_LFP_comparison_same_per_pair_CC;
%                                                                  All_LFP_Cortex_Cortex_comparison{1,fil}.LFP_PS_for_LFP_comparison_other{1,end+1}=LFP_PS_for_LFP_comparison_other_per_pair_CC;
%                                                                  All_LFP_Cortex_Cortex_comparison{1,fil}.LFP_relevant_stage{1,end+1}=LFP_relevant_stage_per_pair_CC;
%                                                                  clear LFP_unit_PS_for_LFP_comparison_per_pair LFP_PS_for_LFP_comparison_same_per_pair LFP_PS_for_LFP_comparison_other_per_pair LFP_relevant_stage_per_pair
%                                                              end
%                                                              last_ii_CC=ii; last_jj_CC=jj;
%                                                              LFP_unit_PS_for_LFP_comparison_per_pair_CC=[];
%                                                              LFP_PS_for_LFP_comparison_same_per_pair_CC=[];
%                                                              LFP_PS_for_LFP_comparison_other_per_pair_CC=[];
%                                                              LFP_relevant_stage_per_pair_CC=[];
%                                                          end
%                                                          LFP_unit_PS_for_LFP_comparison_per_pair_CC=[LFP_unit_PS_for_LFP_comparison_per_pair_CC,data2plot.PS{1,ii}.data_per_bs(:,right_bin)];
%                                                          LFP_PS_for_LFP_comparison_same_per_pair_CC=[LFP_PS_for_LFP_comparison_same_per_pair_CC,pxx_lfp_same/sum(pxx_lfp_same)];
%                                                          LFP_PS_for_LFP_comparison_other_per_pair_CC=[LFP_PS_for_LFP_comparison_other_per_pair_CC,pxx_lfp_other/sum(pxx_lfp_other)];
%                                                          LFP_relevant_stage_per_pair_CC=[LFP_relevant_stage_per_pair_CC,relevant_stage];
%                                                      end                                                     
                                                 end
                                             end
                                             if analyze_LFP_phase_locking_in_N3 && use_SWS_N3_data && relevant_stage==4
                                                 normalizer=normalizer+1;
                                                 min_inst_amp_for_N3_LFP_phase_same=SW_definition_thresh_LFP(1,find(same_file==ii)); % changed 042317: So far I've been using a one-fits-all threshold on the LFP amplitude to define a minimum LFP amplitude. This resulted in vastly different conditions for cortex and BG (where the amplitude of the LFP is totally differetn from the start). Now the threshold to define SW is defined as the X% (70, to start) precentile of the SW amplitude (i.e. after filtration and Hilbert transform) to make the threshold relevant to the specific unit.
                                                 min_inst_amp_for_N3_LFP_phase_other=SW_definition_thresh_LFP(1,find(same_file==jj));
    %                                              min_inst_amp_for_N3_LFP_phase=20; % originally 0.75
                                                 stable_spikes=unit{1,ii}.Spikes; 
                                                 segment_spikes=stable_spikes(stable_spikes>=start & stable_spikes<=stop);
%                                                  phase_map=-pi:2*pi/1000:3*pi-2*pi/1000; % changed 043017 to have more range - -pi to 3 pi that will convert to 0-4pi
                                                 phase_map=0:2*pi/1000:2*pi-2*pi/1000;
    %                                              phase_map=0:1:627; % changed to check what happens if I use 1000 bins that cover all the circle.
                                                 h_signal_same=hilbert(LFP_library{1,find(same_file==ii)}(ceil((start-File_Starts(1,find(same_file==ii))+1)/Info{1,1}.SAMPLING*LFP_SR_for_N3):ceil((stop-File_Starts(1,find(same_file==ii))+1)/Info{1,1}.SAMPLING*LFP_SR_for_N3)));
                                                 ins_amp_same=abs(h_signal_same); % this is the instantaneous amplitude of the (already filtered) signal
                                                 ins_phase_same=atan2(imag(h_signal_same),real(h_signal_same));
                                                 ins_phase_same(find(ins_phase_same<0))=ins_phase_same(find(ins_phase_same<0))+2*pi; % convert to 0:2*pi rather than -pi:pi to avoid std artifacts.
                                                 rounded_ins_phase_same=interp1(phase_map,phase_map,ins_phase_same,'nearest','extrap'); % a line I found in the internet that should do the rounding of a vector to the nearest element in another vector.
    %                                              rounded_ins_phase_same=round(ins_phase_same*100); % changed to check what happens if I use 1000 bins that cover all the circle.
                                                 clear h_signal_same
                                                 h_signal_other=hilbert(LFP_library{1,find(same_file==jj)}(ceil((start-File_Starts(1,find(same_file==jj))+1)/Info{1,1}.SAMPLING*LFP_SR_for_N3):ceil((stop-File_Starts(1,find(same_file==jj))+1)/Info{1,1}.SAMPLING*LFP_SR_for_N3)));
                                                 ins_amp_other=abs(h_signal_other); % this is the instantaneous amplitude of the (already filtered) signal
                                                 ins_phase_other=atan2(imag(h_signal_other),real(h_signal_other));
                                                 ins_phase_other(find(ins_phase_other<0))=ins_phase_other(find(ins_phase_other<0))+2*pi; % convert to 0:2*pi rather than -pi:pi to avoid std artifacts.
                                                 rounded_ins_phase_other=interp1(phase_map,phase_map,ins_phase_other,'nearest','extrap'); % a line I found in the internet that should do the rounding of a vector to the nearest element in another vector.
                                                 clear h_signal_other
    %                                              rounded_ins_phase_other=round(ins_phase_other*100);
    %                                              % changed to check what happens if I use 1000 bins that cover all the circle.

                                                 %070317
                                                 filtered_signal_ii=LFP_library{1,find(same_file==ii)}(ceil((start-File_Starts(1,find(same_file==ii))+1)/Info{1,1}.SAMPLING*LFP_SR_for_N3):ceil((stop-File_Starts(1,find(same_file==ii))+1)/Info{1,1}.SAMPLING*LFP_SR_for_N3));
                                                 filtered_signal_jj=LFP_library{1,find(same_file==jj)}(ceil((start-File_Starts(1,find(same_file==jj))+1)/Info{1,1}.SAMPLING*LFP_SR_for_N3):ceil((stop-File_Starts(1,find(same_file==jj))+1)/Info{1,1}.SAMPLING*LFP_SR_for_N3));
                                                 filtered_signal_ii=filtered_signal_ii-nanmean(filtered_signal_ii);
                                                 filtered_signal_jj=filtered_signal_jj-nanmean(filtered_signal_jj);
                                                 if length(filtered_signal_ii)~=length(filtered_signal_jj) %071617
                                                     filtered_signal_ii=filtered_signal_ii(1:min(length(filtered_signal_ii),length(filtered_signal_jj)));
                                                     filtered_signal_jj=filtered_signal_jj(1:min(length(filtered_signal_ii),length(filtered_signal_jj)));
                                                 end                                                 
                                                 LFP_LFP_corr=[LFP_LFP_corr,corr2(filtered_signal_ii,filtered_signal_jj)]; % 070217
%                                                  filtered_signal_ii_for_cohere=LFP_library_wider_for_LFP_coherence{1,find(same_file==ii)}(ceil((start-File_Starts(1,find(same_file==ii))+1)/Info{1,1}.SAMPLING*LFP_SR_for_N3):ceil((stop-File_Starts(1,find(same_file==ii))+1)/Info{1,1}.SAMPLING*LFP_SR_for_N3));
%                                                  filtered_signal_jj_for_cohere=LFP_library_wider_for_LFP_coherence{1,find(same_file==jj)}(ceil((start-File_Starts(1,find(same_file==jj))+1)/Info{1,1}.SAMPLING*LFP_SR_for_N3):ceil((stop-File_Starts(1,find(same_file==jj))+1)/Info{1,1}.SAMPLING*LFP_SR_for_N3));
%                                                  filtered_signal_ii_for_cohere=filtered_signal_ii_for_cohere-nanmean(filtered_signal_ii_for_cohere);
%                                                  filtered_signal_jj_for_cohere=filtered_signal_jj_for_cohere-nanmean(filtered_signal_jj_for_cohere);                                                 
%                                                  [coher,f_coher_LFP_LFP]=mscohere(filtered_signal_ii_for_cohere,filtered_signal_jj_for_cohere,hamming(2*LFP_SR_for_N3*1000),0.5*2*LFP_SR_for_N3*1000,2^nextpow2(2*LFP_SR_for_N3*1000),LFP_SR_for_N3*1000); 
%                                                  LFP_LFP_coher=[LFP_LFP_coher,coher];
    
                                                 num_of_bins_same=ceil(length(ins_phase_same)/(bin_width*LFP_SR_for_N3));
                                                 first_bin_start_same=1;
                                                 bin_starts_SWA_same=[first_bin_start_same+bin_width*LFP_SR_for_N3*[0:1:num_of_bins_same-1]];
                                                 appropriate_spikes_same=ceil((segment_spikes-start+1)/Info{1,1}.SAMPLING*LFP_SR_for_N3);
                                                 if ~isempty(appropriate_spikes_same) && appropriate_spikes_same(length(appropriate_spikes_same))-length(ins_amp_same)==1
                                                     appropriate_spikes_same(length(appropriate_spikes_same))=appropriate_spikes_same(length(appropriate_spikes_same))-1;
                                                 end
                                                 appropriate_spikes_same=appropriate_spikes_same(find(bitre*ins_amp_same(appropriate_spikes_same)>=bitre*min_inst_amp_for_N3_LFP_phase_same));
                                                 if ~isempty(appropriate_spikes_same)
                                                     bin2phase_mapping_same=rounded_ins_phase_same(bin_starts_SWA_same);
                                                     subtract_bins_from_spikes_mat=(repmat(appropriate_spikes_same,length(bin_starts_SWA_same),1)-repmat(bin_starts_SWA_same',1,length(appropriate_spikes_same)));
                                                     subtract_bins_from_spikes_mat(subtract_bins_from_spikes_mat<0)=inf;
                                                     [~,indind]=min(subtract_bins_from_spikes_mat);
                                                     clear subtract_bins_from_spikes_mat rounded_ins_phase_same
                                                     for jjj=1:length(indind)
                                                          spikes_per_phase_same(find(phase_map==bin2phase_mapping_same(indind(jjj))),1)=spikes_per_phase_same(find(phase_map==bin2phase_mapping_same(indind(jjj))),1)+(1/(bin_width)*1000/(length(find(bin2phase_mapping_same==bin2phase_mapping_same(indind(jjj)))))); % to normalize by the number of times each specific phase appears in the course of the 10 seconds.
                                                     end
                                                 end
                                                 clear appropriate_spikes_same
                                                 num_of_bins_other=ceil(length(ins_phase_other)/(bin_width*LFP_SR_for_N3));
                                                 first_bin_start_other=1;
                                                 bin_starts_SWA_other=[first_bin_start_other+bin_width*LFP_SR_for_N3*[0:1:num_of_bins_other-1]];
                                                 appropriate_spikes_other=ceil((segment_spikes-start+1)/Info{1,1}.SAMPLING*LFP_SR_for_N3);
                                                 if ~isempty(appropriate_spikes_other) && (appropriate_spikes_other(length(appropriate_spikes_other))-length(ins_amp_other)==1)
                                                     appropriate_spikes_other(length(appropriate_spikes_other))=appropriate_spikes_other(length(appropriate_spikes_other))-1;
                                                 end                                         
                                                 appropriate_spikes_other=appropriate_spikes_other(find(bitre*ins_amp_other(appropriate_spikes_other)>=bitre*min_inst_amp_for_N3_LFP_phase_other));
                                                 if ~isempty(appropriate_spikes_other)
                                                     bin2phase_mapping_other=rounded_ins_phase_other(bin_starts_SWA_other);
                                                     subtract_bins_from_spikes_mat=(repmat(appropriate_spikes_other,length(bin_starts_SWA_other),1)-repmat(bin_starts_SWA_other',1,length(appropriate_spikes_other)));
                                                     subtract_bins_from_spikes_mat(subtract_bins_from_spikes_mat<0)=inf;
                                                     [~,indind]=min(subtract_bins_from_spikes_mat);
                                                     clear subtract_bins_from_spikes_mat rounded_ins_phase_other
                                                     for jjj=1:length(indind)
                                                          spikes_per_phase_other(find(phase_map==bin2phase_mapping_other(indind(jjj))),1)=spikes_per_phase_other(find(phase_map==bin2phase_mapping_other(indind(jjj))),1)+(1/(bin_width)*1000/(length(find(bin2phase_mapping_other==bin2phase_mapping_other(indind(jjj))))));
                                                     end
                                                 end
                                                 clear appropriate_spikes_other
                                             end
                                             % compute pause-2-pause correlation
                                             % create 2 1-&-0 vectors (1 signifying a pause)
                                             % for neuron i
        %                                      disp(['file is ',num2str(fil)])
        %                                      disp(['unit 1 is ',num2str(ii)])
        %                                      disp(['unit 2 is ',num2str(jj)])
                                             if compute_pause_correlation
                                                 flag=0; a=All_Pauses{1,find(same_file==ii)}+1; b=All_Pauses{2,find(same_file==ii)}-1; % + and -1 to get the beginning/endings of the pauses, and not the first/last spike after/before a pause
                                                 all_begins_and_ends=sort([a,b]); 
                                                 last_before_start=all_begins_and_ends(find(all_begins_and_ends<start,1,'last'));
                                                 if isempty(last_before_start)
                                                     flag=0;
                                                 else
                                                     if ismember(last_before_start,a)
                                                         flag=1;
                                                     elseif ismember(last_before_start,b)
                                                         flag=2;
                                                     end
                                                 end
                                                 all_begins_and_ends=all_begins_and_ends(all_begins_and_ends>=start & all_begins_and_ends<=stop);
                                                 neuron_1=zeros(1,stop-start+1);
                                                 if ~isempty(all_begins_and_ends)
                                                     all_begins_and_ends=all_begins_and_ends-start+1; % normalize to have 1-to-length of segment units
                                                     for counter=1:length(all_begins_and_ends)
                                                         if mod(counter,2)==0
                                                             neuron_1(all_begins_and_ends(counter)+1:end)=zeros(1,length(neuron_1)-all_begins_and_ends(counter)); % the difference in 1's is due to the fact that I assume that for even counters, a pause is closed, so the zero should be started one sample after, whereas for odd counters, the pause is started and a 1 is due in that proper sample.
                                                         elseif mod(counter,2)==1
                                                             neuron_1(all_begins_and_ends(counter):end)=ones(1,length(neuron_1)-all_begins_and_ends(counter)+1);
                                                         end
                                                     end
                                                     if flag==0 || flag==2
                                                         neuron_1=neuron_1; % in these cases the first all_begins_and_ends is a pause start, keep everything as is.
                                                     elseif flag==1
                                                         neuron_1=abs(neuron_1-1); % make all 1s zeros and vice versa because the first all_begins_and_ends is a pause end and not a pause start.
                                                     end
                                                 else
                                                     if flag==0 || flag==2
                                                        neuron_1=neuron_1;
                                                     elseif flag==1
                                                        neuron_1=ones(1,length(neuron_1));
                                                     end                                         
                                                 end
                                                 % neuron 2
                                                 flag=0; a=All_Pauses{1,find(same_file==jj)}+1; b=All_Pauses{2,find(same_file==jj)}-1; % + and -1 to get the beginning/endings of the pauses, and not the first/last spike after/before a pause
                                                 all_begins_and_ends=sort([a,b]); 
                                                 last_before_start=all_begins_and_ends(find(all_begins_and_ends<start,1,'last'));
                                                 if isempty(last_before_start)
                                                     flag=0;
                                                 else
                                                     if ismember(last_before_start,a)
                                                         flag=1;
                                                     elseif ismember(last_before_start,b)
                                                         flag=2;
                                                     end
                                                 end
                                                 all_begins_and_ends=all_begins_and_ends(all_begins_and_ends>=start & all_begins_and_ends<=stop);
                                                 neuron_2=zeros(1,stop-start+1);
                                                 if ~isempty(all_begins_and_ends)
                                                     all_begins_and_ends=all_begins_and_ends-start+1; % normalize to have 1-to-length of segment units
                                                     for counter=1:length(all_begins_and_ends)
                                                         if mod(counter,2)==0
                                                             neuron_2(all_begins_and_ends(counter)+1:end)=zeros(1,length(neuron_2)-all_begins_and_ends(counter)); % the difference in 1's is due to the fact that I assume that for even counters, a pause is closed, so the zero should be started one sample after, whereas for odd counters, the pause is started and a 1 is due in that proper sample.
                                                         elseif mod(counter,2)==1
                                                             neuron_2(all_begins_and_ends(counter):end)=ones(1,length(neuron_2)-all_begins_and_ends(counter)+1);
                                                         end
                                                     end
                                                     if flag==0 || flag==2
                                                         neuron_2=neuron_2; % in these cases the first all_begins_and_ends is a pause start, keep everything as is.
                                                     elseif flag==1
                                                         neuron_2=abs(neuron_2-1); % make all 1s zeros and vice versa because the first all_begins_and_ends is a pause end and not a pause start.
                                                     end
                                                 else
                                                     if flag==0 || flag==2
                                                        neuron_2=neuron_2;
                                                     elseif flag==1
                                                        neuron_2=ones(1,length(neuron_2));
                                                     end                                         
                                                 end 
                                                 pause_correlation=corr(neuron_1',neuron_2');
                                                 % compute the gaussian overlap and the decreasing overlap
                                                 neuron_1_gaussian=neuron_1;
                                                 neuron_1_monotone_decreasing=neuron_1;
                                                 neuron_1_appended=[0,neuron_1,0];
                                                 a=find(diff(neuron_1_appended)==1); % all pause starts
                                                 b=find(diff(neuron_1_appended)==-1)-1; % all pause ends. a and b must be the same length
                                                 for pp=1:length(a)
                                                     if b(pp)-a(pp)>=50
                                                         neuron_1_gaussian(1,a(pp):b(pp))=neuron_1(1,a(pp):b(pp)).*gausswin(b(pp)-a(pp)+1)';
                                                         monotone_decreasing_win=1-((0:(b(pp)-a(pp)))/(b(pp)-a(pp)+1));
                                                         neuron_1_monotone_decreasing(1,a(pp):b(pp))=neuron_1(1,a(pp):b(pp)).*monotone_decreasing_win;
                                                     end
                                                 end
                                                 neuron_2_gaussian=neuron_2;
                                                 neuron_2_monotone_decreasing=neuron_2;
                                                 neuron_2_appended=[0,neuron_2,0];
                                                 a=find(diff(neuron_2_appended)==1); % all pause starts
                                                 b=find(diff(neuron_2_appended)==-1)-1; % all pause ends. a and b must be the same length
                                                 for pp=1:length(a)
                                                     if b(pp)-a(pp)>=50
                                                         neuron_2_gaussian(1,a(pp):b(pp))=neuron_2(1,a(pp):b(pp)).*gausswin(b(pp)-a(pp)+1)';
                                                         monotone_decreasing_win=1-((0:(b(pp)-a(pp)))/(b(pp)-a(pp)+1));
                                                         neuron_2_monotone_decreasing(1,a(pp):b(pp))=neuron_2(1,a(pp):b(pp)).*monotone_decreasing_win;
                                                     end
                                                 end                                  
                                                 sum_gaussian=neuron_1_gaussian+neuron_2_gaussian;
                                                 multiplication_gaussian=neuron_1_gaussian.*neuron_2_gaussian;
                                                 gaussian_correlation_measure=sum(sum_gaussian(multiplication_gaussian~=0))/2/sum(neuron_1_gaussian)/sum(neuron_1); % to take in account only the samples were both neurons were on a pause. There are 3 "normalizations". The first is just dividing by 2 so in the case that the two pauses are overlapping we will not get the kernels from the two pauses, but only their average. This is of course maximized when they beggin (in the case of the monotone decreasing) or reach the middle (in the case of the gaussian) together. Next, the normalization by the entire pause time (after modification) of the neuron, is to get a 0 to 1 grade. The next normalization is between neurons - this is divided by the entire pause probability to be able to compare between units.
                                                 sum_monotone_decreasing=neuron_1_monotone_decreasing+neuron_2_monotone_decreasing;
                                                 multiplication_monotone_decreasing=neuron_1_monotone_decreasing.*neuron_2_monotone_decreasing;
                                                 monotone_decreasing_correlation_measure=sum(sum_monotone_decreasing(multiplication_monotone_decreasing~=0))/2/sum(neuron_1_monotone_decreasing)/sum(neuron_1); 
                                             end
                                                 switch relevant_stage
                                                     case 1 
                                                         All_CrossCorr{1,fil}.first_unit{1,ii}.second_unit{1,jj}.W.y_axis=[All_CrossCorr{1,fil}.first_unit{1,ii}.second_unit{1,jj}.W.y_axis;crosscorrelogram_y];                                                         
                                                         if compute_pause_correlation
                                                             All_PauseCorr{1,fil}.first_unit{1,ii}.second_unit{1,jj}.W.y_axis=[All_PauseCorr{1,fil}.first_unit{1,ii}.second_unit{1,jj}.W.y_axis;[pause_correlation,gaussian_correlation_measure,monotone_decreasing_correlation_measure]];                                                             
                                                         end
                                                         if compute_coherence
                                                             All_Coherence{1,fil}.first_unit{1,ii}.second_unit{1,jj}.W.y_axis=[All_Coherence{1,fil}.first_unit{1,ii}.second_unit{1,jj}.W.y_axis;Coh'];
                                                             All_Coherence{1,fil}.first_unit{1,ii}.second_unit{1,jj}.W.x_axis=Coh_F;
                                                         end
                                                     case 2
                                                         All_CrossCorr{1,fil}.first_unit{1,ii}.second_unit{1,jj}.N1.y_axis=[All_CrossCorr{1,fil}.first_unit{1,ii}.second_unit{1,jj}.N1.y_axis;crosscorrelogram_y];
                                                         if compute_pause_correlation
                                                            All_PauseCorr{1,fil}.first_unit{1,ii}.second_unit{1,jj}.N1.y_axis=[All_PauseCorr{1,fil}.first_unit{1,ii}.second_unit{1,jj}.N1.y_axis;[pause_correlation,gaussian_correlation_measure,monotone_decreasing_correlation_measure]];
                                                         end
                                                         if compute_coherence 
                                                             All_Coherence{1,fil}.first_unit{1,ii}.second_unit{1,jj}.N1.y_axis=[All_Coherence{1,fil}.first_unit{1,ii}.second_unit{1,jj}.N1.y_axis;Coh'];
                                                             All_Coherence{1,fil}.first_unit{1,ii}.second_unit{1,jj}.N1.x_axis=Coh_F;
                                                         end
                                                     case 3 %
                                                         All_CrossCorr{1,fil}.first_unit{1,ii}.second_unit{1,jj}.N2.y_axis=[All_CrossCorr{1,fil}.first_unit{1,ii}.second_unit{1,jj}.N2.y_axis;ones(1,600)];                                      
%                                                          All_CrossCorr{1,fil}.first_unit{1,ii}.second_unit{1,jj}.N2.y_axis=[All_CrossCorr{1,fil}.first_unit{1,ii}.second_unit{1,jj}.N2.y_axis;crosscorrelogram_y];                                        
%                                                          if compute_pause_correlation
%                                                              All_PauseCorr{1,fil}.first_unit{1,ii}.second_unit{1,jj}.N2.y_axis=[All_PauseCorr{1,fil}.first_unit{1,ii}.second_unit{1,jj}.N2.y_axis;[pause_correlation,gaussian_correlation_measure,monotone_decreasing_correlation_measure]];                                        
%                                                          end
%                                                          if compute_coherence
%                                                              All_Coherence{1,fil}.first_unit{1,ii}.second_unit{1,jj}.N2.y_axis=[All_Coherence{1,fil}.first_unit{1,ii}.second_unit{1,jj}.N2.y_axis;Coh'];
%                                                              All_Coherence{1,fil}.first_unit{1,ii}.second_unit{1,jj}.N2.x_axis=Coh_F;
%                                                          end
                                                     case 4
                                                         All_CrossCorr{1,fil}.first_unit{1,ii}.second_unit{1,jj}.N3.y_axis=[All_CrossCorr{1,fil}.first_unit{1,ii}.second_unit{1,jj}.N3.y_axis;crosscorrelogram_y];
                                                         if compute_pause_correlation
                                                            All_PauseCorr{1,fil}.first_unit{1,ii}.second_unit{1,jj}.N3.y_axis=[All_PauseCorr{1,fil}.first_unit{1,ii}.second_unit{1,jj}.N3.y_axis;[pause_correlation,gaussian_correlation_measure,monotone_decreasing_correlation_measure]];
                                                         end
                                                         if compute_coherence
                                                             All_Coherence{1,fil}.first_unit{1,ii}.second_unit{1,jj}.N3.y_axis=[All_Coherence{1,fil}.first_unit{1,ii}.second_unit{1,jj}.N3.y_axis;Coh'];                                             
                                                             All_Coherence{1,fil}.first_unit{1,ii}.second_unit{1,jj}.N3.x_axis=Coh_F;
                                                         end
                                                         if compute_spike_SW_cross_correlation
                                                             if exist('crosscorrelogram_spikes_SW_1')
                                                                 spike_SW_cross{1,fil}.first_unit{1,ii}.second_unit{1,jj}.neuron_1=[spike_SW_cross{1,fil}.first_unit{1,ii}.second_unit{1,jj}.neuron_1;crosscorrelogram_spikes_SW_1];
                                                             end
                                                             if exist('crosscorrelogram_spikes_SW_2')
                                                                 spike_SW_cross{1,fil}.first_unit{1,ii}.second_unit{1,jj}.neuron_2=[spike_SW_cross{1,fil}.first_unit{1,ii}.second_unit{1,jj}.neuron_2;crosscorrelogram_spikes_SW_2];
                                                             end
                                                         end
                                                     case 5
                                                         All_CrossCorr{1,fil}.first_unit{1,ii}.second_unit{1,jj}.R.y_axis=[All_CrossCorr{1,fil}.first_unit{1,ii}.second_unit{1,jj}.R.y_axis;crosscorrelogram_y];
                                                         if compute_pause_correlation
                                                             All_PauseCorr{1,fil}.first_unit{1,ii}.second_unit{1,jj}.R.y_axis=[All_PauseCorr{1,fil}.first_unit{1,ii}.second_unit{1,jj}.R.y_axis;[pause_correlation,gaussian_correlation_measure,monotone_decreasing_correlation_measure]];
                                                         end
                                                         if compute_coherence
                                                            All_Coherence{1,fil}.first_unit{1,ii}.second_unit{1,jj}.R.y_axis=[All_Coherence{1,fil}.first_unit{1,ii}.second_unit{1,jj}.R.y_axis;Coh'];                                             
                                                            All_Coherence{1,fil}.first_unit{1,ii}.second_unit{1,jj}.R.x_axis=Coh_F;
                                                         end
                                                      case 6
                                                         All_CrossCorr{1,fil}.first_unit{1,ii}.second_unit{1,jj}.U.y_axis=[All_CrossCorr{1,fil}.first_unit{1,ii}.second_unit{1,jj}.U.y_axis;crosscorrelogram_y];                                        
                                                         if compute_pause_correlation
                                                            All_PauseCorr{1,fil}.first_unit{1,ii}.second_unit{1,jj}.U.y_axis=[All_PauseCorr{1,fil}.first_unit{1,ii}.second_unit{1,jj}.U.y_axis;[pause_correlation,gaussian_correlation_measure,monotone_decreasing_correlation_measure]];                                                                                     
                                                         end
                                                         if compute_coherence
                                                            All_Coherence{1,fil}.first_unit{1,ii}.second_unit{1,jj}.U.y_axis=[All_Coherence{1,fil}.first_unit{1,ii}.second_unit{1,jj}.U.y_axis;Coh'];                                                                                     
                                                            All_Coherence{1,fil}.first_unit{1,ii}.second_unit{1,jj}.U.x_axis=Coh_F;                                                                                                                                  
                                                         end
                                                     end                                             
                                         end
                                         
                                     end
                                     end
                                     if relevant_stage==0
%                                          disp(['No Pair analysis on segment ',num2str(segment),'/',num2str(length(1:max(overlap_between_bins,1):length(rel_segments))),' in units ',num2str(ii),' and ',num2str(jj),' of ',num2str(length(same_file)),' units, file ',num2str(fil),' of ',num2str(length(filenames_unique)),' files. Relevant stage was not found.'])
                                         relevant_stage_0=relevant_stage_0+1;
                                     elseif relevant_stage==6
                                         relevant_stage_6=relevant_stage_6+1;
                                     else
                                         if ~(length(stable_digital_for_auto_ii)>=min_num_of_spikes_per_10_seconds && length(stable_digital_for_auto_jj)>=min_num_of_spikes_per_10_seconds)
%                                              disp(['No Pair analysis on segment ',num2str(segment),'/',num2str(length(1:max(overlap_between_bins,1):length(rel_segments))),' in units ',num2str(ii),' and ',num2str(jj),' of ',num2str(length(same_file)),' units, file ',num2str(fil),' of ',num2str(length(filenames_unique)),' files. Number of spikes in on of units is not enough.'])
                                            All_CrossCorr{1,fil}.first_unit{1,ii}.second_unit{1,jj}.N2.y_axis=[All_CrossCorr{1,fil}.first_unit{1,ii}.second_unit{1,jj}.N2.y_axis;ones(1,600)];                                      
                                             too_little_spikes=too_little_spikes+1;
                                         else 
                                             if relevant_stage~=4
%                                                  disp(['No Pair analysis on segment ',num2str(segment),'/',num2str(length(1:max(overlap_between_bins,1):length(rel_segments))),' in units ',num2str(ii),' and ',num2str(jj),' of ',num2str(length(same_file)),' units, file ',num2str(fil),' of ',num2str(length(filenames_unique)),' files. Stage is not (augmented) N3. Pause Correlation and GPe-Cortex analysis may have succeeded.'])
                                                 relevant_stage_not_4=relevant_stage_not_4+1;
                                             else
                                                 if ~(power_SW_range_1>=minimum_energy_threshold_for_FR && power_SW_range_2>=minimum_energy_threshold_for_FR)
%                                                      disp(['No Pair analysis on segment ',num2str(segment),'/',num2str(length(1:max(overlap_between_bins,1):length(rel_segments))),' in units ',num2str(ii),' and ',num2str(jj),' of ',num2str(length(same_file)),' units, file ',num2str(fil),' of ',num2str(length(filenames_unique)),' files. One of the units does not have enough SW content.'])
                                                     too_little_SW_power=too_little_SW_power+1;
                                                 else
                                                     if ~exist('peak_ind_1','var') && ~exist('peak_ind_2','var')
%                                                          disp(['No Pair analysis on segment ',num2str(segment),'/',num2str(length(1:max(overlap_between_bins,1):length(rel_segments))),' in units ',num2str(ii),' and ',num2str(jj),' of ',num2str(length(same_file)),' units, file ',num2str(fil),' of ',num2str(length(filenames_unique)),' files. Peaks were not found in any of the units.'])
                                                         no_peaks=no_peaks+1;
                                                     else
                                                         num_of_analyzed_segments=num_of_analyzed_segments+1;
                                                     end
                                                 end
                                             end
                                         end
                                     end                                     
                                 end
                                 if analyze_LFP_phase_locking_in_N3 && use_SWS_N3_data
                                     N3_Spiking_LFP_Phase{1,fil}.first_unit{1,ii}.second_unit{1,jj}.same_neuron=spikes_per_phase_same/normalizer;
                                     N3_Spiking_LFP_Phase{1,fil}.first_unit{1,ii}.second_unit{1,jj}.other_neuron=spikes_per_phase_other/normalizer;
                                     N3_SWA_synchronization{1,fil}.first_unit{1,ii}.second_unit{1,jj}.LFP_LFP_correlation=LFP_LFP_corr; %070217
%                                      N3_SWA_synchronization{1,fil}.first_unit{1,ii}.second_unit{1,jj}.LFP_LFP_coherence=LFP_LFP_coher; %070317
%                                      N3_SWA_synchronization{1,fil}.first_unit{1,ii}.second_unit{1,jj}.LFP_LFP_coherence_freqaxis=f_coher_LFP_LFP; %070317                                     
                                 end
                             end
                             analyzed_units=[analyzed_units;[ii,jj]];
                             if isempty(good_stable)
                                 disp(['No Pair analysis on units ',num2str(ii),' and ',num2str(jj),' of ',num2str(length(same_file)),' units, file ',num2str(fil),' of ',num2str(length(filenames_unique)),' files. No overlap segments were found.'])
                             else 
                                 disp(['Finished Pair analysis for units ',num2str(ii),' and ',num2str(jj),' of ',num2str(length(same_file)),' units, file ',num2str(fil),' of ',num2str(length(filenames_unique)),' files.'])
                                 disp(['Analyzed segments: ',num2str(num_of_analyzed_segments),'/',num2str(length(1:max(overlap_between_bins,1):length(rel_segments)))])
                                 disp(['Segments with relevant stage 0: ',num2str(relevant_stage_0),'/',num2str(length(1:max(overlap_between_bins,1):length(rel_segments)))])
                                 disp(['Segments with relevant stage 6: ',num2str(relevant_stage_6),'/',num2str(length(1:max(overlap_between_bins,1):length(rel_segments)))])
                                 disp(['Segments with too little spikes: ',num2str(too_little_spikes),'/',num2str(length(1:max(overlap_between_bins,1):length(rel_segments)))])
                                 disp(['Segments with relevant stage not 4: ',num2str(relevant_stage_not_4),'/',num2str(length(1:max(overlap_between_bins,1):length(rel_segments)))])
                                 disp(['Segments with too little SW power: ',num2str(too_little_SW_power),'/',num2str(length(1:max(overlap_between_bins,1):length(rel_segments)))])
                                 disp(['Segments with no peaks: ',num2str(no_peaks),'/',num2str(length(1:max(overlap_between_bins,1):length(rel_segments)))])
                             end
                     end
                 end
                 if exist('crosscorrelogram_x')
                    All_CrossCorr{1,fil}.x_axis=crosscorrelogram_x; 
                 end
                 if exist('crosscorrelogram_spikes_SW_x')
                    spike_SW_cross{1,fil}.x_axis=crosscorrelogram_spikes_SW_x;
                 end
                 LFP_library{1,find(same_file==ii)}=[]; % to save space and increase speed
                 clear all_segments_begs all_segments_ends
             end
         data2plot.CrossCorrelation=All_CrossCorr;
         if compute_pause_correlation
            data2plot.PauseCorrelation=All_PauseCorr;
         end
         if compute_coherence
            data2plot.Coherece=All_Coherence;
         end
         if analyze_simultaneous_Cortex_GPe && exist('LFP_GPe_unit_PS_for_LFP_comparison_per_pair_CG','var')
             All_LFP_GPe_Cortex_comparison{1,fil}.LFP_GPe_unit_PS_for_LFP_comparison{1,end+1}=LFP_GPe_unit_PS_for_LFP_comparison_per_pair_CG;
             All_LFP_GPe_Cortex_comparison{1,fil}.LFP_Cortex_unit_PS_for_LFP_comparison{1,end+1}=LFP_Cortex_unit_PS_for_LFP_comparison_per_pair_CG;
             All_LFP_GPe_Cortex_comparison{1,fil}.LFP_PS_for_LFP_comparison_same{1,end+1}=LFP_PS_for_LFP_comparison_same_per_pair_CG;
             All_LFP_GPe_Cortex_comparison{1,fil}.LFP_PS_for_LFP_comparison_other{1,end+1}=LFP_PS_for_LFP_comparison_other_per_pair_CG;
             All_LFP_GPe_Cortex_comparison{1,fil}.LFP_relevant_stage{1,end+1}=LFP_relevant_stage_per_pair_CG;
%              EEG_PS_for_LFP_comparison_1{1,end+1}=EEG_PS_for_LFP_comparison_1_per_pair;
%              EEG_PS_for_LFP_comparison_2{1,end+1}=EEG_PS_for_LFP_comparison_2_per_pair;
             clear LFP_GPe_unit_PS_for_LFP_comparison_per_pair_CG LFP_Cortex_unit_PS_for_LFP_comparison_per_pair_CG LFP_PS_for_LFP_comparison_same_per_pair_CG LFP_PS_for_LFP_comparison_other_per_pair_CG LFP_relevant_stage_per_pair_CG             
         end
%          if analyze_simultaneous_Cortex_GPe && exist('LFP_unit_PS_for_LFP_comparison_per_pair_CC','var')
%              All_LFP_Cortex_Cortex_comparison{1,fil}.LFP_unit_PS_for_LFP_comparison{1,end+1}=LFP_unit_PS_for_LFP_comparison_per_pair_CC;
%              All_LFP_Cortex_Cortex_comparison{1,fil}.LFP_PS_for_LFP_comparison_same{1,end+1}=LFP_PS_for_LFP_comparison_same_per_pair_CC;
%              All_LFP_Cortex_Cortex_comparison{1,fil}.LFP_PS_for_LFP_comparison_other{1,end+1}=LFP_PS_for_LFP_comparison_other_per_pair_CC;
%              All_LFP_Cortex_Cortex_comparison{1,fil}.LFP_relevant_stage{1,end+1}=LFP_relevant_stage_per_pair_CC;
%              clear LFP_unit_PS_for_LFP_comparison_per_pair_CC LFP_PS_for_LFP_comparison_same_per_pair_CC LFP_PS_for_LFP_comparison_other_per_pair_CC LFP_relevant_stage_per_pair_CC
%          end
        end
         
        %  Spike_Triggered LFP
        if binsize_vec(1,8)
            % compute the LFP around each spike of any unit, and average.
            ms_before=500;
            ms_after=1000;
            dsmp_factor=1;
            load('C:\Aviv\Sleep\Code\Main\BACKUP_FILES_FOR_CROSS_CORRELATION')
            MIN_OVERLAP_TIME=20;
            [filenames_unique,~,indices]=unique(filenames);
             for fil=1:length(filenames_unique)
                 same_file=find(indices==fil);
                 for ii=same_file(1):same_file(end)
                     for tt=1:6
                         Trace_storage_same{1,tt}=zeros(1,ms_before*Info{1,ii}.SAMPLING/dsmp_factor+1+ms_after*Info{1,ii}.SAMPLING/dsmp_factor);
                         Trace_storage_other{1,tt}=zeros(1,ms_before*Info{1,ii}.SAMPLING/dsmp_factor+1+ms_after*Info{1,ii}.SAMPLING/dsmp_factor);
                     end
                     other_index=zeros(1,6); same_index=zeros(1,6);
                       if use_SWS_N3_data && exist('polysomnography_with_N3','var') && ~isempty(polysomnography_with_N3{1,unitnum}.stages.N3.begin_sample) 
                          W_begins=polysomnography{ii}.stages.W.begin_sample; W_ends=polysomnography{ii}.stages.W.end_sample;
                          N1_begins=polysomnography{ii}.stages.N1.begin_sample; N1_ends=polysomnography{ii}.stages.N1.end_sample;
                          N2_begins=polysomnography{ii}.stages.N2.begin_sample; N2_ends=polysomnography{ii}.stages.N2.end_sample;
                          R_begins=polysomnography{ii}.stages.R.begin_sample; R_ends=polysomnography{ii}.stages.R.end_sample;
                          U_begins=polysomnography{ii}.stages.U.begin_sample; U_ends=polysomnography{ii}.stages.U.end_sample;
                          N3_begins=polysomnography_with_N3{1,ii}.stages.N3.begin_sample; N3_ends=polysomnography_with_N3{1,ii}.stages.N3.end_sample;
                          for kk=1:length(N3_begins)
                              if ismember(N3_begins(kk),N2_begins) && ismember(N3_ends(kk),N2_ends)
                                  N2_begins=N2_begins(N2_begins~=N3_begins(kk));
                                  N2_ends=N2_ends(N2_ends~=N3_ends(kk));
                              elseif ismember(N3_begins(kk),N2_begins) && ~ismember(N3_ends(kk),N2_ends)
                                  N2_begins(find(N2_begins==N3_begins(kk)))=N3_ends(kk)+1;
                              elseif ~ismember(N3_begins(kk),N2_begins) && ismember(N3_ends(kk),N2_ends)
                                  N2_ends(find(N2_ends==N3_ends(kk)))=N3_begins(kk)-1;
                              elseif ~ismember(N3_begins(kk),N2_begins) && ~ismember(N3_ends(kk),N2_ends)
                                  N2_begins=sort([N2_begins,N3_ends(kk)+1]);
                                  N2_ends=sort([N2_ends,N3_begins(kk)-1]);
                              end
                          beginners={sort(unique(W_begins));sort(unique(N1_begins));sort(unique(N2_begins));sort(unique(N3_begins));sort(unique(R_begins));sort(unique(U_begins))};
                          enders={sort(unique(W_ends));sort(unique(N1_ends));sort(unique(N2_ends));sort(unique(N3_ends));sort(unique(R_ends));sort(unique(U_ends))};
                          end
                      else
                          beginners={polysomnography{1,ii}.stages.W.begin_sample;polysomnography{1,ii}.stages.N1.begin_sample;polysomnography{1,ii}.stages.N2.begin_sample;polysomnography{1,ii}.stages.N3.begin_sample;polysomnography{1,ii}.stages.R.begin_sample;polysomnography{1,ii}.stages.U.begin_sample};
                          enders={polysomnography{1,ii}.stages.W.end_sample;polysomnography{1,ii}.stages.N1.end_sample;polysomnography{1,ii}.stages.N2.end_sample;polysomnography{1,ii}.stages.N3.end_sample;polysomnography{1,ii}.stages.R.end_sample;polysomnography{1,ii}.stages.U.end_sample};               
                      end
                     % get the list of spikes
                     RAW_storage=cell(length(same_file(1):same_file(end)),4);
                     for jj=same_file(1):same_file(end) % notice here I am calculating the local LFP as well as the other electrode LFP.
                         % Harvest the RAW LFP trace
                         [x,y]=find_intersect({unit{1,ii}.StableStartTime,unit{1,jj}.StableStartTime}, {unit{1,ii}.StableStopTime,unit{1,jj}.StableStopTime});
                         good_stable=find((y-x)>=(MIN_OVERLAP_TIME*1000*Info{1,ii}.SAMPLING));
                         x=x(good_stable); y=y(good_stable);
                         LFP_start=[]; LFP_end=[];
                         if ~isempty(x) && ~isempty(y)
                             LFP_start=x(1); LFP_end=y(end);
                             all_file_starts=[]; all_file_ends=[];
                             for ff=1:length(Datafiles{1,jj})
                                 all_file_starts=[all_file_starts,Datafiles{1,jj}(ff,1).start_sample];
                                 all_file_ends=[all_file_ends,Datafiles{1,jj}(ff,1).end_sample];
                             end
                             beginning_file=find(all_file_starts<=LFP_start,1,'last'); ending_file=find(all_file_ends>=LFP_end,1,'first');
                             beginning_gap=LFP_start-all_file_starts(beginning_file);  ending_gap=all_file_ends(ending_file)-LFP_end;
                             LFP=[]; 
                             aaa=0;
                           for ff=beginning_file:ending_file
                               % I found a very nice bug in the original Alpha Omega System: Many times the start sample for a new file would be lower than the end sample for the previous one. I always assumed until now that the data is also common to the ending of the first and the beginning of the next, i.e. if file n ended 100 samples after file n+1 started, the first 100 samples at n+1 will be the same as the last 100 in n. This is not the case. Rather, the system continues to record, doesn't miss samples, but it does "miss" with the genuine start and end samples, reporting erroneous figures. This is of course never more than 100 samples, but up until now it made me write an unnecessary workaround that erased samples to overcome this "bug". Since no samples are actually lost in the original files (or actually, since I can't tell how many are lost) I am erasing this workaround, here and in the LFP PS and rms analysis. 
                               % loading of files is like for the LFP PS code
                                if ff~=beginning_file
                                    difference_between_samples=Datafiles{1,jj}(ff,1).start_sample-Datafiles{1,jj}(ff-1,1).end_sample;
                                    aaa=aaa+difference_between_samples;
                                    if difference_between_samples>1
                                        LFP=[LFP,zeros(1,round((difference_between_samples-1)/Info{1,jj}.SAMPLING*RAW_KHz))];
                                    elseif difference_between_samples<1
                                        LFP=LFP(1:length(LFP)-round((1-difference_between_samples)/Info{1,jj}.SAMPLING*RAW_KHz));
                                    end
                                end
                                a=0;
                                AA=['CRAW_00',num2str(ElecNum(1,jj))];
                                BB=['CRAW_00',num2str(ElecNum(1,jj)),'_KHz'];
                                CC=['CRAW_00',num2str(ElecNum(1,jj)),'_TimeBegin'];
                                filename=Datafiles{1,jj}(ff,1).name;
                                if exist(filename)
                                    load(filename,'-mat',AA);
                                    eval(['a=~isstruct(',AA,');'])
                                    if a==1
                                        load(filename,'-mat',BB,CC);
                                        eval(['CRAW_00',num2str(ElecNum(1,jj)),'.Samples=double(',AA,');']);
                                        eval(['CRAW_00',num2str(ElecNum(1,jj)),'.KHz=double(',BB,');']);
                                        eval(['CRAW_00',num2str(ElecNum(1,jj)),'.TimeBegin=double(',CC,');']);
                                    end
                                end
                                    eval(['signal=CRAW_00',num2str(ElecNum(1,jj)),'.Samples;']);
                                if ff==beginning_file
                                    eval(['RAW_KHz=CRAW_00',num2str(ElecNum(1,jj)),'.KHz;']);
                                    eval(['file_begin_sample=floor(CRAW_00',num2str(ElecNum(1,jj)),'.TimeBegin*RAW_KHz*1000);']);
                                end
                                signal=double(signal-nanmean(signal));
                                signal=BWfilter_designer(double(signal), RAW_KHz*1000, 70, 85, 'LP');
                                LFP=[LFP,signal]; % no assumption of no sample loss between files (see before)
                                clear CLFP_0*
                           end
                            LFP=LFP(beginning_gap+1:length(LFP)-ending_gap); % As of now, LFP_start is the sample where the RAW LFP trace beggings. All spikes locations should be compared to that.
                            % The downsampling is done such that each number is converted to its closest multiple
                            % of dsmp factor from above, div. by dsmp factor, e.g. if dsmp factor=16, then 37 will become 3.
                            if dsmp_factor~=1
                                LFP=LFP(find(mod(1:length(LFP),dsmp_factor)==1)); % Downsample the signal only after filtration to achieve smarter downsampling. Data is initially sampled at 44 KHz so 1:16 filtration yields 2.75 KHz-equivalent sampling. This is fine, and actually an overkill, since the highest frequency in the signal (post filtration) is 85 Hz.
                                LFP_start=ceil(LFP_start/dsmp_factor); LFP_end=ceil(LFP_end/dsmp_factor); % Update start and end samples for the LFP trace accordingly
                            end
                            RAW_storage{find(same_file==jj),1}=LFP; RAW_storage{find(same_file==jj),2}=LFP_start; RAW_storage{find(same_file==jj),3}=LFP_end; RAW_storage{find(same_file==jj),4}=same_file(find(same_file==jj));
                         end
                     end
                     
                     % Go spike by spike and compute a. the average trace for the LFP recorded from the same electrode. b. The
                     % average trace for all other electrodes
                     spikes_orig=unit{1,ii}.Spikes(find(sum((repmat(unit{1,ii}.Spikes',1,size(unit{1,ii}.StableStartTime,2))>=repmat(unit{1,ii}.StableStartTime,size(unit{1,ii}.Spikes,2),1)).*(repmat(unit{1,ii}.Spikes',1,size(unit{1,ii}.StableStopTime,2))<=repmat(unit{1,ii}.StableStopTime,size(unit{1,ii}.Spikes,2),1)),2)));
                     if dsmp_factor~=1
                         spikes=ceil(spikes_orig/dsmp_factor); % move spikes to the downsampled Sampling Frequency
                     else
                         spikes=spikes_orig;
                     end
                     for ll=1:length(spikes)
                         triggered_trace_other=[];   % other electrodes
                         triggered_trace_same=[];    % same electrode
                         for jj=same_file(1):same_file(end)
                             disp(['spike ',num2str(ll),' out of ',num2str(length(spikes))])
                             if ~isempty(RAW_storage{find(same_file==jj),1})
                                 if (spikes(ll)-ms_before*Info{1,ii}.SAMPLING/dsmp_factor>=RAW_storage{find(same_file==jj),2} && spikes(ll)+ms_after*Info{1,ii}.SAMPLING/dsmp_factor<=RAW_storage{find(same_file==jj),3})
                                     if jj==ii
                                         if ((spikes(ll)-Info{1,ii}.SAMPLING*ms_before/dsmp_factor-RAW_storage{find(same_file==jj),2}+1)>0 && (spikes(ll)+Info{1,ii}.SAMPLING*ms_after/dsmp_factor-RAW_storage{find(same_file==jj),2}+1)<length(RAW_storage{find(same_file==jj),1}))
                                            triggered_trace_same=[triggered_trace_same;RAW_storage{find(same_file==jj),1}(spikes(ll)-Info{1,ii}.SAMPLING*ms_before/dsmp_factor-RAW_storage{find(same_file==jj),2}+1:spikes(ll)+Info{1,ii}.SAMPLING*ms_after/dsmp_factor-RAW_storage{find(same_file==jj),2}+1)];
                                         end
                                     elseif jj~=ii
                                         if ((spikes(ll)-Info{1,ii}.SAMPLING*ms_before/dsmp_factor-RAW_storage{find(same_file==jj),2}+1)>0 && (spikes(ll)+Info{1,ii}.SAMPLING*ms_after/dsmp_factor-RAW_storage{find(same_file==jj),2}+1)<length(RAW_storage{find(same_file==jj),1}))
                                            triggered_trace_other=[triggered_trace_other;RAW_storage{find(same_file==jj),1}(spikes(ll)-Info{1,ii}.SAMPLING*ms_before/dsmp_factor-RAW_storage{find(same_file==jj),2}+1:spikes(ll)+Info{1,ii}.SAMPLING*ms_after/dsmp_factor-RAW_storage{find(same_file==jj),2}+1)];
                                         end
                                     end
                                 end
                             end
                         end
                         triggered_trace_other=nanmean(triggered_trace_other,1);
                         % find the sleep stage the spike is in, just as before, for the cross correlation
                         relevant_stage=0; 
                         for stage_finder=1:5
                             if ~isempty(find(beginners{stage_finder,1}<=spikes_orig(ll),1,'last')) && ~isempty(find(enders{stage_finder,1}>=spikes_orig(ll),1,'first')) && (find(beginners{stage_finder,1}<=spikes_orig(ll),1,'last')==find(enders{stage_finder,1}>=spikes_orig(ll),1,'first'))
                                  relevant_stage=stage_finder;
                             end
                         end
                         if relevant_stage~=0
                             if ~isempty(triggered_trace_other)
                                 Trace_storage_other{1,relevant_stage}=Trace_storage_other{1,relevant_stage}+triggered_trace_other;
                                 other_index(1,relevant_stage)=other_index(1,relevant_stage)+1;
                             end
                             if ~isempty(triggered_trace_same)                             
                                 Trace_storage_same{1,relevant_stage}=Trace_storage_same{1,relevant_stage}+triggered_trace_same;
                                 same_index(1,relevant_stage)=same_index(1,relevant_stage)+1;
                             end
                         end
                     end
                     for pp=1:6
                        if (~isempty(Trace_storage_same(1,pp)) && same_index(1,pp)~=0)
                            Trace_storage_same{1,pp}=Trace_storage_same{1,pp}/same_index(1,pp); 
                        end
                        if (~isempty(Trace_storage_other(1,pp)) && other_index(1,pp)~=0)
                            Trace_storage_other{1,pp}=Trace_storage_other{1,pp}/other_index(1,pp);
                        end
                     end
                     Spike_Triggered_LFP{1,fil}.first_unit(1,ii).LFP_from_other_electrodes=Trace_storage_other;
                     Spike_Triggered_LFP{1,fil}.first_unit(1,ii).LFP_from_same_electrode=Trace_storage_same;
                 end
             end
            data2plot.Spike_Triggered_LFP=Spike_Triggered_LFP;
        end

        %  Pause-Locked PSTH
%          if binsize_vec(1,9)
%              Pause_Locked_PSTH_Aviv(filenames,unit,Info,'Generic_Suffix')
%          end
        % All analyses are made. Next steps: plot.   
        toc
        end
        plot_all_analyses(unit,polysomnography,Info,ElecNum,ChannelNum,UnitNum,data2plot,stage_length,binsize_vec,overlap_smoothing_settings,singleOrmulti);        
end