updated with new more robust version