refactored code, tried to get it as small as i can, some more corrections