package chiffre;

/**
 * Vigenere-Chiffre
 * 
 * @author Christian Semrau
 * <a href="mailto:Christian.Semrau@student.uni-magdeburg.de">
 * Christian.Semrau@student.uni-magdeburg.de</a>
 */
class Vigenere implements ChiffreInterface {
	int[] enKey, deKey;
	boolean set = false;
/**
 * decode method comment.
 */
public String decode(String s) {
	return endec(s, deKey);
}
/**
 * encode method comment.
 */
public String encode(String s) {
	return endec(s, enKey);
}
/**
 * 
 * @return java.lang.String
 * @param s java.lang.String
 * @param k int
 */
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[i%k.length])%26+'a');
		}else
		if (klar>='A' && klar<='Z'){
			code = (char)((klar-'A'+k[i%k.length])%26+'A');
		}else
			code = klar;
		geheim[i] = code;
	}
	return new String(geheim);
}
/**
 * setKey method comment.
 */
public void setKey(String s) {
	set = false;
	if (s==null||s.length()<=0) { return; }
	try{
		long zahl = new Long(s).longValue();

		short signum = 1;
		int basis = 26;
		int top = 0;
		int[] a = new int[14];

		if (zahl==0) {
			top=1; a[0]=0;
		}else{
			// versagt, wenn zahl = Long.MIN_VALUE
			if (zahl<0) { zahl=-zahl; signum = -1; }

			while (zahl!=0) {
				a[top++] = (int)(zahl%basis);	// Rest = Stelle
				zahl = zahl/basis;		// Quotient wird weiter bearbeitet
			}

			for (int i=0; i<top/2; i++) {
				int h = a[i]; a[i] = a[top-i-1]; a[top-i-1] = h;
			}
		}

		enKey = new int[top];
		deKey = new int[top];
		if (signum==-1){
			System.arraycopy(a, 0, deKey, 0, top);
			for (int i=0; i<deKey.length; i++)
				enKey[i] = (26-deKey[i])%26;
		}else{
			System.arraycopy(a, 0, enKey, 0, top);
			for (int i=0; i<enKey.length; i++)
				deKey[i] = (26-enKey[i])%26;
		}
		set = true;
		return;
	}catch(NumberFormatException e){
	}

	enKey = new int[s.length()];
	deKey = new int[s.length()];
	for (int i=0; i<s.length(); i++){
		char c = Character.toLowerCase(s.charAt(i));
		if (!Character.isLetter(c)){
			enKey = null;
			deKey = null;
			set = false;
			return;
		}
		enKey[i] = (c-'a');
	}
	for (int i=0; i<enKey.length; i++)
		deKey[i] = (26-enKey[i])%26;
	set = true;
}
}