<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def _calculate_mapping_reads(items, work_dir, input_backs=None):
 """Calculate read counts from samtools idxstats for each sample. Optionally moves over pre-calculated mapping counts from a background file. """

    out_file = os.path.join(work_dir, "mapping_reads.txt")
    if not utils.file_exists(out_file):
        lines = []
        for data in items:
            count = 0
            for line in subprocess.check_output([
                "samtools", "idxstats", dd.get_align_bam(data)]).decode().split("\n"):
                if line.strip():
                    count += int(line.split("\t")[2])
            lines.append("%s\t%s" % (dd.get_sample_name(data), count))
        with file_transaction(items[0], out_file) as tx_out_file:
            with open(tx_out_file, "w") as out_handle:
                out_handle.write("\n".join(lines) + "\n")
                if input_backs:
                    for input_back in input_backs:
                        with open(input_back) as in_handle:
                            for line in in_handle:
                                if len(line.split()) == 2:
                                    out_handle.write(line)
    return out_file