/*
 * File: HangingChadKarel.java
 * --------------------
 * A program in which Karel cleans up hanging chads from a ballot.
 * Precondition:  Karel stands at the start of the ballot.
 * Postcondition: Karel is at the end of the ballot and all chad has  
 * been cleared.
 */

import stanford.karel.*;

public class HangingChadKarel extends SuperKarel {

	public void run() {
		// To avoid the fencepost problem, we split the logic into a     
		// loop to process columns, plus one final call to check the 
		// last column.
		while (frontIsClear()) {
			processColumn();
			move();
		}
		processColumn();
	}

	/**
	 * This method clears chad from the current column, if any.
	 * Precondition: Karel is standing in the center of a column,   
	 * facing East.
	 * Postcondition: Karel is back in same place/orientation and chad 
	 * has been cleared.
	 */
	private void processColumn() {
		// If there is chad to clear, clear that chad from the ballot.
		if (noBeepersPresent()) {
			removeAllChad();
		}
	}

	/** 
	 * This method clears chad from the current column.
	 * Precondition: Karel is standing in the center of a column to be 
	 * cleared.
	 * Postcondition: Karel is standing in same place and the column  
	 * has been emptied.
	 */
	private void removeAllChad() {
		turnLeft();     // clean the upper corner
		cleanChad();
		turnAround();   // Clean the lower corner.
		cleanChad();
		turnLeft();     // Face East
	}

	/** 
	 * This method clears chad from the current corner.
	 * Precondition: Karel is facing a corner to be cleared of chad.
	 * Postcondition: Karel is in the same location/orientation, but 
	 * all chad has been cleared from the corner Karel is facing.
	 */
	private void cleanChad() {
		move();
		while (beepersPresent()) {
			pickBeeper();
		}
		moveBackward();
	}

	/**
	 * Karel moves one step backwards.
	 * Postcondition: Karel is facing in its original direction, but
	 * stepped backwards.
	 */
	private void moveBackward() {
		turnAround();
		move();
		turnAround();
	}
}

