__author__ = 'Alena Zablotskaya, Vitaliy Istomov. Laboratory for Cytogenetics and Genome Research (Prof. Dr. Joris R. Vermeesch), KU Leuven, Leuven, Belgium'
#This script trims specified number of bases from each side of a sequencing read, and outputs each trimmed sequence in one line.
#Usage example: python3.4 /path/to/this/script/trimmer.py input_file.fasta input_file_noAdapt.fasta -t 32

def do_stuff(name, seq, output, trim):
    seq = seq.replace("\n", "")
    if trim == 0:
        result = seq
    else:
        result = seq[trim:(trim * -1)]
    if len(result) > 0:
        output.write(name)
        output.write(result + "\n")

def process_input(input_filename, output_filename, trim):
    buffer_seq = ""
    buffer_name = ""
    fa_output = open(output_filename, "w")
    not_first_iteration = False
    with open(input_filename) as fa_input:
        for line in fa_input:
            if line.startswith(">"):
                if not_first_iteration:
                    do_stuff(buffer_name, buffer_seq, fa_output, trim)
                    buffer_seq = ""
                buffer_name = line
            else:
                not_first_iteration = True
                buffer_seq += line
                if not buffer_seq.endswith("\n"):
                    do_stuff(buffer_name, buffer_seq, fa_output, trim)
        do_stuff(buffer_name, buffer_seq, fa_output, trim)

import sys
import argparse

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('input_file', help="Path to input FASTA file")
    parser.add_argument('output_file', help="Path to resulting trimmed file")
    parser.add_argument('-t', '--trim', type=int, default=32, help="Amount of bases to trim as integer")
    args = parser.parse_args()
    print(args)
    process_input(args.input_file, args.output_file, int(args.trim))

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