import os
import re
import numpy as np
import swr

est = re.compile('estimated',re.IGNORECASE)

xsec_files = os.listdir('xsec\\')

for xf in xsec_files:
    if est.search(xf) != None:    
        h,xsec = swr.load_xsec('xsec\\'+xf)
        raw = h[0].split()
        
        npt,x,y,area = int(raw[-4]),float(raw[-3]),float(raw[-2]),float(raw[-1])
        print xf,xsec[:,1].min()      
        if xsec[:,1].min() > -1.0:
         
            xsec[np.where(xsec[:,1] == xsec[:,1].min()),1] = -1.0
        h_new = ' {0:10d} {1:10.3e} {2:10.3e} {3:10.3e} '.format(xsec.shape[0],x,y,area)
        name_new = xf.replace('ESTIMATED','LOWERED')
        swr.write_profile('xsec\\'+name_new,xsec,h_new)

    #xsec_c = np.array((xc,zc)).transpose()    
    #return xsec_c

            



top = np.loadtxt('..\\_model\\bro.01\\ref\\top_mod.ref')

xsec_dir = 'xsec_navd\\'
xsec_files = os.listdir(xsec_dir)
xsecs = {}
for xname in xsec_files:    
    header,xsec = swr.load_xsec(xsec_dir+xname)
    xsecs[xname] = xsec
    
shapename = '..\\_gis\\scratch\\sw_reaches_conn_SWRpolylines'
shapes,records = shapefile.load_as_dict(shapename)
wr = shapefile.Writer()
wr.field('reach',fieldType='N',size=10,decimal=0)
wr.field('top',fieldType='N',size=20,decimal=10)
wr.field('xsec_min',fieldType='N',size=20,decimal=10)
wr.field('xsec_max',fieldType='N',size=20,decimal=10)
wr.field('xsec_depth',fieldType='N',size=20,decimal=10)
wr.field('mod_depth',fieldType='N',size=20,decimal=10)
wr.field('depth_diff',fieldType='N',size=20,decimal=10)
wr.field('xsec_perm',fieldType='N',size=20,decimal=10)
wr.field('mod_perm',fieldType='N',size=20,decimal=10)
wr.field('perm_diff',fieldType='N',size=20,decimal=10)
import os
import re
import numpy as np
import swr

est = re.compile('estimated', re.IGNORECASE)

xsec_files = os.listdir('xsec\\')

for xf in xsec_files:
    if est.search(xf) != None:
        h, xsec = swr.load_xsec('xsec\\' + xf)
        raw = h[0].split()

        npt, x, y, area = int(raw[-4]), float(raw[-3]), float(raw[-2]), float(
            raw[-1])
        print xf, xsec[:, 1].min()
        if xsec[:, 1].min() > -1.0:

            xsec[np.where(xsec[:, 1] == xsec[:, 1].min()), 1] = -1.0
        h_new = ' {0:10d} {1:10.3e} {2:10.3e} {3:10.3e} '.format(
            xsec.shape[0], x, y, area)
        name_new = xf.replace('ESTIMATED', 'LOWERED')
        swr.write_profile('xsec\\' + name_new, xsec, h_new)