// Sushant Kulkarni
// Sample Solution to CIS 3362 Homework #3 Problem #5: Hill encrypter.
// 10/5/2014

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

const int ALPHASIZE = 26;
const int DEBUG = 1;

void modMatMult(int ** mat, int *col, int * res, int dim);

int main(){

	char line[255];
	int len, i, j;
	FILE* fp = fopen("q5.txt", "r");
    fscanf(fp, "%d",&len);

    // Create a matrix with the desired dimesnsionss
    int** mat = (int **) malloc (sizeof(int*) * len);
    for (i = 0; i< len; ++i)
        mat[i] = (int*)malloc (sizeof(int) *len);

    // Create a col matrix for plain text and result matrix for result.
    int* col = (int*)malloc (sizeof(int) * len);
    int *res = (int *) malloc (sizeof(int)* len);

    // Read in matrix.
    for (i=0; i<len; i++)
        for (j=0; j<len; j++)
            fscanf(fp, "%d", &mat[i][j]);

    fscanf(fp,"%s", line);

    // Pad the input.
    int paddsize = (len - (strlen(line)%len))%len;
    while(paddsize != 0){
        strcat(line, "x");
        paddsize--;
    }

    // Process input.
    for (i=0 ; i<strlen(line) ; i+=len){

        // Store this block in a column.
        for (j=0; j<len; j++)
            col[j] = line[i+j] - 'a';

        // Multiply and output result.
        modMatMult(mat, col, res, len);
        for (j=0; j<len; j++)
            printf("%c", (res[j] + 'a'));
    }

    // Manage memory.
    printf("\n");
    fclose(fp);
    free(mat);
    free(col);
    free(res);
	return 0;
}

void modMatMult(int ** mat, int *col, int * res, int dim){
	int i, j, sum;

	// Just sum up each entry in the resultant colu,n
	for (i = 0; i<dim ; i++){
        res[i] = 0;
        for (j=0 ; j<dim; j++)
            res[i] = (res[i] + mat[i][j] * col[j])%ALPHASIZE;
	}
}
