% function [matout,err] = xtract(mat,ivlow,ivhigh)
%  or
% function [matout,err] = xtract(mat,desiv)
%
%   Extract specified portion of a VARYING matrix, with
%   INDEPENDENT VARIABLE's values between IVLOW and IVHIGH.
%   XTRACT assumes that the INDEPENDENT VARIABLE value's are
%   sorted in ascending order. If only two input arguments 
%   are used, then the matrix whose INDEPENDENT VARIABLE's 
%   value is closest to the second input argument is 
%   extracted as a VARYING matrix (with one point).
%
%   ERR is set to -1 if IVLOW is greater than IVHIGH, ERR is
%   set to -2 if there are no INDEPENDENT VARIABLE values in
%   the range selected. ERR is set to -3 if the input matrix
%   is not a VARYING matrix. on a successful call, ERR is 
%   set to 0.
%
%   See also: SEL, VAR2CON, VPCK, VUNPCK, and XTRACTI.

function [matout,err] = xtract(mat,wlow,whigh)
  err = 0;
  if nargin < 2
    disp('usage: [matout,err] = xtract(mat,ivlow,ivhigh)')
    return
  end
  if nargin == 3
    if wlow > whigh
      if nargout == 2
        err = -1;
        return
      else
        error(['ivlow should be <= ivhigh'])
        return
      end
    end
  end
  [mtype,mrows,mcols,mnum] = minfo(mat);
  if mtype == 'vary'
    [nr,nc]=size(mat);
    omega = mat(1:mnum,nc);
    if nargin == 2
      [val,loc] = min(abs(omega-wlow*ones(mnum,1)));
      matout = vpck(mat((loc-1)*mrows+1:mrows*loc,1:mcols),mat(loc,mcols+1));
    else
      if max(size(omega)) == 1
        if omega(1) <= whigh & wlow <= omega(1)
         matout = mat;
        else
          if nargout == 2
            err = -2;
            out = [];
            return
          else
            error(['no INDEPENDENT VARIABLES in range selected'])
            return
          end
        end
      end
      % change ones(omega) into ones(size(omega)) Wes Wang, the MathWorks
      key = omega>=ones(size(omega))*wlow & omega<=ones(size(omega))*whigh;
      ptlow = min(find(key));
      pthigh = max(find(key));
      pt = [ptlow pthigh];
      if ~isempty(pt)
        matout = mat(mrows*(pt(1)-1)+1:mrows*pt(2),1:nc-1);
        newomega = omega(pt(1):pt(2));
        matout=vpck(matout,newomega);
      else
        if nargout == 2
          err = -2;
          return
        else
          error(['no INDEPENDENT VARIABLES in range selected'])
          return
        end
      end
    end
  else
    if nargout == 2
      err = -3;
      return
    else
      error(['input is not a valid VARYING matrix'])
      return
    end
  end
%
% Copyright MUSYN INC 1991,  All Rights Reserved
