% EE  392J
% PROJECT

% Ali Ercan and Ulrich Barnhoefer

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% function [Q,num] = qModifier(inQ,motion)
% This function gets the camera charge as a function of pixel positions and 
% frame numbers, and the trajectory of each point in the scene on pixel plane
% as input. It generates the averaged charge values of each pixel as a function
% of time as described in the project update report. It also outputs how many 
% values were averaged per pixel during the process
%
% Inputs: inQ       : The charge collected at each pixel as a fn of no of frames
%         motion    : The motion trajectory (cell array) last row of each pixel's 
%                     trajectory tells where to stop for that pixel
% Outputs: Q        : The averaged pixel charge values (zero padded to non-valid 
%                     charge values
%          num      : The number of averaged values per pixel
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function [Q,num] = qModifier(inQ,motion)

[m n T] = size(inQ);
Q = zeros(m,n,T);
num = zeros(m,n,T);
for i = 1:m
    for j=1:n
        traj = motion{i,j};
        initPoint = traj(1,1:2);
        [noPoints,dummy] = size(traj);
        noPoints = noPoints - 1;
        
        if noPoints<=0
            error('The motion trajectory is defined falsely - the number of rows in each cell has to be at least 2');
        end
        
        frames = traj(:,3);
        
        for k = 1:noPoints
            %k,pause;
            point = traj(k,1:2);
            frameStart = frames(k)+1;
            frameEnd =frames(k+1)-1;
            if k == noPoints
                frameEnd = frameEnd+1;
            end
            pointx = point(1);
            pointy = point(2);
                       
            originCharge = inQ(pointx,pointy,frameStart-1);
            QCoorx = initPoint(1);
            QCoory = initPoint(2);
            
            for frame = frameStart:frameEnd
                QCoort = frame-frameStart+2;
                inQCoorx = point(1);
                inQCoory = point(2);
                inQCoort = frame;
                Q(QCoorx,QCoory,QCoort)=Q(QCoorx,QCoory,QCoort)+inQ(inQCoorx,inQCoory,inQCoort)-originCharge;
                num(QCoorx,QCoory,QCoort)=num(QCoorx,QCoory,QCoort)+1;
            end
            %Q10= squeeze(Q(10,10,:))'
            %n10=squeeze(num(10,10,:))'
        end
        thisNum = squeeze(num(QCoorx,QCoory,:));
        nonzeroInd = find(thisNum~=0);
        Q(QCoorx,QCoory,nonzeroInd) = Q(QCoorx,QCoory,nonzeroInd)./num(QCoorx,QCoory,nonzeroInd);
    end
end

return;


            