<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def CMS(data, format="PEM"):
 """ Factory function to create CMS objects from received messages. Parses CMS data and returns either SignedData or EnvelopedData object. format argument can be either "PEM" or "DER". It determines object type from the contents of received CMS structure. """

    bio = Membio(data)
    if format == "PEM":
        ptr = libcrypto.PEM_read_bio_CMS(bio.bio, None, None, None)
    else:
        ptr = libcrypto.d2i_CMS_bio(bio.bio, None)
    if ptr is None:
        raise CMSError("Error parsing CMS data")
    typeoid = Oid(libcrypto.OBJ_obj2nid(libcrypto.CMS_get0_type(ptr)))
    if typeoid.shortname() == "pkcs7-signedData":
        return SignedData(ptr)
    elif typeoid.shortname() == "pkcs7-envelopedData":
        return EnvelopedData(ptr)
    elif typeoid.shortname() == "pkcs7-encryptedData":
        return EncryptedData(ptr)
    else:
        raise NotImplementedError("cannot handle "+typeoid.shortname())