changes in code style, DRYer code and other fixes as suggested by n1kO