import re
f = open('1qpz.txt', 'r')
file = f.readlines()
f.close()
clust = {}
clustno = re.compile(r'^([0-9]+)\s')
atomno = re.compile(r'\s([0-9]+)\n')
for line in file:
        no = clustno.match(line).group(1)
        try:
            t = clust[no]
        except KeyError:
            clust[no] = []
        clust[no].append(int(atomno.search(line).group(1)))
        
todel = []
for key in clust:
    if len(clust[key]) < 10:
        todel.append(key)
for key in todel:
    del clust[key]
    
com = open('command.txt', 'a')

selenames = []
for el in clust:
        clust[el] = sorted(clust[el])
        i = 0
        L = len(clust[el])
        t = str(clust[el][i])
        temp = [t,t]
        while i < L-1:
                if clust[el][i+1] == clust[el][i] + 1:
                        temp[-1] = clust[el][i] + 1
                else:
                        temp[-1] = str(temp[-1])
                        t = str(clust[el][i+1])
                        temp.append(t)
                        temp.append(t)
                i += 1
        temp[-1] = str(temp[-1])
        #if last element
        com.write('select phobo' + str(el)+ ', id ')
        L = len(temp)
        i = 1
        while i < L-1:
           com.write(temp[i-1]+'-'+temp[i]+'+')
           i+=2
        com.write(temp[i-1]+'-'+temp[i]+'\n')
        selenames.append('phobo'+str(el))

towrite = 'select ALLphobo, '
for el in selenames:
        towrite = towrite + el + ' or '
com.write(towrite[:-4])
com.close()
