function [y] = quadratic_trend(lenght, idx_first, data, label_y )

% PURPOSE: CALCULATE THE CYCLICAL COMPONENT OF GDP, REER AND CA USING A QUADRATIC DETREND. 
% PLOT THE TREND AND ACTUAL DATA
% 
% INPUT:
%     -lenght: LENGHT OF THE COUNTRY TIME SERIES
%     -idx_first:VECTOR WITH THE FIRST VALID OBSERVATION FOR EACH COUNTRY
%     -data: VARIABLE TO BE DETRENDED
%     -label_y: LABEL Y-AXIS FOR THE PLOTS
%     
% OUTPUT:
%     -y: DETRENDED VARIABLE
% 
%Recall variables defined in the main script
global num_c Countries Years

%Same procedure for each country
    for i=1:num_c

        %Construct a Matrix Counter with # of valid observations
        for j=1:lenght(i,1);
            t(i,j) = j; 
        end

    %Construct matrix of independent regressors
        %First column: vector of ones
        %Second column: corresponding vector of t
        %Third column: squared value of corresponding vector of t
    X= [ones(lenght(i,1),1) t(i,1:lenght(i,1))' (t(i,1:lenght(i,1)).^2)'];

    %Calculate the beta coefficient
    B = X\data(i,idx_first(i,1):end)';


    %Calculate Quadratic trend
    Th= X*B;

    %Calculate the deviations from the quadratic trend over last 17
    %observations
    y(i,:) = data(i,end-16:end) - Th(end-16:end,1)';
% 
%         figure(i)
%         plot(data(i,idx_first(i,1):end), '-*b')
%         xlim([1,lenght(i,1)]) 
%         set(gca,'Xtick', 1:5:lenght(i,1),'Xticklabel',Years(1,idx_first(i,1):5:end),'Fontsize', 6)
%         xlabel ('Years')
%         t=title(Countries(i,1));
%         set(t,'Fontsize',10)
%         ylabel(label_y(1,1))
%         hold on
%         %Plot quadratic trend for each country
%         h = plot(Th(:,1),'r','LineWidth',2);
%         k = legend(h,'Quadratic Trend Estimate');
%         set(k, 'Location', 'Southoutside');
%         hold off
%         box off
%         print( gcf(i), '-dpdf', '-append');
    end
    
    close all
end

