class ALU {

	public String adder (String operand1, String operand2, char c, int length) {
		String normalizedOperand1 = complementLength(operand1, length);
		String normalizedOperand2 = complementLength(operand2, length);
		
		char carry = c;
		StringBuilder finalResult = new StringBuilder();
		
		int partsLeft = length/4;
		int highestBits = length%4; //if length is not a multiple of 4, calculates the rest bits
		
		while(partsLeft>0){
			String claResult = claAdder(normalizedOperand1.substring(highestBits + 4*partsLeft-4, highestBits + 4*partsLeft), normalizedOperand2.substring(highestBits+ 4*partsLeft-4, highestBits+4*partsLeft), carry);
			finalResult.insert(0, claResult.substring(1));
			carry = claResult.charAt(0); 
			partsLeft--;
		}
		
		//uses fullAdder for the rest bits
		for(int i=highestBits-1;i>=0;i--){
			String bitResult = fullAdder(normalizedOperand1.charAt(i), normalizedOperand2.charAt(i), carry);
			carry = bitResult.charAt(0);
			finalResult.insert(0, bitResult.charAt(1));
		}
		
		//overflow
		if (normalizedOperand1.charAt(0)==normalizedOperand2.charAt(0) && normalizedOperand1.charAt(0) != finalResult.charAt(0)){
			finalResult.insert(0, "1");
		}else{
			finalResult.insert(0, "0");
		}
		
		return finalResult.toString();
		
		
	}

}