function[variances] = calcVar(mlh,param,time,alt,range,type)
%This function computes the verical variance of the data for a given range.

% Inputs:
% - mlh: A vector of mixed layer heights to use as reference
% - var: A vector of data where it is necessary to compute the vertical
% variance
% -alt: A vector containing the altitudes
% - time: A vector of times for the data 
% - range: A range of altitude by which to compute the vertical variance
% (e.g., 200m,300m,400m) or times by which to compute the horizontal
% variance (e.g., 5,10,15,20...)
% - type: A string containing which variance calculation should be
% performed (e.g., "vertical" or "horizontal")

% Outputs:
% - variances: The vertical variance of the given altitude range. Same size
% as the original mlh cell array given. 

if contains(type,'vertical')
    variances = cell(size(mlh));
    for vector = 1:length(mlh)
        mlh_data = mlh{vector};
        mlh_data(isnan(mlh_data)) = 0;
%         disp(length(mlh_data))
        alt_data = alt{vector};
        time_data = time{vector};
%         disp(length(time_data))
        param_data = param{vector};
        variances{vector} = [];
        for i = 1:length(time_data)
            mlh_time = mlh_data(i);
            param_time = param_data(:,i);
            if (mlh_time ~=0)
                min_index = fix(interp1(alt_data,find(alt_data),mlh_time-range));
                max_index = fix(interp1(alt_data,find(alt_data),mlh_time+range));
                param_range = param_time(min_index:max_index);
                param_variance = var(param_range,"omitnan");
                variances{vector} = [variances{vector}, param_variance]; % store value into cell array
            else
                variances{vector} = [variances{vector}, nan]; % store NaN value into cell array
            end
        end
    end
end 

if contains(type,'horizontal')
    variances = cell(size(mlh));
    for vector = 1:length(mlh)
        mlh_data = mlh{vector};
        mlh_data(isnan(mlh_data)) = 0;
        alt_data = alt{vector};
        time_data = time{vector};
        param_data = param{vector};
        variances{vector} = [];
        for i = 1:length(time_data)
            mlh_time = mlh_data(i);
            if (mlh_time ~= 0)
                alt_index = fix(interp1(alt_data,find(alt_data),mlh_time));
                i_start = i - range;
                i_end = i + range;
                param_range = param_data(alt_index,i_start:i_end);
                param_variance = var(param_range,"omitnan");
                variances{vector} = [variances{vector}, param_variance]; 
                
            else
                variances{vector} = [variances{vector}, nan]; 
            end
        end
    end

end

end 










