#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import math
import sys

def print_help():
    print("USAGE")
    print("\t   ./107transfer file\n")
    print("DESCRIPTION")
    print("\t   file\t a cvs file containing 'vol;ph' lines");

def error(var):
    content = var.split('\n')
    check = []
    med = 0
    for i in content:
        check.append(i.split(';'))
    if check[-1] == ['']:
        check.pop()
    if len(check) == 0:
        print("File Error")
        print("\tEmpty file")
        exit(84)
    for i in check:
        if len(i) != 2:
            print("Val Error")
            print("\tWrong number on a single line")
            exit(84)
        for j in i:
            try:
                j = float(j)
            except:
                print("Val Error")
                print("\tOne or multiple value aren't number")
                exit(84)
        if float(i[0]) <= med:
            print("Val Error")
            print("\tVolume value must increase and be positive")
            exit(84)
        med = float(i[0])
    return (check)

def derivation(tab):
    point = 0.0
    derivation = []
    a = 0
    b = 1
    print("Derivative:")
    derivation.append(0)
    for i in range(1, len(tab) - 1):
        derivation.append((tab[i + 1][1] - tab[i - 1][1]) / (tab[i + 1][0] - tab[i - 1][0]))
        print("%.1f ml -> %.2f" % (tab[i][0], derivation[i]))
        if point < derivation[i]:
            point = derivation[i]
            b = tab[i][0]
            a = i
    derivation.append(0)
    print("\nEquivalent point at %.1f ml\n" % b)
    print("Second derivative:")
    for i in range(1, len(derivation) - 3):
        p = (derivation[i + 2] - derivation[i]) / (tab[i + 2][0] - tab[i][0])
        print("%.1f ml -> %.2f" % (tab[i + 1][0], p))
    print("\nSecond derivative estimated:")

    res = b
    e = 0
    if a - 2 < 0:
        i = tab[a - 1][0]
        p = v1 = 0
    else:
        i = tab[a - 1][0]
        p = v1 = (derivation[a] - derivation[a - 2]) / (tab[a][0] - tab[a - 2][0])
    v2 = (derivation[a + 1] - derivation[a - 1]) / (tab[a + 1][0] - tab[a - 1][0])
    c = (v2 - v1) / (10 * (tab[a][0] - tab[a - 1][0]))
    while i - 0.05 < tab[a][0]:
        print("%.1f ml -> %.2f" % (i, v1))
        if math.fabs(p) > math.fabs(v1) and a - 1 > 0:
            p = v1
            res = i
        v1 += c
        i += 0.1

    if a + 3 >= len(derivation):
        c = -v2 / 10
    else:
        v1 = (derivation[a + 2] - derivation[a]) / (tab[a + 2][0] - tab[a][0])
        c = (v1 - v2) / (10 * (tab[a + 1][0] - tab[a][0]))
    v2 += c
    while i - 0.05 < tab[a + 1][0]:
        print("%.1f ml -> %.2f" % (i, v2))
        v2 += c
        i += 0.1
        if math.fabs(p) > math.fabs(v2) and a + 3 < len(tab):
            p = v2
            res = i
    print("\nEquivalent point at %.1f ml" % res)
    return derivation

def main():
    if len(sys.argv) != 2:
        print("Arg Error:")
        print("\tWrong arg number")
        exit(84)
    if sys.argv[1] == "-h":
        print_help()
    try:
        with open(sys.argv[1]): pass
    except IOError:
        print("File Error:")
        print("\tFile not found")
        exit(84)
    var = open(sys.argv[1], 'r').read()
    value = error(var)
    for i in range(len(value)):
        for j in range(len(value[i])):
            value[i][j] = float(value[i][j])
    derivation(value)
    return (0)

main()
