function [PDMeasAreas,halfwaypoints]=PerpDropAreas(x,y,startX,endX,MaxVector)
% function [AreaVector]=PerpDropAreas(x,y,startx,endx,MaxVector) Measures
% the peak areas of the peak in x,y, starting an x value of startX and
% ending at endX, with specified peak positions in the vector MaxVector,
% which can be of any length. Uses the halfwaypoint method. Returns the
% areas in the vector PDMeasAreas and optionally the midpoint indices in
% halfwaypoints. Version 1.1, Oct 2020, toh@umd.edu
%
% Example:
% x=[0:.01:18];
% y=exp(-(x-5).^2)+2*exp(-(x-9).^2)+3*exp(-(x-12).^2)+4*exp(-(x-14).^2);
% PDMeasArea=PerpDropAreas(x,y,2,18,[4 9 12 14])
%
if nargin==4,MaxVector=0;end
L=length(MaxVector);
startpoint=round(val2ind(x,startX));
endpoint=round(val2ind(x,endX));
if L>1
for n=1:length(MaxVector)
    peakpoint(n)=val2ind(x,MaxVector(n));
end
for n=1:L-1
    halfwaypoints(n)=round((peakpoint(n+1)+peakpoint(n))/2);
end
PDMeasAreas(1)=trapz(x(startpoint:halfwaypoints(1)),y(startpoint:halfwaypoints(1))); % area
for segment=2:L-1
    PDMeasAreas(segment)=trapz(x(halfwaypoints(segment-1):halfwaypoints(segment)),y(halfwaypoints(segment-1):halfwaypoints(segment))); % area
end
PDMeasAreas(L)=trapz(x(halfwaypoints(L-1):endpoint),y(halfwaypoints(L-1):endpoint));
else
    PDMeasAreas=trapz(x(startpoint:endpoint),y(startpoint:endpoint));
    halfwaypoints=(startX+endX)/2;
end
function [index,closestval]=val2ind(x,val)
dif=abs(x-val);
index=find((dif-min(dif))==0);
closestval=x(index);