rewritten in cpp