#!/usr/bin/env python3
# -*- coding: utf8 -*-

# Gaik Tamazian, 2019
# mail (at) gtamazian (dot) com

"""
Split RADSeq FASTQ file to a pair of FASTQ files.

RADSeq FASTQ files contain both forward and reverse reads which names
have suffixes '_1' and '_2', respectively. The script produces two FASTQ
files that contain forward and reverse reads and removes the suffixes
from the read names.

The script has two command-line arguments: a RADSeq FASTQ file name and
the output file name prefix.
"""

import sys
from .. import fastq

assert sys.version_info >= (3, 5), "Python 3.5 or higher required"


def split_radseq_fastq(fastq_fname, out_prefix):
    """
    Split a RADSeq FASTQ file to a pair of FASTQ files which names have
    the specified prefix.

    :param fastq_fname: a RADSeq FASTQ file name
    :param out_prefix: a prefix of output FASTQ files
    """
    with open(out_prefix + "_1.fq", "w") as fwd_fastq, \
            open(out_prefix + "_2.fq", "w") as rev_fastq:
        for read in fastq.iterate_reads(fastq_fname):
            assert read[0].endswith("_1") or read[0].endswith("_2"), \
                    "the read name must end with '_1' or '_2'"
            if read[0].endswith("_1"):
                read = (read[0][:-2], ) + read[1:]
                fwd_fastq.write(fastq.print_read(read))
            else:
                read = (read[0][:-2], ) + read[1:]
                rev_fastq.write(fastq.print_read(read))


def main(args):
    if len(args) != 3:
        print("Usage: split_radseq_fastq radseq.fq out_prefix",
              file=sys.stderr)
        sys.exit(1)
    split_radseq_fastq(args[1], args[2])


if __name__ == "__main__":
    main(sys.argv)
