main, p(b|a,d) and optimizations