Add sorting by score + initial template support + fix many robustness bugs