#!/usr/bin/python3

import sys
from math import *
from numpy import *

'''
program normalizedHistogram.py
	- from the user provided data and the number of bins this program determines the histogram approximation 
	to probability density and store it in file with
	extension .hist  that can be 
	visualized using, e.g., xmgrace or gnuplot

	- example of usage:

        python3 normalizedHistogram.py mc.dat 100

	in this case, data are read from the file mc.dat (one item per line assumed)
	and histogram with 100 bins (covering interval between minimal and maximal value
	found in mc.dat) and result is written into file mc.dat.hist
'''

kB = 8.6173857e-5

f1 = sys.argv[1]
fo1 = f1+".hist"

# a=float(sys.argv[1])
# b=float(sys.argv[2])
bins = int(sys.argv[2])

f1 = open(f1, 'r')

x1 = []
for line in f1.readlines():
    line = line.split()
    x1.append(float(line[0]))
f1.close()

a1 = min(x1)
b1 = max(x1)
step1 = abs(b1-a1)/bins
norm1 = len(x1)*step1

hist1 = zeros(bins, float)
for i in range(len(x1)):
    for j in range(bins-1):
        if x1[i] > a1+j*step1 and x1[i] < a1+(j+1)*step1:
            hist1[j] += 1.
            break


fo1 = open(fo1, 'w')

for i in range(len(hist1)):
    xx1 = a1+(i+1)*step1-step1/2.
    rrr1 = str(xx1)+'\t'+str(hist1[i]/norm1)+'\n'
    fo1.write(rrr1)

fo1.close()
