function err = error_global_map(X,Trans,W,rbar,Cab)

if nargin < 4, rbar = 0; end


if nargin >= 5
    do_cov = 1;
else
    do_cov = 0;
end

numM = size(Trans,2);
%unpack the X vector into positions

Twm = reshape(X,[3,numM]);

[i,j] = find(W);
ind = sub2ind(size(W),i,j);

Twij = zeros(3,numM,numM);

if 0
   
   Twij(:,ind) = mul_config(Twm(:,i),Trans(:,ind));
   Twij(3,ind) = mod(Twij(3,ind)+pi,2*pi)-pi;
   W3 = reshape(repmat(W(:)',[3 1]),[3 numM numM]);
   Twm2 = squeeze(sum(Twij.*W3,2)./sum(W3,2));
   
   err = Twm-Twm2;
   %err(3,:) = mod(err(3,:)+pi,2*pi)-pi;
else
   
   Twij(:,ind) = diff_config(Twm(:,i),Twm(:,j));
   err = diff_config(Trans(:,ind), Twij(:,ind));
   err(3,:) = mod(err(3,:)+pi,2*pi)-pi;
   
   if do_cov
       for i=1:length(ind)
           J = chol(inv(Cab(:,:,ind(i))));
           err(:,i) = J*err(:,i);
       end
   end
   
   if length(size(rbar))==3
       % rbar contains the sqrts of the transition covariances
       % use them to decorellate the error components
       for i=1:length(ind)
           err(:,i) = rbar(:,:,i)*err(:,i);
       end
   elseif (rbar > 0)
       dist2 = sum(err(1:2,:).^2);
       %weight = 1./(1 + dist2/rbar.^2);
       weight = rbar*sqrt(log(1+dist2/rbar.^2))./sqrt(dist2);
       err = weight([1 1 1],:).*err;
   end

   err = err.*repmat(W(ind)',3,1);
   
end
