function SP=data_merge2(DD,kdim,iiview,ii_concat,ii_Jday_ax);
% Call SP=data_merge(DD,kdim,iiview,ii_concat,ii_Jday_ax);
%
% DD            = structure containing data structures to join or string containing data file root;
% kdim		    = dimension over which to join datasets;
% iiview	    = 1 to call view5 on the output SP (default is 0);
% ii_concat     = 0 to interpolate, 1 to concatenate only;
% ii_Jday_ax    = 1 to convert time axis in hours to Julian day;
%
% See also data_join, data_interp, data_join_mult
%
%
% COPYRIGHT (c) 2008
% 
% Applied Research Laboratories, The University of Texas at Austin
% (ARL:UT)
% All rights reserved.
% 
% This material may be reproduced by or for the U.S. Government
% only. This notice must appear in all copies of this file and its
% derivatives. Further distribution outside the U.S. Government is
% prohibited without the explicit written authorization from the
% Director of the Environmental Sciences Laboratory, ARL:UT.
% 
% THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
% EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO THE
% IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
% PURPOSE, OR NONINFRINGEMENT.
% 
% IN NO EVENT WILL ARL:UT BE LIABLE FOR ANY DAMAGES WHATSOEVER ARISING
% OUT OF THE USE OR INABILITY TO USE THIS SOFTWARE, EVEN IF ARL:UT HAS
% BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
if nargin<4, ii_concat=0; end
if nargin<5, ii_Jday_ax=0; end
%
if nargin<1, DD='*'; end
if ischar(DD),
    ii_slash=findstr(DD,'\');
    if isempty(ii_slash), ii_slash=0; end
    data_dir=DD(1:ii_slash(end));
    mat_files=dir([DD,'*.mat']); nfile=length(mat_files);
    if nfile==0, disp('No files found that match input string'); SP=[]; return; end
    for jfile=1:nfile,
        disp([int2str(jfile),': ',mat_files(jfile).name])
    end
    iif=str2num(input('Enter file numbers to join ([]=all): ','s'));
    if isempty(iif), iif=[1:nfile]; end
    DD=cell(length(iif),1);
    for jfile=1:length(iif);
        str=['xx=load(''',data_dir,mat_files(iif(jfile)).name,''');']; eval(str);
        fields=fieldnames(xx); str=['DD{jfile}=xx.',fields{1},';']; eval(str);
    end
end
ndata=length(DD); 
if nargin<2 | isempty(kdim),
    for jdata=1:ndata,
        str=sprintf('    %s   ',DD{jdata}.labels{1:DD{jdata}.ndim}); 
        disp(['DATA ',int2str(jdata),' axis labels: ',str]);
        for jdim=1:DD{jdata}.ndim,
            lims=DD{jdata}.scales{jdim}([1,end]);
            str=['   Axis limits = ',sprintf('[%1.2f %1.2f] nval = %i',[lims(:)',DD{jdata}.dims(jdim)])]; 
            disp(str);
        end
    end
    kdim=       str2num(input(['Enter dimension number over which to join: '],'s'));
end
if nargin<3,
    iiview=     str2num(input(['          Automatically view output? (1=yes,0=no,[]=yes)   : '],'s'));
end
if isempty(iiview), iiview=1; end
% Interpolate if not same size:
ax_data=[]; delta=zeros(1,ndata);
disp(['Merging over dimension labeled ',DD{1}.labels{kdim}]);
dims_max=DD{1}.dims; ndim=length(dims_max);
scales_max=DD{1}.scales;
label=lower(DD{1}.labels{kdim});
if ~isempty(findstr(label,'time')) & ~isempty(findstr(label,'day')), 
    ii_time=1; Jday=zeros(1,ndata); 
else, 
    ii_time=0; 
end
for jdata=1:ndata,
    if DD{jdata}.ndim~=ndim, error('All data structures must have same number of dimensions'); end
	label=lower(DD{jdata}.labels{kdim}); scales=DD{jdata}.scales{kdim}(:);
    if ii_time,
        ii=findstr(label,'day'); 
        Jday(jdata)=str2num(label(ii+4:min(ii+6,end)));
        scales=scales + Jday(jdata)*24;
    end
    ax_data=[ax_data; scales]; nax=length(ax_data);
    indices{jdata}=[nax-length(scales)+1:nax];
    if DD{jdata}.dims(kdim)>1,
        delta(jdata)=mean(diff(DD{jdata}.scales{kdim}));
    else
        delta(jdata)=1;
    end
    for jdim=1:ndim,
        if DD{jdata}.dims(jdim)>dims_max(jdim),
            dims_max(jdim)=DD{jdata}.dims(jdim); 
            scales_max{jdim}=DD{jdata}.scales{jdim};
            if isfield(DD{jdata},'scales2'), scales_max2{jdim}=DD{jdata}.scales2{jdim}; end
        end
    end
end
if ii_time,
    [Jday0,jdata0]=min(Jday); ax_data=ax_data - Jday0*24;
else
    jdata0=1;
end
ax_sort=sort(ax_data);
delta_avg=median(delta);
if ii_concat==0,
    scale_merged=[ax_sort(1):delta_avg:ax_sort(end)];
else
    scale_merged=ax_sort; 
end
ldim_merged=length(scale_merged);
dims_new=dims_max; dims_new(kdim)=ldim_merged;
scales_new=scales_max; scales_new{kdim}=scale_merged;
for jdim=1:ndim, indx_full{jdim}=[1:dims_new(jdim)]; end
% Create output DATA structure:
SP=DD{jdata0}; SP.dims=dims_new; SP.scales=scales_new; SP.data=repmat(NaN,SP.dims);
if isfield(SP,'scales2'), SP.scales2{kdim}=SP.scales{kdim}; end
for jdata=1:ndata,
	if ii_concat==0,
        scales_cur=ax_data(indices{jdata});     % These are current DATA scales, possibly adjusted for hour wrapping;
        dims_cur=DD{jdata}.dims;
        ii_put=find(scale_merged>=scales_cur(1) & scale_merged<=scales_cur(end)); nput=length(ii_put);
        if nput==0, break; end
        kdim_diff=find(dims_cur~=dims_new & [1:ndim]~=kdim); ndim_diff=length(kdim_diff);
        if ndim_diff>1,
            disp(['Cannot merge DATA set ',DD{jdata}.title,' since > 1 dims other than merge dim have ', ...
                    'different sizes']);
            disp(['   dims_new = ',int2str(dims_new),'; dims_cur = ',int2str(dims_cur)]);
            break;
        end
        scales_interp=scales_max; scales_interp{kdim}=scale_merged(ii_put); 
        DD{jdata}.scales{kdim}=scales_cur;       % So that interpolation works from correct scales;
        if ndim_diff==1,
            scales_interp{kdim_diff}=scales_max{kdim_diff};
            DATA=data_interp(DD{jdata},[kdim,kdim_diff],3,scales_interp,0);
			if isfield(SP,'scales2'), SP.scales2{kdim_diff}=scales_interp{kdim_diff}; end
        else
            DATA=data_interp(DD{jdata},[kdim],3,scales_interp,0);
        end
    else
        DATA=DD{jdata};
    end
	indx_full{kdim}=ii_put;
    SP.data(indx_full{:})=DATA.data;
end
%
if ldim_merged>0 & ii_time & ii_Jday_ax,
    SP.scales{kdim}=Jday0 + SP.scales{kdim}/24;
    SP.labels{kdim}='Time - Julian Day';
    if isfield(SP,'scales2'), SP.scales2{kdim}=SP.scales{kdim}; SP.labels2{kdim}=SP.labels{kdim}; end
end
if iiview, view5(SP); end
