import skrf as rf
import numpy as np
import os
import xlsxwriter
    
def write_s1p(filename, distance, data):
    f = open('Files_Time/' + filename + ".s1p","w+")
    f.write('!Keysight Technologies N9923A: A.08.19\n')
    f.write('!Date: Thursday, 16 January 2020 11:30:00\n')
    f.write('!TimeZone: (GMT-03:00) Brasilia!Model: N9923A\n')
    f.write('!Serial: MY51491501\n')
    f.write('!GPS Latitude: \n')
    f.write('!GPS Longitude: \n')
    f.write('!GPS TimeStamp: 0001-01-01 00:00:00Z\n')
    f.write('!GPS Seconds Since Last Read: 0\n')
    f.write('!CHECKSUM:1078980270\n')
    f.write('!Correction: S11(ON U)\n')
    f.write('!S1P File: Measurement: S11:\n')
    f.write('# D S DB R 50\n')

    for i in range(len(distance)):
        f.write(str(distance[i]) + ' ' + str(data[i]) + ' ' + str(0)  + '\n')
         
    f.close()

def smooth(y, box_pts):
    box = np.ones(box_pts)/box_pts
    y_smooth = np.convolve(y, box, mode='same')
    return y_smooth

wb = xlsxwriter.Workbook('Time01.xlsx')
ws = wb.add_worksheet()
head_writed = False

for i,file1 in enumerate(os.listdir("Files")):
    
    if file1.endswith(".s1p"):
        s = file1.split('_')
        index1 = s[1]
        fonte = s[2]
        haste = s[3][0:-4]
        f = open('Files_Time/' + file1 + ".s1p","r+")
        s = f.readline()
        j = 0
        while s:
            if s.startswith('!') or s.startswith('#'):
                pass
            else:
                l = s.split(' ')
                if head_writed is False:
                    ws.write(i,j,np.round(float(l[0]),2))
                    ws.write(i+1,j,l[1])
                else:
                    ws.write(i+1,j,l[1]) 
                j = j + 1            
            s = f.readline()
        head_writed = True    
    #df.to_excel('Modulo de S11.xlsx', sheet_name='sheet1', index=False)
wb.close()                             
##for i,file1 in enumerate(os.listdir("Files")):
##    
##    if file1.endswith(".s1p"):
##        probe = rf.Network('Files/'+ file1)
##        x,y = probe.plot_s_db_time(window=('kaiser', 6))
##        x = 0.92*3*10**8*x/2
##        y = smooth(y,3)
##        write_s1p(file1, x, y )
