function [DProf,data_new] = DProfile(imp_resp)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   Power delay Profile function:                (Raul de Lacerda, 27/03/2007)
%      [DProf,data_new] = DProfile(imp_resp)
%
%      DProfile is a function created to estimate the power delay profile of the 
%      files generated by the EMOS TestBed.
%      - imp_resp is the input file with the Impulse Responses dim(t,tau,Tx,Rx)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Nconv  = 9; % length of the sliding window (Odd Value)

%%% N_T   = Number of samples
%%% N_tau = Impulse response length
%%% N_Tx  = Number of TX antennas
%%% N_Rx  = Number of RX antennas
[N_t,N_tau,N_Tx,N_Rx]   = size(imp_resp);

if isempty(imp_resp)
    data_new = imp_resp;
    DProf = 0;
else

% Channel synchronization
data = abs(imp_resp).^2;
data_new = zeros(size(data));
tmp2 = zeros(1,N_tau);

%data_new = [data(:,end-20:end,:,:) data(:,1:end-21,:,:)];
for ii = 1:N_t,
    for jj = 1:N_Tx,
        for kk = 1:N_Rx,
            tmp1    = [data(ii,end-((Nconv-1)/2)+1:end,jj,kk)  data(ii,:,jj,kk) data(ii,1:(Nconv-1)/2,jj,kk)];  
            tmp2(1) = sum(tmp1(1:Nconv));
            for  aa = 2:N_tau,
                tmp2(aa) = tmp2(aa-1)-tmp1(aa-1)+tmp1(aa-1+Nconv);  
            end
            [tmp,pos] = max(tmp2);
            
            if pos == 20,
                data_new(ii,:,jj,kk) = data(ii,:,jj,kk);
            elseif pos > 20,
                data_new(ii,:,jj,kk) = [data(ii,pos-19:end,jj,kk) data(ii,1:pos-20,jj,kk)];
            else
                data_new(ii,:,jj,kk) = [data(ii,end-(20-pos)+1:end,jj,kk) data(ii,1:end-(20-pos),jj,kk)];
            end
        end
    end
end

DProf = zeros(1,N_tau);

% Power Delay profile
for aa = 1:N_tau,
    DProf(aa) = 0;
    for ii = 1:N_t,
        for jj = 1:N_Tx,
            for kk = 1:N_Rx,
               DProf(aa) = DProf(aa) + data_new(ii,aa,jj,kk);
            end
        end
    end
end
DProf = DProf/(N_t*N_Tx*N_Rx);

end