move cost calculation out to function