Final version, would be nice to refactor