Runs the contamination check for samples.

    :param in_prefix: the prefix of the input files.
    :param in_type: the type of the input files.
    :param out_prefix: the output prefix.
    :param base_dir: the output directory.
    :param options: the options needed.

    :type in_prefix: str
    :type in_type: str
    :type out_prefix: str
    :type base_dir: str
    :type options: list

    :returns: a tuple containing the prefix of the output files (the input
              prefix for the next script) and the type of the output files
              (``bfile``).

def run_contamination(in_prefix, in_type, out_prefix, base_dir, options):
    """Runs the contamination check for samples.

    :param in_prefix: the prefix of the input files.
    :param in_type: the type of the input files.
    :param out_prefix: the output prefix.
    :param base_dir: the output directory.
    :param options: the options needed.

    :type in_prefix: str
    :type in_type: str
    :type out_prefix: str
    :type base_dir: str
    :type options: list

    :returns: a tuple containing the prefix of the output files (the input
              prefix for the next script) and the type of the output files
              (``bfile``).

    """
    # Creating the output directory
    os.mkdir(out_prefix)

    # We know we need a bfile
    required_type = "bfile"
    check_input_files(in_prefix, in_type, required_type)

    # We need to inject the name of the input file and the name of the output
    # prefix
    script_prefix = os.path.join(out_prefix, "contamination")
    options += ["--{}".format(required_type), in_prefix,
                "--out", script_prefix]

    # We run the script
    try:
        contamination.main(options)
    except contamination.ProgramError as e:
        msg = "contamination: {}".format(e)
        raise ProgramError(msg)

    # Counting the number of markers used for contamination
    nb_autosomal = 0
    with open(script_prefix + ".to_extract", "r") as i_file:
        nb_autosomal = len(i_file.read().splitlines())

    # Reading the "contamination" file
    nb_tested_samples = 0
    contaminated_table = []
    nb_contaminated_samples = 0
    with open(script_prefix + ".bafRegress", "r") as i_file:
        header = None
        for i, line in enumerate(i_file):
            row = line.rstrip("\r\n").split("\t")
            if i == 0:
                contaminated_table.append(("sample", "estimate$^1$",
                                           "stderr$^1$", "tval", "pval",
                                           "callrate", "Nhom$^2$"))
                header = {name: i for i, name in enumerate(row)}

                for name in ("sample", "estimate", "stderr", "tval", "pval",
                             "callrate", "Nhom"):
                    if name not in header:
                        raise ProgramError("{}: missing column {}".format(
                            script_prefix + ".bafRegress",
                            name,
                        ))
                continue

            # One more sample
            nb_tested_samples += 1

            # Reading the data
            estimate = float(row[header["estimate"]])
            if estimate > 0.01:
                # This might be a contaminated samples
                contaminated_table.append((
                    latex_template.sanitize_tex(row[header["sample"]]),
                    "{:.4f}".format(float(row[header["estimate"]])),
                    "{:.4f}".format(float(row[header["stderr"]])),
                    "{:.4f}".format(float(row[header["tval"]])),
                    latex_template.format_numbers("{:.3e}".format(
                        float(row[header["pval"]]),
                    )),
                    "{:.4f}".format(float(row[header["callrate"]])),
                    "{:,d}".format(int(row[header["Nhom"]])),
                ))
                nb_contaminated_samples += 1

    # We write a LaTeX summary
    latex_file = os.path.join(script_prefix + ".summary.tex")
    try:
        with open(latex_file, "w") as o_file:
            print >>o_file, latex_template.subsection(
                contamination.pretty_name,
            )
            text = ("A total of {:,d} sample{} {} analyzed for contamination "
                    r"using \textit{bafRegress}\cite{bafRegress}. The "
                    "analysis was performed using {:,d} autosomal marker{}. "
                    "Using a threshold of 0.01, {:,d} sample{} {} estimated "
                    "to be contaminated.".format(
                        nb_tested_samples,
                        "s" if nb_tested_samples > 1 else "",
                        "were" if nb_tested_samples > 1 else "was",
                        nb_autosomal,
                        "s" if nb_autosomal > 1 else "",
                        nb_contaminated_samples,
                        "s" if nb_contaminated_samples > 1 else "",
                        "were" if nb_contaminated_samples > 1 else "was",
                        bafRegress="{bafRegress}",
                    ))
            print >>o_file, latex_template.wrap_lines(text)

            if nb_contaminated_samples > 0:
                label = re.sub(r"[/\\]", "_", script_prefix)
                text = (
                    r"Table~\ref{" + label + "} list all the samples that "
                    r"were estimated to be contaminated (\textit{i.e.} with "
                    r"an estimate $>0.01$)."
                )
                print >>o_file, latex_template.wrap_lines(text)

                # Getting the template
                longtable_template = latex_template.jinja2_env.get_template(
                    "longtable_template.tex",
                )

                # Rendering
                print >>o_file, longtable_template.render(
                    table_caption=r"List of all possible contaminated samples "
                                  r"(\textit{i.e.} with an estimate computed "
                                  r"by \textit{bafRegress} $>0.01$).",
                    table_label=label,
                    nb_col=len(contaminated_table[1]),
                    col_alignments="lrrrrrr",
                    text_size="scriptsize",
                    header_data=zip(contaminated_table[0],
                                    [1 for i in contaminated_table[0]]),
                    tabular_data=sorted(
                        contaminated_table[1:],
                        key=lambda item: item[0],
                    ),
                    footnotes=[
                        "$^1$Contamination estimate (with standard error)",
                        "$^2$Number of homozygous genotypes used in the model",
                    ],
                )

    except IOError:
        msg = "{}: cannot write LaTeX summary".format(latex_file)
        raise ProgramError(msg)

    # Writing the summary results
    with open(os.path.join(base_dir, "results_summary.txt"), "a") as o_file:
        print >>o_file, "# {}".format(script_prefix)
        print >>o_file, ("Number of possibly contaminated "
                         "samples\t{:,d}".format(nb_contaminated_samples))
        print >>o_file, "---"

    # We know this step doesn't produce an new data set, so we return the old
    # prefix and the old in_type
    return _StepResult(
        next_file=in_prefix,
        next_file_type=required_type,
        latex_summary=latex_file,
        description=contamination.desc,
        long_description=contamination.long_desc,
        graph_path=None,
    )