Modified to accept a stream instead of a filename