
function D = backProp( X, Y, Thetas, lambda = 0 )

	L = length(Thetas) + 1;
    for c = 1:L-1,
        Deltas{c} = zeros(size(Thetas{c}));
    end

    m = size(X, 1);
    for i = 1:m,
        [y, a] = forwardProp( X(i,:)' , Thetas);
        delta{L} = a{L} - Y(i,:)';

        for j = L-1:-1:2,
            delta{j} = (Thetas{j})' * delta{j+1} .* ...
                                        (a{j} .* (1 - a{j}));
            delta{j} = delta{j}(2:end);
        end

        for c = 1:L-1,
           Deltas{c} = Deltas{c} + delta{c+1} * (a{c})';
        end
    end

	for c = 1:L-1,
		tmp = Deltas{c} ./ m;
        D{c} = tmp + lambda * Thetas{c};
        D{c}(:,1) = tmp(:,1);
        %----------------
        % D{c}(:,1) = Deltas(:,1) ./ m;
        % D{c}(:,2:end) = Deltas(:,2:end) ./ m + ...
        %                      lambda * Thetas{c}(:,2:end);
	end

end
