/* Cifrario bifido. Usa il quadrato di Polibio, legge le prima tutte le prime cifre, poi tutte le seconde, ricodifica con lo stesso quadrato. */

#include <stdio.h>
#include <string.h>

#define N 5

int main(int argc, char **argv){
	char polybius[N][N];
	int s[128];
	char c='a';
	char *p=&polybius[0][0];
	int i, j, k, l;

	/* Build and print a simple Polybius Square */
	for(i=0; i<N*N; i++){
		*p=c;
		c++;
		p++;
		if (c=='j') c++;
	}
	
	printf("Polybius Square\n");
	for(i=0; i<N; i++){
		for(j=0; j<N; j++)
			printf("%c ", polybius[i][j]);
		printf("\n");
	}
	
	/* Stop if no argument is given */
	if (argc<2) return 0;
	l=strlen(argv[1]);

	printf ("Encoding %s\n", argv[1]);
	/* Run Polybius encoding*/
	for(k=0, p=argv[1]; *p!='\0'; k++, p++) {
		if (*p=='j') *p='i';
		for(i=0; i<N; i++)
			for(j=0; j<N; j++)
				if (*p==polybius[i][j]){
					s[k]=i;
					s[k+l]=j;
				}
	}

	/* Print transposed encoding */
	for(i=0; i<2*l; i++){
		printf("%d", s[i]);
	}
	printf("\n");

	/* Run Polybius decoding on transposition */	
	for(i=0; i<2*l; i+=2){
		printf(" %c", polybius[s[i]][s[i+1]]);
	}
	printf("\n");
	return 0;
}


