Well according to wikipedia:
P(w,d) = \sum_c P(c) P(d|c) P(w|c) = P(d) \sum_c P(c|d) P(w|c)
That is the formula you need to implement.
Further, the EM algorithm is what you need. If you don't understand the algorithm or the function you cannot successfully be a consumer of it.