Corrected some bugs and implemented dynamic template selection.