//Prime form algorithm:
// Get the ordered form
// For every permutation
//  Calculate the span and find lowest span
// Get temporary Succsive interval array for lowest span and its inversion
//  compare two successive interval arrays
// Output prime form as an array

function primeForm(set) {
	//finds lowest span and smallest SIA.
	var temp = findMinSpan(stringToNumArray(set));
	//get the inversion as well
	var tempI = new Array();
	for (var i = 0; i < temp.length; i++) {
		tempI[temp.length - i - 1] = temp[0] - temp[i];
	}
	temp = normalize(temp);
	tempI = normalize(tempI);
	//we have the prime forms now...but the representation is off...fix any negatives.
	temp = fixNegatives(temp);
	tempI = fixNegatives(tempI);
	//debug(tempI);
	//debug(numArrayToString(tempI));
	tempI = findMinSpan(tempI);
	//debug(tempI);
	tempI = normalize(tempI);
	tempI = fixNegatives(tempI);
	//debug(tempI);
	return (normalize(findMinSIA(temp, tempI)));
}

function findMinSpan(array) {
	var span = 12;
	var minspan = span;
	var temp = array;
	var temp2 = new Array();
	copyArray(temp, temp2);
	var final = new Array(temp.length);
	for (var i = 0; i < array.length; i++) {
		if (temp[0] > temp[temp.length - 1])
			span = 12 - (temp[0] - temp[temp.length - 1]); 
		else
			span = temp[temp.length - 1] - temp[0];
		if (span < minspan) {
			minspan = span;
			//debug("findMinSpan: Found new minspan to be " + minspan + "and comparing temp and final.");
			copyArray(temp, final);
			//debug("findMinSpan: new final is" + final);
		}
		else if (span == minspan) {
			minspan = span;
			copyArray(findMinSIA(temp, final), final);

		}
		//permute the array once
		for (var j = 0; j < array.length; j++) {
			temp[j] = temp2[(i + j + 1) % temp2.length]
		}
		//debug("findMinSpan: temp is now " + temp + " and i is " + i + " and final is " + final);
	}
	return final;
}

//a and b must both be normalized (0 in the first spot)
function findMinSIA(a, b) {
	//compare the SIA of two arrays and returns the array with the smaller intervals "to the left"
	var min = "a";
	if ( a.length != b.length) {
		alert("findMinSIA: arrays are not equal length! (a is " + a.length + " and b is " + b.length + ")");
	}
	else {
		for (var i = 0; i < a.length - 1; i++) {
			// if first array has a smaller interval, escape
			if ( Math.abs(a[i + 1] - a[i]) < Math.abs(b[i + 1] - b[i]) ) {
				min = "a";
				i = a.length;
			}
			// if second array has smaller interval, switch to "b" and escape
			else if ( Math.abs(a[i + 1] - a[i]) > Math.abs(b[i + 1] - b[i]) ) {
				min = "b";
				i = a.length;
			}
			//if it's equal, keep on incrementing
			//if everything happens to be the same, then either a or B should be fine
		}
		//return the right array
		if ( min == "a")
			return a;
		else
			return b;
	}
}