#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2011, A. Murat Eren
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
#
# Please read the COPYING file.

import os
import sys

import IlluminaUtils.lib.fastqlib as u


def main(input_file_path, output_file_path, trim_from, trim_to, compressed):
    input = u.FastQSource(input_file_path, compressed)
    output = u.FastQOutput(output_file_path, compressed)

    while input.next(trim_from = trim_from, trim_to = trim_to, raw = True):
        if input.p_available:
            input.print_percentage()
        output.store_entry(input.entry)

    sys.stderr.write('\n')
    return


if __name__ == '__main__':
    import argparse

    parser = argparse.ArgumentParser(description='Trim Illumina reads')
    parser.add_argument('input', metavar = 'FILE_PATH', help = 'FASTQ file to be trimmed')
    parser.add_argument('output', metavar = 'FILE_PATH', help = 'Where trimmed sequences will be written (default: [-i]-TRIMMED-TO-[-l]')
    parser.add_argument('-f', '--trim-from', type=int, metavar = 'INT', help = 'Trim from', default=0)
    parser.add_argument('-t', '--trim-to', type=int, metavar = 'INT', help = 'Trim to', default=sys.maxsize)

    args = parser.parse_args()

    input_file_path = args.input
    
    compressed = input_file_path.endswith('.gz')
    
    if compressed and not args.output.endswith('.gz'):
        output_file_path = args.output + '.gz'
    else:
        output_file_path = args.output

    sys.exit(main(input_file_path, output_file_path, args.trim_from, args.trim_to, compressed))
