package chiffre;

/**
 * Caesar-Chiffre
 * 
 * @author Christian Semrau
 * <a href="mailto:Christian.Semrau@student.uni-magdeburg.de">
 * Christian.Semrau@student.uni-magdeburg.de</a>
 */
class Caesar implements ChiffreInterface {
	int key;
	boolean set = false;
/**
 */
public String decode(String s) {
	return endec(s, 26-key);
}
/**
 */
public String encode(String s) {
	return endec(s, key);
}
/**
 */
public String endec(String s, int k) {
	if (!set) return "";
	char[] geheim = new char[s.length()];
	for (int i=0; i<s.length(); i++){
		char klar = s.charAt(i);
		char code;
		if (klar>='a' && klar<='z'){
			code = (char)((klar-'a'+k)%26+'a');
		}else
		if (klar>='A' && klar<='Z'){
			code = (char)((klar-'A'+k)%26+'A');
		}else
			code = klar;
		geheim[i] = code;
	}
	return new String(geheim);
}
/**
 * Setzt den Schluessel, eine ganze Zahl oder ein
 * einzelner Buchstabe.
 */
public void setKey(String s) {
	if (s==null||s.length()<=0){ set = false; return; }
	if (Character.isLetter(s.charAt(0))){
		key = (Character.toLowerCase(s.charAt(0))-'a');
		set = true;
		return;
	}
	try{
		key = (new Integer(s).intValue()%26);
		set = true;
		while (key<0) key+=26;
	}catch(NumberFormatException e){
		set = false;
	}
}
}