VERSION = version; VERSION = str2num(VERSION(1));
sss = sprintf('\n'); disp(sss)
disp('Please type in the name of the session or options file you''d like to Append')
disp('to this one in your STAPLOT workspace.  Sessions must have been stored')
disp('within your Matlabpath. Do not specify a pathname.  Remember that variables')
disp('not on the proplist will be overwritten if their names are not unique.')
disp('If you are not sure you will have enough memory, STOP NOW, and check.')
sss = sprintf('\n'); disp(sss)
disp('The new data must already be in STAPLOT format. If they aren''t, quit this')
disp('session, start STAPLOT again, and use Loaddata to load and convert it.')
sss = sprintf('\n'); disp(sss)

isopts = 0;
new_optsfile = input('Options filename? ([CR] to abort) >> ','s');
if ~isempty(new_optsfile)
  if exist(new_optsfile) == 2
    sss = sprintf('\n'); disp(sss)
    disp(['Evaluating and comparing ' new_optsfile])
    disp('Please wait a minute ... ')
    sss = sprintf('\n'); disp(sss)
    % now we have to backup ALL the user-specified options
    len = size(proplist); len = len(1);
    if len ~= length(typevar)
      disp('Number of variable types and variable names do not match!')
      disp('You must correct your current session before you can add another')
      return
    end
    optsmerg
    eval(new_optsfile)
    newnstn = oldnstn + nstn;
    if ~isempty(nstn)
      isopts = 1;
    else
      disp([new_optsfile ' did not appear to be a valid STAPLOT options file'])
      return
    end
  else
    disp('Not a valid options file')
    return
  end
else
  return
end

s = size(proplist); sss = []; for i = 1:s(1); sss = [sss ' ']; end
sss = sprintf('%s',[proplist sss']');
eval(['global ' sss]);

tmpnames = []; % we have a new opts file to use.  Hallelujah.
% back up the old data in proplist
olen = size(oldproplist); olen = olen(1);
for i = 1:olen
  if VERSION < 5
    t = ['tmp' num2str(round(10*rand(1,10)))];
  else
    % this is from the Mathworks script 'tempname.m'.
    t0 = clock;
    while(1)
      t = clock;
      if (fix(t0(6)*100) ~= fix(t(6)*100))
	break;
      end
    end
    t = sprintf('tmp%02.0f%04.0f', t(5), t(6)*100);
  end
  tmpnames = str2mat(tmpnames,t);
  eval([t ' = ' deblank(oldproplist(i,:)) ';'])
  eval([deblank(oldproplist(i,:)) ' = [];'])
end
tmpnames = tmpnames(2:i+1,:);

% now check the concept vars for consistency!
% pr_var etc.  We'll make a matrix and keep them in order.
% there are 8 concept vars.
oldconcepts = str2mat(oldlat_var, oldlon_var, oldsta_var, oldpr_var, ...
    oldpt_var, oldsa_var, oldde_var, oldte_var);
concepts = str2mat(lat_var, lon_var, sta_var, pr_var, ...
    pt_var, sa_var, de_var, te_var);
% first line is reserved for 'Dist'
newproplist = str2mat('Dist','','','','','','','','');
data_flag = zeros(9,3); 

% this is a little complicated, since the concept not only has 
% to be defined, but also on the proplist.
for i = 1:8
  if ~isempty(deblank(oldconcepts(i,:)));
    s = size(oldproplist);
    for ii = 1:s(1);
      if strcmp(deblank(oldconcepts(i,:)),deblank(oldproplist(ii,:)))
	 if i==8
	   newproplist = str2mat(newproplist(1:i,:),deblank(oldconcepts(i,:)));
	 else
	   newproplist = str2mat(newproplist(1:i,:),deblank(oldconcepts(i,:)), ...
	       newproplist(i+2:9,:));
	 end
	data_flag(i+1,1) = 1; % listed & exists on old, at least
	data_flag(i+1,2) = ii; 
	break
      end
    end
    if ~isempty(deblank(concepts(i,:))) & (data_flag(i+1,1) == 1),
      % if it doesn't exist in the old proplist, we're not interested
      s = size(proplist);
      for ii = 1:s(1);
	if strcmp(deblank(concepts(i,:)),deblank(proplist(ii,:)))
	  data_flag(i+1,1) = 3; 	% listed & exists in both
	  data_flag(i+1,3) = ii;
	  break
	end
      end
    end
  elseif ~isempty(deblank(concepts(i,:)));
    s = size(proplist);
    for ii = 1:s(1);
      if strcmp(deblank(concepts(i,:)),deblank(proplist(ii,:)))
	if i==8
	  newproplist = str2mat(newproplist(1:i,:),deblank(concepts(i,:)));
	else
	  newproplist = str2mat(newproplist(1:i,:),deblank(concepts(i,:)), ...
	      newproplist(i+2:9,:));
	end
	data_flag(i+1,1) = 2;	% listed & exists on new only
	data_flag(i+1,3) = ii;
	break
      end
    end
  end
end
i = find(data_flag(:,1) > 0);
if ~any(i == 1), i = [1; i(:)]; end
data_flag = data_flag(i,:);
newproplist = newproplist(i,:);
% add on everything in the old list not in the concepts list
for i = 1:olen;
  k = 1;
  for j = 1:8
    if strcmp(deblank(oldproplist(i,:)),deblank(oldconcepts(j,:)))
      k = 0; % we found a match
    elseif strcmp(deblank(oldproplist(i,:)),'Dist')
      k = 0;
    end
  end
  if k
    newproplist = str2mat(newproplist,deblank(oldproplist(i,:)));
    s = size(newproplist); data_flag(s(1),:) = [1 i 0];
  end
end

% add on everything in the new list not in the concepts list
len = size(proplist); len = len(1);
for i = 1:len;
  k = 1;
  for j = 1:8
    if strcmp(deblank(proplist(i,:)),deblank(concepts(j,:)))
      k = 0; % we found a match
    elseif strcmp(deblank(proplist(i,:)),'Dist')
      k = 0; % we found a match
    end
  end
  if k
    newproplist = str2mat(newproplist,deblank(proplist(i,:)));
    s = size(newproplist); data_flag(s(1),:) = [2 0 i];
  end
end

% eliminate duplicates
newlen = size(newproplist); newlen = newlen(1);
k = ones(newlen,1);
for i = 1:newlen
  for j = i+1:newlen
    if strcmp(newproplist(i,:),newproplist(j,:))
      k(i) = 0; data_flag(j,:) = data_flag(i,:) + data_flag(j,:);
    end
  end
end
k = find(k);
newproplist = newproplist(k,:); data_flag = data_flag(k,:);

% SET THE VARIABLE TYPES
s = size(newproplist); newlen = s(1);
newtypevar = zeros(1,newlen); newtypevar(1) = 1; % for 'Dist'
for i = 2:newlen
  if data_flag(i,1) == 3
    old_var_type = oldtypevar(data_flag(i,2));
    var_type = typevar(data_flag(i,3));
    if old_var_type == var_type
      if (old_var_type < 1) | (old_var_type > 3) |  ...
	    (old_var_type ~= round(old_var_type))
	disp(['Variable ' deblank(newproplist(i,:)) ' is of invalid type.'])
	disp('At the prompt, please input the correct type (1, 2 or 3).')
	disp('[CR] or an invalid answer will cause the variable to be deleted.')
	tt = input('Variable type? >> ');
	if ~isempty(tt)
	  newtypevar(i) = tt;
	else
	  newtypevar(i) = 0;
	end
      else
	newtypevar(i) = old_var_type;
      end
    else
      disp(['Warning; variable types for ''' deblank(newproplist(i,:)), ...
		''' are different!'])
      aa = sprintf('Old variable type is %i.  New variable type is %i.', ...
	  old_var_type, var_type);
      disp(aa)
      disp('At the prompt, please input the correct type (1, 2 or 3).')
      disp('[CR] or an invalid answer will cause the variable to be deleted.')
      tt = input('Variable type? >> ');
      if ~isempty(tt)
	newtypevar(i) = tt;
      else
	newtypevar(i) = 0;
      end
    end
  elseif data_flag(i,1) == 1
    old_var_type = oldtypevar(data_flag(i,2));
    if (old_var_type < 1) | (old_var_type > 3) | (old_var_type ~= round(old_var_type))
      disp(['Variable ''' deblank(newproplist(i,:)) ''' is of type ', ...
	      num2str(old_var_type) ' (invalid).'])
      disp('At the prompt, please input the correct type (1, 2 or 3).')
      disp('[CR] or an invalid answer will cause the variable to be deleted.')
      tt = input('Variable type? >> ');
      if ~isempty(tt)
	newtypevar(i) = tt;
      else
	newtypevar(i) = 0;
      end
    else
      newtypevar(i) = old_var_type;
    end
  elseif data_flag(i,1) == 2
    var_type = typevar(data_flag(i,3));
    if (var_type < 1) | (var_type > 3) | (var_type ~= round(var_type))
      disp(['Variable ''' deblank(newproplist(i,:)) ''' is of type ', ...
	      num2str(old_var_type) ' (invalid).'])
      disp('At the prompt, please input the correct type (1, 2 or 3).')
      disp('[CR] or an invalid answer will cause the variable to be deleted.')
      tt = input('Variable type? >> ');
      if ~isempty(tt)
	newtypevar(i) = tt;
      else
	newtypevar(i) = 0;
      end
    else
      newtypevar(i) = var_type;
    end
  else
    newtypevar(i) = 0;
  end
end
% -----------------LOAD THE DATA -------------------------------------------

disp(['options file loaded. Data file is: ' file])
q = input('Do you wish to change the path? y/n [n] >> ','s');
if isempty(q)
  q = 'n';
end
if strcmp(lower(deblank(q)),'y')
  newpath = input('New path >> ','s');
  if ~isempty(newpath)
    newpath = fliplr(deblank(fliplr(deblank(newpath))));
    if ~isempty(newpath)
      ll = size(newpath,2);
      dirsep = '/';
      c = computer;
      if strcmp(c(1:2),'PC')
	dirsep = '\';
      elseif strcmp(c(1:2),'MA')
	dirsep = ':';
      else
	if isvms
	  %shite
	  disp('Sorry, I''m foxed.')
	  return
	end
      end
      % strip off old path
      p = findstr(file,dirsep);
      if ~isempty(p)
	file = file(max(p)+1:size(file,2));
      end
      if ~strcmp(newpath(ll),dirsep);
	newpath = [newpath dirsep];
      end
      file = [newpath file];
    end
  end
end
disp(['Now attempting to load the data file ' file])
if ~isempty(file)
  if isstr(file)
    file = deblank(file);
    file = fliplr(deblank(fliplr(file)));
    l = length(file);
    if l > 4,
	if strcmp(file(l-3:l),'.mat')
	  file = file(1:l-4);
	end
    end
    if exist([file '.mat']) == 2
	isopts = 1;
    else
	disp('not a valid filename')
	disp('Please quit STAPLOT now and start again')
	return
    end
  else
    disp('not a valid filename')
    disp('Please quit STAPLOT now and start again')
    return
  end
end

disp(['loading data ' file ' ...'])
% take care of weird filenames
while (~isempty(findstr(file,'''')))
  file = strrep(file,'''','');
end
eval(['load ' '''' file '''']);
k = ones(newlen,1);
q = input('Pad with bottom values? y/n [n] >> ','s');
if isempty(q)
  q = 'n';
end
for i = 2:newlen
  var = deblank(newproplist(i,:));
  if data_flag(i,1) == 3 % variable in both proplists
    old_var = deblank(tmpnames(data_flag(i,2),:));
    new_var = deblank(proplist(data_flag(i,3),:));
    nsz = size(eval(new_var));
    osz = size(eval(old_var));
    % must check for pressure or depth and flip if necessary
    if strcmp(deblank(newproplist(i,:)),deblank(oldpr_var))
      if oldpr_reverse ~= pr_reverse
	eval([new_var '= -1*' new_var ';']);
	pr_reverse = oldpr_reverse;
      end
    end
    if strcmp(deblank(newproplist(i,:)),deblank(oldde_var))
      if oldde_reverse ~= de_reverse
	eval([new_var '= -1*' new_var ';']);
	de_reverse = oldde_reverse;
      end
    end

    % now work on combining them
    if all(nsz > 0) & all(osz > 0) 	% both actually exist
      if newtypevar(i) == 3
	if strcmp(q,'n')
	  if nsz(1) < osz(1)
	    eval([var  ' = [' old_var ', [' new_var, ...
		  '; nan*ones(osz(1)-nsz(1),nsz(2))]];'])
	  elseif nsz(1) == osz(1)
	    eval([var ' = [' old_var ',' new_var '];'])
	  elseif nsz(1) > osz(1)
	    eval([var ' = [ [' old_var '; nan*ones(nsz(1)-osz(1),osz(2))],', ...
		  new_var '];'])
	  end
	else
	  if nsz(1) < osz(1)
	    eval(['datamax = ' new_var '(nsz(1),:);'])
	    eval([var  ' = [' old_var ', [' new_var, ...
		  '; ones(osz(1)-nsz(1),1)*datamax]];'])
	  elseif nsz(1) == osz(1)
	    eval([var ' = [' old_var ',' new_var '];'])
	  elseif nsz(1) > osz(1)
	    eval(['datamax = ' old_var '(osz(1),:);'])
	    eval([var ' = [ [' old_var '; ones(nsz(1)-osz(1),1)*datamax],', ...
		  new_var '];'])
	  end
	end
      elseif newtypevar(i) == 1
	eval([var ' = [' old_var '(:)'',' new_var '(:)''];'])
      elseif newtypevar(i) == 2
	% simply write in new_var.
	eval([var ' = ' new_var ';'])
      end
    elseif all(nsz > 0)
      disp(['Data ' var ' exist only in new dataset.'])
      if newtypevar(i) == 3
	eval([var ' = [nan*zeros(nsz(1),oldnstn),'  new_var '];'])
      elseif newtypevar(i) == 1
	eval([var ' = [nan*ones(1,oldnstn), ' new_var '(:)''];'])
      elseif newtypevar(i) == 2
	eval([var ' = ' new_var ';'])
      end
    elseif all(osz > 0)
      disp(['Data ' var ' exist only in old dataset. '])
      if newtypevar(i) == 3
	eval([var ' = [' old_var ', nan*zeros(osz(1),nstn)];'])
      elseif newtypevar(i) == 1
	eval([var  ' = [' old_var '(:)'', nan*ones(1,nstn)];'])
      elseif newtypevar(i) == 2
	eval([var ' = ' old_var ';'])
      end
    else
      k(i) = 0;
    end
    if ~strcmp(var, new_var)
      eval(['clear ' new_var])
    end
    eval(['clear ' old_var])
  elseif data_flag(i,1) == 1 		% these data only exist in old set
    % must check for pressure or depth and flip if necessary
    if strcmp(deblank(newproplist(i,:)),deblank(oldpr_var))
      pr_reverse = oldpr_reverse;
    end
    if strcmp(deblank(newproplist(i,:)),deblank(oldde_var))
      de_reverse = oldde_reverse;
    end
    old_var = deblank(tmpnames(data_flag(i,2),:));
    sz = size(eval(old_var));
    if all(sz > 0)
      if newtypevar(i) == 3
	eval([var  '= nan*ones(sz(1),newnstn);'])
	eval([var '(:,1:oldnstn) = ' old_var ';'])
      elseif newtypevar(i) == 1
	eval([var ' = [' old_var '(:)'', nan*ones(1,nstn)];'])
      elseif newtypevar(i) == 2
	eval([var  ' = ' old_var ';'])
      end
    else
      k(i) = 0;
    end
    eval(['clear ' old_var])
  elseif data_flag(i,1) == 2 		% these data exist only in new dataset
    new_var = deblank(proplist(data_flag(i,3),:));
    sz = size(eval(new_var));
    if all (sz > 0)
      if newtypevar(i) == 3
	eval([var ' = [nan*zeros(sz(1),oldnstn), ' new_var '];'])
      elseif newtypevar(i) == 1
	eval([var ' = [nan*ones(1,oldnstn), ' new_var '(:)''];'])
      elseif newtypevar(i) == 2
	eval([var ' = ' new_var ';'])
      end
    end
  else
    k(i) = 0;
  end
end
k = find(k); proplist = newproplist(k,:); typevar = newtypevar(k);
data_flag = data_flag(k,:);
% reset concepts
for i = 1:newlen
  var = deblank(newproplist(i,:));
  for ii = 1:8
    if strcmp(var,deblank(oldconcepts(ii,:)))
      if ii == 1,
	lat_var = oldlat_var;
      elseif ii == 2,
	lon_var = oldlon_var;
      elseif ii == 3,
	sta_var = oldsta_var;
      elseif ii == 4,
	pr_var= oldpr_var;
      elseif ii == 5,
	pt_var = oldpt_var;
      elseif ii == 6,
	sa_var = oldsa_var;
      elseif ii == 7,
	de_var= oldde_var;
      elseif ii == 8,
	te_var = oldte_var;
      end
    end
  end
end

sections = [oldsections; sections+oldnstn];
station_style = [oldstation_style station_style];
nstn = newnstn; clear newnstn
% and now to strike a blow for continuity
proj = oldproj; 
if ~isempty(oldprojlim)
  projlim = oldprojlim;
end
if ~isempty(oldgeolim)
  geolim = oldgeolim;
end
colornames = oldcolornames; batlist = oldbatlist;
mapcolors = oldmapcolors; plotcolors = oldplotcolors;
plotstyle = oldplotstyle; isopycnals = oldisopycnals;
contno = oldcontno; marksize = oldmarksize;
pr_reverse =  oldpr_reverse; de_reverse =  oldde_reverse;
sta_write = oldsta_write;

for i = 1:olen
  eval(['clear ' tmpnames(i,:)])
end
sss = sprintf('\n'); disp(sss)

max_nrow = 0;
disp('New type 2 and 3 variables may have unequal numbers of rows.')
q = input('Pad them to the same length? y/n [y] >> ','s');
if isempty(q)
  q = 'y';
end
if strcmp(lower(deblank(q)),'y')
  ss = zeros(1,length(typevar));
  for i = 1:length(typevar)
    s = size(eval(proplist(i,:)));
    if typevar(i) == 2
      ss(i) = max(s);
    elseif typevar(i) == 3
      ss(i) = s(1);
    end
  end
  max_nrow = max(ss);
  aa = ['cc = [proplist(i,:) '' = '' deblank(proplist(i,:)) ''(:);'' ', ...
	'proplist(i,:) '' = ['' proplist(i,:) ', ...
	'''; nan*ones(max_nrow-ss(i),1)];''];'];
  bb = ['cc = [proplist(i,:) '' = ['' proplist(i,:) ', ...
	'''; nan*ones(max_nrow-ss(i),nstn)];''];'];

  for i = 1:length(typevar)
    if typevar(i) == 2
      if ss(i) < max_nrow
	eval(aa)
	eval(cc)
      end
    elseif typevar(i) == 3
      if ss(i) < max_nrow
	disp(bb)
	eval(bb)
	disp(cc)
	eval(cc)
      end
    end
  end
end

sss = sprintf('\n'); disp(sss)
disp('Datasets and options'' files merged.  To be able to reload the new, merged')
disp('session at startup, you will have to save the merged dataset as a single')
disp('file. Note that only the variables on the plot list will be saved.  Please')
disp('specify a fully qualified path with the file.')
q = input('Would you like to save the merged data now? (y/n) [n] >> ','s');
if isempty(q)
  q = 'n';
end
if strcmp(deblank(lower(q)),'y')
  file = input('Filename ([CR] to abort) >> ','s');
  if ~isempty(file)
    file = deblank(file);
    file = fliplr(deblank(fliplr(file)));
    sss = []; s = size(proplist); for i = 1:s(1); sss = [sss ' ']; end
    sss = sprintf('%s',[proplist sss']');
    % take care of weird filenames
    while (~isempty(findstr(file,'''')))
      file = strrep(file,'''','');
    end
    eval(['save '''  file ''' ' sss ]);
    sss = sprintf('\n'); disp(sss)
    disp('Merged data saved.')
    disp(' Don''t forget to save the merged session options with ''saveopts''.')
  else
    disp('Merge finished.')
  end
else
  disp('Merge finished.')
end

clear old_var_type ox nx var_type newproplist newtypevar
clear f i ii isopts j k l len olen newlen concepts
clear sz osz nsz q s t sss tmpnames new_optsfile oldconcepts
clear oldproj oldprojlim oldcolornames oldmapcolors oldplotcolors
clear oldplotstyle oldisopycnals oldcontno oldmarksize
clear oldpr_reverse oldde_reverse oldsta_write oldtypevar
clear oldpr_var oldde_var oldpt_var oldsa_var oldsta_var
clear oldte_var oldlon_var oldlat_var olddist_var 
clear oldsections oldfile oldstation_style oldproplist 
clear oldnstn old_var new_var newfile var data_flag

kids = get(0,'children');
for i = 1:length(kids) 			% close all subsidiary staplot plots
  if isstrcmp(get(kids(i),'userdata'),'staplot')
    close(kids(i))
  end
end
F_HANDLES = []; figchars = [];
set(B_HANDLES(4),'Style','Popup','String', proplist)
drawnow
if ~isempty(sections)
  s = size(sections);
  buttonstring = ['Sel All'];
  for i = 1:s(1)
    newstring = ['section ' num2str(i)];
    buttonstring = str2mat(buttonstring, newstring);
  end
end
set(B_HANDLES(3),'Style','Popup', 'String', ...
    buttonstring)
drawnow
prop = [0 0 0]; Dist = [];
hydroplt('replot')
