clearCap();
capOn(MINING,BRIDGE,WATER,LAVA,COBBLE);
term("\n\n### Ore Filter v3 ###");
term("Coded by MightyPork");
term("\nEnter any text to start.");
bell();
while(!term.hasInput()){}


if(level < 7){
	term("This program needs miner level 7+.");
	bell();
	restart;	
}

if(countItems(BUCKET_LAVA)==0){
	term("Missing lava bucket.");
	bell();
	restart;
}

if(countItems(BUCKET_WATER)==0){
	term("Missing water bucket.");
	bell();
	restart;
}

if(fuel() < 6000){
	term("Insert some more fuel. \nYou have only "+fuel());
	bell();
	restart;
}

term("*** Program started. ***\n");
do{
	term("Enter how far you want to mine:");
	until(term.hasInput()){}
	txt = term.getInput();
	if(!isnum(txt)){
		term(txt+" is not a valid number, try again.");
		continue;
	}
	if(atoi(txt) < 2 || atoi(txt)> 200){
		term("Number out of range 2-200, try again.");
		continue;		
	}
}while(false);

dist = atoi(txt);


term("Preparing block buffers...");

global a0=0; global b0=0; global c0=0; global d0=0;
global a1=0; global b1=0; global c1=0; global d1=0;
global a2=0; global b2=0; global c2=0; global d2=0;
	
term("* Starting main digging loop...");

diggRow(dist);

term("* Reached end, turning around.");
right();
digg();digg();
right();

term("* Starting to digg back.");
diggRow(dist);


term("* Digging finished, \n  Moving back to original position.");
right();

digg();digg();
right();

burn(JUNK, COBBLE, DIRT);
term("Burning cobble, dirt and other junk.");
bell();
term("\n\n*** Program ended.***\nEnjoy your ores!");

	
function diggRow(d){	
	for(i=1:d){
		term("Digging block "+i+" of "+d);
		digg();
	}
}
	
function digg(){
	
	
	// shift the buffers
	place("B2",a2);
	place("B1",b2);
	place("B4",c2);
	place("B3",d2);
	
	a2 = a1;
	b2 = b1;
	c2 = c1;
	d2 = d1;
	
	a1 = a0;
	b1 = b0;
	c1 = c0;
	d1 = d0;
	
	a0 = getId("F1");
	b0 = getId("F2");
	c0 = getId("F3");
	d0 = getId("F4");
	
	// ores→cobble, make it from
  // lava and water buckets
	if(ideq(a0, PRECIOUS)){
		term("* Found "+otn(a0)+"!");
		a0 = COBBLE;
	}
	
	if(ideq(b0, PRECIOUS)){
		term("* Found "+otn(b0)+"!");
		b0 = COBBLE;
	}
	
	if(ideq(c0, PRECIOUS)){
		term("* Found "+otn(c0)+"!");
		c0 = COBBLE;
	}
	
	if(ideq(d0, PRECIOUS)){
		term("* Found "+otn(d0)+"!");
		d0 = COBBLE;
	}
	
	// stone→cobble, grass→dirt
	a0 = norm(a0);
	b0 = norm(b0);
	c0 = norm(c0);
	d0 = norm(d0);
	
	if(fuel() < 5000){
		term("* Running out of fuel!\n * only "+fuel()+" remaining.");
	}
	
	fw();
}

// ore to name
function otn(ore){
	if(ore == LAPISORE) return "lapis";
	if(ore == COALORE) return "coal";
	if(ore == DIAMONDORE) return "diamond";
	if(ore == GOLDORE) return "gold";
	if(ore == REDSTONEORE) return "redstone";
	if(ore == GLOWSTONE) return "glowstone";
	
	return "unknown";
}

// normalize id
function norm(id){
	if(id == STONE) id = COBBLE;
	if(id == GRASS) id = DIRT;
	return id;
}