/*
 * File: DayAtTheBeach.java
 * ------------------------
 * Karel collects all beeper piles of size 2 and places them
 * in the "bucket" at (1, 1).
 */

import stanford.karel.SuperKarel;

public class DayAtTheBeach extends SuperKarel {
	
	public void run() {
		collectAllShells();
		depositShells();
	}
	
	/* Pre: Karel is at (2, 1), facing east
	 * Post: Karel is at  upper left corner of the world, facing west
	 */
	private void collectAllShells() {
		while(leftIsClear()) {
			collectRow();
			moveToNextRow();
		}
		collectRow();
	}
	
	/* Pre: Karel is in the leftmost spot of a row, facing east
	 * Post: Karel has collected valid beeper piles in that row,
	 * and is back in the leftmost spot of that row, facing west
	 */
	private void collectRow() {
		while (frontIsClear()) {
			checkPile();
			move();
		}
		checkPile();
		turnAround();
		moveToEnd();
	}
	
	/* Pre: Karel is in the leftmost spot of a row, facing west
	 * Post: Karel is one row up, facing east
	 */
	private void moveToNextRow() {
		turnRight();
		move();
		turnRight();
	}
	
	/* Pre: Karel is standing on any corner
	 * Post: Karel is standing in the same spot as before, but has
	 * picked up the pile if it contained exactly 2 beepers
	 */
	private void checkPile() {
		if (beepersPresent()) {
			pickBeeper();
			if (beepersPresent()) {
				pickBeeper();
			} else {
				putBeeper();
			}
		}
	}
	
	/* Pre: None
	 * Post: Karel has moved forward until their front is blocked
	 */
	private void moveToEnd() {
		while (frontIsClear()) {
			move();
		}
	}
	
	/* Pre: Karel is at  upper left corner of the world, facing west
	 * Post: Karel is at (1, 1), has deposited all collected beepers
	 */
	private void depositShells() {
		// move to bucket
		turnLeft();    // Karel is now facing south
		moveToEnd();   // this moves Karel down to (1, 1)
		
		// place all collected beepers into bucket
		while (beepersInBag()) {
			putBeeper();
		}
	}
}