from matplotlib import pyplot as plt
import numpy as np

fid = open('Kuj2012-13_inflow.dat','r')

depth = 12.

M = 40
dz = 0.5*depth/float(M+1) #for the upper level only
dt = 15.2 #days

ncol_width = 2
ncol_u = 3

disch = []
line = '0'
j = -1
while(line != ''):
	j += 1
	disch.append(0.)
	for i in range(M+1):
		line = fid.readline()
		print(line)
		if line != '':
			line = line.split()
			disch[j] += float(line[ncol_width-1])*dz*float(line[ncol_u-1])

time = []
for i in range(j+1):
	time.append(dt*i)

print(len(disch),len(time))
plt.plot(time,disch)
plt.title('Inflow')
#plt.show()
fid.close()



#Outflow
fid = open('Kuj2012-13_outflow.dat','r')

dischout = []
line = '0'
j = -1
while(line != ''):
	j += 1
	dischout.append(0.)
	for i in range(M+1):
		line = fid.readline()
		print(line)
		if line != '':
			line = line.split()
			dischout[j] += float(line[ncol_width-1])*dz*float(line[ncol_u-1])

print(len(dischout),len(time))
plt.plot(time,dischout)
plt.title('Outflow')
plt.show()
fid.close()

dd = np.asarray(dischout) - np.asarray(disch)

fout = open('Kuj2012-13_inflow_new.dat','w')
fid = open('Kuj2012-13_inflow.dat','r')
#fid.seek(0)

j = -1
line = [' ']
while(line != ''):
	j += 1
	line = []
	for i in range(M+1):
		line.append(fid.readline())
		#print(line)
		if line[i] != '':
			fout.write(str(line[i]))
			#disch[j] += float(line[ncol_width-1])*dz*float(line[ncol_u-1])

	line[0] = line[0].split()
	print(line[0][ncol_width-1], dd[j],dz,float(line[0][ncol_u-1]))
	if (float(line[0][ncol_u-1]) != 0.):
		line[0][ncol_width-1] = str(dd[j]/dz/float(line[0][ncol_u-1]))
	else:
		line[0][ncol_width-1] = str(0.)
	line_ = ' '.join(line[0])
	fout.write(str(line_)+'\n')
	for i in range(1,M+1,1):
		fout.write(str(line[i]))
		#line[i] = line[i].split()
		#print(line[i])
		#line[i][ncol_width-1] = str(dd[j]/dz/float(line[i][ncol_u-1]))
		#line_ = ' '.join(line[i])
		#fout.write(str(line_)+'\n')



