#!/usr/bin/env python

#script designed to get all the count files generated by HTSeq-count and merge into a final data frame. 
import argparse 
import pandas as pd
import os 

parser= argparse.ArgumentParser(description='script takes a folder with a bunch of .tab outputs of ht-seq and merges them into a genes x samples matrix') 
parser.add_argument('-d', help='input directory')
args = parser.parse_args()
files_to_merge = [f for f in os.listdir(args.d) if f.endswith('.tab') ]
dummy_df = pd.read_csv(args.d+files_to_merge[0], sep='\t',names=['id','count'], index_col=0)
final_df = pd.DataFrame(data=None, index=dummy_df.index)

for f in files_to_merge: 
   df_to_add = pd.read_csv(args.d+f, sep='\t', index_col=0, names=[f.split('.')[0].split('/')[-1]]) 
   final_df = pd.merge(final_df, df_to_add, left_index=True, right_index=True) 

final_df.to_csv(args.d+'htseq_counts_output_merged.csv') 
