//Regular expression for something in the form XdY+/-Z, with X and +/-Z optional
diceRegex=/[0-9]{0,}[d|D][0-9]{1,}([+|-][0-9]{1,}){0,1}/

function d(sides) {
	return Math.ceil(Math.random()*sides)
}

function XdY(dice, sides) {
	results=0
	for (i=0; i<dice; i++) {
		results+=d(sides)
	}
	return results
}

function dFormParse(toCheck) {
	match=toCheck.match(diceRegex)
	if (match!=null) {
		return match[0]
	} else {
		return null
	}
}

function rollDForm(dForm) {
	dForm=dForm.toLowerCase()
	dIndex=dForm.indexOf("d")
	signIndex=dForm.indexOf("+")
	sign=true
	positive=true
	if (signIndex==-1) {
		positive=false
		signIndex=dForm.indexOf("-")
	}
	if (signIndex==-1) {
		signIndex=dForm.length
		sign=false
	}
	dice=0
	sides=0
	addOn=0
	
	if (dIndex==0) {
		dice=1
	} else {
		dice=dForm.substring(0,dIndex)
	}
	sides=dForm.substring(dIndex+1,signIndex)
	if (sign) {
		addOn=dForm.substring(signIndex+1)
		if (!positive) {
			addOn*=-1
		}
	}
	result=XdY(dice, sides)+(addOn/1)
	return result
}