made some more code reusable and fixed some issues.