Cleanup code structure, move code to central functions