function [S,Sred]=reduce_templatewise(filename,S_template)
%SAXS/REDUCE_TEMPLATEWISE transfers SAXS values from a template and then reduces the data.
%load the file
S=getsaxs(filename);

%put in template values
S.type='rth';
S.error_norm_fact=S_template.error_norm_fact;
S.xaxisbintype=S_template.xaxisbintype;
S.transfact=S_template.transfact;
S.sample_thickness=S_template.sample_thickness;
S.calibrationtype=S_template.calibrationtype;
S.kcal=S_template.kcal;
S.pixelcal=S_template.pixelcal;
S.koffset=S_template.koffset;
S.wavelength=S_template.wavelength;
S.reduction_type=S_template.reduction_type;
S.reduction_state=S_template.reduction_state;
S.raw_center=S_template.raw_center;
S.bsmask_configuration=S_template.bsmask_configuration;
S.bsmask_pixels=S_template.bsmask_pixels;
S.mask_filename=S_template.mask_filename;
S.mask_pixels=S_template.mask_pixels;
S.flatfield_filename=S_template.flatfield_filename;
S.flatfield_pixels=S_template.flatfield_pixels;
S.flatfieldtype=S_template.flatfieldtype;
S.empty_filename=S_template.empty_filename;
S.empty_pixels=S_template.empty_pixels;
S.empty_transfact=S_template.empty_transfact;
S.empty_livetime=S_template.empty_livetime;
S.solvent_filename=S_template.solvent_filename;
S.solvent_pixels=S_template.solvent_pixels;
S.solvent_transfact=S_template.solvent_transfact;
S.solvent_livetime=S_template.solvent_livetime;
S.solvent_thickness=S_template.solvent_thickness;
S.darkcurrent_filename=S_template.darkcurrent_filename;
S.darkcurrent_pixels=S_template.darkcurrent_pixels;
S.darkcurrent_livetime=S_template.darkcurrent_livetime;
S.readoutnoise_filename=S_template.readoutnoise_filename;
S.readoutnoise=S_template.readoutnoise;
S.zinger_removal=S_template.zinger_removal;
S.abs_int_fact=S_template.abs_int_fact;

%perform the average
%first setting some necessary parameters
bounds(1)=S_template.xaxis(1);
bounds(2)=S_template.yaxis(1);
bounds(3)=S_template.xaxis(2)-S_template.xaxis(1);
bounds(4)=S_template.yaxis(2)-S_template.yaxis(1);

npts=length(S_template.xaxisfull);

if strcmp(S_template.type,'th-ave')
    Sred = average_raw(S, 'y',bounds, npts);
else
    Sred = average_raw(S, 'x',bounds, npts);
end

%return