
#code to convert fasta file with Ns and \ns and titles and stuff to just ATGC; NOTHING ELSE
#each fasta file contains the whole chromosome
#this code will read a chromosome fasta file and then split it into MANY text files
#each text file will contain up to 1,000,000 letters


import os
#####################
chromosome_number=1 # CHANGE THIS ONE LINE TO SET ALL THE FILE NAMES
#for example if you want to generate all the files for chromosome 1, set ^ to 1 
#################

#create an output folder for the chromosome files
output_dir = 'c'+str(chromosome_number)
if not os.path.exists(output_dir):
    os.makedirs(output_dir)

file_number=0 # to keep track of (for a given chromosome fasta file) which number output file 

f=open('sequence'+str(chromosome_number)+'.fasta','r') #open fasta file
lines= f.readlines()
lines[0]="NNN" #overwrite the title so the ATGCs in the title dont get added to the sequence
print(lines[0]) #not really necessary
f.close()


l=0; #line number
d=0; #letter number
file_out='c'+str(chromosome_number)+'s'+str(file_number)+'.txt' #text file to save just the ATGCs to
file_path = os.path.join(output_dir, file_out) #code to save that file in that chromosome output folder
out=open(file_path,'a')

for line in lines:
    for letter in line:
    
        if letter in ['A','T','G','C']:
            out.write(letter)
            d=d+1
            if d==1000000:
                d=0
                out.write("5") #a 5 is added to the end of each file for the arduino code to detect that the file is finished
                out.close()
                file_number+=1
                file_out='c'+str(chromosome_number)+'s'+str(file_number)+'.txt' #text file to save just the ATGCs to
                file_path = os.path.join(output_dir, file_out)
                out=open(file_path,'a')



    l=l+1
    print("Percent done: "+str(round(l/len(lines)*100,2)))

out.write("5")       
out.close()
#print(list_of_files)

#just a quick check to see if it worked
file_path = os.path.join(output_dir, 'c'+str(chromosome_number)+'s0.txt')
out=open(file_path,'r')
line=out.readline()
out.close()
print(line[0:10]) #can check against first ATGCs in Fasta file to make sure they match


 
