U1.Gumbel<-function(x.obs,y.obs,dx,dy,lower=0.01,upper=50,U.plot=TRUE){

  n=length(x.obs)
  x.ox=x.obs[order(x.obs)]
  y.oy=y.obs[order(y.obs)]
  d.ox=dx[order(x.obs)]
  d.oy=dy[order(y.obs)]
  Sx.vec=cumprod(1-d.ox/n:1)
  Sy.vec=cumprod(1-d.oy/n:1)
  Sx.vec=c(1,Sx.vec[-n])
  Sy.vec=c(1,Sy.vec[-n])
  x.ox=as.numeric(levels(factor(sort(x.obs))))
  nx=length(x.ox)
  y.oy=as.numeric(levels(factor(sort(y.obs))))
  ny=length(y.oy)
  Sx.vec=numeric(nx)
  Sy.vec=numeric(ny)
  Sx=Sy=1
  for(i in 1:nx){
    Dx=sum((x.obs==x.ox[i])&(dx==1))
    Rx=sum(x.obs>=x.ox[i])
    Sx=Sx*(1-Dx/Rx)
    Sx.vec[i]=Sx
  }
  for(i in 1:ny){
    Dy=sum((y.obs==y.oy[i])&(dy==1))
    Ry=sum(y.obs>=y.oy[i])
    Sy=Sy*(1-Dy/Ry)
    Sy.vec[i]=Sy
  }
  Sx.vec=pmax(Sx.vec,1/n);Sy.vec=pmax(Sy.vec,1/n)

  U.func=function(theta){
    u=0
    for(i in 1:(n-1)){
      xi=x.obs[i];yi=y.obs[i];dxi=dx[i];dyi=dy[i]
      for(j in (i+1):n){
        xj=x.obs[j];yj=y.obs[j];dxj=dx[j];dyj=dy[j]
        Ox=(dxi&dxj)|(dxi&(!dxj)&(xi<xj))|((dxj)&(!dxi)&(xj<xi))
        Oy=(dyi&dyj)|(dyi&(!dyj)&(yi<yj))|((dyj)&(!dyi)&(yj<yi))
        if(Ox&Oy){
          xij=min(xi,xj);yij=min(yi,yj)
          Rij=sum( (x.obs>=xij)&(y.obs>=yij) )
          Sx=Sx.vec[sum(x.ox<=xij)];Sy=Sy.vec[sum(y.oy<=yij)]
          Sij=exp(-( (-log(Sx))^(theta+1)+(-log(Sy))^(theta+1) )^(1/(theta+1)))
          Wij=(2*log(Sij)-theta)/(log(Sij)-theta)/(theta-Rij*log(Sij))
          u=u+Wij*(  ((xi-xj)*(yi-yj)>0)-1+1/(2-theta/log(Sij))  )
        }
      }
    }
    u
  }

  if((U.func(lower)<0)&(U.func(upper)<0)){ theta=lower }else{
    theta=uniroot(U.func,lower=lower,upper=upper)$root
  }
  tau=theta/(theta+1)

  if(U.plot==TRUE){
    curve(U.func,lower,upper,xlab=expression(theta),
          ylab=expression(U[1](theta)))
    points(theta,U.func(theta),col="red",cex=1)
    abline(h=0,lty="dotted",col="blue")
  }

  return(c(theta=theta,tau=tau))
}
