#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"

void print_prime(int *input, int count){ // input is an array of primes, and count is the account of primes
    if (count == 0){ // no more primes
        return;
    }
    int p[2]; // a pipe to passing selected nums
    pipe(p);
    int i = 0;
    int prime = *input; // this is equals to input[0],which is certified a prime! (important)
    char buf[4];
    printf("prime %d\n", prime);
    if (fork() == 0){ // child process, pass rest of the nums into the parent process
        close(p[0]);
        for (; i < count; i++){
            write(p[1], (char*) (input + i), 4);
        }
    close(p[1]);
    exit(0);
    }
    else{
        close(p[1]);
        count = 0; // initialize the account of primes
        while(read(p[0], buf, 4) != 0){ // read the context of child
            int temp = *((int *) buf); // the number waiting to be selected
            if (temp % prime) { // the number is not mutiple of the current prime(remainder is not  0)
                *input++ = temp; // make the number a member of next list to be selected
                count++;
            }
        }
        print_prime(input - count, count); // input - count is to go back to input[0]
        close(p[0]);
    }
}

int main(int argc, char* argv[]){
    int input[34], i = 0;
    for(; i < 34; i++){
        input[i] = i + 2; // nums from 2 to 35
    }
    print_prime(input, 34);
    exit(0);
}