var MidDisplacement = function( p ){

	var points = [];
	var iterations = 1;
	const roughness = 1;
	var vertical_displacement;
	let button;

	p.setup = function(){
		p.createCanvas(800, 500);
		p.frameRate(2);
		p.background(217);

		button = p.createButton('Reset Button')
		//button.position(p.width, p.height);
		button.mousePressed(p.resetSketch);
		p.initValues();
		
	}

	p.draw = function(){}

	p.bubbleSort = function() {
	    var length = points.length;
	    //Number of passes
	    for (var i = 0; i < length; i++) { 
	        //Notice that j < (length - i)
	        for (var j = 0; j < (length - i - 1); j++) { 
	            //Compare the x values
	            if(points[j].x > points[j+1].x) {
	                //Swap the numbers
	                var tmp = points[j];  //Temporary variable to hold the current number
	                points[j] = points[j+1]; //Replace current number with adjacent number
	                points[j+1] = tmp; //Replace adjacent number with current number
	            }
	        }        
	    }
	}

	p.mouseClicked = function(){
		if (iterations < 11){
			var pLength = points.length;

			for (var i = 0; i < pLength - 1; i++){

			 	var midX = (points[i].x + points[i + 1].x) / 2;
			 	var midY = (points[i].y + points[i + 1].y) / 2;
			 	midY += p.random(-vertical_displacement, vertical_displacement);
			 	
				points[pLength + i] = new dot(midX, midY);
			}

			iterations += 1;
			vertical_displacement *= 2 ** (-roughness);

			p.bubbleSort();

			p.clear();
			p.background(215);

			for (var i = 0; i < pLength; i++){
				p.strokeWeight(4);
				p.stroke(0);
				p.point(points[i].x * 2, points[i].y);

				p.strokeWeight(1);
				p.stroke(215, 15, 15);
				p.line(points[i].x * 2, points[i].y, points[i+1].x * 2, points[i+1].y);
			}
		}
	}

	p.initValues = function(){
		points[0] = new dot(0, p.height/2);
		points[1] = new dot(p.width, p.height/2);

		vertical_displacement = points[0].y + points[1].y / 2;
		vertical_displacement *= 2 ** (-roughness);

		iterations = 1;
	}

	p.resetSketch = function(){
		points.length = 0;
		p.clear()
		p.background(217);
		p.initValues();
	}
};
var myp5 = new p5(MidDisplacement, 'c1');