various improvements and DRYer code