function [c] = black_scholes(S0, r, T, K, sigma, type)
% Computes the theoretical price of the european option
% via the Black-Scholes-Merton formula
%
%[C]
%   Returns the price of the option
%
%BLACK_SCHOLES(S0,R,T,K,SIGMA,TYPE)
%   S0  Prize of the stock now
%   R   Interest rate
%   T   Maturity
%   K   Strike price
%   SIGMA   Volatility
%   TYPE    Either 'call' or 'put'
%
%NOTES:
%   Except the parameter 'type', others can be vectors.

%% Input parameters handling
if nargin < 6; type = 'call'; end
if nargin < 5; sigma = 0.3; end
if nargin < 4; K = 100; end
if nargin < 3; T = 1; end
if nargin < 2; r = 0.05; end
if nargin < 1; S0 = 100; end

%% Computation task
% d1 ... d+, d2 ... d-
d1 = 1./(sigma.*sqrt(T)).*(log(S0./K) + (r + sigma.^2/2).*T);
d2 = d1 - sigma.*sqrt(T);
switch lower(type)
    case "call", c = S0.*normcdf(d1) - exp(-r.*T).*K.*normcdf(d2);
    case "put",  c = exp(-r.*T).*K.*normcdf(-d2) - S0.*normcdf(-d1);
    otherwise
        disp("Wrong type selected. Only 'call' and 'put' are allowed.")
end