import numpy as np
import glob
import re
import commands
import os

tunit=6.88027e+14/3.157e7

folderlist = glob.glob('RD????')
upperfolder = os.getcwd()
for folder in folderlist:
 n = int(re.sub(r'\D',"",folder))
 os.chdir(upperfolder+"/"+folder)
 name,= glob.glob('RedshiftOutput????')

 a=commands.getoutput('grep CurrentTimeIdentifier '+name)
 SnapCurrentTimeIdentifier=float(a.split()[2])
 a=commands.getoutput('grep InitialTime '+name)
 currenttime=float(a.split()[2])

 f=open('PopII_haloes_%04i.txt'%n,'r')
 fo = open('PopII_halos_stellarmass_%04i.txt'%n,'w')
 lines = f.readlines()
 f.close()

 i = 0
 while i <len(lines):
   haloid = int(lines[i].split()[0])
   i = i+1
   sm = 0.0;asm = 0.0
   if lines[i].split()[0] == '0':
      i=i+3
   else:
      i = i+1
      while lines[i] != "\n":
        mass = float(lines[i].split()[1])
        ct = float(lines[i].split()[2])
        sm = sm + mass
        if currenttime - ct < 2.0e7/tunit:
           asm=asm+mass
        i=i+1
      i=i+2
   fo.write(str(haloid)+" "+str(sm)+" "+str(asm)+"\n")

 fo.close()
 os.chdir(upperfolder)
