rule spades:
    """
    SPAdes is a *de-novo* assembler designed for small genomes like bacteria
    or fungi. It correct reads the assemble them using different size of kmer.
    With the careful options, SPAdes corrects mismatches and short INDELs in
    the contigs using BWA. This rule works only with paired-end files.

    Required input:
        - __spades__fastq: List of paired FASTQ files.

    Required output:
        - __spades__contigs: FASTA file of created contigs.
        - __spades__scaffolds: FASTA file of created scaffolds.

    Required log:
        - __spades__log: Log file with stdout and stderr of SPAdes.

    Required configuration:
        .. code-block:: yaml

            spades:
                k: 21,33,55,77 # Comma-separated list of k-mer sizes (must be odd and less than 128).
                careful: yes # Tries to reduce number of mismatches and short indels.
                only_assembler: no # Runs only assembling (without read error correction).
                memory: 250 # RAM limit for SPAdes in Gb (terminates if exceeded).
                threads: 8 # Number of threads to be used.
                options: "" # Any options recognised by spades.py.

    Reference:
        - http://cab.spbu.ru/software/spades/
    """
    input:
        fastq = __spades__fastq
    output:
        contigs = __spades__contigs,
        scaffolds = __spades__scaffolds
    log:
        l = __spades__log
    threads:
        config['spades']['threads']
    params:
        k = config['spades']['k'],
        careful = config['spades']['careful'],
        only_assembler = config['spades']['only_assembler'],
        m = config['spades']['memory'],
        options = config['spades']['options'],
        outdir = __spades__outdir
    run:
        cmd = "spades.py -k %s -m %i -t %i %s" % (params['k'], params['m'],
                                                  threads, params['options'])
        if params['careful']:
            cmd += " --careful"
        if params['only_assembler']:
            cmd += " --only-assembler"
        cmd += " -1 %s -2 %s -o %s > %s 2>&1" % (
            input['fastq'][0], input['fastq'][1], params['outdir'], log['l'])
        shell(cmd)
 
        import shutil
        shutil.copy("%s/scaffolds.fasta" % params['outdir'],
                    output["scaffolds"])
        shutil.copy("%s/contigs.fasta" % params['outdir'],
                    output["contigs"]) 
