#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

#define N_CIFRA 3

void cifra_cesar(char *c) {
	int tmp = *c + N_CIFRA;
	
	if( (tmp >= 'a' && tmp <= 'z') || (tmp >= 'A' && tmp <= 'Z') )
		*c = tmp; //caso esteja dentro das maiusculas e minusculas
	else if(tmp > 'Z' && tmp < 'a')
		*c = tmp - 'Z' - 1 + 'A'; //caso exceda o Z maiusculo
	else if(tmp > 'z' && *c <= 'z')
		*c = tmp - 'z' - 1 + 'a'; // caso exceda o z minusculo
}

void p1(int writefd) {
	char buf[1];

	buf[0] = (char)fgetc(stdin);
	while(buf[0] != '$') {
		write(writefd, buf, 1);
		buf[0] = fgetc(stdin);
	}
	
	/* se for para terminar enviar a mensagem aos outros processos */
	write(writefd, buf, 1);
}

void p2(int readfd, int writefd) {
	char buf[1];

	read(readfd, buf, 1);
	while(buf[0] != '$') {
		cifra_cesar(buf);
		write(writefd, buf, 1);
		read(readfd, buf, 1);
	}
	
	/* se for para terminar enviar a mensagem aos outros processos */
	write(writefd, buf, 1);
}

void p3(int readfd) {
	char buf[1];
	int fd = open("t2.txt", O_WRONLY|O_CREAT|O_TRUNC, 0600);

	read(readfd, buf, 1);
	while(buf[0] != '$') {
		write(fd, buf, 1);
		read(readfd, buf, 1);
	}

	close(fd);
}

int main(int argc, char *argv[]) {
	int pipe1[2];
	int pipe2[2];

	pipe(pipe1);
	pipe(pipe2);

	if(fork() == 0) { //processo que lĂȘ do teclado
		p1(pipe1[1]); exit(0);
	}
	if(fork() == 0) { //processo que aplica a cifra
		p2(pipe1[0], pipe2[1]); exit(0);
	}
	if(fork() == 0) { //processo que escreve no ficheiro
		p3(pipe2[0]); exit(0);
	}

	wait(NULL); wait(NULL); wait(NULL);
}