#!/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
import IlluminaUtils.utils.helperfunctions as h

def main(input_file_path, output_file_path, trim_from, trim_to):
    input_file = u.FastQSource(input_file_path, compressed=(True if input_file_path.endswith('.gz') else False))
    output_file = u.FastQOutput(output_file_path, compressed=(True if output_file_path.endswith('.gz') else False))

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

    input_file.close()
    output_file.close()

    sys.stderr.write('\n')


if __name__ == '__main__':
    import argparse

    parser = argparse.ArgumentParser(description='Trim Illumina reads')
    parser.add_argument('input_file', metavar = 'FILE_PATH', help = 'FASTQ file to be trimmed')
    parser.add_argument('output_file', 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()

    try:
        main(args.input_file, args.output_file, args.trim_from, args.trim_to)
    except h.ConfigError as e:
        print(e)
        sys.exit(-1)
    except u.FastQLibError as e:
        print(e)
        sys.exit(-2)
