dalphaped <- function(x, shape=2, scale=1, log=FALSE){
  if(shape == 1L){
    y <- dexp(x=x, rate=scale, log = log)
  } else{
    n <- length(x)
    c1 <- exp(-scale*x)
    c2 <- shape^(1-c1)
    c3 <- scale*log(shape)/(shape - 1)
    if(log){
      y <- log(c3*c1*c2)
    } else{
      y <- c3*c2*c1
    }
  }
  y
}

# cumulative distribution function
palphaped <-  function(q, shape=2, scale=1, log.p=FALSE){
  # print(shape)
  if(shape==1L){
    y <- pexp(q=q, rate=scale, log.p = log.p)
  } else{
    c1 <- exp(-scale*q)
    c2 <- shape^(1-c1)-1
    c3 <- shape - 1
    if(log.p){
      y <- log(c2/c3)
    } else{
      y <- c2/c3
    }
  }
  y
}

# survival function 
salphaped <-  function(q, shape=2, scale=1, log.s=FALSE){
  if(shape==1L){
    y <- 1 - pexp(q=q, rate=scale)
    if(log.s){
      y <- log(y)
    }
  } else{
    c1 <- exp(-scale*q)
    c2 <- shape^(1-c1)-1
    c3 <- shape - 1
    if(log.s){
      y <- log(1-c2/c3)
    } else{
      y <- 1-c2/c3
    }
  }
  y
}


# quantile function
qalphaped <- function(p, shape=2, scale=1, log.p=FALSE){
  if(log.p){
    p <- exp(p)
  } 
  if(shape==1L){
    c3 <- qexp(p=p, rate=scale)
  } else{
    c1 <- log(shape) - log(p*(shape-1)+1)
    c2 <- log(shape)
    c3 <- (log(c2) - log(c1))/scale
  }
  c3
}

# random sampling function
ralphaped <- function(n, shape=2, scale=1){
  if(shape==1L){
    xr <- rexp(n=n, rate=scale)
  } else{
    u <- runif(n)
    xr <- qalphaped(u, shape = shape, scale=scale)
  }
  xr
}

rualphaped <- function(u, shape=2, scale=1){
  xr <- qalphaped(u, shape = shape, scale=scale)
  xr
}