#!/usr/bin/python
# -*- coding: utf-8 -*-

from __future__ import division
import re
import sys
from pylab import *
from scipy import *
import math

def usage():
    print "USAGE : ./109titrage [angle] < text file"
    sys.exit(1)

def frange(start, stop, step):
    i = start
    while i < stop:
        yield i
        i += step

def launch():
    if not sys.stdin.isatty():
        f = sys.stdin
    else:
        print "Nothing in standard input"
        sys.exit(1)
    tab = []
    x = []
    y = []
    deriv_y = []
    eq_x = []
    eq_y = []
    for line in f:
        if (str(line) == "FIN" or str(line) == "FIN\n"):
            break
        try:
            tab = line.split(';')
        except:
            print "Bad separator"
            sys.exit(1)
        try :
            x.append(float(tab[0]))
        except:
            print "Problem in file : x"
            sys.exit(1)
        try :
            y.append(float(tab[1]))
        except:
            print "Problem in file : y"
            sys.exit(1)
    plot(x, y, 'b', label="V(pH)")
    xlim(0, x[-1])
    ylim(0, 14)
    for i in range(len(x)):
        try:
            deriv_y.append((y[i + 1] - y[i]) / (x[i + 1] - x[i]))
        except:
            deriv_y.append((y[i] - y[i - 1]) / (x[i] - (x[i - 1])))
            break
    plot(x, deriv_y, 'g', label="Derivee")
    title("Titrage par pHmetrie de l'acide benzoique par de la soude", fontsize = 16)
    xlabel('Volume (mL)', fontsize = 16)
    ylabel('pH', fontsize = 16)
    for i in frange(0, max(deriv_y), 0.01):
        eq_x.append(x[deriv_y.index(max(deriv_y))])
        eq_y.append(i)
    plot(eq_x, eq_y, 'black', label="Volume equivalent")
    legend(loc=2)
    print "Volume équivalent : %.2f mL" % x[deriv_y.index(max(deriv_y))]

def launch_angle(angle):
    print "Fonctionnalité non gérée"
    sys.exit()

fig = gcf()
fig.canvas.set_window_title('SansTitre-age1.jpg')

if (len(sys.argv) == 1):
    launch()
elif (len(sys.argv) == 2):
    try:
        angle = int(sys.argv[1])
    except:
        print "Please enter a number"
        usage()
    if (angle > 80 or angle < 10):
        print "ERROR : 10 <= a <= 80"
        usage()
    launch_angle(int(sys.argv[1]))
elif (len(sys.argv) != 2 or len(sys.argv) != 1):
    usage()

show()
