/* This is one of the cipher files for the cipher interface written ** by wart@ugcs.caltech.edu ** ** Please don't steal my code without my permission. ** */ #include #include #include #include #include "term.h" #include "types.h" #include "ctypes.h" #define SPC '.' #define SPACE_DIGIT (int) 26 tridigit::tridigit(){ valid_chars = "1234567890"; period=0; *cipher = (char) NULL; key.init(27); } int tridigit::execute_option(char option){ int valid_option = TRUE; switch(option){ case SUBSTITUTE: substitute(); break; case UNDO: undo(); break; default: valid_option = base_exec_option(option); break; } return valid_option; } void tridigit::substitute(){ char letter; int number; prompt("What is the number? "); number = get_char(); prompt("What is the letter? "); letter = get_char(); if(do_sub(number, letter) == BAD_SUB){ msgerror("Bad substitution."); } } int tridigit::do_sub(char number, char letter){ int state = NEW_SUB; int i, count = 0; if(!isdigit(number)){ state = BAD_SUB; } else if(!isalpha(letter)){ if(letter != SPC){ state = BAD_SUB; } else{ state = key.alter(number, SPACE_DIGIT); for(i = 0; i < 26; i++){ if(key.val(i) == number){ key.clearkey(i); } } } } else{ letter |= ' '; for(i = 0; i < 26; i++){ if(key.val(i) == number) count++; } if(count > 2){ state = BAD_SUB; } else{ state = key.alter(number, key.index(letter)); if(key.val(SPACE_DIGIT) == number){ key.clearkey(SPACE_DIGIT); } } } return state; } void tridigit::show_menu(){ menu(1, "(S)ubstitute (U)ndo (W)rite (Q)uit"); } void tridigit::show_cipher(){ int i, j, x, y; char lets[3]; for(i = 0; i < length; i++){ x = (i%36)*2; y = (i/36 + 1)*4; put_char(cipher[i], x, y); get_letters(cipher[i], lets); for(j = 0; j < 3; j++){ put_char(lets[j], x, y-1-j); } } } int tridigit::get_letters(char number, char lets[3]){ int i, count = 0; for(i = 0; i < 3; i++) lets[i] = BLANK; if(key.val(SPACE_DIGIT) == number){ lets[0] = SPC; count = 1; } else{ for(i = 25; i >= 0 && count < 3; i--){ if(key.val(i) == number){ lets[count++] = i+'a'; } } } return count; } void tridigit::show_key(){ int i, j; char lets[3]; for(i = 0; i < 10; i++){ put_char(i+'0', i*2, 20); get_letters(i+'0', lets); for(j = 0; j < 3; j++){ put_char(lets[j], i*2, 19-j); } } } void tridigit::undo(){ char letter; int i; prompt("Undo which number/letter? "); letter = get_char(); if(letter == '*'){ key.clearkey(); } else if(isalpha(letter)){ letter |= ' '; key.clearkey(key.index(letter)); } else if(isdigit(letter)){ for(i = 0; i < 27; i++){ if(key.val(i) == letter){ key.clearkey(i); } } } else{ msgerror("Bad letter."); } } void tridigit::decipher(char *string){ char lets[3]; int i, j; *string = (char) NULL; for(i = 0; i < length; i++){ get_letters(cipher[i], lets); for(j = 0; j < 3; j++){ sprintf(string+4*i, "%c%c%c\n", lets[0], lets[1], lets[2]); } } string[4*length] = (char) NULL; }