#include #include const int PARAMS_NUM = 4; const int GRILL_SIZE = 12; const char HOLE = 'X'; FILE *open_file(const char *filename, const char *access); void read_matrix(const char *filename, char matrix[][GRILL_SIZE], int size); enum GRILL_TYPE {GRILL_NOT_LEGAL = 0 , GRILL_LEGAL = 1}; GRILL_TYPE grill_legal(char grill[][GRILL_SIZE], int size); void decrypt(char output[], const char encrypted[][GRILL_SIZE], char grill[][GRILL_SIZE], int size); void turn_grill(char grill[GRILL_SIZE][GRILL_SIZE]); void write_output(const char *filename, char output[], int size); int main(int argc, char *argv[]) { if(argc != PARAMS_NUM) { fprintf(stderr,"Invalid number of parameters, usage : grill \n"); exit(-1); } char encrypted[GRILL_SIZE][GRILL_SIZE]; char grill[GRILL_SIZE][GRILL_SIZE]; char plain[GRILL_SIZE*GRILL_SIZE]; read_matrix(argv[1], encrypted, GRILL_SIZE); read_matrix(argv[2], grill, GRILL_SIZE); if( grill_legal(grill, GRILL_SIZE) == GRILL_NOT_LEGAL) { fprintf(stderr, "Illegal grid inserted !!!\n"); exit(1); } decrypt(plain, encrypted, grill, GRILL_SIZE); write_output(argv[3], plain, GRILL_SIZE*GRILL_SIZE); return 0; } FILE *open_file(const char *filename, const char *access) { FILE *file_handle; file_handle = fopen(filename, access); if(file_handle == NULL) { fprintf(stderr,"Unable to open file %s\n", filename); exit(-1); } return file_handle; } void read_matrix(const char *filename, char matrix[][GRILL_SIZE], int size) { FILE *file_handle = open_file(filename, "r"); for(int i = 0; i < size ; i++) { for(int j = 0 ; j < size ; j++) { matrix[i][j] = fgetc(file_handle); } fgetc(file_handle); // The newline character } fclose(file_handle); } GRILL_TYPE grill_legal(char grill[][GRILL_SIZE], int size) { for(int i = 0 ; i < size ; i++) { for(int j = 0 ; j < size ; j++) { if( (grill[i][j] == HOLE) && ( (grill[j][size - 1 - i] == HOLE) || (grill[size - 1 - i][size - 1 - j] == HOLE) || (grill[size - 1 - j][i] == HOLE))) { return GRILL_NOT_LEGAL; } } } return GRILL_LEGAL; } void decrypt(char output[], const char encrypted[][GRILL_SIZE], char grill[][GRILL_SIZE], int size) { int output_cnt = 0; for(int turns = 0 ; turns < 4 ; turns++) { for(int i = 0 ; i < size ; i++) { for(int j = 0 ; j < size ; j++) { if(grill[i][j] == HOLE) output[output_cnt++] = encrypted[i][j]; } } turn_grill(grill); } } void turn_grill(char grill[GRILL_SIZE][GRILL_SIZE]) { char temp[GRILL_SIZE][GRILL_SIZE]; for(int i = 0 ; i < GRILL_SIZE ; i++) { for(int j = 0 ; j < GRILL_SIZE ; j++) { temp[j][(GRILL_SIZE - 1) - i] = grill[i][j]; } } for(i = 0 ; i < GRILL_SIZE ; i++) { for(int j = 0 ; j < GRILL_SIZE ; j++) { grill[i][j] = temp[i][j]; } } } void write_output(const char *filename, char output[], int size) { FILE *file_handle = open_file(filename, "w"); for(int i = 0 ; i < size ; i++) { fputc(output[i], file_handle); } fclose(file_handle); }