% Unaligned rectangles
function F12 = RectRectView(flag,x,y,varargin)
  if strcmp(flag,'perp')
    [hy,z]=varargin{:};
    B=@(l,m,n,o)Bt(x(l),y(m),hy(n),z(o));
  elseif strcmp(flag,'para')
    [hx,hy,z]=varargin{:};
    B=@(l,m,n,o)Bp(x(l),y(m),hx(n),hy(o),z(end));
  else
    error('Unknown flag. Choose from ''perp'' or ''para''');
    return;
  end
  sum=0;
  for l=1:2
    for m=1:2
      for n=1:2
        for o=1:2
          sum=sum+(-1)^(l+m+n+o)*B(l,m,n,o);
        end
      end
    end
  end
  F12=sum/2/pi/(x(2)-x(1))/(y(2)-y(1));
end

function val=Bt(x,y,hy,hz)
  u=sqrt(x^2+hz^2);
  eps = 1.0e-10;
  if u < eps
    u = eps;
  end
  v=(y-hy)/u;
  val=(y-hy)*u*atan(v)-u^2/4*(1-v^2)*log(u^2*(1+v^2));
end

function val=Bp(x,y,hx,hy,z)
  u=x-hx;
  v=y-hy;
  p=sqrt(u^2+z^2);
  q=sqrt(v^2+z^2);
  val=v*p*atan(v/p)+u*q*atan(u/q)-z^2/2*log(u^2+v^2+z^2);
end 
