cid, resnum = args.resid

for seqf in seqfs:
	pdbf = General.changeExt( seqf.replace(args.head + '_', ''), 'pdb')
	if not os.path.isfile(pdbf):
		print(pdbf + ' doesn\'t exist!')
		continue

	outf = General.changeExt(pdbf, args.o)

	if args.wgap != None: # specific to gap
		assert args.conR == False, 'wgap and conR cannot be specified simultaneously'
		dirname = General.getBase(pdbf)
		pdbf = args.wgap + '/' + dirname + '/'+ pdbf

	index = PDB.findPositionInPDB(pdbf, resnum, cid)
	aacol = Analyze.readColumn(seqf, index, top = args.uplimit)

	if args.conR: # should contacting residue be constrained?
		conid = General.getBase(seqf).split('_')[-1]
		ccid, cresnum = conid[0], conid[1:]
		cindex = PDB.findPositionInPDB(pdbf, cresnum, ccid)
		cres = PDB.getResByInd(pdbf, ccid, cresnum).getResname()
		cres = PDB.t2s(cres)
		caacol = Analyze.readColumn(seqf, cindex, top = args.uplimit)

	if args.env != None: # environment corrected counts
		envf = General.getBase(seqf.replace(args.head, args.envhead)) + '.' + args.env
		if not os.path.isfile(envf):
			print(envf + ' doesn\'t exist!')
			continue
        base = General.getBase(pdb)
        matchf = args.head + '_' + base + '.match'
        if not os.path.isfile(matchf):
            continue
        outname = General.getBase(matchf) + '.' + args.o
        if os.path.isfile(outname):
            continue
        if outname in seen:
            continue
        seen[outname] = 1

        # for the gap test only
        if args.wgap != None:
            pdb = args.wgap + '/' + mut.dir + '/' + pdb
        ##
        pos = PDB.findPositionInPDB(pdb, str(mut.n), mut.c)
        if pos == -1:
            print('cannot found the residue in fragment pdb: '+ pdb)
            continue

        pdb = General.removePath(pdb)
        cmd = ['python', selfbin +'/envForMatches.py','--m', matchf, '--n', str(pos-1), '--o', outname]
        if args.uplimit != None:
            cmd.extend(['--uplimit', args.uplimit])
        if args.wgap != None:
            cmd.append('--wgap')
        cmd = ' '.join(cmd)
        job = General.jobOnCluster([cmd], mut.dir, os.path.realpath(outname))
        job.submit(3)
        jobs.append(job)
        sleep(0.5)
dirs = [x for x in os.listdir('.') if os.path.isdir(x)]
dirs.sort()
odir = os.getcwd()

for d in dirs:
	os.chdir(odir)
	os.chdir(d)
	pdbs = glob.glob('*.pdb')
	cmds = []
	resn = int(d.split('_')[1][2:])
	for pdb in pdbs:
		matchf = args.head + '_' + General.changeExt(pdb, 'match')
		if not os.path.isfile(matchf):
			continue

		pos = PDB.findPositionInPDB(pdb, resn)
		# if output file is already there, skip the job
		if os.path.isfile('nr'+args.id +'_'+matchf):
			continue

		cmd = ['python', selfbin + '/removeLocalRedundancy.py', '--m', matchf, '--cres', str(pos), '--id', args.id, '--outh', 'nr'+args.id]
		if not args.db == None:
			cmd.extend(['--db', args.db])
		if args.conR:
			conresn = General.getBase(pdb).split('_')[2][1:]
			conpos = PDB.findPositionInPDB(pdb, conresn)
			cmd.extend(['--conres', str(conpos)])
		if args.env != None:
			cmd.extend(['--env', args.env])
		cmd = ' '.join(cmd)
		cmds.append(cmd)
    pdbs = glob.glob('*.pdb')
    pdbs.sort()

    for pdb in pdbs:
        base = General.getBase(pdb)
        matchf = args.head + '_' + base + '.match'
        if not os.path.isfile(matchf):
            continue
        outname = General.getBase(matchf) + '.' + args.o
        if os.path.isfile(outname):
            continue
        if outname in seen:
            continue
        seen[outname] = 1

        pos = PDB.findPositionInPDB(pdb, str(mut.n), mut.c)
        if pos == -1:
            print('cannot found the residue in fragment pdb: '+ pdb)
            continue

        con = base.split('_')[-1]
        conc, conn = con[0], con[1:]
        conpos = PDB.findPositionInPDB(pdb, str(conn), conc)

        cmd = ['python', selfbin +'/envForMatches_pair.py','--m', matchf, '--n', str(pos-1), str(conpos-1), '--o', outname]
        if args.uplimit != None:
            cmd.extend(['--uplimit', args.uplimit])

        cmd = ' '.join(cmd)
        job = General.jobOnCluster([cmd], mut.dir, os.path.realpath(outname))
        job.submit(3)