function update_local(filename)
%
%  This function reads dataset archive.m filenames from an input
%  file, and incorporates those datasets into the Matlab GUI.
%  
%  Inputs:
% 
%  filename  The name of the file from which the datasets are to
%            be read. The file is formatted as follows: each line
%            of the file represents another dataset. The first 
%            entry of each line is the name of an archive.m file. 
%            Each other name on the same line indicates a file 
%            needed for the operation of the archive.m file. 
%            Unlike updating from the remote MANIFEST file, all 
%            files named in this local file should already be in
%            the $MATLABPATH somewhere, so they need not be 
%            fetched. Here's a sample line from the local file:
% 
%            reyweek combine daily uriwkurl
% 
%            This implies that reyweek.m is a new archive.m file,
%            containing meta-data about the data whose short name
%            is "reyweek." For reyweek.m to work properly, the
%            files combine.m, daily.m, and uriwkurl.m must also
%            exist in the $MATLABPATH.
%
%            Note that there is no 'new' or 'all' switch on this
%            function. Datasets will be added to the existing set.
%            In the case of name conflicts, the new dataset 
%            supersedes the one already named in the master
%            dataset list.

% $Id: updatlcl.m,v 1.14 1999/07/21 15:30:11 dbyrne Exp $

% $Log: updatlcl.m,v $
% Revision 1.14  1999/07/21 15:30:11  dbyrne
%
%
% Update and updatlclm have been changed in the following ways:  Bug in updatlcl
% that inserted an empty line into the top of master_archives, master_getxxx, etc
% has been fixed.
%
% Both routines will now automatically strip out any variable names that are not
% used by any datasets.  Both will now alphabetize the dataset names and the
% variables lists used in the scrolling menus.  Both will also strip trailing
% blanks off of the end of the variables list (should do this for datasets, too).
%
% dbyrne 99/07/21
%
% Revision 1.13  1999/05/13 03:09:54  dbyrne
%
%
% Added Acknowledge and Data_Use_Policy to archive.m.  Fixed getxxx functions
% to use dodsmsg instead of stdout for errors/info.  Made ChangeLog so that it's
% in Emacs format.  All changes for release 3.0.0 -- dbyrne 99/05/12
%
% Revision 1.2  1998/09/11 18:07:03  dbyrne
% removed ReturnedVariables.
%
% Revision 1.1  1998/05/17 14:10:55  dbyrne
% *** empty log message ***
%
% Revision 1.6  1997/10/17 15:34:59  tom
% Changed manner in which we checked for blank MANIFEST lines,
% on the kind advice of Matlab version 5.
%
% Revision 1.5  1997/10/10 00:57:48  tom
% Corrected array index bug for case where you are updating the last
% dataset in the master list.
%
% Revision 1.4  1997/10/09 23:46:56  tom
% Fixed use of the blanks function to repair incompatibility with
% Matlab version 5.
%
% Revision 1.3  1997/09/30 19:22:59  tom
% fixed to better accomodate using the local Manifest to
% replace archives with a local version
%
% Revision 1.2  1997/09/24 01:13:52  tom
% Fixed to update rangemax and rangemin.
%
% Revision 1.1.1.1  1997/09/22 14:13:54  tom
% Imported Matlab GUI sources to CVS
%

%
%  These are other necessary input information. 
global dodsdir VERSION plotcolors

% 
%  These are the variables that must be modified in order to incorporate
%  a new dataset into the browser (output of this function): 
global master_getxxx master_rangemax master_rangemin 
global master_resolutions master_variables master_archives 
global master_dataprops master_datasets num_sets num_vars
global datacolor master_georange rangemax rangemin

%
%  Open the manifest file and read it all into a character array

disp('Reading manifest ...')
fid = fopen(filename,'r');
files = fscanf(fid,'%c');

%
%  Close the manifest file
fclose(fid);

%  Step through each file named in the manifest, reading its data 
%  into the appropriate places.

lines = findstr(files,setstr(10));  % find the end of each line
numlines = length(lines);
if lines(numlines) < length(files)
  numlines = numlines + 1;
  files = [files setstr(10)];
  lines = [lines length(files)];
end
lines = [0 lines];

disp('evaluating archive files ...')
t0 = clock;
for i = 1:numlines
  line = files((lines(i)+1):(lines(i+1)-1));
  if etime(clock,t0) > 10
    disp('still evaluating archive files ...')
    t0 = clock;
  end
%
%  Strip out any comments from the line
%
  lineLength = length(line);
  i = min(findstr(line,'%'));
  if ~isempty(i)
    line = line(1:i-1);
  end

  if ~isempty(deblank(line)) % If the line is blank, throw it away.

    while ~isempty(findstr(line,'  ')) 	% get rid of extraneous whitespace
      line = strrep(line,'  ',' ');
    end

    line = deblank(line);
    spaces = findstr(line,' '); 	% find number of files on the line
    num_args = length(spaces)+1;
    spaces = [0 spaces length(line)+1];

%
%  Extract the archive.m name
    arg = line((spaces(1)+1):(spaces(2)-1));

%
%  Check it against the datasets we already have.
    new = 1; DatasetNum = 1;
    for k = 1:num_sets
      if strcmp(arg,deblank(master_archives(DatasetNum,:)))
        new = 0; 
        break
      end
      DatasetNum = DatasetNum + 1;
    end

%  Check that the other files on this line are present and accounted for.
    for j = 2:num_args
      if exist(line((spaces(j)+1):(spaces(j+1)-1))) ~= 2
        disp(['Warning: Can''t find ' ...
               line((spaces(j)+1):(spaces(j+1)-1)) '.m ']);
      end
    end

%  Read the archive.m file and incorporate its metadata.
    if exist(arg) == 2
      GetFunctionName = ''; DataName = '';
      Resolution = NaN; TimeRange = [NaN NaN];
      LonRange = [NaN NaN]; LatRange = [NaN NaN]; 
      DepthRange = [NaN NaN];
      SelectableVariables = '';
      eval(arg) 		% EVALUATE THE ARCHIVE.M FUNCTION
  
      if ~isempty(GetFunctionName) & ~isempty(DataName)

%
%  Check metadata values, and prepare them to be incorporated into the
%  master data lists.

  	      %sort out Longitude range
	      if ~isempty(LonRange) & all(size(LonRange) == [1 2])
	        x = sort(LonRange);
	      end

	      % sort Latitude range
	      if ~isempty(LatRange) & all(size(LatRange) == [1 2])
	        y = sort(LatRange);
	      end

  	      % sort Depth range
	      if ~isempty(DepthRange) & all(size(DepthRange) == [1 2])
	        d = sort(DepthRange);
	      end

	      % sort Time range
	      if ~isempty(TimeRange) & all(size(TimeRange) == [1 2])
	        t = sort(TimeRange);
	      end

%
%  Add metadata values to master lists.
%
        if DatasetNum > num_sets
          master_datasets = str2mat(master_datasets, DataName);
          master_archives = str2mat(master_archives,arg);
          master_getxxx = str2mat(master_getxxx, GetFunctionName);
          num_sets = num_sets + 1;   % SET IS OFFICIALLY ADDED
          master_dataprops = [master_dataprops; zeros(1,num_vars)];
          master_resolutions = [master_resolutions; Resolution];
          master_rangemin = [master_rangemin; x(1) y(1) d(1) t(1)];
          master_rangemax = [master_rangemax; x(2) y(2) d(2) t(2)];
        elseif DatasetNum < num_sets
	  if DatasetNum == 1
	    master_datasets = str2mat(DataName, ...
		master_datasets((DatasetNum+1):num_sets,:));
	    master_archives = str2mat(arg, ...
		master_archives((DatasetNum+1):num_sets,:));
	    master_getxxx = str2mat(GetFunctionName, ...
		master_getxxx((DatasetNum+1):num_sets,:));
	  else
	    master_datasets = str2mat(master_datasets(1:(DatasetNum-1),:), ...
		DataName, master_datasets((DatasetNum+1):num_sets,:));
	    master_archives = str2mat(master_archives(1:(DatasetNum-1),:), ...
		arg, master_archives((DatasetNum+1):num_sets,:));
	    master_getxxx = str2mat(master_getxxx(1:(DatasetNum-1),:), ...
		GetFunctionName, master_getxxx((DatasetNum+1):num_sets,:));
	  end
          master_dataprops(DatasetNum,:) = zeros(1,num_vars);
          master_resolutions(DatasetNum) = Resolution;
          master_rangemin(DatasetNum,:) = [x(1) y(1) d(1) t(1)];
          master_rangemax(DatasetNum,:) = [x(2) y(2) d(2) t(2)];

        else % DatasetNum == num_sets

          master_datasets = str2mat(master_datasets(1:(DatasetNum-1),:), ...
                 DataName);
          master_archives = str2mat(master_archives(1:(DatasetNum-1),:), ...
                 arg);
          master_getxxx = str2mat(master_getxxx(1:(DatasetNum-1),:), ...
                 GetFunctionName);

          master_dataprops(DatasetNum,:) = zeros(1,num_vars);
          master_resolutions(DatasetNum) = Resolution;
          master_rangemin(DatasetNum,:) = [x(1) y(1) d(1) t(1)];
          master_rangemax(DatasetNum,:) = [x(2) y(2) d(2) t(2)];
        end

%
%  Now the dataset name and archive.m name are in the lists. Check to 
%  see whether the getxxx function used is one we have.

        if exist(deblank(master_getxxx(DatasetNum,:))) ~= 2
          disp(['Warning: Can''t find ' ...
                 deblank(master_getxxx(DatasetNum,:)) '.m ']);
        end
%
%  The dataset is added. Now we have to add the variables it contains
%  to the master_variables list, and adjust the master_dataprops array.
%  First check to see whether the variables are already in the master
%  lists.

        if ~isempty(SelectableVariables)
          for ii = 1:size(SelectableVariables,1)
            new = 1;
            for jj = 1:num_vars
              if strcmp(deblank(master_variables(jj,:)), ...
                        deblank(SelectableVariables(ii,:)))
                new = 0;
                break
              end
            end

	    if new
              master_variables = str2mat(master_variables, ...
                     deblank(SelectableVariables(ii,:)));
              if num_vars == 0
                master_variables = master_variables(2,:);
              end
              num_vars = num_vars + 1;
              master_dataprops = [master_dataprops zeros(num_sets,1)];
              master_dataprops(DatasetNum,num_vars) = 1; 
            else

              master_dataprops(DatasetNum,jj) = 1;
            end
          end % /* end of looping through SelectableVariables */
        end % /* if there are no selectable variables, we do nothing */


      else % /* missing GetFunctionName or DataName */
  
        disp(['Dataset ' arg ' cannot be added.  Missing GetFunctionName'])
        disp('or DataName -- Necessary metadata in the archive file.')
      end  
  
    else
  
      disp([' WARNING: archive ' arg ' in manifest unable to be read']) 
    end 
  end % end of if empty line 
end % end of looping through all lines in MANIFEST (i) 

%
%  Save the data in the browse data stash.

if (num_sets > 0 & num_vars > 0 & ...
      all(size(master_dataprops) == [num_sets num_vars]) & ...
      size(master_variables,1) == num_vars &  ...
      size(master_datasets,1) == num_sets & ...
      size(master_resolutions,1) == num_sets & ...
      all(size(master_rangemin) == [num_sets 4]) & ...
      all(size(master_rangemax) == [num_sets 4]) & ...
      size(master_archives,1) == num_sets & ...
      size(master_getxxx,1) == num_sets)
  % eliminate any variables with no datasets associated!
  i = find(sum(master_dataprops) == 0);
  if ~isempty(i)
    j = find(sum(master_dataprops) > 0);
    master_dataprops = master_dataprops(:,j);
    master_variables = master_variables(j,:);
    num_vars = length(j);
  end
  % deblank end of variable names
  i = sum(abs(master_variables) == 32);
  s = size(master_variables);
  while i(s(2)) == num_vars
    master_variables = master_variables(:,1:s(2)-1);
    i = sum(abs(master_variables) == 32);
    s = size(master_variables);
  end
  % .... and dataset names
  i = sum(abs(master_datasets) == 32);
  s = size(master_datasets);
  while i(s(2)) == num_sets
    master_datasets = master_datasets(:,1:s(2)-1);
    i = sum(abs(master_datasets) == 32);
    s = size(master_datasets);
  end
  
  % alphabetize both lists
  disp('Alphabetizing lists ...')
  % datasets ...
  tmplist = lower(master_datasets);
  s = size(tmplist);
  inx = 1:s(1);
  for k = s(2):-1:1
    [i j] = sort(tmplist(:,k));
    tmplist = tmplist(j,:);
    inx = inx(j);
  end
  master_datasets = flipud(master_datasets(inx,:));
  master_archives = flipud(master_archives(inx,:));
  master_getxxx = flipud(master_getxxx(inx,:));
  master_rangemin = flipud(master_rangemin(inx,:));
  master_rangemax = flipud(master_rangemax(inx,:));
  master_resolutions = flipud(master_resolutions(inx,:));
  master_dataprops = flipud(master_dataprops(inx,:));
  % and variables
  tmplist = lower(master_variables);
  s = size(tmplist);
  inx = 1:s(1);
  for k = s(2):-1:1
    [i j] = sort(tmplist(:,k));
    tmplist = tmplist(j,:);
    inx = inx(j);
  end
  master_variables = flipud(master_variables(inx,:));
  master_dataprops = fliplr(master_dataprops(:,inx));

  % now save the file to harddisk
  fname = [dodsdir 'brsdat2'];
  string = [' master_getxxx master_rangemax master_rangemin ' ...
	  'master_resolutions master_variables master_archives ' ...
	  'master_dataprops master_datasets '];
  if VERSION < 5
    eval(['save ' fname string])
  else
    eval(['save -v4 ' fname string])
  end
%
%  Reset things that need resetting:
%
%     Reset the VARIABLES list
  scroll('vreset')
	
%
%     Reset the LONGITUDE RANGE (must do before the dataset list)
  temp = master_georange;
  master_georange = [-180 180 -90 90];
  rangemin = master_rangemin(:,1);
  rangemax = master_rangemax(:,1);
  for i = 1:num_sets
    x = xrange('range', master_georange, [master_rangemin(i,1) master_rangemax(i,1)]);
    if max(size(x) == 2)
      rangemin(i) = x(1); rangemax(i) = x(2);
    else
      rangemin(i) = x(1); rangemax(i) = x(4);
    end
  end
  master_georange = temp;
  
%
%     Reset the DATASET LIST

  l = size(plotcolors,1);
  for i = 1:num_sets
    ii = rem(i,l)+1;
    datacolor(i,:) = plotcolors(ii,:);
  end
  scroll('datset')
  selected_datasets = zeros(size(master_datasets,1),1);
  
  disp('       ')
  disp('                Finished Updating datasets     ')
  disp('       ')
else
  % If we are here, there is serious, but unexplained, trouble.
  disp('       ')
  disp('  Problem with primary array sizes. Unable to complete update! ')
  disp('       ')

  % Bail out and reload old stuff
  fname = [dodsdir 'brsdat2'];
  eval(['load ' fname])
end

%
%  End

return

