function [stimulus_trains]=called_by_labview_scriptnode__stimulusgenerator(recording_status,output_channel_to_presynaptic,number_of_trials,short_ITI_possible,long_ITI,ITI_decision_threshold,...
    hy,stim_philosophy,OVSF_presyn_possible,pulse_duration_presyn_possible,evoke_postsynaptic_AP,postsyn_AP_delay_possible,OVSF_postsyn_possible,...
    pulse_duration_postsyn_possible,cs,interleaved_spontaneous_recording,mcc_output_gain_scaling_factor,stim_phil5,sampling_rate
%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
%____________________


samples_per_ms=(sampling_rate/1000);
halfsecond=(samples_per_ms*500);   %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);


%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))+300)*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=(1300*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;
raw_axis=[2000 samples_per_trigger 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);
    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);
    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));%(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
    %----------------
    
    
   
    %---------
    
    
    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=repmat(0,100000,2);
%     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);
    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
    figure(1)
    set(1,'Position',[5          53        1282         333])
    clf
    colordef(figure(1),'black')
    lengthdaaataaa=length(daaataaa)
%     yl=ylim,xl=xlim
    abcde=samples_per_ms
    plot([inv(samples_per_ms):inv(samples_per_ms):(length(daaataaa)/samples_per_ms)],daaataaa(:,1:2))
    %axis([490 600 -30 10])
    axis([200 length(daaataaa)/samples_per_ms raw_axis(3) raw_axis(4)])
%             set(1,'ButtonDownFcn','figure(1),ylim=yl;xlim=xl;')
%             set(gca,'ButtonDownFcn','error(f)')%'figure(1),set(gca,''ylim'',yl)')
    %plot([inv(sampling_rate):inv(sampling_rate):(length(daaataaa)/sampling_rate)],daaataaa(:,1:2))                                           %the third column is for the temperature sensor input
    %axis([0 (length(daaataaa)/sampling_rate) raw_axis(3) raw_axis(4)])
    %axis([3000 9000 -200 20])
    ylabel('membrane current (pA)'),xlabel('time (ms)')
    if recording_status,title(strcat('Raw data__',patchlog_name)),else title('Raw data'),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
    
    %-----------------    
    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
    
    

end

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