Add weights to k-factor templates
Fix memory leak, tree and tmp file was leaking