import re
import subprocess
import os
TYPES_C = []
TYPES_H = []

with open('atomtypes.atp','r') as types:
	for line in types:
		if line.startswith(' opls_') and len(line.strip().split()) > 3:
			#print(line.strip().split())
			type = line.strip().split()[0]
			mass = int(float(line.strip().split()[1]))
			if mass == 12:
				TYPES_C.append(type)
			elif mass == 1:
				TYPES_H.append(type)
print(len(TYPES_C))
print(len(TYPES_H))

line_with_type_C =  r'\s*\d\s*CX'
line_with_type_H =  r'\s*\d\s*HX'
i=0
for type_c in TYPES_C:
	i+=1
	j=0
	for type_h in TYPES_H:
		j+=1
		filename = 'et_correct_'+str(i)+'_'+str(j)+'.top'
		with open(filename,'w') as top_correct:
			with open('et.top','r') as top:
				for line in top:
					hit_C = re.search(line_with_type_C, line)
					hit_H = re.search(line_with_type_H, line)
					if  hit_C != None:
						line = line.split('CX')
						line = line[0] + type_c + line[1]
						top_correct.write(line)
					elif  hit_H != None:
						line = line.split('HX')
						line = line[0] + type_h + line[1]
						top_correct.write(line)
					else:
						top_correct.write(line)
						pass
		try:
			test = subprocess.check_call(['grompp','-f', 'be.mdp', '-c', 'et.gro', '-p',filename,'-o','et_test.tpr'])
			print(filename)
			print(TYPES_C[i], TYPES_H[j])
			break
		except Exception, e:
			#print(e)
			os.remove(filename)
			os.remove('mdout.mdp')
		#break
	#break