cleaned up, refined algorithms