def cmbuild_from_alignment(aln, structure_string, refine=False, \
    return_alignment=False,params=None):
    """Uses cmbuild to build a CM file given an alignment and structure string.

        - aln: an Alignment object or something that can be used to construct
            one.  All sequences must be the same length.
        - structure_string: vienna structure string representing the consensus
            stucture for the sequences in aln.  Must be the same length as the
            alignment.
        - refine: refine the alignment and realign before building the cm.
            (Default=False)
        - return_alignment: Return (in Stockholm format) alignment file used to
            construct the CM file.  This will either be the original alignment
            and structure string passed in, or the refined alignment if --refine
            was used. (Default=False)
            - Note.  This will be a string that can either be written to a file
                or parsed.
    """
    aln = Alignment(aln)
    if len(structure_string) != aln.SeqLen:
        raise ValueError, """Structure string is not same length as alignment.  Structure string is %s long. Alignment is %s long."""%(len(structure_string),\
        aln.SeqLen)
    else:
        struct_dict = {'SS_cons':structure_string}
    #Make new Cmbuild app instance.
    app = Cmbuild(InputHandler='_input_as_paths',WorkingDir='/tmp',\
        params=params)

    #turn on refine flag if True.
    if refine:
        _, tmp_file = mkstemp(dir=app.WorkingDir)
        app.Parameters['--refine'].on(tmp_file)

    #Get alignment in Stockholm format
    aln_file_string = stockholm_from_alignment(aln,GC_annotation=struct_dict)

    #get path to alignment filename
    aln_path = app._input_as_multiline_string(aln_file_string)
    cm_path = aln_path.split('.txt')[0]+'.cm'
    app.Parameters['-n'].on(cm_path)

    filepaths = [cm_path,aln_path]

    res = app(filepaths)

    cm_file = res['CmFile'].read()

    if return_alignment:
        #If alignment was refined, return refined alignment and structure,
        # otherwise return original alignment and structure.
        if refine:
            aln_file_string = res['Refined'].read()
        res.cleanUp()
        return cm_file, aln_file_string
    #Just return cm_file
    else:
        res.cleanUp()
        return cm_file