function [ x_detrended ] = linear_trend(num_var,schindler_years,x)


% PURPOSE: LINEARLY DETREND THE VARIABLE OF INTEREST AND RETURN THE
% CYCLICAL COMPONENT
% 
% INPUT:
%     -num_var: NUMER OF TIME SERIES OF THE VARIABLE OF INTEREST
%     -schindler_years: NUMBER OF YEAR OF THE VARIABLE OF INTEREST
%     -x: VARIABLE OF INTEREST TO BE DETRENDED
%     
% OUTPUT:
%     -x_detrended: CYCLICAL COMPONENT OF THE VARIABLE OF INTEREST



%Recall variables defined in the main script
global num_c Countries

    schindler_years_list=(1995:1:2011);

    %Construct counter with # of years for the Schindler index
    for j=1:schindler_years
        t_b(j,1) = j;
    end

    %Create matrix of independet regressors
        % First column: vector of ones
        % second column: vector of years for Schindler index
    X_b = [ones(schindler_years,1) t_b(:,1)];

    %Calculate the beta coefficient for each country
    for j = 1:num_var
        for i=1:num_c
            B_b(:,j,i) = X_b\x(i,:,j)';
        end
    end

    %Calculate the trend and the detrended values of the index for each country
    for j = 1:num_var
        for i=1:num_c
            Th_b(:,:,i) = X_b*B_b(:,:,i);
            Th_b_permute=permute(Th_b, [3 1 2]);
            x_detrended(i,:,j) = x(i,:,j) - Th_b_permute(i,:,j);
        
%         figure(i)
%         plot(x(i,:,1), '-*b')
%         xlim([1,schindler_years]) 
%         set(gca,'Xtick', 1:5:schindler_years,'Xticklabel',schindler_years_list,'Fontsize', 6)
%         xlabel ('Years')
%         t=title(Countries(i,1));
%         set(t,'Fontsize',10)
%         ylabel('Index')
%         hold on
%         %Plot quadratic trend for each country
%         h = plot(Th_b_permute(i,:,1),'r','LineWidth',2);
%         k = legend(h,'Linear Trend Estimate');
%         set(k, 'Location', 'Southoutside');
%         hold off
%         box off

        end
    end

end

