Second commit, more refined fixed some errors will do further work later