// ************************************************************************** //
//                                                                            //
//    eses                   eses                                             //
//   eses                     eses                                            //
//  eses    eseses  esesese    eses   Embedded Systems Group                  //
//  ese    ese  ese ese         ese                                           //
//  ese    eseseses eseseses    ese   Department of Computer Science          //
//  eses   eses          ese   eses                                           //
//   eses   eseses  eseseses  eses    University of Kaiserslautern            //
//    eses                   eses                                             //
//                                                                            //
// ************************************************************************** //
// Factorial numbers are recursively defined as follows: F(n) := n * F(n-1)
// with F(0) := 1. The following algorithm is based on the parallel prefix sum
// and computes the first N factorial numbers in time O(log(n)) with O(n) work.
// ************************************************************************** //

macro M = 4;
macro N = exp(2,M);

module Factorial([N]nat fac, event rdy) {

    // initialize array fac
    fac[0] = 1;
    for(i=1..N-1) fac[i] = i;

    // bottom-up traversal requires time log(N)
    // with N-1 work and N/2 processors
    for(l=1..M) {
        for(j=1..N/exp(2,l)) {
            let(s = exp(2,l-1))
            next(fac[2*j*s-1]) = fac[2*j*s-1] * fac[(2*j-1)*s-1];
        }
        pause;
    }

    // top-down traversal requires time log(N)-1
    // with N-log(N)-1 work and N/2 processors
    for(i=1..M-1) {
        let(l = M-i)
        for(j=1..exp(2,i)-1) {
            let(s = exp(2,l-1))
            next(fac[(2*j+1)*s-1]) = fac[(2*j+1)*s-1] * fac[2*j*s-1];
        }
        pause;
    }

    // signal the termination
    emit(rdy);

}
drivenby {
    await(rdy);
}