rewrite logic to be readable instead of spaghetti