function dwnexpt_digi
%this is the main program for experiments, as of aug 26, 2003 [substantial cleanup march 4, 2004]

daqreset
hdfml('closeall')       %close any open hdf data sets
%clear all               
tic                     %works with toc, at the end of the file, to time the whole execution
%____________________
recording_status=1              %for 1 the input object will log data to disk&memory, for 0 to memory only
output_channel_to_presynaptic=2    %tells which electrode is being treated as on the presynaptic side in matlab channel numbering (output channel 1 is hardware channel 0 etc.)                        
                                    %this info will be used by random_train.m and update_patchlog.m to fliplr the output stim and to fliplr the recorded data when set to 2
                                    %since update_patchlog.m will fliplr(1 2), all subsequent processing that works from the log file need not be changed
number_of_trials=777
short_ITI_possible=[1 45000 15000]  %the short intertrial interval, in milliseconds -- general form for these randomly variable variables:  number of possible values, minimum value, step size
long_ITI=45000                      %the long intertrial interval, in milliseconds
ITI_decision_threshold=.75           %determines the ratio of short ITIs to long ITIs (*100 = percentage of ITIs that will be short)
%stim_philosophy=1                  %1 for trains randomly generated each trial, 2 for pre-set trains (stdp induction is stim philosophy 3)
%the presynaptic stimulus information matrix, used when stim_philosophy==1 (if hy is empty the output generated by random_train will be a single pulse)
%first row number of possible values for that IPI (#IPIs = #values in the first row, so #APs is that +1),%second row is minimum for that IPI in ms, %third row is interval size for that in ms
     
hy=[]%[25 50 100 200 400]%[repmat(1,1,200);repmat(10,1,200);repmat(1,1,200)]%[12.5 25 50 100 200 400 800];%[1 1 1 1 5; 10 10 10 10 100; 1 1 1 1 100]%[1 1 1 1 1; 10 10 10 10 300; 1 1 1 1 1];%[3 3 3; 300 300 300; 300 300 300]%[12.5 25 50 100 200 400 800]%[repmat(1,1,200);repmat(250,1,200);repmat(1,1,200)]%[1 1 1 1 1 1; 50 50 50 50 50 500; 1 1 1 1 1 1]%%
bouton_serch_axes=0
stim_philosophy=0
trial_time_add_on=3000;             %in milliseconds -- used in calculating additional_trial_time below

OVSF_presyn_possible=[1 5 1]                   %stim intensity from the board in volts -- output voltage scaling factor
pulse_duration_presyn_possible=[1 5 1]         %in ms
evoke_postsynaptic_AP=[0 1]                         %1 or 0, yea or nay, and if so, every how many trials
	postsyn_AP_delay_possible=[1 0 10]                           %in ms    
	OVSF_postsyn_possible=[1 5 1]                   %combinatorially occur equal numbers of times
	pulse_duration_postsyn_possible=[1 4 1]        %these two variables will be used by cs or by the joint pre-post matrix (added oct 19, 2003)
        cs=[];                                      %the matrix for postsynaptic IPIs (structured analgously to hy) (alternatively could do an 'overall' matrix, s.t. pre-and post spike time combinations)

interleaved_spontaneous_recording=[0 3]        %yea or nay and if so, for how many seconds
blankenstimulus=[1 30]
alternating_presynaptic_channel=0

ydepth_of_rawplot=-60  
yheight_of_rawplot=60
stim_phil5=[25,2000,47,290]         %used if stim_philosophy==5 (number of pulses, mean IPI in samples, pulse duration in samples, minimum interpulse interval in samples) 
mcc_output_gain_scaling_factor=400; %(pA/V) this depends on two settings in MCC, the feedback resistor (under gains) for voltage clamp, and the output gain;  this factor gives the number of pA of membrane current for each V recorded on the BNC board
%______________________
autapse_analysis_mode=0             %used by dwnrawreader_core (if true, the postsyn trace is set equal to the presyn [with a correction for stim pulses])
begin_window=7                      %in ms  %setting the windowing -- how many ms after the (end of the) input pulse to measure current?  -- used by dwnrawreader
end_window=10                       %in ms
artifact_threshold=40              %used by dwnrawreader to determine where the stimulation artifacts occurred
interleaved_mini_analysis=0  

		unsorted_overall_plot=[0 4500]      %run or not, if so how many samples from the first presyn stim
		basic_stsd_charting=[0 25]          %run or not, if so marker_scaler

        grid_raw=0
            normalize_raw_to_first_PSC=0
            raw_time_zoom=1
		grid_extracted_psc=0
            normalize_PSCs_to_first_PSC=0
            gabar_extrapolation=0
		grid_extracted_charge=0
            charge_normalization=0
		network_analysis_mode=0
            max_bump_number=0
            bump_o_overlay=[0 1500]         %run or not, if so how many samples    
            grid_bumps=0
                bump_marker_scaler=1
                bump_time_zoom=1
            grid_bump_counts=0
        grid_latencies=0    
		failed_psc_becomes_zero=0;
		colorscheme='jet';
		IPI_jitter=.4                       %(in ms) used by dwnprosslogreader to determine how similar in duration two IPIs must be to be considered 'the same'
        stim_artifact_jitter=4              %#of multiples of pulse duration over which stim artifacts will be treated as belonging to the same pulse
        sampling_rate=10000;                %in kHz
		text_alignment_threshold=-.05       %used by textlogmaker to align trials to the hyperpolarizing (access resistance test) pulse
		save_prosslogreader_output=0;       %save_prosslogreader_output determines whether prosslogreader.m stores its output (in the re_pross_log.hdf file)                         
		age_and_types=('')
 
%_____________________
samples_per_ms=(sampling_rate/1000);
halfsecond=(samples_per_ms*2500);   %used by random_train to insert a period of silence at the beginning of each trial
spontaneous_record_samples=interleaved_spontaneous_recording(2)*1000*samples_per_ms;
output_channel_to_postsynaptic=2*(1/output_channel_to_presynaptic);

if stim_philosophy==0
    APs_in_the_train=1
    permutations_of_IPIs=[]
    possible_repetitions_of_permutation=[]
    max_length_raw=200*samples_per_ms
    min_length_raw=200*samples_per_ms
    sum_of_maximum_IPIs=1000
%     sum_of_maximum_IPIs=0;
% 	for bb=1:length(hy(1,:))
%         sum_of_maximum_IPIs=sum_of_maximum_IPIs+((hy(1,bb)-1)*hy(3,bb))+hy(2,bb);
% 	end
elseif stim_philosophy==1
    sum_of_maximum_IPIs=0;
	for bb=1:length(hy(1,:))
        sum_of_maximum_IPIs=sum_of_maximum_IPIs+((hy(1,bb)-1)*hy(3,bb))+hy(2,bb);
	end
    global stsd_extracted_matrix
    global stsd_raw_matrix
	APs_in_the_train=length(hy(1,:))+1
    permutations_of_IPIs=hy(1,:)
    possible_repetitions_of_permutation=ceil(number_of_trials/prod(hy(1,:)))
    max_length_raw=samples_per_ms*max(((hy(1,:)-1).*hy(3,:))+hy(2,:))
    min_length_raw=samples_per_ms*min(hy(2,:))
    metrics_of_interest=5   %trial, psc, q, # of bumps, and latencies
	stsd_extracted_matrix=ones([permutations_of_IPIs    possible_repetitions_of_permutation   APs_in_the_train    metrics_of_interest]);  
	stsd_extracted_matrix=stsd_extracted_matrix*NaN;
	stsd_raw_matrix=ones([permutations_of_IPIs    possible_repetitions_of_permutation   APs_in_the_train    max_length_raw]); 
	stsd_raw_matrix=NaN*stsd_raw_matrix;
    if network_analysis_mode & grid_bumps
        bump_data_matrix=ones([permutations_of_IPIs    possible_repetitions_of_permutation   APs_in_the_train max_bump_number max_bump_number]);%stores index and value info for bumps after each pulse 
        bump_data_matrix=NaN*bump_data_matrix;
    end
elseif stim_philosophy==2
    APs_in_the_train=10;
    permutations_of_IPIs=[]
    possible_repetitions_of_permutation=[]
    max_length_raw=200*samples_per_ms
    min_length_raw=200*samples_per_ms
    sum_of_maximum_IPIs=2000;     %in ms
elseif stim_philosophy==3
    APs_in_the_train=1
    permutations_of_IPIs=[]
    possible_repetitions_of_permutation=[]
    max_length_raw=200*samples_per_ms
    min_length_raw=200*samples_per_ms
    sum_of_maximum_IPIs=1000
elseif stim_philosophy==4
elseif stim_philosophy==5
%     blitzkrieg_yesno=input('Apply the blitzkrieg stimulus?','s')
% 	if strcmp(blitzkrieg_yesno,'yes')|strcmp(blitzkrieg_yesno,'y')
%         disp('Neuron will be bombarded')
%     else
%         error('What stimulus is to be evoked?')
% 	end
elseif stim_philosophy==6
    irreg_pair_tally=zeros(1,length(hy));
    sum_of_maximum_IPIs=1;  %will be irrelevant later
end
%the x-dimension size of the raw plot, and the duration of the recording period for each trial, are set here
if stim_philosophy==9
    end_postsyn_current=50000
elseif stim_philosophy~=5
	end_postsyn_current=halfsecond+(samples_per_ms*(sum_of_maximum_IPIs+300))     %300 extra ms allotted to record the last PSC
else
    end_postsyn_current=stim_phil5(1)+5000;    
end
if evoke_postsynaptic_AP(1)
    additional_trial_time=((postsyn_AP_delay_possible(2)+((postsyn_AP_delay_possible(1)-1)*postsyn_AP_delay_possible(3))+trial_time_add_on)*samples_per_ms)    %one second delay, then the postsyn spike is induced and 300ms allotted to record the PSC in presyn cell
else
    additional_trial_time=(trial_time_add_on*samples_per_ms);     %record for 300ms following the last presyn AP, assuming all IPIs are maximal
end
%a=[0:.001:2]; b=fliplr(a); c=[a b]';
% a=sin([0:.001:5*pi]);
% %b=a.*a.*a.*a.*a.*a.*a.*a.*a.*a.*a.*a.*a.*a.*a.*a.*a;
% b=a;
% d=4*b;
% c=d';
samples_per_trigger=end_postsyn_current+additional_trial_time;
raw_axis=[2200 2800 ydepth_of_rawplot yheight_of_rawplot];     %xmin, xmax, ymin, ymax -- used for plotting several figures
%raw_axis=[4000 6000 ydepth_of_rawplot yheight_of_rawplot] 

%dataset management                                     
if recording_status
    global patchlog_name
    patchlog_name=create_patchlog_name                      %the .hdf file holding the raw data 
    sd_id_u_p=hdfsd('start',patchlog_name,'create');        %this sd file will be written to by update_patchlog.m
    global prosslog_name
    prosslog_name=strcat('pross',patchlog_name)
    sd_id_pross_rr=hdfsd('start',prosslog_name,'create');   %this sd file will be written to by dwnrawreader
    %end the accessibility of the newly-created .hdf log files  -- they will be reopened during each run of the for loop below
    statupdate_end_sd_id_u_p_oned=hdfsd('end',sd_id_u_p);
    statupdate_end_sd_id_pross_oned=hdfsd('end',sd_id_pross_rr);
    if interleaved_spontaneous_recording
        minilog_name=strcat('mini_',patchlog_name) 
		sd_id_mini=hdfsd('start',minilog_name,'create');        %this sd file will be written to by update_patchlog.m
		statupdate_end_mini=hdfsd('end',sd_id_mini);  
        miniprosslog_name=strcat('pross',minilog_name)
        sd_id_minipross=hdfsd('start',miniprosslog_name,'create');
        statupdate_end_minipross=hdfsd('end',sd_id_minipross);
    end
end
 
if stim_philosophy==2
    load poisson_train_e;                            %loading the preset stimuli
    load poisson_train_g;
end

%keeping track of these variables if they randomly vary
OVSF_presyn_tally=[];
short_ITI_tally=[];
pulse_duration_presyn_tally=[];
postsyn_AP_delay_tally=[];
if evoke_postsynaptic_AP(1)
   OVSF_postsyn_tally=[];                   
   pulse_duration_postsyn_tally=[];        
end

%building the stim and actually running trials
for trial=1:number_of_trials
    if alternating_presynaptic_channel
        if ceil(trial/2)==(trial/2)
            output_channel_to_presynaptic=2
        else
            output_channel_to_presynaptic=1
        end
    end
        
    [OVSF_presyn,OVSF_presyn_tally]=onedim_randomizer(OVSF_presyn_possible,OVSF_presyn_tally)
    [short_ITI,short_ITI_tally]=onedim_randomizer(short_ITI_possible,short_ITI_tally)
    [pulse_duration_presyn,pulse_duration_presyn_tally]=onedim_randomizer(pulse_duration_presyn_possible,pulse_duration_presyn_tally)
    
    evoke_postsynaptic_AP_this_trial=0;
    OVSF_postsyn=5;
    pulse_duration_postsyn=0;
    if evoke_postsynaptic_AP(1) & (rem(trial,evoke_postsynaptic_AP(2))==0)
            evoke_postsynaptic_AP_this_trial=1;
            [OVSF_postsyn,OVSF_postsyn_tally]=onedim_randomizer(OVSF_postsyn_possible,OVSF_postsyn_tally)
            [pulse_duration_postsyn,pulse_duration_postsyn_tally]=onedim_randomizer(pulse_duration_postsyn_possible,pulse_duration_postsyn_tally)
            [postsyn_AP_delay,postsyn_AP_delay_tally]=onedim_randomizer(postsyn_AP_delay_possible,postsyn_AP_delay_tally)
    else
        postsyn_AP_delay=[]
    end
    if stim_philosophy==0
        output_trains=random_train0(pulse_duration_presyn,pulse_duration_postsyn,samples_per_ms,halfsecond,trial,hy,cs,samples_per_trigger,OVSF_presyn,OVSF_postsyn,output_channel_to_presynaptic,...
            evoke_postsynaptic_AP_this_trial,end_postsyn_current,postsyn_AP_delay);
%         output_trains=[output_trains(:,1) output_trains(:,1)];
    elseif stim_philosophy==1                        %stim_philosophy==1: making a new random stimulus each trial
        output_trains=random_train1(pulse_duration_presyn,pulse_duration_postsyn,samples_per_ms,halfsecond,trial,hy,cs,samples_per_trigger,OVSF_presyn,OVSF_postsyn,output_channel_to_presynaptic,...
            evoke_postsynaptic_AP_this_trial,end_postsyn_current,postsyn_AP_delay);
%          output_trains=[output_trains(:,1) output_trains(:,1)];
    elseif stim_philosophy==2                   %stim_philosophy==2: using a preset stimulus each trial
        if ceil(trial/2)==(trial/2)             %even-numbered trials
            poisson_out=poisson_train_e;
        elseif ceil(trial/2)~=(trial/2)         %odd-numbered trials
            poisson_out=poisson_train_g;
        end
        blank_out=repmat(0,length(poisson_out),1);
        poisson_out(3000:3499)=-1/(4*OVSF_presyn);     %assuming Multiclamp Commander is set at 20mv/V, this will give a hyperpolarizing pulse of -5mv from the 300th to the 349th millisecond inclusive
        poisson_out=OVSF_presyn*poisson_out;           %(changed from 10 to 50ms march 10, 2004)
        output_trains=[poisson_out blank_out];
        if output_channel_to_presynaptic==2
            output_trains=fliplr(output_trains);
        end
    elseif stim_philosophy==3
        output_trains=random_train3(pulse_duration_presyn,pulse_duration_postsyn,samples_per_ms,halfsecond,trial,hy,cs,samples_per_trigger,OVSF_presyn,OVSF_postsyn,output_channel_to_presynaptic,...
            evoke_postsynaptic_AP_this_trial,end_postsyn_current,postsyn_AP_delay);
    elseif stim_philosophy==4
        output_trains=cat(2,5*ones(samples_per_trigger,1),0*ones(samples_per_trigger,1))
    elseif stim_philosophy==5
        poiss_train=make_poissontrain_dwn(stim_phil5(1),stim_phil5(2),stim_phil5(3),stim_phil5(4),samples_per_ms,OVSF_presyn);%(numberofpulses, IPI, pulse_dur, minimum_interval);
        poiss_train=OVSF_presyn*poiss_train;
        samples_per_trigger=length(poiss_train);
        output_trains=cat(2,poiss_train',zeros(length(poiss_train),1));
        if output_channel_to_presynaptic==2
            output_trains=fliplr(output_trains);
        end
    elseif stim_philosophy==6   %sept 2005
        [irreg_pair_tally,output_trains]=irregularly_spaced_pairs_dwn(hy,samples_per_ms,pulse_duration_presyn,OVSF_presyn,irreg_pair_tally);
        output_trains=output_trains*OVSF_presyn;
        if output_channel_to_presynaptic==2
            output_trains=fliplr(output_trains);
        end
        samples_per_trigger=length(output_trains);
    elseif stim_philosophy==9 %for matt's okadaic acid expt june 14 2005
        output_trains=zeros(500000,2);
    else error('stim_philosophy cannot be executed')
    end
    %----------------
    
    trial
    if trial==1                                                             %no intertrial interval on first trial, so no while structure is needed
        time_since_prev_trial=0;              
    else
        ITI_decision=rand;        %deciding on long v. short inter-trial interval
        disp('Hit ctrl-C now to end without compromising datalogs')
        if trial==2;intertrialinterval_overshoot=0;end
        if trial==3
            if preceding_iti==1,intertrialinterval_overshoot=inter_trial_interval-short_ITI
            elseif preceding_iti==2,intertrialinterval_overshoot=inter_trial_interval-long_ITI
            end
        end
        if ITI_decision < ITI_decision_threshold
            pause((short_ITI/1000)-5)
            disp('Do not modify now')
            while (timesincemidnightinms(clock)-time_begin_wait) < (short_ITI-(samples_per_trigger/samples_per_ms)-intertrialinterval_overshoot); %the time of the stim itself should be deleted from the time waited
                time_since_prev_trial=timesincemidnightinms(clock)-time_begin_wait;                                    %and the additional 100ms deleted from the wait is empirical (processing time)
            end
            preceding_iti=1; %0 for first trial, 1 if prev. iti was short, 2 if prev iti was long
        else
            pause ((long_ITI/1000)-5)
            disp('Do not modify now')
            while (timesincemidnightinms(clock)-time_begin_wait) < (long_ITI-(samples_per_trigger/samples_per_ms)-intertrialinterval_overshoot); %the time of the stim itself should be deleted from the time waited
                time_since_prev_trial=timesincemidnightinms(clock)-time_begin_wait;                                     %and the additional 100ms deleted from the wait is empirical (processing time)
            end
            preceding_iti=2; %0 for first trial, 1 if prev. iti was short, 2 if prev iti was long
        end
                xl=xlim,yl=ylim
        time_since_prev_trial
    end
    
    %---------
    %building the output object
d1output=analogoutput('nidaq',1);
addchannel(d1output,0);       
addchannel(d1output,1);            
%addchannel(d1output,2);           %add this channel for the picospritzer
%addchannel(d1output,3);           %add this channel if the camera needs gated
%set(d1output,'TransferMode','SingleDMA') %DMA can only be used by one of the objects, so it is used by d1input
set(d1output,'TransferMode','Interrupts') 
%set(d1output,'TriggerType','Immediate')
set(d1output,'TriggerType','Manual')        %DAQ manual says manual triggering is the fastest, other than hardware triggering
set(d1output,'TriggerType','HwDigital')
set(d1output,'SampleRate',sampling_rate)
%actualout=get(d1output,'SampleRate')      %these two lines are for debugging/checks on d1output
%get(d1output)

%building the input object
d1input=analoginput('nidaq',1);
addchannel(d1input,0);
addchannel(d1input,1);              %channels 0 and 1 carry the information recorded from neurons
addchannel(d1input,2);              %this channel is for the temperature gauge -- added feb 11 2004
if blankenstimulus(1)
    sampling_rate=10000
    samples_per_trigger=sampling_rate*blankenstimulus(2);
    output_trains=repmat(0,samples_per_trigger,2);
    output_trains(100001:200000,1)=5;
end
set(d1input,'SampleRate',sampling_rate)       
set(d1input,'SamplesPerTrigger',samples_per_trigger)
set(d1input,'ChannelSkewMode','Minimum')   
set(d1input,'TransferMode','SingleDMA')    
%set(d1input,'TransferMode','Interrupts')
%set(d1input,'TriggerType','Immediate')
%set(d1input,'TriggerType','Manual')             %DAQ manual says manual triggering is the fastest, other than hardware triggering
set(d1input,'TriggerType','HwDigital')
%set(d1input,'ManualTriggerHwOn','Trigger')     %this is added per the recommendation of the DAQ manual (p. 6-37) (but commented out to allow these m-files to work w/ matlab 6.5)
if recording_status                             %this is part of matlab DAQ logging, the files created for which will be used for the .hdf patch log
    set(d1input,'LoggingMode','Disk&Memory')
else
    set(d1input,'LoggingMode','Memory')
end
%actualin=setverify(d1input,'SampleRate',sampling_rate)       %these two lines are for debugging/checks on d1input
% get(d1input) 
    %---------
    
    
    log_filename=generate_log_filename(time_since_prev_trial);          %making the new log_filename for this trial, with generate_log_filename
        set(d1input,'LogFileName',log_filename);
    %------------
%     output_trains(5000:7000,:)=5;
   % figure(15), plot(output_trains(:,1))
    putdata (d1output,[output_trains])
    start(d1input);start(d1output);
    
	picospritzer_dig_object=digitalio('nidaq',1);
	addline(picospritzer_dig_object,5,'out','line_for_spritzer');
    putvalue(picospritzer_dig_object.Line,1)
    %firstdigstart=timesincemidnightinms(clock);
    pause(.15)
    putvalue(picospritzer_dig_object.Line,0)
    delete(picospritzer_dig_object)
	clear picospritzer_dig_object
    
    dig_object=digitalio('nidaq',1);
	addline(dig_object,1:2,'out','trigger_line');
	%c=get(hwlines,{'HwLine', 'Index', 'Parent','Type'})
    %hwinfo=daqhwinfo(dig_object);
    %hwinfo.Port(1)
    if trial>1
        inter_trial_interval=timesincemidnightinms(clock)-time_prev_trial_began;
    end
    if trial>0
        time_prev_trial_began=timesincemidnightinms(clock);
	end
    putvalue(dig_object.Line,1)%<--when the trigger is actually executed
    seconddigstart=timesincemidnightinms(clock);
	[dataa timee]=getdata(d1input);
    datagatheringend=timesincemidnightinms(clock);
%     dataa(:,1)=dataa(:,1)-mean(dataa(1:2500,1));
%     dataa(:,2)=dataa(:,2)-mean(dataa(1:2500,2));
    putvalue(dig_object.Line,0)%<--setting the trigger back to zero
%     figure(10)
%     plot(trial,(seconddigstart-firstdigstart),'o','markerfacecolor','m','markeredgecolor','m','markersize',8),hold on
%     plot(trial,(datagatheringend-firstdigstart),'o','markerfacecolor','c','markeredgecolor','c','markersize',8),hold on
    %plot(timee,dataa)
    time_begin_wait=timesincemidnightinms(clock);                   %as of feb 1 2003, times from the time_since_prev_trial are very close to those from comparing the two time_begin_waits (feb 22 -- or from clock_uno/clock_dos)
    daaataaa=dataa;%getdata(d1input);   
    daaataaa=mcc_output_gain_scaling_factor*daaataaa;                           %converting to picoamps
    
    
    if trial==1
        figure(1),clf
        set(1,'Position',[5 53 1282 333])
        colordef(figure(1),'none')
        global fig1_axes_control_toggle
        fig1_axes_control_toggle=0
    end
    set(1,'ButtonDownFcn','global fig1_axes_control_toggle, fig1_axes_control_toggle = bitcmp(fig1_axes_control_toggle,1)')

    xxll=get(gca,'xlim'),yyll=get(gca,'ylim')
    plot([inv(samples_per_ms):inv(samples_per_ms):(length(daaataaa)/samples_per_ms)],daaataaa(:,1:2))
    if bouton_serch_axes
       axis([2440 2940 -165 15])
    else
       axis([0 (length(daaataaa)/samples_per_ms) raw_axis(3) raw_axis(4)])%([200 length(daaataaa)/samples_per_ms raw_axis(3) raw_axis(4)])
    end
    if fig1_axes_control_toggle
        xlim([xxll])
        ylim([yyll])
    end
       %             
    ylabel('membrane current (pA)'),xlabel('time (ms)')
    if recording_status,title(strcat('Raw data__',patchlog_name,'__trial#',num2str(trial))),else title(strcat('Raw data','__trial#',num2str(trial))),end
          
    aitime=d1input.InitialTriggerTime;    %these four lines find the difference in the start time of the input object and that of the output object
    aotime=d1output.InitialTriggerTime;   %with 10kHz sampling, it looks like the average value is about eleven ms, and increases if the output obj. sampling rate is increased (output starting *before* input)
    delta=abs(aotime-aitime)              %one consequence is that setting windows based on where pulses occur in the output train cannot work
    sprintf('%d',delta(6))                %instead must find windows based on detection of stim pulses in the recorded trains -- as dwnrawreader does 
    stop(d1input)  %not getting rid of these guys until after the mini_recorder is called may cause trouble
    stop(d1output)
    delete(dig_object)
	clear dig_object
    
delete(d1output)
clear d1output
delete(d1input)
clear d1input
        
    %-----------------    
    if recording_status
        update_patchlog(trial,time_since_prev_trial,log_filename,OVSF_presyn,OVSF_postsyn,pulse_duration_presyn,pulse_duration_postsyn,sampling_rate,stim_philosophy,...
            output_channel_to_presynaptic,patchlog_name)
        if stim_philosophy~=3
%             rawreader_shell(samples_per_ms,artifact_threshold,begin_window,end_window,raw_axis,trial,patchlog_name,prosslog_name,autapse_analysis_mode,...
%                 stim_philosophy,hy,number_of_trials,mcc_output_gain,permutations_of_IPIs,possible_repetitions_of_permutation,APs_in_the_train,max_length_raw,min_length_raw,...
%                 IPI_jitter,gabar_extrapolation,network_analysis_mode,grid_bumps,grid_bump_counts,normalize_PSCs_to_first_PSC,normalize_raw_to_first_PSC,...
%                 unsorted_overall_plot,bump_o_overlay,max_bump_number,grid_raw,charge_normalization,grid_extracted_charge,colorscheme,failed_psc_becomes_zero,stim_artifact_jitter,grid_latencies,...
%                 grid_extracted_psc)
%             prosslogreader_shell(samples_per_ms,raw_axis,IPI_jitter,trial, number_of_trials, prosslog_name,stim_philosophy,hy,autapse_analysis_mode,...
%                 grid_raw,grid_extracted_psc,grid_extracted_charge,grid_bumps,bump_marker_scaler,bump_time_zoom,grid_bump_counts,max_bump_number,network_analysis_mode,...
%                 normalize_PSCs_to_first_PSC,normalize_raw_to_first_PSC,basic_stsd_charting,charge_normalization,age_and_types,colorscheme,raw_time_zoom,grid_latencies,...
%                 permutations_of_IPIs,possible_repetitions_of_permutation,APs_in_the_train,max_length_raw,min_length_raw)
        end
%         %because of the addition of new information (OVSF_presyn,OVSF_postsyn,pulse_duration_presyn,pulse_duration_postsyn,sampling_rate,stim_philosophy_or_timing_offset,...
        %output_channel_to_presynaptic) to the information stored in the hdf file for each trial (from dwnexpt1d or from stdp2) there is some redundancy here; it is left
        %in place for reasons of back-compatability (oct 19, 2003)
        if interleaved_spontaneous_recording(1)
            mini_recorder(trial,spontaneous_record_samples,samples_per_ms,minilog_name,miniprosslog_name,mcc_output_gain,autapse_analysis_mode,output_channel_to_presynaptic,output_channel_to_postsynaptic,...
                stim_philosophy,time_since_prev_trial)
            if interleaved_mini_analysis
                minireader_shell(trial,minilog_name,miniprosslog_name,samples_per_ms,mini_threshold,before_mini_window,after_mini_window,trial,output_channel_to_presyn,mcc_output_gain)
                miniprocessor_shell
            end        
        end
    end
    
    
%     figure(4)
%     plot(trial,delta(find(delta)),'o','markerfacecolor','r','markeredgecolor','r','markersize',8),hold on
%     figure(5)
%     if trial>1
%         plot(trial,inter_trial_interval,'o','markerfacecolor','g','markeredgecolor','g','markersize',8),hold on
%     end        
end

% cleanup
% synch=[];
% delete(synch)
% clear synch
hdfml('closeall')
%!C:MATLAB6p1/work/daq_rmv.bat
toc