function run_expt_dwn
%simplified and modified from earlier programs, e.g. dwnexpt_digi
%jan 2, 2007 -- removed variable ITI and tried to simplify and make more precise the ITI timing

%daqreset
hdfml('closeall')       %close any open hdf data sets
clear all, close all               
tic                     %works with toc, at the end of the file, to time the whole execution
%____________________
[recording_status,output_channel_to_presynaptic,number_of_trials,ITI,hy,stim_philosophy,trial_time_add_on,OVSF_presyn_possible,...
pulse_duration_presyn_possible,evoke_postsynaptic_AP,postsyn_AP_delay_possible,OVSF_postsyn_possible,pulse_duration_postsyn_possible,...
cs,stim_phil5,blankenstimulus,alternating_presynaptic_channel,alternating_spritzing,ramp_height,ramp_duration,perform_triggered_imaging,...
image_every_nth_trial,trigger_high_duration,ydepth_of_rawplot,yheight_of_rawplot,mcc_output_gain_scaling_factor,autapse_analysis_mode,...
sampling_rate]=run_expt_dwn_parametersfile;
%______________________
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
output_channel_to_postsynaptic=2*(1/output_channel_to_presynaptic);

if stim_philosophy==0
    sum_of_maximum_IPIs=1000
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
elseif stim_philosophy==2
    sum_of_maximum_IPIs=2000;     %in ms
elseif stim_philosophy==3
   sum_of_maximum_IPIs=1000
elseif stim_philosophy==4
elseif stim_philosophy==5
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==10
    end_postsyn_current=10000;
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

samples_per_trigger=end_postsyn_current+additional_trial_time;   %for several stimulus classes, this value will be altered below


%dataset management                                     
if recording_status
    %global patchlog_name %deglobalized jan 2, 2007
    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
    %end the accessibility of the newly-created .hdf log file  -- it will be reopened during each run of the for loop below
    statupdate_end_sd_id_u_p_oned=hdfsd('end',sd_id_u_p);
end
 
if stim_philosophy==2
    load poisson_train_e;                            %loading the preset stimuli
    load poisson_train_g;
end

%------------------
%building the output object
d1output=analogoutput('nidaq',1);
addchannel(d1output,0);       
addchannel(d1output,1);            
%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
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) 
if perform_triggered_imaging    %building the digital object to trigger the camera and the shutter and taking the first exposure before the first stimulus --added oct 16, 2007
    camera_shutter_trig_dig_object=digitalio('nidaq',1);addline(camera_shutter_trig_dig_object,7,'out');
    putvalue(camera_shutter_trig_dig_object.Line(1),1),pause(trigger_high_duration),putvalue(camera_shutter_trig_dig_object.Line(1),0)
end
%------------------
%keeping track of these variables if they randomly vary
OVSF_presyn_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
    
    if alternating_spritzing
        if ceil(trial/2)==(trial/2)
            triggerspritzer
        else
            stopspritzer
        end
        pause(10)
    end
        
    [OVSF_presyn,OVSF_presyn_tally]=onedim_randomizer(OVSF_presyn_possible,OVSF_presyn_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:3999)=-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);
        set(d1input,'SamplesPerTrigger',samples_per_trigger);
        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);
        set(d1input,'SamplesPerTrigger',samples_per_trigger);
    elseif stim_philosophy==9 %for matt's okadaic acid expt june 14 2005
        output_trains=zeros(500000,2);
    elseif stim_philosophy==10  %the ramp stimulus
        output_trains=make_ramp_stimulus(ramp_height,ramp_duration);
        if output_channel_to_presynaptic==2
            output_trains=fliplr(output_trains);
        end
        samples_per_trigger=length(output_trains);
        set(d1input,'SamplesPerTrigger',samples_per_trigger);
    else error('stim_philosophy cannot be executed')
    end
    if blankenstimulus(1)               %yes/no, trial_duration_in_seconds, pulse_start_time_in_seconds, pulse_duration_in_seconds, pulsed_channel
        trial_duration_in_seconds=blankenstimulus(2);
		pulse_start_time_in_seconds=blankenstimulus(3);
		pulse_duration_in_seconds=blankenstimulus(4);
		pulsed_channel=blankenstimulus(5);
        
        samples_per_trigger=sampling_rate*trial_duration_in_seconds;
        set(d1input,'SamplesPerTrigger',samples_per_trigger);
        output_trains=repmat(0,samples_per_trigger,2);
        output_trains(pulse_start_time_in_seconds*sampling_rate+[1:pulse_duration_in_seconds*sampling_rate],pulsed_channel)=10;
		%bb=pulse_start_time_in_seconds*sampling_rate;
		%cc=pulse_duration_in_seconds*sampling_rate;
		%for i=0:5:25
		%output_trains(bb+(i*10000)+[1:8000],pulsed_channel)=5;
		%end
        output_trains(10001:11000,inv(pulsed_channel/2))=-.25;  %test pulse
	end
    %----------------
    trial
	disp('Hit ctrl-C to end')
    if trial==1                                                             %no intertrial interval on first trial, so no while structure is needed
        time_since_prev_trial=0;  %n.b.:  ITI is from beginning of one trial to beginning of next, but time_since_prev_trial is from end of one trial to beginning of next               
    else
        pause(ITI-(samples_per_trigger/sampling_rate)-5)
        disp('Beginning next trial')
        while (timesincemidnightinms(clock)-time_begin_wait)/1000 < (ITI-(samples_per_trigger/sampling_rate)-.11); %the time of the stim itself should be deleted from the time waited;  the .11 is for the ~110 ms used by generating the log filename and triggering
            time_since_prev_trial=timesincemidnightinms(clock)-time_begin_wait;
        end
        time_since_prev_trial
    end	
        %---------
	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);
        %------------
            
    synch=[d1output d1input];
	putdata (d1output,[output_trains])
	start(synch)
	 
    if trial>1
        inter_trial_interval=timesincemidnightinms(clock)-time_prev_trial_began
    end
    if trial>0
        time_prev_trial_began=timesincemidnightinms(clock);
	end

	trigger(synch)
    [daaataaa timee]=getdata(d1input);
    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)
    if perform_triggered_imaging && ~mod(trial,image_every_nth_trial) 
        putvalue(camera_shutter_trig_dig_object.Line(1),1),pause(trigger_high_duration),putvalue(camera_shutter_trig_dig_object.Line(1),0)
    end
    daaataaa=mcc_output_gain_scaling_factor*daaataaa;                           %converting to picoamps
    if alternating_spritzing,stopspritzer,end      
    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))
    axis([0 (length(daaataaa)/samples_per_ms) ydepth_of_rawplot yheight_of_rawplot])%([200 length(daaataaa)/samples_per_ms raw_axis(3) raw_axis(4)])
    
    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
    
    stop(d1input)  
    stop(d1output)
    %-----------------    
    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)
    end
end


%cleanup
delete(d1output)
clear d1output
delete(d1input)
clear d1input
% synch=[];
delete(synch)
clear synch
hdfml('closeall')
delete *.daq
toc