function[CI] = confidence_T(alpha, input_data, tail)

% reference: t_inv - https://www.mathworks.com/matlabcentral/answers/260564-how-to-implement-tinv-manually-without-statistics-and-machine-learning-toolbox
% Inputs:
%
% alpha
% standard_dev: standard deviation of sample
% size: number of data points in sample
% tail: 
%    if tail = 1; 1-tailed t-distribution
%    if tail = 2; 2-tailed t-distribution

%% Local functions

tdist2T = @(t,v) (1-betainc(v/(v+t^2),v/2,0.5));        % 2-tailed t-distribution
tdist1T = @(t,v) 1-(1-tdist2T(t,v))/2;                  % 1-tailed t-distribution

%% Calculations

v = length(input_data)-1;                               % degrees of freedom
SEM = std(input_data)/sqrt(length(input_data));         % Standard Error

if tail == 1
    t_inv = @(alpha,v) fzero(@(tval) (max(alpha,(1-alpha)) - tdist1T(tval,v)), 5);  % T-Statistic Given Probability ‘alpha’ & Degrees-Of-Freedom ‘v’  
    ts = t_inv(alpha,v);                                % T-Score  
end

if tail == 2
    t_inv = @(alpha,v) fzero(@(tval) (max(alpha,(1-alpha)) - tdist2T(tval,v)), 5);  % T-Statistic Given Probability ‘alpha’ & Degrees-Of-Freedom ‘v’  
    ts = t_inv(alpha,v);                                % T-Score
end

CI = mean(input_data) + ts*SEM;                         % Confidence Intervals                      

