package projectEQ2440.utils;

/**
 * <b>public class CircleMemory</b><br/>
 * Memory of integer turning in circle
 */
public class CircleMemory {
	
	// Saved values
	private final int[] memory;

	// length of the memory
	public final int length;
	
	// Pointer in the the memory
	private int pointer;
	
	/**
	 * <b>public CircleMemory(int length)</b><br/>
	 * Constructor with a given length
	 * 
	 * @param length : length of the circle memory
	 */
	public CircleMemory(int length) {
		memory = new int[length];
		pointer = 0;
		this.length = length;
	}
	
	/**
	 * <b>public int read(int position)</b><br/>
	 * Read the value at position position
	 * 
	 * @param position : position to read
	 * @return the value at position asked
	 */
	public int read(int position) {
		return memory[(pointer+position)%length];
	}
	
	/**
	 * <b>public void write(int position, int value)</b><br/>
	 * write a value at a specific position
	 * 
	 * @param position : the position where to write
	 * @param value : the value to write
	 */
	public void write(int position, int value) {
		memory[(pointer+position)%length] = value;
	}
	
	/**
	 * <b>public void writeRight(int value)</b><br/>
	 * write the value at the right of the memory
	 * 
	 * @param value : the value to write
	 */
	public void writeRight(int value) {
		memory[pointer] = value;
		pointer = (pointer+1)%length; 
	}

	/**
	 * <b>public void writeLeft(int value)</b><br/>
	 * write the value at the left of the memory
	 * 
	 * @param value : the value to write
	 */
	public void writeLeft(int value) {
		pointer = (pointer+length-1)%length;
		memory[pointer] = value;
	}
	
	/**
	 * <b>public void raz()</b><br/>
	 * Put every value of the memory to 0
	 */
	public void raz() {
		int k;
		for (k=0; k<length; k++) memory[k] = 0;
	}
	
	/**
	 * <b>public int sum()</b><br/>
	 * Give the summation of all the memory
	 * 
	 * @return the sum of the memory
	 */
	public int sum() {
		int k, tmp = 0;
		for (k=0; k<length; k++) tmp += memory[k];
		return tmp;
	}
}
