#############################################################################################################################################
#Copyright: Please email the author before using this code.
#Description: This file reads a volumninous file from the end skips the last line
#then reads the line where the 1st word matches AVG for average. Prints the 3rd 
#and the 5th column variables for each line, until the 1st word is not AVG. This 
#code works to take input from the DIPsDIV.py output file which generates the 
#average score of divergence file.
#USAGE $ python3 programname fileWithDivergenceScore fileNametoStoreSCoreAverageScore fileToRetrieveColumnNumber jumpingIndexCountSteps
#Example: $ python3 reverseReadMulti.py divergence reverse multiColumnSplitSample.csv 2
#where DivergenceScore.txt is the file generated by DIPsDIV.py script.
#Author: Abhishek N. Singh, Email: aby.narain@gmail.com
#Date: 10th May 2019
##############################################################################################################################################
import numpy as np
import pandas as pd
import sys

#We need to read the SNPs plus DIPs file in order to get the number of column variables
dataset = pd.read_csv(sys.argv[3])

def revScore(col): #Reverse the score for file created for Column variable
    readFileName = "./readwrite/" + sys.argv[1] + str(col)
    try:
        f = open(readFileName , 'r').readlines()[::-1]
    except FileNotFoundError: #If the file is not found we simply break out
        return None #Here we exit the function with no return value
    firstline = f.pop(0) #skipping the 1st line from bottom which has the total score
    writeFileName = "./readwrite/" + sys.argv[2] + str(col)
    fWrite = open(writeFileName, 'w') #
    #next(f) #Skipping the 1st line
    for line in f:
        words = line.split()
        try: #We put this i Try Exception Mode since there would be some files to read with no value in it as there were no DIPs for the column
            if words[0] != "AVG":
                break
        except IndexError:
            break
        else:
            fWrite.write(words[2]+"\t"+words[4]+"\n")
            #print(words[2],"\t",words[4])
    fWrite.close()
	
for i in range(1,len(dataset.columns),int(sys.argv[4])):
	#print(i)
	revScore(i)
