function [enu, xyze] = beam_enu(vel, varargin);
% function [enu, xyze] = beam_enu(vel, varargin);
%           (vel, H, P, R, 'geometry', 'concave', 'angle', 30)
%      or   (vel, HPR, 'geometry', 'convex', 'angle', 30)
%      key/value pairs are optional.
%      defaults are downward orientation, convex instrument,
%                and 30-degree beam angle.
%      enu includes east, north, up, and error velocity if the
%      key/value pair 'error', 1
%

% 99/10/22 modified for orientation and angle inputs.
% 2000/09/25 modified to optionally include error velocity in enu array.

convex = 1;
beam_angle_deg = 30;
include_ev = 0;


% Find, use, and remove either or both of the optional
% keyword/argument pairs.
for ii = (length(varargin)-1):-2:1
   if strcmp(varargin{ii}, 'geometry')
      if strcmp(varargin{ii+1}, 'concave')
         convex = 0;
      elseif ~strcmp(varargin{ii+1}, 'convex')
         help('beam_enu')
         error('unrecognized geometry value')
      end
      varargin(ii:ii+1) = [];
   elseif strcmp(varargin{ii}, 'angle')
      beam_angle_deg = varargin{ii+1};
      varargin(ii:ii+1) = [];
   elseif strcmp(varargin{ii}, 'error')
      include_ev = varargin{ii+1};
      varargin(ii:ii+1) = [];
   end
end

% Remaining arguments should be either the hpr array from
% adp.m, or separate arrays of heading, pitch, and roll.
nva = length(varargin);
if nva == 1,
   hpr = varargin{1};
   Pitch = hpr(:,2);
   Roll = hpr(:,3);
   Heading = hpr(:,1);
elseif nva == 3,
   Heading = varargin{1};
   Pitch = varargin{2};
   Roll = varargin{3};
else
   help('beam_enu')
   error('Cannot parse input arguments.')
end

if convex,
   geom_string = 'convex';
else
   geom_string = 'concave';
end

xyze = beam_xyz(vel, 'angle', beam_angle_deg, 'geometry', geom_string);

if (length(size(xyze)) == 2)
   enu = xyz_enu(xyze(1:3, :), Heading, Pitch, Roll);
else
   enu = xyz_enu(xyze(:, 1:3, :), Heading, Pitch, Roll);
end

if include_ev,
   enu = cat(2, enu, xyze(:,4,:));
end

