Debug, refactor, improve tests