#!/usr/bin/env python
 
import re
 
InFileName = "manage-orders.html"
InFile = open(InFileName, 'r')

# First step: Find the order numbers in "manage-orders.html"

OrderList = []

for Line in InFile:
	Result = str("")
	SearchStr = "tcl%22[^\d]+(\d+)" # Regular expression to find the order numbers
	Result = re.search(SearchStr, Line) # Return the result of the query or 'None' if nothing is found
	if Result != None: # Add the new order number to a list if found in the line
		OrderNumber = str(Result.group(1))
		OrderList += [OrderNumber]
		
print OrderList
InFile.close()
OutFileName = "ListOligos.csv"
OutFile = open(OutFileName, 'w')

OrderNumber = 0
NameOligos = []
SeqOligos = []
LineNumber = 0
NbOligos = 0
ListNbOligos = []

for OrderNumber in OrderList: # Grosse boucle qui ouvre une part une les commandes et va chercher les infos sur les oligos
	
	InFileName = "order%s.html" % (OrderNumber)
	InFile = open(InFileName, 'r')
	InFileTwo = open(InFileName, 'r')
	FileLines = InFileTwo.readlines()
	
	for Line in InFile:
		GoodLine = re.search("bp", Line)
		if GoodLine != None:
			
			# Ajout de la sequence dans la liste des Oligos
			SearchOligo = re.search("<td>([\w, ]+)", Line)
			SeqOligo = str(SearchOligo.group(1)).replace(" ","")
			SeqOligos += [SeqOligo] 
			
			# Ajout du nom de la sequence dans la liste des noms
			SearchName = re.search("<td>([\w, ]+)", FileLines[LineNumber - 5])
			NameOligo = str(SearchName.group(1)).strip()
			NameOligos += [NameOligo]
				
			# Compteur du nombre d'Oligos par commande
			NbOligos += 1
			
		#Incrementation des lignes
		LineNumber += 1
	
	ListNbOligos += [NbOligos]		
	InFile.close()
	InFileTwo.close()
	LineNumber = 0
	NbOligos = 0
	
# Creation d'une liste avec les numeros de commandes pour chaque oligo
OrderNb = 0
OligoOrders = []

for Order in OrderList:
	for Oligo in range(0, ListNbOligos[OrderNb]):
		OligoOrders += [Order]
	OrderNb += 1
	
print SeqOligos
print NameOligos
print ListNbOligos
print OligoOrders

Headstring = "Order_Number,Oligo_Name,Oligo_Sequence\n"
OutFile.write(Headstring)

for Oligo in range(0,len(SeqOligos)): 
	OligoData = "%s,%s,%s\n" % (OligoOrders[Oligo], NameOligos[Oligo], SeqOligos[Oligo])
	OutFile.write(OligoData)
	
OutFile.close()

