function [out1, out2, out3, out4, out5, out6] = gnsc20l(...
    mode, get_ranges, get_dset, get_vars, get_dset_stride, ...
    get_num_urls, get_georange, get_variables, get_archive, ...
    pass)

% This is the 'getxxx' function for the NSCAT level 2.0 50km data.
% version 1.1 28 March 1999 by pdh.
%
% version 1.2  4 March 1999 by paul hemenway
%               gone from MATLAB4 to MATLAB5
%               if this continues to work I'll be amazed.
% 
% version 1.2.1 5 March 1999 by paul hemenway
%               more work on adding rowstride.
%
% version 1.2.2 6 March 1999 by paul hemenway
%               initialize argout1 near rowstride definition.
%
% version 1.2.3 27 March 1999 by paul hemenway
%               changed the order of orbit selection
%               by putting the time into the nscat_50_orbits.m file
%
%%%
%%% This is the get function for NSCAT level 2.0 data. It is different from
%%% getrectg with daily/monthly catalog servers in that it accesses two
%%% special inventory files (orbit data and equatorial crossing data) in
%%% order to perform the catalog function.
%%%
%%% The types of values returned by this function depend one the input
%%% arguments. That is, this function is really three functions rolled into
%%% one. The formal parameter
%%% `mode' selects which of the three modes are
%%% performed. The parameters used to actually get the data (e.g., the
%%% space-time constraint) are stored in various global variables.
%%%
%%% mode: the strings `cat', 'datasize', or  `get'. 
%%%      `cat' returns a catalog of passes matching the current space-time
%%%                    constraint. 
%%%      'datasize' returns an estimate of the data to be downloaded.
%%%
%%%      `get'  formulates the URLs and obtains the requested data.
%%%
%%% pass: current pending request 
%%%
%%% Return values:
%%%
%%% When mode == `cat':
%%% out1: The inventory of requested passes.
%%% out2: A vector the length that is the size of the inventory.
%%% out3: Same as out2.
%%% out4: Vector of pass times in decimal years.
%%% out5: Number of passes.
%%%
%%% When mode == `datasize'
%%% out1: Megabytes in the request. (The data will be trimmed later.)
%%% out2: Number of passes.
%%%
%%% When mode == `get' 
%%% out1: The total dataset this pass concatinated into a long vector.
%%% out2: A vector of sizes of each data string in out1.
%%% out3: A vector of names of each data string in out1.
%%% out4: A vector of the indexnumbers of the variables selected.
%%% out5: A vector of the requested URLs.
%%%
%%% Functions called:
%%%
%%% nscat_50_EQ: This function is used to compute the equatorial crossings
%%%   used to build the inventory and to determine the pass subdirectory
%%%   to build the URL.
%%%
%%% nscat_50_inv: Given the crossings, build an inventory.
%%%
%%%
%%% Notes: 
%%%
%%% $Id: gnsc20l.m,v 1.6 2000/03/23 02:00:11 dbyrne Exp $


% ok, a little purusal shows that out5 is the urllist, I think.
% see the call to getxxx in the browser about line 206, in the 'getcat'
% section of the code.  See also the Matlab GUI manual, section 3.2 
%  on the "GET function".  


%
% Revision 1.22  1998/11/09 20:26:56  dbyrne
% *** empty log message ***
%
% Revision 1.5  1998/09/10 08:56:24  dbyrne
% Changed input to getfunctions so mode is first arg.
%
% Revision 1.4  1998/09/09 20:12:47  dbyrne
% Trying to bring this up-to-date.  Definitely not functional at the moment.
%
% Revision 1.3  1998/09/09 07:57:36  dbyrne
% replaced Data_Scale with DataScale, Data_Null with DataNull, and Data_Range
% with DataRange for consistency with other variables in the archive.m files.
%
% Revision 1.2  1998/09/09 07:40:21  dbyrne
% Replaced getrectangular with getrectg
%
% Revision 1.1  1998/05/17 14:18:04  dbyrne
% *** empty log message ***
%
% Revision 1.15  1997/12/09 20:00:07  jimg
% Fixed bug where number of URLs and dataset (accessed with `get' and
% num_passes == 0) was hosed. This function was returning a vector for the
% number of URLs when the caller expected an integer.
%
% Revision 1.14  1997/12/09 06:22:21  jimg
% Fixed broken index code.
% Added to comments about functions used.
%
% Revision 1.13  1997/12/09 03:41:30  jimg
% Fixed up comments.
% Added separate retrieval of Lat, Lon and wind values to minimize data
% transfered.
% Fixed bad return of time value.
%
% Revision 1.12  1997/11/22 01:08:08  jimg
% Fix annoying error about failure to assign output arguments.
%
% Revision 1.11  1997/11/22 00:49:30  jimg
% Marked remaining debugging statements. The calculation of dataset size
% appears to be correct but the value displayed by the browser is not right.
%
% Revision 1.10  1997/11/22 00:18:10  jimg
% Fixed up comments; addedd Log.
%

% Initialize return arguments:
out1 = []; out2 = []; out3 = []; out4 = []; out5 = []; out6 = [];

% the following copied from getrectg.m
% 26 december 1998   pdh
%
% these are used only locally
%
global Pass_Times old_var old_dset old_ranges

% set up globals:
global archive;		% Name of metadata `master' file for this dataset.
global Time;		% 2D array; start and stop time of dataset.
global ranges;		% Contains the current space-time constraint.
global orbits;		% The inventory built by this function.
global orbitsa orbitsd; % Inventory of ascending and descending orbits.
global nanswitch        % If=1, bad data are NaNs, if=0, bad data are zeros.
global have_informed  
% Global variable ascend will be used in nscatrows.m and nscatcols.m
global ascend;
global gotpasses  aE_old  aW_old  dE_old  dW_old;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% added 18mar00  pdh
nanswitch=1;
  
  
  
% **************
% added 5 March 1999, by pdh:
rowstride=get_dset_stride;
argout1=[];
%***************
  
% remove this whole thing.  It was a debugging tool.
% pdh 6 July 99
% only give users this annoying message once per session!
%if isempty(have_informed) 
%  % nanswitch is set here: 
%  nanswitch=1;
%  if nanswitch == 0
%    dodsmsg('bad data will be set to NaNs')
%  else
%    dodsmsg('bad data will be set to zeros')
%  end
%else
%  if have_informed == 0
%    nanswitch=1;
%    if nanswitch == 0
%      dodsmsg('bad data will be set to NaNs')
%    else
%      dodsmsg('bad data will be set to zeros')
%    end
%  end
%end

%have_informed = 1;

% test for the archive file:
if exist(get_archive) == 2
  eval(get_archive)
else
  dodsmsg(['Problem reading dataset metadata ' get_archive ' .m'])
end

if nargin >=1
  
  % Initialize return arguments:
  out1 = []; out2 = []; out3 = []; out4 = []; out5 = []; out6 = [];
  
  
  eval(archive);		% Source archive metadata
  
  
  % ***
  if (strcmp(mode, 'get') == 1)
    % fprintf('processing pass #: %d\n',pass)
%  todo:  I want to put in a puppd (popup,pause,popdown) message here.
%         up for 1.5 seconds, then down, just for information.
%         pdh 7 july 1999
  end
  
  % check the time ranges:
  if (get_ranges(4,1)>Time(2)) | (get_ranges(4,2)<Time(1))
    dodsmsg('Requested range does not overlap data.  Please respecify')
    return
  end
  
  % set the cross track limit based on the number of cross-track points:
  % numxtrackpts comes from the archive file above.
  xtlim=int2str(numxtrackpts - 1);
  
  % *************** Get the inventory *************
  
  % Extract constraint information from `ranges'.
  mintime = max(Time(1), ranges(4,1));
  maxtime = min(Time(2), ranges(4,2));
  minlon = ranges(1,1);
  maxlon = ranges(1,2);
  minlat = ranges(2,1); 
  maxlat = ranges(2,2);
  minlon1=[]; maxlon1=[]; minlon2=[]; maxlon2=[];
  if minlon < 0; minlon = minlon+360; end
  if minlon>maxlon; maxlon=maxlon+360; end
  
  
  % Compute the ascending and descending equatorial crossings that correspond
  % to orbits that fall within the given latitude/longitude box.

%%%%%%
% check to see if the orbits have been computed with the current ranges.
%
% if they have, we don't need to compute them again.
%
%%%%%%

  
    [aE aW dE dW] = nsc50EQ('CO', minlat, maxlat, minlon, maxlon);
  
    % Find all orbits which match the equatorial crossings above.
  
    [orbits,orbitsa,orbitsd] = nsc50orb(aE, aW, dE, dW,mintime,maxtime);


%%%%
% check to see if any orbits were found to cross the (lon,lat,time) boundaries.
%
%   pdh 6 July 1999
%%%%

    if isempty(orbits)
       dodsmsg('no data are available in the ranges specified');
       if strcmp(mode, 'get')
          out6=0;
       end
       return
    end
  
  
  
  % Select orbits which fall within the time constraint.
  % I put the following into nscat_50_orbits BEFORE the lan selection.
  % 27 March 1999, pdh
  
  %time_idx = find(orbits(:,2) >= mintime & orbits(:,2) <= maxtime);
  %orbits = orbits(time_idx,:);
  %timeida  = find(orbitsa(:,2)>=mintime & orbitsa(:,2) <= maxtime);
  %orbitsa= orbitsa(timeida,:);
  %timeidd  = find(orbitsd(:,2)>=mintime & orbitsd(:,2) <= maxtime);
  %orbitsd= orbitsd(timeidd,:);
  
  % If the request was `cat' return an inventory to the caller.
  if strcmp(mode, 'cat')
    
    %  the following was copied from getrectg.m
    %  26 dec 98  pdh
    %
    % save these values
    old_ranges = get_ranges;
    old_dset = get_dset;
    old_var = get_vars;
    
    out1 = orbits(:,1);			% orbit, date, crossing, # of lines
    out2 = zeros(size(orbits,1)); 
    out3 = out2; 
    out4 = orbits(:,2);			% 2nd column is decimal date
    out5 = size(orbits,1);
    out6 = [];
    
    dodsmsg(['Inventory completed: ' int2str(out5) ' orbits selected.']);
    
    return;
    
  elseif strcmp(mode,'datasize')
    % Return the approximate (very) size of the pending request.
    % Assume the caller wants all of every passes.
    % bad assumption! -- dbyrne.  Hacked a fix below. 
    % not a hack.  This is the right place to do it. -- pdh
    % better -- restrict estimate to latitude range. -- pdh 
    num_of_passes = size(orbits(:,1), 1);
    num_of_scans = 0;
    for p = 1 : num_of_passes
      num_of_scans = num_of_scans + orbits(p, 4);
    end
    
    % Each scan contains 4 matrices each of which contains 24 floating point
    % values (8 bytes each).
    %    out1 = (4 * 24 * 8 * num_of_scans) / (2^20);
    out1 = ((4 * 24 * 8 * num_of_scans) / (2^20))* ...
           ((maxlat-minlat)/150)/rowstride; % dbyrne 99/05/12,pdh 99/06/01
    out2 = num_of_passes;
    out3 = [];
    out4 = [];
    out5 = [];
    % ***
    dodsmsg(sprintf('%s\n%s', ...
	['Number of scans: ' int2str(num_of_scans)], ...
	['Mbytes: ' num2str(out1)]));
    return;
    
  else    % mode is 'get'
    
    
    %  see if dataset request has changed at all get inventory again.

    if isempty(old_var) | isempty(old_dset) | isempty(old_ranges)
      [x,y,z,t,n,URL] = gnsc20l('cat', get_ranges, get_dset, get_vars, ...
	  get_dset_stride, get_num_urls, get_georange, get_variables, ...
	  get_archive,pass);
      if isempty(n)
         n=0;
      end
      get_num_urls = n;
    end
    
    if size(get_vars) ~= size(old_var) | (get_dset ~= old_dset) | ...
	  any(any(get_ranges ~= old_ranges))
      [x,y,z,t,n,URL] = gnsc20l('cat',get_ranges, get_dset, get_vars, ...
	  get_dset_stride, get_num_urls, get_georange, get_variables, ...
	  get_archive,pass);
      if isempty(n)
         n=0;
      end
      get_num_urls = n;
    end
    
    if get_num_urls > 0
    % Return data for pass number `pass'
    
    % Process: 
    % 1) Read the latitude matrix and use that to determine which rows to
    % read; constrain subsequent reads to only those rows.
    % 2) Read the longitude matrix and get-variables, and constrain
    %   accordingly.
    % 3) process into U and V vector components.
    orb_num = orbits(pass, 1);
    
    File = sprintf('S20%05d.HDF.Z',orbits(pass,1));
    s2 = int2str(orbits(pass, 4) - 1);
    
    
    
    % Decide which of the descending or ascending part of the orbit crosses the
    %   selected area.
    
    %fprintf('aE aW dE dW: %f %f   %f %f\n',aE, aW, dE, dW)
    
    %*****************  ascending or descending orbit or both *************
    
    %  define an orbit-type for this orbit.  orbtyp
    %   orbit does not pass over the area:                 orbtyp = 0
    %       (this case should not happen)
    %   orbit passes over the area on the ascending pass:  orbtyp = 1
    %   orbit passes over the area on the descending pass: orbtyp = 2
    %   orbit passes over the area on BOTH asc and desc:   orbtyp = 3
    
    passlan=orbits(pass,3);
    passlanm = passlan-360;
    passlanp = passlan+360;
    
    % determine the orbit type:
    orbtyp = 0;
    if ((passlanm<=dE & passlanm>=dW)|(passlan<=dE & passlan>=dW)| ...
	  (passlanp<=dE & passlanp>=dW))
      orbtyp = 2;
    end
    
    if ((passlanm<=aE & passlanm>=aW)|(passlan<=aE & passlan>=aW)| ...
	  (passlanp<=aE & passlanp>=aW))
      orbtyp = orbtyp + 1;
    end
    
    
    % add the following to get the /L20/ subdirectory
    %       which is contained in the 5th column of INV50.
    
    
    % Read the latitude matrix
    Constraint = [LatitudeName '[0:' s2 '][0:' xtlim ']' ];
    URL = [Server,'/S',int2str(orbits(pass,5)),'/', File, '?', Constraint];

    loaddods(URL);
    % fprintf('the data have been returned...I can proceed\n');
    
    %**********************************************************************
    %*****************  determine the start and stop row vectors **********
    
    eval(sprintf( ...
	'[rowstart,rowstop]=swathrow(minlat,maxlat,%s,%f,%f);' ...
	,LatitudeName,DataScale(3,2),DataNull(3)))
    
    
    %     fprintf('the following is the size of %s before row selection\n', ...
    %              LatitudeName)
    %     eval(sprintf('size(%s)',LatitudeName))
    
    %**********************************************************************
    %   *******  concatinate the latitude swath segments *****************
    kkend=length(rowstart);
    latmtx=[];
    
    %*********************
    %  5 March 1999, pdh added rowstride:
    for kk=1:kkend
      eval(sprintf( ...
	  'latmtx=[latmtx; %s(rowstart(kk):rowstride:rowstop(kk),:)];', ...
	  LatitudeName))
    end
    %*********************
    
    eval(sprintf('%s=latmtx;',LatitudeName))
    
    %     fprintf('size of %s after row selection and concatination\n', ...
    %               LatitudeName)
    
    %     eval(sprintf('size(%s)',LatitudeName))
    %**********************************************************************
    %**********************************************************************
    
    %********* obtain and process the other variables *********************
    %*********                                        *********************
    
    % get the sizes of the get_ and compute_ and Selectable variable name arrays:
    
    svs1=size(SelectableVariables,1);
    svs2=size(SelectableVariables,2);
    gvs1=size(get_variables,1);
    gvs2=size(get_variables,2);
    cvs1=size(compute_variables,1);
    cvs2=size(compute_variables,2);
    
    % initialize the the variables and their temporaries:
    
    eval(sprintf( ...
	'%stmp=[];', ...
	LongitudeName))
    
    for k=1:svs1
      swn=deblank(SelectableVariables(k,:));
      eval(sprintf( ...
	  '%s=[];', ...
	  swn))
      eval(sprintf( ...
	  '%stmp=[];', ...
	  swn))
    end
    
    % do all swath segments:
    
    for isegment=1:length(rowstart)
      row_start=rowstart(isegment);
      row_stop = rowstop(isegment);
      
      
      %   [row_start, row_stop] = nscatrows(minlat, maxlat, eval(LatitudeName));
      
      % NB: subtract 1 from indices because DODS uses 0-based indexing.
      
      %******************************
      %   old line:
      %   row_constraint = [ '[' int2str(row_start-1) ':' int2str(row_stop-1) ']' ];
      % add row stride
      % changed 4 March 1999 by pdh:
      row_constraint = [ '[' int2str(row_start-1) ':' int2str(rowstride) ':' ...
	    int2str(row_stop-1) ']' ];
      %******************************
      
      % Set up the longitude matrix:
      Constraint = [LongitudeName       row_constraint '[0:' xtlim ']' ];
      
      conflag=zeros(svs1,1);
      
      % Set up the other "selected" data matrices:
      for k=1:gvs1
	%        gwn is the 'get' working name of the current variable
	%        cwn is the 'compute' working name of each computed variable
	gwn=deblank(get_variables(k,:));
	
	%        test the current name against the list of variables that must
	%        be computed
	gwntest=0;
	for kk=1:cvs1
	  cwn=deblank(compute_variables(kk,:));
	  if length(cwn) == length(gwn)
	    if cwn==gwn
	      gwntest=1;
	    end
	  end
	end
	
	%        if the variable is not a computed variable, 
	%             make a constraint for it, and set the constraint flag.
	
	if gwntest==0
	  for kflag=1:svs1
	    if strcmp(deblank(SelectableVariables(kflag,:)),gwn)
	      conflag(kflag)=1;
	    end
	  end
	  if strcmp(gwn,'Wind_Speed') | strcmp(gwn,'Wind_Dir')
	    newconstraint= [gwn row_constraint '[0:' xtlim '][0:0]' ];
	  else
	    newconstraint=[gwn row_constraint '[0:' xtlim ']' ];
	  end
	  Constraint = [Constraint ',' newconstraint];
	end
      end
      %
      
      % check the computed variable dependencies:  
      
      %   Loop through the computed variables.
      for kc=1:cvs1
	
	%   if this computed variable is a get_variable, then process it.
	for kg=1:gvs1
	  if strcmp(deblank(compute_variables(kc,:)), ...
		deblank(get_variables(kg,:)))
	    
	    %   If a computed variable requires a SelectableVariable without a
	    %                     set constraint flag,
	    %             make a constraint for the SelectableVariable, and 
	    %             set the constraint flag.
	    %
	    %   Set up the dependencies for THIS COMPUTED variable:
	    
	    eval(sprintf( ...
		'cvdkc=cvdependencies%d;', ...
		kc))
	    
	    %       loop through the independent variables for THIS COMPUTED variable:
	    for ki=1:size(cvdkc,1)
	      
	      %        loop through the SelectableVariables:
	      for ks=1:svs1
		swn=deblank(SelectableVariables(ks,:));
		
		if strcmp(deblank(cvdkc(ki,:)),swn)==1 & conflag(ks)==0
		  
		  % WARNING WARNING WARNING:  THE FOLLOWING IS DATASET DEPENDENT!
		  
		  newconstraint= [swn row_constraint '[0:' xtlim '][0:0]' ];
		  
		  conflag(ks)=1;
		  Constraint = [Constraint ',' newconstraint];
		  % fprintf('processed a constraint for %s\n',swn);
		  
		end
		
	      end % SelectableVariable loop
	    end % independent variable loop
	  end
	end
      end % computed variables loop
      
      %*******************************************************************
      
      
      URL = [Server,'/S',int2str(orbits(pass,5)),'/', File, '?', Constraint];

      loaddods(URL);
      
      % fprintf('the data have been returned...I can proceed\n');
      
      %************* concatenate the variable swath segments ************
      
      %  note:  do not concatenate the computed variables.  
      %         They are not computed yet!
      
      %  loop through the variables (don't forget the longitude variable):
      
      % OK, OK, so if MATLAB gets a single scan, then it takes it as a
      %   COLUMN VECTOR rathar than a ROW VECTOR.  UG!
      
      szln=0;
      eval(sprintf( ...
	  'szln=size(%s,2);', ...
	  LongitudeName))
      if szln==1
	eval(sprintf( ...
	    '%stmp=[%stmp; %s''];', ...
	    LongitudeName,LongitudeName,LongitudeName))
      else
	eval(sprintf( ...
	    '%stmp=[%stmp; %s];', ...
	    LongitudeName,LongitudeName,LongitudeName))
      end
      
      for k=1:svs1
	
	swn = deblank(SelectableVariables(k,:));
	
	% Concatinate the variables:
	
	if szln==1
	  
	  eval(sprintf( ...
	      '%stmp=[%stmp; %s''];', ...
	      swn,swn,swn))
	else
	  
	  eval(sprintf( ...
	      '%stmp=[%stmp; %s];', ...
	      swn,swn,swn))
	end
	
	
      end  %end loop through the variables
      
    end %end swath segments
    %************************************************************************
    
    % ** NOW RE-ESTABLISH THE VARIABLES TO THEIR ORIGINAL NAMES: ************
    
    % loop through the dataset variables and reset them to their temporaries:
    %        again, don't forget the longitude variable:
    
    eval(sprintf( ...
	'%s=%stmp;', ...
	LongitudeName,LongitudeName))
    
    
    for k=1:svs1
      swn=deblank(SelectableVariables(k,:));
      
      %    Rename the variables:
      eval(sprintf('%s=%stmp;',swn,swn))
      
    end % end 2nd loop through variables
    
    
    %********************************************************************
    
    %****************** filter the longitudes ***************************
    
    %   THIS REPLACES nscatcols, sort of
    %   fprintf('filtering longitudes\n')
    
    %   start by filtering the longitude matrix with the latitude filter
    %   to make the longitude matrix conform to the latitude matrix.
    
    %   eval(sprintf('%s=%s.*latndx;',LongitudeName,LongitudeName));
    
    %   take care of the 4 cases, plus the case
    %   of someone specifying reverse longitudes in the text window.
    %   note that the simple case of 0<minlon<maxlon is the default case (1).
    loncase=1;
    if minlon>maxlon
      % fprintf('maxlon must be larger than minlon\n')
      return;
    elseif minlon<0 & maxlon<0
      loncase=2;
      minlon=minlon+360; maxlon=maxlon + 360;
    elseif minlon<0 & maxlon>0
      loncase=3;
      minlon1=0; maxlon1=maxlon;
      minlon2=minlon+360; maxlon2=360;
    elseif minlon<360 & maxlon>360
      loncase=4;
      minlon1=0; maxlon1=maxlon-360;
      minlon2=minlon; maxlon2=360;
    end
    
    
    %   set the longitude index matrix:
    %     need to scale minlon and maxlon:
    upscale=1/DataScale(2,2);
    
    % let's do longitude and latitude at the same time:
    strlat=sprintf( ...
	'(%s>=minlat*upscale)&(%s<=maxlat*upscale)', ...
	LatitudeName,LatitudeName);
    
    if loncase<=2
      strstr=sprintf('(%s>=minlon*upscale)&(%s<=maxlon*upscale);', ...
	  LongitudeName,LongitudeName);
      eval(['lonndx=' strlat '&' strstr]);
    else
      strstr1=sprintf('(%s>=minlon1*upscale&%s<=maxlon1*upscale)', ...
	  LongitudeName,LongitudeName);
      strstr2=sprintf('(%s>=minlon2*upscale&%s<=maxlon2*upscale)', ...
	  LongitudeName,LongitudeName);
      eval(['lonndx=' strlat '&(' strstr1 '|' strstr2 ');']);
    end
    
    %   filter the longitude and latitude arrays:
    
    %    LongitudeName=LongitudeName.*lonndx;
    eval(sprintf('%s=%s.*lonndx;',LongitudeName,LongitudeName))
    %    LatitudeName = LatitudeName.*lonndx;
    eval(sprintf('%s=%s.*lonndx;',LatitudeName,LatitudeName))
    
    
    %********************************************************************
    
    %************** filter the other arrays with data *******************
    
    
    %   filter the other arrays that were specified:
    %     these array names are given in 'Selectable Variables'
    %     the arrays with the necessary data have conflag(k)=1.
    
    for k=1:svs1
      %     wn is the workingname of the current variable
      wn=deblank(SelectableVariables(k,:));
      if conflag(k)==1
	eval(sprintf('%s=%s.*lonndx;',wn,wn))
      end
    end
    
    
    
    %*******************************************************************
    
    %***************  compute the computed variables *******************
    
    
    gvs1=size(get_variables,1);
    gvs2=size(get_variables,2);
    for k = 1:gvs1
      if strcmp(deblank(get_variables(k,1:gvs2)), 'U_Wind')
	U_Wind = (Wind_Speed/100) .* sin(Wind_Dir * pi / 18000.0);
      elseif strcmp(deblank(get_variables(k,1:gvs2)), 'V_Wind')
	V_Wind = (Wind_Speed/100) .* cos(Wind_Dir * pi / 18000.0);
      end
    end
    
    %******************************************************************
    
    
    %******* eliminate the rows of lon and lat that are all zeros *****
    
    % nullrows=~any(lon')&~any(lat')
    
    %   find the bad rows
    eval(sprintf(  ...
	'nullrows = ~any(%s'')&~any(%s'');', ...
	LongitudeName,LatitudeName));
    
    %   find the good rows
    goodrows=~nullrows;
    
    
    % save only the good rows in all the variables:
    eval(sprintf( ...
	'%s=%s(goodrows,:);', ...
	LatitudeName,LatitudeName));
    
    eval(sprintf( ...
	'%s=%s(goodrows,:);', ...
	LongitudeName,LongitudeName));
    
    for k=1:gvs1
      gvn=deblank(get_variables(k,1:gvs2));
      eval(sprintf( ...
	  '%s=%s(goodrows,:);', ...
	  gvn,gvn));
    end
    
    %******************************************************************
    
    % test for nanswitch
    if ~isempty(nanswitch)
     if nanswitch==1
      %***************  set all (lat,lon)=(0,0) data to NaN *************
      %   % find where longitudes and latitudes are both zero
      %eval(sprintf( ...
%	  '[whr1,whr2]=find(%s==0 & %s==0);', ...
%	  LongitudeName,LatitudeName))
      findnanstr = sprintf('%s==0 & %s==0', ...
         LongitudeName,LatitudeName);
      for knan=1:gvs1
         gvn=deblank(get_variables(knan,1:gvs2));
         if strcmp(gvn,'Wind_Speed')|strcmp(gvn,'Wind_Dir')
            findnanstr=sprintf('%s & %s==0',findnanstr,gvn);
         end
      end
      
      eval(sprintf( ...
         '[whr1,whr2]=find(%s);', ...
         findnanstr));

      
      % matlab wants a matrix, so I'll give it a matrix:
      % we'll use the additive identity instead of the multiplicative identity.
      % all the variable matrices should have the same size by now!
      eval(sprintf( ...
	  'nantrix=zeros(size(%s));', ...
	  LongitudeName));
      for ivar=1:length(whr1)
	nantrix(whr1(ivar),whr2(ivar))=NaN;
      end
      
      %   
      %   set those locations to NaN for all variables.
      eval(sprintf( ...
	  '%s = %s + nantrix;', ...
	  LatitudeName,LatitudeName));
      
      eval(sprintf( ...
	  '%s = %s + nantrix;', ...
	  LongitudeName,LongitudeName));
      
      for k = 1:gvs1
	gvn=deblank(get_variables(k,1:gvs2));
	eval(sprintf( ...
	    '%s = %s + nantrix;', ...
	    gvn,gvn))
      end
      %******************************************************************
     end % end nanswitch == 1
    end % end nanswitch ~isempty
    
    %**************** which version of matlab are we in? **************
    
    VERSION = version; VERSION = str2num(VERSION(1));
    
    %******************************************************************
    
    
    %*********** construct lists to pass back to the browser ***********
    
    whichvariables = [];
    for i = 1:size(get_variables,1)
      for j = 1:size(SelectableVariables,1)
	if strcmp(deblank(get_variables(i,:)), ...
	      deblank(SelectableVariables(j,:)))
	  whichvariables = [whichvariables j];
	end
      end
    end
    if ~isempty(whichvariables)
      variablelist = DodsName(whichvariables,:); 
    else
      dodsmsg('gnsc20l: No variables were selected!')
    end
    
    %*******************************************************************
    
    
    %**************  Load up the return arguments.  *******************
    %
    %  the following was copied from getrectg.m, as an initial guess.
    %   pdh 27 dec 98.
    
    
    % now make up a list of all returned variables
    % (above list plus time, longitude, latitude, depth),
    % evaluate their sizes, scale them and convert nulls to NaNs.
    % this has to be a temporary variable list -- 'variablelist'
    % is still in use
    tmpvariablelist = str2mat(TimeName,LongitudeName,LatitudeName, ...
	DepthName, variablelist);
    tmpwhichvariables = [1 2 3 4 whichvariables+4];
    
    for i = 1:size(tmpvariablelist,1)
      tmpname = dods_dbk(tmpvariablelist(i,:));
      if VERSION < 5 % fix v4 bug
	if size(tmpname,2) > 19
	  tmpname = tmpname(1:19);
	end
      end
      if ~isempty(deblank(tmpname))
	if exist(tmpname) == 1
	  % make a temporary variable to work with
	  tmpout = eval(tmpname);
	  sizes(i,:) = size(tmpout);
	  sizesnew(i,1)=size(tmpout,1)*size(tmpout,2);
	  sizesnew(i,2)=1;
	  if exist('DataNull') == 1
	    if ~isnan(DataNull(tmpwhichvariables(i)))
	      j = find(tmpout == DataNull(tmpwhichvariables(i)));
              if ~isempty(j)
		tmpout(j) = NaN*j;
	      end
	    else
	      % do nothing because null values are already NaNs
	    end
	  end
	  % stack data in a column and scale it if possible
	  if exist('DataScale') == 1
	    if size(DataScale,1) ~= size(SelectableVariables,1)+4
	      dodsmsg(sprintf('%s\n%s', ...
		  'Data cannot be auto-scaled.', ...
		  ['Error is in ' get_archive '.m']))
	      argout1 = [argout1; tmpout(:)];
	    else
	      if ~isnan(DataScale(tmpwhichvariables(i),1))
		argout1 = [argout1; DataScale(tmpwhichvariables(i),1) + ...
		      tmpout(:)*DataScale(tmpwhichvariables(i),2)];
	      else % scale exists but is a nan -- don't scale
		argout1 = [argout1; tmpout(:)];
	      end
	    end
	  else % there is no DataScale
	    argout1 = [argout1; tmpout(:)];
	  end
	else % the supposedly returned variable DOES NOT EXIST 
	  % in this workspace.  Put in an empty placeholder.
	  if ~isempty(tmpname)
	    eval([tmpname '= [];'])
	  end
	  sizes(i,:) = [0 0];
	  sizesnew(i,:)=[0 0];
	end
      end
    end  %for size of tmpvariablelist
    % now convert variablelist to user-friendly names
    names = str2mat('Time','Longitude','Latitude', 'Depth', ...
	SelectableVariables(whichvariables,:));
    out1=argout1;
    out2=sizes;
    out3=names;
    out4=tmpwhichvariables;
    out5=URL;
   end   
   return;
  end
end % if nargin >= 1
