Design and optimization of a stencil engine