def covariates_to_design_matrix(contrast, covariates=None):
    """
    Generate design matrix for SurfStat based on the contrast and the optional list of covariates.

    Design matrix "1 + <contrast> + <covariate_1> + ... + <covariate_n>"

    Example:
        >>> from clinicaml.pipelines.statistics_surface.statistics_surface_utils import covariates_to_design_matrix
        >>> covariates_to_design_matrix('group', 'age sex group')
        1 + group + age + sex
        >>> covariates_to_design_matrix('group', 'age')
        1 + group + age
        >>> covariates_to_design_matrix('group', None)
        1 + group
    """
    if covariates:
        # Convert string to list while handling case where several spaces are present
        list_covariates = list(set(covariates.split(" ")))
        try:
            list_covariates.remove("")
        except ValueError:
            pass

        if contrast in list_covariates:
            design_matrix = "1 + " + " + ".join(
                covariate for covariate in list_covariates
            )
        else:
            design_matrix = (
                "1 + "
                + contrast
                + " + "
                + " + ".join(covariate for covariate in list_covariates)
            )
    else:
        design_matrix = "1 + " + contrast

    return design_matrix