Code rewrite first commit (untested)