.packageName <- "viadam"
"damangle" <- 
# the angle of a dam side with respect to the sloping 
# terrain in the direction normal to the dam axis (alfa) computed 
# from deflecting angle with respect to the direction of steepest 
# decent in a sloping coordinate system aligned with the terrain (phi), 
# the slope of the terrain (psi), and the steepest slope of the dam side (alfas)
function(phi,psi,alfas) {
if (any(phi<0) || any(phi>pi/2)) 
   stop("phi cannot be outside the range [0,pi/2]")
if (any(psi<0) || any(psi>pi/2)) 
   stop("psi cannot be outside the range [0,pi/2]")
if (any(alfas<0) || any(alfas>pi/2)) 
   stop("alfas cannot be outside the range [0,pi/2]")
tmp <- (sin(alfas)^2-(cos(phi)*sin(psi))^2)/(cos(psi)^2+(sin(phi)*sin(psi))^2)
if (any(tmp<0)) warning("inconsistent combination of angles")
asin(sqrt(ifelse(tmp>0,tmp,0))) + atan(sin(phi)*tan(psi))
}
mound.jump <- 
# Compute the ballistic trajectory of a jet formed by the 
# flow of an avalanche that hits a braking mound or a dam
function(u0,beta,h,psi,k,fph=0.004,dt=0.1)
{
	if (any(u0<0) || any(u0>999)) 
		stop("u0 cannot be outside the range [0,999]")
	if (any(beta<0) || any(beta>pi/2)) 
		stop("beta cannot be outside the range [0,pi/2]")
	if (any(h<0) || any(h>999)) 
		stop("h cannot be outside the range [0,999]")
	if (any(psi<0) || any(psi>pi/2)) 
		stop("psi cannot be outside the range [0,pi/2]")
	if (any(k<0) || any(k>1)) 
		stop("k cannot be outside the range [0,1]")
	if (!missing(k)) { 
		if (any(fph<0) || any(fph>0.1)) 
			stop("fph cannot be outside the range [0,0.1]")
        }
	if (!missing(dt)) { 
		if (any(dt<0) || any(dt>10)) 
			stop("dt cannot be outside the range [0,10]")
	}
        assign("gcpsi.mound.jump",9.82*cos(psi),envir=sys.frame(1))
        assign("gspsi.mound.jump",9.82*sin(psi),envir=sys.frame(1))
        assign("fph.mound.jump",fph,envir=sys.frame(1))
        dfun <- function(x,y) { u <- sqrt(y[3]^2+y[4]^2)
                c(y[3],y[4],gspsi.mound.jump-fph.mound.jump*u*y[3],
                -gcpsi.mound.jump-fph.mound.jump*u*y[4]) }
        u1 <- k*sqrt(u0^2-2*h*gcpsi.mound.jump)
        t <- 0
        y <- c(0,h,u1*cos(beta),u1*sin(beta))
        tt <- t
        xx <- y[1]
        yy <- y[2]
        ux <- y[3]
        uy <- y[4]
        uu <- u1
        while (y[2]>=0.0) {
                y <- viadam.runge.kutta(t,dt,y,dfun)
                t <- t+dt
                #print (paste(t,y[1],y[2],y[3],y[4]))
                #print (dfun(t,y))
                xx <- c(xx,y[1])
                yy <- c(yy,y[2])
                ux <- c(ux,y[3])
                uy <- c(uy,y[4])
                uu <- c(uu,sqrt(y[3]^2+y[4]^2))
        }
        l <- length(yy)
        x2 <- approx(yy[(l-1):l],xx[(l-1):l],xout=0)$y
        ux2 <- approx(yy[(l-1):l],ux[(l-1):l],xout=0)$y
        uy2 <- approx(yy[(l-1):l],uy[(l-1):l],xout=0)$y
        betalnd <- atan(-uy2/ux2)
        u2 <- sqrt(ux2^2+uy2^2)
        res <- c(u1,x2,x2*cos(psi),u2,betalnd)
        names(res) <- c("u1","x2","x2cpsi","u2","betalnd")
        par <- c(u0,beta,h,psi,k,fph,dt)
        names(par) <- c("u0","beta","h","psi","k","fph","dt")
        list(par=par,res=res,x=xx,y=yy,u=uu)
}
"mxphi" <- 
# compute the maximum deflecting angle and the corresponding shock angle
# that separates the weak and strong obliques shocks for a particular value 
# of the Froude number.
function(Fr, method=c("exact","approximate")) {
if (any(Fr<0) || any(Fr>999)) 
   stop("Fr cannot be outside the range [0,999]")
mthd <- switch(match.arg(method), exact = 1, approximate = 2)
if (mthd==1) {
   teta <- rep(NA,length(Fr))
   for (i in seq(along=Fr)) 
      teta[i] <- uniroot(viadam.mxdffn,lower=asin(1/Fr[i]),upper=pi/2-.Machine$double.eps,Fr=Fr[i])$root
   phi <- obliqueshock(teta,Fr)$phi
} else {
   phi <- pi/2 - 2^(3/4)/sqrt(Fr) - 2^(1/4)/6/Fr^1.5
   teta <- obliquenshock(phi,Fr)$teta
}
data.frame(teta=teta,phi=phi)
}

viadam.mxdffn <- 
# function used by mxphi
function(teta,Fr) {
cs <- cos(teta)
sn <- sin(teta)
tn <- tan(teta)
cs2 <- cs^2
sn2 <- sn^2
Fr2sn2 <- Fr^2*sn2
G  <- sqrt(1+8*Fr2sn2)
2*G*(G-1) - 16*cs2*Fr2sn2 - (1+(2*tn/(G-1))^2)*G*(G-1)^2*cs2
}
"obliquenshock" <- 
# compute various characteristics of an oblique shock 
# as functions of the deflecting angle (phi) and Froude number (F)
# using an approximation based on the flow against a normal shock
# with the speed of the normal component of the oblique flow
function(phi, Fr) {
if (any(phi<0) || any(phi>pi/2)) 
   stop("phi cannot be outside the range [0,pi/2]")
if (any(Fr<0) || any(Fr>999)) 
   stop("Fr cannot be outside the range [0,999]")
csphi <- cos(phi)
snphi <- sin(phi)
Fp <- Fr*snphi
Fp2 <- Fp^2
alfa  <- pi/6 - atan((9*Fp2-8)/Fp/sqrt(27*(16+(13+8*Fp2)*Fp2)))/3
h2ph1 <- (2*sqrt(6*Fp2+4)*cos(alfa)+1)/3
philt90 <- phi < pi/2-.Machine$double.eps
dlt   <- ifelse(philt90,csphi*snphi/(csphi^2*h2ph1-1),0)
if (any(dlt<0)) dlt[dlt<0] <- 0
teta  <- phi+dlt
cs <- cos(teta)
sn <- sin(teta)
tn <- tan(teta)
tndlt  <- dlt  # to the same approximation as other quantities
tndlt2 <- tndlt^2
csdlt <- sqrt(1/(1+tndlt2))
sndlt <- sqrt(tndlt2/(1+tndlt2))
ret <- data.frame(teta=teta, phi=phi, delta=dlt, h2ph1=h2ph1, 
  u2pu1=ifelse(philt90,cs/csdlt,0), 
  h2u2ph1u1=ifelse(philt90,sn/sndlt,0))
attr(ret,"Fr") <- Fr
attr(ret,"Fp") <- Fp
ret
}
"obliqueshock" <- 
# compute various characteristics of an oblique shock 
# as functions of the shock angle (teta) and Froude number (F)
function(teta, Fr) {
if (any(teta<0) || any(teta>pi/2)) 
   stop("teta cannot be outside the range [0,pi/2]")
if (any(Fr<0) || any(Fr>999)) 
   stop("Fr cannot be outside the range [0,999]")
cs <- cos(teta)
sn <- sin(teta)
tn <- tan(teta)
cs2 <- cs^2
sn2 <- sn^2
Fr2sn2 <- Fr^2*sn2
G   <- sqrt(1+8*Fr2sn2)
tnphi <- 4*sn*cs*(Fr2sn2-1)/(3+4*(Fr2sn2-1)*cs2+G)
tndlt <- 2*tn/(G-1)
tndlt2 <- tndlt^2
phi   <- atan(tnphi)
dlt   <- atan(tndlt)
csdlt <- sqrt(1/(1+tndlt2))
sndlt <- sqrt(tndlt2/(1+tndlt2))
ret <- data.frame(teta=teta, phi=phi, delta=dlt, h2ph1=tn/tndlt, u2pu1=cs/csdlt, h2u2ph1u1=sn/sndlt)
attr(ret,"Fr") <- Fr
ret
}
"phi2phi" <- 
# convert from a deflecting angle in a sloping coordinate system aligned 
# with the terrain (phi) to deflecting angle in a horizontal projection
# (phih), that is the angle between the avalanche direction and the dam
# axis in the map plane, or the other way around
function(phi,phih,psi) {
if (!missing(phi)) {
   if (any(phi<0) || any(phi>pi/2)) 
      stop("phi cannot be outside the range [0,pi/2]")
}
if (!missing(phih)) {
   if (any(phih<0) || any(phih>pi/2)) 
      stop("phih cannot be outside the range [0,pi/2]")
}
if (any(psi<0) || any(psi>pi/2)) 
   stop("psi cannot be outside the range [0,pi/2]")
ret <- NULL
if (!missing(phi) && !missing(phih)) stop("only one of phi or phih may be specified")
else if (!missing(phi)) { ret <- atan(tan(phi)/cos(psi)) }
else if (!missing(phih)) { ret <- atan(tan(phih)*cos(psi)) }
else stop("neither phi nor phih is given")
ret
}
"phicontour" <- 
# the "deflecting angle" of contour lines on a dam side computed 
# from deflecting angle with respect to the direction of steepest decent 
# in a sloping coordinate system aligned with the terrain (phi), 
# the slope of the terrain (psi), and the angle of the dam side with 
# respect to the sloping terrain in the direction normal to the dam axis
function(phi,psi,alfa) {
if (any(phi<0) || any(phi>pi/2)) 
   stop("phi cannot be outside the range [0,pi/2]")
if (any(psi<0) || any(psi>pi/2)) 
   stop("psi cannot be outside the range [0,pi/2]")
if (any(alfa<0) || any(alfa>pi/2)) 
   stop("alfa cannot be outside the range [0,pi/2]")
atan((sin(phi)*cos(psi)*sin(alfa)-sin(psi)*cos(alfa))/(cos(phi)*sin(alfa)))
}
runuph <-
# run-up height on a dam or an obstacle corresponding to both supercritical 
# overflow and downstream thickness of a shock
function(phih,u1,h1,psi,psip,alfa,k,kp,xi,hs)
{
if (any(phih<0) || any(phih>pi/2)) 
   stop("phih cannot be outside the range [0,pi/2]")
if (any(u1<0) || any(u1>999)) 
   stop("u1 cannot be outside the range [0,999]")
if (any(h1<0) || any(h1>999)) 
   stop("h1 cannot be outside the range [0,999]")
if (any(psi<0) || any(psi>pi/2)) 
   stop("psi cannot be outside the range [0,pi/2]")
if (any(psip<(-pi/2)) || any(psip>pi/2)) 
   stop("psip cannot be outside the range [-pi/2,pi/2]")
if (!missing(alfa)) {
   if (any(alfa<0) || any(alfa>pi/2)) 
      stop("alfa cannot be outside the range [0,pi/2]")
}
if (!missing(k)) {
   if (any(k<0) || any(k>1)) 
      stop("k cannot be outside the range [0,1]")
}
if (!missing(kp)) {
   if (any(kp<0) || any(kp>0.1)) 
      stop("kp cannot be outside the range [0,0.1]")
}
if (!missing(xi)) {
   if (any(xi<0) || any(xi>999999)) 
      stop("xi cannot be outside the range [0,999999]")
}
if (!missing(hs)) {
   if (any(hs<0) || any(hs>99)) 
      stop("hs cannot be outside the range [0,999]")
}
n <- max(length(phih),length(u1),length(h1))
if (missing(kp)) kp <- rep(0,n)
if (missing(xi)) xi <- rep(0,n)
if (missing(hs)) hs <- rep(0,n)
dHslp <- rep(0,n)
dHcrv <- rep(0,n)
cspsi <- cos(psi)
phi <- phi2phi(phih=phih,psi=psi) # atan(tan(phi)*cspsi)
snphi <- sin(phi)
csphi <- cos(phi)
u1n <- u1*snphi
Fr1 <- u1/sqrt(9.82*cspsi*h1)
Fr1n <- Fr1*snphi
if (missing(k)) {
   if (missing(alfa)) stop("Either k or alfa must be specified")
   a <- alfa
   a[a>60*pi/180] <- 60*pi/180
   k <- 0.75 + 0.1*(60-a*180/pi)/30
   k[a<30*pi/180] <- 1
   if (any(a<30*pi/180)) warning("Alfa less than 30 degrees is not recommended for a dam")
}
Hcr <- h1*(1/k + 0.5*(k*Fr1n)^2 - 1.5*Fr1n^(2/3))
hcr <- h1*Fr1n^(2/3)
if (any(Fr1n<k^(-3/2))) {
   Hcr[Fr1n<k^(-3/2)] <- 0
   warning("Hcr set to zero where Fr1n < k^(-3/2)")
}
hrp <- Hcr+hcr
mxp <- mxphi(Fr1,method="approx")$phi
if (any(phi>(mxp-10*pi/180) & phi<pi/2*0.99)) {
   warning("Deflecting angle(s) are greater than recommended (phi>(mxphi-10)); phi is set to pi/2 for such angles in shock computations")
   phi[phi>(mxp-10*pi/180)] <- pi/2
}
shk <- obliquenshock(phi,Fr1)
if (any(phi<pi/2*0.99)) {
   dHslp <- sqrt(2)*tan(psip)/(2*Fr1*csphi)*xi
   dHcrv <- sqrt(2)*(u1*csphi)^2/(2*Fr1*csphi*9.82*cspsi)*kp*xi
   dHslp[phi>=pi/2*0.99] <- 0
   dHslp[phi>=pi/2*0.99] <- 0
} else {
   dHslp <- 0
   dHcrv <- 0
}
hrmx <- apply(cbind(hrp,h1*shk$h2ph1+dHslp+dHcrv),1,max) + hs
hd <- vdamheight(phi,psi,alfa,hrmx)
par <- data.frame(phih=phih,u1=u1,h1=h1,psi=psi,psip=psip,alfa=alfa,k=k,kp=kp,xi=xi,hs=hs)
ret <- data.frame(phi=phi,Fr1=Fr1,u1n=u1n,Fr1n=Fr1n,Hcr=Hcr,hcr=hcr,hrp=hrp,
       teta=shk$teta,delta=shk$delta,h2=h1*shk$h2ph1,u2=u1*shk$u2pu1,
       dHslp=dHslp,dHcrv=dHcrv,hrmx=hrmx,hd=hd)
attr(ret,"par") <- par
ret
}
"sdamslope" <- 
# the steepest slope of a dam side computed from deflecting 
# angle with respect to the direction of steepest decent 
# in a sloping coordinate system aligned with the terrain (phi), 
# the slope of the terrain (psi), and the angle of the dam side with 
# respect to the sloping terrain in the direction normal to the dam axis
function(phi,psi,alfa) {
if (any(phi<0) || any(phi>pi/2)) 
   stop("phi cannot be outside the range [0,pi/2]")
if (any(psi<0) || any(psi>pi/2)) 
   stop("psi cannot be outside the range [0,pi/2]")
if (any(alfa<0) || any(alfa>pi/2)) 
   stop("alfa cannot be outside the range [0,pi/2]")
asin(sqrt((cos(phi)*sin(psi))^2 + (cos(psi)*sin(alfa)-sin(phi)*sin(psi)*cos(alfa))^2))
}
"vdamheight" <- 
# vertical dam height computed from dam height normal to the 
# terrain (h), deflecting angle with respect to the direction of steepest
# decent in a sloping coordinate system aligned with the terrain (phi), 
# the slope of the terrain (psi), and the angle of the dam side with 
# respect to the sloping terrain in the direction normal to the dam axis
function(phi,psi,alfa,h) {
if (any(phi<0) || any(phi>pi/2)) 
   stop("phi cannot be outside the range [0,pi/2]")
if (any(psi<0) || any(psi>pi/2)) 
   stop("psi cannot be outside the range [0,pi/2]")
if (any(alfa<0) || any(alfa>pi/2)) 
   stop("alfa cannot be outside the range [0,pi/2]")
if (any(h<0) || any(h>999)) 
   stop("h cannot be outside the range [0,999]")
hd <- (cos(psi)-sin(phi)*sin(psi)*cos(alfa)/sin(alfa))/(1-(cos(phi)*sin(psi))^2)*h
if (any(hd<0)) warning("inconsistent combination of angles")
hd
}
"vdamheightngi" <- 
# vertical dam height according to a formula from NGI reports 
# (equivalent to the function vdamheight) computed from dam height normal
# to the terrain (h), deflecting angle with respect to the direction of steepest
# decent in a sloping coordinate system aligned with the terrain (phi), 
# the slope of the terrain (psi), and the angle of the dam side with 
# respect to the sloping terrain in the direction normal to the dam axis,
# this function is only defined for validation purposes
function(phi,psi,alfa,h) {
if (any(phi<0) || any(phi>pi/2)) 
   stop("phi cannot be outside the range [0,pi/2]")
if (any(psi<0) || any(psi>pi/2)) 
   stop("psi cannot be outside the range [0,pi/2]")
if (any(alfa<0) || any(alfa>pi/2)) 
   stop("alfa cannot be outside the range [0,pi/2]")
if (any(h<0) || any(h>999)) 
   stop("h cannot be outside the range [0,999]")
gx <- cos(phi)*sin(psi)
gy <- -cos(psi)*sin(alfa)+sin(phi)*sin(psi)*cos(alfa)
gz <- -cos(psi)*cos(alfa)-sin(phi)*sin(psi)*sin(alfa)
xi <- acos((gy^2+gz^2)/sqrt(1-gx^2-gx^2*gz^2))
hd <- (cos(psi)*sin(alfa)-sin(phi)*sin(psi)*cos(alfa)+tan(xi)*cos(phi)*sin(psi))*h/sin(alfa)
hd
}
viadam.runge.kutta <- 
# One step of the fourth-order Runge-Kutta integration
# algorithm for a first order system of differential equations.
function(x,dx,y,f)
{
        w1 <- dx*eval(expression(f(x,y)))
        w2 <- dx*eval(expression(f(x+dx/2,y+w1/2)))
        w3 <- dx*eval(expression(f(x+dx/2,y+w2/2)))
        w4 <- dx*eval(expression(f(x+dx,y+w3)))
        y + (w1 + 2*w2 + 2*w3 + w4)/6
}
