function varargout = vecplot(x,y,u,v,varargin)
% h = vecplot(x,y,u,v)
%
% SYNTAX:
%   h = vecplot(x,y,u,v,'PropertyName',PropertyValue,...)
%   h = vecplot(u,v,'PropertyName',PropertyValue,...)
%
% INPUT:
%   x,y = Position Coordinates
%   u,v = Vector Componentes
%
% PROPERTIES:
%   'DataAspectRatio' = Scaling factor between x and y axes
%       This is set as the second element of the property 'DataAspectRatio'
%   'LengthScale' = Length scaling factor for the barbs or arrows
%   'LineSpec' = Line specification string syntax  (default '-k^')
%           (e.g. '^k' - plots black arrows, 'k' - plots black sticks)
%   'Linewidth' = Linewidth
%   'Marker' = '^' for triangle arrows, 'v' for angled arrows,
%              and '' for stick plots (default stick)
%   'MarkerFaceColor' = Arrow fill color (default none)
%   'MarkerEdgeColor' = Arrow edge color (default line color)
%   'MarkerSize' = Marker size
%   'LegendLength' = Sets the length of the legend vector
%   'LegendUnits' = Sets the units for the legend vector
%   'legendPosition' = Sets the legend position (normalized units 0-1)
%   'Color' = Sets the line and arrow color. Can be a 1D scalar array,
%             nx3 rgb color array, or string.
%
% OUTPUT:
%   h = handle with plot objects
%
% written by Alex Sanchez

if nargin==0
    vecplotdemo    
    return
end

%Default values
dar = [];  %data aspect ratio [1 dar 1]
ra = [];   %length scaling
w = 1;     %linewidth
co = 'k';  %line and edge color for marker
st = '-';  %linestyle
m = [];    %marker type, either '' or '^'
mfc = '';  %marker face color
mec = 'k'; %marker edge color
ms = 1;    %marker size
msx = [];
msy = [];
rv = 0;   %scale vector length
vxy = [];  %scale vector position
vu = [];   %scale vector units

%Check input
if nargin==2
   u = x;   v = y;
   x = 1:length(x); y = 0*x;
elseif nargin==1 || nargin==3
    error('Invalide number of input arguments')
elseif nargin>=4
    if ischar(u)
        varargin{end+1} = u; varargin{end+1} = v;
        u = x; v = y;
        x = 1:length(u); y = 0*x;
    end
end

%Get properties
for i=1:2:length(varargin)-1
    switch lower(varargin{i})
        case 'dataaspectratio'
            dar = varargin{i+1};
            if length(dar)>1
                dar = dar(2)/dar(1);
            end
        case 'lengthscale'  
            ra = varargin{i+1};
        case 'color' 
            co = varargin{i+1};
        case 'linestyle'
            st = varargin{i+1};
        case 'linewidth'
            w = varargin{i+1};    
        case 'marker'
            m = varargin{i+1}; %'^' Arrow, '' None
        case 'markerfacecolor'  
            mfc = varargin{i+1};
        case 'markersize'  
            ms = varargin{i+1};
        case 'markersizex'  
            msx = varargin{i+1};
        case 'markersizey'  
            msy = varargin{i+1};     
        case 'linespec'
            [st,co,m] = colstyle(varargin{i+1}); 
        case 'legendlength'
            rv = varargin{i+1};
        case 'legendunits'
            vu = varargin{i+1};
        case 'legendposition'
            vxy = varargin{i+1};
            if length(vxy)==1
                vxy(2) = vxy(1);
            end
        otherwise
            warning(['Unidentified Property: ',varargin{i}])
    end
end

%Check for unassigned variables
if isempty(dar)
   dar = 1;
end
if isempty(ra)
   ra = 1; 
end
if isempty(x)
   x = 0:length(x)-1; 
end
if isempty(y)
   y = 0*x;
end
if rv>0 && isempty(vxy)
    vxy = [0.8 0.8];    
end
if isempty(msx)
   msx = ms; 
end
if isempty(msy)
    msy = ms; 
end

%Preprocessing
ind = isfinite(u) & isfinite(v);
x = x(ind); y = y(ind); u = u(ind); v = v(ind); 
x = x(:);   y = y(:);   u = u(:);   v = v(:);  
u = u./dar; %Scaling

%Draw sticks or arrows
i = sqrt(-1);
if isempty(m) %Stick plot
    b = [0; 1; NaN]; %Stick
    ndim = 3;
elseif ~isempty(mfc) %Filled in arrow    
    b = [0; 1-0.2*ms; NaN]; %Stick
    ndim = 3;
else %Non-filled in arrow
    b = [0;1;1-0.2*msx;1;1-0.2*msx;NaN] + [0;0;0.1*msy;0;-0.1*msy;NaN]*i; %Arrow
    ndim = 6;      
end

z = (u + v*i).';
a = ra*b*z + ones(ndim,1)*x' + ones(ndim,1)*y'*i;
h = plot(a,st,'clipping','off','LineWidth',w);
if ischar(co) %constant color
    set(h,'color',co)
elseif min(size(co)) %scalar array
    map = colormap;
    ind = fix((co-min(co))/(max(co)-min(co))*(size(map,1)-1))+1;
    for i=1:length(h)
        set(h(i),'color',map(ind(i),:))
    end
elseif size(co,3)==3 %rgb array
	for i=1:length(h)
        set(h(i),'color',co(i,:))
    end 
end

if ~isempty(mfc) && ~isempty(m) %Fill-in arrow
    if strcmpi(m,'^')
        b = [1-0.2*msx;1;1-0.2*msx;1-0.2*msx] + [0.1*msy;0;-0.1*msy;0]*i;
    else %strcmpi(m,'v')
        b = [1-0.25*msx;1;1-0.25*msx;1-0.2*msx] + [0.1*msy;0;-0.1*msy; 0]*i;
    end
    
    ndim = 4;
    a = ra*b*z + ones(ndim,1)*x' + ones(ndim,1)*y'*i;
    h = [h; patch(real(a),imag(a),mfc,'edgecolor',mec)];
end

%Scale Bar
if rv>0
    yval = get(gca,'ylim');	
    xval = get(gca,'xlim');
    ydist = abs(yval(2)-yval(1));		
    xdist = abs(xval(2)-xval(1));
    px = xval(1) + vxy(1)*xdist;		
    py = yval(1) + vxy(2)*ydist;
    grad = px + py.*i;
    a = [1; 1]*grad - ra*[0; 1]*rv/dar;
    h = [h; line(real(a),imag(a), ...
        'color',co,'LineStyle',st',...
        'clipping','off','linewidth',w)];
    txt = sprintf('%g %s',rv,vu);
    h = [h; text(px,py,txt,'verticalAlign','bottom', ...
        'horizontalalign','left')];
end

set(gca,'PlotBoxAspectRatioMode','Manual')
set(gca,'DataAspectRatio',[1,dar,1],'PlotboxAspectRatio',[1,dar,1]);

if nargout>0
  varargout{1} = h;    
end

return

%********************************************
function vecplotdemo

%Example 1
u = linspace(0,-5,30);
v = linspace(-5,5,30);
dar = 0.5;
ra = 1;

figure
subplot(2,2,1)
feather(u,v)
title('feather.m')

subplot(2,2,2)
vecplot(u,v,'DataAspectRatio',dar,'LengthScale',ra,...
    'marker','^','markersize',0.5,'LegendLength',2,'LegendUnits','m/s',...
    'LegendPosition',[0.8 0.2])
title('vecplot.m')

%Example 2
[x,y] = meshgrid(-3:.2:3);
z = peaks(x,y);
[u,v] = gradient(z,.2,.2);
r = sqrt(x.^2+y.^2);
ind = r>3; u(ind) = NaN; v(ind) = NaN;

subplot(2,2,3)
quiver(x,y,u,v)
title('quiver.m')

subplot(2,2,4)
dar = 1; ra = 0.02;
vecplot(x,y,u,v,'DataAspectRatio',dar,'LengthScale',ra,'LineSpec','-b^')
set(gca,'xlim',[-4 4],'ylim',[-4 4])
title('vecplot.m')

%Example 3
load wind
figure
x = x(:,:,10); y = y(:,:,10);
u = u(:,:,10); v = v(:,:,10);
vecplot(x,y,u,v,'DataAspectRatio',1,'LengthScale',0.04,...
    'Marker','v','MarkerFaceColor','r','markersize',2,'linewidth',1)
axis equal

%Example 4
ind = 1:3:100;
x = x(ind); y = y(ind);
u = u(ind); v = v(ind);
figure
vecplot(x,y,u,v,'DataAspectRatio',1,'LengthScale',0.1,...
    'Marker','^','MarkerFaceColor','k','markersize',1,'linewidth',2)

return
