implementation of macro expansion algorithm by Kohlbecker et al