Move logic to correct place, mostly modularized