#!/usr/bin/python3

import math
import sys
import re
import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

def getv(ind,val):
    if len(sys.argv) > ind and len(sys.argv[ind])>0:
        return sys.argv[ind]
    else:
        return val

if len(sys.argv) < 2:
    raise ValueError('Please provide input file name')
 
filename = sys.argv[1]

thresh1 = float(getv(2,1026.5))
thresh2 = float(getv(3,1030.0))
thresh3 = float(getv(4,1028))
thresh4 = float(getv(5,1028.5))

title = getv(6,filename)
opt = getv(7,"")

nominal_field = (thresh1>800 and thresh3>800)

datarr = []
timarr = []
dtarr = []
Xarr = []
Yarr = []
Zarr = []
Farr = []
Tarr = []
tarr = []
array=[]
off = None
dtarr1 = []
Farr1 = []

file = open(filename,'r')
for line in file.readlines():
    array+=[line]
    a,b,c,d,e,f,g,h = line.split()
    if off is None:
        pt=dt.datetime.strptime(b,'%H:%M:%S')
        total_seconds=pt.second + pt.minute*60 + pt.hour*3600
        off=int(re.sub(',.*','',h))-total_seconds

    xfield = float(re.sub(',','.',c))
    field = float(re.sub(',','.',f))
    if (not nominal_field or (xfield<-10 and field>800)) and c+d+e+f+g!="00000": # only correct polarity and field close to nominal
        dtarr += [dt.datetime.strptime(a+' '+b+re.sub('.*,',',',h)[0:7],'%d.%m.%Y %H:%M:%S,%f')]
        datarr += [a]
        timarr += [b]
        Xarr += [abs(float(re.sub(',','.',c)))]
        Yarr += [abs(float(re.sub(',','.',d)))]
        Zarr += [abs(float(re.sub(',','.',e)))]
        Farr += [float(re.sub(',','.',f))]
        Tarr += [float(re.sub(',','.',g))]
        tarr += [float(re.sub(',','.',h))-off]
        if (field<thresh3 or field>thresh4) and field>thresh1 and field<thresh2:
            dtarr1 += [dtarr[-1]]
            Farr1  += [Farr[-1]]

file.close()

n=len(Farr)
print(title)
print('Number of points %d' % n)
if n>0:
    dt = dtarr[-1] - dtarr[0]
    if dt.days<3:
        plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M'))
    else:
        plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
        plt.gca().xaxis.set_major_locator(mdates.DayLocator())
    plt.gca().set_ylim(thresh1,thresh2)
    plt.plot(dtarr, Farr, linewidth=2, label="Total field")
    #plt.plot(dtarr1,Farr1, 's', color='red', label="Field outside limits")
    plt.scatter(dtarr1,Farr1, color='red', label="Field outside limits [%s,%s]"%(thresh3,thresh4))
    #plt.plot(dtarr, Xarr, linewidth=2, label="abs(X-axis)")
    #plt.plot(dtarr, Yarr, linewidth=2, label="abs(Y-axis)")
    #plt.plot(dtarr, Zarr, linewidth=2, label="abs(Z-axis)")
    plt.gcf().autofmt_xdate()
    plt.grid()
    plt.title(title)
    plt.legend(loc="upper right")
    if opt=="":
        plt.savefig("field.png")
    else:
        plt.show()
else:
    print('Field was below %f or above %f all the time' % (thresh1,thresh2))
