function data_analysis = benford_analysis( data_in ,plot_yes_or_no)
%benford_analysis analyzes data in any array against Benford's Law
%   data_in can be any data in an array stored (preferably) as a double.
%   Strings won't work. The data is filtered for the leading digit, and
%   then the results plotted against Benford's Law. Super simple.

%%%% NOTE: The data is scrubbed to remove zeros and NaNs before proceeding.
%%%% first_dig_input can't handle this data, and Benford's Law doesn't
%%%% apply, so this is a reasonable assumption.

%scrubs data
data_in=nonzeros(data_in);
data_in=data_in(isfinite(data_in));

%counts number of datapoints
num_data_pts=numel(data_in);

%preallocates a holder for the leading digits of the same size as the
%scrubbed data
leading_digits=zeros(num_data_pts,1);

%gets the leaing digits
for i=1:num_data_pts
    leading_digits(i)=first_dig_input(data_in(i));
end

%sets up a variable to store the data about the leading digits
data_analysis=zeros(9,1);

%extracts the data about the leading digits
for i=1:9
    data_analysis(i)=numel(find(leading_digits==i));
end

%sets up a variable for the appropriately scaled benford's law predictions
benfords_law=zeros(9,1);

%gets the benford's law predictions by calculating the appropriately scaled
%benford's law to say ~30% of the data points should be a 1, etc...
for i=1:9
    benfords_law(i)=num_data_pts*(log10(i+1)-log10(i));
end

%sets up an X-axis variable for plotting below
X=1:9;


%plots the data against Benford's Law's Predictions if you ask it to
if plot_yes_or_no==1
    figure(1); plot(X,data_analysis,'--rs','LineWidth',2,...
                'MarkerEdgeColor','k',...
                'MarkerFaceColor','r',...
                'MarkerSize',10);
            hold all
    figure(1); plot(X,benfords_law,'--gs','LineWidth',2,...
                'MarkerEdgeColor','k',...
                'MarkerFaceColor','g',...
                'MarkerSize',10);
    h = legend('data','Benfords Law',2);
    set(h,'Interpreter','none')
end

end

