extracted the final version put in the repo, also cleaned up some code